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