Skip to main content

mockforge_http/
lib.rs

1//! # MockForge HTTP
2//!
3//! HTTP/REST API mocking library for MockForge.
4//!
5//! This crate provides HTTP-specific functionality for creating mock REST APIs,
6//! including OpenAPI integration, request validation, AI-powered response generation,
7//! and management endpoints.
8//!
9//! ## Overview
10//!
11//! MockForge HTTP enables you to:
12//!
13//! - **Serve OpenAPI specs**: Automatically generate mock endpoints from OpenAPI/Swagger
14//! - **Validate requests**: Enforce schema validation with configurable modes
15//! - **AI-powered responses**: Generate intelligent responses using LLMs
16//! - **Management API**: Real-time monitoring, configuration, and control
17//! - **Request logging**: Comprehensive HTTP request/response logging
18//! - **Metrics collection**: Track performance and usage statistics
19//! - **Server-Sent Events**: Stream logs and metrics to clients
20//!
21//! ## Quick Start
22//!
23//! ### Basic HTTP Server from OpenAPI
24//!
25//! ```rust,no_run
26//! use axum::Router;
27//! use mockforge_core::openapi_routes::ValidationMode;
28//! use mockforge_core::ValidationOptions;
29//! use mockforge_http::build_router;
30//!
31//! #[tokio::main]
32//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
33//!     // Build router from OpenAPI specification
34//!     let router = build_router(
35//!         Some("./api-spec.json".to_string()),
36//!         Some(ValidationOptions {
37//!             request_mode: ValidationMode::Enforce,
38//!             ..ValidationOptions::default()
39//!         }),
40//!         None,
41//!     ).await;
42//!
43//!     // Start the server
44//!     let addr: std::net::SocketAddr = "0.0.0.0:3000".parse()?;
45//!     let listener = tokio::net::TcpListener::bind(addr).await?;
46//!     axum::serve(listener, router).await?;
47//!
48//!     Ok(())
49//! }
50//! ```
51//!
52//! ### With Management API
53//!
54//! Enable real-time monitoring and configuration:
55//!
56//! ```rust,no_run
57//! use mockforge_http::{management_router, ManagementState};
58//!
59//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
60//! let state = ManagementState::new(None, None, 3000);
61//!
62//! // Build management router
63//! let mgmt_router = management_router(state);
64//!
65//! // Mount under your main router
66//! let app = axum::Router::new()
67//!     .nest("/__mockforge", mgmt_router);
68//! # Ok(())
69//! # }
70//! ```
71//!
72//! ### AI-Powered Responses
73//!
74//! Generate intelligent responses based on request context:
75//!
76//! ```rust,no_run
77//! use mockforge_data::intelligent_mock::{IntelligentMockConfig, ResponseMode};
78//! use mockforge_http::{process_response_with_ai, AiResponseConfig};
79//! use serde_json::json;
80//!
81//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
82//! let ai_config = AiResponseConfig {
83//!     intelligent: Some(
84//!         IntelligentMockConfig::new(ResponseMode::Intelligent)
85//!             .with_prompt("Generate realistic user data".to_string()),
86//!     ),
87//!     drift: None,
88//! };
89//!
90//! let response = process_response_with_ai(
91//!     Some(json!({"name": "Alice"})),
92//!     ai_config
93//!         .intelligent
94//!         .clone()
95//!         .map(serde_json::to_value)
96//!         .transpose()?,
97//!     ai_config
98//!         .drift
99//!         .clone()
100//!         .map(serde_json::to_value)
101//!         .transpose()?,
102//! )
103//! .await?;
104//! # Ok(())
105//! # }
106//! ```
107//!
108//! ## Key Features
109//!
110//! ### OpenAPI Integration
111//! - Automatic endpoint generation from specs
112//! - Request/response validation
113//! - Schema-based mock data generation
114//!
115//! ### Management & Monitoring
116//! - [`management`]: REST API for server control and monitoring
117//! - [`management_ws`]: WebSocket API for real-time updates
118//! - [`sse`]: Server-Sent Events for log streaming
119//! - [`request_logging`]: Comprehensive request/response logging
120//! - [`metrics_middleware`]: Performance metrics collection
121//!
122//! ### Advanced Features
123//! - [`ai_handler`]: AI-powered response generation
124//! - [`auth`]: Authentication and authorization
125//! - [`chain_handlers`]: Multi-step request workflows
126//! - [`latency_profiles`]: Configurable latency simulation
127//! - [`replay_listing`]: Fixture management
128//!
129//! ## Middleware
130//!
131//! MockForge HTTP includes several middleware layers:
132//!
133//! - **Request Tracing**: [`http_tracing_middleware`] - Distributed tracing integration
134//! - **Metrics Collection**: [`metrics_middleware`] - Prometheus-compatible metrics
135//! - **Operation Metadata**: [`op_middleware`] - OpenAPI operation tracking
136//!
137//! ## Management API Endpoints
138//!
139//! When using the management router, these endpoints are available:
140//!
141//! - `GET /health` - Health check
142//! - `GET /stats` - Server statistics
143//! - `GET /logs` - Request logs (SSE stream)
144//! - `GET /metrics` - Performance metrics
145//! - `GET /fixtures` - List available fixtures
146//! - `POST /config/*` - Update configuration
147//!
148//! ## Examples
149//!
150//! See the [examples directory](https://github.com/SaaSy-Solutions/mockforge/tree/main/examples)
151//! for complete working examples.
152//!
153//! ## Related Crates
154//!
155//! - [`mockforge-core`](https://docs.rs/mockforge-core): Core mocking functionality
156//! - [`mockforge-data`](https://docs.rs/mockforge-data): Synthetic data generation
157//! - [`mockforge-plugin-core`](https://docs.rs/mockforge-plugin-core): Plugin development
158//!
159//! ## Documentation
160//!
161//! - [MockForge Book](https://docs.mockforge.dev/)
162//! - [HTTP Mocking Guide](https://docs.mockforge.dev/user-guide/http-mocking.html)
163//! - [API Reference](https://docs.rs/mockforge-http)
164
165pub mod ai_handler;
166pub mod auth;
167pub mod chain_handlers;
168/// Cross-protocol consistency engine integration for HTTP
169pub mod consistency;
170/// Contract diff middleware for automatic request capture
171pub mod contract_diff_middleware;
172pub mod coverage;
173pub mod database;
174/// File generation service for creating mock PDF, CSV, JSON files
175pub mod file_generator;
176/// File serving for generated mock files
177pub mod file_server;
178/// Kubernetes-native health check endpoints (liveness, readiness, startup probes)
179pub mod health;
180pub mod http_tracing_middleware;
181/// Latency profile configuration for HTTP request simulation
182pub mod latency_profiles;
183/// Management API for server control and monitoring
184pub mod management;
185/// WebSocket-based management API for real-time updates
186pub mod management_ws;
187pub mod metrics_middleware;
188pub mod middleware;
189pub mod op_middleware;
190/// Browser/Mobile Proxy Server
191pub mod proxy_server;
192/// Quick mock generation utilities
193pub mod quick_mock;
194/// RAG-powered AI response generation
195pub mod rag_ai_generator;
196/// Replay listing and fixture management
197pub mod replay_listing;
198pub mod request_logging;
199/// Specification import API for OpenAPI and AsyncAPI
200pub mod spec_import;
201/// Server-Sent Events for streaming logs and metrics
202pub mod sse;
203/// State machine API for scenario state machines
204pub mod state_machine_api;
205/// TLS/HTTPS support
206pub mod tls;
207/// Token response utilities
208pub mod token_response;
209/// UI Builder API for low-code mock endpoint creation
210pub mod ui_builder;
211/// Verification API for request verification
212pub mod verification;
213
214// Access review handlers
215pub mod handlers;
216
217// Re-export AI handler utilities
218pub use ai_handler::{process_response_with_ai, AiResponseConfig, AiResponseHandler};
219// Re-export health check utilities
220pub use health::{HealthManager, ServiceStatus};
221
222// Re-export management API utilities
223pub use management::{
224    management_router, management_router_with_ui_builder, ManagementState, MockConfig,
225    ServerConfig, ServerStats,
226};
227
228// Re-export UI Builder utilities
229pub use ui_builder::{create_ui_builder_router, EndpointConfig, UIBuilderState};
230
231// Re-export management WebSocket utilities
232pub use management_ws::{ws_management_router, MockEvent, WsManagementState};
233
234// Re-export verification API utilities
235pub use verification::verification_router;
236
237// Re-export metrics middleware
238pub use metrics_middleware::collect_http_metrics;
239
240// Re-export tracing middleware
241pub use http_tracing_middleware::http_tracing_middleware;
242
243// Re-export coverage utilities
244pub use coverage::{calculate_coverage, CoverageReport, MethodCoverage, RouteCoverage};
245
246/// Helper function to load persona from config file
247/// Tries to load from common config locations: config.yaml, mockforge.yaml, tools/mockforge/config.yaml
248async fn load_persona_from_config() -> Option<Arc<Persona>> {
249    use mockforge_core::config::load_config;
250
251    // Try common config file locations
252    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            // Access intelligent_behavior through mockai config
262            // Note: Config structure is mockai.intelligent_behavior.personas
263            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/// Route info for storing in state
311#[derive(Clone)]
312pub struct RouteInfo {
313    /// HTTP method (GET, POST, PUT, etc.)
314    pub method: String,
315    /// API path pattern (e.g., "/api/users/{id}")
316    pub path: String,
317    /// OpenAPI operation ID if available
318    pub operation_id: Option<String>,
319    /// Operation summary from OpenAPI spec
320    pub summary: Option<String>,
321    /// Operation description from OpenAPI spec
322    pub description: Option<String>,
323    /// List of parameter names for this route
324    pub parameters: Vec<String>,
325}
326
327/// Shared state for tracking OpenAPI routes
328#[derive(Clone)]
329pub struct HttpServerState {
330    /// List of registered routes from OpenAPI spec
331    pub routes: Vec<RouteInfo>,
332    /// Optional global rate limiter for request throttling
333    pub rate_limiter: Option<Arc<middleware::rate_limit::GlobalRateLimiter>>,
334    /// Production headers to add to all responses (for deceptive deploy)
335    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    /// Create a new empty HTTP server state
346    pub fn new() -> Self {
347        Self {
348            routes: Vec::new(),
349            rate_limiter: None,
350            production_headers: None,
351        }
352    }
353
354    /// Create HTTP server state with pre-configured routes
355    pub fn with_routes(routes: Vec<RouteInfo>) -> Self {
356        Self {
357            routes,
358            rate_limiter: None,
359            production_headers: None,
360        }
361    }
362
363    /// Add a rate limiter to the HTTP server state
364    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    /// Add production headers to the HTTP server state
373    pub fn with_production_headers(mut self, headers: Arc<HashMap<String, String>>) -> Self {
374        self.production_headers = Some(headers);
375        self
376    }
377}
378
379/// Handler to return OpenAPI routes information
380async 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
402/// Build the base HTTP router, optionally from an OpenAPI spec.
403pub 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
423/// Apply CORS middleware to the router based on configuration
424fn 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 is_wildcard_origin;
438
439        // Configure allowed origins
440        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            // Try to parse each origin, fallback to permissive if parsing fails
445            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                // If no valid origins, use permissive for development
455                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                // Use the first origin as exact match (tower-http limitation)
460                // For multiple origins, we'd need a custom implementation
461                if origins.len() == 1 {
462                    cors_layer = cors_layer.allow_origin(origins[0].clone());
463                    is_wildcard_origin = false;
464                } else {
465                    // Multiple origins - use permissive for now
466                    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            // No origins specified, use permissive for development
476            cors_layer = cors_layer.allow_origin(Any);
477            is_wildcard_origin = true;
478        }
479
480        // Configure allowed methods
481        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            // Default to common HTTP methods
489            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        // Configure allowed headers
500        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            // Default headers
511            cors_layer =
512                cors_layer.allow_headers([http::header::CONTENT_TYPE, http::header::AUTHORIZATION]);
513        }
514
515        // Configure credentials - cannot allow credentials with wildcard origin
516        // Determine if credentials should be allowed
517        // Cannot allow credentials with wildcard origin per CORS spec
518        let should_allow_credentials = if is_wildcard_origin {
519            // Wildcard origin - credentials must be false
520            false
521        } else {
522            // Specific origins - use config value (defaults to false)
523            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        // No CORS config provided - use permissive CORS for development
535        // Note: permissive() allows credentials, but since it uses wildcard origin,
536        // we need to disable credentials to avoid CORS spec violation
537        debug!("No CORS config provided, using permissive CORS for development");
538        // Create a permissive CORS layer but disable credentials to avoid CORS spec violation
539        // (cannot combine credentials with wildcard origin)
540        app.layer(CorsLayer::permissive().allow_credentials(false))
541    }
542}
543
544/// Build the base HTTP router with multi-tenant workspace support
545#[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    // Set up the basic router
563    let mut app = Router::new();
564
565    // Initialize rate limiter with default configuration
566    // Can be customized via environment variables or config
567    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    // Apply deceptive deploy configuration if enabled
581    let mut final_cors_config = cors_config;
582    let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
583    // Auth config from deceptive deploy OAuth (if configured)
584    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            // Override CORS config if provided
591            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            // Override rate limit config if provided
603            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            // Set production headers
617            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            // Integrate OAuth config from deceptive deploy
624            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    // Add production headers to state if configured
641    if let Some(headers) = production_headers.clone() {
642        state = state.with_production_headers(headers);
643    }
644
645    // Clone spec_path for later use
646    let spec_path_for_mgmt = spec_path.clone();
647
648    // If an OpenAPI spec is provided, integrate it
649    if let Some(spec_path) = spec_path {
650        tracing::debug!("Processing OpenAPI spec path: {}", spec_path);
651
652        // Measure OpenAPI spec loading
653        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                // Measure route registry creation
663                tracing::debug!("Creating OpenAPI route registry...");
664                let registry_start = Instant::now();
665
666                // Try to load persona from config if available
667                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                // Measure route extraction
690                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                // Measure overrides loading
708                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                // Measure router building
731                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    // Add basic health check endpoint
771    app = app.route(
772        "/health",
773        axum::routing::get(|| async {
774            use mockforge_core::server_utils::health::HealthStatus;
775            {
776                // HealthStatus should always serialize, but handle errors gracefully
777                match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
778                    Ok(value) => Json(value),
779                    Err(e) => {
780                        // Log error but return a simple healthy response
781                        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    // Add SSE endpoints
793    .merge(sse::sse_router())
794    // Add file serving endpoints for generated mock files
795    .merge(file_server::file_serving_router());
796
797    // Clone state for routes_router since we'll use it for middleware too
798    let state_for_routes = state.clone();
799
800    // Create a router with state for the routes and coverage endpoints
801    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    // Merge the routes router with the main app
807    app = app.merge(routes_router);
808
809    // Add static coverage UI
810    // Determine the path to the coverage.html file
811    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    // Check if the file exists before serving it
815    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    // Add management API endpoints
829    let management_state = ManagementState::new(None, spec_path_for_mgmt, 3000); // Port will be updated when we know the actual port
830
831    // Create WebSocket state and connect it to management state
832    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    // Note: ProxyConfig not available in this build function path
838    // Migration endpoints will work once ProxyConfig is passed to build_router_with_chains_and_multi_tenant
839
840    #[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    // Add verification API endpoint
864    app = app.merge(verification_router());
865
866    // Add OIDC well-known endpoints
867    use crate::auth::oidc::oidc_router;
868    app = app.merge(oidc_router());
869
870    // Add access review API if enabled
871    {
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    // Add privileged access API if enabled
882    {
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    // Add change management API if enabled
898    {
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    // Add risk assessment API if enabled
911    {
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    // Add token lifecycle API
922    {
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    // Add OAuth2 server endpoints
934    {
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        // Load OIDC state from configuration (environment variables or config file)
939        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            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
946        };
947        app = app.merge(oauth2_server_router(oauth2_state));
948        debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
949    }
950
951    // Add consent screen endpoints
952    {
953        use crate::auth::oidc::load_oidc_state;
954        use crate::auth::risk_engine::RiskEngine;
955        use crate::auth::token_lifecycle::TokenLifecycleManager;
956        use crate::handlers::consent::{consent_router, ConsentState};
957        use crate::handlers::oauth2_server::OAuth2ServerState;
958        // Load OIDC state from configuration (environment variables or config file)
959        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
960        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
961        let oauth2_state = OAuth2ServerState {
962            oidc_state: oidc_state.clone(),
963            lifecycle_manager: lifecycle_manager.clone(),
964            auth_codes: Arc::new(RwLock::new(HashMap::new())),
965            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
966        };
967        let risk_engine = Arc::new(RiskEngine::default());
968        let consent_state = ConsentState {
969            oauth2_state,
970            risk_engine,
971        };
972        app = app.merge(consent_router(consent_state));
973        debug!("Consent screen endpoints mounted at /consent");
974    }
975
976    // Add risk simulation API
977    {
978        use crate::auth::risk_engine::RiskEngine;
979        use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
980        let risk_engine = Arc::new(RiskEngine::default());
981        let risk_state = RiskSimulationState { risk_engine };
982        app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
983        debug!("Risk simulation API mounted at /api/v1/auth/risk");
984    }
985
986    // Add management WebSocket endpoint
987    app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
988
989    // Add request logging middleware to capture all requests
990    app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));
991
992    // Add security middleware for security event tracking (after logging, before contract diff)
993    app = app.layer(axum::middleware::from_fn(middleware::security_middleware));
994
995    // Add contract diff middleware for automatic request capture
996    // This captures requests for contract diff analysis (after logging)
997    app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
998
999    // Add rate limiting middleware (before logging to rate limit early)
1000    app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));
1001
1002    // Add production headers middleware if configured
1003    if state.production_headers.is_some() {
1004        app =
1005            app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
1006    }
1007
1008    // Add authentication middleware if OAuth is configured via deceptive deploy
1009    if let Some(auth_config) = deceptive_deploy_auth_config {
1010        use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1011        use std::collections::HashMap;
1012        use std::sync::Arc;
1013        use tokio::sync::RwLock;
1014
1015        // Create OAuth2 client if configured
1016        let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
1017            match create_oauth2_client(oauth2_config) {
1018                Ok(client) => Some(client),
1019                Err(e) => {
1020                    warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
1021                    None
1022                }
1023            }
1024        } else {
1025            None
1026        };
1027
1028        // Create auth state
1029        let auth_state = AuthState {
1030            config: auth_config,
1031            spec: None, // OpenAPI spec not available in this context
1032            oauth2_client,
1033            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1034        };
1035
1036        // Apply auth middleware
1037        app = app.layer(from_fn_with_state(auth_state, auth_middleware));
1038        info!("Applied OAuth authentication middleware from deceptive deploy configuration");
1039    }
1040
1041    // Add CORS middleware (use final_cors_config which may be overridden by deceptive deploy)
1042    app = apply_cors_middleware(app, final_cors_config);
1043
1044    // Add workspace routing middleware if multi-tenant is enabled
1045    if let Some(mt_config) = multi_tenant_config {
1046        if mt_config.enabled {
1047            use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
1048            use std::sync::Arc;
1049
1050            info!(
1051                "Multi-tenant mode enabled with {} routing strategy",
1052                match mt_config.routing_strategy {
1053                    mockforge_core::RoutingStrategy::Path => "path-based",
1054                    mockforge_core::RoutingStrategy::Port => "port-based",
1055                    mockforge_core::RoutingStrategy::Both => "hybrid",
1056                }
1057            );
1058
1059            // Create the multi-tenant workspace registry
1060            let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
1061
1062            // Register the default workspace before wrapping in Arc
1063            let default_workspace =
1064                mockforge_core::Workspace::new(mt_config.default_workspace.clone());
1065            if let Err(e) =
1066                registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
1067            {
1068                warn!("Failed to register default workspace: {}", e);
1069            } else {
1070                info!("Registered default workspace: '{}'", mt_config.default_workspace);
1071            }
1072
1073            // Auto-discover and register workspaces if configured
1074            if mt_config.auto_discover {
1075                if let Some(config_dir) = &mt_config.config_directory {
1076                    let config_path = Path::new(config_dir);
1077                    if config_path.exists() && config_path.is_dir() {
1078                        match fs::read_dir(config_path).await {
1079                            Ok(mut entries) => {
1080                                while let Ok(Some(entry)) = entries.next_entry().await {
1081                                    let path = entry.path();
1082                                    if path.extension() == Some(OsStr::new("yaml")) {
1083                                        match fs::read_to_string(&path).await {
1084                                            Ok(content) => {
1085                                                match serde_yaml::from_str::<
1086                                                    mockforge_core::Workspace,
1087                                                >(
1088                                                    &content
1089                                                ) {
1090                                                    Ok(workspace) => {
1091                                                        if let Err(e) = registry.register_workspace(
1092                                                            workspace.id.clone(),
1093                                                            workspace,
1094                                                        ) {
1095                                                            warn!("Failed to register auto-discovered workspace from {:?}: {}", path, e);
1096                                                        } else {
1097                                                            info!("Auto-registered workspace from {:?}", path);
1098                                                        }
1099                                                    }
1100                                                    Err(e) => {
1101                                                        warn!("Failed to parse workspace from {:?}: {}", path, e);
1102                                                    }
1103                                                }
1104                                            }
1105                                            Err(e) => {
1106                                                warn!(
1107                                                    "Failed to read workspace file {:?}: {}",
1108                                                    path, e
1109                                                );
1110                                            }
1111                                        }
1112                                    }
1113                                }
1114                            }
1115                            Err(e) => {
1116                                warn!("Failed to read config directory {:?}: {}", config_path, e);
1117                            }
1118                        }
1119                    } else {
1120                        warn!(
1121                            "Config directory {:?} does not exist or is not a directory",
1122                            config_path
1123                        );
1124                    }
1125                }
1126            }
1127
1128            // Wrap registry in Arc for shared access
1129            let registry = Arc::new(registry);
1130
1131            // Create workspace router and wrap the app with workspace middleware
1132            let _workspace_router = WorkspaceRouter::new(registry);
1133
1134            // Note: The actual middleware integration would need to be implemented
1135            // in the WorkspaceRouter to work with Axum's middleware system
1136            info!("Workspace routing middleware initialized for HTTP server");
1137        }
1138    }
1139
1140    let total_startup_duration = startup_start.elapsed();
1141    info!("HTTP router startup completed (total time: {:?})", total_startup_duration);
1142
1143    app
1144}
1145
1146/// Build the base HTTP router with authentication and latency support
1147pub async fn build_router_with_auth_and_latency(
1148    spec_path: Option<String>,
1149    _options: Option<()>,
1150    auth_config: Option<mockforge_core::config::AuthConfig>,
1151    latency_injector: Option<LatencyInjector>,
1152) -> Router {
1153    // Build auth router first, then layer latency on top
1154    let mut app = build_router_with_auth(spec_path.clone(), None, auth_config).await;
1155
1156    // Apply latency injection middleware if configured
1157    if let Some(injector) = latency_injector {
1158        let injector = Arc::new(injector);
1159        app = app.layer(axum::middleware::from_fn(move |req, next: axum::middleware::Next| {
1160            let injector = injector.clone();
1161            async move {
1162                let _ = injector.inject_latency(&[]).await;
1163                next.run(req).await
1164            }
1165        }));
1166    }
1167
1168    app
1169}
1170
1171/// Build the base HTTP router with latency injection support
1172pub async fn build_router_with_latency(
1173    spec_path: Option<String>,
1174    options: Option<ValidationOptions>,
1175    latency_injector: Option<LatencyInjector>,
1176) -> Router {
1177    if let Some(spec) = &spec_path {
1178        match OpenApiSpec::from_file(spec).await {
1179            Ok(openapi) => {
1180                let registry = if let Some(opts) = options {
1181                    OpenApiRouteRegistry::new_with_options(openapi, opts)
1182                } else {
1183                    OpenApiRouteRegistry::new_with_env(openapi)
1184                };
1185
1186                if let Some(injector) = latency_injector {
1187                    return registry.build_router_with_latency(injector);
1188                } else {
1189                    return registry.build_router();
1190                }
1191            }
1192            Err(e) => {
1193                warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec, e);
1194            }
1195        }
1196    }
1197
1198    build_router(None, None, None).await
1199}
1200
1201/// Build the base HTTP router with authentication support
1202pub async fn build_router_with_auth(
1203    spec_path: Option<String>,
1204    options: Option<ValidationOptions>,
1205    auth_config: Option<mockforge_core::config::AuthConfig>,
1206) -> Router {
1207    use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1208    use std::sync::Arc;
1209
1210    // If richer faker is available, register provider once (idempotent)
1211    #[cfg(feature = "data-faker")]
1212    {
1213        register_core_faker_provider();
1214    }
1215
1216    // Set up authentication state
1217    let spec = if let Some(spec_path) = &spec_path {
1218        match OpenApiSpec::from_file(&spec_path).await {
1219            Ok(spec) => Some(Arc::new(spec)),
1220            Err(e) => {
1221                warn!("Failed to load OpenAPI spec for auth: {}", e);
1222                None
1223            }
1224        }
1225    } else {
1226        None
1227    };
1228
1229    // Create OAuth2 client if configured
1230    let oauth2_client = if let Some(auth_config) = &auth_config {
1231        if let Some(oauth2_config) = &auth_config.oauth2 {
1232            match create_oauth2_client(oauth2_config) {
1233                Ok(client) => Some(client),
1234                Err(e) => {
1235                    warn!("Failed to create OAuth2 client: {}", e);
1236                    None
1237                }
1238            }
1239        } else {
1240            None
1241        }
1242    } else {
1243        None
1244    };
1245
1246    let auth_state = AuthState {
1247        config: auth_config.unwrap_or_default(),
1248        spec,
1249        oauth2_client,
1250        introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1251    };
1252
1253    // Set up the basic router with auth state
1254    let mut app = Router::new().with_state(auth_state.clone());
1255
1256    // If an OpenAPI spec is provided, integrate it
1257    if let Some(spec_path) = spec_path {
1258        match OpenApiSpec::from_file(&spec_path).await {
1259            Ok(openapi) => {
1260                info!("Loaded OpenAPI spec from {}", spec_path);
1261                let registry = if let Some(opts) = options {
1262                    OpenApiRouteRegistry::new_with_options(openapi, opts)
1263                } else {
1264                    OpenApiRouteRegistry::new_with_env(openapi)
1265                };
1266
1267                app = registry.build_router();
1268            }
1269            Err(e) => {
1270                warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
1271            }
1272        }
1273    }
1274
1275    // Add basic health check endpoint
1276    app = app.route(
1277        "/health",
1278        axum::routing::get(|| async {
1279            use mockforge_core::server_utils::health::HealthStatus;
1280            {
1281                // HealthStatus should always serialize, but handle errors gracefully
1282                match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1283                    Ok(value) => Json(value),
1284                    Err(e) => {
1285                        // Log error but return a simple healthy response
1286                        tracing::error!("Failed to serialize health status: {}", e);
1287                        Json(serde_json::json!({
1288                            "status": "healthy",
1289                            "service": "mockforge-http",
1290                            "uptime_seconds": 0
1291                        }))
1292                    }
1293                }
1294            }
1295        }),
1296    )
1297    // Add SSE endpoints
1298    .merge(sse::sse_router())
1299    // Add file serving endpoints for generated mock files
1300    .merge(file_server::file_serving_router())
1301    // Add authentication middleware (before logging)
1302    .layer(from_fn_with_state(auth_state.clone(), auth_middleware))
1303    // Add request logging middleware
1304    .layer(axum::middleware::from_fn(request_logging::log_http_requests));
1305
1306    app
1307}
1308
1309/// Serve a provided router on the given port.
1310pub async fn serve_router(
1311    port: u16,
1312    app: Router,
1313) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1314    serve_router_with_tls(port, app, None).await
1315}
1316
1317/// Serve a provided router on the given port with optional TLS support.
1318pub async fn serve_router_with_tls(
1319    port: u16,
1320    app: Router,
1321    tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1322) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1323    use std::net::SocketAddr;
1324
1325    let addr = mockforge_core::wildcard_socket_addr(port);
1326
1327    if let Some(ref tls) = tls_config {
1328        if tls.enabled {
1329            info!("HTTPS listening on {}", addr);
1330            return serve_with_tls(addr, app, tls).await;
1331        }
1332    }
1333
1334    info!("HTTP listening on {}", addr);
1335
1336    let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
1337        format!(
1338            "Failed to bind HTTP server to port {}: {}\n\
1339             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 {}",
1340            port, e, port, port
1341        )
1342    })?;
1343
1344    axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
1345    Ok(())
1346}
1347
1348/// Serve router with TLS/HTTPS support using axum-server
1349///
1350/// This function implements native TLS serving using axum-server and tokio-rustls.
1351/// It supports standard TLS and mutual TLS (mTLS) based on the configuration.
1352async fn serve_with_tls(
1353    addr: std::net::SocketAddr,
1354    app: Router,
1355    tls_config: &mockforge_core::config::HttpTlsConfig,
1356) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1357    use axum_server::tls_rustls::RustlsConfig;
1358    use std::net::SocketAddr;
1359
1360    // Initialize the rustls crypto provider (must be called before TLS operations)
1361    tls::init_crypto_provider();
1362
1363    info!("Loading TLS configuration for HTTPS server");
1364
1365    // Load TLS server configuration (supports mTLS)
1366    let server_config = tls::load_tls_server_config(tls_config)?;
1367
1368    // Create RustlsConfig from the ServerConfig
1369    // Note: axum-server's RustlsConfig can be created from a ServerConfig
1370    let rustls_config = RustlsConfig::from_config(server_config);
1371
1372    info!("Starting HTTPS server on {}", addr);
1373
1374    // Serve with TLS using axum-server
1375    axum_server::bind_rustls(addr, rustls_config)
1376        .serve(app.into_make_service_with_connect_info::<SocketAddr>())
1377        .await
1378        .map_err(|e| format!("HTTPS server error: {}", e).into())
1379}
1380
1381/// Backwards-compatible start that builds + serves the base router.
1382pub async fn start(
1383    port: u16,
1384    spec_path: Option<String>,
1385    options: Option<ValidationOptions>,
1386) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1387    start_with_latency(port, spec_path, options, None).await
1388}
1389
1390/// Start HTTP server with authentication and latency support
1391pub async fn start_with_auth_and_latency(
1392    port: u16,
1393    spec_path: Option<String>,
1394    options: Option<ValidationOptions>,
1395    auth_config: Option<mockforge_core::config::AuthConfig>,
1396    latency_profile: Option<LatencyProfile>,
1397) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1398    start_with_auth_and_injectors(port, spec_path, options, auth_config, latency_profile, None)
1399        .await
1400}
1401
1402/// Start HTTP server with authentication and injectors support
1403pub async fn start_with_auth_and_injectors(
1404    port: u16,
1405    spec_path: Option<String>,
1406    options: Option<ValidationOptions>,
1407    auth_config: Option<mockforge_core::config::AuthConfig>,
1408    _latency_profile: Option<LatencyProfile>,
1409    _failure_injector: Option<FailureInjector>,
1410) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1411    // For now, ignore latency and failure injectors and just use auth
1412    let app = build_router_with_auth(spec_path, options, auth_config).await;
1413    serve_router(port, app).await
1414}
1415
1416/// Start HTTP server with latency injection support
1417pub async fn start_with_latency(
1418    port: u16,
1419    spec_path: Option<String>,
1420    options: Option<ValidationOptions>,
1421    latency_profile: Option<LatencyProfile>,
1422) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1423    let latency_injector =
1424        latency_profile.map(|profile| LatencyInjector::new(profile, Default::default()));
1425
1426    let app = build_router_with_latency(spec_path, options, latency_injector).await;
1427    serve_router(port, app).await
1428}
1429
1430/// Build the base HTTP router with chaining support
1431pub async fn build_router_with_chains(
1432    spec_path: Option<String>,
1433    options: Option<ValidationOptions>,
1434    circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1435) -> Router {
1436    build_router_with_chains_and_multi_tenant(
1437        spec_path,
1438        options,
1439        circling_config,
1440        None,
1441        None,
1442        None,
1443        None,
1444        None,
1445        None,
1446        None,
1447        false,
1448        None, // health_manager
1449        None, // mockai
1450        None, // deceptive_deploy_config
1451        None, // proxy_config
1452    )
1453    .await
1454}
1455
1456// Template expansion is now handled by mockforge_core::template_expansion
1457// which is explicitly isolated from the templating module to avoid Send issues
1458
1459/// Helper function to apply route chaos injection (fault injection and latency)
1460/// This is extracted to avoid capturing RouteChaosInjector in the closure, which causes Send issues
1461/// Uses mockforge-route-chaos crate which is isolated from mockforge-core to avoid Send issues
1462/// Uses the RouteChaosInjectorTrait from mockforge-core to avoid circular dependency
1463async fn apply_route_chaos(
1464    injector: Option<&dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1465    method: &http::Method,
1466    uri: &http::Uri,
1467) -> Option<axum::response::Response> {
1468    use axum::http::StatusCode;
1469    use axum::response::IntoResponse;
1470
1471    if let Some(injector) = injector {
1472        // Check for fault injection first
1473        if let Some(fault_response) = injector.get_fault_response(method, uri) {
1474            // Return fault response
1475            let mut response = Json(serde_json::json!({
1476                "error": fault_response.error_message,
1477                "fault_type": fault_response.fault_type,
1478            }))
1479            .into_response();
1480            *response.status_mut() = StatusCode::from_u16(fault_response.status_code)
1481                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1482            return Some(response);
1483        }
1484
1485        // Inject latency if configured (this is async and may delay the request)
1486        if let Err(e) = injector.inject_latency(method, uri).await {
1487            tracing::warn!("Failed to inject latency: {}", e);
1488        }
1489    }
1490
1491    None // No fault response, processing should continue
1492}
1493
1494/// Build the base HTTP router with chaining and multi-tenant support
1495#[allow(clippy::too_many_arguments)]
1496pub async fn build_router_with_chains_and_multi_tenant(
1497    spec_path: Option<String>,
1498    options: Option<ValidationOptions>,
1499    _circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1500    multi_tenant_config: Option<mockforge_core::MultiTenantConfig>,
1501    route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
1502    cors_config: Option<mockforge_core::config::HttpCorsConfig>,
1503    _ai_generator: Option<Arc<dyn mockforge_core::openapi::response::AiGenerator + Send + Sync>>,
1504    smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
1505    mqtt_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
1506    traffic_shaper: Option<mockforge_core::traffic_shaping::TrafficShaper>,
1507    traffic_shaping_enabled: bool,
1508    health_manager: Option<Arc<HealthManager>>,
1509    _mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
1510    deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
1511    proxy_config: Option<mockforge_core::proxy::config::ProxyConfig>,
1512) -> Router {
1513    use crate::latency_profiles::LatencyProfiles;
1514    use crate::op_middleware::Shared;
1515    use mockforge_core::Overrides;
1516
1517    // Extract template expansion setting before options is moved (used in OpenAPI routes and custom routes)
1518    let template_expand =
1519        options.as_ref().map(|o| o.response_template_expand).unwrap_or_else(|| {
1520            std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
1521                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1522                .unwrap_or(false)
1523        });
1524
1525    let _shared = Shared {
1526        profiles: LatencyProfiles::default(),
1527        overrides: Overrides::default(),
1528        failure_injector: None,
1529        traffic_shaper,
1530        overrides_enabled: false,
1531        traffic_shaping_enabled,
1532    };
1533
1534    // Start with basic router
1535    let mut app = Router::new();
1536    let mut include_default_health = true;
1537    let mut captured_routes: Vec<RouteInfo> = Vec::new();
1538
1539    // If an OpenAPI spec is provided, integrate it
1540    if let Some(ref spec) = spec_path {
1541        match OpenApiSpec::from_file(&spec).await {
1542            Ok(openapi) => {
1543                info!("Loaded OpenAPI spec from {}", spec);
1544
1545                // Try to load persona from config if available
1546                let persona = load_persona_from_config().await;
1547
1548                let mut registry = if let Some(opts) = options {
1549                    tracing::debug!("Using custom validation options");
1550                    if let Some(ref persona) = persona {
1551                        tracing::info!("Using persona '{}' for route generation", persona.name);
1552                    }
1553                    OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
1554                } else {
1555                    tracing::debug!("Using environment-based options");
1556                    if let Some(ref persona) = persona {
1557                        tracing::info!("Using persona '{}' for route generation", persona.name);
1558                    }
1559                    OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
1560                };
1561
1562                // Load custom fixtures if enabled
1563                let fixtures_dir = std::env::var("MOCKFORGE_FIXTURES_DIR")
1564                    .unwrap_or_else(|_| "/app/fixtures".to_string());
1565                let custom_fixtures_enabled = std::env::var("MOCKFORGE_CUSTOM_FIXTURES_ENABLED")
1566                    .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1567                    .unwrap_or(true); // Enabled by default
1568
1569                if custom_fixtures_enabled {
1570                    use mockforge_core::CustomFixtureLoader;
1571                    use std::path::PathBuf;
1572                    use std::sync::Arc;
1573
1574                    let fixtures_path = PathBuf::from(&fixtures_dir);
1575                    let mut custom_loader = CustomFixtureLoader::new(fixtures_path, true);
1576
1577                    if let Err(e) = custom_loader.load_fixtures().await {
1578                        tracing::warn!("Failed to load custom fixtures: {}", e);
1579                    } else {
1580                        tracing::info!("Custom fixtures loaded from {}", fixtures_dir);
1581                        registry = registry.with_custom_fixture_loader(Arc::new(custom_loader));
1582                    }
1583                }
1584
1585                if registry
1586                    .routes()
1587                    .iter()
1588                    .any(|route| route.method == "GET" && route.path == "/health")
1589                {
1590                    include_default_health = false;
1591                }
1592                // Capture route info for the /__mockforge/routes endpoint
1593                captured_routes = registry
1594                    .routes()
1595                    .iter()
1596                    .map(|r| RouteInfo {
1597                        method: r.method.clone(),
1598                        path: r.path.clone(),
1599                        operation_id: r.operation.operation_id.clone(),
1600                        summary: r.operation.summary.clone(),
1601                        description: r.operation.description.clone(),
1602                        parameters: r.parameters.clone(),
1603                    })
1604                    .collect();
1605
1606                // Store routes in the global route store so the admin server
1607                // can serve them without proxying back to the HTTP server.
1608                {
1609                    let global_routes: Vec<mockforge_core::request_logger::GlobalRouteInfo> =
1610                        captured_routes
1611                            .iter()
1612                            .map(|r| mockforge_core::request_logger::GlobalRouteInfo {
1613                                method: r.method.clone(),
1614                                path: r.path.clone(),
1615                                operation_id: r.operation_id.clone(),
1616                                summary: r.summary.clone(),
1617                                description: r.description.clone(),
1618                                parameters: r.parameters.clone(),
1619                            })
1620                            .collect();
1621                    mockforge_core::request_logger::set_global_routes(global_routes);
1622                    tracing::info!("Stored {} routes in global route store", captured_routes.len());
1623                }
1624
1625                // Use MockAI if available, otherwise use standard router
1626                let spec_router = if let Some(ref mockai_instance) = _mockai {
1627                    tracing::debug!("Building router with MockAI support");
1628                    registry.build_router_with_mockai(Some(mockai_instance.clone()))
1629                } else {
1630                    registry.build_router()
1631                };
1632                app = app.merge(spec_router);
1633            }
1634            Err(e) => {
1635                warn!("Failed to load OpenAPI spec from {:?}: {}. Starting without OpenAPI integration.", spec_path, e);
1636            }
1637        }
1638    }
1639
1640    // Register custom routes from config with advanced routing features
1641    // Create RouteChaosInjector for advanced fault injection and latency
1642    // Store as trait object to avoid circular dependency (RouteChaosInjectorTrait is in mockforge-core)
1643    let route_chaos_injector: Option<
1644        std::sync::Arc<dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1645    > = if let Some(ref route_configs) = route_configs {
1646        if !route_configs.is_empty() {
1647            // Convert to the type expected by RouteChaosInjector
1648            // Note: Both use the same mockforge-core, but we need to ensure type compatibility
1649            let route_configs_converted: Vec<mockforge_core::config::RouteConfig> =
1650                route_configs.to_vec();
1651            match mockforge_route_chaos::RouteChaosInjector::new(route_configs_converted) {
1652                Ok(injector) => {
1653                    info!(
1654                        "Initialized advanced routing features for {} route(s)",
1655                        route_configs.len()
1656                    );
1657                    // RouteChaosInjector implements RouteChaosInjectorTrait, so we can cast it
1658                    // The trait is implemented in mockforge-route-chaos/src/lib.rs
1659                    Some(std::sync::Arc::new(injector)
1660                        as std::sync::Arc<
1661                            dyn mockforge_core::priority_handler::RouteChaosInjectorTrait,
1662                        >)
1663                }
1664                Err(e) => {
1665                    warn!(
1666                        "Failed to initialize advanced routing features: {}. Using basic routing.",
1667                        e
1668                    );
1669                    None
1670                }
1671            }
1672        } else {
1673            None
1674        }
1675    } else {
1676        None
1677    };
1678
1679    if let Some(route_configs) = route_configs {
1680        use axum::http::StatusCode;
1681        use axum::response::IntoResponse;
1682
1683        if !route_configs.is_empty() {
1684            info!("Registering {} custom route(s) from config", route_configs.len());
1685        }
1686
1687        let injector = route_chaos_injector.clone();
1688        for route_config in route_configs {
1689            let status = route_config.response.status;
1690            let body = route_config.response.body.clone();
1691            let headers = route_config.response.headers.clone();
1692            let path = route_config.path.clone();
1693            let method = route_config.method.clone();
1694
1695            // Create handler that returns the configured response with template expansion
1696            // Supports both basic templates ({{uuid}}, {{now}}) and request-aware templates
1697            // ({{request.query.name}}, {{request.path.id}}, {{request.headers.name}})
1698            // Register route using `any()` since we need full Request access for template expansion
1699            let expected_method = method.to_uppercase();
1700            // Clone Arc for the closure - Arc is Send-safe
1701            // Note: RouteChaosInjector is marked as Send+Sync via unsafe impl, but the compiler
1702            // is conservative because rng() is available in the rand crate, even though we use thread_rng()
1703            let injector_clone = injector.clone();
1704            app = app.route(
1705                &path,
1706                #[allow(clippy::non_send_fields_in_send_ty)]
1707                axum::routing::any(move |req: http::Request<axum::body::Body>| {
1708                    let body = body.clone();
1709                    let headers = headers.clone();
1710                    let expand = template_expand;
1711                    let expected = expected_method.clone();
1712                    let status_code = status;
1713                    // Clone Arc again for the async block
1714                    let injector_for_chaos = injector_clone.clone();
1715
1716                    async move {
1717                        // Check if request method matches expected method
1718                        if req.method().as_str() != expected.as_str() {
1719                            // Return 405 Method Not Allowed for wrong method
1720                            return axum::response::Response::builder()
1721                                .status(StatusCode::METHOD_NOT_ALLOWED)
1722                                .header("Allow", &expected)
1723                                .body(axum::body::Body::empty())
1724                                .unwrap()
1725                                .into_response();
1726                        }
1727
1728                        // Apply advanced routing features (fault injection and latency) if available
1729                        // Use helper function to avoid capturing RouteChaosInjector in closure
1730                        // Pass the Arc as a reference to the helper function
1731                        if let Some(fault_response) = apply_route_chaos(
1732                            injector_for_chaos.as_deref(),
1733                            req.method(),
1734                            req.uri(),
1735                        )
1736                        .await
1737                        {
1738                            return fault_response;
1739                        }
1740
1741                        // Create JSON response from body, or empty object if None
1742                        let mut body_value = body.unwrap_or(serde_json::json!({}));
1743
1744                        // Apply template expansion if enabled
1745                        // Use mockforge-template-expansion crate which is completely isolated
1746                        // from mockforge-core to avoid Send issues (no rng() in dependency chain)
1747                        if expand {
1748                            use mockforge_template_expansion::RequestContext;
1749                            use serde_json::Value;
1750                            use std::collections::HashMap;
1751
1752                            // Extract request data for template expansion
1753                            let method = req.method().to_string();
1754                            let path = req.uri().path().to_string();
1755
1756                            // Extract query parameters
1757                            let query_params: HashMap<String, Value> = req
1758                                .uri()
1759                                .query()
1760                                .map(|q| {
1761                                    url::form_urlencoded::parse(q.as_bytes())
1762                                        .into_owned()
1763                                        .map(|(k, v)| (k, Value::String(v)))
1764                                        .collect()
1765                                })
1766                                .unwrap_or_default();
1767
1768                            // Extract headers
1769                            let headers: HashMap<String, Value> = req
1770                                .headers()
1771                                .iter()
1772                                .map(|(k, v)| {
1773                                    (
1774                                        k.to_string(),
1775                                        Value::String(v.to_str().unwrap_or_default().to_string()),
1776                                    )
1777                                })
1778                                .collect();
1779
1780                            // Create RequestContext for expand_prompt_template
1781                            // Using RequestContext from mockforge-template-expansion (not mockforge-core)
1782                            // to avoid bringing rng() into scope
1783                            let context = RequestContext {
1784                                method,
1785                                path,
1786                                query_params,
1787                                headers,
1788                                body: None, // Body extraction would require reading the request stream
1789                                path_params: HashMap::new(),
1790                                multipart_fields: HashMap::new(),
1791                                multipart_files: HashMap::new(),
1792                            };
1793
1794                            // Perform template expansion in spawn_blocking to ensure Send safety
1795                            // The template expansion crate is completely isolated from mockforge-core
1796                            // and doesn't have rng() in its dependency chain
1797                            let body_value_clone = body_value.clone();
1798                            let context_clone = context.clone();
1799                            body_value = match tokio::task::spawn_blocking(move || {
1800                                mockforge_template_expansion::expand_templates_in_json(
1801                                    body_value_clone,
1802                                    &context_clone,
1803                                )
1804                            })
1805                            .await
1806                            {
1807                                Ok(result) => result,
1808                                Err(_) => body_value, // Fallback to original on error
1809                            };
1810                        }
1811
1812                        let mut response = Json(body_value).into_response();
1813
1814                        // Set status code
1815                        *response.status_mut() =
1816                            StatusCode::from_u16(status_code).unwrap_or(StatusCode::OK);
1817
1818                        // Add custom headers
1819                        for (key, value) in headers {
1820                            if let Ok(header_name) = http::HeaderName::from_bytes(key.as_bytes()) {
1821                                if let Ok(header_value) = http::HeaderValue::from_str(&value) {
1822                                    response.headers_mut().insert(header_name, header_value);
1823                                }
1824                            }
1825                        }
1826
1827                        response
1828                    }
1829                }),
1830            );
1831
1832            debug!("Registered route: {} {}", method, path);
1833        }
1834    }
1835
1836    // Add health check endpoints
1837    if let Some(health) = health_manager {
1838        // Use comprehensive health check router with all probe endpoints
1839        app = app.merge(health::health_router(health));
1840        info!(
1841            "Health check endpoints enabled: /health, /health/live, /health/ready, /health/startup"
1842        );
1843    } else if include_default_health {
1844        // Fallback to basic health endpoint for backwards compatibility
1845        app = app.route(
1846            "/health",
1847            axum::routing::get(|| async {
1848                use mockforge_core::server_utils::health::HealthStatus;
1849                {
1850                    // HealthStatus should always serialize, but handle errors gracefully
1851                    match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1852                        Ok(value) => Json(value),
1853                        Err(e) => {
1854                            // Log error but return a simple healthy response
1855                            tracing::error!("Failed to serialize health status: {}", e);
1856                            Json(serde_json::json!({
1857                                "status": "healthy",
1858                                "service": "mockforge-http",
1859                                "uptime_seconds": 0
1860                            }))
1861                        }
1862                    }
1863                }
1864            }),
1865        );
1866    }
1867
1868    app = app.merge(sse::sse_router());
1869    // Add file serving endpoints for generated mock files
1870    app = app.merge(file_server::file_serving_router());
1871
1872    // Add management API endpoints
1873    let spec_path_clone = spec_path.clone();
1874    let management_state = ManagementState::new(None, spec_path_clone, 3000); // Port will be updated when we know the actual port
1875
1876    // Create WebSocket state and connect it to management state
1877    use std::sync::Arc;
1878    let ws_state = WsManagementState::new();
1879    let ws_broadcast = Arc::new(ws_state.tx.clone());
1880    let management_state = management_state.with_ws_broadcast(ws_broadcast);
1881
1882    // Add proxy config to management state if available
1883    let management_state = if let Some(proxy_cfg) = proxy_config {
1884        use tokio::sync::RwLock;
1885        let proxy_config_arc = Arc::new(RwLock::new(proxy_cfg));
1886        management_state.with_proxy_config(proxy_config_arc)
1887    } else {
1888        management_state
1889    };
1890
1891    #[cfg(feature = "smtp")]
1892    let management_state = {
1893        if let Some(smtp_reg) = smtp_registry {
1894            match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
1895                Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
1896                Err(e) => {
1897                    error!(
1898                        "Invalid SMTP registry type passed to HTTP management state: {:?}",
1899                        e.type_id()
1900                    );
1901                    management_state
1902                }
1903            }
1904        } else {
1905            management_state
1906        }
1907    };
1908    #[cfg(not(feature = "smtp"))]
1909    let management_state = {
1910        let _ = smtp_registry;
1911        management_state
1912    };
1913    #[cfg(feature = "mqtt")]
1914    let management_state = {
1915        if let Some(broker) = mqtt_broker {
1916            match broker.downcast::<mockforge_mqtt::MqttBroker>() {
1917                Ok(broker) => management_state.with_mqtt_broker(broker),
1918                Err(e) => {
1919                    error!(
1920                        "Invalid MQTT broker passed to HTTP management state: {:?}",
1921                        e.type_id()
1922                    );
1923                    management_state
1924                }
1925            }
1926        } else {
1927            management_state
1928        }
1929    };
1930    #[cfg(not(feature = "mqtt"))]
1931    let management_state = {
1932        let _ = mqtt_broker;
1933        management_state
1934    };
1935    app = app.nest("/__mockforge/api", management_router(management_state));
1936
1937    // Add verification API endpoint
1938    app = app.merge(verification_router());
1939
1940    // Add OIDC well-known endpoints
1941    use crate::auth::oidc::oidc_router;
1942    app = app.merge(oidc_router());
1943
1944    // Add access review API if enabled
1945    {
1946        use mockforge_core::security::get_global_access_review_service;
1947        if let Some(service) = get_global_access_review_service().await {
1948            use crate::handlers::access_review::{access_review_router, AccessReviewState};
1949            let review_state = AccessReviewState { service };
1950            app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
1951            debug!("Access review API mounted at /api/v1/security/access-reviews");
1952        }
1953    }
1954
1955    // Add privileged access API if enabled
1956    {
1957        use mockforge_core::security::get_global_privileged_access_manager;
1958        if let Some(manager) = get_global_privileged_access_manager().await {
1959            use crate::handlers::privileged_access::{
1960                privileged_access_router, PrivilegedAccessState,
1961            };
1962            let privileged_state = PrivilegedAccessState { manager };
1963            app = app.nest(
1964                "/api/v1/security/privileged-access",
1965                privileged_access_router(privileged_state),
1966            );
1967            debug!("Privileged access API mounted at /api/v1/security/privileged-access");
1968        }
1969    }
1970
1971    // Add change management API if enabled
1972    {
1973        use mockforge_core::security::get_global_change_management_engine;
1974        if let Some(engine) = get_global_change_management_engine().await {
1975            use crate::handlers::change_management::{
1976                change_management_router, ChangeManagementState,
1977            };
1978            let change_state = ChangeManagementState { engine };
1979            app = app.nest("/api/v1/change-management", change_management_router(change_state));
1980            debug!("Change management API mounted at /api/v1/change-management");
1981        }
1982    }
1983
1984    // Add risk assessment API if enabled
1985    {
1986        use mockforge_core::security::get_global_risk_assessment_engine;
1987        if let Some(engine) = get_global_risk_assessment_engine().await {
1988            use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
1989            let risk_state = RiskAssessmentState { engine };
1990            app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
1991            debug!("Risk assessment API mounted at /api/v1/security/risks");
1992        }
1993    }
1994
1995    // Add token lifecycle API
1996    {
1997        use crate::auth::token_lifecycle::TokenLifecycleManager;
1998        use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
1999        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2000        let lifecycle_state = TokenLifecycleState {
2001            manager: lifecycle_manager,
2002        };
2003        app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
2004        debug!("Token lifecycle API mounted at /api/v1/auth");
2005    }
2006
2007    // Add OAuth2 server endpoints
2008    {
2009        use crate::auth::oidc::load_oidc_state;
2010        use crate::auth::token_lifecycle::TokenLifecycleManager;
2011        use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
2012        // Load OIDC state from configuration (environment variables or config file)
2013        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
2014        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2015        let oauth2_state = OAuth2ServerState {
2016            oidc_state,
2017            lifecycle_manager,
2018            auth_codes: Arc::new(RwLock::new(HashMap::new())),
2019            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
2020        };
2021        app = app.merge(oauth2_server_router(oauth2_state));
2022        debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
2023    }
2024
2025    // Add consent screen endpoints
2026    {
2027        use crate::auth::oidc::load_oidc_state;
2028        use crate::auth::risk_engine::RiskEngine;
2029        use crate::auth::token_lifecycle::TokenLifecycleManager;
2030        use crate::handlers::consent::{consent_router, ConsentState};
2031        use crate::handlers::oauth2_server::OAuth2ServerState;
2032        // Load OIDC state from configuration (environment variables or config file)
2033        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
2034        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2035        let oauth2_state = OAuth2ServerState {
2036            oidc_state: oidc_state.clone(),
2037            lifecycle_manager: lifecycle_manager.clone(),
2038            auth_codes: Arc::new(RwLock::new(HashMap::new())),
2039            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
2040        };
2041        let risk_engine = Arc::new(RiskEngine::default());
2042        let consent_state = ConsentState {
2043            oauth2_state,
2044            risk_engine,
2045        };
2046        app = app.merge(consent_router(consent_state));
2047        debug!("Consent screen endpoints mounted at /consent");
2048    }
2049
2050    // Add risk simulation API
2051    {
2052        use crate::auth::risk_engine::RiskEngine;
2053        use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
2054        let risk_engine = Arc::new(RiskEngine::default());
2055        let risk_state = RiskSimulationState { risk_engine };
2056        app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
2057        debug!("Risk simulation API mounted at /api/v1/auth/risk");
2058    }
2059
2060    // Initialize database connection (optional)
2061    let database = {
2062        use crate::database::Database;
2063        let database_url = std::env::var("DATABASE_URL").ok();
2064        match Database::connect_optional(database_url.as_deref()).await {
2065            Ok(db) => {
2066                if db.is_connected() {
2067                    // Run migrations if database is connected
2068                    if let Err(e) = db.migrate_if_connected().await {
2069                        warn!("Failed to run database migrations: {}", e);
2070                    } else {
2071                        info!("Database connected and migrations applied");
2072                    }
2073                }
2074                Some(db)
2075            }
2076            Err(e) => {
2077                warn!("Failed to connect to database: {}. Continuing without database support.", e);
2078                None
2079            }
2080        }
2081    };
2082
2083    // Add drift budget and incident management endpoints
2084    // Initialize shared components for drift tracking and protocol contracts
2085    let (drift_engine, incident_manager, drift_config) = {
2086        use mockforge_core::contract_drift::{DriftBudgetConfig, DriftBudgetEngine};
2087        use mockforge_core::incidents::{IncidentManager, IncidentStore};
2088        use std::sync::Arc;
2089
2090        // Initialize drift budget engine with default config
2091        let drift_config = DriftBudgetConfig::default();
2092        let drift_engine = Arc::new(DriftBudgetEngine::new(drift_config.clone()));
2093
2094        // Initialize incident store and manager
2095        let incident_store = Arc::new(IncidentStore::default());
2096        let incident_manager = Arc::new(IncidentManager::new(incident_store.clone()));
2097
2098        (drift_engine, incident_manager, drift_config)
2099    };
2100
2101    {
2102        use crate::handlers::drift_budget::{drift_budget_router, DriftBudgetState};
2103        use crate::middleware::drift_tracking::DriftTrackingState;
2104        use mockforge_core::ai_contract_diff::ContractDiffAnalyzer;
2105        use mockforge_core::consumer_contracts::{ConsumerBreakingChangeDetector, UsageRecorder};
2106        use std::sync::Arc;
2107
2108        // Initialize usage recorder and consumer detector
2109        let usage_recorder = Arc::new(UsageRecorder::default());
2110        let consumer_detector =
2111            Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2112
2113        // Initialize contract diff analyzer if enabled
2114        let diff_analyzer = if drift_config.enabled {
2115            match ContractDiffAnalyzer::new(
2116                mockforge_core::ai_contract_diff::ContractDiffConfig::default(),
2117            ) {
2118                Ok(analyzer) => Some(Arc::new(analyzer)),
2119                Err(e) => {
2120                    warn!("Failed to create contract diff analyzer: {}", e);
2121                    None
2122                }
2123            }
2124        } else {
2125            None
2126        };
2127
2128        // Get OpenAPI spec if available
2129        // Note: Load from spec_path if available, or leave as None for manual configuration.
2130        let spec = if let Some(ref spec_path) = spec_path {
2131            match OpenApiSpec::from_file(spec_path).await {
2132                Ok(s) => Some(Arc::new(s)),
2133                Err(e) => {
2134                    debug!("Failed to load OpenAPI spec for drift tracking: {}", e);
2135                    None
2136                }
2137            }
2138        } else {
2139            None
2140        };
2141
2142        // Create drift tracking state
2143        let drift_tracking_state = DriftTrackingState {
2144            diff_analyzer,
2145            spec,
2146            drift_engine: drift_engine.clone(),
2147            incident_manager: incident_manager.clone(),
2148            usage_recorder,
2149            consumer_detector,
2150            enabled: drift_config.enabled,
2151        };
2152
2153        // Add response body buffering middleware (before drift tracking)
2154        app = app.layer(axum::middleware::from_fn(middleware::buffer_response_middleware));
2155
2156        // Add drift tracking middleware (after response buffering)
2157        // Use a wrapper that inserts state into extensions before calling the middleware
2158        let drift_tracking_state_clone = drift_tracking_state.clone();
2159        app = app.layer(axum::middleware::from_fn(
2160            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2161                let state = drift_tracking_state_clone.clone();
2162                async move {
2163                    // Insert state into extensions if not already present
2164                    if req.extensions().get::<DriftTrackingState>().is_none() {
2165                        req.extensions_mut().insert(state);
2166                    }
2167                    // Call the middleware function
2168                    middleware::drift_tracking::drift_tracking_middleware_with_extensions(req, next)
2169                        .await
2170                }
2171            },
2172        ));
2173
2174        let drift_state = DriftBudgetState {
2175            engine: drift_engine.clone(),
2176            incident_manager: incident_manager.clone(),
2177            gitops_handler: None, // Can be initialized later if GitOps is configured
2178        };
2179
2180        app = app.merge(drift_budget_router(drift_state));
2181        debug!("Drift budget and incident management endpoints mounted at /api/v1/drift");
2182    }
2183
2184    // Add pipeline management endpoints (MockOps)
2185    #[cfg(feature = "pipelines")]
2186    {
2187        use crate::handlers::pipelines::{pipeline_router, PipelineState};
2188
2189        let pipeline_state = PipelineState::new();
2190        app = app.merge(pipeline_router(pipeline_state));
2191        debug!("Pipeline management endpoints mounted at /api/v1/pipelines");
2192    }
2193
2194    // Add governance endpoints (forecasting, semantic drift, threat modeling, contract health)
2195    {
2196        use crate::handlers::contract_health::{contract_health_router, ContractHealthState};
2197        use crate::handlers::forecasting::{forecasting_router, ForecastingState};
2198        use crate::handlers::semantic_drift::{semantic_drift_router, SemanticDriftState};
2199        use crate::handlers::threat_modeling::{threat_modeling_router, ThreatModelingState};
2200        use mockforge_core::contract_drift::forecasting::{Forecaster, ForecastingConfig};
2201        use mockforge_core::contract_drift::threat_modeling::{
2202            ThreatAnalyzer, ThreatModelingConfig,
2203        };
2204        use mockforge_core::incidents::semantic_manager::SemanticIncidentManager;
2205        use std::sync::Arc;
2206
2207        // Initialize forecasting
2208        let forecasting_config = ForecastingConfig::default();
2209        let forecaster = Arc::new(Forecaster::new(forecasting_config));
2210        let forecasting_state = ForecastingState {
2211            forecaster,
2212            database: database.clone(),
2213        };
2214
2215        // Initialize semantic drift manager
2216        let semantic_manager = Arc::new(SemanticIncidentManager::new());
2217        let semantic_state = SemanticDriftState {
2218            manager: semantic_manager,
2219            database: database.clone(),
2220        };
2221
2222        // Initialize threat analyzer
2223        let threat_config = ThreatModelingConfig::default();
2224        let threat_analyzer = match ThreatAnalyzer::new(threat_config) {
2225            Ok(analyzer) => Arc::new(analyzer),
2226            Err(e) => {
2227                warn!("Failed to create threat analyzer: {}. Using default.", e);
2228                Arc::new(ThreatAnalyzer::new(ThreatModelingConfig::default()).unwrap_or_else(
2229                    |_| {
2230                        // Fallback to a minimal config if default also fails
2231                        ThreatAnalyzer::new(ThreatModelingConfig {
2232                            enabled: false,
2233                            ..Default::default()
2234                        })
2235                        .expect("Failed to create fallback threat analyzer")
2236                    },
2237                ))
2238            }
2239        };
2240        // Load webhook configs from ServerConfig
2241        let mut webhook_configs = Vec::new();
2242        let config_paths = [
2243            "config.yaml",
2244            "mockforge.yaml",
2245            "tools/mockforge/config.yaml",
2246            "../tools/mockforge/config.yaml",
2247        ];
2248
2249        for path in &config_paths {
2250            if let Ok(config) = mockforge_core::config::load_config(path).await {
2251                if !config.incidents.webhooks.is_empty() {
2252                    webhook_configs = config.incidents.webhooks.clone();
2253                    info!("Loaded {} webhook configs from config: {}", webhook_configs.len(), path);
2254                    break;
2255                }
2256            }
2257        }
2258
2259        if webhook_configs.is_empty() {
2260            debug!("No webhook configs found in config files, using empty list");
2261        }
2262
2263        let threat_state = ThreatModelingState {
2264            analyzer: threat_analyzer,
2265            webhook_configs,
2266            database: database.clone(),
2267        };
2268
2269        // Initialize contract health state
2270        let contract_health_state = ContractHealthState {
2271            incident_manager: incident_manager.clone(),
2272            semantic_manager: Arc::new(SemanticIncidentManager::new()),
2273            database: database.clone(),
2274        };
2275
2276        // Register routers
2277        app = app.merge(forecasting_router(forecasting_state));
2278        debug!("Forecasting endpoints mounted at /api/v1/forecasts");
2279
2280        app = app.merge(semantic_drift_router(semantic_state));
2281        debug!("Semantic drift endpoints mounted at /api/v1/semantic-drift");
2282
2283        app = app.merge(threat_modeling_router(threat_state));
2284        debug!("Threat modeling endpoints mounted at /api/v1/threats");
2285
2286        app = app.merge(contract_health_router(contract_health_state));
2287        debug!("Contract health endpoints mounted at /api/v1/contract-health");
2288    }
2289
2290    // Add protocol contracts endpoints with fitness registry initialization
2291    {
2292        use crate::handlers::protocol_contracts::{
2293            protocol_contracts_router, ProtocolContractState,
2294        };
2295        use mockforge_core::contract_drift::{
2296            ConsumerImpactAnalyzer, FitnessFunctionRegistry, ProtocolContractRegistry,
2297        };
2298        use std::sync::Arc;
2299        use tokio::sync::RwLock;
2300
2301        // Initialize protocol contract registry
2302        let contract_registry = Arc::new(RwLock::new(ProtocolContractRegistry::new()));
2303
2304        // Initialize fitness function registry and load from config
2305        let mut fitness_registry = FitnessFunctionRegistry::new();
2306
2307        // Try to load config and populate fitness rules
2308        let config_paths = [
2309            "config.yaml",
2310            "mockforge.yaml",
2311            "tools/mockforge/config.yaml",
2312            "../tools/mockforge/config.yaml",
2313        ];
2314
2315        let mut config_loaded = false;
2316        for path in &config_paths {
2317            if let Ok(config) = mockforge_core::config::load_config(path).await {
2318                if !config.contracts.fitness_rules.is_empty() {
2319                    if let Err(e) =
2320                        fitness_registry.load_from_config(&config.contracts.fitness_rules)
2321                    {
2322                        warn!("Failed to load fitness rules from config {}: {}", path, e);
2323                    } else {
2324                        info!(
2325                            "Loaded {} fitness rules from config: {}",
2326                            config.contracts.fitness_rules.len(),
2327                            path
2328                        );
2329                        config_loaded = true;
2330                        break;
2331                    }
2332                }
2333            }
2334        }
2335
2336        if !config_loaded {
2337            debug!("No fitness rules found in config files, using empty registry");
2338        }
2339
2340        let fitness_registry = Arc::new(RwLock::new(fitness_registry));
2341
2342        // Reuse drift engine and incident manager from drift budget section
2343
2344        // Initialize consumer impact analyzer
2345        let consumer_mapping_registry =
2346            mockforge_core::contract_drift::ConsumerMappingRegistry::new();
2347        let consumer_analyzer =
2348            Arc::new(RwLock::new(ConsumerImpactAnalyzer::new(consumer_mapping_registry)));
2349
2350        let protocol_state = ProtocolContractState {
2351            registry: contract_registry,
2352            drift_engine: Some(drift_engine.clone()),
2353            incident_manager: Some(incident_manager.clone()),
2354            fitness_registry: Some(fitness_registry),
2355            consumer_analyzer: Some(consumer_analyzer),
2356        };
2357
2358        app = app.nest("/api/v1/contracts", protocol_contracts_router(protocol_state));
2359        debug!("Protocol contracts endpoints mounted at /api/v1/contracts");
2360    }
2361
2362    // Add behavioral cloning middleware (optional - applies learned behavior to requests)
2363    #[cfg(feature = "behavioral-cloning")]
2364    {
2365        use crate::middleware::behavioral_cloning::BehavioralCloningMiddlewareState;
2366        use std::path::PathBuf;
2367
2368        // Determine database path (defaults to ./recordings.db)
2369        let db_path = std::env::var("RECORDER_DATABASE_PATH")
2370            .ok()
2371            .map(PathBuf::from)
2372            .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2373
2374        let bc_middleware_state = if let Some(path) = db_path {
2375            BehavioralCloningMiddlewareState::with_database_path(path)
2376        } else {
2377            BehavioralCloningMiddlewareState::new()
2378        };
2379
2380        // Only enable if BEHAVIORAL_CLONING_ENABLED is set to true
2381        let enabled = std::env::var("BEHAVIORAL_CLONING_ENABLED")
2382            .ok()
2383            .and_then(|v| v.parse::<bool>().ok())
2384            .unwrap_or(false);
2385
2386        if enabled {
2387            let bc_state_clone = bc_middleware_state.clone();
2388            app = app.layer(axum::middleware::from_fn(
2389                move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2390                    let state = bc_state_clone.clone();
2391                    async move {
2392                        // Insert state into extensions if not already present
2393                        if req.extensions().get::<BehavioralCloningMiddlewareState>().is_none() {
2394                            req.extensions_mut().insert(state);
2395                        }
2396                        // Call the middleware function
2397                        crate::middleware::behavioral_cloning::behavioral_cloning_middleware(
2398                            req, next,
2399                        )
2400                        .await
2401                    }
2402                },
2403            ));
2404            debug!("Behavioral cloning middleware enabled (applies learned behavior to requests)");
2405        }
2406    }
2407
2408    // Add consumer contracts endpoints
2409    {
2410        use crate::handlers::consumer_contracts::{
2411            consumer_contracts_router, ConsumerContractsState,
2412        };
2413        use mockforge_core::consumer_contracts::{
2414            ConsumerBreakingChangeDetector, ConsumerRegistry, UsageRecorder,
2415        };
2416        use std::sync::Arc;
2417
2418        // Initialize consumer registry
2419        let registry = Arc::new(ConsumerRegistry::default());
2420
2421        // Initialize usage recorder
2422        let usage_recorder = Arc::new(UsageRecorder::default());
2423
2424        // Initialize breaking change detector
2425        let detector = Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2426
2427        let consumer_state = ConsumerContractsState {
2428            registry,
2429            usage_recorder,
2430            detector,
2431            violations: Arc::new(RwLock::new(HashMap::new())),
2432        };
2433
2434        app = app.merge(consumer_contracts_router(consumer_state));
2435        debug!("Consumer contracts endpoints mounted at /api/v1/consumers");
2436    }
2437
2438    // Add behavioral cloning endpoints
2439    #[cfg(feature = "behavioral-cloning")]
2440    {
2441        use crate::handlers::behavioral_cloning::{
2442            behavioral_cloning_router, BehavioralCloningState,
2443        };
2444        use std::path::PathBuf;
2445
2446        // Determine database path (defaults to ./recordings.db)
2447        let db_path = std::env::var("RECORDER_DATABASE_PATH")
2448            .ok()
2449            .map(PathBuf::from)
2450            .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2451
2452        let bc_state = if let Some(path) = db_path {
2453            BehavioralCloningState::with_database_path(path)
2454        } else {
2455            BehavioralCloningState::new()
2456        };
2457
2458        app = app.merge(behavioral_cloning_router(bc_state));
2459        debug!("Behavioral cloning endpoints mounted at /api/v1/behavioral-cloning");
2460    }
2461
2462    // Add consistency engine and cross-protocol state management
2463    {
2464        use crate::consistency::{ConsistencyMiddlewareState, HttpAdapter};
2465        use crate::handlers::consistency::{consistency_router, ConsistencyState};
2466        use mockforge_core::consistency::ConsistencyEngine;
2467        use std::sync::Arc;
2468
2469        // Initialize consistency engine
2470        let consistency_engine = Arc::new(ConsistencyEngine::new());
2471
2472        // Create and register HTTP adapter
2473        let http_adapter = Arc::new(HttpAdapter::new(consistency_engine.clone()));
2474        consistency_engine.register_adapter(http_adapter.clone()).await;
2475
2476        // Create consistency state for handlers
2477        let consistency_state = ConsistencyState {
2478            engine: consistency_engine.clone(),
2479        };
2480
2481        // Create X-Ray state first (needed for middleware)
2482        use crate::handlers::xray::XRayState;
2483        let xray_state = Arc::new(XRayState {
2484            engine: consistency_engine.clone(),
2485            request_contexts: std::sync::Arc::new(RwLock::new(HashMap::new())),
2486        });
2487
2488        // Create consistency middleware state
2489        let consistency_middleware_state = ConsistencyMiddlewareState {
2490            engine: consistency_engine.clone(),
2491            adapter: http_adapter,
2492            xray_state: Some(xray_state.clone()),
2493        };
2494
2495        // Add consistency middleware (before other middleware to inject state early)
2496        let consistency_middleware_state_clone = consistency_middleware_state.clone();
2497        app = app.layer(axum::middleware::from_fn(
2498            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2499                let state = consistency_middleware_state_clone.clone();
2500                async move {
2501                    // Insert state into extensions if not already present
2502                    if req.extensions().get::<ConsistencyMiddlewareState>().is_none() {
2503                        req.extensions_mut().insert(state);
2504                    }
2505                    // Call the middleware function
2506                    consistency::middleware::consistency_middleware(req, next).await
2507                }
2508            },
2509        ));
2510
2511        // Add consistency API endpoints
2512        app = app.merge(consistency_router(consistency_state));
2513        debug!("Consistency engine initialized and endpoints mounted at /api/v1/consistency");
2514
2515        // Add fidelity score endpoints
2516        {
2517            use crate::handlers::fidelity::{fidelity_router, FidelityState};
2518            let fidelity_state = FidelityState::new();
2519            app = app.merge(fidelity_router(fidelity_state));
2520            debug!("Fidelity score endpoints mounted at /api/v1/workspace/:workspace_id/fidelity");
2521        }
2522
2523        // Add scenario studio endpoints
2524        {
2525            use crate::handlers::scenario_studio::{scenario_studio_router, ScenarioStudioState};
2526            let scenario_studio_state = ScenarioStudioState::new();
2527            app = app.merge(scenario_studio_router(scenario_studio_state));
2528            debug!("Scenario Studio endpoints mounted at /api/v1/scenario-studio");
2529        }
2530
2531        // Add performance mode endpoints
2532        {
2533            use crate::handlers::performance::{performance_router, PerformanceState};
2534            let performance_state = PerformanceState::new();
2535            app = app.nest("/api/performance", performance_router(performance_state));
2536            debug!("Performance mode endpoints mounted at /api/performance");
2537        }
2538
2539        // Add world state endpoints
2540        {
2541            use crate::handlers::world_state::{world_state_router, WorldStateState};
2542            use mockforge_world_state::WorldStateEngine;
2543            use std::sync::Arc;
2544            use tokio::sync::RwLock;
2545
2546            let world_state_engine = Arc::new(RwLock::new(WorldStateEngine::new()));
2547            let world_state_state = WorldStateState {
2548                engine: world_state_engine,
2549            };
2550            app = app.nest("/api/world-state", world_state_router().with_state(world_state_state));
2551            debug!("World state endpoints mounted at /api/world-state");
2552        }
2553
2554        // Add snapshot management endpoints
2555        {
2556            use crate::handlers::snapshots::{snapshot_router, SnapshotState};
2557            use mockforge_core::snapshots::SnapshotManager;
2558            use std::path::PathBuf;
2559
2560            let snapshot_dir = std::env::var("MOCKFORGE_SNAPSHOT_DIR").ok().map(PathBuf::from);
2561            let snapshot_manager = Arc::new(SnapshotManager::new(snapshot_dir));
2562
2563            let snapshot_state = SnapshotState {
2564                manager: snapshot_manager,
2565                consistency_engine: Some(consistency_engine.clone()),
2566                workspace_persistence: None, // Can be initialized later if workspace persistence is available
2567                vbr_engine: None, // Can be initialized when VBR engine is available in server state
2568                recorder: None,   // Can be initialized when Recorder is available in server state
2569            };
2570
2571            app = app.merge(snapshot_router(snapshot_state));
2572            debug!("Snapshot management endpoints mounted at /api/v1/snapshots");
2573
2574            // Add X-Ray API endpoints for browser extension
2575            {
2576                use crate::handlers::xray::xray_router;
2577                app = app.merge(xray_router((*xray_state).clone()));
2578                debug!("X-Ray API endpoints mounted at /api/v1/xray");
2579            }
2580        }
2581
2582        // Add A/B testing endpoints and middleware
2583        {
2584            use crate::handlers::ab_testing::{ab_testing_router, ABTestingState};
2585            use crate::middleware::ab_testing::ab_testing_middleware;
2586
2587            let ab_testing_state = ABTestingState::new();
2588
2589            // Add A/B testing middleware (before other response middleware)
2590            let ab_testing_state_clone = ab_testing_state.clone();
2591            app = app.layer(axum::middleware::from_fn(
2592                move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2593                    let state = ab_testing_state_clone.clone();
2594                    async move {
2595                        // Insert state into extensions if not already present
2596                        if req.extensions().get::<ABTestingState>().is_none() {
2597                            req.extensions_mut().insert(state);
2598                        }
2599                        // Call the middleware function
2600                        ab_testing_middleware(req, next).await
2601                    }
2602                },
2603            ));
2604
2605            // Add A/B testing API endpoints
2606            app = app.merge(ab_testing_router(ab_testing_state));
2607            debug!("A/B testing endpoints mounted at /api/v1/ab-tests");
2608        }
2609    }
2610
2611    // Add PR generation endpoints (optional - only if configured)
2612    {
2613        use crate::handlers::pr_generation::{pr_generation_router, PRGenerationState};
2614        use mockforge_core::pr_generation::{PRGenerator, PRProvider};
2615        use std::sync::Arc;
2616
2617        // Load PR generation config from environment or use default
2618        let pr_config = mockforge_core::pr_generation::PRGenerationConfig::from_env();
2619
2620        let generator = if pr_config.enabled && pr_config.token.is_some() {
2621            let token = pr_config.token.as_ref().unwrap().clone();
2622            let generator = match pr_config.provider {
2623                PRProvider::GitHub => PRGenerator::new_github(
2624                    pr_config.owner.clone(),
2625                    pr_config.repo.clone(),
2626                    token,
2627                    pr_config.base_branch.clone(),
2628                ),
2629                PRProvider::GitLab => PRGenerator::new_gitlab(
2630                    pr_config.owner.clone(),
2631                    pr_config.repo.clone(),
2632                    token,
2633                    pr_config.base_branch.clone(),
2634                ),
2635            };
2636            Some(Arc::new(generator))
2637        } else {
2638            None
2639        };
2640
2641        let pr_state = PRGenerationState {
2642            generator: generator.clone(),
2643        };
2644
2645        app = app.merge(pr_generation_router(pr_state));
2646        if generator.is_some() {
2647            debug!(
2648                "PR generation endpoints mounted at /api/v1/pr (configured for {:?})",
2649                pr_config.provider
2650            );
2651        } else {
2652            debug!("PR generation endpoints mounted at /api/v1/pr (not configured - set GITHUB_TOKEN/GITLAB_TOKEN and PR_REPO_OWNER/PR_REPO_NAME)");
2653        }
2654    }
2655
2656    // Add management WebSocket endpoint
2657    app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
2658
2659    // Add workspace routing middleware if multi-tenant is enabled
2660    if let Some(mt_config) = multi_tenant_config {
2661        if mt_config.enabled {
2662            use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
2663            use std::sync::Arc;
2664
2665            info!(
2666                "Multi-tenant mode enabled with {} routing strategy",
2667                match mt_config.routing_strategy {
2668                    mockforge_core::RoutingStrategy::Path => "path-based",
2669                    mockforge_core::RoutingStrategy::Port => "port-based",
2670                    mockforge_core::RoutingStrategy::Both => "hybrid",
2671                }
2672            );
2673
2674            // Create the multi-tenant workspace registry
2675            let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
2676
2677            // Register the default workspace before wrapping in Arc
2678            let default_workspace =
2679                mockforge_core::Workspace::new(mt_config.default_workspace.clone());
2680            if let Err(e) =
2681                registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
2682            {
2683                warn!("Failed to register default workspace: {}", e);
2684            } else {
2685                info!("Registered default workspace: '{}'", mt_config.default_workspace);
2686            }
2687
2688            // Wrap registry in Arc for shared access
2689            let registry = Arc::new(registry);
2690
2691            // Create workspace router
2692            let _workspace_router = WorkspaceRouter::new(registry);
2693            info!("Workspace routing middleware initialized for HTTP server");
2694        }
2695    }
2696
2697    // Apply deceptive deploy configuration if enabled
2698    let mut final_cors_config = cors_config;
2699    let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
2700    // Auth config from deceptive deploy OAuth (if configured)
2701    let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
2702    let mut rate_limit_config = middleware::RateLimitConfig {
2703        requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
2704            .ok()
2705            .and_then(|v| v.parse().ok())
2706            .unwrap_or(1000),
2707        burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
2708            .ok()
2709            .and_then(|v| v.parse().ok())
2710            .unwrap_or(2000),
2711        per_ip: true,
2712        per_endpoint: false,
2713    };
2714
2715    if let Some(deploy_config) = &deceptive_deploy_config {
2716        if deploy_config.enabled {
2717            info!("Deceptive deploy mode enabled - applying production-like configuration");
2718
2719            // Override CORS config if provided
2720            if let Some(prod_cors) = &deploy_config.cors {
2721                final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
2722                    enabled: true,
2723                    allowed_origins: prod_cors.allowed_origins.clone(),
2724                    allowed_methods: prod_cors.allowed_methods.clone(),
2725                    allowed_headers: prod_cors.allowed_headers.clone(),
2726                    allow_credentials: prod_cors.allow_credentials,
2727                });
2728                info!("Applied production-like CORS configuration");
2729            }
2730
2731            // Override rate limit config if provided
2732            if let Some(prod_rate_limit) = &deploy_config.rate_limit {
2733                rate_limit_config = middleware::RateLimitConfig {
2734                    requests_per_minute: prod_rate_limit.requests_per_minute,
2735                    burst: prod_rate_limit.burst,
2736                    per_ip: prod_rate_limit.per_ip,
2737                    per_endpoint: false,
2738                };
2739                info!(
2740                    "Applied production-like rate limiting: {} req/min, burst: {}",
2741                    prod_rate_limit.requests_per_minute, prod_rate_limit.burst
2742                );
2743            }
2744
2745            // Set production headers
2746            if !deploy_config.headers.is_empty() {
2747                let headers_map: HashMap<String, String> = deploy_config.headers.clone();
2748                production_headers = Some(std::sync::Arc::new(headers_map));
2749                info!("Configured {} production headers", deploy_config.headers.len());
2750            }
2751
2752            // Integrate OAuth config from deceptive deploy
2753            if let Some(prod_oauth) = &deploy_config.oauth {
2754                let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
2755                deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
2756                    oauth2: Some(oauth2_config),
2757                    ..Default::default()
2758                });
2759                info!("Applied production-like OAuth configuration for deceptive deploy");
2760            }
2761        }
2762    }
2763
2764    // Initialize rate limiter and state
2765    let rate_limiter =
2766        std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
2767
2768    let mut state = HttpServerState::new().with_rate_limiter(rate_limiter.clone());
2769
2770    // Add production headers to state if configured
2771    if let Some(headers) = production_headers.clone() {
2772        state = state.with_production_headers(headers);
2773    }
2774
2775    // Add rate limiting middleware
2776    app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));
2777
2778    // Add production headers middleware if configured
2779    if state.production_headers.is_some() {
2780        app =
2781            app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
2782    }
2783
2784    // Add authentication middleware if OAuth is configured via deceptive deploy
2785    if let Some(auth_config) = deceptive_deploy_auth_config {
2786        use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
2787        use std::collections::HashMap;
2788        use std::sync::Arc;
2789        use tokio::sync::RwLock;
2790
2791        // Create OAuth2 client if configured
2792        let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
2793            match create_oauth2_client(oauth2_config) {
2794                Ok(client) => Some(client),
2795                Err(e) => {
2796                    warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
2797                    None
2798                }
2799            }
2800        } else {
2801            None
2802        };
2803
2804        // Create auth state
2805        let auth_state = AuthState {
2806            config: auth_config,
2807            spec: None, // OpenAPI spec not available in this context
2808            oauth2_client,
2809            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
2810        };
2811
2812        // Apply auth middleware
2813        app = app.layer(from_fn_with_state(auth_state, auth_middleware));
2814        info!("Applied OAuth authentication middleware from deceptive deploy configuration");
2815    }
2816
2817    // Add runtime daemon 404 detection middleware (if enabled)
2818    #[cfg(feature = "runtime-daemon")]
2819    {
2820        use mockforge_runtime_daemon::{AutoGenerator, NotFoundDetector, RuntimeDaemonConfig};
2821        use std::sync::Arc;
2822
2823        // Load runtime daemon config from environment
2824        let daemon_config = RuntimeDaemonConfig::from_env();
2825
2826        if daemon_config.enabled {
2827            info!("Runtime daemon enabled - auto-creating mocks from 404s");
2828
2829            // Determine management API URL (default to localhost:3000)
2830            let management_api_url =
2831                std::env::var("MOCKFORGE_MANAGEMENT_API_URL").unwrap_or_else(|_| {
2832                    let port =
2833                        std::env::var("MOCKFORGE_HTTP_PORT").unwrap_or_else(|_| "3000".to_string());
2834                    format!("http://localhost:{}", port)
2835                });
2836
2837            // Create auto-generator
2838            let generator = Arc::new(AutoGenerator::new(daemon_config.clone(), management_api_url));
2839
2840            // Create detector and set generator
2841            let detector = NotFoundDetector::new(daemon_config.clone());
2842            detector.set_generator(generator).await;
2843
2844            // Add middleware layer
2845            let detector_clone = detector.clone();
2846            app = app.layer(axum::middleware::from_fn(
2847                move |req: axum::extract::Request, next: axum::middleware::Next| {
2848                    let detector = detector_clone.clone();
2849                    async move { detector.detect_and_auto_create(req, next).await }
2850                },
2851            ));
2852
2853            debug!("Runtime daemon 404 detection middleware added");
2854        }
2855    }
2856
2857    // Add /__mockforge/routes endpoint so the admin UI can discover registered routes
2858    {
2859        let routes_state = HttpServerState::with_routes(captured_routes);
2860        let routes_router = Router::new()
2861            .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
2862            .with_state(routes_state);
2863        app = app.merge(routes_router);
2864    }
2865
2866    // Add request logging middleware to capture all requests for the admin dashboard
2867    app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));
2868
2869    // Add contract diff middleware for automatic request capture
2870    // This captures requests for contract diff analysis
2871    app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
2872
2873    // Add CORS middleware (use final_cors_config which may be overridden by deceptive deploy)
2874    app = apply_cors_middleware(app, final_cors_config);
2875
2876    app
2877}
2878
2879// Note: start_with_traffic_shaping function removed due to compilation issues
2880// Use build_router_with_traffic_shaping_and_multi_tenant directly instead
2881
2882#[test]
2883fn test_route_info_clone() {
2884    let route = RouteInfo {
2885        method: "POST".to_string(),
2886        path: "/users".to_string(),
2887        operation_id: Some("createUser".to_string()),
2888        summary: None,
2889        description: None,
2890        parameters: vec![],
2891    };
2892
2893    let cloned = route.clone();
2894    assert_eq!(route.method, cloned.method);
2895    assert_eq!(route.path, cloned.path);
2896    assert_eq!(route.operation_id, cloned.operation_id);
2897}
2898
2899#[test]
2900fn test_http_server_state_new() {
2901    let state = HttpServerState::new();
2902    assert_eq!(state.routes.len(), 0);
2903}
2904
2905#[test]
2906fn test_http_server_state_with_routes() {
2907    let routes = vec![
2908        RouteInfo {
2909            method: "GET".to_string(),
2910            path: "/users".to_string(),
2911            operation_id: Some("getUsers".to_string()),
2912            summary: None,
2913            description: None,
2914            parameters: vec![],
2915        },
2916        RouteInfo {
2917            method: "POST".to_string(),
2918            path: "/users".to_string(),
2919            operation_id: Some("createUser".to_string()),
2920            summary: None,
2921            description: None,
2922            parameters: vec![],
2923        },
2924    ];
2925
2926    let state = HttpServerState::with_routes(routes.clone());
2927    assert_eq!(state.routes.len(), 2);
2928    assert_eq!(state.routes[0].method, "GET");
2929    assert_eq!(state.routes[1].method, "POST");
2930}
2931
2932#[test]
2933fn test_http_server_state_clone() {
2934    let routes = vec![RouteInfo {
2935        method: "GET".to_string(),
2936        path: "/test".to_string(),
2937        operation_id: None,
2938        summary: None,
2939        description: None,
2940        parameters: vec![],
2941    }];
2942
2943    let state = HttpServerState::with_routes(routes);
2944    let cloned = state.clone();
2945
2946    assert_eq!(state.routes.len(), cloned.routes.len());
2947    assert_eq!(state.routes[0].method, cloned.routes[0].method);
2948}
2949
2950#[tokio::test]
2951async fn test_build_router_without_openapi() {
2952    let _router = build_router(None, None, None).await;
2953    // Should succeed without OpenAPI spec
2954}
2955
2956#[tokio::test]
2957async fn test_build_router_with_nonexistent_spec() {
2958    let _router = build_router(Some("/nonexistent/spec.yaml".to_string()), None, None).await;
2959    // Should succeed but log a warning
2960}
2961
2962#[tokio::test]
2963async fn test_build_router_with_auth_and_latency() {
2964    let _router = build_router_with_auth_and_latency(None, None, None, None).await;
2965    // Should succeed without parameters
2966}
2967
2968#[tokio::test]
2969async fn test_build_router_with_latency() {
2970    let _router = build_router_with_latency(None, None, None).await;
2971    // Should succeed without parameters
2972}
2973
2974#[tokio::test]
2975async fn test_build_router_with_auth() {
2976    let _router = build_router_with_auth(None, None, None).await;
2977    // Should succeed without parameters
2978}
2979
2980#[tokio::test]
2981async fn test_build_router_with_chains() {
2982    let _router = build_router_with_chains(None, None, None).await;
2983    // Should succeed without parameters
2984}
2985
2986#[test]
2987fn test_route_info_with_all_fields() {
2988    let route = RouteInfo {
2989        method: "PUT".to_string(),
2990        path: "/users/{id}".to_string(),
2991        operation_id: Some("updateUser".to_string()),
2992        summary: Some("Update user".to_string()),
2993        description: Some("Updates an existing user".to_string()),
2994        parameters: vec!["id".to_string(), "body".to_string()],
2995    };
2996
2997    assert!(route.operation_id.is_some());
2998    assert!(route.summary.is_some());
2999    assert!(route.description.is_some());
3000    assert_eq!(route.parameters.len(), 2);
3001}
3002
3003#[test]
3004fn test_route_info_with_minimal_fields() {
3005    let route = RouteInfo {
3006        method: "DELETE".to_string(),
3007        path: "/users/{id}".to_string(),
3008        operation_id: None,
3009        summary: None,
3010        description: None,
3011        parameters: vec![],
3012    };
3013
3014    assert!(route.operation_id.is_none());
3015    assert!(route.summary.is_none());
3016    assert!(route.description.is_none());
3017    assert_eq!(route.parameters.len(), 0);
3018}
3019
3020#[test]
3021fn test_http_server_state_empty_routes() {
3022    let state = HttpServerState::with_routes(vec![]);
3023    assert_eq!(state.routes.len(), 0);
3024}
3025
3026#[test]
3027fn test_http_server_state_multiple_routes() {
3028    let routes = vec![
3029        RouteInfo {
3030            method: "GET".to_string(),
3031            path: "/users".to_string(),
3032            operation_id: Some("listUsers".to_string()),
3033            summary: Some("List all users".to_string()),
3034            description: None,
3035            parameters: vec![],
3036        },
3037        RouteInfo {
3038            method: "GET".to_string(),
3039            path: "/users/{id}".to_string(),
3040            operation_id: Some("getUser".to_string()),
3041            summary: Some("Get a user".to_string()),
3042            description: None,
3043            parameters: vec!["id".to_string()],
3044        },
3045        RouteInfo {
3046            method: "POST".to_string(),
3047            path: "/users".to_string(),
3048            operation_id: Some("createUser".to_string()),
3049            summary: Some("Create a user".to_string()),
3050            description: None,
3051            parameters: vec!["body".to_string()],
3052        },
3053    ];
3054
3055    let state = HttpServerState::with_routes(routes);
3056    assert_eq!(state.routes.len(), 3);
3057
3058    // Verify different HTTP methods
3059    let methods: Vec<&str> = state.routes.iter().map(|r| r.method.as_str()).collect();
3060    assert!(methods.contains(&"GET"));
3061    assert!(methods.contains(&"POST"));
3062}
3063
3064#[test]
3065fn test_http_server_state_with_rate_limiter() {
3066    use std::sync::Arc;
3067
3068    let config = crate::middleware::RateLimitConfig::default();
3069    let rate_limiter = Arc::new(crate::middleware::GlobalRateLimiter::new(config));
3070
3071    let state = HttpServerState::new().with_rate_limiter(rate_limiter);
3072
3073    assert!(state.rate_limiter.is_some());
3074    assert_eq!(state.routes.len(), 0);
3075}
3076
3077#[tokio::test]
3078async fn test_build_router_includes_rate_limiter() {
3079    let _router = build_router(None, None, None).await;
3080    // Router should be created successfully with rate limiter initialized
3081}