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<std::sync::Arc<crate::middleware::rate_limit::GlobalRateLimiter>>,
334 pub production_headers: Option<std::sync::Arc<std::collections::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: std::sync::Arc<crate::middleware::rate_limit::GlobalRateLimiter>,
367 ) -> Self {
368 self.rate_limiter = Some(rate_limiter);
369 self
370 }
371
372 pub fn with_production_headers(
374 mut self,
375 headers: std::sync::Arc<std::collections::HashMap<String, String>>,
376 ) -> Self {
377 self.production_headers = Some(headers);
378 self
379 }
380}
381
382async fn get_routes_handler(State(state): State<HttpServerState>) -> Json<serde_json::Value> {
384 let route_info: Vec<serde_json::Value> = state
385 .routes
386 .iter()
387 .map(|route| {
388 serde_json::json!({
389 "method": route.method,
390 "path": route.path,
391 "operation_id": route.operation_id,
392 "summary": route.summary,
393 "description": route.description,
394 "parameters": route.parameters
395 })
396 })
397 .collect();
398
399 Json(serde_json::json!({
400 "routes": route_info,
401 "total": state.routes.len()
402 }))
403}
404
405pub async fn build_router(
407 spec_path: Option<String>,
408 options: Option<ValidationOptions>,
409 failure_config: Option<FailureConfig>,
410) -> Router {
411 build_router_with_multi_tenant(
412 spec_path,
413 options,
414 failure_config,
415 None,
416 None,
417 None,
418 None,
419 None,
420 None,
421 None,
422 )
423 .await
424}
425
426fn apply_cors_middleware(
428 app: Router,
429 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
430) -> Router {
431 use http::Method;
432 use tower_http::cors::AllowOrigin;
433
434 if let Some(config) = cors_config {
435 if !config.enabled {
436 return app;
437 }
438
439 let mut cors_layer = CorsLayer::new();
440 let mut is_wildcard_origin = false;
441
442 if config.allowed_origins.contains(&"*".to_string()) {
444 cors_layer = cors_layer.allow_origin(Any);
445 is_wildcard_origin = true;
446 } else if !config.allowed_origins.is_empty() {
447 let origins: Vec<_> = config
449 .allowed_origins
450 .iter()
451 .filter_map(|origin| {
452 origin.parse::<http::HeaderValue>().ok().map(AllowOrigin::exact)
453 })
454 .collect();
455
456 if origins.is_empty() {
457 warn!("No valid CORS origins configured, using permissive CORS");
459 cors_layer = cors_layer.allow_origin(Any);
460 is_wildcard_origin = true;
461 } else {
462 if origins.len() == 1 {
465 cors_layer = cors_layer.allow_origin(origins[0].clone());
466 is_wildcard_origin = false;
467 } else {
468 warn!(
470 "Multiple CORS origins configured, using permissive CORS. \
471 Consider using '*' for all origins."
472 );
473 cors_layer = cors_layer.allow_origin(Any);
474 is_wildcard_origin = true;
475 }
476 }
477 } else {
478 cors_layer = cors_layer.allow_origin(Any);
480 is_wildcard_origin = true;
481 }
482
483 if !config.allowed_methods.is_empty() {
485 let methods: Vec<Method> =
486 config.allowed_methods.iter().filter_map(|m| m.parse().ok()).collect();
487 if !methods.is_empty() {
488 cors_layer = cors_layer.allow_methods(methods);
489 }
490 } else {
491 cors_layer = cors_layer.allow_methods([
493 Method::GET,
494 Method::POST,
495 Method::PUT,
496 Method::DELETE,
497 Method::PATCH,
498 Method::OPTIONS,
499 ]);
500 }
501
502 if !config.allowed_headers.is_empty() {
504 let headers: Vec<_> = config
505 .allowed_headers
506 .iter()
507 .filter_map(|h| h.parse::<http::HeaderName>().ok())
508 .collect();
509 if !headers.is_empty() {
510 cors_layer = cors_layer.allow_headers(headers);
511 }
512 } else {
513 cors_layer =
515 cors_layer.allow_headers([http::header::CONTENT_TYPE, http::header::AUTHORIZATION]);
516 }
517
518 let should_allow_credentials = if is_wildcard_origin {
522 false
524 } else {
525 config.allow_credentials
527 };
528
529 cors_layer = cors_layer.allow_credentials(should_allow_credentials);
530
531 info!(
532 "CORS middleware enabled with configured settings (credentials: {})",
533 should_allow_credentials
534 );
535 app.layer(cors_layer)
536 } else {
537 debug!("No CORS config provided, using permissive CORS for development");
541 app.layer(CorsLayer::permissive().allow_credentials(false))
544 }
545}
546
547#[allow(clippy::too_many_arguments)]
549pub async fn build_router_with_multi_tenant(
550 spec_path: Option<String>,
551 options: Option<ValidationOptions>,
552 failure_config: Option<FailureConfig>,
553 multi_tenant_config: Option<mockforge_core::MultiTenantConfig>,
554 _route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
555 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
556 ai_generator: Option<
557 std::sync::Arc<dyn mockforge_core::openapi::response::AiGenerator + Send + Sync>,
558 >,
559 smtp_registry: Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
560 mockai: Option<
561 std::sync::Arc<tokio::sync::RwLock<mockforge_core::intelligent_behavior::MockAI>>,
562 >,
563 deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
564) -> Router {
565 use std::time::Instant;
566
567 let startup_start = Instant::now();
568
569 let mut app = Router::new();
571
572 let mut rate_limit_config = crate::middleware::RateLimitConfig {
575 requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
576 .ok()
577 .and_then(|v| v.parse().ok())
578 .unwrap_or(1000),
579 burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
580 .ok()
581 .and_then(|v| v.parse().ok())
582 .unwrap_or(2000),
583 per_ip: true,
584 per_endpoint: false,
585 };
586
587 let mut final_cors_config = cors_config;
589 let mut production_headers: Option<std::sync::Arc<std::collections::HashMap<String, String>>> =
590 None;
591 let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
593
594 if let Some(deploy_config) = &deceptive_deploy_config {
595 if deploy_config.enabled {
596 info!("Deceptive deploy mode enabled - applying production-like configuration");
597
598 if let Some(prod_cors) = &deploy_config.cors {
600 final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
601 enabled: true,
602 allowed_origins: prod_cors.allowed_origins.clone(),
603 allowed_methods: prod_cors.allowed_methods.clone(),
604 allowed_headers: prod_cors.allowed_headers.clone(),
605 allow_credentials: prod_cors.allow_credentials,
606 });
607 info!("Applied production-like CORS configuration");
608 }
609
610 if let Some(prod_rate_limit) = &deploy_config.rate_limit {
612 rate_limit_config = crate::middleware::RateLimitConfig {
613 requests_per_minute: prod_rate_limit.requests_per_minute,
614 burst: prod_rate_limit.burst,
615 per_ip: prod_rate_limit.per_ip,
616 per_endpoint: false,
617 };
618 info!(
619 "Applied production-like rate limiting: {} req/min, burst: {}",
620 prod_rate_limit.requests_per_minute, prod_rate_limit.burst
621 );
622 }
623
624 if !deploy_config.headers.is_empty() {
626 let headers_map: std::collections::HashMap<String, String> =
627 deploy_config.headers.clone();
628 production_headers = Some(std::sync::Arc::new(headers_map));
629 info!("Configured {} production headers", deploy_config.headers.len());
630 }
631
632 if let Some(prod_oauth) = &deploy_config.oauth {
634 let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
635 deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
636 oauth2: Some(oauth2_config),
637 ..Default::default()
638 });
639 info!("Applied production-like OAuth configuration for deceptive deploy");
640 }
641 }
642 }
643
644 let rate_limiter =
645 std::sync::Arc::new(crate::middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
646
647 let mut state = HttpServerState::new().with_rate_limiter(rate_limiter.clone());
648
649 if let Some(headers) = production_headers.clone() {
651 state = state.with_production_headers(headers);
652 }
653
654 let spec_path_for_mgmt = spec_path.clone();
656
657 if let Some(spec_path) = spec_path {
659 tracing::debug!("Processing OpenAPI spec path: {}", spec_path);
660
661 let spec_load_start = Instant::now();
663 match OpenApiSpec::from_file(&spec_path).await {
664 Ok(openapi) => {
665 let spec_load_duration = spec_load_start.elapsed();
666 info!(
667 "Successfully loaded OpenAPI spec from {} (took {:?})",
668 spec_path, spec_load_duration
669 );
670
671 tracing::debug!("Creating OpenAPI route registry...");
673 let registry_start = Instant::now();
674
675 let persona = load_persona_from_config().await;
677
678 let registry = if let Some(opts) = options {
679 tracing::debug!("Using custom validation options");
680 if let Some(ref persona) = persona {
681 tracing::info!("Using persona '{}' for route generation", persona.name);
682 }
683 OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
684 } else {
685 tracing::debug!("Using environment-based options");
686 if let Some(ref persona) = persona {
687 tracing::info!("Using persona '{}' for route generation", persona.name);
688 }
689 OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
690 };
691 let registry_duration = registry_start.elapsed();
692 info!(
693 "Created OpenAPI route registry with {} routes (took {:?})",
694 registry.routes().len(),
695 registry_duration
696 );
697
698 let extract_start = Instant::now();
700 let route_info: Vec<RouteInfo> = registry
701 .routes()
702 .iter()
703 .map(|route| RouteInfo {
704 method: route.method.clone(),
705 path: route.path.clone(),
706 operation_id: route.operation.operation_id.clone(),
707 summary: route.operation.summary.clone(),
708 description: route.operation.description.clone(),
709 parameters: route.parameters.clone(),
710 })
711 .collect();
712 state.routes = route_info;
713 let extract_duration = extract_start.elapsed();
714 debug!("Extracted route information (took {:?})", extract_duration);
715
716 let overrides = if std::env::var("MOCKFORGE_HTTP_OVERRIDES_GLOB").is_ok() {
718 tracing::debug!("Loading overrides from environment variable");
719 let overrides_start = Instant::now();
720 match mockforge_core::Overrides::load_from_globs(&[]).await {
721 Ok(overrides) => {
722 let overrides_duration = overrides_start.elapsed();
723 info!(
724 "Loaded {} override rules (took {:?})",
725 overrides.rules().len(),
726 overrides_duration
727 );
728 Some(overrides)
729 }
730 Err(e) => {
731 tracing::warn!("Failed to load overrides: {}", e);
732 None
733 }
734 }
735 } else {
736 None
737 };
738
739 let router_build_start = Instant::now();
741 let overrides_enabled = overrides.is_some();
742 let openapi_router = if let Some(mockai_instance) = &mockai {
743 tracing::debug!("Building router with MockAI support");
744 registry.build_router_with_mockai(Some(mockai_instance.clone()))
745 } else if let Some(ai_generator) = &ai_generator {
746 tracing::debug!("Building router with AI generator support");
747 registry.build_router_with_ai(Some(ai_generator.clone()))
748 } else if let Some(failure_config) = &failure_config {
749 tracing::debug!("Building router with failure injection and overrides");
750 let failure_injector = FailureInjector::new(Some(failure_config.clone()), true);
751 registry.build_router_with_injectors_and_overrides(
752 LatencyInjector::default(),
753 Some(failure_injector),
754 overrides,
755 overrides_enabled,
756 )
757 } else {
758 tracing::debug!("Building router with overrides");
759 registry.build_router_with_injectors_and_overrides(
760 LatencyInjector::default(),
761 None,
762 overrides,
763 overrides_enabled,
764 )
765 };
766 let router_build_duration = router_build_start.elapsed();
767 debug!("Built OpenAPI router (took {:?})", router_build_duration);
768
769 tracing::debug!("Merging OpenAPI router with main router");
770 app = app.merge(openapi_router);
771 tracing::debug!("Router built successfully");
772 }
773 Err(e) => {
774 warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
775 }
776 }
777 }
778
779 app = app.route(
781 "/health",
782 axum::routing::get(|| async {
783 use mockforge_core::server_utils::health::HealthStatus;
784 {
785 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
787 Ok(value) => axum::Json(value),
788 Err(e) => {
789 tracing::error!("Failed to serialize health status: {}", e);
791 axum::Json(serde_json::json!({
792 "status": "healthy",
793 "service": "mockforge-http",
794 "uptime_seconds": 0
795 }))
796 }
797 }
798 }
799 }),
800 )
801 .merge(sse::sse_router())
803 .merge(file_server::file_serving_router());
805
806 let state_for_routes = state.clone();
808
809 let routes_router = Router::new()
811 .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
812 .route("/__mockforge/coverage", axum::routing::get(coverage::get_coverage_handler))
813 .with_state(state_for_routes);
814
815 app = app.merge(routes_router);
817
818 let coverage_html_path = std::env::var("MOCKFORGE_COVERAGE_UI_PATH")
821 .unwrap_or_else(|_| "crates/mockforge-http/static/coverage.html".to_string());
822
823 if std::path::Path::new(&coverage_html_path).exists() {
825 app = app.nest_service(
826 "/__mockforge/coverage.html",
827 tower_http::services::ServeFile::new(&coverage_html_path),
828 );
829 debug!("Serving coverage UI from: {}", coverage_html_path);
830 } else {
831 debug!(
832 "Coverage UI file not found at: {}. Skipping static file serving.",
833 coverage_html_path
834 );
835 }
836
837 let management_state = ManagementState::new(None, spec_path_for_mgmt, 3000); use std::sync::Arc;
842 let ws_state = WsManagementState::new();
843 let ws_broadcast = Arc::new(ws_state.tx.clone());
844 let management_state = management_state.with_ws_broadcast(ws_broadcast);
845
846 #[cfg(feature = "smtp")]
850 let management_state = {
851 if let Some(smtp_reg) = smtp_registry {
852 match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
853 Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
854 Err(e) => {
855 error!(
856 "Invalid SMTP registry type passed to HTTP management state: {:?}",
857 e.type_id()
858 );
859 management_state
860 }
861 }
862 } else {
863 management_state
864 }
865 };
866 #[cfg(not(feature = "smtp"))]
867 let management_state = management_state;
868 #[cfg(not(feature = "smtp"))]
869 let _ = smtp_registry;
870 app = app.nest("/__mockforge/api", management_router(management_state));
871
872 app = app.merge(verification_router());
874
875 use crate::auth::oidc::oidc_router;
877 app = app.merge(oidc_router());
878
879 {
881 use mockforge_core::security::get_global_access_review_service;
882 if let Some(service) = get_global_access_review_service().await {
883 use crate::handlers::access_review::{access_review_router, AccessReviewState};
884 let review_state = AccessReviewState { service };
885 app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
886 debug!("Access review API mounted at /api/v1/security/access-reviews");
887 }
888 }
889
890 {
892 use mockforge_core::security::get_global_privileged_access_manager;
893 if let Some(manager) = get_global_privileged_access_manager().await {
894 use crate::handlers::privileged_access::{
895 privileged_access_router, PrivilegedAccessState,
896 };
897 let privileged_state = PrivilegedAccessState { manager };
898 app = app.nest(
899 "/api/v1/security/privileged-access",
900 privileged_access_router(privileged_state),
901 );
902 debug!("Privileged access API mounted at /api/v1/security/privileged-access");
903 }
904 }
905
906 {
908 use mockforge_core::security::get_global_change_management_engine;
909 if let Some(engine) = get_global_change_management_engine().await {
910 use crate::handlers::change_management::{
911 change_management_router, ChangeManagementState,
912 };
913 let change_state = ChangeManagementState { engine };
914 app = app.nest("/api/v1/change-management", change_management_router(change_state));
915 debug!("Change management API mounted at /api/v1/change-management");
916 }
917 }
918
919 {
921 use mockforge_core::security::get_global_risk_assessment_engine;
922 if let Some(engine) = get_global_risk_assessment_engine().await {
923 use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
924 let risk_state = RiskAssessmentState { engine };
925 app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
926 debug!("Risk assessment API mounted at /api/v1/security/risks");
927 }
928 }
929
930 {
932 use crate::auth::token_lifecycle::TokenLifecycleManager;
933 use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
934 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
935 let lifecycle_state = TokenLifecycleState {
936 manager: lifecycle_manager,
937 };
938 app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
939 debug!("Token lifecycle API mounted at /api/v1/auth");
940 }
941
942 {
944 use crate::auth::oidc::load_oidc_state;
945 use crate::auth::token_lifecycle::TokenLifecycleManager;
946 use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
947 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
949 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
950 let oauth2_state = OAuth2ServerState {
951 oidc_state,
952 lifecycle_manager,
953 auth_codes: Arc::new(RwLock::new(HashMap::new())),
954 };
955 app = app.merge(oauth2_server_router(oauth2_state));
956 debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
957 }
958
959 {
961 use crate::auth::oidc::load_oidc_state;
962 use crate::auth::risk_engine::RiskEngine;
963 use crate::auth::token_lifecycle::TokenLifecycleManager;
964 use crate::handlers::consent::{consent_router, ConsentState};
965 use crate::handlers::oauth2_server::OAuth2ServerState;
966 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
968 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
969 let oauth2_state = OAuth2ServerState {
970 oidc_state: oidc_state.clone(),
971 lifecycle_manager: lifecycle_manager.clone(),
972 auth_codes: Arc::new(RwLock::new(HashMap::new())),
973 };
974 let risk_engine = Arc::new(RiskEngine::default());
975 let consent_state = ConsentState {
976 oauth2_state,
977 risk_engine,
978 };
979 app = app.merge(consent_router(consent_state));
980 debug!("Consent screen endpoints mounted at /consent");
981 }
982
983 {
985 use crate::auth::risk_engine::RiskEngine;
986 use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
987 let risk_engine = Arc::new(RiskEngine::default());
988 let risk_state = RiskSimulationState { risk_engine };
989 app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
990 debug!("Risk simulation API mounted at /api/v1/auth/risk");
991 }
992
993 app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
995
996 app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));
998
999 app = app.layer(axum::middleware::from_fn(crate::middleware::security_middleware));
1001
1002 app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
1005
1006 app = app.layer(from_fn_with_state(state.clone(), crate::middleware::rate_limit_middleware));
1008
1009 if state.production_headers.is_some() {
1011 app = app.layer(from_fn_with_state(
1012 state.clone(),
1013 crate::middleware::production_headers_middleware,
1014 ));
1015 }
1016
1017 if let Some(auth_config) = deceptive_deploy_auth_config {
1019 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1020 use std::collections::HashMap;
1021 use std::sync::Arc;
1022 use tokio::sync::RwLock;
1023
1024 let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
1026 match create_oauth2_client(oauth2_config) {
1027 Ok(client) => Some(client),
1028 Err(e) => {
1029 warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
1030 None
1031 }
1032 }
1033 } else {
1034 None
1035 };
1036
1037 let auth_state = AuthState {
1039 config: auth_config,
1040 spec: None, oauth2_client,
1042 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1043 };
1044
1045 app = app.layer(axum::middleware::from_fn_with_state(auth_state, auth_middleware));
1047 info!("Applied OAuth authentication middleware from deceptive deploy configuration");
1048 }
1049
1050 app = apply_cors_middleware(app, final_cors_config);
1052
1053 if let Some(mt_config) = multi_tenant_config {
1055 if mt_config.enabled {
1056 use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
1057 use std::sync::Arc;
1058
1059 info!(
1060 "Multi-tenant mode enabled with {} routing strategy",
1061 match mt_config.routing_strategy {
1062 mockforge_core::RoutingStrategy::Path => "path-based",
1063 mockforge_core::RoutingStrategy::Port => "port-based",
1064 mockforge_core::RoutingStrategy::Both => "hybrid",
1065 }
1066 );
1067
1068 let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
1070
1071 let default_workspace =
1073 mockforge_core::Workspace::new(mt_config.default_workspace.clone());
1074 if let Err(e) =
1075 registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
1076 {
1077 warn!("Failed to register default workspace: {}", e);
1078 } else {
1079 info!("Registered default workspace: '{}'", mt_config.default_workspace);
1080 }
1081
1082 if mt_config.auto_discover {
1084 if let Some(config_dir) = &mt_config.config_directory {
1085 let config_path = Path::new(config_dir);
1086 if config_path.exists() && config_path.is_dir() {
1087 match fs::read_dir(config_path).await {
1088 Ok(mut entries) => {
1089 while let Ok(Some(entry)) = entries.next_entry().await {
1090 let path = entry.path();
1091 if path.extension() == Some(OsStr::new("yaml")) {
1092 match fs::read_to_string(&path).await {
1093 Ok(content) => {
1094 match serde_yaml::from_str::<
1095 mockforge_core::Workspace,
1096 >(
1097 &content
1098 ) {
1099 Ok(workspace) => {
1100 if let Err(e) = registry.register_workspace(
1101 workspace.id.clone(),
1102 workspace,
1103 ) {
1104 warn!("Failed to register auto-discovered workspace from {:?}: {}", path, e);
1105 } else {
1106 info!("Auto-registered workspace from {:?}", path);
1107 }
1108 }
1109 Err(e) => {
1110 warn!("Failed to parse workspace from {:?}: {}", path, e);
1111 }
1112 }
1113 }
1114 Err(e) => {
1115 warn!(
1116 "Failed to read workspace file {:?}: {}",
1117 path, e
1118 );
1119 }
1120 }
1121 }
1122 }
1123 }
1124 Err(e) => {
1125 warn!("Failed to read config directory {:?}: {}", config_path, e);
1126 }
1127 }
1128 } else {
1129 warn!(
1130 "Config directory {:?} does not exist or is not a directory",
1131 config_path
1132 );
1133 }
1134 }
1135 }
1136
1137 let registry = Arc::new(registry);
1139
1140 let _workspace_router = WorkspaceRouter::new(registry);
1142
1143 info!("Workspace routing middleware initialized for HTTP server");
1146 }
1147 }
1148
1149 let total_startup_duration = startup_start.elapsed();
1150 info!("HTTP router startup completed (total time: {:?})", total_startup_duration);
1151
1152 app
1153}
1154
1155pub async fn build_router_with_auth_and_latency(
1157 _spec_path: Option<String>,
1158 _options: Option<()>,
1159 _auth_config: Option<mockforge_core::config::AuthConfig>,
1160 _latency_injector: Option<LatencyInjector>,
1161) -> Router {
1162 build_router(None, None, None).await
1164}
1165
1166pub async fn build_router_with_latency(
1168 _spec_path: Option<String>,
1169 _options: Option<ValidationOptions>,
1170 _latency_injector: Option<LatencyInjector>,
1171) -> Router {
1172 build_router(None, None, None).await
1174}
1175
1176pub async fn build_router_with_auth(
1178 spec_path: Option<String>,
1179 options: Option<ValidationOptions>,
1180 auth_config: Option<mockforge_core::config::AuthConfig>,
1181) -> Router {
1182 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1183 use std::sync::Arc;
1184
1185 #[cfg(feature = "data-faker")]
1187 {
1188 register_core_faker_provider();
1189 }
1190
1191 let spec = if let Some(spec_path) = &spec_path {
1193 match mockforge_core::openapi::OpenApiSpec::from_file(&spec_path).await {
1194 Ok(spec) => Some(Arc::new(spec)),
1195 Err(e) => {
1196 warn!("Failed to load OpenAPI spec for auth: {}", e);
1197 None
1198 }
1199 }
1200 } else {
1201 None
1202 };
1203
1204 let oauth2_client = if let Some(auth_config) = &auth_config {
1206 if let Some(oauth2_config) = &auth_config.oauth2 {
1207 match create_oauth2_client(oauth2_config) {
1208 Ok(client) => Some(client),
1209 Err(e) => {
1210 warn!("Failed to create OAuth2 client: {}", e);
1211 None
1212 }
1213 }
1214 } else {
1215 None
1216 }
1217 } else {
1218 None
1219 };
1220
1221 let auth_state = AuthState {
1222 config: auth_config.unwrap_or_default(),
1223 spec,
1224 oauth2_client,
1225 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1226 };
1227
1228 let mut app = Router::new().with_state(auth_state.clone());
1230
1231 if let Some(spec_path) = spec_path {
1233 match OpenApiSpec::from_file(&spec_path).await {
1234 Ok(openapi) => {
1235 info!("Loaded OpenAPI spec from {}", spec_path);
1236 let registry = if let Some(opts) = options {
1237 OpenApiRouteRegistry::new_with_options(openapi, opts)
1238 } else {
1239 OpenApiRouteRegistry::new_with_env(openapi)
1240 };
1241
1242 app = registry.build_router();
1243 }
1244 Err(e) => {
1245 warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
1246 }
1247 }
1248 }
1249
1250 app = app.route(
1252 "/health",
1253 axum::routing::get(|| async {
1254 use mockforge_core::server_utils::health::HealthStatus;
1255 {
1256 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1258 Ok(value) => axum::Json(value),
1259 Err(e) => {
1260 tracing::error!("Failed to serialize health status: {}", e);
1262 axum::Json(serde_json::json!({
1263 "status": "healthy",
1264 "service": "mockforge-http",
1265 "uptime_seconds": 0
1266 }))
1267 }
1268 }
1269 }
1270 }),
1271 )
1272 .merge(sse::sse_router())
1274 .merge(file_server::file_serving_router())
1276 .layer(axum::middleware::from_fn_with_state(auth_state.clone(), auth_middleware))
1278 .layer(axum::middleware::from_fn(request_logging::log_http_requests));
1280
1281 app
1282}
1283
1284pub async fn serve_router(
1286 port: u16,
1287 app: Router,
1288) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1289 serve_router_with_tls(port, app, None).await
1290}
1291
1292pub async fn serve_router_with_tls(
1294 port: u16,
1295 app: Router,
1296 tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1297) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1298 use std::net::SocketAddr;
1299
1300 let addr = mockforge_core::wildcard_socket_addr(port);
1301
1302 if let Some(ref tls) = tls_config {
1303 if tls.enabled {
1304 info!("HTTPS listening on {}", addr);
1305 return serve_with_tls(addr, app, tls).await;
1306 }
1307 }
1308
1309 info!("HTTP listening on {}", addr);
1310
1311 let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
1312 format!(
1313 "Failed to bind HTTP server to port {}: {}\n\
1314 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 {}",
1315 port, e, port, port
1316 )
1317 })?;
1318
1319 axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
1320 Ok(())
1321}
1322
1323async fn serve_with_tls(
1329 addr: std::net::SocketAddr,
1330 _app: Router,
1331 tls_config: &mockforge_core::config::HttpTlsConfig,
1332) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1333 let _acceptor = tls::load_tls_acceptor(tls_config)?;
1335
1336 Err(format!(
1339 "TLS/HTTPS support is configured but requires a reverse proxy (nginx) for production use.\n\
1340 Certificate validation passed: {} and {}\n\
1341 For native TLS support, please use a reverse proxy or wait for axum-server integration.\n\
1342 You can configure nginx with TLS termination pointing to the HTTP server on port {}.",
1343 tls_config.cert_file,
1344 tls_config.key_file,
1345 addr.port()
1346 )
1347 .into())
1348}
1349
1350pub async fn start(
1352 port: u16,
1353 spec_path: Option<String>,
1354 options: Option<ValidationOptions>,
1355) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1356 start_with_latency(port, spec_path, options, None).await
1357}
1358
1359pub async fn start_with_auth_and_latency(
1361 port: u16,
1362 spec_path: Option<String>,
1363 options: Option<ValidationOptions>,
1364 auth_config: Option<mockforge_core::config::AuthConfig>,
1365 latency_profile: Option<LatencyProfile>,
1366) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1367 start_with_auth_and_injectors(port, spec_path, options, auth_config, latency_profile, None)
1368 .await
1369}
1370
1371pub async fn start_with_auth_and_injectors(
1373 port: u16,
1374 spec_path: Option<String>,
1375 options: Option<ValidationOptions>,
1376 auth_config: Option<mockforge_core::config::AuthConfig>,
1377 _latency_profile: Option<LatencyProfile>,
1378 _failure_injector: Option<mockforge_core::FailureInjector>,
1379) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1380 let app = build_router_with_auth(spec_path, options, auth_config).await;
1382 serve_router(port, app).await
1383}
1384
1385pub async fn start_with_latency(
1387 port: u16,
1388 spec_path: Option<String>,
1389 options: Option<ValidationOptions>,
1390 latency_profile: Option<LatencyProfile>,
1391) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1392 let latency_injector =
1393 latency_profile.map(|profile| LatencyInjector::new(profile, Default::default()));
1394
1395 let app = build_router_with_latency(spec_path, options, latency_injector).await;
1396 serve_router(port, app).await
1397}
1398
1399pub async fn build_router_with_chains(
1401 spec_path: Option<String>,
1402 options: Option<ValidationOptions>,
1403 circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1404) -> Router {
1405 build_router_with_chains_and_multi_tenant(
1406 spec_path,
1407 options,
1408 circling_config,
1409 None,
1410 None,
1411 None,
1412 None,
1413 None,
1414 None,
1415 None,
1416 false,
1417 None, None, None, None, )
1422 .await
1423}
1424
1425async fn apply_route_chaos(
1433 injector: Option<&dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1434 method: &axum::http::Method,
1435 uri: &axum::http::Uri,
1436) -> Option<axum::response::Response> {
1437 use axum::http::StatusCode;
1438 use axum::response::IntoResponse;
1439
1440 if let Some(injector) = injector {
1441 if let Some(fault_response) = injector.get_fault_response(method, uri) {
1443 let mut response = axum::Json(serde_json::json!({
1445 "error": fault_response.error_message,
1446 "fault_type": fault_response.fault_type,
1447 }))
1448 .into_response();
1449 *response.status_mut() = StatusCode::from_u16(fault_response.status_code)
1450 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1451 return Some(response);
1452 }
1453
1454 if let Err(e) = injector.inject_latency(method, uri).await {
1456 tracing::warn!("Failed to inject latency: {}", e);
1457 }
1458 }
1459
1460 None }
1462
1463#[allow(clippy::too_many_arguments)]
1465pub async fn build_router_with_chains_and_multi_tenant(
1466 spec_path: Option<String>,
1467 options: Option<ValidationOptions>,
1468 _circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1469 multi_tenant_config: Option<mockforge_core::MultiTenantConfig>,
1470 route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
1471 cors_config: Option<mockforge_core::config::HttpCorsConfig>,
1472 _ai_generator: Option<
1473 std::sync::Arc<dyn mockforge_core::openapi::response::AiGenerator + Send + Sync>,
1474 >,
1475 smtp_registry: Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
1476 mqtt_broker: Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
1477 traffic_shaper: Option<mockforge_core::traffic_shaping::TrafficShaper>,
1478 traffic_shaping_enabled: bool,
1479 health_manager: Option<std::sync::Arc<health::HealthManager>>,
1480 _mockai: Option<
1481 std::sync::Arc<tokio::sync::RwLock<mockforge_core::intelligent_behavior::MockAI>>,
1482 >,
1483 deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
1484 proxy_config: Option<mockforge_core::proxy::config::ProxyConfig>,
1485) -> Router {
1486 use crate::latency_profiles::LatencyProfiles;
1487 use crate::op_middleware::Shared;
1488 use mockforge_core::Overrides;
1489
1490 let template_expand =
1492 options.as_ref().map(|o| o.response_template_expand).unwrap_or_else(|| {
1493 std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
1494 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1495 .unwrap_or(false)
1496 });
1497
1498 let _shared = Shared {
1499 profiles: LatencyProfiles::default(),
1500 overrides: Overrides::default(),
1501 failure_injector: None,
1502 traffic_shaper,
1503 overrides_enabled: false,
1504 traffic_shaping_enabled,
1505 };
1506
1507 let mut app = Router::new();
1509 let mut include_default_health = true;
1510
1511 if let Some(ref spec) = spec_path {
1513 match OpenApiSpec::from_file(&spec).await {
1514 Ok(openapi) => {
1515 info!("Loaded OpenAPI spec from {}", spec);
1516
1517 let persona = load_persona_from_config().await;
1519
1520 let mut registry = if let Some(opts) = options {
1521 tracing::debug!("Using custom validation options");
1522 if let Some(ref persona) = persona {
1523 tracing::info!("Using persona '{}' for route generation", persona.name);
1524 }
1525 OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
1526 } else {
1527 tracing::debug!("Using environment-based options");
1528 if let Some(ref persona) = persona {
1529 tracing::info!("Using persona '{}' for route generation", persona.name);
1530 }
1531 OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
1532 };
1533
1534 let fixtures_dir = std::env::var("MOCKFORGE_FIXTURES_DIR")
1536 .unwrap_or_else(|_| "/app/fixtures".to_string());
1537 let custom_fixtures_enabled = std::env::var("MOCKFORGE_CUSTOM_FIXTURES_ENABLED")
1538 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1539 .unwrap_or(true); if custom_fixtures_enabled {
1542 use mockforge_core::CustomFixtureLoader;
1543 use std::path::PathBuf;
1544 use std::sync::Arc;
1545
1546 let fixtures_path = PathBuf::from(&fixtures_dir);
1547 let mut custom_loader = CustomFixtureLoader::new(fixtures_path, true);
1548
1549 if let Err(e) = custom_loader.load_fixtures().await {
1550 tracing::warn!("Failed to load custom fixtures: {}", e);
1551 } else {
1552 tracing::info!("Custom fixtures loaded from {}", fixtures_dir);
1553 registry = registry.with_custom_fixture_loader(Arc::new(custom_loader));
1554 }
1555 }
1556
1557 if registry
1558 .routes()
1559 .iter()
1560 .any(|route| route.method == "GET" && route.path == "/health")
1561 {
1562 include_default_health = false;
1563 }
1564 let spec_router = if let Some(ref mockai_instance) = _mockai {
1566 tracing::debug!("Building router with MockAI support");
1567 registry.build_router_with_mockai(Some(mockai_instance.clone()))
1568 } else {
1569 registry.build_router()
1570 };
1571 app = app.merge(spec_router);
1572 }
1573 Err(e) => {
1574 warn!("Failed to load OpenAPI spec from {:?}: {}. Starting without OpenAPI integration.", spec_path, e);
1575 }
1576 }
1577 }
1578
1579 let route_chaos_injector: Option<
1583 std::sync::Arc<dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1584 > = if let Some(ref route_configs) = route_configs {
1585 if !route_configs.is_empty() {
1586 match mockforge_route_chaos::RouteChaosInjector::new(route_configs.clone()) {
1587 Ok(injector) => {
1588 info!(
1589 "Initialized advanced routing features for {} route(s)",
1590 route_configs.len()
1591 );
1592 Some(std::sync::Arc::new(injector)
1593 as std::sync::Arc<
1594 dyn mockforge_core::priority_handler::RouteChaosInjectorTrait,
1595 >)
1596 }
1597 Err(e) => {
1598 warn!(
1599 "Failed to initialize advanced routing features: {}. Using basic routing.",
1600 e
1601 );
1602 None
1603 }
1604 }
1605 } else {
1606 None
1607 }
1608 } else {
1609 None
1610 };
1611
1612 if let Some(route_configs) = route_configs {
1613 use axum::http::StatusCode;
1614 use axum::response::IntoResponse;
1615
1616 if !route_configs.is_empty() {
1617 info!("Registering {} custom route(s) from config", route_configs.len());
1618 }
1619
1620 let injector = route_chaos_injector.clone();
1621 for route_config in route_configs {
1622 let status = route_config.response.status;
1623 let body = route_config.response.body.clone();
1624 let headers = route_config.response.headers.clone();
1625 let path = route_config.path.clone();
1626 let method = route_config.method.clone();
1627
1628 let expected_method = method.to_uppercase();
1633 let injector_clone = injector.clone();
1637 app = app.route(
1638 &path,
1639 #[allow(clippy::non_send_fields_in_send_ty)]
1640 axum::routing::any(move |req: axum::http::Request<axum::body::Body>| {
1641 let body = body.clone();
1642 let headers = headers.clone();
1643 let expand = template_expand;
1644 let expected = expected_method.clone();
1645 let status_code = status;
1646 let injector_for_chaos = injector_clone.clone();
1648
1649 async move {
1650 if req.method().as_str() != expected.as_str() {
1652 return axum::response::Response::builder()
1654 .status(axum::http::StatusCode::METHOD_NOT_ALLOWED)
1655 .header("Allow", &expected)
1656 .body(axum::body::Body::empty())
1657 .unwrap()
1658 .into_response();
1659 }
1660
1661 if let Some(fault_response) = apply_route_chaos(
1665 injector_for_chaos.as_deref(),
1666 req.method(),
1667 req.uri(),
1668 )
1669 .await
1670 {
1671 return fault_response;
1672 }
1673
1674 let mut body_value = body.unwrap_or(serde_json::json!({}));
1676
1677 if expand {
1681 use mockforge_template_expansion::RequestContext;
1682 use serde_json::Value;
1683 use std::collections::HashMap;
1684
1685 let method = req.method().to_string();
1687 let path = req.uri().path().to_string();
1688
1689 let query_params: HashMap<String, Value> = req
1691 .uri()
1692 .query()
1693 .map(|q| {
1694 url::form_urlencoded::parse(q.as_bytes())
1695 .into_owned()
1696 .map(|(k, v)| (k, Value::String(v)))
1697 .collect()
1698 })
1699 .unwrap_or_default();
1700
1701 let headers: HashMap<String, Value> = req
1703 .headers()
1704 .iter()
1705 .map(|(k, v)| {
1706 (
1707 k.to_string(),
1708 Value::String(v.to_str().unwrap_or_default().to_string()),
1709 )
1710 })
1711 .collect();
1712
1713 let context = RequestContext {
1717 method,
1718 path,
1719 query_params,
1720 headers,
1721 body: None, path_params: HashMap::new(),
1723 multipart_fields: HashMap::new(),
1724 multipart_files: HashMap::new(),
1725 };
1726
1727 let body_value_clone = body_value.clone();
1731 let context_clone = context.clone();
1732 body_value = match tokio::task::spawn_blocking(move || {
1733 mockforge_template_expansion::expand_templates_in_json(
1734 body_value_clone,
1735 &context_clone,
1736 )
1737 })
1738 .await
1739 {
1740 Ok(result) => result,
1741 Err(_) => body_value, };
1743 }
1744
1745 let mut response = axum::Json(body_value).into_response();
1746
1747 *response.status_mut() =
1749 StatusCode::from_u16(status_code).unwrap_or(StatusCode::OK);
1750
1751 for (key, value) in headers {
1753 if let Ok(header_name) =
1754 axum::http::HeaderName::from_bytes(key.as_bytes())
1755 {
1756 if let Ok(header_value) = axum::http::HeaderValue::from_str(&value)
1757 {
1758 response.headers_mut().insert(header_name, header_value);
1759 }
1760 }
1761 }
1762
1763 response
1764 }
1765 }),
1766 );
1767
1768 debug!("Registered route: {} {}", method, path);
1769 }
1770 }
1771
1772 if let Some(health) = health_manager {
1774 app = app.merge(health::health_router(health));
1776 info!(
1777 "Health check endpoints enabled: /health, /health/live, /health/ready, /health/startup"
1778 );
1779 } else if include_default_health {
1780 app = app.route(
1782 "/health",
1783 axum::routing::get(|| async {
1784 use mockforge_core::server_utils::health::HealthStatus;
1785 {
1786 match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1788 Ok(value) => axum::Json(value),
1789 Err(e) => {
1790 tracing::error!("Failed to serialize health status: {}", e);
1792 axum::Json(serde_json::json!({
1793 "status": "healthy",
1794 "service": "mockforge-http",
1795 "uptime_seconds": 0
1796 }))
1797 }
1798 }
1799 }
1800 }),
1801 );
1802 }
1803
1804 app = app.merge(sse::sse_router());
1805 app = app.merge(file_server::file_serving_router());
1807
1808 let spec_path_clone = spec_path.clone();
1810 let management_state = ManagementState::new(None, spec_path_clone, 3000); use std::sync::Arc;
1814 let ws_state = WsManagementState::new();
1815 let ws_broadcast = Arc::new(ws_state.tx.clone());
1816 let management_state = management_state.with_ws_broadcast(ws_broadcast);
1817
1818 let management_state = if let Some(proxy_cfg) = proxy_config {
1820 use tokio::sync::RwLock;
1821 let proxy_config_arc = Arc::new(RwLock::new(proxy_cfg));
1822 management_state.with_proxy_config(proxy_config_arc)
1823 } else {
1824 management_state
1825 };
1826
1827 #[cfg(feature = "smtp")]
1828 let management_state = {
1829 if let Some(smtp_reg) = smtp_registry {
1830 match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
1831 Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
1832 Err(e) => {
1833 error!(
1834 "Invalid SMTP registry type passed to HTTP management state: {:?}",
1835 e.type_id()
1836 );
1837 management_state
1838 }
1839 }
1840 } else {
1841 management_state
1842 }
1843 };
1844 #[cfg(not(feature = "smtp"))]
1845 let management_state = {
1846 let _ = smtp_registry;
1847 management_state
1848 };
1849 #[cfg(feature = "mqtt")]
1850 let management_state = {
1851 if let Some(broker) = mqtt_broker {
1852 match broker.downcast::<mockforge_mqtt::MqttBroker>() {
1853 Ok(broker) => management_state.with_mqtt_broker(broker),
1854 Err(e) => {
1855 error!(
1856 "Invalid MQTT broker passed to HTTP management state: {:?}",
1857 e.type_id()
1858 );
1859 management_state
1860 }
1861 }
1862 } else {
1863 management_state
1864 }
1865 };
1866 #[cfg(not(feature = "mqtt"))]
1867 let management_state = {
1868 let _ = mqtt_broker;
1869 management_state
1870 };
1871 app = app.nest("/__mockforge/api", management_router(management_state));
1872
1873 app = app.merge(verification_router());
1875
1876 use crate::auth::oidc::oidc_router;
1878 app = app.merge(oidc_router());
1879
1880 {
1882 use mockforge_core::security::get_global_access_review_service;
1883 if let Some(service) = get_global_access_review_service().await {
1884 use crate::handlers::access_review::{access_review_router, AccessReviewState};
1885 let review_state = AccessReviewState { service };
1886 app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
1887 debug!("Access review API mounted at /api/v1/security/access-reviews");
1888 }
1889 }
1890
1891 {
1893 use mockforge_core::security::get_global_privileged_access_manager;
1894 if let Some(manager) = get_global_privileged_access_manager().await {
1895 use crate::handlers::privileged_access::{
1896 privileged_access_router, PrivilegedAccessState,
1897 };
1898 let privileged_state = PrivilegedAccessState { manager };
1899 app = app.nest(
1900 "/api/v1/security/privileged-access",
1901 privileged_access_router(privileged_state),
1902 );
1903 debug!("Privileged access API mounted at /api/v1/security/privileged-access");
1904 }
1905 }
1906
1907 {
1909 use mockforge_core::security::get_global_change_management_engine;
1910 if let Some(engine) = get_global_change_management_engine().await {
1911 use crate::handlers::change_management::{
1912 change_management_router, ChangeManagementState,
1913 };
1914 let change_state = ChangeManagementState { engine };
1915 app = app.nest("/api/v1/change-management", change_management_router(change_state));
1916 debug!("Change management API mounted at /api/v1/change-management");
1917 }
1918 }
1919
1920 {
1922 use mockforge_core::security::get_global_risk_assessment_engine;
1923 if let Some(engine) = get_global_risk_assessment_engine().await {
1924 use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
1925 let risk_state = RiskAssessmentState { engine };
1926 app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
1927 debug!("Risk assessment API mounted at /api/v1/security/risks");
1928 }
1929 }
1930
1931 {
1933 use crate::auth::token_lifecycle::TokenLifecycleManager;
1934 use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
1935 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1936 let lifecycle_state = TokenLifecycleState {
1937 manager: lifecycle_manager,
1938 };
1939 app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
1940 debug!("Token lifecycle API mounted at /api/v1/auth");
1941 }
1942
1943 {
1945 use crate::auth::oidc::load_oidc_state;
1946 use crate::auth::token_lifecycle::TokenLifecycleManager;
1947 use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
1948 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1950 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1951 let oauth2_state = OAuth2ServerState {
1952 oidc_state,
1953 lifecycle_manager,
1954 auth_codes: Arc::new(RwLock::new(HashMap::new())),
1955 };
1956 app = app.merge(oauth2_server_router(oauth2_state));
1957 debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
1958 }
1959
1960 {
1962 use crate::auth::oidc::load_oidc_state;
1963 use crate::auth::risk_engine::RiskEngine;
1964 use crate::auth::token_lifecycle::TokenLifecycleManager;
1965 use crate::handlers::consent::{consent_router, ConsentState};
1966 use crate::handlers::oauth2_server::OAuth2ServerState;
1967 let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1969 let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1970 let oauth2_state = OAuth2ServerState {
1971 oidc_state: oidc_state.clone(),
1972 lifecycle_manager: lifecycle_manager.clone(),
1973 auth_codes: Arc::new(RwLock::new(HashMap::new())),
1974 };
1975 let risk_engine = Arc::new(RiskEngine::default());
1976 let consent_state = ConsentState {
1977 oauth2_state,
1978 risk_engine,
1979 };
1980 app = app.merge(consent_router(consent_state));
1981 debug!("Consent screen endpoints mounted at /consent");
1982 }
1983
1984 {
1986 use crate::auth::risk_engine::RiskEngine;
1987 use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
1988 let risk_engine = Arc::new(RiskEngine::default());
1989 let risk_state = RiskSimulationState { risk_engine };
1990 app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
1991 debug!("Risk simulation API mounted at /api/v1/auth/risk");
1992 }
1993
1994 let database = {
1996 use crate::database::Database;
1997 let database_url = std::env::var("DATABASE_URL").ok();
1998 match Database::connect_optional(database_url.as_deref()).await {
1999 Ok(db) => {
2000 if db.is_connected() {
2001 if let Err(e) = db.migrate_if_connected().await {
2003 warn!("Failed to run database migrations: {}", e);
2004 } else {
2005 info!("Database connected and migrations applied");
2006 }
2007 }
2008 Some(db)
2009 }
2010 Err(e) => {
2011 warn!("Failed to connect to database: {}. Continuing without database support.", e);
2012 None
2013 }
2014 }
2015 };
2016
2017 let (drift_engine, incident_manager, drift_config) = {
2020 use mockforge_core::contract_drift::{DriftBudgetConfig, DriftBudgetEngine};
2021 use mockforge_core::incidents::{IncidentManager, IncidentStore};
2022 use std::sync::Arc;
2023
2024 let drift_config = DriftBudgetConfig::default();
2026 let drift_engine = Arc::new(DriftBudgetEngine::new(drift_config.clone()));
2027
2028 let incident_store = Arc::new(IncidentStore::default());
2030 let incident_manager = Arc::new(IncidentManager::new(incident_store.clone()));
2031
2032 (drift_engine, incident_manager, drift_config)
2033 };
2034
2035 {
2036 use crate::handlers::drift_budget::{drift_budget_router, DriftBudgetState};
2037 use crate::middleware::drift_tracking::DriftTrackingState;
2038 use mockforge_core::ai_contract_diff::ContractDiffAnalyzer;
2039 use mockforge_core::consumer_contracts::{ConsumerBreakingChangeDetector, UsageRecorder};
2040 use std::sync::Arc;
2041
2042 let usage_recorder = Arc::new(UsageRecorder::default());
2044 let consumer_detector =
2045 Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2046
2047 let diff_analyzer = if drift_config.enabled {
2049 match ContractDiffAnalyzer::new(
2050 mockforge_core::ai_contract_diff::ContractDiffConfig::default(),
2051 ) {
2052 Ok(analyzer) => Some(Arc::new(analyzer)),
2053 Err(e) => {
2054 warn!("Failed to create contract diff analyzer: {}", e);
2055 None
2056 }
2057 }
2058 } else {
2059 None
2060 };
2061
2062 let spec = if let Some(ref spec_path) = spec_path {
2065 match mockforge_core::openapi::OpenApiSpec::from_file(spec_path).await {
2066 Ok(s) => Some(Arc::new(s)),
2067 Err(e) => {
2068 debug!("Failed to load OpenAPI spec for drift tracking: {}", e);
2069 None
2070 }
2071 }
2072 } else {
2073 None
2074 };
2075
2076 let drift_tracking_state = DriftTrackingState {
2078 diff_analyzer,
2079 spec,
2080 drift_engine: drift_engine.clone(),
2081 incident_manager: incident_manager.clone(),
2082 usage_recorder,
2083 consumer_detector,
2084 enabled: drift_config.enabled,
2085 };
2086
2087 app = app.layer(axum::middleware::from_fn(crate::middleware::buffer_response_middleware));
2089
2090 let drift_tracking_state_clone = drift_tracking_state.clone();
2093 app = app.layer(axum::middleware::from_fn(
2094 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2095 let state = drift_tracking_state_clone.clone();
2096 async move {
2097 if req
2099 .extensions()
2100 .get::<crate::middleware::drift_tracking::DriftTrackingState>()
2101 .is_none()
2102 {
2103 req.extensions_mut().insert(state);
2104 }
2105 crate::middleware::drift_tracking::drift_tracking_middleware_with_extensions(
2107 req, next,
2108 )
2109 .await
2110 }
2111 },
2112 ));
2113
2114 let drift_state = DriftBudgetState {
2115 engine: drift_engine.clone(),
2116 incident_manager: incident_manager.clone(),
2117 gitops_handler: None, };
2119
2120 app = app.merge(drift_budget_router(drift_state));
2121 debug!("Drift budget and incident management endpoints mounted at /api/v1/drift");
2122 }
2123
2124 #[cfg(feature = "pipelines")]
2126 {
2127 use crate::handlers::pipelines::{pipeline_router, PipelineState};
2128
2129 let pipeline_state = PipelineState::new();
2130 app = app.merge(pipeline_router(pipeline_state));
2131 debug!("Pipeline management endpoints mounted at /api/v1/pipelines");
2132 }
2133
2134 {
2136 use crate::handlers::contract_health::{contract_health_router, ContractHealthState};
2137 use crate::handlers::forecasting::{forecasting_router, ForecastingState};
2138 use crate::handlers::semantic_drift::{semantic_drift_router, SemanticDriftState};
2139 use crate::handlers::threat_modeling::{threat_modeling_router, ThreatModelingState};
2140 use mockforge_core::contract_drift::forecasting::{Forecaster, ForecastingConfig};
2141 use mockforge_core::contract_drift::threat_modeling::{
2142 ThreatAnalyzer, ThreatModelingConfig,
2143 };
2144 use mockforge_core::incidents::semantic_manager::SemanticIncidentManager;
2145 use std::sync::Arc;
2146
2147 let forecasting_config = ForecastingConfig::default();
2149 let forecaster = Arc::new(Forecaster::new(forecasting_config));
2150 let forecasting_state = ForecastingState {
2151 forecaster,
2152 database: database.clone(),
2153 };
2154
2155 let semantic_manager = Arc::new(SemanticIncidentManager::new());
2157 let semantic_state = SemanticDriftState {
2158 manager: semantic_manager,
2159 database: database.clone(),
2160 };
2161
2162 let threat_config = ThreatModelingConfig::default();
2164 let threat_analyzer = match ThreatAnalyzer::new(threat_config) {
2165 Ok(analyzer) => Arc::new(analyzer),
2166 Err(e) => {
2167 warn!("Failed to create threat analyzer: {}. Using default.", e);
2168 Arc::new(ThreatAnalyzer::new(ThreatModelingConfig::default()).unwrap_or_else(
2169 |_| {
2170 ThreatAnalyzer::new(ThreatModelingConfig {
2172 enabled: false,
2173 ..Default::default()
2174 })
2175 .expect("Failed to create fallback threat analyzer")
2176 },
2177 ))
2178 }
2179 };
2180 let mut webhook_configs = Vec::new();
2182 let config_paths = [
2183 "config.yaml",
2184 "mockforge.yaml",
2185 "tools/mockforge/config.yaml",
2186 "../tools/mockforge/config.yaml",
2187 ];
2188
2189 for path in &config_paths {
2190 if let Ok(config) = mockforge_core::config::load_config(path).await {
2191 if !config.incidents.webhooks.is_empty() {
2192 webhook_configs = config.incidents.webhooks.clone();
2193 info!("Loaded {} webhook configs from config: {}", webhook_configs.len(), path);
2194 break;
2195 }
2196 }
2197 }
2198
2199 if webhook_configs.is_empty() {
2200 debug!("No webhook configs found in config files, using empty list");
2201 }
2202
2203 let threat_state = ThreatModelingState {
2204 analyzer: threat_analyzer,
2205 webhook_configs,
2206 database: database.clone(),
2207 };
2208
2209 let contract_health_state = ContractHealthState {
2211 incident_manager: incident_manager.clone(),
2212 semantic_manager: Arc::new(SemanticIncidentManager::new()),
2213 database: database.clone(),
2214 };
2215
2216 app = app.merge(forecasting_router(forecasting_state));
2218 debug!("Forecasting endpoints mounted at /api/v1/forecasts");
2219
2220 app = app.merge(semantic_drift_router(semantic_state));
2221 debug!("Semantic drift endpoints mounted at /api/v1/semantic-drift");
2222
2223 app = app.merge(threat_modeling_router(threat_state));
2224 debug!("Threat modeling endpoints mounted at /api/v1/threats");
2225
2226 app = app.merge(contract_health_router(contract_health_state));
2227 debug!("Contract health endpoints mounted at /api/v1/contract-health");
2228 }
2229
2230 {
2232 use crate::handlers::protocol_contracts::{
2233 protocol_contracts_router, ProtocolContractState,
2234 };
2235 use mockforge_core::contract_drift::{
2236 ConsumerImpactAnalyzer, FitnessFunctionRegistry, ProtocolContractRegistry,
2237 };
2238 use std::sync::Arc;
2239 use tokio::sync::RwLock;
2240
2241 let contract_registry = Arc::new(RwLock::new(ProtocolContractRegistry::new()));
2243
2244 let mut fitness_registry = FitnessFunctionRegistry::new();
2246
2247 let config_paths = [
2249 "config.yaml",
2250 "mockforge.yaml",
2251 "tools/mockforge/config.yaml",
2252 "../tools/mockforge/config.yaml",
2253 ];
2254
2255 let mut config_loaded = false;
2256 for path in &config_paths {
2257 if let Ok(config) = mockforge_core::config::load_config(path).await {
2258 if !config.contracts.fitness_rules.is_empty() {
2259 if let Err(e) =
2260 fitness_registry.load_from_config(&config.contracts.fitness_rules)
2261 {
2262 warn!("Failed to load fitness rules from config {}: {}", path, e);
2263 } else {
2264 info!(
2265 "Loaded {} fitness rules from config: {}",
2266 config.contracts.fitness_rules.len(),
2267 path
2268 );
2269 config_loaded = true;
2270 break;
2271 }
2272 }
2273 }
2274 }
2275
2276 if !config_loaded {
2277 debug!("No fitness rules found in config files, using empty registry");
2278 }
2279
2280 let fitness_registry = Arc::new(RwLock::new(fitness_registry));
2281
2282 let consumer_mapping_registry =
2286 mockforge_core::contract_drift::ConsumerMappingRegistry::new();
2287 let consumer_analyzer =
2288 Arc::new(RwLock::new(ConsumerImpactAnalyzer::new(consumer_mapping_registry)));
2289
2290 let protocol_state = ProtocolContractState {
2291 registry: contract_registry,
2292 drift_engine: Some(drift_engine.clone()),
2293 incident_manager: Some(incident_manager.clone()),
2294 fitness_registry: Some(fitness_registry),
2295 consumer_analyzer: Some(consumer_analyzer),
2296 };
2297
2298 app = app.nest("/api/v1/contracts", protocol_contracts_router(protocol_state));
2299 debug!("Protocol contracts endpoints mounted at /api/v1/contracts");
2300 }
2301
2302 #[cfg(feature = "behavioral-cloning")]
2304 {
2305 use crate::middleware::behavioral_cloning::BehavioralCloningMiddlewareState;
2306 use std::path::PathBuf;
2307
2308 let db_path = std::env::var("RECORDER_DATABASE_PATH")
2310 .ok()
2311 .map(PathBuf::from)
2312 .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2313
2314 let bc_middleware_state = if let Some(path) = db_path {
2315 BehavioralCloningMiddlewareState::with_database_path(path)
2316 } else {
2317 BehavioralCloningMiddlewareState::new()
2318 };
2319
2320 let enabled = std::env::var("BEHAVIORAL_CLONING_ENABLED")
2322 .ok()
2323 .and_then(|v| v.parse::<bool>().ok())
2324 .unwrap_or(false);
2325
2326 if enabled {
2327 let bc_state_clone = bc_middleware_state.clone();
2328 app = app.layer(axum::middleware::from_fn(
2329 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2330 let state = bc_state_clone.clone();
2331 async move {
2332 if req.extensions().get::<BehavioralCloningMiddlewareState>().is_none() {
2334 req.extensions_mut().insert(state);
2335 }
2336 crate::middleware::behavioral_cloning::behavioral_cloning_middleware(
2338 req, next,
2339 )
2340 .await
2341 }
2342 },
2343 ));
2344 debug!("Behavioral cloning middleware enabled (applies learned behavior to requests)");
2345 }
2346 }
2347
2348 {
2350 use crate::handlers::consumer_contracts::{
2351 consumer_contracts_router, ConsumerContractsState,
2352 };
2353 use mockforge_core::consumer_contracts::{
2354 ConsumerBreakingChangeDetector, ConsumerRegistry, UsageRecorder,
2355 };
2356 use std::sync::Arc;
2357
2358 let registry = Arc::new(ConsumerRegistry::default());
2360
2361 let usage_recorder = Arc::new(UsageRecorder::default());
2363
2364 let detector = Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2366
2367 let consumer_state = ConsumerContractsState {
2368 registry,
2369 usage_recorder,
2370 detector,
2371 };
2372
2373 app = app.merge(consumer_contracts_router(consumer_state));
2374 debug!("Consumer contracts endpoints mounted at /api/v1/consumers");
2375 }
2376
2377 #[cfg(feature = "behavioral-cloning")]
2379 {
2380 use crate::handlers::behavioral_cloning::{
2381 behavioral_cloning_router, BehavioralCloningState,
2382 };
2383 use std::path::PathBuf;
2384
2385 let db_path = std::env::var("RECORDER_DATABASE_PATH")
2387 .ok()
2388 .map(PathBuf::from)
2389 .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2390
2391 let bc_state = if let Some(path) = db_path {
2392 BehavioralCloningState::with_database_path(path)
2393 } else {
2394 BehavioralCloningState::new()
2395 };
2396
2397 app = app.merge(behavioral_cloning_router(bc_state));
2398 debug!("Behavioral cloning endpoints mounted at /api/v1/behavioral-cloning");
2399 }
2400
2401 {
2403 use crate::consistency::{ConsistencyMiddlewareState, HttpAdapter};
2404 use crate::handlers::consistency::{consistency_router, ConsistencyState};
2405 use mockforge_core::consistency::ConsistencyEngine;
2406 use std::sync::Arc;
2407
2408 let consistency_engine = Arc::new(ConsistencyEngine::new());
2410
2411 let http_adapter = Arc::new(HttpAdapter::new(consistency_engine.clone()));
2413 consistency_engine.register_adapter(http_adapter.clone()).await;
2414
2415 let consistency_state = ConsistencyState {
2417 engine: consistency_engine.clone(),
2418 };
2419
2420 use crate::handlers::xray::XRayState;
2422 let xray_state = Arc::new(XRayState {
2423 engine: consistency_engine.clone(),
2424 request_contexts: std::sync::Arc::new(tokio::sync::RwLock::new(
2425 std::collections::HashMap::new(),
2426 )),
2427 });
2428
2429 let consistency_middleware_state = ConsistencyMiddlewareState {
2431 engine: consistency_engine.clone(),
2432 adapter: http_adapter,
2433 xray_state: Some(xray_state.clone()),
2434 };
2435
2436 let consistency_middleware_state_clone = consistency_middleware_state.clone();
2438 app = app.layer(axum::middleware::from_fn(
2439 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2440 let state = consistency_middleware_state_clone.clone();
2441 async move {
2442 if req.extensions().get::<ConsistencyMiddlewareState>().is_none() {
2444 req.extensions_mut().insert(state);
2445 }
2446 crate::consistency::middleware::consistency_middleware(req, next).await
2448 }
2449 },
2450 ));
2451
2452 app = app.merge(consistency_router(consistency_state));
2454 debug!("Consistency engine initialized and endpoints mounted at /api/v1/consistency");
2455
2456 {
2458 use crate::handlers::fidelity::{fidelity_router, FidelityState};
2459 let fidelity_state = FidelityState::new();
2460 app = app.merge(fidelity_router(fidelity_state));
2461 debug!("Fidelity score endpoints mounted at /api/v1/workspace/:workspace_id/fidelity");
2462 }
2463
2464 {
2466 use crate::handlers::scenario_studio::{scenario_studio_router, ScenarioStudioState};
2467 let scenario_studio_state = ScenarioStudioState::new();
2468 app = app.merge(scenario_studio_router(scenario_studio_state));
2469 debug!("Scenario Studio endpoints mounted at /api/v1/scenario-studio");
2470 }
2471
2472 {
2474 use crate::handlers::performance::{performance_router, PerformanceState};
2475 let performance_state = PerformanceState::new();
2476 app = app.nest("/api/performance", performance_router(performance_state));
2477 debug!("Performance mode endpoints mounted at /api/performance");
2478 }
2479
2480 {
2482 use crate::handlers::world_state::{world_state_router, WorldStateState};
2483 use mockforge_world_state::WorldStateEngine;
2484 use std::sync::Arc;
2485 use tokio::sync::RwLock;
2486
2487 let world_state_engine = Arc::new(RwLock::new(WorldStateEngine::new()));
2488 let world_state_state = WorldStateState {
2489 engine: world_state_engine,
2490 };
2491 app = app.nest("/api/world-state", world_state_router().with_state(world_state_state));
2492 debug!("World state endpoints mounted at /api/world-state");
2493 }
2494
2495 {
2497 use crate::handlers::snapshots::{snapshot_router, SnapshotState};
2498 use mockforge_core::snapshots::SnapshotManager;
2499 use std::path::PathBuf;
2500
2501 let snapshot_dir = std::env::var("MOCKFORGE_SNAPSHOT_DIR").ok().map(PathBuf::from);
2502 let snapshot_manager = Arc::new(SnapshotManager::new(snapshot_dir));
2503
2504 let snapshot_state = SnapshotState {
2505 manager: snapshot_manager,
2506 consistency_engine: Some(consistency_engine.clone()),
2507 workspace_persistence: None, vbr_engine: None, recorder: None, };
2511
2512 app = app.merge(snapshot_router(snapshot_state));
2513 debug!("Snapshot management endpoints mounted at /api/v1/snapshots");
2514
2515 {
2517 use crate::handlers::xray::xray_router;
2518 app = app.merge(xray_router((*xray_state).clone()));
2519 debug!("X-Ray API endpoints mounted at /api/v1/xray");
2520 }
2521 }
2522
2523 {
2525 use crate::handlers::ab_testing::{ab_testing_router, ABTestingState};
2526 use crate::middleware::ab_testing::ab_testing_middleware;
2527
2528 let ab_testing_state = ABTestingState::new();
2529
2530 let ab_testing_state_clone = ab_testing_state.clone();
2532 app = app.layer(axum::middleware::from_fn(
2533 move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2534 let state = ab_testing_state_clone.clone();
2535 async move {
2536 if req.extensions().get::<ABTestingState>().is_none() {
2538 req.extensions_mut().insert(state);
2539 }
2540 ab_testing_middleware(req, next).await
2542 }
2543 },
2544 ));
2545
2546 app = app.merge(ab_testing_router(ab_testing_state));
2548 debug!("A/B testing endpoints mounted at /api/v1/ab-tests");
2549 }
2550 }
2551
2552 {
2554 use crate::handlers::pr_generation::{pr_generation_router, PRGenerationState};
2555 use mockforge_core::pr_generation::{PRGenerator, PRProvider};
2556 use std::sync::Arc;
2557
2558 let pr_config = mockforge_core::pr_generation::PRGenerationConfig::from_env();
2560
2561 let generator = if pr_config.enabled && pr_config.token.is_some() {
2562 let token = pr_config.token.as_ref().unwrap().clone();
2563 let generator = match pr_config.provider {
2564 PRProvider::GitHub => PRGenerator::new_github(
2565 pr_config.owner.clone(),
2566 pr_config.repo.clone(),
2567 token,
2568 pr_config.base_branch.clone(),
2569 ),
2570 PRProvider::GitLab => PRGenerator::new_gitlab(
2571 pr_config.owner.clone(),
2572 pr_config.repo.clone(),
2573 token,
2574 pr_config.base_branch.clone(),
2575 ),
2576 };
2577 Some(Arc::new(generator))
2578 } else {
2579 None
2580 };
2581
2582 let pr_state = PRGenerationState {
2583 generator: generator.clone(),
2584 };
2585
2586 app = app.merge(pr_generation_router(pr_state));
2587 if generator.is_some() {
2588 debug!(
2589 "PR generation endpoints mounted at /api/v1/pr (configured for {:?})",
2590 pr_config.provider
2591 );
2592 } else {
2593 debug!("PR generation endpoints mounted at /api/v1/pr (not configured - set GITHUB_TOKEN/GITLAB_TOKEN and PR_REPO_OWNER/PR_REPO_NAME)");
2594 }
2595 }
2596
2597 app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
2599
2600 if let Some(mt_config) = multi_tenant_config {
2602 if mt_config.enabled {
2603 use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
2604 use std::sync::Arc;
2605
2606 info!(
2607 "Multi-tenant mode enabled with {} routing strategy",
2608 match mt_config.routing_strategy {
2609 mockforge_core::RoutingStrategy::Path => "path-based",
2610 mockforge_core::RoutingStrategy::Port => "port-based",
2611 mockforge_core::RoutingStrategy::Both => "hybrid",
2612 }
2613 );
2614
2615 let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
2617
2618 let default_workspace =
2620 mockforge_core::Workspace::new(mt_config.default_workspace.clone());
2621 if let Err(e) =
2622 registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
2623 {
2624 warn!("Failed to register default workspace: {}", e);
2625 } else {
2626 info!("Registered default workspace: '{}'", mt_config.default_workspace);
2627 }
2628
2629 let registry = Arc::new(registry);
2631
2632 let _workspace_router = WorkspaceRouter::new(registry);
2634 info!("Workspace routing middleware initialized for HTTP server");
2635 }
2636 }
2637
2638 let mut final_cors_config = cors_config;
2640 let mut production_headers: Option<std::sync::Arc<std::collections::HashMap<String, String>>> =
2641 None;
2642 let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
2644 let mut rate_limit_config = crate::middleware::RateLimitConfig {
2645 requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
2646 .ok()
2647 .and_then(|v| v.parse().ok())
2648 .unwrap_or(1000),
2649 burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
2650 .ok()
2651 .and_then(|v| v.parse().ok())
2652 .unwrap_or(2000),
2653 per_ip: true,
2654 per_endpoint: false,
2655 };
2656
2657 if let Some(deploy_config) = &deceptive_deploy_config {
2658 if deploy_config.enabled {
2659 info!("Deceptive deploy mode enabled - applying production-like configuration");
2660
2661 if let Some(prod_cors) = &deploy_config.cors {
2663 final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
2664 enabled: true,
2665 allowed_origins: prod_cors.allowed_origins.clone(),
2666 allowed_methods: prod_cors.allowed_methods.clone(),
2667 allowed_headers: prod_cors.allowed_headers.clone(),
2668 allow_credentials: prod_cors.allow_credentials,
2669 });
2670 info!("Applied production-like CORS configuration");
2671 }
2672
2673 if let Some(prod_rate_limit) = &deploy_config.rate_limit {
2675 rate_limit_config = crate::middleware::RateLimitConfig {
2676 requests_per_minute: prod_rate_limit.requests_per_minute,
2677 burst: prod_rate_limit.burst,
2678 per_ip: prod_rate_limit.per_ip,
2679 per_endpoint: false,
2680 };
2681 info!(
2682 "Applied production-like rate limiting: {} req/min, burst: {}",
2683 prod_rate_limit.requests_per_minute, prod_rate_limit.burst
2684 );
2685 }
2686
2687 if !deploy_config.headers.is_empty() {
2689 let headers_map: std::collections::HashMap<String, String> =
2690 deploy_config.headers.clone();
2691 production_headers = Some(std::sync::Arc::new(headers_map));
2692 info!("Configured {} production headers", deploy_config.headers.len());
2693 }
2694
2695 if let Some(prod_oauth) = &deploy_config.oauth {
2697 let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
2698 deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
2699 oauth2: Some(oauth2_config),
2700 ..Default::default()
2701 });
2702 info!("Applied production-like OAuth configuration for deceptive deploy");
2703 }
2704 }
2705 }
2706
2707 let rate_limiter =
2709 std::sync::Arc::new(crate::middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
2710
2711 let mut state = HttpServerState::new().with_rate_limiter(rate_limiter.clone());
2712
2713 if let Some(headers) = production_headers.clone() {
2715 state = state.with_production_headers(headers);
2716 }
2717
2718 app = app.layer(from_fn_with_state(state.clone(), crate::middleware::rate_limit_middleware));
2720
2721 if state.production_headers.is_some() {
2723 app = app.layer(from_fn_with_state(
2724 state.clone(),
2725 crate::middleware::production_headers_middleware,
2726 ));
2727 }
2728
2729 if let Some(auth_config) = deceptive_deploy_auth_config {
2731 use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
2732 use std::collections::HashMap;
2733 use std::sync::Arc;
2734 use tokio::sync::RwLock;
2735
2736 let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
2738 match create_oauth2_client(oauth2_config) {
2739 Ok(client) => Some(client),
2740 Err(e) => {
2741 warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
2742 None
2743 }
2744 }
2745 } else {
2746 None
2747 };
2748
2749 let auth_state = AuthState {
2751 config: auth_config,
2752 spec: None, oauth2_client,
2754 introspection_cache: Arc::new(RwLock::new(HashMap::new())),
2755 };
2756
2757 app = app.layer(axum::middleware::from_fn_with_state(auth_state, auth_middleware));
2759 info!("Applied OAuth authentication middleware from deceptive deploy configuration");
2760 }
2761
2762 #[cfg(feature = "runtime-daemon")]
2764 {
2765 use mockforge_runtime_daemon::{AutoGenerator, NotFoundDetector, RuntimeDaemonConfig};
2766 use std::sync::Arc;
2767
2768 let daemon_config = RuntimeDaemonConfig::from_env();
2770
2771 if daemon_config.enabled {
2772 info!("Runtime daemon enabled - auto-creating mocks from 404s");
2773
2774 let management_api_url =
2776 std::env::var("MOCKFORGE_MANAGEMENT_API_URL").unwrap_or_else(|_| {
2777 let port =
2778 std::env::var("MOCKFORGE_HTTP_PORT").unwrap_or_else(|_| "3000".to_string());
2779 format!("http://localhost:{}", port)
2780 });
2781
2782 let generator = Arc::new(AutoGenerator::new(daemon_config.clone(), management_api_url));
2784
2785 let detector = NotFoundDetector::new(daemon_config.clone());
2787 detector.set_generator(generator).await;
2788
2789 let detector_clone = detector.clone();
2791 app = app.layer(axum::middleware::from_fn(
2792 move |req: axum::extract::Request, next: axum::middleware::Next| {
2793 let detector = detector_clone.clone();
2794 async move { detector.detect_and_auto_create(req, next).await }
2795 },
2796 ));
2797
2798 debug!("Runtime daemon 404 detection middleware added");
2799 }
2800 }
2801
2802 app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
2805
2806 app = apply_cors_middleware(app, final_cors_config);
2808
2809 app
2810}
2811
2812#[test]
2816fn test_route_info_clone() {
2817 let route = RouteInfo {
2818 method: "POST".to_string(),
2819 path: "/users".to_string(),
2820 operation_id: Some("createUser".to_string()),
2821 summary: None,
2822 description: None,
2823 parameters: vec![],
2824 };
2825
2826 let cloned = route.clone();
2827 assert_eq!(route.method, cloned.method);
2828 assert_eq!(route.path, cloned.path);
2829 assert_eq!(route.operation_id, cloned.operation_id);
2830}
2831
2832#[test]
2833fn test_http_server_state_new() {
2834 let state = HttpServerState::new();
2835 assert_eq!(state.routes.len(), 0);
2836}
2837
2838#[test]
2839fn test_http_server_state_with_routes() {
2840 let routes = vec![
2841 RouteInfo {
2842 method: "GET".to_string(),
2843 path: "/users".to_string(),
2844 operation_id: Some("getUsers".to_string()),
2845 summary: None,
2846 description: None,
2847 parameters: vec![],
2848 },
2849 RouteInfo {
2850 method: "POST".to_string(),
2851 path: "/users".to_string(),
2852 operation_id: Some("createUser".to_string()),
2853 summary: None,
2854 description: None,
2855 parameters: vec![],
2856 },
2857 ];
2858
2859 let state = HttpServerState::with_routes(routes.clone());
2860 assert_eq!(state.routes.len(), 2);
2861 assert_eq!(state.routes[0].method, "GET");
2862 assert_eq!(state.routes[1].method, "POST");
2863}
2864
2865#[test]
2866fn test_http_server_state_clone() {
2867 let routes = vec![RouteInfo {
2868 method: "GET".to_string(),
2869 path: "/test".to_string(),
2870 operation_id: None,
2871 summary: None,
2872 description: None,
2873 parameters: vec![],
2874 }];
2875
2876 let state = HttpServerState::with_routes(routes);
2877 let cloned = state.clone();
2878
2879 assert_eq!(state.routes.len(), cloned.routes.len());
2880 assert_eq!(state.routes[0].method, cloned.routes[0].method);
2881}
2882
2883#[tokio::test]
2884async fn test_build_router_without_openapi() {
2885 let _router = build_router(None, None, None).await;
2886 }
2888
2889#[tokio::test]
2890async fn test_build_router_with_nonexistent_spec() {
2891 let _router = build_router(Some("/nonexistent/spec.yaml".to_string()), None, None).await;
2892 }
2894
2895#[tokio::test]
2896async fn test_build_router_with_auth_and_latency() {
2897 let _router = build_router_with_auth_and_latency(None, None, None, None).await;
2898 }
2900
2901#[tokio::test]
2902async fn test_build_router_with_latency() {
2903 let _router = build_router_with_latency(None, None, None).await;
2904 }
2906
2907#[tokio::test]
2908async fn test_build_router_with_auth() {
2909 let _router = build_router_with_auth(None, None, None).await;
2910 }
2912
2913#[tokio::test]
2914async fn test_build_router_with_chains() {
2915 let _router = build_router_with_chains(None, None, None).await;
2916 }
2918
2919#[test]
2920fn test_route_info_with_all_fields() {
2921 let route = RouteInfo {
2922 method: "PUT".to_string(),
2923 path: "/users/{id}".to_string(),
2924 operation_id: Some("updateUser".to_string()),
2925 summary: Some("Update user".to_string()),
2926 description: Some("Updates an existing user".to_string()),
2927 parameters: vec!["id".to_string(), "body".to_string()],
2928 };
2929
2930 assert!(route.operation_id.is_some());
2931 assert!(route.summary.is_some());
2932 assert!(route.description.is_some());
2933 assert_eq!(route.parameters.len(), 2);
2934}
2935
2936#[test]
2937fn test_route_info_with_minimal_fields() {
2938 let route = RouteInfo {
2939 method: "DELETE".to_string(),
2940 path: "/users/{id}".to_string(),
2941 operation_id: None,
2942 summary: None,
2943 description: None,
2944 parameters: vec![],
2945 };
2946
2947 assert!(route.operation_id.is_none());
2948 assert!(route.summary.is_none());
2949 assert!(route.description.is_none());
2950 assert_eq!(route.parameters.len(), 0);
2951}
2952
2953#[test]
2954fn test_http_server_state_empty_routes() {
2955 let state = HttpServerState::with_routes(vec![]);
2956 assert_eq!(state.routes.len(), 0);
2957}
2958
2959#[test]
2960fn test_http_server_state_multiple_routes() {
2961 let routes = vec![
2962 RouteInfo {
2963 method: "GET".to_string(),
2964 path: "/users".to_string(),
2965 operation_id: Some("listUsers".to_string()),
2966 summary: Some("List all users".to_string()),
2967 description: None,
2968 parameters: vec![],
2969 },
2970 RouteInfo {
2971 method: "GET".to_string(),
2972 path: "/users/{id}".to_string(),
2973 operation_id: Some("getUser".to_string()),
2974 summary: Some("Get a user".to_string()),
2975 description: None,
2976 parameters: vec!["id".to_string()],
2977 },
2978 RouteInfo {
2979 method: "POST".to_string(),
2980 path: "/users".to_string(),
2981 operation_id: Some("createUser".to_string()),
2982 summary: Some("Create a user".to_string()),
2983 description: None,
2984 parameters: vec!["body".to_string()],
2985 },
2986 ];
2987
2988 let state = HttpServerState::with_routes(routes);
2989 assert_eq!(state.routes.len(), 3);
2990
2991 let methods: Vec<&str> = state.routes.iter().map(|r| r.method.as_str()).collect();
2993 assert!(methods.contains(&"GET"));
2994 assert!(methods.contains(&"POST"));
2995}
2996
2997#[test]
2998fn test_http_server_state_with_rate_limiter() {
2999 use std::sync::Arc;
3000
3001 let config = crate::middleware::RateLimitConfig::default();
3002 let rate_limiter = Arc::new(crate::middleware::GlobalRateLimiter::new(config));
3003
3004 let state = HttpServerState::new().with_rate_limiter(rate_limiter);
3005
3006 assert!(state.rate_limiter.is_some());
3007 assert_eq!(state.routes.len(), 0);
3008}
3009
3010#[tokio::test]
3011async fn test_build_router_includes_rate_limiter() {
3012 let _router = build_router(None, None, None).await;
3013 }