1pub mod ai_handler;
201pub mod auth;
202pub mod chain_handlers;
203pub mod consistency;
205pub mod contract_diff_api;
207pub mod contract_diff_middleware;
209pub mod counting_listener;
212pub mod coverage;
213#[cfg(feature = "database")]
219pub mod database {
220 pub use mockforge_intelligence::database::*;
221}
222pub mod file_generator;
224pub mod file_server;
226pub mod fixtures_api;
228pub mod health;
230pub mod http_tracing_middleware;
231pub mod latency_profiles;
233
234pub mod llm_mock;
236
237pub mod management;
239pub mod management_auth;
241pub mod management_ws;
243pub mod mcp_mock;
245pub mod metrics_middleware;
246pub mod middleware;
247pub mod mockai_api;
249pub mod network_profile_runtime;
251pub mod op_middleware;
252pub mod protocol_server;
254pub mod proxy_server;
256pub mod quick_mock;
258pub mod rag_ai_generator;
260pub mod reality_proxy;
262pub mod replay_listing;
264pub mod request_logging;
265pub mod route_chaos_runtime;
266#[cfg(feature = "scenario-engine")]
268pub mod scenarios_runtime;
269pub mod spec_import;
271pub mod sse;
273pub mod state_machine_api;
275pub mod time_travel_api;
277pub mod tls;
279pub mod token_response;
281pub mod ui_builder;
283pub mod verification;
285
286pub mod handlers;
288
289pub use ai_handler::{process_response_with_ai, AiResponseConfig, AiResponseHandler};
291pub use health::{HealthManager, ServiceStatus};
293
294pub use management::{
296 management_router, management_router_with_ui_builder, ManagementState, MockConfig,
297 ServerConfig, ServerStats,
298};
299
300pub use ui_builder::{create_ui_builder_router, EndpointConfig, UIBuilderState};
302
303pub use management_ws::{ws_management_router, MockEvent, WsManagementState};
305
306pub use verification::verification_router;
308
309pub use metrics_middleware::collect_http_metrics;
311
312pub use http_tracing_middleware::http_tracing_middleware;
314
315pub use coverage::{calculate_coverage, CoverageReport, MethodCoverage, RouteCoverage};
317
318async fn load_persona_from_config() -> Option<Arc<Persona>> {
321 use mockforge_core::config::load_config;
322
323 let config_paths = [
325 "config.yaml",
326 "mockforge.yaml",
327 "tools/mockforge/config.yaml",
328 "../tools/mockforge/config.yaml",
329 ];
330
331 for path in &config_paths {
332 if let Ok(config) = load_config(path).await {
333 if let Some(persona) = config.mockai.intelligent_behavior.personas.get_active_persona()
336 {
337 tracing::info!(
338 "Loaded active persona '{}' from config file: {}",
339 persona.name,
340 path
341 );
342 return Some(Arc::new(persona.clone()));
343 } else {
344 tracing::debug!(
345 "No active persona found in config file: {} (personas count: {})",
346 path,
347 config.mockai.intelligent_behavior.personas.personas.len()
348 );
349 }
350 } else {
351 tracing::debug!("Could not load config from: {}", path);
352 }
353 }
354
355 tracing::debug!("No persona found in config files, persona-based generation will be disabled");
356 None
357}
358
359use axum::body::Body;
360use axum::extract::State;
361use axum::http::Request;
362use axum::middleware::from_fn_with_state;
363use axum::response::Json;
364use axum::Router;
365use mockforge_chaos::core_failure_injection::{FailureConfig, FailureInjector};
366use mockforge_core::intelligent_behavior::config::Persona;
367use mockforge_foundation::latency::LatencyInjector;
368use mockforge_openapi::openapi_routes::OpenApiRouteRegistry;
369use mockforge_openapi::openapi_routes::ValidationOptions;
370use mockforge_openapi::OpenApiSpec;
371use std::sync::Arc;
372use tower_http::cors::{Any, CorsLayer};
373
374#[cfg(feature = "data-faker")]
375use mockforge_data::provider::register_core_faker_provider;
376use mockforge_foundation::latency::LatencyProfile;
377use std::collections::HashMap;
378use std::ffi::OsStr;
379use std::path::Path;
380use tokio::fs;
381use tokio::sync::RwLock;
382use tracing::*;
383
384#[derive(Clone)]
386pub struct RouteInfo {
387 pub method: String,
389 pub path: String,
391 pub operation_id: Option<String>,
393 pub summary: Option<String>,
395 pub description: Option<String>,
397 pub parameters: Vec<String>,
399}
400
401#[derive(Clone)]
403pub struct HttpServerState {
404 pub routes: Vec<RouteInfo>,
406 pub rate_limiter: Option<Arc<middleware::rate_limit::GlobalRateLimiter>>,
408 pub production_headers: Option<Arc<HashMap<String, String>>>,
410}
411
412impl Default for HttpServerState {
413 fn default() -> Self {
414 Self::new()
415 }
416}
417
418impl HttpServerState {
419 pub fn new() -> Self {
421 Self {
422 routes: Vec::new(),
423 rate_limiter: None,
424 production_headers: None,
425 }
426 }
427
428 pub fn with_routes(routes: Vec<RouteInfo>) -> Self {
430 Self {
431 routes,
432 rate_limiter: None,
433 production_headers: None,
434 }
435 }
436
437 pub fn with_rate_limiter(
439 mut self,
440 rate_limiter: Arc<middleware::rate_limit::GlobalRateLimiter>,
441 ) -> Self {
442 self.rate_limiter = Some(rate_limiter);
443 self
444 }
445
446 pub fn with_production_headers(mut self, headers: Arc<HashMap<String, String>>) -> Self {
448 self.production_headers = Some(headers);
449 self
450 }
451}
452
453async fn get_routes_handler(State(state): State<HttpServerState>) -> Json<serde_json::Value> {
455 let route_info: Vec<serde_json::Value> = state
456 .routes
457 .iter()
458 .map(|route| {
459 serde_json::json!({
460 "method": route.method,
461 "path": route.path,
462 "operation_id": route.operation_id,
463 "summary": route.summary,
464 "description": route.description,
465 "parameters": route.parameters
466 })
467 })
468 .collect();
469
470 Json(serde_json::json!({
471 "routes": route_info,
472 "total": state.routes.len()
473 }))
474}
475
476async fn get_docs_handler() -> axum::response::Html<&'static str> {
478 axum::response::Html(include_str!("../static/docs.html"))
479}
480
481pub async fn build_router(
483 spec_path: Option<String>,
484 options: Option<ValidationOptions>,
485 failure_config: Option<FailureConfig>,
486) -> Router {
487 build_router_with_multi_tenant(
488 spec_path,
489 options,
490 failure_config,
491 None,
492 None,
493 None,
494 None,
495 None,
496 None,
497 None,
498 )
499 .await
500}
501
502fn apply_cors_middleware(
504 app: Router,
505 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
506) -> Router {
507 use http::Method;
508 use tower_http::cors::AllowOrigin;
509
510 if let Some(config) = cors_config {
511 if !config.enabled {
512 return app;
513 }
514
515 let mut cors_layer = CorsLayer::new();
516 let is_wildcard_origin;
517
518 if config.allowed_origins.contains(&"*".to_string()) {
520 cors_layer = cors_layer.allow_origin(Any);
521 is_wildcard_origin = true;
522 } else if !config.allowed_origins.is_empty() {
523 let origins: Vec<_> = config
525 .allowed_origins
526 .iter()
527 .filter_map(|origin| {
528 origin.parse::<http::HeaderValue>().ok().map(AllowOrigin::exact)
529 })
530 .collect();
531
532 if origins.is_empty() {
533 warn!("No valid CORS origins configured, using permissive CORS");
535 cors_layer = cors_layer.allow_origin(Any);
536 is_wildcard_origin = true;
537 } else {
538 if origins.len() == 1 {
541 cors_layer = cors_layer.allow_origin(origins[0].clone());
542 is_wildcard_origin = false;
543 } else {
544 warn!(
546 "Multiple CORS origins configured, using permissive CORS. \
547 Consider using '*' for all origins."
548 );
549 cors_layer = cors_layer.allow_origin(Any);
550 is_wildcard_origin = true;
551 }
552 }
553 } else {
554 cors_layer = cors_layer.allow_origin(Any);
556 is_wildcard_origin = true;
557 }
558
559 if !config.allowed_methods.is_empty() {
561 let methods: Vec<Method> =
562 config.allowed_methods.iter().filter_map(|m| m.parse().ok()).collect();
563 if !methods.is_empty() {
564 cors_layer = cors_layer.allow_methods(methods);
565 }
566 } else {
567 cors_layer = cors_layer.allow_methods([
569 Method::GET,
570 Method::POST,
571 Method::PUT,
572 Method::DELETE,
573 Method::PATCH,
574 Method::OPTIONS,
575 ]);
576 }
577
578 if !config.allowed_headers.is_empty() {
580 let headers: Vec<_> = config
581 .allowed_headers
582 .iter()
583 .filter_map(|h| h.parse::<http::HeaderName>().ok())
584 .collect();
585 if !headers.is_empty() {
586 cors_layer = cors_layer.allow_headers(headers);
587 }
588 } else {
589 cors_layer =
591 cors_layer.allow_headers([http::header::CONTENT_TYPE, http::header::AUTHORIZATION]);
592 }
593
594 let should_allow_credentials = if is_wildcard_origin {
598 false
600 } else {
601 config.allow_credentials
603 };
604
605 cors_layer = cors_layer.allow_credentials(should_allow_credentials);
606
607 info!(
608 "CORS middleware enabled with configured settings (credentials: {})",
609 should_allow_credentials
610 );
611 app.layer(cors_layer)
612 } else {
613 debug!("No CORS config provided, using permissive CORS for development");
617 app.layer(CorsLayer::permissive().allow_credentials(false))
620 }
621}
622
623#[allow(clippy::too_many_arguments)]
625#[allow(deprecated)] pub async fn build_router_with_multi_tenant(
627 spec_path: Option<String>,
628 options: Option<ValidationOptions>,
629 failure_config: Option<FailureConfig>,
630 multi_tenant_config: Option<mockforge_foundation::multi_tenant_types::MultiTenantConfig>,
631 _route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
632 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
633 ai_generator: Option<Arc<dyn mockforge_openapi::response::AiGenerator + Send + Sync>>,
634 smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
635 mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
636 deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
637) -> Router {
638 use std::time::Instant;
639
640 let startup_start = Instant::now();
641
642 let mut app = Router::new();
644
645 let mut rate_limit_config = middleware::RateLimitConfig {
648 requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
649 .ok()
650 .and_then(|v| v.parse().ok())
651 .unwrap_or(1000),
652 burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
653 .ok()
654 .and_then(|v| v.parse().ok())
655 .unwrap_or(2000),
656 per_ip: true,
657 per_endpoint: false,
658 };
659
660 let mut final_cors_config = cors_config;
662 let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
663 let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
665
666 if let Some(deploy_config) = &deceptive_deploy_config {
667 if deploy_config.enabled {
668 info!("Deceptive deploy mode enabled - applying production-like configuration");
669
670 if let Some(prod_cors) = &deploy_config.cors {
672 final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
673 enabled: true,
674 allowed_origins: prod_cors.allowed_origins.clone(),
675 allowed_methods: prod_cors.allowed_methods.clone(),
676 allowed_headers: prod_cors.allowed_headers.clone(),
677 allow_credentials: prod_cors.allow_credentials,
678 });
679 info!("Applied production-like CORS configuration");
680 }
681
682 if let Some(prod_rate_limit) = &deploy_config.rate_limit {
684 rate_limit_config = middleware::RateLimitConfig {
685 requests_per_minute: prod_rate_limit.requests_per_minute,
686 burst: prod_rate_limit.burst,
687 per_ip: prod_rate_limit.per_ip,
688 per_endpoint: false,
689 };
690 info!(
691 "Applied production-like rate limiting: {} req/min, burst: {}",
692 prod_rate_limit.requests_per_minute, prod_rate_limit.burst
693 );
694 }
695
696 if !deploy_config.headers.is_empty() {
698 let headers_map: HashMap<String, String> = deploy_config.headers.clone();
699 production_headers = Some(std::sync::Arc::new(headers_map));
700 info!("Configured {} production headers", deploy_config.headers.len());
701 }
702
703 if let Some(prod_oauth) = &deploy_config.oauth {
705 let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
706 deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
707 oauth2: Some(oauth2_config),
708 ..Default::default()
709 });
710 info!("Applied production-like OAuth configuration for deceptive deploy");
711 }
712 }
713 }
714
715 let rate_limit_disabled = middleware::is_rate_limit_disabled();
716 let rate_limiter =
717 std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
718
719 let mut state = HttpServerState::new();
720 if rate_limit_disabled {
721 info!(
722 "HTTP rate limiting disabled (MOCKFORGE_RATE_LIMIT_ENABLED=false or --no-rate-limit)"
723 );
724 } else {
725 state = state.with_rate_limiter(rate_limiter.clone());
726 }
727
728 if let Some(headers) = production_headers.clone() {
730 state = state.with_production_headers(headers);
731 }
732
733 let spec_path_for_mgmt = spec_path.clone();
735
736 if let Some(spec_path) = spec_path {
738 tracing::debug!("Processing OpenAPI spec path: {}", spec_path);
739
740 let spec_load_start = Instant::now();
742 match OpenApiSpec::from_file(&spec_path).await {
743 Ok(openapi) => {
744 let spec_load_duration = spec_load_start.elapsed();
745 info!(
746 "Successfully loaded OpenAPI spec from {} (took {:?})",
747 spec_path, spec_load_duration
748 );
749
750 tracing::debug!("Creating OpenAPI route registry...");
752 let registry_start = Instant::now();
753
754 let persona = load_persona_from_config().await;
756
757 let registry = if let Some(opts) = options {
758 tracing::debug!("Using custom validation options");
759 if let Some(ref persona) = persona {
760 tracing::info!("Using persona '{}' for route generation", persona.name);
761 }
762 OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
763 } else {
764 tracing::debug!("Using environment-based options");
765 if let Some(ref persona) = persona {
766 tracing::info!("Using persona '{}' for route generation", persona.name);
767 }
768 OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
769 };
770 let registry_duration = registry_start.elapsed();
771 info!(
772 "Created OpenAPI route registry with {} routes (took {:?})",
773 registry.routes().len(),
774 registry_duration
775 );
776
777 let extract_start = Instant::now();
779 let route_info: Vec<RouteInfo> = registry
780 .routes()
781 .iter()
782 .map(|route| RouteInfo {
783 method: route.method.clone(),
784 path: route.path.clone(),
785 operation_id: route.operation.operation_id.clone(),
786 summary: route.operation.summary.clone(),
787 description: route.operation.description.clone(),
788 parameters: route.parameters.clone(),
789 })
790 .collect();
791 state.routes = route_info;
792 let extract_duration = extract_start.elapsed();
793 debug!("Extracted route information (took {:?})", extract_duration);
794
795 let registry = registry.with_overrides(Arc::new(
796 mockforge_core::SharedOverrides::load(Vec::new()).await,
797 ));
798 let router_build_start = Instant::now();
799 let response_rewriter: Option<
800 std::sync::Arc<dyn mockforge_openapi::response_rewriter::ResponseRewriter>,
801 > = Some(std::sync::Arc::new(
802 mockforge_core::openapi_rewriter::CoreResponseRewriter::new(),
803 ));
804 let openapi_router = if let Some(mockai_instance) = &mockai {
805 tracing::debug!("Building router with MockAI support");
806 registry.build_router_with_mockai(Some(mockai_instance.clone()))
807 } else if let Some(ai_generator) = &ai_generator {
808 tracing::debug!("Building router with AI generator support");
809 registry.build_router_with_ai(Some(ai_generator.clone()))
810 } else if let Some(failure_config) = &failure_config {
811 tracing::debug!("Building router with failure injection and overrides");
812 let failure_injector = FailureInjector::new(Some(failure_config.clone()), true);
813 registry.build_router_with_injectors_and_rewriter(
814 LatencyInjector::default(),
815 Some(failure_injector),
816 response_rewriter,
817 )
818 } else {
819 tracing::debug!("Building router with overrides");
820 registry.build_router_with_injectors_and_rewriter(
821 LatencyInjector::default(),
822 None,
823 response_rewriter,
824 )
825 };
826 let router_build_duration = router_build_start.elapsed();
827 debug!("Built OpenAPI router (took {:?})", router_build_duration);
828
829 let body_limit_mb = std::env::var("MOCKFORGE_HTTP_BODY_LIMIT_MB")
837 .ok()
838 .and_then(|v| v.parse::<usize>().ok())
839 .unwrap_or(50);
840 let body_limit_bytes = body_limit_mb.saturating_mul(1024 * 1024);
841 let openapi_router =
842 openapi_router.layer(axum::extract::DefaultBodyLimit::max(body_limit_bytes));
843 tracing::info!(
844 body_limit_mb = body_limit_mb,
845 "Merging OpenAPI router with main router"
846 );
847 app = app.merge(openapi_router);
848 tracing::debug!("Router built successfully");
849 }
850 Err(e) => {
851 warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
852 }
853 }
854 }
855
856 app = app.route(
858 "/health",
859 axum::routing::get(|| async {
860 use mockforge_core::server_utils::health::HealthStatus;
861 {
862 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
864 Ok(value) => Json(value),
865 Err(e) => {
866 tracing::error!("Failed to serialize health status: {}", e);
868 Json(serde_json::json!({
869 "status": "healthy",
870 "service": "mockforge-http",
871 "uptime_seconds": 0
872 }))
873 }
874 }
875 }
876 }),
877 )
878 .merge(sse::sse_router())
880 .merge(file_server::file_serving_router());
882
883 let state_for_routes = state.clone();
885
886 let routes_router = Router::new()
888 .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
889 .route("/__mockforge/coverage", axum::routing::get(coverage::get_coverage_handler))
890 .with_state(state_for_routes);
891
892 app = app.merge(routes_router);
894
895 app = app.route("/__mockforge/docs", axum::routing::get(get_docs_handler));
897
898 let coverage_html_path = std::env::var("MOCKFORGE_COVERAGE_UI_PATH")
901 .unwrap_or_else(|_| "crates/mockforge-http/static/coverage.html".to_string());
902
903 if Path::new(&coverage_html_path).exists() {
905 app = app.nest_service(
906 "/__mockforge/coverage.html",
907 tower_http::services::ServeFile::new(&coverage_html_path),
908 );
909 debug!("Serving coverage UI from: {}", coverage_html_path);
910 } else {
911 debug!(
912 "Coverage UI file not found at: {}. Skipping static file serving.",
913 coverage_html_path
914 );
915 }
916
917 let mgmt_spec = if let Some(ref sp) = spec_path_for_mgmt {
920 match OpenApiSpec::from_file(sp).await {
921 Ok(s) => Some(Arc::new(s)),
922 Err(e) => {
923 debug!("Failed to load OpenAPI spec for management API: {}", e);
924 None
925 }
926 }
927 } else {
928 None
929 };
930 let mgmt_port = std::env::var("PORT")
931 .or_else(|_| std::env::var("MOCKFORGE_HTTP_PORT"))
932 .ok()
933 .and_then(|p| p.parse().ok())
934 .unwrap_or(3000);
935 let management_state = ManagementState::new(mgmt_spec, spec_path_for_mgmt, mgmt_port);
936
937 use std::sync::Arc;
939 let ws_state = WsManagementState::new();
940 let ws_broadcast = Arc::new(ws_state.tx.clone());
941 let management_state = management_state.with_ws_broadcast(ws_broadcast);
942
943 #[cfg(feature = "smtp")]
947 let management_state = {
948 if let Some(smtp_reg) = smtp_registry {
949 match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
950 Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
951 Err(e) => {
952 error!(
953 "Invalid SMTP registry type passed to HTTP management state: {:?}",
954 e.type_id()
955 );
956 management_state
957 }
958 }
959 } else {
960 management_state
961 }
962 };
963 #[cfg(not(feature = "smtp"))]
964 let management_state = management_state;
965 #[cfg(not(feature = "smtp"))]
966 let _ = smtp_registry;
967 let management_state_for_fallback = management_state.clone();
968 app = app.nest("/__mockforge/api", management_router(management_state));
969 app = app.fallback_service(
974 axum::routing::any(management::dynamic_mock_fallback)
975 .with_state(management_state_for_fallback),
976 );
977
978 app = app.merge(verification_router());
980
981 use crate::auth::oidc::oidc_router;
983 app = app.merge(oidc_router());
984
985 {
987 use mockforge_core::security::get_global_access_review_service;
988 if let Some(service) = get_global_access_review_service().await {
989 use crate::handlers::access_review::{access_review_router, AccessReviewState};
990 let review_state = AccessReviewState { service };
991 app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
992 debug!("Access review API mounted at /api/v1/security/access-reviews");
993 }
994 }
995
996 {
998 use mockforge_core::security::get_global_privileged_access_manager;
999 if let Some(manager) = get_global_privileged_access_manager().await {
1000 use crate::handlers::privileged_access::{
1001 privileged_access_router, PrivilegedAccessState,
1002 };
1003 let privileged_state = PrivilegedAccessState { manager };
1004 app = app.nest(
1005 "/api/v1/security/privileged-access",
1006 privileged_access_router(privileged_state),
1007 );
1008 debug!("Privileged access API mounted at /api/v1/security/privileged-access");
1009 }
1010 }
1011
1012 {
1014 use mockforge_core::security::get_global_change_management_engine;
1015 if let Some(engine) = get_global_change_management_engine().await {
1016 use crate::handlers::change_management::{
1017 change_management_router, ChangeManagementState,
1018 };
1019 let change_state = ChangeManagementState { engine };
1020 app = app.nest("/api/v1/change-management", change_management_router(change_state));
1021 debug!("Change management API mounted at /api/v1/change-management");
1022 }
1023 }
1024
1025 {
1027 use mockforge_core::security::get_global_risk_assessment_engine;
1028 if let Some(engine) = get_global_risk_assessment_engine().await {
1029 use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
1030 let risk_state = RiskAssessmentState { engine };
1031 app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
1032 debug!("Risk assessment API mounted at /api/v1/security/risks");
1033 }
1034 }
1035
1036 {
1038 use crate::auth::token_lifecycle::TokenLifecycleManager;
1039 use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
1040 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1041 let lifecycle_state = TokenLifecycleState {
1042 manager: lifecycle_manager,
1043 };
1044 app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
1045 debug!("Token lifecycle API mounted at /api/v1/auth");
1046 }
1047
1048 {
1050 use crate::auth::oidc::load_oidc_state;
1051 use crate::auth::token_lifecycle::TokenLifecycleManager;
1052 use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
1053 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1055 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1056 let oauth2_state = OAuth2ServerState {
1057 oidc_state,
1058 lifecycle_manager,
1059 auth_codes: Arc::new(RwLock::new(HashMap::new())),
1060 refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
1061 };
1062 app = app.merge(oauth2_server_router(oauth2_state));
1063 debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
1064 }
1065
1066 {
1068 use crate::auth::oidc::load_oidc_state;
1069 use crate::auth::risk_engine::RiskEngine;
1070 use crate::auth::token_lifecycle::TokenLifecycleManager;
1071 use crate::handlers::consent::{consent_router, ConsentState};
1072 use crate::handlers::oauth2_server::OAuth2ServerState;
1073 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1075 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1076 let oauth2_state = OAuth2ServerState {
1077 oidc_state: oidc_state.clone(),
1078 lifecycle_manager: lifecycle_manager.clone(),
1079 auth_codes: Arc::new(RwLock::new(HashMap::new())),
1080 refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
1081 };
1082 let risk_engine = Arc::new(RiskEngine::default());
1083 let consent_state = ConsentState {
1084 oauth2_state,
1085 risk_engine,
1086 };
1087 app = app.merge(consent_router(consent_state));
1088 debug!("Consent screen endpoints mounted at /consent");
1089 }
1090
1091 {
1093 use crate::auth::risk_engine::RiskEngine;
1094 use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
1095 let risk_engine = Arc::new(RiskEngine::default());
1096 let risk_state = RiskSimulationState { risk_engine };
1097 app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
1098 debug!("Risk simulation API mounted at /api/v1/auth/risk");
1099 }
1100
1101 app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
1103
1104 app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));
1106
1107 app = app.layer(axum::middleware::from_fn(middleware::security_middleware));
1109
1110 app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
1113
1114 app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));
1116
1117 if state.production_headers.is_some() {
1119 app =
1120 app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
1121 }
1122
1123 if middleware::is_keepalive_hint_enabled() {
1129 info!(
1130 "MOCKFORGE_HTTP_KEEPALIVE_HINT enabled — emitting Connection: keep-alive + Keep-Alive headers on all responses (Issue #79 workaround)"
1131 );
1132 app = app.layer(axum::middleware::from_fn(middleware::keepalive_hint_middleware));
1133 }
1134
1135 if middleware::is_conn_log_enabled() {
1140 info!(
1141 "MOCKFORGE_HTTP_LOG_CONN enabled — logging HTTP version + Connection headers per request (Issue #79 diagnostic)"
1142 );
1143 app = app.layer(axum::middleware::from_fn(middleware::conn_diag_middleware));
1144 }
1145
1146 if let Some(auth_config) = deceptive_deploy_auth_config {
1148 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1149 use std::collections::HashMap;
1150 use std::sync::Arc;
1151 use tokio::sync::RwLock;
1152
1153 let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
1155 match create_oauth2_client(oauth2_config) {
1156 Ok(client) => Some(client),
1157 Err(e) => {
1158 warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
1159 None
1160 }
1161 }
1162 } else {
1163 None
1164 };
1165
1166 let auth_state = AuthState {
1168 config: auth_config,
1169 spec: None, oauth2_client,
1171 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1172 };
1173
1174 app = app.layer(from_fn_with_state(auth_state, auth_middleware));
1176 info!("Applied OAuth authentication middleware from deceptive deploy configuration");
1177 }
1178
1179 app = apply_cors_middleware(app, final_cors_config);
1181
1182 if let Some(mt_config) = multi_tenant_config {
1184 if mt_config.enabled {
1185 use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
1186 use std::sync::Arc;
1187
1188 info!(
1189 "Multi-tenant mode enabled with {} routing strategy",
1190 match mt_config.routing_strategy {
1191 mockforge_foundation::multi_tenant_types::RoutingStrategy::Path => "path-based",
1192 mockforge_foundation::multi_tenant_types::RoutingStrategy::Port => "port-based",
1193 mockforge_foundation::multi_tenant_types::RoutingStrategy::Both => "hybrid",
1194 }
1195 );
1196
1197 let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
1199
1200 let default_workspace =
1202 mockforge_core::Workspace::new(mt_config.default_workspace.clone());
1203 if let Err(e) =
1204 registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
1205 {
1206 warn!("Failed to register default workspace: {}", e);
1207 } else {
1208 info!("Registered default workspace: '{}'", mt_config.default_workspace);
1209 }
1210
1211 if mt_config.auto_discover {
1213 if let Some(config_dir) = &mt_config.config_directory {
1214 let config_path = Path::new(config_dir);
1215 if config_path.exists() && config_path.is_dir() {
1216 match fs::read_dir(config_path).await {
1217 Ok(mut entries) => {
1218 while let Ok(Some(entry)) = entries.next_entry().await {
1219 let path = entry.path();
1220 if path.extension() == Some(OsStr::new("yaml")) {
1221 match fs::read_to_string(&path).await {
1222 Ok(content) => {
1223 match serde_yaml::from_str::<
1224 mockforge_core::Workspace,
1225 >(
1226 &content
1227 ) {
1228 Ok(workspace) => {
1229 if let Err(e) = registry.register_workspace(
1230 workspace.id.clone(),
1231 workspace,
1232 ) {
1233 warn!("Failed to register auto-discovered workspace from {:?}: {}", path, e);
1234 } else {
1235 info!("Auto-registered workspace from {:?}", path);
1236 }
1237 }
1238 Err(e) => {
1239 warn!("Failed to parse workspace from {:?}: {}", path, e);
1240 }
1241 }
1242 }
1243 Err(e) => {
1244 warn!(
1245 "Failed to read workspace file {:?}: {}",
1246 path, e
1247 );
1248 }
1249 }
1250 }
1251 }
1252 }
1253 Err(e) => {
1254 warn!("Failed to read config directory {:?}: {}", config_path, e);
1255 }
1256 }
1257 } else {
1258 warn!(
1259 "Config directory {:?} does not exist or is not a directory",
1260 config_path
1261 );
1262 }
1263 }
1264 }
1265
1266 let registry = Arc::new(registry);
1268
1269 let _workspace_router = WorkspaceRouter::new(registry);
1271
1272 info!("Workspace routing middleware initialized for HTTP server");
1275 }
1276 }
1277
1278 let total_startup_duration = startup_start.elapsed();
1279 info!("HTTP router startup completed (total time: {:?})", total_startup_duration);
1280
1281 app
1282}
1283
1284pub async fn build_router_with_auth_and_latency(
1286 spec_path: Option<String>,
1287 _options: Option<()>,
1288 auth_config: Option<mockforge_core::config::AuthConfig>,
1289 latency_injector: Option<LatencyInjector>,
1290) -> Router {
1291 let mut app = build_router_with_auth(spec_path.clone(), None, auth_config).await;
1293
1294 if let Some(injector) = latency_injector {
1296 let injector = Arc::new(injector);
1297 app = app.layer(axum::middleware::from_fn(move |req, next: axum::middleware::Next| {
1298 let injector = injector.clone();
1299 async move {
1300 let _ = injector.inject_latency(&[]).await;
1301 next.run(req).await
1302 }
1303 }));
1304 }
1305
1306 app
1307}
1308
1309pub async fn build_router_with_latency(
1311 spec_path: Option<String>,
1312 options: Option<ValidationOptions>,
1313 latency_injector: Option<LatencyInjector>,
1314) -> Router {
1315 if let Some(spec) = &spec_path {
1316 match OpenApiSpec::from_file(spec).await {
1317 Ok(openapi) => {
1318 let registry = if let Some(opts) = options {
1319 OpenApiRouteRegistry::new_with_options(openapi, opts)
1320 } else {
1321 OpenApiRouteRegistry::new_with_env(openapi)
1322 };
1323
1324 if let Some(injector) = latency_injector {
1325 return registry.build_router_with_latency(injector);
1326 } else {
1327 return registry.build_router();
1328 }
1329 }
1330 Err(e) => {
1331 warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec, e);
1332 }
1333 }
1334 }
1335
1336 build_router(None, None, None).await
1337}
1338
1339pub async fn build_router_with_auth(
1341 spec_path: Option<String>,
1342 options: Option<ValidationOptions>,
1343 auth_config: Option<mockforge_core::config::AuthConfig>,
1344) -> Router {
1345 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1346 use std::sync::Arc;
1347
1348 #[cfg(feature = "data-faker")]
1350 {
1351 register_core_faker_provider();
1352 }
1353
1354 let spec = if let Some(spec_path) = &spec_path {
1356 match OpenApiSpec::from_file(&spec_path).await {
1357 Ok(spec) => Some(Arc::new(spec)),
1358 Err(e) => {
1359 warn!("Failed to load OpenAPI spec for auth: {}", e);
1360 None
1361 }
1362 }
1363 } else {
1364 None
1365 };
1366
1367 let oauth2_client = if let Some(auth_config) = &auth_config {
1369 if let Some(oauth2_config) = &auth_config.oauth2 {
1370 match create_oauth2_client(oauth2_config) {
1371 Ok(client) => Some(client),
1372 Err(e) => {
1373 warn!("Failed to create OAuth2 client: {}", e);
1374 None
1375 }
1376 }
1377 } else {
1378 None
1379 }
1380 } else {
1381 None
1382 };
1383
1384 let auth_state = AuthState {
1385 config: auth_config.unwrap_or_default(),
1386 spec,
1387 oauth2_client,
1388 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1389 };
1390
1391 let mut app = Router::new().with_state(auth_state.clone());
1393
1394 if let Some(spec_path) = spec_path {
1396 match OpenApiSpec::from_file(&spec_path).await {
1397 Ok(openapi) => {
1398 info!("Loaded OpenAPI spec from {}", spec_path);
1399 let registry = if let Some(opts) = options {
1400 OpenApiRouteRegistry::new_with_options(openapi, opts)
1401 } else {
1402 OpenApiRouteRegistry::new_with_env(openapi)
1403 };
1404
1405 app = registry.build_router();
1406 }
1407 Err(e) => {
1408 warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
1409 }
1410 }
1411 }
1412
1413 app = app.route(
1415 "/health",
1416 axum::routing::get(|| async {
1417 use mockforge_core::server_utils::health::HealthStatus;
1418 {
1419 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1421 Ok(value) => Json(value),
1422 Err(e) => {
1423 tracing::error!("Failed to serialize health status: {}", e);
1425 Json(serde_json::json!({
1426 "status": "healthy",
1427 "service": "mockforge-http",
1428 "uptime_seconds": 0
1429 }))
1430 }
1431 }
1432 }
1433 }),
1434 )
1435 .merge(sse::sse_router())
1437 .merge(file_server::file_serving_router())
1439 .layer(from_fn_with_state(auth_state.clone(), auth_middleware))
1441 .layer(axum::middleware::from_fn(request_logging::log_http_requests));
1443
1444 app
1445}
1446
1447pub async fn serve_router(
1449 port: u16,
1450 app: Router,
1451) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1452 serve_router_with_tls(port, app, None).await
1453}
1454
1455pub async fn serve_router_with_tls(
1457 port: u16,
1458 app: Router,
1459 tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1460) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1461 serve_router_with_tls_notify(port, app, tls_config, None).await
1462}
1463
1464pub async fn serve_router_with_tls_notify(
1472 port: u16,
1473 app: Router,
1474 tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1475 bound_port_tx: Option<tokio::sync::oneshot::Sender<u16>>,
1476) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1477 serve_router_with_tls_notify_chaos(port, app, tls_config, bound_port_tx, None).await
1478}
1479
1480pub async fn serve_router_with_tls_notify_chaos(
1489 port: u16,
1490 app: Router,
1491 tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1492 bound_port_tx: Option<tokio::sync::oneshot::Sender<u16>>,
1493 chaos_config: Option<Arc<RwLock<mockforge_chaos::ChaosConfig>>>,
1494) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1495 use std::net::SocketAddr;
1496
1497 let addr = mockforge_core::wildcard_socket_addr(port);
1498
1499 if let Some(ref tls) = tls_config {
1500 if tls.enabled {
1501 info!("HTTPS listening on {}", addr);
1502 if let Some(tx) = bound_port_tx {
1503 let _ = tx.send(port);
1504 }
1505 return serve_with_tls(addr, app, tls).await;
1506 }
1507 }
1508
1509 let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
1510 format!(
1511 "Failed to bind HTTP server to port {}: {}\n\
1512 Hint: The port may already be in use. Try using a different port with --http-port or check if another process is using this port with: lsof -i :{} or netstat -tulpn | grep {}",
1513 port, e, port, port
1514 )
1515 })?;
1516
1517 let actual_port = listener.local_addr().map(|a| a.port()).unwrap_or(port);
1518 info!("HTTP listening on {}", listener.local_addr().unwrap_or(addr));
1519 if let Some(tx) = bound_port_tx {
1520 let _ = tx.send(actual_port);
1521 }
1522
1523 let odata_app = tower::ServiceBuilder::new()
1527 .layer(mockforge_core::odata_rewrite::ODataRewriteLayer)
1528 .service(app);
1529 if let Some(cfg) = chaos_config {
1530 info!("HTTP listener wrapped with chaos TCP listener (RST/FIN injection enabled)");
1531 let chaos_listener = mockforge_chaos::ChaosTcpListener::new(listener, cfg);
1532 let app_with_addr_compat = tower::ServiceBuilder::new()
1535 .layer(axum::middleware::from_fn(copy_chaos_addr_to_socketaddr))
1536 .service(odata_app);
1537 let make_svc = axum::ServiceExt::<Request<Body>>::into_make_service_with_connect_info::<
1538 mockforge_chaos::ChaosClientAddr,
1539 >(app_with_addr_compat);
1540 let counted = counting_listener::CountingMakeService::new(make_svc);
1542 axum::serve(chaos_listener, counted).await?;
1543 } else {
1544 let make_svc = axum::ServiceExt::<Request<Body>>::into_make_service_with_connect_info::<
1545 SocketAddr,
1546 >(odata_app);
1547 let counted = counting_listener::CountingMakeService::new(make_svc);
1550 axum::serve(listener, counted).await?;
1551 }
1552 Ok(())
1553}
1554
1555async fn copy_chaos_addr_to_socketaddr(
1559 mut req: Request<Body>,
1560 next: axum::middleware::Next,
1561) -> axum::response::Response {
1562 use axum::extract::ConnectInfo;
1563 if let Some(ConnectInfo(chaos_addr)) =
1564 req.extensions().get::<ConnectInfo<mockforge_chaos::ChaosClientAddr>>().copied()
1565 {
1566 let sock: std::net::SocketAddr = *chaos_addr;
1567 req.extensions_mut().insert(ConnectInfo(sock));
1568 }
1569 next.run(req).await
1570}
1571
1572async fn serve_with_tls(
1577 addr: std::net::SocketAddr,
1578 app: Router,
1579 tls_config: &mockforge_core::config::HttpTlsConfig,
1580) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1581 use axum_server::tls_rustls::RustlsConfig;
1582 use std::net::SocketAddr;
1583
1584 tls::init_crypto_provider();
1586
1587 info!("Loading TLS configuration for HTTPS server");
1588
1589 let server_config = tls::load_tls_server_config(tls_config)?;
1591
1592 let rustls_config = RustlsConfig::from_config(server_config);
1595
1596 info!("Starting HTTPS server on {}", addr);
1597
1598 let odata_app = tower::ServiceBuilder::new()
1602 .layer(mockforge_core::odata_rewrite::ODataRewriteLayer)
1603 .service(app);
1604 let make_svc = axum::ServiceExt::<Request<Body>>::into_make_service_with_connect_info::<
1605 SocketAddr,
1606 >(odata_app);
1607 let counted = counting_listener::CountingMakeService::new(make_svc);
1610
1611 axum_server::bind_rustls(addr, rustls_config)
1613 .serve(counted)
1614 .await
1615 .map_err(|e| format!("HTTPS server error: {}", e).into())
1616}
1617
1618pub async fn start(
1620 port: u16,
1621 spec_path: Option<String>,
1622 options: Option<ValidationOptions>,
1623) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1624 start_with_latency(port, spec_path, options, None).await
1625}
1626
1627pub async fn start_with_auth_and_latency(
1629 port: u16,
1630 spec_path: Option<String>,
1631 options: Option<ValidationOptions>,
1632 auth_config: Option<mockforge_core::config::AuthConfig>,
1633 latency_profile: Option<LatencyProfile>,
1634) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1635 start_with_auth_and_injectors(port, spec_path, options, auth_config, latency_profile, None)
1636 .await
1637}
1638
1639pub async fn start_with_auth_and_injectors(
1641 port: u16,
1642 spec_path: Option<String>,
1643 options: Option<ValidationOptions>,
1644 auth_config: Option<mockforge_core::config::AuthConfig>,
1645 _latency_profile: Option<LatencyProfile>,
1646 _failure_injector: Option<FailureInjector>,
1647) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1648 let app = build_router_with_auth(spec_path, options, auth_config).await;
1650 serve_router(port, app).await
1651}
1652
1653pub async fn start_with_latency(
1655 port: u16,
1656 spec_path: Option<String>,
1657 options: Option<ValidationOptions>,
1658 latency_profile: Option<LatencyProfile>,
1659) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1660 let latency_injector =
1661 latency_profile.map(|profile| LatencyInjector::new(profile, Default::default()));
1662
1663 let app = build_router_with_latency(spec_path, options, latency_injector).await;
1664 serve_router(port, app).await
1665}
1666
1667pub async fn build_router_with_chains(
1669 spec_path: Option<String>,
1670 options: Option<ValidationOptions>,
1671 circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1672) -> Router {
1673 build_router_with_chains_and_multi_tenant(
1674 spec_path,
1675 options,
1676 circling_config,
1677 None,
1678 None,
1679 None,
1680 None,
1681 None, None, None, None, None, false,
1687 None, None, None, None, mockforge_core::SharedOverrides::load(Vec::new()).await,
1692 )
1693 .await
1694}
1695
1696async fn apply_route_chaos(
1704 injector: Option<&dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1705 method: &http::Method,
1706 uri: &http::Uri,
1707) -> Option<axum::response::Response> {
1708 use axum::http::StatusCode;
1709 use axum::response::IntoResponse;
1710
1711 if let Some(injector) = injector {
1712 if let Some(fault_response) = injector.get_fault_response(method, uri) {
1714 let mut response = Json(serde_json::json!({
1716 "error": fault_response.error_message,
1717 "fault_type": fault_response.fault_type,
1718 }))
1719 .into_response();
1720 *response.status_mut() = StatusCode::from_u16(fault_response.status_code)
1721 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1722 return Some(response);
1723 }
1724
1725 if let Err(e) = injector.inject_latency(method, uri).await {
1727 tracing::warn!("Failed to inject latency: {}", e);
1728 }
1729 }
1730
1731 None }
1733
1734#[allow(clippy::too_many_arguments)]
1736#[allow(deprecated)] pub async fn build_router_with_chains_and_multi_tenant(
1738 spec_path: Option<String>,
1739 options: Option<ValidationOptions>,
1740 _circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1741 multi_tenant_config: Option<mockforge_foundation::multi_tenant_types::MultiTenantConfig>,
1742 route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
1743 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
1744 _ai_generator: Option<Arc<dyn mockforge_openapi::response::AiGenerator + Send + Sync>>,
1745 smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
1746 mqtt_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
1747 amqp_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
1748 kafka_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
1749 traffic_shaper: Option<mockforge_core::traffic_shaping::TrafficShaper>,
1750 traffic_shaping_enabled: bool,
1751 health_manager: Option<Arc<HealthManager>>,
1752 mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
1753 deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
1754 proxy_config: Option<mockforge_proxy::config::ProxyConfig>,
1755 overrides: mockforge_core::SharedOverrides,
1756) -> Router {
1757 use crate::latency_profiles::LatencyProfiles;
1758 use crate::op_middleware::Shared;
1759
1760 let template_expand =
1762 options.as_ref().map(|o| o.response_template_expand).unwrap_or_else(|| {
1763 std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
1764 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1765 .unwrap_or(false)
1766 });
1767
1768 let _shared = Shared {
1769 profiles: LatencyProfiles::default(),
1770 failure_injector: None,
1771 traffic_shaper,
1772 traffic_shaping_enabled,
1773 };
1774
1775 let mut app = Router::new();
1777 let mut include_default_health = true;
1778 let mut captured_routes: Vec<RouteInfo> = Vec::new();
1779
1780 if let Some(ref spec) = spec_path {
1782 match OpenApiSpec::from_file(&spec).await {
1783 Ok(openapi) => {
1784 info!("Loaded OpenAPI spec from {}", spec);
1785
1786 let persona = load_persona_from_config().await;
1788
1789 let mut registry = if let Some(opts) = options {
1790 tracing::debug!("Using custom validation options");
1791 if let Some(ref persona) = persona {
1792 tracing::info!("Using persona '{}' for route generation", persona.name);
1793 }
1794 OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
1795 } else {
1796 tracing::debug!("Using environment-based options");
1797 if let Some(ref persona) = persona {
1798 tracing::info!("Using persona '{}' for route generation", persona.name);
1799 }
1800 OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
1801 };
1802
1803 let fixtures_dir = std::env::var("MOCKFORGE_FIXTURES_DIR")
1805 .unwrap_or_else(|_| "/app/fixtures".to_string());
1806 let custom_fixtures_enabled = std::env::var("MOCKFORGE_CUSTOM_FIXTURES_ENABLED")
1807 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1808 .unwrap_or(true); if custom_fixtures_enabled {
1811 use mockforge_openapi::CustomFixtureLoader;
1812 use std::path::PathBuf;
1813 use std::sync::Arc;
1814
1815 let fixtures_path = PathBuf::from(&fixtures_dir);
1816 let mut custom_loader = CustomFixtureLoader::new(fixtures_path, true);
1817
1818 if let Err(e) = custom_loader.load_fixtures().await {
1819 tracing::warn!("Failed to load custom fixtures: {}", e);
1820 } else {
1821 tracing::info!("Custom fixtures loaded from {}", fixtures_dir);
1822 registry = registry.with_custom_fixture_loader(Arc::new(custom_loader));
1823 }
1824 }
1825 registry = registry.with_overrides(Arc::new(overrides.clone()));
1826
1827 if registry
1828 .routes()
1829 .iter()
1830 .any(|route| route.method == "GET" && route.path == "/health")
1831 {
1832 include_default_health = false;
1833 }
1834 captured_routes = registry
1836 .routes()
1837 .iter()
1838 .map(|r| RouteInfo {
1839 method: r.method.clone(),
1840 path: r.path.clone(),
1841 operation_id: r.operation.operation_id.clone(),
1842 summary: r.operation.summary.clone(),
1843 description: r.operation.description.clone(),
1844 parameters: r.parameters.clone(),
1845 })
1846 .collect();
1847
1848 {
1851 let global_routes: Vec<mockforge_core::request_logger::GlobalRouteInfo> =
1852 captured_routes
1853 .iter()
1854 .map(|r| mockforge_core::request_logger::GlobalRouteInfo {
1855 method: r.method.clone(),
1856 path: r.path.clone(),
1857 operation_id: r.operation_id.clone(),
1858 summary: r.summary.clone(),
1859 description: r.description.clone(),
1860 parameters: r.parameters.clone(),
1861 })
1862 .collect();
1863 mockforge_core::request_logger::set_global_routes(global_routes);
1864 tracing::info!("Stored {} routes in global route store", captured_routes.len());
1865 }
1866
1867 let spec_router = if let Some(ref mockai_instance) = mockai {
1869 tracing::debug!("Building router with MockAI support");
1870 registry.build_router_with_mockai(Some(mockai_instance.clone()))
1871 } else {
1872 registry.build_router()
1873 };
1874 let body_limit_mb = std::env::var("MOCKFORGE_HTTP_BODY_LIMIT_MB")
1882 .ok()
1883 .and_then(|v| v.parse::<usize>().ok())
1884 .unwrap_or(50);
1885 let body_limit_bytes = body_limit_mb.saturating_mul(1024 * 1024);
1886 let spec_router =
1887 spec_router.layer(axum::extract::DefaultBodyLimit::max(body_limit_bytes));
1888 tracing::info!(
1889 body_limit_mb = body_limit_mb,
1890 "Merging OpenAPI router with main router"
1891 );
1892 app = app.merge(spec_router);
1893 }
1894 Err(e) => {
1895 warn!("Failed to load OpenAPI spec from {:?}: {}. Starting without OpenAPI integration.", spec_path, e);
1896 }
1897 }
1898 }
1899
1900 let route_chaos_injector: Option<
1904 std::sync::Arc<dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1905 > = if let Some(ref route_configs) = route_configs {
1906 if !route_configs.is_empty() {
1907 let route_configs_converted: Vec<mockforge_core::config::RouteConfig> =
1910 route_configs.to_vec();
1911 match mockforge_route_chaos::RouteChaosInjector::new(route_configs_converted) {
1912 Ok(injector) => {
1913 info!(
1914 "Initialized advanced routing features for {} route(s)",
1915 route_configs.len()
1916 );
1917 Some(std::sync::Arc::new(injector)
1920 as std::sync::Arc<
1921 dyn mockforge_core::priority_handler::RouteChaosInjectorTrait,
1922 >)
1923 }
1924 Err(e) => {
1925 warn!(
1926 "Failed to initialize advanced routing features: {}. Using basic routing.",
1927 e
1928 );
1929 None
1930 }
1931 }
1932 } else {
1933 None
1934 }
1935 } else {
1936 None
1937 };
1938
1939 if let Some(route_configs) = route_configs {
1940 use axum::http::StatusCode;
1941 use axum::response::IntoResponse;
1942
1943 if !route_configs.is_empty() {
1944 info!("Registering {} custom route(s) from config", route_configs.len());
1945 }
1946
1947 let injector = route_chaos_injector.clone();
1948 for route_config in route_configs {
1949 let status = route_config.response.status;
1950 let body = route_config.response.body.clone();
1951 let headers = route_config.response.headers.clone();
1952 let path = route_config.path.clone();
1953 let method = route_config.method.clone();
1954
1955 let expected_method = method.to_uppercase();
1960 let injector_clone = injector.clone();
1964 app = app.route(
1965 &path,
1966 #[allow(clippy::non_send_fields_in_send_ty)]
1967 axum::routing::any(move |req: Request<Body>| {
1968 let body = body.clone();
1969 let headers = headers.clone();
1970 let expand = template_expand;
1971 let expected = expected_method.clone();
1972 let status_code = status;
1973 let injector_for_chaos = injector_clone.clone();
1975
1976 async move {
1977 if req.method().as_str() != expected.as_str() {
1979 return axum::response::Response::builder()
1981 .status(StatusCode::METHOD_NOT_ALLOWED)
1982 .header("Allow", &expected)
1983 .body(Body::empty())
1984 .unwrap()
1985 .into_response();
1986 }
1987
1988 if let Some(fault_response) = apply_route_chaos(
1992 injector_for_chaos.as_deref(),
1993 req.method(),
1994 req.uri(),
1995 )
1996 .await
1997 {
1998 return fault_response;
1999 }
2000
2001 let mut body_value = body.unwrap_or(serde_json::json!({}));
2003
2004 if expand {
2008 use mockforge_template_expansion::RequestContext;
2009 use serde_json::Value;
2010 use std::collections::HashMap;
2011
2012 let method = req.method().to_string();
2014 let path = req.uri().path().to_string();
2015
2016 let query_params: HashMap<String, Value> = req
2018 .uri()
2019 .query()
2020 .map(|q| {
2021 url::form_urlencoded::parse(q.as_bytes())
2022 .into_owned()
2023 .map(|(k, v)| (k, Value::String(v)))
2024 .collect()
2025 })
2026 .unwrap_or_default();
2027
2028 let headers: HashMap<String, Value> = req
2030 .headers()
2031 .iter()
2032 .map(|(k, v)| {
2033 (
2034 k.to_string(),
2035 Value::String(v.to_str().unwrap_or_default().to_string()),
2036 )
2037 })
2038 .collect();
2039
2040 let context = RequestContext {
2044 method,
2045 path,
2046 query_params,
2047 headers,
2048 body: None, path_params: HashMap::new(),
2050 multipart_fields: HashMap::new(),
2051 multipart_files: HashMap::new(),
2052 };
2053
2054 let body_value_clone = body_value.clone();
2058 let context_clone = context.clone();
2059 body_value = match tokio::task::spawn_blocking(move || {
2060 mockforge_template_expansion::expand_templates_in_json(
2061 body_value_clone,
2062 &context_clone,
2063 )
2064 })
2065 .await
2066 {
2067 Ok(result) => result,
2068 Err(_) => body_value, };
2070 }
2071
2072 let mut response = Json(body_value).into_response();
2073
2074 *response.status_mut() =
2076 StatusCode::from_u16(status_code).unwrap_or(StatusCode::OK);
2077
2078 for (key, value) in headers {
2080 if let Ok(header_name) = http::HeaderName::from_bytes(key.as_bytes()) {
2081 if let Ok(header_value) = http::HeaderValue::from_str(&value) {
2082 response.headers_mut().insert(header_name, header_value);
2083 }
2084 }
2085 }
2086
2087 response
2088 }
2089 }),
2090 );
2091
2092 debug!("Registered route: {} {}", method, path);
2093 }
2094 }
2095
2096 if let Some(health) = health_manager {
2098 app = app.merge(health::health_router(health));
2100 info!(
2101 "Health check endpoints enabled: /health, /health/live, /health/ready, /health/startup"
2102 );
2103 } else if include_default_health {
2104 app = app.route(
2106 "/health",
2107 axum::routing::get(|| async {
2108 use mockforge_core::server_utils::health::HealthStatus;
2109 {
2110 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
2112 Ok(value) => Json(value),
2113 Err(e) => {
2114 tracing::error!("Failed to serialize health status: {}", e);
2116 Json(serde_json::json!({
2117 "status": "healthy",
2118 "service": "mockforge-http",
2119 "uptime_seconds": 0
2120 }))
2121 }
2122 }
2123 }
2124 }),
2125 );
2126 }
2127
2128 app = app.merge(sse::sse_router());
2129 app = app.merge(file_server::file_serving_router());
2131
2132 let mgmt_spec = if let Some(ref sp) = spec_path {
2135 match OpenApiSpec::from_file(sp).await {
2136 Ok(s) => Some(Arc::new(s)),
2137 Err(e) => {
2138 debug!("Failed to load OpenAPI spec for management API: {}", e);
2139 None
2140 }
2141 }
2142 } else {
2143 None
2144 };
2145 let spec_path_clone = spec_path.clone();
2146 let mgmt_port = std::env::var("PORT")
2147 .or_else(|_| std::env::var("MOCKFORGE_HTTP_PORT"))
2148 .ok()
2149 .and_then(|p| p.parse().ok())
2150 .unwrap_or(3000);
2151 let management_state = ManagementState::new(mgmt_spec, spec_path_clone, mgmt_port);
2152
2153 use std::sync::Arc;
2155 let ws_state = WsManagementState::new();
2156 let ws_broadcast = Arc::new(ws_state.tx.clone());
2157 let management_state = management_state.with_ws_broadcast(ws_broadcast);
2158
2159 let management_state = if let Some(proxy_cfg) = proxy_config {
2161 use tokio::sync::RwLock;
2162 let proxy_config_arc = Arc::new(RwLock::new(proxy_cfg));
2163 management_state.with_proxy_config(proxy_config_arc)
2164 } else {
2165 management_state
2166 };
2167
2168 #[cfg(feature = "smtp")]
2169 let management_state = {
2170 if let Some(smtp_reg) = smtp_registry {
2171 match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
2172 Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
2173 Err(e) => {
2174 error!(
2175 "Invalid SMTP registry type passed to HTTP management state: {:?}",
2176 e.type_id()
2177 );
2178 management_state
2179 }
2180 }
2181 } else {
2182 management_state
2183 }
2184 };
2185 #[cfg(not(feature = "smtp"))]
2186 let management_state = {
2187 let _ = smtp_registry;
2188 management_state
2189 };
2190 #[cfg(feature = "mqtt")]
2191 let management_state = {
2192 if let Some(sessions) = mqtt_broker {
2195 match sessions.downcast::<mockforge_mqtt::SessionManager>() {
2196 Ok(sessions) => management_state.with_mqtt_sessions(sessions),
2197 Err(e) => {
2198 error!(
2199 "Invalid MQTT session manager passed to HTTP management state: {:?}",
2200 e.type_id()
2201 );
2202 management_state
2203 }
2204 }
2205 } else {
2206 management_state
2207 }
2208 };
2209 #[cfg(not(feature = "mqtt"))]
2210 let management_state = {
2211 let _ = mqtt_broker;
2212 management_state
2213 };
2214 #[cfg(feature = "amqp")]
2215 let management_state = {
2216 if let Some(broker) = amqp_broker {
2217 match broker.downcast::<mockforge_amqp::AmqpBroker>() {
2218 Ok(broker) => management_state.with_amqp_broker(broker),
2219 Err(e) => {
2220 error!(
2221 "Invalid AMQP broker passed to HTTP management state: {:?}",
2222 e.type_id()
2223 );
2224 management_state
2225 }
2226 }
2227 } else {
2228 management_state
2229 }
2230 };
2231 #[cfg(not(feature = "amqp"))]
2232 let management_state = {
2233 let _ = amqp_broker;
2234 management_state
2235 };
2236 #[cfg(feature = "kafka")]
2237 let management_state = {
2238 if let Some(broker) = kafka_broker {
2239 match broker.downcast::<mockforge_kafka::KafkaMockBroker>() {
2240 Ok(broker) => management_state.with_kafka_broker(broker),
2241 Err(e) => {
2242 error!(
2243 "Invalid Kafka broker passed to HTTP management state: {:?}",
2244 e.type_id()
2245 );
2246 management_state
2247 }
2248 }
2249 } else {
2250 management_state
2251 }
2252 };
2253 #[cfg(not(feature = "kafka"))]
2254 let management_state = {
2255 let _ = kafka_broker;
2256 management_state
2257 };
2258 let management_state_for_fallback = management_state.clone();
2259 app = app.nest("/__mockforge/api", management_router(management_state));
2260 app = app.fallback_service(
2262 axum::routing::any(management::dynamic_mock_fallback)
2263 .with_state(management_state_for_fallback),
2264 );
2265
2266 app = app.merge(verification_router());
2268
2269 {
2274 use crate::chain_handlers::{chains_router, create_chain_state};
2275 let chain_config = _circling_config.clone().unwrap_or_default();
2276 let chain_registry = Arc::new(mockforge_core::request_chaining::RequestChainRegistry::new(
2277 chain_config.clone(),
2278 ));
2279 let chain_engine = Arc::new(mockforge_core::chain_execution::ChainExecutionEngine::new(
2280 chain_registry.clone(),
2281 chain_config,
2282 ));
2283 app = app.nest(
2284 "/__mockforge/chains",
2285 chains_router(create_chain_state(chain_registry, chain_engine)),
2286 );
2287 }
2288
2289 {
2294 use crate::contract_diff_api::{contract_diff_api_router, ContractDiffApiState};
2295 let cd_state = Arc::new(ContractDiffApiState::new(spec_path.clone()));
2296 app = app.nest("/__mockforge/api/contract-diff", contract_diff_api_router(cd_state));
2297 }
2298
2299 {
2306 use crate::fixtures_api::{fixtures_api_router, FixturesApiState};
2307 let fx_state = FixturesApiState::from_env();
2308 app = app.nest("/__mockforge/fixtures", fixtures_api_router(fx_state));
2309 }
2310
2311 {
2318 use crate::mockai_api::{mockai_api_router, MockAiApiState};
2319 let api_state = MockAiApiState::new(mockai.clone());
2320 app = app.nest("/__mockforge/api/mockai", mockai_api_router(api_state));
2321 }
2322
2323 app = app.nest("/__mockforge/time-travel", time_travel_api::time_travel_router());
2330
2331 {
2336 use crate::route_chaos_runtime::{
2337 route_chaos_api_router, runtime_route_chaos_middleware, RuntimeRouteChaosState,
2338 };
2339 let runtime_state = RuntimeRouteChaosState::new(Vec::new());
2340 let middleware_state = runtime_state.clone();
2341 app = app.layer(from_fn_with_state(middleware_state, runtime_route_chaos_middleware));
2342 app = app.nest("/__mockforge/api/route-chaos", route_chaos_api_router(runtime_state));
2343 }
2344
2345 {
2351 use crate::network_profile_runtime::{
2352 network_profile_api_router, network_profile_middleware, NetworkProfileRuntimeState,
2353 };
2354 let runtime_state = NetworkProfileRuntimeState::new(
2355 mockforge_core::network_profiles::NetworkProfileCatalog::new(),
2356 );
2357 let middleware_state = runtime_state.clone();
2358 app = app.layer(from_fn_with_state(middleware_state, network_profile_middleware));
2359 app = app
2360 .nest("/__mockforge/api/network-profiles", network_profile_api_router(runtime_state));
2361 }
2362
2363 use crate::auth::oidc::oidc_router;
2365 app = app.merge(oidc_router());
2366
2367 {
2369 use mockforge_core::security::get_global_access_review_service;
2370 if let Some(service) = get_global_access_review_service().await {
2371 use crate::handlers::access_review::{access_review_router, AccessReviewState};
2372 let review_state = AccessReviewState { service };
2373 app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
2374 debug!("Access review API mounted at /api/v1/security/access-reviews");
2375 }
2376 }
2377
2378 {
2380 use mockforge_core::security::get_global_privileged_access_manager;
2381 if let Some(manager) = get_global_privileged_access_manager().await {
2382 use crate::handlers::privileged_access::{
2383 privileged_access_router, PrivilegedAccessState,
2384 };
2385 let privileged_state = PrivilegedAccessState { manager };
2386 app = app.nest(
2387 "/api/v1/security/privileged-access",
2388 privileged_access_router(privileged_state),
2389 );
2390 debug!("Privileged access API mounted at /api/v1/security/privileged-access");
2391 }
2392 }
2393
2394 {
2396 use mockforge_core::security::get_global_change_management_engine;
2397 if let Some(engine) = get_global_change_management_engine().await {
2398 use crate::handlers::change_management::{
2399 change_management_router, ChangeManagementState,
2400 };
2401 let change_state = ChangeManagementState { engine };
2402 app = app.nest("/api/v1/change-management", change_management_router(change_state));
2403 debug!("Change management API mounted at /api/v1/change-management");
2404 }
2405 }
2406
2407 {
2409 use mockforge_core::security::get_global_risk_assessment_engine;
2410 if let Some(engine) = get_global_risk_assessment_engine().await {
2411 use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
2412 let risk_state = RiskAssessmentState { engine };
2413 app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
2414 debug!("Risk assessment API mounted at /api/v1/security/risks");
2415 }
2416 }
2417
2418 {
2420 use crate::auth::token_lifecycle::TokenLifecycleManager;
2421 use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
2422 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2423 let lifecycle_state = TokenLifecycleState {
2424 manager: lifecycle_manager,
2425 };
2426 app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
2427 debug!("Token lifecycle API mounted at /api/v1/auth");
2428 }
2429
2430 {
2432 use crate::auth::oidc::load_oidc_state;
2433 use crate::auth::token_lifecycle::TokenLifecycleManager;
2434 use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
2435 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
2437 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2438 let oauth2_state = OAuth2ServerState {
2439 oidc_state,
2440 lifecycle_manager,
2441 auth_codes: Arc::new(RwLock::new(HashMap::new())),
2442 refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
2443 };
2444 app = app.merge(oauth2_server_router(oauth2_state));
2445 debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
2446 }
2447
2448 {
2450 use crate::auth::oidc::load_oidc_state;
2451 use crate::auth::risk_engine::RiskEngine;
2452 use crate::auth::token_lifecycle::TokenLifecycleManager;
2453 use crate::handlers::consent::{consent_router, ConsentState};
2454 use crate::handlers::oauth2_server::OAuth2ServerState;
2455 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
2457 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2458 let oauth2_state = OAuth2ServerState {
2459 oidc_state: oidc_state.clone(),
2460 lifecycle_manager: lifecycle_manager.clone(),
2461 auth_codes: Arc::new(RwLock::new(HashMap::new())),
2462 refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
2463 };
2464 let risk_engine = Arc::new(RiskEngine::default());
2465 let consent_state = ConsentState {
2466 oauth2_state,
2467 risk_engine,
2468 };
2469 app = app.merge(consent_router(consent_state));
2470 debug!("Consent screen endpoints mounted at /consent");
2471 }
2472
2473 {
2475 use crate::auth::risk_engine::RiskEngine;
2476 use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
2477 let risk_engine = Arc::new(RiskEngine::default());
2478 let risk_state = RiskSimulationState { risk_engine };
2479 app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
2480 debug!("Risk simulation API mounted at /api/v1/auth/risk");
2481 }
2482
2483 #[cfg(feature = "database")]
2485 let database = {
2486 use crate::database::Database;
2487 let database_url = std::env::var("DATABASE_URL").ok();
2488 match Database::connect_optional(database_url.as_deref()).await {
2489 Ok(db) => {
2490 if db.is_connected() {
2491 if let Err(e) = db.migrate_if_connected().await {
2493 warn!("Failed to run database migrations: {}", e);
2494 } else {
2495 info!("Database connected and migrations applied");
2496 }
2497 }
2498 Some(db)
2499 }
2500 Err(e) => {
2501 warn!("Failed to connect to database: {}. Continuing without database support.", e);
2502 None
2503 }
2504 }
2505 };
2506
2507 let (drift_engine, incident_manager, drift_config) = {
2510 use mockforge_core::contract_drift::{DriftBudgetConfig, DriftBudgetEngine};
2511 use mockforge_core::incidents::{IncidentManager, IncidentStore};
2512 use std::sync::Arc;
2513
2514 let drift_config = DriftBudgetConfig::default();
2516 let drift_engine = Arc::new(DriftBudgetEngine::new(drift_config.clone()));
2517
2518 let incident_store = Arc::new(IncidentStore::default());
2520 let incident_manager = Arc::new(IncidentManager::new(incident_store.clone()));
2521
2522 (drift_engine, incident_manager, drift_config)
2523 };
2524
2525 {
2526 use crate::handlers::drift_budget::{drift_budget_router, DriftBudgetState};
2527 use crate::middleware::drift_tracking::DriftTrackingState;
2528 use mockforge_contracts::consumer_contracts::{
2529 ConsumerBreakingChangeDetector, UsageRecorder,
2530 };
2531 use mockforge_core::ai_contract_diff::ContractDiffAnalyzer;
2532 use std::sync::Arc;
2533
2534 let usage_recorder = Arc::new(UsageRecorder::default());
2536 let consumer_detector =
2537 Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2538
2539 let diff_analyzer = if drift_config.enabled {
2541 match ContractDiffAnalyzer::new(
2542 mockforge_core::ai_contract_diff::ContractDiffConfig::default(),
2543 ) {
2544 Ok(analyzer) => Some(Arc::new(analyzer)),
2545 Err(e) => {
2546 warn!("Failed to create contract diff analyzer: {}", e);
2547 None
2548 }
2549 }
2550 } else {
2551 None
2552 };
2553
2554 let spec = if let Some(ref spec_path) = spec_path {
2557 match OpenApiSpec::from_file(spec_path).await {
2558 Ok(s) => Some(Arc::new(s)),
2559 Err(e) => {
2560 debug!("Failed to load OpenAPI spec for drift tracking: {}", e);
2561 None
2562 }
2563 }
2564 } else {
2565 None
2566 };
2567
2568 let drift_tracking_state = DriftTrackingState {
2570 diff_analyzer,
2571 spec,
2572 drift_engine: drift_engine.clone(),
2573 incident_manager: incident_manager.clone(),
2574 usage_recorder,
2575 consumer_detector,
2576 enabled: drift_config.enabled,
2577 };
2578
2579 app = app.layer(axum::middleware::from_fn(middleware::buffer_response_middleware));
2581
2582 let drift_tracking_state_clone = drift_tracking_state.clone();
2585 app = app.layer(axum::middleware::from_fn(
2586 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2587 let state = drift_tracking_state_clone.clone();
2588 async move {
2589 if req.extensions().get::<DriftTrackingState>().is_none() {
2591 req.extensions_mut().insert(state);
2592 }
2593 middleware::drift_tracking::drift_tracking_middleware_with_extensions(req, next)
2595 .await
2596 }
2597 },
2598 ));
2599
2600 let drift_state = DriftBudgetState {
2601 engine: drift_engine.clone(),
2602 incident_manager: incident_manager.clone(),
2603 gitops_handler: None, };
2605
2606 app = app.merge(drift_budget_router(drift_state));
2607 debug!("Drift budget and incident management endpoints mounted at /api/v1/drift");
2608 }
2609
2610 #[cfg(feature = "pipelines")]
2612 {
2613 use crate::handlers::pipelines::{pipeline_router, PipelineState};
2614
2615 let pipeline_state = PipelineState::new();
2616 app = app.merge(pipeline_router(pipeline_state));
2617 debug!("Pipeline management endpoints mounted at /api/v1/pipelines");
2618 }
2619
2620 {
2622 use crate::handlers::contract_health::{contract_health_router, ContractHealthState};
2623 use mockforge_contracts::contract_drift::forecasting::{Forecaster, ForecastingConfig};
2624 use mockforge_core::contract_drift::threat_modeling::ThreatAnalyzer;
2625 use mockforge_core::incidents::semantic_manager::SemanticIncidentManager;
2626 use mockforge_foundation::threat_modeling_types::ThreatModelingConfig;
2627 use mockforge_intelligence::handlers::forecasting::{forecasting_router, ForecastingState};
2628 use mockforge_intelligence::handlers::semantic_drift::{
2629 semantic_drift_router, SemanticDriftState,
2630 };
2631 use mockforge_intelligence::handlers::threat_modeling::{
2632 threat_modeling_router, ThreatModelingState,
2633 };
2634 use std::sync::Arc;
2635
2636 let forecasting_config = ForecastingConfig::default();
2638 let forecaster = Arc::new(Forecaster::new(forecasting_config));
2639 let forecasting_state = ForecastingState {
2640 forecaster,
2641 #[cfg(feature = "database")]
2642 database: database.clone(),
2643 };
2644
2645 let semantic_manager = Arc::new(SemanticIncidentManager::new());
2647 let semantic_state = SemanticDriftState {
2648 manager: semantic_manager,
2649 #[cfg(feature = "database")]
2650 database: database.clone(),
2651 };
2652
2653 let threat_config = ThreatModelingConfig::default();
2655 let threat_analyzer = match ThreatAnalyzer::new(threat_config) {
2656 Ok(analyzer) => Arc::new(analyzer),
2657 Err(e) => {
2658 warn!("Failed to create threat analyzer: {}. Using default.", e);
2659 Arc::new(ThreatAnalyzer::new(ThreatModelingConfig::default()).unwrap_or_else(
2660 |_| {
2661 ThreatAnalyzer::new(ThreatModelingConfig {
2663 enabled: false,
2664 ..Default::default()
2665 })
2666 .expect("Failed to create fallback threat analyzer")
2667 },
2668 ))
2669 }
2670 };
2671 let mut webhook_configs = Vec::new();
2673 let config_paths = [
2674 "config.yaml",
2675 "mockforge.yaml",
2676 "tools/mockforge/config.yaml",
2677 "../tools/mockforge/config.yaml",
2678 ];
2679
2680 for path in &config_paths {
2681 if let Ok(config) = mockforge_core::config::load_config(path).await {
2682 if !config.incidents.webhooks.is_empty() {
2683 webhook_configs = config.incidents.webhooks.clone();
2684 info!("Loaded {} webhook configs from config: {}", webhook_configs.len(), path);
2685 break;
2686 }
2687 }
2688 }
2689
2690 if webhook_configs.is_empty() {
2691 debug!("No webhook configs found in config files, using empty list");
2692 }
2693
2694 let threat_state = ThreatModelingState {
2695 analyzer: threat_analyzer,
2696 webhook_configs,
2697 #[cfg(feature = "database")]
2698 database: database.clone(),
2699 };
2700
2701 let contract_health_state = ContractHealthState {
2703 incident_manager: incident_manager.clone(),
2704 semantic_manager: Arc::new(SemanticIncidentManager::new()),
2705 #[cfg(feature = "database")]
2706 database: database.clone(),
2707 };
2708
2709 app = app.merge(forecasting_router(forecasting_state));
2711 debug!("Forecasting endpoints mounted at /api/v1/forecasts");
2712
2713 app = app.merge(semantic_drift_router(semantic_state));
2714 debug!("Semantic drift endpoints mounted at /api/v1/semantic-drift");
2715
2716 app = app.merge(threat_modeling_router(threat_state));
2717 debug!("Threat modeling endpoints mounted at /api/v1/threats");
2718
2719 app = app.merge(contract_health_router(contract_health_state));
2720 debug!("Contract health endpoints mounted at /api/v1/contract-health");
2721 }
2722
2723 {
2725 use crate::handlers::protocol_contracts::{
2726 protocol_contracts_router, ProtocolContractState,
2727 };
2728 use mockforge_core::contract_drift::{
2729 ConsumerImpactAnalyzer, FitnessFunctionRegistry, ProtocolContractRegistry,
2730 };
2731 use std::sync::Arc;
2732 use tokio::sync::RwLock;
2733
2734 let contract_registry = Arc::new(RwLock::new(ProtocolContractRegistry::new()));
2736
2737 let mut fitness_registry = FitnessFunctionRegistry::new();
2739
2740 let config_paths = [
2742 "config.yaml",
2743 "mockforge.yaml",
2744 "tools/mockforge/config.yaml",
2745 "../tools/mockforge/config.yaml",
2746 ];
2747
2748 let mut config_loaded = false;
2749 for path in &config_paths {
2750 if let Ok(config) = mockforge_core::config::load_config(path).await {
2751 if !config.contracts.fitness_rules.is_empty() {
2752 if let Err(e) =
2753 fitness_registry.load_from_config(&config.contracts.fitness_rules)
2754 {
2755 warn!("Failed to load fitness rules from config {}: {}", path, e);
2756 } else {
2757 info!(
2758 "Loaded {} fitness rules from config: {}",
2759 config.contracts.fitness_rules.len(),
2760 path
2761 );
2762 config_loaded = true;
2763 break;
2764 }
2765 }
2766 }
2767 }
2768
2769 if !config_loaded {
2770 debug!("No fitness rules found in config files, using empty registry");
2771 }
2772
2773 let fitness_registry = Arc::new(RwLock::new(fitness_registry));
2774
2775 let consumer_mapping_registry =
2779 mockforge_core::contract_drift::ConsumerMappingRegistry::new();
2780 let consumer_analyzer =
2781 Arc::new(RwLock::new(ConsumerImpactAnalyzer::new(consumer_mapping_registry)));
2782
2783 let protocol_state = ProtocolContractState {
2784 registry: contract_registry,
2785 drift_engine: Some(drift_engine.clone()),
2786 incident_manager: Some(incident_manager.clone()),
2787 fitness_registry: Some(fitness_registry),
2788 consumer_analyzer: Some(consumer_analyzer),
2789 };
2790
2791 app = app.nest("/api/v1/contracts", protocol_contracts_router(protocol_state));
2792 debug!("Protocol contracts endpoints mounted at /api/v1/contracts");
2793 }
2794
2795 #[cfg(feature = "behavioral-cloning")]
2797 {
2798 use crate::middleware::behavioral_cloning::BehavioralCloningMiddlewareState;
2799 use std::path::PathBuf;
2800
2801 let db_path = std::env::var("RECORDER_DATABASE_PATH")
2803 .ok()
2804 .map(PathBuf::from)
2805 .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2806
2807 let bc_middleware_state = if let Some(path) = db_path {
2808 BehavioralCloningMiddlewareState::with_database_path(path)
2809 } else {
2810 BehavioralCloningMiddlewareState::new()
2811 };
2812
2813 let enabled = std::env::var("BEHAVIORAL_CLONING_ENABLED")
2815 .ok()
2816 .and_then(|v| v.parse::<bool>().ok())
2817 .unwrap_or(false);
2818
2819 if enabled {
2820 let bc_state_clone = bc_middleware_state.clone();
2821 app = app.layer(axum::middleware::from_fn(
2822 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2823 let state = bc_state_clone.clone();
2824 async move {
2825 if req.extensions().get::<BehavioralCloningMiddlewareState>().is_none() {
2827 req.extensions_mut().insert(state);
2828 }
2829 middleware::behavioral_cloning::behavioral_cloning_middleware(req, next)
2831 .await
2832 }
2833 },
2834 ));
2835 debug!("Behavioral cloning middleware enabled (applies learned behavior to requests)");
2836 }
2837 }
2838
2839 {
2841 use crate::handlers::consumer_contracts::{
2842 consumer_contracts_router, ConsumerContractsState,
2843 };
2844 use mockforge_contracts::consumer_contracts::{
2845 ConsumerBreakingChangeDetector, ConsumerRegistry, UsageRecorder,
2846 };
2847 use std::sync::Arc;
2848
2849 let registry = Arc::new(ConsumerRegistry::default());
2851
2852 let usage_recorder = Arc::new(UsageRecorder::default());
2854
2855 let detector = Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2857
2858 let consumer_state = ConsumerContractsState {
2859 registry,
2860 usage_recorder,
2861 detector,
2862 violations: Arc::new(RwLock::new(HashMap::new())),
2863 };
2864
2865 app = app.merge(consumer_contracts_router(consumer_state));
2866 debug!("Consumer contracts endpoints mounted at /api/v1/consumers");
2867 }
2868
2869 #[cfg(feature = "behavioral-cloning")]
2871 {
2872 use crate::handlers::behavioral_cloning::{
2873 behavioral_cloning_router, BehavioralCloningState,
2874 };
2875 use std::path::PathBuf;
2876
2877 let db_path = std::env::var("RECORDER_DATABASE_PATH")
2879 .ok()
2880 .map(PathBuf::from)
2881 .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2882
2883 let bc_state = if let Some(path) = db_path {
2884 BehavioralCloningState::with_database_path(path)
2885 } else {
2886 BehavioralCloningState::new()
2887 };
2888
2889 app = app.merge(behavioral_cloning_router(bc_state));
2890 debug!("Behavioral cloning endpoints mounted at /api/v1/behavioral-cloning");
2891 }
2892
2893 {
2895 use crate::consistency::{ConsistencyMiddlewareState, HttpAdapter};
2896 use mockforge_intelligence::consistency::ConsistencyEngine;
2897 use mockforge_intelligence::handlers::consistency::{consistency_router, ConsistencyState};
2898 use std::sync::Arc;
2899
2900 let consistency_engine = Arc::new(ConsistencyEngine::new());
2902
2903 let http_adapter = Arc::new(HttpAdapter::new(consistency_engine.clone()));
2905 consistency_engine.register_adapter(http_adapter.clone()).await;
2906
2907 let consistency_state = ConsistencyState {
2909 engine: consistency_engine.clone(),
2910 };
2911
2912 use mockforge_intelligence::handlers::xray::XRayState;
2914 let xray_state = Arc::new(XRayState::new(consistency_engine.clone()));
2915
2916 let consistency_middleware_state = ConsistencyMiddlewareState {
2918 engine: consistency_engine.clone(),
2919 adapter: http_adapter,
2920 xray_state: Some(xray_state.clone()),
2921 };
2922
2923 if let Some(reality_cfg) = reality_proxy::RealityProxyConfig::from_env() {
2931 tracing::info!(
2932 upstream = %reality_cfg.upstream_base,
2933 "Reality-driven proxy middleware enabled — requests will be split between mock and upstream based on reality_continuum_ratio"
2934 );
2935 app = app.layer(axum::middleware::from_fn(
2936 move |req: axum::extract::Request, next: axum::middleware::Next| {
2937 let cfg = reality_cfg.clone();
2938 async move { reality_proxy::reality_proxy_middleware(cfg, req, next).await }
2939 },
2940 ));
2941 }
2942
2943 let consistency_middleware_state_clone = consistency_middleware_state.clone();
2945 app = app.layer(axum::middleware::from_fn(
2946 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2947 let state = consistency_middleware_state_clone.clone();
2948 async move {
2949 if req.extensions().get::<ConsistencyMiddlewareState>().is_none() {
2951 req.extensions_mut().insert(state);
2952 }
2953 consistency::middleware::consistency_middleware(req, next).await
2955 }
2956 },
2957 ));
2958
2959 app = app.merge(consistency_router(consistency_state));
2961 debug!("Consistency engine initialized and endpoints mounted at /api/v1/consistency");
2962
2963 #[cfg(feature = "scenario-engine")]
2971 {
2972 use crate::scenarios_runtime::{scenarios_api_router, ScenarioRuntimeState};
2973 let mut scenario_storage = match mockforge_scenarios::ScenarioStorage::new() {
2974 Ok(s) => s,
2975 Err(e) => {
2976 tracing::warn!(
2977 error = %e,
2978 "Failed to init scenario storage; runtime scenarios API will list empty"
2979 );
2980 let tmp = std::env::temp_dir().join("mockforge-empty-scenarios");
2983 mockforge_scenarios::ScenarioStorage::with_dir(&tmp)
2984 .expect("temp scenario storage")
2985 }
2986 };
2987 if let Err(e) = scenario_storage.load().await {
2988 tracing::warn!(
2989 error = %e,
2990 "Failed to load installed scenarios; API will list empty until scenarios are installed"
2991 );
2992 }
2993 let scenarios_state =
2994 ScenarioRuntimeState::new(scenario_storage, consistency_engine.clone());
2995 app = app.nest("/__mockforge/api/scenarios", scenarios_api_router(scenarios_state));
2996 debug!("Scenario runtime API mounted at /__mockforge/api/scenarios");
2997 }
2998
2999 {
3001 use mockforge_intelligence::handlers::fidelity::{fidelity_router, FidelityState};
3002 let fidelity_state = FidelityState::new();
3003 app = app.merge(fidelity_router(fidelity_state));
3004 debug!("Fidelity score endpoints mounted at /api/v1/workspace/:workspace_id/fidelity");
3005 }
3006
3007 {
3009 use mockforge_intelligence::handlers::scenario_studio::{
3010 scenario_studio_router, ScenarioStudioState,
3011 };
3012 let scenario_studio_state = ScenarioStudioState::new();
3013 app = app.merge(scenario_studio_router(scenario_studio_state));
3014 debug!("Scenario Studio endpoints mounted at /api/v1/scenario-studio");
3015 }
3016
3017 {
3019 use crate::handlers::performance::{performance_router, PerformanceState};
3020 let performance_state = PerformanceState::new();
3021 app = app.nest("/api/performance", performance_router(performance_state));
3022 debug!("Performance mode endpoints mounted at /api/performance");
3023 }
3024
3025 {
3027 use crate::handlers::world_state::{world_state_router, WorldStateState};
3028 use mockforge_world_state::WorldStateEngine;
3029 use std::sync::Arc;
3030 use tokio::sync::RwLock;
3031
3032 let world_state_engine = Arc::new(RwLock::new(WorldStateEngine::new()));
3033 let world_state_state = WorldStateState {
3034 engine: world_state_engine,
3035 };
3036 app = app.nest("/api/world-state", world_state_router().with_state(world_state_state));
3037 debug!("World state endpoints mounted at /api/world-state");
3038 }
3039
3040 {
3042 use crate::handlers::snapshots::{snapshot_router, SnapshotState};
3043 use mockforge_core::snapshots::SnapshotManager;
3044 use std::path::PathBuf;
3045
3046 let snapshot_dir = std::env::var("MOCKFORGE_SNAPSHOT_DIR").ok().map(PathBuf::from);
3047 let snapshot_manager = Arc::new(SnapshotManager::new(snapshot_dir));
3048
3049 let snapshot_state = SnapshotState {
3050 manager: snapshot_manager,
3051 consistency_engine: Some(consistency_engine.clone()),
3052 workspace_persistence: None, vbr_engine: None, recorder: None, };
3056
3057 app = app.merge(snapshot_router(snapshot_state));
3058 debug!("Snapshot management endpoints mounted at /api/v1/snapshots");
3059
3060 {
3062 use mockforge_intelligence::handlers::xray::xray_router;
3063 app = app.merge(xray_router((*xray_state).clone()));
3064 debug!("X-Ray API endpoints mounted at /api/v1/xray");
3065 }
3066 }
3067
3068 {
3070 use crate::handlers::ab_testing::{ab_testing_router, ABTestingState};
3071 use crate::middleware::ab_testing::ab_testing_middleware;
3072
3073 let ab_testing_state = ABTestingState::new();
3074
3075 let ab_testing_state_clone = ab_testing_state.clone();
3077 app = app.layer(axum::middleware::from_fn(
3078 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
3079 let state = ab_testing_state_clone.clone();
3080 async move {
3081 if req.extensions().get::<ABTestingState>().is_none() {
3083 req.extensions_mut().insert(state);
3084 }
3085 ab_testing_middleware(req, next).await
3087 }
3088 },
3089 ));
3090
3091 app = app.merge(ab_testing_router(ab_testing_state));
3093 debug!("A/B testing endpoints mounted at /api/v1/ab-tests");
3094 }
3095 }
3096
3097 {
3099 use crate::handlers::pr_generation::{pr_generation_router, PRGenerationState};
3100 use mockforge_intelligence::pr_generation::{PRGenerator, PRProvider};
3101 use std::sync::Arc;
3102
3103 let pr_config = mockforge_intelligence::pr_generation::PRGenerationConfig::from_env();
3105
3106 let generator = pr_config.token.clone().filter(|_| pr_config.enabled).map(|token| {
3109 let generator = match pr_config.provider {
3110 PRProvider::GitHub => PRGenerator::new_github(
3111 pr_config.owner.clone(),
3112 pr_config.repo.clone(),
3113 token,
3114 pr_config.base_branch.clone(),
3115 ),
3116 PRProvider::GitLab => PRGenerator::new_gitlab(
3117 pr_config.owner.clone(),
3118 pr_config.repo.clone(),
3119 token,
3120 pr_config.base_branch.clone(),
3121 ),
3122 };
3123 Arc::new(generator)
3124 });
3125
3126 let pr_state = PRGenerationState {
3127 generator: generator.clone(),
3128 };
3129
3130 app = app.merge(pr_generation_router(pr_state));
3131 if generator.is_some() {
3132 debug!(
3133 "PR generation endpoints mounted at /api/v1/pr (configured for {:?})",
3134 pr_config.provider
3135 );
3136 } else {
3137 debug!("PR generation endpoints mounted at /api/v1/pr (not configured - set GITHUB_TOKEN/GITLAB_TOKEN and PR_REPO_OWNER/PR_REPO_NAME)");
3138 }
3139 }
3140
3141 app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
3143
3144 if let Some(mt_config) = multi_tenant_config {
3146 if mt_config.enabled {
3147 use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
3148 use std::sync::Arc;
3149
3150 info!(
3151 "Multi-tenant mode enabled with {} routing strategy",
3152 match mt_config.routing_strategy {
3153 mockforge_foundation::multi_tenant_types::RoutingStrategy::Path => "path-based",
3154 mockforge_foundation::multi_tenant_types::RoutingStrategy::Port => "port-based",
3155 mockforge_foundation::multi_tenant_types::RoutingStrategy::Both => "hybrid",
3156 }
3157 );
3158
3159 let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
3161
3162 let default_workspace =
3164 mockforge_core::Workspace::new(mt_config.default_workspace.clone());
3165 if let Err(e) =
3166 registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
3167 {
3168 warn!("Failed to register default workspace: {}", e);
3169 } else {
3170 info!("Registered default workspace: '{}'", mt_config.default_workspace);
3171 }
3172
3173 let registry = Arc::new(registry);
3175
3176 let _workspace_router = WorkspaceRouter::new(registry);
3178 info!("Workspace routing middleware initialized for HTTP server");
3179 }
3180 }
3181
3182 let mut final_cors_config = cors_config;
3184 let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
3185 let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
3187 let mut rate_limit_config = middleware::RateLimitConfig {
3188 requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
3189 .ok()
3190 .and_then(|v| v.parse().ok())
3191 .unwrap_or(1000),
3192 burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
3193 .ok()
3194 .and_then(|v| v.parse().ok())
3195 .unwrap_or(2000),
3196 per_ip: true,
3197 per_endpoint: false,
3198 };
3199
3200 if let Some(deploy_config) = &deceptive_deploy_config {
3201 if deploy_config.enabled {
3202 info!("Deceptive deploy mode enabled - applying production-like configuration");
3203
3204 if let Some(prod_cors) = &deploy_config.cors {
3206 final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
3207 enabled: true,
3208 allowed_origins: prod_cors.allowed_origins.clone(),
3209 allowed_methods: prod_cors.allowed_methods.clone(),
3210 allowed_headers: prod_cors.allowed_headers.clone(),
3211 allow_credentials: prod_cors.allow_credentials,
3212 });
3213 info!("Applied production-like CORS configuration");
3214 }
3215
3216 if let Some(prod_rate_limit) = &deploy_config.rate_limit {
3218 rate_limit_config = middleware::RateLimitConfig {
3219 requests_per_minute: prod_rate_limit.requests_per_minute,
3220 burst: prod_rate_limit.burst,
3221 per_ip: prod_rate_limit.per_ip,
3222 per_endpoint: false,
3223 };
3224 info!(
3225 "Applied production-like rate limiting: {} req/min, burst: {}",
3226 prod_rate_limit.requests_per_minute, prod_rate_limit.burst
3227 );
3228 }
3229
3230 if !deploy_config.headers.is_empty() {
3232 let headers_map: HashMap<String, String> = deploy_config.headers.clone();
3233 production_headers = Some(std::sync::Arc::new(headers_map));
3234 info!("Configured {} production headers", deploy_config.headers.len());
3235 }
3236
3237 if let Some(prod_oauth) = &deploy_config.oauth {
3239 let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
3240 deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
3241 oauth2: Some(oauth2_config),
3242 ..Default::default()
3243 });
3244 info!("Applied production-like OAuth configuration for deceptive deploy");
3245 }
3246 }
3247 }
3248
3249 let rate_limit_disabled = middleware::is_rate_limit_disabled();
3251 let rate_limiter =
3252 std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
3253
3254 let mut state = HttpServerState::new();
3255 if rate_limit_disabled {
3256 info!(
3257 "HTTP rate limiting disabled (MOCKFORGE_RATE_LIMIT_ENABLED=false or --no-rate-limit)"
3258 );
3259 } else {
3260 state = state.with_rate_limiter(rate_limiter.clone());
3261 }
3262
3263 if let Some(headers) = production_headers.clone() {
3265 state = state.with_production_headers(headers);
3266 }
3267
3268 app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));
3270
3271 if state.production_headers.is_some() {
3273 app =
3274 app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
3275 }
3276
3277 if middleware::is_keepalive_hint_enabled() {
3282 info!(
3283 "MOCKFORGE_HTTP_KEEPALIVE_HINT enabled — emitting Connection: keep-alive + Keep-Alive headers on all responses (Issue #79 workaround)"
3284 );
3285 app = app.layer(axum::middleware::from_fn(middleware::keepalive_hint_middleware));
3286 }
3287
3288 if middleware::is_conn_log_enabled() {
3293 info!(
3294 "MOCKFORGE_HTTP_LOG_CONN enabled — logging HTTP version + Connection headers per request (Issue #79 diagnostic)"
3295 );
3296 app = app.layer(axum::middleware::from_fn(middleware::conn_diag_middleware));
3297 }
3298
3299 if let Some(auth_config) = deceptive_deploy_auth_config {
3301 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
3302 use std::collections::HashMap;
3303 use std::sync::Arc;
3304 use tokio::sync::RwLock;
3305
3306 let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
3308 match create_oauth2_client(oauth2_config) {
3309 Ok(client) => Some(client),
3310 Err(e) => {
3311 warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
3312 None
3313 }
3314 }
3315 } else {
3316 None
3317 };
3318
3319 let auth_state = AuthState {
3321 config: auth_config,
3322 spec: None, oauth2_client,
3324 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
3325 };
3326
3327 app = app.layer(from_fn_with_state(auth_state, auth_middleware));
3329 info!("Applied OAuth authentication middleware from deceptive deploy configuration");
3330 }
3331
3332 #[cfg(feature = "runtime-daemon")]
3334 {
3335 use mockforge_runtime_daemon::{AutoGenerator, NotFoundDetector, RuntimeDaemonConfig};
3336 use std::sync::Arc;
3337
3338 let daemon_config = RuntimeDaemonConfig::from_env();
3340
3341 if daemon_config.enabled {
3342 info!("Runtime daemon enabled - auto-creating mocks from 404s");
3343
3344 let management_api_url =
3346 std::env::var("MOCKFORGE_MANAGEMENT_API_URL").unwrap_or_else(|_| {
3347 let port =
3348 std::env::var("MOCKFORGE_HTTP_PORT").unwrap_or_else(|_| "3000".to_string());
3349 format!("http://localhost:{}", port)
3350 });
3351
3352 let generator = Arc::new(AutoGenerator::new(daemon_config.clone(), management_api_url));
3354
3355 let detector = NotFoundDetector::new(daemon_config.clone());
3357 detector.set_generator(generator).await;
3358
3359 let detector_clone = detector.clone();
3361 app = app.layer(axum::middleware::from_fn(
3362 move |req: axum::extract::Request, next: axum::middleware::Next| {
3363 let detector = detector_clone.clone();
3364 async move { detector.detect_and_auto_create(req, next).await }
3365 },
3366 ));
3367
3368 debug!("Runtime daemon 404 detection middleware added");
3369 }
3370 }
3371
3372 {
3374 let routes_state = HttpServerState::with_routes(captured_routes);
3375 let routes_router = Router::new()
3376 .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
3377 .with_state(routes_state);
3378 app = app.merge(routes_router);
3379 }
3380
3381 app = app.route("/__mockforge/docs", axum::routing::get(get_docs_handler));
3383
3384 app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));
3389
3390 app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
3393
3394 app = apply_cors_middleware(app, final_cors_config);
3396
3397 app
3398}
3399
3400#[test]
3404fn test_route_info_clone() {
3405 let route = RouteInfo {
3406 method: "POST".to_string(),
3407 path: "/users".to_string(),
3408 operation_id: Some("createUser".to_string()),
3409 summary: None,
3410 description: None,
3411 parameters: vec![],
3412 };
3413
3414 let cloned = route.clone();
3415 assert_eq!(route.method, cloned.method);
3416 assert_eq!(route.path, cloned.path);
3417 assert_eq!(route.operation_id, cloned.operation_id);
3418}
3419
3420#[test]
3421fn test_http_server_state_new() {
3422 let state = HttpServerState::new();
3423 assert_eq!(state.routes.len(), 0);
3424}
3425
3426#[test]
3427fn test_http_server_state_with_routes() {
3428 let routes = vec![
3429 RouteInfo {
3430 method: "GET".to_string(),
3431 path: "/users".to_string(),
3432 operation_id: Some("getUsers".to_string()),
3433 summary: None,
3434 description: None,
3435 parameters: vec![],
3436 },
3437 RouteInfo {
3438 method: "POST".to_string(),
3439 path: "/users".to_string(),
3440 operation_id: Some("createUser".to_string()),
3441 summary: None,
3442 description: None,
3443 parameters: vec![],
3444 },
3445 ];
3446
3447 let state = HttpServerState::with_routes(routes.clone());
3448 assert_eq!(state.routes.len(), 2);
3449 assert_eq!(state.routes[0].method, "GET");
3450 assert_eq!(state.routes[1].method, "POST");
3451}
3452
3453#[test]
3454fn test_http_server_state_clone() {
3455 let routes = vec![RouteInfo {
3456 method: "GET".to_string(),
3457 path: "/test".to_string(),
3458 operation_id: None,
3459 summary: None,
3460 description: None,
3461 parameters: vec![],
3462 }];
3463
3464 let state = HttpServerState::with_routes(routes);
3465 let cloned = state.clone();
3466
3467 assert_eq!(state.routes.len(), cloned.routes.len());
3468 assert_eq!(state.routes[0].method, cloned.routes[0].method);
3469}
3470
3471#[tokio::test]
3472async fn test_build_router_without_openapi() {
3473 let _router = build_router(None, None, None).await;
3474 }
3476
3477#[tokio::test]
3478async fn test_build_router_with_nonexistent_spec() {
3479 let _router = build_router(Some("/nonexistent/spec.yaml".to_string()), None, None).await;
3480 }
3482
3483#[tokio::test]
3484async fn test_build_router_with_auth_and_latency() {
3485 let _router = build_router_with_auth_and_latency(None, None, None, None).await;
3486 }
3488
3489#[tokio::test]
3490async fn test_build_router_with_latency() {
3491 let _router = build_router_with_latency(None, None, None).await;
3492 }
3494
3495#[tokio::test]
3496async fn test_build_router_with_auth() {
3497 let _router = build_router_with_auth(None, None, None).await;
3498 }
3500
3501#[tokio::test]
3502async fn test_build_router_with_chains() {
3503 let _router = build_router_with_chains(None, None, None).await;
3504 }
3506
3507#[test]
3508fn test_route_info_with_all_fields() {
3509 let route = RouteInfo {
3510 method: "PUT".to_string(),
3511 path: "/users/{id}".to_string(),
3512 operation_id: Some("updateUser".to_string()),
3513 summary: Some("Update user".to_string()),
3514 description: Some("Updates an existing user".to_string()),
3515 parameters: vec!["id".to_string(), "body".to_string()],
3516 };
3517
3518 assert!(route.operation_id.is_some());
3519 assert!(route.summary.is_some());
3520 assert!(route.description.is_some());
3521 assert_eq!(route.parameters.len(), 2);
3522}
3523
3524#[test]
3525fn test_route_info_with_minimal_fields() {
3526 let route = RouteInfo {
3527 method: "DELETE".to_string(),
3528 path: "/users/{id}".to_string(),
3529 operation_id: None,
3530 summary: None,
3531 description: None,
3532 parameters: vec![],
3533 };
3534
3535 assert!(route.operation_id.is_none());
3536 assert!(route.summary.is_none());
3537 assert!(route.description.is_none());
3538 assert_eq!(route.parameters.len(), 0);
3539}
3540
3541#[test]
3542fn test_http_server_state_empty_routes() {
3543 let state = HttpServerState::with_routes(vec![]);
3544 assert_eq!(state.routes.len(), 0);
3545}
3546
3547#[test]
3548fn test_http_server_state_multiple_routes() {
3549 let routes = vec![
3550 RouteInfo {
3551 method: "GET".to_string(),
3552 path: "/users".to_string(),
3553 operation_id: Some("listUsers".to_string()),
3554 summary: Some("List all users".to_string()),
3555 description: None,
3556 parameters: vec![],
3557 },
3558 RouteInfo {
3559 method: "GET".to_string(),
3560 path: "/users/{id}".to_string(),
3561 operation_id: Some("getUser".to_string()),
3562 summary: Some("Get a user".to_string()),
3563 description: None,
3564 parameters: vec!["id".to_string()],
3565 },
3566 RouteInfo {
3567 method: "POST".to_string(),
3568 path: "/users".to_string(),
3569 operation_id: Some("createUser".to_string()),
3570 summary: Some("Create a user".to_string()),
3571 description: None,
3572 parameters: vec!["body".to_string()],
3573 },
3574 ];
3575
3576 let state = HttpServerState::with_routes(routes);
3577 assert_eq!(state.routes.len(), 3);
3578
3579 let methods: Vec<&str> = state.routes.iter().map(|r| r.method.as_str()).collect();
3581 assert!(methods.contains(&"GET"));
3582 assert!(methods.contains(&"POST"));
3583}
3584
3585#[test]
3586fn test_http_server_state_with_rate_limiter() {
3587 use std::sync::Arc;
3588
3589 let config = middleware::RateLimitConfig::default();
3590 let rate_limiter = Arc::new(middleware::GlobalRateLimiter::new(config));
3591
3592 let state = HttpServerState::new().with_rate_limiter(rate_limiter);
3593
3594 assert!(state.rate_limiter.is_some());
3595 assert_eq!(state.routes.len(), 0);
3596}
3597
3598#[tokio::test]
3599async fn test_build_router_includes_rate_limiter() {
3600 let _router = build_router(None, None, None).await;
3601 }