1pub mod ai_handler;
166pub mod auth;
167pub mod chain_handlers;
168pub mod consistency;
170pub mod contract_diff_middleware;
172pub mod coverage;
173pub mod database;
174pub mod file_generator;
176pub mod file_server;
178pub mod health;
180pub mod http_tracing_middleware;
181pub mod latency_profiles;
183pub mod management;
185pub mod management_ws;
187pub mod metrics_middleware;
188pub mod middleware;
189pub mod op_middleware;
190pub mod proxy_server;
192pub mod quick_mock;
194pub mod rag_ai_generator;
196pub mod replay_listing;
198pub mod request_logging;
199pub mod spec_import;
201pub mod sse;
203pub mod state_machine_api;
205pub mod tls;
207pub mod token_response;
209pub mod ui_builder;
211pub mod verification;
213
214pub mod handlers;
216
217pub use ai_handler::{process_response_with_ai, AiResponseConfig, AiResponseHandler};
219pub use health::{HealthManager, ServiceStatus};
221
222pub use management::{
224 management_router, management_router_with_ui_builder, ManagementState, MockConfig,
225 ServerConfig, ServerStats,
226};
227
228pub use ui_builder::{create_ui_builder_router, EndpointConfig, UIBuilderState};
230
231pub use management_ws::{ws_management_router, MockEvent, WsManagementState};
233
234pub use verification::verification_router;
236
237pub use metrics_middleware::collect_http_metrics;
239
240pub use http_tracing_middleware::http_tracing_middleware;
242
243pub use coverage::{calculate_coverage, CoverageReport, MethodCoverage, RouteCoverage};
245
246async fn load_persona_from_config() -> Option<Arc<Persona>> {
249 use mockforge_core::config::load_config;
250
251 let config_paths = [
253 "config.yaml",
254 "mockforge.yaml",
255 "tools/mockforge/config.yaml",
256 "../tools/mockforge/config.yaml",
257 ];
258
259 for path in &config_paths {
260 if let Ok(config) = load_config(path).await {
261 if let Some(persona) = config.mockai.intelligent_behavior.personas.get_active_persona()
264 {
265 tracing::info!(
266 "Loaded active persona '{}' from config file: {}",
267 persona.name,
268 path
269 );
270 return Some(Arc::new(persona.clone()));
271 } else {
272 tracing::debug!(
273 "No active persona found in config file: {} (personas count: {})",
274 path,
275 config.mockai.intelligent_behavior.personas.personas.len()
276 );
277 }
278 } else {
279 tracing::debug!("Could not load config from: {}", path);
280 }
281 }
282
283 tracing::debug!("No persona found in config files, persona-based generation will be disabled");
284 None
285}
286
287use axum::extract::State;
288use axum::middleware::from_fn_with_state;
289use axum::response::Json;
290use axum::Router;
291use mockforge_core::failure_injection::{FailureConfig, FailureInjector};
292use mockforge_core::intelligent_behavior::config::Persona;
293use mockforge_core::latency::LatencyInjector;
294use mockforge_core::openapi::OpenApiSpec;
295use mockforge_core::openapi_routes::OpenApiRouteRegistry;
296use mockforge_core::openapi_routes::ValidationOptions;
297use std::sync::Arc;
298use tower_http::cors::{Any, CorsLayer};
299
300use mockforge_core::LatencyProfile;
301#[cfg(feature = "data-faker")]
302use mockforge_data::provider::register_core_faker_provider;
303use std::collections::HashMap;
304use std::ffi::OsStr;
305use std::path::Path;
306use tokio::fs;
307use tokio::sync::RwLock;
308use tracing::*;
309
310#[derive(Clone)]
312pub struct RouteInfo {
313 pub method: String,
315 pub path: String,
317 pub operation_id: Option<String>,
319 pub summary: Option<String>,
321 pub description: Option<String>,
323 pub parameters: Vec<String>,
325}
326
327#[derive(Clone)]
329pub struct HttpServerState {
330 pub routes: Vec<RouteInfo>,
332 pub rate_limiter: Option<Arc<middleware::rate_limit::GlobalRateLimiter>>,
334 pub production_headers: Option<Arc<HashMap<String, String>>>,
336}
337
338impl Default for HttpServerState {
339 fn default() -> Self {
340 Self::new()
341 }
342}
343
344impl HttpServerState {
345 pub fn new() -> Self {
347 Self {
348 routes: Vec::new(),
349 rate_limiter: None,
350 production_headers: None,
351 }
352 }
353
354 pub fn with_routes(routes: Vec<RouteInfo>) -> Self {
356 Self {
357 routes,
358 rate_limiter: None,
359 production_headers: None,
360 }
361 }
362
363 pub fn with_rate_limiter(
365 mut self,
366 rate_limiter: Arc<middleware::rate_limit::GlobalRateLimiter>,
367 ) -> Self {
368 self.rate_limiter = Some(rate_limiter);
369 self
370 }
371
372 pub fn with_production_headers(mut self, headers: Arc<HashMap<String, String>>) -> Self {
374 self.production_headers = Some(headers);
375 self
376 }
377}
378
379async fn get_routes_handler(State(state): State<HttpServerState>) -> Json<serde_json::Value> {
381 let route_info: Vec<serde_json::Value> = state
382 .routes
383 .iter()
384 .map(|route| {
385 serde_json::json!({
386 "method": route.method,
387 "path": route.path,
388 "operation_id": route.operation_id,
389 "summary": route.summary,
390 "description": route.description,
391 "parameters": route.parameters
392 })
393 })
394 .collect();
395
396 Json(serde_json::json!({
397 "routes": route_info,
398 "total": state.routes.len()
399 }))
400}
401
402pub async fn build_router(
404 spec_path: Option<String>,
405 options: Option<ValidationOptions>,
406 failure_config: Option<FailureConfig>,
407) -> Router {
408 build_router_with_multi_tenant(
409 spec_path,
410 options,
411 failure_config,
412 None,
413 None,
414 None,
415 None,
416 None,
417 None,
418 None,
419 )
420 .await
421}
422
423fn apply_cors_middleware(
425 app: Router,
426 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
427) -> Router {
428 use http::Method;
429 use tower_http::cors::AllowOrigin;
430
431 if let Some(config) = cors_config {
432 if !config.enabled {
433 return app;
434 }
435
436 let mut cors_layer = CorsLayer::new();
437 let mut is_wildcard_origin = false;
438
439 if config.allowed_origins.contains(&"*".to_string()) {
441 cors_layer = cors_layer.allow_origin(Any);
442 is_wildcard_origin = true;
443 } else if !config.allowed_origins.is_empty() {
444 let origins: Vec<_> = config
446 .allowed_origins
447 .iter()
448 .filter_map(|origin| {
449 origin.parse::<http::HeaderValue>().ok().map(AllowOrigin::exact)
450 })
451 .collect();
452
453 if origins.is_empty() {
454 warn!("No valid CORS origins configured, using permissive CORS");
456 cors_layer = cors_layer.allow_origin(Any);
457 is_wildcard_origin = true;
458 } else {
459 if origins.len() == 1 {
462 cors_layer = cors_layer.allow_origin(origins[0].clone());
463 is_wildcard_origin = false;
464 } else {
465 warn!(
467 "Multiple CORS origins configured, using permissive CORS. \
468 Consider using '*' for all origins."
469 );
470 cors_layer = cors_layer.allow_origin(Any);
471 is_wildcard_origin = true;
472 }
473 }
474 } else {
475 cors_layer = cors_layer.allow_origin(Any);
477 is_wildcard_origin = true;
478 }
479
480 if !config.allowed_methods.is_empty() {
482 let methods: Vec<Method> =
483 config.allowed_methods.iter().filter_map(|m| m.parse().ok()).collect();
484 if !methods.is_empty() {
485 cors_layer = cors_layer.allow_methods(methods);
486 }
487 } else {
488 cors_layer = cors_layer.allow_methods([
490 Method::GET,
491 Method::POST,
492 Method::PUT,
493 Method::DELETE,
494 Method::PATCH,
495 Method::OPTIONS,
496 ]);
497 }
498
499 if !config.allowed_headers.is_empty() {
501 let headers: Vec<_> = config
502 .allowed_headers
503 .iter()
504 .filter_map(|h| h.parse::<http::HeaderName>().ok())
505 .collect();
506 if !headers.is_empty() {
507 cors_layer = cors_layer.allow_headers(headers);
508 }
509 } else {
510 cors_layer =
512 cors_layer.allow_headers([http::header::CONTENT_TYPE, http::header::AUTHORIZATION]);
513 }
514
515 let should_allow_credentials = if is_wildcard_origin {
519 false
521 } else {
522 config.allow_credentials
524 };
525
526 cors_layer = cors_layer.allow_credentials(should_allow_credentials);
527
528 info!(
529 "CORS middleware enabled with configured settings (credentials: {})",
530 should_allow_credentials
531 );
532 app.layer(cors_layer)
533 } else {
534 debug!("No CORS config provided, using permissive CORS for development");
538 app.layer(CorsLayer::permissive().allow_credentials(false))
541 }
542}
543
544#[allow(clippy::too_many_arguments)]
546pub async fn build_router_with_multi_tenant(
547 spec_path: Option<String>,
548 options: Option<ValidationOptions>,
549 failure_config: Option<FailureConfig>,
550 multi_tenant_config: Option<mockforge_core::MultiTenantConfig>,
551 _route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
552 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
553 ai_generator: Option<Arc<dyn mockforge_core::openapi::response::AiGenerator + Send + Sync>>,
554 smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
555 mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
556 deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
557) -> Router {
558 use std::time::Instant;
559
560 let startup_start = Instant::now();
561
562 let mut app = Router::new();
564
565 let mut rate_limit_config = middleware::RateLimitConfig {
568 requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
569 .ok()
570 .and_then(|v| v.parse().ok())
571 .unwrap_or(1000),
572 burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
573 .ok()
574 .and_then(|v| v.parse().ok())
575 .unwrap_or(2000),
576 per_ip: true,
577 per_endpoint: false,
578 };
579
580 let mut final_cors_config = cors_config;
582 let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
583 let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
585
586 if let Some(deploy_config) = &deceptive_deploy_config {
587 if deploy_config.enabled {
588 info!("Deceptive deploy mode enabled - applying production-like configuration");
589
590 if let Some(prod_cors) = &deploy_config.cors {
592 final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
593 enabled: true,
594 allowed_origins: prod_cors.allowed_origins.clone(),
595 allowed_methods: prod_cors.allowed_methods.clone(),
596 allowed_headers: prod_cors.allowed_headers.clone(),
597 allow_credentials: prod_cors.allow_credentials,
598 });
599 info!("Applied production-like CORS configuration");
600 }
601
602 if let Some(prod_rate_limit) = &deploy_config.rate_limit {
604 rate_limit_config = middleware::RateLimitConfig {
605 requests_per_minute: prod_rate_limit.requests_per_minute,
606 burst: prod_rate_limit.burst,
607 per_ip: prod_rate_limit.per_ip,
608 per_endpoint: false,
609 };
610 info!(
611 "Applied production-like rate limiting: {} req/min, burst: {}",
612 prod_rate_limit.requests_per_minute, prod_rate_limit.burst
613 );
614 }
615
616 if !deploy_config.headers.is_empty() {
618 let headers_map: HashMap<String, String> = deploy_config.headers.clone();
619 production_headers = Some(std::sync::Arc::new(headers_map));
620 info!("Configured {} production headers", deploy_config.headers.len());
621 }
622
623 if let Some(prod_oauth) = &deploy_config.oauth {
625 let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
626 deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
627 oauth2: Some(oauth2_config),
628 ..Default::default()
629 });
630 info!("Applied production-like OAuth configuration for deceptive deploy");
631 }
632 }
633 }
634
635 let rate_limiter =
636 std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
637
638 let mut state = HttpServerState::new().with_rate_limiter(rate_limiter.clone());
639
640 if let Some(headers) = production_headers.clone() {
642 state = state.with_production_headers(headers);
643 }
644
645 let spec_path_for_mgmt = spec_path.clone();
647
648 if let Some(spec_path) = spec_path {
650 tracing::debug!("Processing OpenAPI spec path: {}", spec_path);
651
652 let spec_load_start = Instant::now();
654 match OpenApiSpec::from_file(&spec_path).await {
655 Ok(openapi) => {
656 let spec_load_duration = spec_load_start.elapsed();
657 info!(
658 "Successfully loaded OpenAPI spec from {} (took {:?})",
659 spec_path, spec_load_duration
660 );
661
662 tracing::debug!("Creating OpenAPI route registry...");
664 let registry_start = Instant::now();
665
666 let persona = load_persona_from_config().await;
668
669 let registry = if let Some(opts) = options {
670 tracing::debug!("Using custom validation options");
671 if let Some(ref persona) = persona {
672 tracing::info!("Using persona '{}' for route generation", persona.name);
673 }
674 OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
675 } else {
676 tracing::debug!("Using environment-based options");
677 if let Some(ref persona) = persona {
678 tracing::info!("Using persona '{}' for route generation", persona.name);
679 }
680 OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
681 };
682 let registry_duration = registry_start.elapsed();
683 info!(
684 "Created OpenAPI route registry with {} routes (took {:?})",
685 registry.routes().len(),
686 registry_duration
687 );
688
689 let extract_start = Instant::now();
691 let route_info: Vec<RouteInfo> = registry
692 .routes()
693 .iter()
694 .map(|route| RouteInfo {
695 method: route.method.clone(),
696 path: route.path.clone(),
697 operation_id: route.operation.operation_id.clone(),
698 summary: route.operation.summary.clone(),
699 description: route.operation.description.clone(),
700 parameters: route.parameters.clone(),
701 })
702 .collect();
703 state.routes = route_info;
704 let extract_duration = extract_start.elapsed();
705 debug!("Extracted route information (took {:?})", extract_duration);
706
707 let overrides = if std::env::var("MOCKFORGE_HTTP_OVERRIDES_GLOB").is_ok() {
709 tracing::debug!("Loading overrides from environment variable");
710 let overrides_start = Instant::now();
711 match mockforge_core::Overrides::load_from_globs(&[]).await {
712 Ok(overrides) => {
713 let overrides_duration = overrides_start.elapsed();
714 info!(
715 "Loaded {} override rules (took {:?})",
716 overrides.rules().len(),
717 overrides_duration
718 );
719 Some(overrides)
720 }
721 Err(e) => {
722 tracing::warn!("Failed to load overrides: {}", e);
723 None
724 }
725 }
726 } else {
727 None
728 };
729
730 let router_build_start = Instant::now();
732 let overrides_enabled = overrides.is_some();
733 let openapi_router = if let Some(mockai_instance) = &mockai {
734 tracing::debug!("Building router with MockAI support");
735 registry.build_router_with_mockai(Some(mockai_instance.clone()))
736 } else if let Some(ai_generator) = &ai_generator {
737 tracing::debug!("Building router with AI generator support");
738 registry.build_router_with_ai(Some(ai_generator.clone()))
739 } else if let Some(failure_config) = &failure_config {
740 tracing::debug!("Building router with failure injection and overrides");
741 let failure_injector = FailureInjector::new(Some(failure_config.clone()), true);
742 registry.build_router_with_injectors_and_overrides(
743 LatencyInjector::default(),
744 Some(failure_injector),
745 overrides,
746 overrides_enabled,
747 )
748 } else {
749 tracing::debug!("Building router with overrides");
750 registry.build_router_with_injectors_and_overrides(
751 LatencyInjector::default(),
752 None,
753 overrides,
754 overrides_enabled,
755 )
756 };
757 let router_build_duration = router_build_start.elapsed();
758 debug!("Built OpenAPI router (took {:?})", router_build_duration);
759
760 tracing::debug!("Merging OpenAPI router with main router");
761 app = app.merge(openapi_router);
762 tracing::debug!("Router built successfully");
763 }
764 Err(e) => {
765 warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
766 }
767 }
768 }
769
770 app = app.route(
772 "/health",
773 axum::routing::get(|| async {
774 use mockforge_core::server_utils::health::HealthStatus;
775 {
776 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
778 Ok(value) => Json(value),
779 Err(e) => {
780 tracing::error!("Failed to serialize health status: {}", e);
782 Json(serde_json::json!({
783 "status": "healthy",
784 "service": "mockforge-http",
785 "uptime_seconds": 0
786 }))
787 }
788 }
789 }
790 }),
791 )
792 .merge(sse::sse_router())
794 .merge(file_server::file_serving_router());
796
797 let state_for_routes = state.clone();
799
800 let routes_router = Router::new()
802 .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
803 .route("/__mockforge/coverage", axum::routing::get(coverage::get_coverage_handler))
804 .with_state(state_for_routes);
805
806 app = app.merge(routes_router);
808
809 let coverage_html_path = std::env::var("MOCKFORGE_COVERAGE_UI_PATH")
812 .unwrap_or_else(|_| "crates/mockforge-http/static/coverage.html".to_string());
813
814 if Path::new(&coverage_html_path).exists() {
816 app = app.nest_service(
817 "/__mockforge/coverage.html",
818 tower_http::services::ServeFile::new(&coverage_html_path),
819 );
820 debug!("Serving coverage UI from: {}", coverage_html_path);
821 } else {
822 debug!(
823 "Coverage UI file not found at: {}. Skipping static file serving.",
824 coverage_html_path
825 );
826 }
827
828 let management_state = ManagementState::new(None, spec_path_for_mgmt, 3000); use std::sync::Arc;
833 let ws_state = WsManagementState::new();
834 let ws_broadcast = Arc::new(ws_state.tx.clone());
835 let management_state = management_state.with_ws_broadcast(ws_broadcast);
836
837 #[cfg(feature = "smtp")]
841 let management_state = {
842 if let Some(smtp_reg) = smtp_registry {
843 match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
844 Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
845 Err(e) => {
846 error!(
847 "Invalid SMTP registry type passed to HTTP management state: {:?}",
848 e.type_id()
849 );
850 management_state
851 }
852 }
853 } else {
854 management_state
855 }
856 };
857 #[cfg(not(feature = "smtp"))]
858 let management_state = management_state;
859 #[cfg(not(feature = "smtp"))]
860 let _ = smtp_registry;
861 app = app.nest("/__mockforge/api", management_router(management_state));
862
863 app = app.merge(verification_router());
865
866 use crate::auth::oidc::oidc_router;
868 app = app.merge(oidc_router());
869
870 {
872 use mockforge_core::security::get_global_access_review_service;
873 if let Some(service) = get_global_access_review_service().await {
874 use crate::handlers::access_review::{access_review_router, AccessReviewState};
875 let review_state = AccessReviewState { service };
876 app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
877 debug!("Access review API mounted at /api/v1/security/access-reviews");
878 }
879 }
880
881 {
883 use mockforge_core::security::get_global_privileged_access_manager;
884 if let Some(manager) = get_global_privileged_access_manager().await {
885 use crate::handlers::privileged_access::{
886 privileged_access_router, PrivilegedAccessState,
887 };
888 let privileged_state = PrivilegedAccessState { manager };
889 app = app.nest(
890 "/api/v1/security/privileged-access",
891 privileged_access_router(privileged_state),
892 );
893 debug!("Privileged access API mounted at /api/v1/security/privileged-access");
894 }
895 }
896
897 {
899 use mockforge_core::security::get_global_change_management_engine;
900 if let Some(engine) = get_global_change_management_engine().await {
901 use crate::handlers::change_management::{
902 change_management_router, ChangeManagementState,
903 };
904 let change_state = ChangeManagementState { engine };
905 app = app.nest("/api/v1/change-management", change_management_router(change_state));
906 debug!("Change management API mounted at /api/v1/change-management");
907 }
908 }
909
910 {
912 use mockforge_core::security::get_global_risk_assessment_engine;
913 if let Some(engine) = get_global_risk_assessment_engine().await {
914 use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
915 let risk_state = RiskAssessmentState { engine };
916 app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
917 debug!("Risk assessment API mounted at /api/v1/security/risks");
918 }
919 }
920
921 {
923 use crate::auth::token_lifecycle::TokenLifecycleManager;
924 use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
925 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
926 let lifecycle_state = TokenLifecycleState {
927 manager: lifecycle_manager,
928 };
929 app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
930 debug!("Token lifecycle API mounted at /api/v1/auth");
931 }
932
933 {
935 use crate::auth::oidc::load_oidc_state;
936 use crate::auth::token_lifecycle::TokenLifecycleManager;
937 use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
938 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
940 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
941 let oauth2_state = OAuth2ServerState {
942 oidc_state,
943 lifecycle_manager,
944 auth_codes: Arc::new(RwLock::new(HashMap::new())),
945 };
946 app = app.merge(oauth2_server_router(oauth2_state));
947 debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
948 }
949
950 {
952 use crate::auth::oidc::load_oidc_state;
953 use crate::auth::risk_engine::RiskEngine;
954 use crate::auth::token_lifecycle::TokenLifecycleManager;
955 use crate::handlers::consent::{consent_router, ConsentState};
956 use crate::handlers::oauth2_server::OAuth2ServerState;
957 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
959 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
960 let oauth2_state = OAuth2ServerState {
961 oidc_state: oidc_state.clone(),
962 lifecycle_manager: lifecycle_manager.clone(),
963 auth_codes: Arc::new(RwLock::new(HashMap::new())),
964 };
965 let risk_engine = Arc::new(RiskEngine::default());
966 let consent_state = ConsentState {
967 oauth2_state,
968 risk_engine,
969 };
970 app = app.merge(consent_router(consent_state));
971 debug!("Consent screen endpoints mounted at /consent");
972 }
973
974 {
976 use crate::auth::risk_engine::RiskEngine;
977 use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
978 let risk_engine = Arc::new(RiskEngine::default());
979 let risk_state = RiskSimulationState { risk_engine };
980 app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
981 debug!("Risk simulation API mounted at /api/v1/auth/risk");
982 }
983
984 app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
986
987 app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));
989
990 app = app.layer(axum::middleware::from_fn(middleware::security_middleware));
992
993 app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
996
997 app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));
999
1000 if state.production_headers.is_some() {
1002 app =
1003 app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
1004 }
1005
1006 if let Some(auth_config) = deceptive_deploy_auth_config {
1008 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1009 use std::collections::HashMap;
1010 use std::sync::Arc;
1011 use tokio::sync::RwLock;
1012
1013 let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
1015 match create_oauth2_client(oauth2_config) {
1016 Ok(client) => Some(client),
1017 Err(e) => {
1018 warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
1019 None
1020 }
1021 }
1022 } else {
1023 None
1024 };
1025
1026 let auth_state = AuthState {
1028 config: auth_config,
1029 spec: None, oauth2_client,
1031 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1032 };
1033
1034 app = app.layer(from_fn_with_state(auth_state, auth_middleware));
1036 info!("Applied OAuth authentication middleware from deceptive deploy configuration");
1037 }
1038
1039 app = apply_cors_middleware(app, final_cors_config);
1041
1042 if let Some(mt_config) = multi_tenant_config {
1044 if mt_config.enabled {
1045 use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
1046 use std::sync::Arc;
1047
1048 info!(
1049 "Multi-tenant mode enabled with {} routing strategy",
1050 match mt_config.routing_strategy {
1051 mockforge_core::RoutingStrategy::Path => "path-based",
1052 mockforge_core::RoutingStrategy::Port => "port-based",
1053 mockforge_core::RoutingStrategy::Both => "hybrid",
1054 }
1055 );
1056
1057 let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
1059
1060 let default_workspace =
1062 mockforge_core::Workspace::new(mt_config.default_workspace.clone());
1063 if let Err(e) =
1064 registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
1065 {
1066 warn!("Failed to register default workspace: {}", e);
1067 } else {
1068 info!("Registered default workspace: '{}'", mt_config.default_workspace);
1069 }
1070
1071 if mt_config.auto_discover {
1073 if let Some(config_dir) = &mt_config.config_directory {
1074 let config_path = Path::new(config_dir);
1075 if config_path.exists() && config_path.is_dir() {
1076 match fs::read_dir(config_path).await {
1077 Ok(mut entries) => {
1078 while let Ok(Some(entry)) = entries.next_entry().await {
1079 let path = entry.path();
1080 if path.extension() == Some(OsStr::new("yaml")) {
1081 match fs::read_to_string(&path).await {
1082 Ok(content) => {
1083 match serde_yaml::from_str::<
1084 mockforge_core::Workspace,
1085 >(
1086 &content
1087 ) {
1088 Ok(workspace) => {
1089 if let Err(e) = registry.register_workspace(
1090 workspace.id.clone(),
1091 workspace,
1092 ) {
1093 warn!("Failed to register auto-discovered workspace from {:?}: {}", path, e);
1094 } else {
1095 info!("Auto-registered workspace from {:?}", path);
1096 }
1097 }
1098 Err(e) => {
1099 warn!("Failed to parse workspace from {:?}: {}", path, e);
1100 }
1101 }
1102 }
1103 Err(e) => {
1104 warn!(
1105 "Failed to read workspace file {:?}: {}",
1106 path, e
1107 );
1108 }
1109 }
1110 }
1111 }
1112 }
1113 Err(e) => {
1114 warn!("Failed to read config directory {:?}: {}", config_path, e);
1115 }
1116 }
1117 } else {
1118 warn!(
1119 "Config directory {:?} does not exist or is not a directory",
1120 config_path
1121 );
1122 }
1123 }
1124 }
1125
1126 let registry = Arc::new(registry);
1128
1129 let _workspace_router = WorkspaceRouter::new(registry);
1131
1132 info!("Workspace routing middleware initialized for HTTP server");
1135 }
1136 }
1137
1138 let total_startup_duration = startup_start.elapsed();
1139 info!("HTTP router startup completed (total time: {:?})", total_startup_duration);
1140
1141 app
1142}
1143
1144pub async fn build_router_with_auth_and_latency(
1146 _spec_path: Option<String>,
1147 _options: Option<()>,
1148 _auth_config: Option<mockforge_core::config::AuthConfig>,
1149 _latency_injector: Option<LatencyInjector>,
1150) -> Router {
1151 build_router(None, None, None).await
1153}
1154
1155pub async fn build_router_with_latency(
1157 _spec_path: Option<String>,
1158 _options: Option<ValidationOptions>,
1159 _latency_injector: Option<LatencyInjector>,
1160) -> Router {
1161 build_router(None, None, None).await
1163}
1164
1165pub async fn build_router_with_auth(
1167 spec_path: Option<String>,
1168 options: Option<ValidationOptions>,
1169 auth_config: Option<mockforge_core::config::AuthConfig>,
1170) -> Router {
1171 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1172 use std::sync::Arc;
1173
1174 #[cfg(feature = "data-faker")]
1176 {
1177 register_core_faker_provider();
1178 }
1179
1180 let spec = if let Some(spec_path) = &spec_path {
1182 match OpenApiSpec::from_file(&spec_path).await {
1183 Ok(spec) => Some(Arc::new(spec)),
1184 Err(e) => {
1185 warn!("Failed to load OpenAPI spec for auth: {}", e);
1186 None
1187 }
1188 }
1189 } else {
1190 None
1191 };
1192
1193 let oauth2_client = if let Some(auth_config) = &auth_config {
1195 if let Some(oauth2_config) = &auth_config.oauth2 {
1196 match create_oauth2_client(oauth2_config) {
1197 Ok(client) => Some(client),
1198 Err(e) => {
1199 warn!("Failed to create OAuth2 client: {}", e);
1200 None
1201 }
1202 }
1203 } else {
1204 None
1205 }
1206 } else {
1207 None
1208 };
1209
1210 let auth_state = AuthState {
1211 config: auth_config.unwrap_or_default(),
1212 spec,
1213 oauth2_client,
1214 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1215 };
1216
1217 let mut app = Router::new().with_state(auth_state.clone());
1219
1220 if let Some(spec_path) = spec_path {
1222 match OpenApiSpec::from_file(&spec_path).await {
1223 Ok(openapi) => {
1224 info!("Loaded OpenAPI spec from {}", spec_path);
1225 let registry = if let Some(opts) = options {
1226 OpenApiRouteRegistry::new_with_options(openapi, opts)
1227 } else {
1228 OpenApiRouteRegistry::new_with_env(openapi)
1229 };
1230
1231 app = registry.build_router();
1232 }
1233 Err(e) => {
1234 warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
1235 }
1236 }
1237 }
1238
1239 app = app.route(
1241 "/health",
1242 axum::routing::get(|| async {
1243 use mockforge_core::server_utils::health::HealthStatus;
1244 {
1245 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1247 Ok(value) => Json(value),
1248 Err(e) => {
1249 tracing::error!("Failed to serialize health status: {}", e);
1251 Json(serde_json::json!({
1252 "status": "healthy",
1253 "service": "mockforge-http",
1254 "uptime_seconds": 0
1255 }))
1256 }
1257 }
1258 }
1259 }),
1260 )
1261 .merge(sse::sse_router())
1263 .merge(file_server::file_serving_router())
1265 .layer(from_fn_with_state(auth_state.clone(), auth_middleware))
1267 .layer(axum::middleware::from_fn(request_logging::log_http_requests));
1269
1270 app
1271}
1272
1273pub async fn serve_router(
1275 port: u16,
1276 app: Router,
1277) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1278 serve_router_with_tls(port, app, None).await
1279}
1280
1281pub async fn serve_router_with_tls(
1283 port: u16,
1284 app: Router,
1285 tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1286) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1287 use std::net::SocketAddr;
1288
1289 let addr = mockforge_core::wildcard_socket_addr(port);
1290
1291 if let Some(ref tls) = tls_config {
1292 if tls.enabled {
1293 info!("HTTPS listening on {}", addr);
1294 return serve_with_tls(addr, app, tls).await;
1295 }
1296 }
1297
1298 info!("HTTP listening on {}", addr);
1299
1300 let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
1301 format!(
1302 "Failed to bind HTTP server to port {}: {}\n\
1303 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 {}",
1304 port, e, port, port
1305 )
1306 })?;
1307
1308 axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
1309 Ok(())
1310}
1311
1312async fn serve_with_tls(
1317 addr: std::net::SocketAddr,
1318 app: Router,
1319 tls_config: &mockforge_core::config::HttpTlsConfig,
1320) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1321 use axum_server::tls_rustls::RustlsConfig;
1322 use std::net::SocketAddr;
1323
1324 tls::init_crypto_provider();
1326
1327 info!("Loading TLS configuration for HTTPS server");
1328
1329 let server_config = tls::load_tls_server_config(tls_config)?;
1331
1332 let rustls_config = RustlsConfig::from_config(server_config);
1335
1336 info!("Starting HTTPS server on {}", addr);
1337
1338 axum_server::bind_rustls(addr, rustls_config)
1340 .serve(app.into_make_service_with_connect_info::<SocketAddr>())
1341 .await
1342 .map_err(|e| format!("HTTPS server error: {}", e).into())
1343}
1344
1345pub async fn start(
1347 port: u16,
1348 spec_path: Option<String>,
1349 options: Option<ValidationOptions>,
1350) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1351 start_with_latency(port, spec_path, options, None).await
1352}
1353
1354pub async fn start_with_auth_and_latency(
1356 port: u16,
1357 spec_path: Option<String>,
1358 options: Option<ValidationOptions>,
1359 auth_config: Option<mockforge_core::config::AuthConfig>,
1360 latency_profile: Option<LatencyProfile>,
1361) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1362 start_with_auth_and_injectors(port, spec_path, options, auth_config, latency_profile, None)
1363 .await
1364}
1365
1366pub async fn start_with_auth_and_injectors(
1368 port: u16,
1369 spec_path: Option<String>,
1370 options: Option<ValidationOptions>,
1371 auth_config: Option<mockforge_core::config::AuthConfig>,
1372 _latency_profile: Option<LatencyProfile>,
1373 _failure_injector: Option<FailureInjector>,
1374) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1375 let app = build_router_with_auth(spec_path, options, auth_config).await;
1377 serve_router(port, app).await
1378}
1379
1380pub async fn start_with_latency(
1382 port: u16,
1383 spec_path: Option<String>,
1384 options: Option<ValidationOptions>,
1385 latency_profile: Option<LatencyProfile>,
1386) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1387 let latency_injector =
1388 latency_profile.map(|profile| LatencyInjector::new(profile, Default::default()));
1389
1390 let app = build_router_with_latency(spec_path, options, latency_injector).await;
1391 serve_router(port, app).await
1392}
1393
1394pub async fn build_router_with_chains(
1396 spec_path: Option<String>,
1397 options: Option<ValidationOptions>,
1398 circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1399) -> Router {
1400 build_router_with_chains_and_multi_tenant(
1401 spec_path,
1402 options,
1403 circling_config,
1404 None,
1405 None,
1406 None,
1407 None,
1408 None,
1409 None,
1410 None,
1411 false,
1412 None, None, None, None, )
1417 .await
1418}
1419
1420async fn apply_route_chaos(
1428 injector: Option<&dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1429 method: &http::Method,
1430 uri: &http::Uri,
1431) -> Option<axum::response::Response> {
1432 use axum::http::StatusCode;
1433 use axum::response::IntoResponse;
1434
1435 if let Some(injector) = injector {
1436 if let Some(fault_response) = injector.get_fault_response(method, uri) {
1438 let mut response = Json(serde_json::json!({
1440 "error": fault_response.error_message,
1441 "fault_type": fault_response.fault_type,
1442 }))
1443 .into_response();
1444 *response.status_mut() = StatusCode::from_u16(fault_response.status_code)
1445 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1446 return Some(response);
1447 }
1448
1449 if let Err(e) = injector.inject_latency(method, uri).await {
1451 tracing::warn!("Failed to inject latency: {}", e);
1452 }
1453 }
1454
1455 None }
1457
1458#[allow(clippy::too_many_arguments)]
1460pub async fn build_router_with_chains_and_multi_tenant(
1461 spec_path: Option<String>,
1462 options: Option<ValidationOptions>,
1463 _circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1464 multi_tenant_config: Option<mockforge_core::MultiTenantConfig>,
1465 route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
1466 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
1467 _ai_generator: Option<Arc<dyn mockforge_core::openapi::response::AiGenerator + Send + Sync>>,
1468 smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
1469 mqtt_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
1470 traffic_shaper: Option<mockforge_core::traffic_shaping::TrafficShaper>,
1471 traffic_shaping_enabled: bool,
1472 health_manager: Option<Arc<HealthManager>>,
1473 _mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
1474 deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
1475 proxy_config: Option<mockforge_core::proxy::config::ProxyConfig>,
1476) -> Router {
1477 use crate::latency_profiles::LatencyProfiles;
1478 use crate::op_middleware::Shared;
1479 use mockforge_core::Overrides;
1480
1481 let template_expand =
1483 options.as_ref().map(|o| o.response_template_expand).unwrap_or_else(|| {
1484 std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
1485 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1486 .unwrap_or(false)
1487 });
1488
1489 let _shared = Shared {
1490 profiles: LatencyProfiles::default(),
1491 overrides: Overrides::default(),
1492 failure_injector: None,
1493 traffic_shaper,
1494 overrides_enabled: false,
1495 traffic_shaping_enabled,
1496 };
1497
1498 let mut app = Router::new();
1500 let mut include_default_health = true;
1501
1502 if let Some(ref spec) = spec_path {
1504 match OpenApiSpec::from_file(&spec).await {
1505 Ok(openapi) => {
1506 info!("Loaded OpenAPI spec from {}", spec);
1507
1508 let persona = load_persona_from_config().await;
1510
1511 let mut registry = if let Some(opts) = options {
1512 tracing::debug!("Using custom validation options");
1513 if let Some(ref persona) = persona {
1514 tracing::info!("Using persona '{}' for route generation", persona.name);
1515 }
1516 OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
1517 } else {
1518 tracing::debug!("Using environment-based options");
1519 if let Some(ref persona) = persona {
1520 tracing::info!("Using persona '{}' for route generation", persona.name);
1521 }
1522 OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
1523 };
1524
1525 let fixtures_dir = std::env::var("MOCKFORGE_FIXTURES_DIR")
1527 .unwrap_or_else(|_| "/app/fixtures".to_string());
1528 let custom_fixtures_enabled = std::env::var("MOCKFORGE_CUSTOM_FIXTURES_ENABLED")
1529 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1530 .unwrap_or(true); if custom_fixtures_enabled {
1533 use mockforge_core::CustomFixtureLoader;
1534 use std::path::PathBuf;
1535 use std::sync::Arc;
1536
1537 let fixtures_path = PathBuf::from(&fixtures_dir);
1538 let mut custom_loader = CustomFixtureLoader::new(fixtures_path, true);
1539
1540 if let Err(e) = custom_loader.load_fixtures().await {
1541 tracing::warn!("Failed to load custom fixtures: {}", e);
1542 } else {
1543 tracing::info!("Custom fixtures loaded from {}", fixtures_dir);
1544 registry = registry.with_custom_fixture_loader(Arc::new(custom_loader));
1545 }
1546 }
1547
1548 if registry
1549 .routes()
1550 .iter()
1551 .any(|route| route.method == "GET" && route.path == "/health")
1552 {
1553 include_default_health = false;
1554 }
1555 let spec_router = if let Some(ref mockai_instance) = _mockai {
1557 tracing::debug!("Building router with MockAI support");
1558 registry.build_router_with_mockai(Some(mockai_instance.clone()))
1559 } else {
1560 registry.build_router()
1561 };
1562 app = app.merge(spec_router);
1563 }
1564 Err(e) => {
1565 warn!("Failed to load OpenAPI spec from {:?}: {}. Starting without OpenAPI integration.", spec_path, e);
1566 }
1567 }
1568 }
1569
1570 let route_chaos_injector: Option<
1574 std::sync::Arc<dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1575 > = if let Some(ref route_configs) = route_configs {
1576 if !route_configs.is_empty() {
1577 let route_configs_converted: Vec<mockforge_core::config::RouteConfig> =
1580 route_configs.iter().cloned().collect();
1581 match mockforge_route_chaos::RouteChaosInjector::new(route_configs_converted) {
1582 Ok(injector) => {
1583 info!(
1584 "Initialized advanced routing features for {} route(s)",
1585 route_configs.len()
1586 );
1587 Some(std::sync::Arc::new(injector)
1590 as std::sync::Arc<
1591 dyn mockforge_core::priority_handler::RouteChaosInjectorTrait,
1592 >)
1593 }
1594 Err(e) => {
1595 warn!(
1596 "Failed to initialize advanced routing features: {}. Using basic routing.",
1597 e
1598 );
1599 None
1600 }
1601 }
1602 } else {
1603 None
1604 }
1605 } else {
1606 None
1607 };
1608
1609 if let Some(route_configs) = route_configs {
1610 use axum::http::StatusCode;
1611 use axum::response::IntoResponse;
1612
1613 if !route_configs.is_empty() {
1614 info!("Registering {} custom route(s) from config", route_configs.len());
1615 }
1616
1617 let injector = route_chaos_injector.clone();
1618 for route_config in route_configs {
1619 let status = route_config.response.status;
1620 let body = route_config.response.body.clone();
1621 let headers = route_config.response.headers.clone();
1622 let path = route_config.path.clone();
1623 let method = route_config.method.clone();
1624
1625 let expected_method = method.to_uppercase();
1630 let injector_clone = injector.clone();
1634 app = app.route(
1635 &path,
1636 #[allow(clippy::non_send_fields_in_send_ty)]
1637 axum::routing::any(move |req: http::Request<axum::body::Body>| {
1638 let body = body.clone();
1639 let headers = headers.clone();
1640 let expand = template_expand;
1641 let expected = expected_method.clone();
1642 let status_code = status;
1643 let injector_for_chaos = injector_clone.clone();
1645
1646 async move {
1647 if req.method().as_str() != expected.as_str() {
1649 return axum::response::Response::builder()
1651 .status(StatusCode::METHOD_NOT_ALLOWED)
1652 .header("Allow", &expected)
1653 .body(axum::body::Body::empty())
1654 .unwrap()
1655 .into_response();
1656 }
1657
1658 if let Some(fault_response) = apply_route_chaos(
1662 injector_for_chaos.as_deref(),
1663 req.method(),
1664 req.uri(),
1665 )
1666 .await
1667 {
1668 return fault_response;
1669 }
1670
1671 let mut body_value = body.unwrap_or(serde_json::json!({}));
1673
1674 if expand {
1678 use mockforge_template_expansion::RequestContext;
1679 use serde_json::Value;
1680 use std::collections::HashMap;
1681
1682 let method = req.method().to_string();
1684 let path = req.uri().path().to_string();
1685
1686 let query_params: HashMap<String, Value> = req
1688 .uri()
1689 .query()
1690 .map(|q| {
1691 url::form_urlencoded::parse(q.as_bytes())
1692 .into_owned()
1693 .map(|(k, v)| (k, Value::String(v)))
1694 .collect()
1695 })
1696 .unwrap_or_default();
1697
1698 let headers: HashMap<String, Value> = req
1700 .headers()
1701 .iter()
1702 .map(|(k, v)| {
1703 (
1704 k.to_string(),
1705 Value::String(v.to_str().unwrap_or_default().to_string()),
1706 )
1707 })
1708 .collect();
1709
1710 let context = RequestContext {
1714 method,
1715 path,
1716 query_params,
1717 headers,
1718 body: None, path_params: HashMap::new(),
1720 multipart_fields: HashMap::new(),
1721 multipart_files: HashMap::new(),
1722 };
1723
1724 let body_value_clone = body_value.clone();
1728 let context_clone = context.clone();
1729 body_value = match tokio::task::spawn_blocking(move || {
1730 mockforge_template_expansion::expand_templates_in_json(
1731 body_value_clone,
1732 &context_clone,
1733 )
1734 })
1735 .await
1736 {
1737 Ok(result) => result,
1738 Err(_) => body_value, };
1740 }
1741
1742 let mut response = Json(body_value).into_response();
1743
1744 *response.status_mut() =
1746 StatusCode::from_u16(status_code).unwrap_or(StatusCode::OK);
1747
1748 for (key, value) in headers {
1750 if let Ok(header_name) = http::HeaderName::from_bytes(key.as_bytes()) {
1751 if let Ok(header_value) = http::HeaderValue::from_str(&value) {
1752 response.headers_mut().insert(header_name, header_value);
1753 }
1754 }
1755 }
1756
1757 response
1758 }
1759 }),
1760 );
1761
1762 debug!("Registered route: {} {}", method, path);
1763 }
1764 }
1765
1766 if let Some(health) = health_manager {
1768 app = app.merge(health::health_router(health));
1770 info!(
1771 "Health check endpoints enabled: /health, /health/live, /health/ready, /health/startup"
1772 );
1773 } else if include_default_health {
1774 app = app.route(
1776 "/health",
1777 axum::routing::get(|| async {
1778 use mockforge_core::server_utils::health::HealthStatus;
1779 {
1780 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1782 Ok(value) => Json(value),
1783 Err(e) => {
1784 tracing::error!("Failed to serialize health status: {}", e);
1786 Json(serde_json::json!({
1787 "status": "healthy",
1788 "service": "mockforge-http",
1789 "uptime_seconds": 0
1790 }))
1791 }
1792 }
1793 }
1794 }),
1795 );
1796 }
1797
1798 app = app.merge(sse::sse_router());
1799 app = app.merge(file_server::file_serving_router());
1801
1802 let spec_path_clone = spec_path.clone();
1804 let management_state = ManagementState::new(None, spec_path_clone, 3000); use std::sync::Arc;
1808 let ws_state = WsManagementState::new();
1809 let ws_broadcast = Arc::new(ws_state.tx.clone());
1810 let management_state = management_state.with_ws_broadcast(ws_broadcast);
1811
1812 let management_state = if let Some(proxy_cfg) = proxy_config {
1814 use tokio::sync::RwLock;
1815 let proxy_config_arc = Arc::new(RwLock::new(proxy_cfg));
1816 management_state.with_proxy_config(proxy_config_arc)
1817 } else {
1818 management_state
1819 };
1820
1821 #[cfg(feature = "smtp")]
1822 let management_state = {
1823 if let Some(smtp_reg) = smtp_registry {
1824 match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
1825 Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
1826 Err(e) => {
1827 error!(
1828 "Invalid SMTP registry type passed to HTTP management state: {:?}",
1829 e.type_id()
1830 );
1831 management_state
1832 }
1833 }
1834 } else {
1835 management_state
1836 }
1837 };
1838 #[cfg(not(feature = "smtp"))]
1839 let management_state = {
1840 let _ = smtp_registry;
1841 management_state
1842 };
1843 #[cfg(feature = "mqtt")]
1844 let management_state = {
1845 if let Some(broker) = mqtt_broker {
1846 match broker.downcast::<mockforge_mqtt::MqttBroker>() {
1847 Ok(broker) => management_state.with_mqtt_broker(broker),
1848 Err(e) => {
1849 error!(
1850 "Invalid MQTT broker passed to HTTP management state: {:?}",
1851 e.type_id()
1852 );
1853 management_state
1854 }
1855 }
1856 } else {
1857 management_state
1858 }
1859 };
1860 #[cfg(not(feature = "mqtt"))]
1861 let management_state = {
1862 let _ = mqtt_broker;
1863 management_state
1864 };
1865 app = app.nest("/__mockforge/api", management_router(management_state));
1866
1867 app = app.merge(verification_router());
1869
1870 use crate::auth::oidc::oidc_router;
1872 app = app.merge(oidc_router());
1873
1874 {
1876 use mockforge_core::security::get_global_access_review_service;
1877 if let Some(service) = get_global_access_review_service().await {
1878 use crate::handlers::access_review::{access_review_router, AccessReviewState};
1879 let review_state = AccessReviewState { service };
1880 app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
1881 debug!("Access review API mounted at /api/v1/security/access-reviews");
1882 }
1883 }
1884
1885 {
1887 use mockforge_core::security::get_global_privileged_access_manager;
1888 if let Some(manager) = get_global_privileged_access_manager().await {
1889 use crate::handlers::privileged_access::{
1890 privileged_access_router, PrivilegedAccessState,
1891 };
1892 let privileged_state = PrivilegedAccessState { manager };
1893 app = app.nest(
1894 "/api/v1/security/privileged-access",
1895 privileged_access_router(privileged_state),
1896 );
1897 debug!("Privileged access API mounted at /api/v1/security/privileged-access");
1898 }
1899 }
1900
1901 {
1903 use mockforge_core::security::get_global_change_management_engine;
1904 if let Some(engine) = get_global_change_management_engine().await {
1905 use crate::handlers::change_management::{
1906 change_management_router, ChangeManagementState,
1907 };
1908 let change_state = ChangeManagementState { engine };
1909 app = app.nest("/api/v1/change-management", change_management_router(change_state));
1910 debug!("Change management API mounted at /api/v1/change-management");
1911 }
1912 }
1913
1914 {
1916 use mockforge_core::security::get_global_risk_assessment_engine;
1917 if let Some(engine) = get_global_risk_assessment_engine().await {
1918 use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
1919 let risk_state = RiskAssessmentState { engine };
1920 app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
1921 debug!("Risk assessment API mounted at /api/v1/security/risks");
1922 }
1923 }
1924
1925 {
1927 use crate::auth::token_lifecycle::TokenLifecycleManager;
1928 use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
1929 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1930 let lifecycle_state = TokenLifecycleState {
1931 manager: lifecycle_manager,
1932 };
1933 app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
1934 debug!("Token lifecycle API mounted at /api/v1/auth");
1935 }
1936
1937 {
1939 use crate::auth::oidc::load_oidc_state;
1940 use crate::auth::token_lifecycle::TokenLifecycleManager;
1941 use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
1942 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1944 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1945 let oauth2_state = OAuth2ServerState {
1946 oidc_state,
1947 lifecycle_manager,
1948 auth_codes: Arc::new(RwLock::new(HashMap::new())),
1949 };
1950 app = app.merge(oauth2_server_router(oauth2_state));
1951 debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
1952 }
1953
1954 {
1956 use crate::auth::oidc::load_oidc_state;
1957 use crate::auth::risk_engine::RiskEngine;
1958 use crate::auth::token_lifecycle::TokenLifecycleManager;
1959 use crate::handlers::consent::{consent_router, ConsentState};
1960 use crate::handlers::oauth2_server::OAuth2ServerState;
1961 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1963 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1964 let oauth2_state = OAuth2ServerState {
1965 oidc_state: oidc_state.clone(),
1966 lifecycle_manager: lifecycle_manager.clone(),
1967 auth_codes: Arc::new(RwLock::new(HashMap::new())),
1968 };
1969 let risk_engine = Arc::new(RiskEngine::default());
1970 let consent_state = ConsentState {
1971 oauth2_state,
1972 risk_engine,
1973 };
1974 app = app.merge(consent_router(consent_state));
1975 debug!("Consent screen endpoints mounted at /consent");
1976 }
1977
1978 {
1980 use crate::auth::risk_engine::RiskEngine;
1981 use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
1982 let risk_engine = Arc::new(RiskEngine::default());
1983 let risk_state = RiskSimulationState { risk_engine };
1984 app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
1985 debug!("Risk simulation API mounted at /api/v1/auth/risk");
1986 }
1987
1988 let database = {
1990 use crate::database::Database;
1991 let database_url = std::env::var("DATABASE_URL").ok();
1992 match Database::connect_optional(database_url.as_deref()).await {
1993 Ok(db) => {
1994 if db.is_connected() {
1995 if let Err(e) = db.migrate_if_connected().await {
1997 warn!("Failed to run database migrations: {}", e);
1998 } else {
1999 info!("Database connected and migrations applied");
2000 }
2001 }
2002 Some(db)
2003 }
2004 Err(e) => {
2005 warn!("Failed to connect to database: {}. Continuing without database support.", e);
2006 None
2007 }
2008 }
2009 };
2010
2011 let (drift_engine, incident_manager, drift_config) = {
2014 use mockforge_core::contract_drift::{DriftBudgetConfig, DriftBudgetEngine};
2015 use mockforge_core::incidents::{IncidentManager, IncidentStore};
2016 use std::sync::Arc;
2017
2018 let drift_config = DriftBudgetConfig::default();
2020 let drift_engine = Arc::new(DriftBudgetEngine::new(drift_config.clone()));
2021
2022 let incident_store = Arc::new(IncidentStore::default());
2024 let incident_manager = Arc::new(IncidentManager::new(incident_store.clone()));
2025
2026 (drift_engine, incident_manager, drift_config)
2027 };
2028
2029 {
2030 use crate::handlers::drift_budget::{drift_budget_router, DriftBudgetState};
2031 use crate::middleware::drift_tracking::DriftTrackingState;
2032 use mockforge_core::ai_contract_diff::ContractDiffAnalyzer;
2033 use mockforge_core::consumer_contracts::{ConsumerBreakingChangeDetector, UsageRecorder};
2034 use std::sync::Arc;
2035
2036 let usage_recorder = Arc::new(UsageRecorder::default());
2038 let consumer_detector =
2039 Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2040
2041 let diff_analyzer = if drift_config.enabled {
2043 match ContractDiffAnalyzer::new(
2044 mockforge_core::ai_contract_diff::ContractDiffConfig::default(),
2045 ) {
2046 Ok(analyzer) => Some(Arc::new(analyzer)),
2047 Err(e) => {
2048 warn!("Failed to create contract diff analyzer: {}", e);
2049 None
2050 }
2051 }
2052 } else {
2053 None
2054 };
2055
2056 let spec = if let Some(ref spec_path) = spec_path {
2059 match OpenApiSpec::from_file(spec_path).await {
2060 Ok(s) => Some(Arc::new(s)),
2061 Err(e) => {
2062 debug!("Failed to load OpenAPI spec for drift tracking: {}", e);
2063 None
2064 }
2065 }
2066 } else {
2067 None
2068 };
2069
2070 let drift_tracking_state = DriftTrackingState {
2072 diff_analyzer,
2073 spec,
2074 drift_engine: drift_engine.clone(),
2075 incident_manager: incident_manager.clone(),
2076 usage_recorder,
2077 consumer_detector,
2078 enabled: drift_config.enabled,
2079 };
2080
2081 app = app.layer(axum::middleware::from_fn(middleware::buffer_response_middleware));
2083
2084 let drift_tracking_state_clone = drift_tracking_state.clone();
2087 app = app.layer(axum::middleware::from_fn(
2088 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2089 let state = drift_tracking_state_clone.clone();
2090 async move {
2091 if req.extensions().get::<DriftTrackingState>().is_none() {
2093 req.extensions_mut().insert(state);
2094 }
2095 middleware::drift_tracking::drift_tracking_middleware_with_extensions(req, next)
2097 .await
2098 }
2099 },
2100 ));
2101
2102 let drift_state = DriftBudgetState {
2103 engine: drift_engine.clone(),
2104 incident_manager: incident_manager.clone(),
2105 gitops_handler: None, };
2107
2108 app = app.merge(drift_budget_router(drift_state));
2109 debug!("Drift budget and incident management endpoints mounted at /api/v1/drift");
2110 }
2111
2112 #[cfg(feature = "pipelines")]
2114 {
2115 use crate::handlers::pipelines::{pipeline_router, PipelineState};
2116
2117 let pipeline_state = PipelineState::new();
2118 app = app.merge(pipeline_router(pipeline_state));
2119 debug!("Pipeline management endpoints mounted at /api/v1/pipelines");
2120 }
2121
2122 {
2124 use crate::handlers::contract_health::{contract_health_router, ContractHealthState};
2125 use crate::handlers::forecasting::{forecasting_router, ForecastingState};
2126 use crate::handlers::semantic_drift::{semantic_drift_router, SemanticDriftState};
2127 use crate::handlers::threat_modeling::{threat_modeling_router, ThreatModelingState};
2128 use mockforge_core::contract_drift::forecasting::{Forecaster, ForecastingConfig};
2129 use mockforge_core::contract_drift::threat_modeling::{
2130 ThreatAnalyzer, ThreatModelingConfig,
2131 };
2132 use mockforge_core::incidents::semantic_manager::SemanticIncidentManager;
2133 use std::sync::Arc;
2134
2135 let forecasting_config = ForecastingConfig::default();
2137 let forecaster = Arc::new(Forecaster::new(forecasting_config));
2138 let forecasting_state = ForecastingState {
2139 forecaster,
2140 database: database.clone(),
2141 };
2142
2143 let semantic_manager = Arc::new(SemanticIncidentManager::new());
2145 let semantic_state = SemanticDriftState {
2146 manager: semantic_manager,
2147 database: database.clone(),
2148 };
2149
2150 let threat_config = ThreatModelingConfig::default();
2152 let threat_analyzer = match ThreatAnalyzer::new(threat_config) {
2153 Ok(analyzer) => Arc::new(analyzer),
2154 Err(e) => {
2155 warn!("Failed to create threat analyzer: {}. Using default.", e);
2156 Arc::new(ThreatAnalyzer::new(ThreatModelingConfig::default()).unwrap_or_else(
2157 |_| {
2158 ThreatAnalyzer::new(ThreatModelingConfig {
2160 enabled: false,
2161 ..Default::default()
2162 })
2163 .expect("Failed to create fallback threat analyzer")
2164 },
2165 ))
2166 }
2167 };
2168 let mut webhook_configs = Vec::new();
2170 let config_paths = [
2171 "config.yaml",
2172 "mockforge.yaml",
2173 "tools/mockforge/config.yaml",
2174 "../tools/mockforge/config.yaml",
2175 ];
2176
2177 for path in &config_paths {
2178 if let Ok(config) = mockforge_core::config::load_config(path).await {
2179 if !config.incidents.webhooks.is_empty() {
2180 webhook_configs = config.incidents.webhooks.clone();
2181 info!("Loaded {} webhook configs from config: {}", webhook_configs.len(), path);
2182 break;
2183 }
2184 }
2185 }
2186
2187 if webhook_configs.is_empty() {
2188 debug!("No webhook configs found in config files, using empty list");
2189 }
2190
2191 let threat_state = ThreatModelingState {
2192 analyzer: threat_analyzer,
2193 webhook_configs,
2194 database: database.clone(),
2195 };
2196
2197 let contract_health_state = ContractHealthState {
2199 incident_manager: incident_manager.clone(),
2200 semantic_manager: Arc::new(SemanticIncidentManager::new()),
2201 database: database.clone(),
2202 };
2203
2204 app = app.merge(forecasting_router(forecasting_state));
2206 debug!("Forecasting endpoints mounted at /api/v1/forecasts");
2207
2208 app = app.merge(semantic_drift_router(semantic_state));
2209 debug!("Semantic drift endpoints mounted at /api/v1/semantic-drift");
2210
2211 app = app.merge(threat_modeling_router(threat_state));
2212 debug!("Threat modeling endpoints mounted at /api/v1/threats");
2213
2214 app = app.merge(contract_health_router(contract_health_state));
2215 debug!("Contract health endpoints mounted at /api/v1/contract-health");
2216 }
2217
2218 {
2220 use crate::handlers::protocol_contracts::{
2221 protocol_contracts_router, ProtocolContractState,
2222 };
2223 use mockforge_core::contract_drift::{
2224 ConsumerImpactAnalyzer, FitnessFunctionRegistry, ProtocolContractRegistry,
2225 };
2226 use std::sync::Arc;
2227 use tokio::sync::RwLock;
2228
2229 let contract_registry = Arc::new(RwLock::new(ProtocolContractRegistry::new()));
2231
2232 let mut fitness_registry = FitnessFunctionRegistry::new();
2234
2235 let config_paths = [
2237 "config.yaml",
2238 "mockforge.yaml",
2239 "tools/mockforge/config.yaml",
2240 "../tools/mockforge/config.yaml",
2241 ];
2242
2243 let mut config_loaded = false;
2244 for path in &config_paths {
2245 if let Ok(config) = mockforge_core::config::load_config(path).await {
2246 if !config.contracts.fitness_rules.is_empty() {
2247 if let Err(e) =
2248 fitness_registry.load_from_config(&config.contracts.fitness_rules)
2249 {
2250 warn!("Failed to load fitness rules from config {}: {}", path, e);
2251 } else {
2252 info!(
2253 "Loaded {} fitness rules from config: {}",
2254 config.contracts.fitness_rules.len(),
2255 path
2256 );
2257 config_loaded = true;
2258 break;
2259 }
2260 }
2261 }
2262 }
2263
2264 if !config_loaded {
2265 debug!("No fitness rules found in config files, using empty registry");
2266 }
2267
2268 let fitness_registry = Arc::new(RwLock::new(fitness_registry));
2269
2270 let consumer_mapping_registry =
2274 mockforge_core::contract_drift::ConsumerMappingRegistry::new();
2275 let consumer_analyzer =
2276 Arc::new(RwLock::new(ConsumerImpactAnalyzer::new(consumer_mapping_registry)));
2277
2278 let protocol_state = ProtocolContractState {
2279 registry: contract_registry,
2280 drift_engine: Some(drift_engine.clone()),
2281 incident_manager: Some(incident_manager.clone()),
2282 fitness_registry: Some(fitness_registry),
2283 consumer_analyzer: Some(consumer_analyzer),
2284 };
2285
2286 app = app.nest("/api/v1/contracts", protocol_contracts_router(protocol_state));
2287 debug!("Protocol contracts endpoints mounted at /api/v1/contracts");
2288 }
2289
2290 #[cfg(feature = "behavioral-cloning")]
2292 {
2293 use crate::middleware::behavioral_cloning::BehavioralCloningMiddlewareState;
2294 use std::path::PathBuf;
2295
2296 let db_path = std::env::var("RECORDER_DATABASE_PATH")
2298 .ok()
2299 .map(PathBuf::from)
2300 .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2301
2302 let bc_middleware_state = if let Some(path) = db_path {
2303 BehavioralCloningMiddlewareState::with_database_path(path)
2304 } else {
2305 BehavioralCloningMiddlewareState::new()
2306 };
2307
2308 let enabled = std::env::var("BEHAVIORAL_CLONING_ENABLED")
2310 .ok()
2311 .and_then(|v| v.parse::<bool>().ok())
2312 .unwrap_or(false);
2313
2314 if enabled {
2315 let bc_state_clone = bc_middleware_state.clone();
2316 app = app.layer(axum::middleware::from_fn(
2317 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2318 let state = bc_state_clone.clone();
2319 async move {
2320 if req.extensions().get::<BehavioralCloningMiddlewareState>().is_none() {
2322 req.extensions_mut().insert(state);
2323 }
2324 crate::middleware::behavioral_cloning::behavioral_cloning_middleware(
2326 req, next,
2327 )
2328 .await
2329 }
2330 },
2331 ));
2332 debug!("Behavioral cloning middleware enabled (applies learned behavior to requests)");
2333 }
2334 }
2335
2336 {
2338 use crate::handlers::consumer_contracts::{
2339 consumer_contracts_router, ConsumerContractsState,
2340 };
2341 use mockforge_core::consumer_contracts::{
2342 ConsumerBreakingChangeDetector, ConsumerRegistry, UsageRecorder,
2343 };
2344 use std::sync::Arc;
2345
2346 let registry = Arc::new(ConsumerRegistry::default());
2348
2349 let usage_recorder = Arc::new(UsageRecorder::default());
2351
2352 let detector = Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2354
2355 let consumer_state = ConsumerContractsState {
2356 registry,
2357 usage_recorder,
2358 detector,
2359 };
2360
2361 app = app.merge(consumer_contracts_router(consumer_state));
2362 debug!("Consumer contracts endpoints mounted at /api/v1/consumers");
2363 }
2364
2365 #[cfg(feature = "behavioral-cloning")]
2367 {
2368 use crate::handlers::behavioral_cloning::{
2369 behavioral_cloning_router, BehavioralCloningState,
2370 };
2371 use std::path::PathBuf;
2372
2373 let db_path = std::env::var("RECORDER_DATABASE_PATH")
2375 .ok()
2376 .map(PathBuf::from)
2377 .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2378
2379 let bc_state = if let Some(path) = db_path {
2380 BehavioralCloningState::with_database_path(path)
2381 } else {
2382 BehavioralCloningState::new()
2383 };
2384
2385 app = app.merge(behavioral_cloning_router(bc_state));
2386 debug!("Behavioral cloning endpoints mounted at /api/v1/behavioral-cloning");
2387 }
2388
2389 {
2391 use crate::consistency::{ConsistencyMiddlewareState, HttpAdapter};
2392 use crate::handlers::consistency::{consistency_router, ConsistencyState};
2393 use mockforge_core::consistency::ConsistencyEngine;
2394 use std::sync::Arc;
2395
2396 let consistency_engine = Arc::new(ConsistencyEngine::new());
2398
2399 let http_adapter = Arc::new(HttpAdapter::new(consistency_engine.clone()));
2401 consistency_engine.register_adapter(http_adapter.clone()).await;
2402
2403 let consistency_state = ConsistencyState {
2405 engine: consistency_engine.clone(),
2406 };
2407
2408 use crate::handlers::xray::XRayState;
2410 let xray_state = Arc::new(XRayState {
2411 engine: consistency_engine.clone(),
2412 request_contexts: std::sync::Arc::new(RwLock::new(HashMap::new())),
2413 });
2414
2415 let consistency_middleware_state = ConsistencyMiddlewareState {
2417 engine: consistency_engine.clone(),
2418 adapter: http_adapter,
2419 xray_state: Some(xray_state.clone()),
2420 };
2421
2422 let consistency_middleware_state_clone = consistency_middleware_state.clone();
2424 app = app.layer(axum::middleware::from_fn(
2425 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2426 let state = consistency_middleware_state_clone.clone();
2427 async move {
2428 if req.extensions().get::<ConsistencyMiddlewareState>().is_none() {
2430 req.extensions_mut().insert(state);
2431 }
2432 consistency::middleware::consistency_middleware(req, next).await
2434 }
2435 },
2436 ));
2437
2438 app = app.merge(consistency_router(consistency_state));
2440 debug!("Consistency engine initialized and endpoints mounted at /api/v1/consistency");
2441
2442 {
2444 use crate::handlers::fidelity::{fidelity_router, FidelityState};
2445 let fidelity_state = FidelityState::new();
2446 app = app.merge(fidelity_router(fidelity_state));
2447 debug!("Fidelity score endpoints mounted at /api/v1/workspace/:workspace_id/fidelity");
2448 }
2449
2450 {
2452 use crate::handlers::scenario_studio::{scenario_studio_router, ScenarioStudioState};
2453 let scenario_studio_state = ScenarioStudioState::new();
2454 app = app.merge(scenario_studio_router(scenario_studio_state));
2455 debug!("Scenario Studio endpoints mounted at /api/v1/scenario-studio");
2456 }
2457
2458 {
2460 use crate::handlers::performance::{performance_router, PerformanceState};
2461 let performance_state = PerformanceState::new();
2462 app = app.nest("/api/performance", performance_router(performance_state));
2463 debug!("Performance mode endpoints mounted at /api/performance");
2464 }
2465
2466 {
2468 use crate::handlers::world_state::{world_state_router, WorldStateState};
2469 use mockforge_world_state::WorldStateEngine;
2470 use std::sync::Arc;
2471 use tokio::sync::RwLock;
2472
2473 let world_state_engine = Arc::new(RwLock::new(WorldStateEngine::new()));
2474 let world_state_state = WorldStateState {
2475 engine: world_state_engine,
2476 };
2477 app = app.nest("/api/world-state", world_state_router().with_state(world_state_state));
2478 debug!("World state endpoints mounted at /api/world-state");
2479 }
2480
2481 {
2483 use crate::handlers::snapshots::{snapshot_router, SnapshotState};
2484 use mockforge_core::snapshots::SnapshotManager;
2485 use std::path::PathBuf;
2486
2487 let snapshot_dir = std::env::var("MOCKFORGE_SNAPSHOT_DIR").ok().map(PathBuf::from);
2488 let snapshot_manager = Arc::new(SnapshotManager::new(snapshot_dir));
2489
2490 let snapshot_state = SnapshotState {
2491 manager: snapshot_manager,
2492 consistency_engine: Some(consistency_engine.clone()),
2493 workspace_persistence: None, vbr_engine: None, recorder: None, };
2497
2498 app = app.merge(snapshot_router(snapshot_state));
2499 debug!("Snapshot management endpoints mounted at /api/v1/snapshots");
2500
2501 {
2503 use crate::handlers::xray::xray_router;
2504 app = app.merge(xray_router((*xray_state).clone()));
2505 debug!("X-Ray API endpoints mounted at /api/v1/xray");
2506 }
2507 }
2508
2509 {
2511 use crate::handlers::ab_testing::{ab_testing_router, ABTestingState};
2512 use crate::middleware::ab_testing::ab_testing_middleware;
2513
2514 let ab_testing_state = ABTestingState::new();
2515
2516 let ab_testing_state_clone = ab_testing_state.clone();
2518 app = app.layer(axum::middleware::from_fn(
2519 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2520 let state = ab_testing_state_clone.clone();
2521 async move {
2522 if req.extensions().get::<ABTestingState>().is_none() {
2524 req.extensions_mut().insert(state);
2525 }
2526 ab_testing_middleware(req, next).await
2528 }
2529 },
2530 ));
2531
2532 app = app.merge(ab_testing_router(ab_testing_state));
2534 debug!("A/B testing endpoints mounted at /api/v1/ab-tests");
2535 }
2536 }
2537
2538 {
2540 use crate::handlers::pr_generation::{pr_generation_router, PRGenerationState};
2541 use mockforge_core::pr_generation::{PRGenerator, PRProvider};
2542 use std::sync::Arc;
2543
2544 let pr_config = mockforge_core::pr_generation::PRGenerationConfig::from_env();
2546
2547 let generator = if pr_config.enabled && pr_config.token.is_some() {
2548 let token = pr_config.token.as_ref().unwrap().clone();
2549 let generator = match pr_config.provider {
2550 PRProvider::GitHub => PRGenerator::new_github(
2551 pr_config.owner.clone(),
2552 pr_config.repo.clone(),
2553 token,
2554 pr_config.base_branch.clone(),
2555 ),
2556 PRProvider::GitLab => PRGenerator::new_gitlab(
2557 pr_config.owner.clone(),
2558 pr_config.repo.clone(),
2559 token,
2560 pr_config.base_branch.clone(),
2561 ),
2562 };
2563 Some(Arc::new(generator))
2564 } else {
2565 None
2566 };
2567
2568 let pr_state = PRGenerationState {
2569 generator: generator.clone(),
2570 };
2571
2572 app = app.merge(pr_generation_router(pr_state));
2573 if generator.is_some() {
2574 debug!(
2575 "PR generation endpoints mounted at /api/v1/pr (configured for {:?})",
2576 pr_config.provider
2577 );
2578 } else {
2579 debug!("PR generation endpoints mounted at /api/v1/pr (not configured - set GITHUB_TOKEN/GITLAB_TOKEN and PR_REPO_OWNER/PR_REPO_NAME)");
2580 }
2581 }
2582
2583 app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
2585
2586 if let Some(mt_config) = multi_tenant_config {
2588 if mt_config.enabled {
2589 use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
2590 use std::sync::Arc;
2591
2592 info!(
2593 "Multi-tenant mode enabled with {} routing strategy",
2594 match mt_config.routing_strategy {
2595 mockforge_core::RoutingStrategy::Path => "path-based",
2596 mockforge_core::RoutingStrategy::Port => "port-based",
2597 mockforge_core::RoutingStrategy::Both => "hybrid",
2598 }
2599 );
2600
2601 let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
2603
2604 let default_workspace =
2606 mockforge_core::Workspace::new(mt_config.default_workspace.clone());
2607 if let Err(e) =
2608 registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
2609 {
2610 warn!("Failed to register default workspace: {}", e);
2611 } else {
2612 info!("Registered default workspace: '{}'", mt_config.default_workspace);
2613 }
2614
2615 let registry = Arc::new(registry);
2617
2618 let _workspace_router = WorkspaceRouter::new(registry);
2620 info!("Workspace routing middleware initialized for HTTP server");
2621 }
2622 }
2623
2624 let mut final_cors_config = cors_config;
2626 let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
2627 let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
2629 let mut rate_limit_config = middleware::RateLimitConfig {
2630 requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
2631 .ok()
2632 .and_then(|v| v.parse().ok())
2633 .unwrap_or(1000),
2634 burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
2635 .ok()
2636 .and_then(|v| v.parse().ok())
2637 .unwrap_or(2000),
2638 per_ip: true,
2639 per_endpoint: false,
2640 };
2641
2642 if let Some(deploy_config) = &deceptive_deploy_config {
2643 if deploy_config.enabled {
2644 info!("Deceptive deploy mode enabled - applying production-like configuration");
2645
2646 if let Some(prod_cors) = &deploy_config.cors {
2648 final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
2649 enabled: true,
2650 allowed_origins: prod_cors.allowed_origins.clone(),
2651 allowed_methods: prod_cors.allowed_methods.clone(),
2652 allowed_headers: prod_cors.allowed_headers.clone(),
2653 allow_credentials: prod_cors.allow_credentials,
2654 });
2655 info!("Applied production-like CORS configuration");
2656 }
2657
2658 if let Some(prod_rate_limit) = &deploy_config.rate_limit {
2660 rate_limit_config = middleware::RateLimitConfig {
2661 requests_per_minute: prod_rate_limit.requests_per_minute,
2662 burst: prod_rate_limit.burst,
2663 per_ip: prod_rate_limit.per_ip,
2664 per_endpoint: false,
2665 };
2666 info!(
2667 "Applied production-like rate limiting: {} req/min, burst: {}",
2668 prod_rate_limit.requests_per_minute, prod_rate_limit.burst
2669 );
2670 }
2671
2672 if !deploy_config.headers.is_empty() {
2674 let headers_map: HashMap<String, String> = deploy_config.headers.clone();
2675 production_headers = Some(std::sync::Arc::new(headers_map));
2676 info!("Configured {} production headers", deploy_config.headers.len());
2677 }
2678
2679 if let Some(prod_oauth) = &deploy_config.oauth {
2681 let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
2682 deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
2683 oauth2: Some(oauth2_config),
2684 ..Default::default()
2685 });
2686 info!("Applied production-like OAuth configuration for deceptive deploy");
2687 }
2688 }
2689 }
2690
2691 let rate_limiter =
2693 std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
2694
2695 let mut state = HttpServerState::new().with_rate_limiter(rate_limiter.clone());
2696
2697 if let Some(headers) = production_headers.clone() {
2699 state = state.with_production_headers(headers);
2700 }
2701
2702 app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));
2704
2705 if state.production_headers.is_some() {
2707 app =
2708 app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
2709 }
2710
2711 if let Some(auth_config) = deceptive_deploy_auth_config {
2713 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
2714 use std::collections::HashMap;
2715 use std::sync::Arc;
2716 use tokio::sync::RwLock;
2717
2718 let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
2720 match create_oauth2_client(oauth2_config) {
2721 Ok(client) => Some(client),
2722 Err(e) => {
2723 warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
2724 None
2725 }
2726 }
2727 } else {
2728 None
2729 };
2730
2731 let auth_state = AuthState {
2733 config: auth_config,
2734 spec: None, oauth2_client,
2736 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
2737 };
2738
2739 app = app.layer(from_fn_with_state(auth_state, auth_middleware));
2741 info!("Applied OAuth authentication middleware from deceptive deploy configuration");
2742 }
2743
2744 #[cfg(feature = "runtime-daemon")]
2746 {
2747 use mockforge_runtime_daemon::{AutoGenerator, NotFoundDetector, RuntimeDaemonConfig};
2748 use std::sync::Arc;
2749
2750 let daemon_config = RuntimeDaemonConfig::from_env();
2752
2753 if daemon_config.enabled {
2754 info!("Runtime daemon enabled - auto-creating mocks from 404s");
2755
2756 let management_api_url =
2758 std::env::var("MOCKFORGE_MANAGEMENT_API_URL").unwrap_or_else(|_| {
2759 let port =
2760 std::env::var("MOCKFORGE_HTTP_PORT").unwrap_or_else(|_| "3000".to_string());
2761 format!("http://localhost:{}", port)
2762 });
2763
2764 let generator = Arc::new(AutoGenerator::new(daemon_config.clone(), management_api_url));
2766
2767 let detector = NotFoundDetector::new(daemon_config.clone());
2769 detector.set_generator(generator).await;
2770
2771 let detector_clone = detector.clone();
2773 app = app.layer(axum::middleware::from_fn(
2774 move |req: axum::extract::Request, next: axum::middleware::Next| {
2775 let detector = detector_clone.clone();
2776 async move { detector.detect_and_auto_create(req, next).await }
2777 },
2778 ));
2779
2780 debug!("Runtime daemon 404 detection middleware added");
2781 }
2782 }
2783
2784 app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
2787
2788 app = apply_cors_middleware(app, final_cors_config);
2790
2791 app
2792}
2793
2794#[test]
2798fn test_route_info_clone() {
2799 let route = RouteInfo {
2800 method: "POST".to_string(),
2801 path: "/users".to_string(),
2802 operation_id: Some("createUser".to_string()),
2803 summary: None,
2804 description: None,
2805 parameters: vec![],
2806 };
2807
2808 let cloned = route.clone();
2809 assert_eq!(route.method, cloned.method);
2810 assert_eq!(route.path, cloned.path);
2811 assert_eq!(route.operation_id, cloned.operation_id);
2812}
2813
2814#[test]
2815fn test_http_server_state_new() {
2816 let state = HttpServerState::new();
2817 assert_eq!(state.routes.len(), 0);
2818}
2819
2820#[test]
2821fn test_http_server_state_with_routes() {
2822 let routes = vec![
2823 RouteInfo {
2824 method: "GET".to_string(),
2825 path: "/users".to_string(),
2826 operation_id: Some("getUsers".to_string()),
2827 summary: None,
2828 description: None,
2829 parameters: vec![],
2830 },
2831 RouteInfo {
2832 method: "POST".to_string(),
2833 path: "/users".to_string(),
2834 operation_id: Some("createUser".to_string()),
2835 summary: None,
2836 description: None,
2837 parameters: vec![],
2838 },
2839 ];
2840
2841 let state = HttpServerState::with_routes(routes.clone());
2842 assert_eq!(state.routes.len(), 2);
2843 assert_eq!(state.routes[0].method, "GET");
2844 assert_eq!(state.routes[1].method, "POST");
2845}
2846
2847#[test]
2848fn test_http_server_state_clone() {
2849 let routes = vec![RouteInfo {
2850 method: "GET".to_string(),
2851 path: "/test".to_string(),
2852 operation_id: None,
2853 summary: None,
2854 description: None,
2855 parameters: vec![],
2856 }];
2857
2858 let state = HttpServerState::with_routes(routes);
2859 let cloned = state.clone();
2860
2861 assert_eq!(state.routes.len(), cloned.routes.len());
2862 assert_eq!(state.routes[0].method, cloned.routes[0].method);
2863}
2864
2865#[tokio::test]
2866async fn test_build_router_without_openapi() {
2867 let _router = build_router(None, None, None).await;
2868 }
2870
2871#[tokio::test]
2872async fn test_build_router_with_nonexistent_spec() {
2873 let _router = build_router(Some("/nonexistent/spec.yaml".to_string()), None, None).await;
2874 }
2876
2877#[tokio::test]
2878async fn test_build_router_with_auth_and_latency() {
2879 let _router = build_router_with_auth_and_latency(None, None, None, None).await;
2880 }
2882
2883#[tokio::test]
2884async fn test_build_router_with_latency() {
2885 let _router = build_router_with_latency(None, None, None).await;
2886 }
2888
2889#[tokio::test]
2890async fn test_build_router_with_auth() {
2891 let _router = build_router_with_auth(None, None, None).await;
2892 }
2894
2895#[tokio::test]
2896async fn test_build_router_with_chains() {
2897 let _router = build_router_with_chains(None, None, None).await;
2898 }
2900
2901#[test]
2902fn test_route_info_with_all_fields() {
2903 let route = RouteInfo {
2904 method: "PUT".to_string(),
2905 path: "/users/{id}".to_string(),
2906 operation_id: Some("updateUser".to_string()),
2907 summary: Some("Update user".to_string()),
2908 description: Some("Updates an existing user".to_string()),
2909 parameters: vec!["id".to_string(), "body".to_string()],
2910 };
2911
2912 assert!(route.operation_id.is_some());
2913 assert!(route.summary.is_some());
2914 assert!(route.description.is_some());
2915 assert_eq!(route.parameters.len(), 2);
2916}
2917
2918#[test]
2919fn test_route_info_with_minimal_fields() {
2920 let route = RouteInfo {
2921 method: "DELETE".to_string(),
2922 path: "/users/{id}".to_string(),
2923 operation_id: None,
2924 summary: None,
2925 description: None,
2926 parameters: vec![],
2927 };
2928
2929 assert!(route.operation_id.is_none());
2930 assert!(route.summary.is_none());
2931 assert!(route.description.is_none());
2932 assert_eq!(route.parameters.len(), 0);
2933}
2934
2935#[test]
2936fn test_http_server_state_empty_routes() {
2937 let state = HttpServerState::with_routes(vec![]);
2938 assert_eq!(state.routes.len(), 0);
2939}
2940
2941#[test]
2942fn test_http_server_state_multiple_routes() {
2943 let routes = vec![
2944 RouteInfo {
2945 method: "GET".to_string(),
2946 path: "/users".to_string(),
2947 operation_id: Some("listUsers".to_string()),
2948 summary: Some("List all users".to_string()),
2949 description: None,
2950 parameters: vec![],
2951 },
2952 RouteInfo {
2953 method: "GET".to_string(),
2954 path: "/users/{id}".to_string(),
2955 operation_id: Some("getUser".to_string()),
2956 summary: Some("Get a user".to_string()),
2957 description: None,
2958 parameters: vec!["id".to_string()],
2959 },
2960 RouteInfo {
2961 method: "POST".to_string(),
2962 path: "/users".to_string(),
2963 operation_id: Some("createUser".to_string()),
2964 summary: Some("Create a user".to_string()),
2965 description: None,
2966 parameters: vec!["body".to_string()],
2967 },
2968 ];
2969
2970 let state = HttpServerState::with_routes(routes);
2971 assert_eq!(state.routes.len(), 3);
2972
2973 let methods: Vec<&str> = state.routes.iter().map(|r| r.method.as_str()).collect();
2975 assert!(methods.contains(&"GET"));
2976 assert!(methods.contains(&"POST"));
2977}
2978
2979#[test]
2980fn test_http_server_state_with_rate_limiter() {
2981 use std::sync::Arc;
2982
2983 let config = crate::middleware::RateLimitConfig::default();
2984 let rate_limiter = Arc::new(crate::middleware::GlobalRateLimiter::new(config));
2985
2986 let state = HttpServerState::new().with_rate_limiter(rate_limiter);
2987
2988 assert!(state.rate_limiter.is_some());
2989 assert_eq!(state.routes.len(), 0);
2990}
2991
2992#[tokio::test]
2993async fn test_build_router_includes_rate_limiter() {
2994 let _router = build_router(None, None, None).await;
2995 }