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
1324///
1325/// Note: This is a simplified implementation. For production use, consider using
1326/// a reverse proxy (nginx) for TLS termination, or use axum-server crate.
1327/// This implementation validates TLS configuration but recommends using a reverse proxy.
1328async fn serve_with_tls(
1329    addr: std::net::SocketAddr,
1330    _app: Router,
1331    tls_config: &mockforge_core::config::HttpTlsConfig,
1332) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1333    // Validate TLS configuration by attempting to load certificates
1334    let _acceptor = tls::load_tls_acceptor(tls_config)?;
1335
1336    // For now, return an informative error suggesting reverse proxy usage
1337    // Full TLS implementation with axum requires axum-server or similar
1338    Err(format!(
1339        "TLS/HTTPS support is configured but requires a reverse proxy (nginx) for production use.\n\
1340         Certificate validation passed: {} and {}\n\
1341         For native TLS support, please use a reverse proxy or wait for axum-server integration.\n\
1342         You can configure nginx with TLS termination pointing to the HTTP server on port {}.",
1343        tls_config.cert_file,
1344        tls_config.key_file,
1345        addr.port()
1346    )
1347    .into())
1348}
1349
1350/// Backwards-compatible start that builds + serves the base router.
1351pub async fn start(
1352    port: u16,
1353    spec_path: Option<String>,
1354    options: Option<ValidationOptions>,
1355) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1356    start_with_latency(port, spec_path, options, None).await
1357}
1358
1359/// Start HTTP server with authentication and latency support
1360pub async fn start_with_auth_and_latency(
1361    port: u16,
1362    spec_path: Option<String>,
1363    options: Option<ValidationOptions>,
1364    auth_config: Option<mockforge_core::config::AuthConfig>,
1365    latency_profile: Option<LatencyProfile>,
1366) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1367    start_with_auth_and_injectors(port, spec_path, options, auth_config, latency_profile, None)
1368        .await
1369}
1370
1371/// Start HTTP server with authentication and injectors support
1372pub async fn start_with_auth_and_injectors(
1373    port: u16,
1374    spec_path: Option<String>,
1375    options: Option<ValidationOptions>,
1376    auth_config: Option<mockforge_core::config::AuthConfig>,
1377    _latency_profile: Option<LatencyProfile>,
1378    _failure_injector: Option<mockforge_core::FailureInjector>,
1379) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1380    // For now, ignore latency and failure injectors and just use auth
1381    let app = build_router_with_auth(spec_path, options, auth_config).await;
1382    serve_router(port, app).await
1383}
1384
1385/// Start HTTP server with latency injection support
1386pub async fn start_with_latency(
1387    port: u16,
1388    spec_path: Option<String>,
1389    options: Option<ValidationOptions>,
1390    latency_profile: Option<LatencyProfile>,
1391) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1392    let latency_injector =
1393        latency_profile.map(|profile| LatencyInjector::new(profile, Default::default()));
1394
1395    let app = build_router_with_latency(spec_path, options, latency_injector).await;
1396    serve_router(port, app).await
1397}
1398
1399/// Build the base HTTP router with chaining support
1400pub async fn build_router_with_chains(
1401    spec_path: Option<String>,
1402    options: Option<ValidationOptions>,
1403    circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1404) -> Router {
1405    build_router_with_chains_and_multi_tenant(
1406        spec_path,
1407        options,
1408        circling_config,
1409        None,
1410        None,
1411        None,
1412        None,
1413        None,
1414        None,
1415        None,
1416        false,
1417        None, // health_manager
1418        None, // mockai
1419        None, // deceptive_deploy_config
1420        None, // proxy_config
1421    )
1422    .await
1423}
1424
1425// Template expansion is now handled by mockforge_core::template_expansion
1426// which is explicitly isolated from the templating module to avoid Send issues
1427
1428/// Helper function to apply route chaos injection (fault injection and latency)
1429/// This is extracted to avoid capturing RouteChaosInjector in the closure, which causes Send issues
1430/// Uses mockforge-route-chaos crate which is isolated from mockforge-core to avoid Send issues
1431/// Uses the RouteChaosInjectorTrait from mockforge-core to avoid circular dependency
1432async fn apply_route_chaos(
1433    injector: Option<&dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1434    method: &axum::http::Method,
1435    uri: &axum::http::Uri,
1436) -> Option<axum::response::Response> {
1437    use axum::http::StatusCode;
1438    use axum::response::IntoResponse;
1439
1440    if let Some(injector) = injector {
1441        // Check for fault injection first
1442        if let Some(fault_response) = injector.get_fault_response(method, uri) {
1443            // Return fault response
1444            let mut response = axum::Json(serde_json::json!({
1445                "error": fault_response.error_message,
1446                "fault_type": fault_response.fault_type,
1447            }))
1448            .into_response();
1449            *response.status_mut() = StatusCode::from_u16(fault_response.status_code)
1450                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1451            return Some(response);
1452        }
1453
1454        // Inject latency if configured (this is async and may delay the request)
1455        if let Err(e) = injector.inject_latency(method, uri).await {
1456            tracing::warn!("Failed to inject latency: {}", e);
1457        }
1458    }
1459
1460    None // No fault response, processing should continue
1461}
1462
1463/// Build the base HTTP router with chaining and multi-tenant support
1464#[allow(clippy::too_many_arguments)]
1465pub async fn build_router_with_chains_and_multi_tenant(
1466    spec_path: Option<String>,
1467    options: Option<ValidationOptions>,
1468    _circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1469    multi_tenant_config: Option<mockforge_core::MultiTenantConfig>,
1470    route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
1471    cors_config: Option<mockforge_core::config::HttpCorsConfig>,
1472    _ai_generator: Option<
1473        std::sync::Arc<dyn mockforge_core::openapi::response::AiGenerator + Send + Sync>,
1474    >,
1475    smtp_registry: Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
1476    mqtt_broker: Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
1477    traffic_shaper: Option<mockforge_core::traffic_shaping::TrafficShaper>,
1478    traffic_shaping_enabled: bool,
1479    health_manager: Option<std::sync::Arc<health::HealthManager>>,
1480    _mockai: Option<
1481        std::sync::Arc<tokio::sync::RwLock<mockforge_core::intelligent_behavior::MockAI>>,
1482    >,
1483    deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
1484    proxy_config: Option<mockforge_core::proxy::config::ProxyConfig>,
1485) -> Router {
1486    use crate::latency_profiles::LatencyProfiles;
1487    use crate::op_middleware::Shared;
1488    use mockforge_core::Overrides;
1489
1490    // Extract template expansion setting before options is moved (used in OpenAPI routes and custom routes)
1491    let template_expand =
1492        options.as_ref().map(|o| o.response_template_expand).unwrap_or_else(|| {
1493            std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
1494                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1495                .unwrap_or(false)
1496        });
1497
1498    let _shared = Shared {
1499        profiles: LatencyProfiles::default(),
1500        overrides: Overrides::default(),
1501        failure_injector: None,
1502        traffic_shaper,
1503        overrides_enabled: false,
1504        traffic_shaping_enabled,
1505    };
1506
1507    // Start with basic router
1508    let mut app = Router::new();
1509    let mut include_default_health = true;
1510
1511    // If an OpenAPI spec is provided, integrate it
1512    if let Some(ref spec) = spec_path {
1513        match OpenApiSpec::from_file(&spec).await {
1514            Ok(openapi) => {
1515                info!("Loaded OpenAPI spec from {}", spec);
1516
1517                // Try to load persona from config if available
1518                let persona = load_persona_from_config().await;
1519
1520                let mut registry = if let Some(opts) = options {
1521                    tracing::debug!("Using custom validation options");
1522                    if let Some(ref persona) = persona {
1523                        tracing::info!("Using persona '{}' for route generation", persona.name);
1524                    }
1525                    OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
1526                } else {
1527                    tracing::debug!("Using environment-based options");
1528                    if let Some(ref persona) = persona {
1529                        tracing::info!("Using persona '{}' for route generation", persona.name);
1530                    }
1531                    OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
1532                };
1533
1534                // Load custom fixtures if enabled
1535                let fixtures_dir = std::env::var("MOCKFORGE_FIXTURES_DIR")
1536                    .unwrap_or_else(|_| "/app/fixtures".to_string());
1537                let custom_fixtures_enabled = std::env::var("MOCKFORGE_CUSTOM_FIXTURES_ENABLED")
1538                    .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1539                    .unwrap_or(true); // Enabled by default
1540
1541                if custom_fixtures_enabled {
1542                    use mockforge_core::CustomFixtureLoader;
1543                    use std::path::PathBuf;
1544                    use std::sync::Arc;
1545
1546                    let fixtures_path = PathBuf::from(&fixtures_dir);
1547                    let mut custom_loader = CustomFixtureLoader::new(fixtures_path, true);
1548
1549                    if let Err(e) = custom_loader.load_fixtures().await {
1550                        tracing::warn!("Failed to load custom fixtures: {}", e);
1551                    } else {
1552                        tracing::info!("Custom fixtures loaded from {}", fixtures_dir);
1553                        registry = registry.with_custom_fixture_loader(Arc::new(custom_loader));
1554                    }
1555                }
1556
1557                if registry
1558                    .routes()
1559                    .iter()
1560                    .any(|route| route.method == "GET" && route.path == "/health")
1561                {
1562                    include_default_health = false;
1563                }
1564                // Use MockAI if available, otherwise use standard router
1565                let spec_router = if let Some(ref mockai_instance) = _mockai {
1566                    tracing::debug!("Building router with MockAI support");
1567                    registry.build_router_with_mockai(Some(mockai_instance.clone()))
1568                } else {
1569                    registry.build_router()
1570                };
1571                app = app.merge(spec_router);
1572            }
1573            Err(e) => {
1574                warn!("Failed to load OpenAPI spec from {:?}: {}. Starting without OpenAPI integration.", spec_path, e);
1575            }
1576        }
1577    }
1578
1579    // Register custom routes from config with advanced routing features
1580    // Create RouteChaosInjector for advanced fault injection and latency
1581    // Store as trait object to avoid circular dependency (RouteChaosInjectorTrait is in mockforge-core)
1582    let route_chaos_injector: Option<
1583        std::sync::Arc<dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1584    > = if let Some(ref route_configs) = route_configs {
1585        if !route_configs.is_empty() {
1586            match mockforge_route_chaos::RouteChaosInjector::new(route_configs.clone()) {
1587                Ok(injector) => {
1588                    info!(
1589                        "Initialized advanced routing features for {} route(s)",
1590                        route_configs.len()
1591                    );
1592                    Some(std::sync::Arc::new(injector)
1593                        as std::sync::Arc<
1594                            dyn mockforge_core::priority_handler::RouteChaosInjectorTrait,
1595                        >)
1596                }
1597                Err(e) => {
1598                    warn!(
1599                        "Failed to initialize advanced routing features: {}. Using basic routing.",
1600                        e
1601                    );
1602                    None
1603                }
1604            }
1605        } else {
1606            None
1607        }
1608    } else {
1609        None
1610    };
1611
1612    if let Some(route_configs) = route_configs {
1613        use axum::http::StatusCode;
1614        use axum::response::IntoResponse;
1615
1616        if !route_configs.is_empty() {
1617            info!("Registering {} custom route(s) from config", route_configs.len());
1618        }
1619
1620        let injector = route_chaos_injector.clone();
1621        for route_config in route_configs {
1622            let status = route_config.response.status;
1623            let body = route_config.response.body.clone();
1624            let headers = route_config.response.headers.clone();
1625            let path = route_config.path.clone();
1626            let method = route_config.method.clone();
1627
1628            // Create handler that returns the configured response with template expansion
1629            // Supports both basic templates ({{uuid}}, {{now}}) and request-aware templates
1630            // ({{request.query.name}}, {{request.path.id}}, {{request.headers.name}})
1631            // Register route using `any()` since we need full Request access for template expansion
1632            let expected_method = method.to_uppercase();
1633            // Clone Arc for the closure - Arc is Send-safe
1634            // Note: RouteChaosInjector is marked as Send+Sync via unsafe impl, but the compiler
1635            // is conservative because rng() is available in the rand crate, even though we use thread_rng()
1636            let injector_clone = injector.clone();
1637            app = app.route(
1638                &path,
1639                #[allow(clippy::non_send_fields_in_send_ty)]
1640                axum::routing::any(move |req: axum::http::Request<axum::body::Body>| {
1641                    let body = body.clone();
1642                    let headers = headers.clone();
1643                    let expand = template_expand;
1644                    let expected = expected_method.clone();
1645                    let status_code = status;
1646                    // Clone Arc again for the async block
1647                    let injector_for_chaos = injector_clone.clone();
1648
1649                    async move {
1650                        // Check if request method matches expected method
1651                        if req.method().as_str() != expected.as_str() {
1652                            // Return 405 Method Not Allowed for wrong method
1653                            return axum::response::Response::builder()
1654                                .status(axum::http::StatusCode::METHOD_NOT_ALLOWED)
1655                                .header("Allow", &expected)
1656                                .body(axum::body::Body::empty())
1657                                .unwrap()
1658                                .into_response();
1659                        }
1660
1661                        // Apply advanced routing features (fault injection and latency) if available
1662                        // Use helper function to avoid capturing RouteChaosInjector in closure
1663                        // Pass the Arc as a reference to the helper function
1664                        if let Some(fault_response) = apply_route_chaos(
1665                            injector_for_chaos.as_deref(),
1666                            req.method(),
1667                            req.uri(),
1668                        )
1669                        .await
1670                        {
1671                            return fault_response;
1672                        }
1673
1674                        // Create JSON response from body, or empty object if None
1675                        let mut body_value = body.unwrap_or(serde_json::json!({}));
1676
1677                        // Apply template expansion if enabled
1678                        // Use mockforge-template-expansion crate which is completely isolated
1679                        // from mockforge-core to avoid Send issues (no rng() in dependency chain)
1680                        if expand {
1681                            use mockforge_template_expansion::RequestContext;
1682                            use serde_json::Value;
1683                            use std::collections::HashMap;
1684
1685                            // Extract request data for template expansion
1686                            let method = req.method().to_string();
1687                            let path = req.uri().path().to_string();
1688
1689                            // Extract query parameters
1690                            let query_params: HashMap<String, Value> = req
1691                                .uri()
1692                                .query()
1693                                .map(|q| {
1694                                    url::form_urlencoded::parse(q.as_bytes())
1695                                        .into_owned()
1696                                        .map(|(k, v)| (k, Value::String(v)))
1697                                        .collect()
1698                                })
1699                                .unwrap_or_default();
1700
1701                            // Extract headers
1702                            let headers: HashMap<String, Value> = req
1703                                .headers()
1704                                .iter()
1705                                .map(|(k, v)| {
1706                                    (
1707                                        k.to_string(),
1708                                        Value::String(v.to_str().unwrap_or_default().to_string()),
1709                                    )
1710                                })
1711                                .collect();
1712
1713                            // Create RequestContext for expand_prompt_template
1714                            // Using RequestContext from mockforge-template-expansion (not mockforge-core)
1715                            // to avoid bringing rng() into scope
1716                            let context = RequestContext {
1717                                method,
1718                                path,
1719                                query_params,
1720                                headers,
1721                                body: None, // Body extraction would require reading the request stream
1722                                path_params: HashMap::new(),
1723                                multipart_fields: HashMap::new(),
1724                                multipart_files: HashMap::new(),
1725                            };
1726
1727                            // Perform template expansion in spawn_blocking to ensure Send safety
1728                            // The template expansion crate is completely isolated from mockforge-core
1729                            // and doesn't have rng() in its dependency chain
1730                            let body_value_clone = body_value.clone();
1731                            let context_clone = context.clone();
1732                            body_value = match tokio::task::spawn_blocking(move || {
1733                                mockforge_template_expansion::expand_templates_in_json(
1734                                    body_value_clone,
1735                                    &context_clone,
1736                                )
1737                            })
1738                            .await
1739                            {
1740                                Ok(result) => result,
1741                                Err(_) => body_value, // Fallback to original on error
1742                            };
1743                        }
1744
1745                        let mut response = axum::Json(body_value).into_response();
1746
1747                        // Set status code
1748                        *response.status_mut() =
1749                            StatusCode::from_u16(status_code).unwrap_or(StatusCode::OK);
1750
1751                        // Add custom headers
1752                        for (key, value) in headers {
1753                            if let Ok(header_name) =
1754                                axum::http::HeaderName::from_bytes(key.as_bytes())
1755                            {
1756                                if let Ok(header_value) = axum::http::HeaderValue::from_str(&value)
1757                                {
1758                                    response.headers_mut().insert(header_name, header_value);
1759                                }
1760                            }
1761                        }
1762
1763                        response
1764                    }
1765                }),
1766            );
1767
1768            debug!("Registered route: {} {}", method, path);
1769        }
1770    }
1771
1772    // Add health check endpoints
1773    if let Some(health) = health_manager {
1774        // Use comprehensive health check router with all probe endpoints
1775        app = app.merge(health::health_router(health));
1776        info!(
1777            "Health check endpoints enabled: /health, /health/live, /health/ready, /health/startup"
1778        );
1779    } else if include_default_health {
1780        // Fallback to basic health endpoint for backwards compatibility
1781        app = app.route(
1782            "/health",
1783            axum::routing::get(|| async {
1784                use mockforge_core::server_utils::health::HealthStatus;
1785                {
1786                    // HealthStatus should always serialize, but handle errors gracefully
1787                    match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1788                        Ok(value) => axum::Json(value),
1789                        Err(e) => {
1790                            // Log error but return a simple healthy response
1791                            tracing::error!("Failed to serialize health status: {}", e);
1792                            axum::Json(serde_json::json!({
1793                                "status": "healthy",
1794                                "service": "mockforge-http",
1795                                "uptime_seconds": 0
1796                            }))
1797                        }
1798                    }
1799                }
1800            }),
1801        );
1802    }
1803
1804    app = app.merge(sse::sse_router());
1805    // Add file serving endpoints for generated mock files
1806    app = app.merge(file_server::file_serving_router());
1807
1808    // Add management API endpoints
1809    let spec_path_clone = spec_path.clone();
1810    let management_state = ManagementState::new(None, spec_path_clone, 3000); // Port will be updated when we know the actual port
1811
1812    // Create WebSocket state and connect it to management state
1813    use std::sync::Arc;
1814    let ws_state = WsManagementState::new();
1815    let ws_broadcast = Arc::new(ws_state.tx.clone());
1816    let management_state = management_state.with_ws_broadcast(ws_broadcast);
1817
1818    // Add proxy config to management state if available
1819    let management_state = if let Some(proxy_cfg) = proxy_config {
1820        use tokio::sync::RwLock;
1821        let proxy_config_arc = Arc::new(RwLock::new(proxy_cfg));
1822        management_state.with_proxy_config(proxy_config_arc)
1823    } else {
1824        management_state
1825    };
1826
1827    #[cfg(feature = "smtp")]
1828    let management_state = {
1829        if let Some(smtp_reg) = smtp_registry {
1830            match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
1831                Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
1832                Err(e) => {
1833                    error!(
1834                        "Invalid SMTP registry type passed to HTTP management state: {:?}",
1835                        e.type_id()
1836                    );
1837                    management_state
1838                }
1839            }
1840        } else {
1841            management_state
1842        }
1843    };
1844    #[cfg(not(feature = "smtp"))]
1845    let management_state = {
1846        let _ = smtp_registry;
1847        management_state
1848    };
1849    #[cfg(feature = "mqtt")]
1850    let management_state = {
1851        if let Some(broker) = mqtt_broker {
1852            match broker.downcast::<mockforge_mqtt::MqttBroker>() {
1853                Ok(broker) => management_state.with_mqtt_broker(broker),
1854                Err(e) => {
1855                    error!(
1856                        "Invalid MQTT broker passed to HTTP management state: {:?}",
1857                        e.type_id()
1858                    );
1859                    management_state
1860                }
1861            }
1862        } else {
1863            management_state
1864        }
1865    };
1866    #[cfg(not(feature = "mqtt"))]
1867    let management_state = {
1868        let _ = mqtt_broker;
1869        management_state
1870    };
1871    app = app.nest("/__mockforge/api", management_router(management_state));
1872
1873    // Add verification API endpoint
1874    app = app.merge(verification_router());
1875
1876    // Add OIDC well-known endpoints
1877    use crate::auth::oidc::oidc_router;
1878    app = app.merge(oidc_router());
1879
1880    // Add access review API if enabled
1881    {
1882        use mockforge_core::security::get_global_access_review_service;
1883        if let Some(service) = get_global_access_review_service().await {
1884            use crate::handlers::access_review::{access_review_router, AccessReviewState};
1885            let review_state = AccessReviewState { service };
1886            app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
1887            debug!("Access review API mounted at /api/v1/security/access-reviews");
1888        }
1889    }
1890
1891    // Add privileged access API if enabled
1892    {
1893        use mockforge_core::security::get_global_privileged_access_manager;
1894        if let Some(manager) = get_global_privileged_access_manager().await {
1895            use crate::handlers::privileged_access::{
1896                privileged_access_router, PrivilegedAccessState,
1897            };
1898            let privileged_state = PrivilegedAccessState { manager };
1899            app = app.nest(
1900                "/api/v1/security/privileged-access",
1901                privileged_access_router(privileged_state),
1902            );
1903            debug!("Privileged access API mounted at /api/v1/security/privileged-access");
1904        }
1905    }
1906
1907    // Add change management API if enabled
1908    {
1909        use mockforge_core::security::get_global_change_management_engine;
1910        if let Some(engine) = get_global_change_management_engine().await {
1911            use crate::handlers::change_management::{
1912                change_management_router, ChangeManagementState,
1913            };
1914            let change_state = ChangeManagementState { engine };
1915            app = app.nest("/api/v1/change-management", change_management_router(change_state));
1916            debug!("Change management API mounted at /api/v1/change-management");
1917        }
1918    }
1919
1920    // Add risk assessment API if enabled
1921    {
1922        use mockforge_core::security::get_global_risk_assessment_engine;
1923        if let Some(engine) = get_global_risk_assessment_engine().await {
1924            use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
1925            let risk_state = RiskAssessmentState { engine };
1926            app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
1927            debug!("Risk assessment API mounted at /api/v1/security/risks");
1928        }
1929    }
1930
1931    // Add token lifecycle API
1932    {
1933        use crate::auth::token_lifecycle::TokenLifecycleManager;
1934        use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
1935        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1936        let lifecycle_state = TokenLifecycleState {
1937            manager: lifecycle_manager,
1938        };
1939        app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
1940        debug!("Token lifecycle API mounted at /api/v1/auth");
1941    }
1942
1943    // Add OAuth2 server endpoints
1944    {
1945        use crate::auth::oidc::load_oidc_state;
1946        use crate::auth::token_lifecycle::TokenLifecycleManager;
1947        use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
1948        // Load OIDC state from configuration (environment variables or config file)
1949        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1950        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1951        let oauth2_state = OAuth2ServerState {
1952            oidc_state,
1953            lifecycle_manager,
1954            auth_codes: Arc::new(RwLock::new(HashMap::new())),
1955        };
1956        app = app.merge(oauth2_server_router(oauth2_state));
1957        debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
1958    }
1959
1960    // Add consent screen endpoints
1961    {
1962        use crate::auth::oidc::load_oidc_state;
1963        use crate::auth::risk_engine::RiskEngine;
1964        use crate::auth::token_lifecycle::TokenLifecycleManager;
1965        use crate::handlers::consent::{consent_router, ConsentState};
1966        use crate::handlers::oauth2_server::OAuth2ServerState;
1967        // Load OIDC state from configuration (environment variables or config file)
1968        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1969        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1970        let oauth2_state = OAuth2ServerState {
1971            oidc_state: oidc_state.clone(),
1972            lifecycle_manager: lifecycle_manager.clone(),
1973            auth_codes: Arc::new(RwLock::new(HashMap::new())),
1974        };
1975        let risk_engine = Arc::new(RiskEngine::default());
1976        let consent_state = ConsentState {
1977            oauth2_state,
1978            risk_engine,
1979        };
1980        app = app.merge(consent_router(consent_state));
1981        debug!("Consent screen endpoints mounted at /consent");
1982    }
1983
1984    // Add risk simulation API
1985    {
1986        use crate::auth::risk_engine::RiskEngine;
1987        use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
1988        let risk_engine = Arc::new(RiskEngine::default());
1989        let risk_state = RiskSimulationState { risk_engine };
1990        app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
1991        debug!("Risk simulation API mounted at /api/v1/auth/risk");
1992    }
1993
1994    // Initialize database connection (optional)
1995    let database = {
1996        use crate::database::Database;
1997        let database_url = std::env::var("DATABASE_URL").ok();
1998        match Database::connect_optional(database_url.as_deref()).await {
1999            Ok(db) => {
2000                if db.is_connected() {
2001                    // Run migrations if database is connected
2002                    if let Err(e) = db.migrate_if_connected().await {
2003                        warn!("Failed to run database migrations: {}", e);
2004                    } else {
2005                        info!("Database connected and migrations applied");
2006                    }
2007                }
2008                Some(db)
2009            }
2010            Err(e) => {
2011                warn!("Failed to connect to database: {}. Continuing without database support.", e);
2012                None
2013            }
2014        }
2015    };
2016
2017    // Add drift budget and incident management endpoints
2018    // Initialize shared components for drift tracking and protocol contracts
2019    let (drift_engine, incident_manager, drift_config) = {
2020        use mockforge_core::contract_drift::{DriftBudgetConfig, DriftBudgetEngine};
2021        use mockforge_core::incidents::{IncidentManager, IncidentStore};
2022        use std::sync::Arc;
2023
2024        // Initialize drift budget engine with default config
2025        let drift_config = DriftBudgetConfig::default();
2026        let drift_engine = Arc::new(DriftBudgetEngine::new(drift_config.clone()));
2027
2028        // Initialize incident store and manager
2029        let incident_store = Arc::new(IncidentStore::default());
2030        let incident_manager = Arc::new(IncidentManager::new(incident_store.clone()));
2031
2032        (drift_engine, incident_manager, drift_config)
2033    };
2034
2035    {
2036        use crate::handlers::drift_budget::{drift_budget_router, DriftBudgetState};
2037        use crate::middleware::drift_tracking::DriftTrackingState;
2038        use mockforge_core::ai_contract_diff::ContractDiffAnalyzer;
2039        use mockforge_core::consumer_contracts::{ConsumerBreakingChangeDetector, UsageRecorder};
2040        use std::sync::Arc;
2041
2042        // Initialize usage recorder and consumer detector
2043        let usage_recorder = Arc::new(UsageRecorder::default());
2044        let consumer_detector =
2045            Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2046
2047        // Initialize contract diff analyzer if enabled
2048        let diff_analyzer = if drift_config.enabled {
2049            match ContractDiffAnalyzer::new(
2050                mockforge_core::ai_contract_diff::ContractDiffConfig::default(),
2051            ) {
2052                Ok(analyzer) => Some(Arc::new(analyzer)),
2053                Err(e) => {
2054                    warn!("Failed to create contract diff analyzer: {}", e);
2055                    None
2056                }
2057            }
2058        } else {
2059            None
2060        };
2061
2062        // Get OpenAPI spec if available
2063        // Note: Load from spec_path if available, or leave as None for manual configuration.
2064        let spec = if let Some(ref spec_path) = spec_path {
2065            match mockforge_core::openapi::OpenApiSpec::from_file(spec_path).await {
2066                Ok(s) => Some(Arc::new(s)),
2067                Err(e) => {
2068                    debug!("Failed to load OpenAPI spec for drift tracking: {}", e);
2069                    None
2070                }
2071            }
2072        } else {
2073            None
2074        };
2075
2076        // Create drift tracking state
2077        let drift_tracking_state = DriftTrackingState {
2078            diff_analyzer,
2079            spec,
2080            drift_engine: drift_engine.clone(),
2081            incident_manager: incident_manager.clone(),
2082            usage_recorder,
2083            consumer_detector,
2084            enabled: drift_config.enabled,
2085        };
2086
2087        // Add response body buffering middleware (before drift tracking)
2088        app = app.layer(axum::middleware::from_fn(crate::middleware::buffer_response_middleware));
2089
2090        // Add drift tracking middleware (after response buffering)
2091        // Use a wrapper that inserts state into extensions before calling the middleware
2092        let drift_tracking_state_clone = drift_tracking_state.clone();
2093        app = app.layer(axum::middleware::from_fn(
2094            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2095                let state = drift_tracking_state_clone.clone();
2096                async move {
2097                    // Insert state into extensions if not already present
2098                    if req
2099                        .extensions()
2100                        .get::<crate::middleware::drift_tracking::DriftTrackingState>()
2101                        .is_none()
2102                    {
2103                        req.extensions_mut().insert(state);
2104                    }
2105                    // Call the middleware function
2106                    crate::middleware::drift_tracking::drift_tracking_middleware_with_extensions(
2107                        req, next,
2108                    )
2109                    .await
2110                }
2111            },
2112        ));
2113
2114        let drift_state = DriftBudgetState {
2115            engine: drift_engine.clone(),
2116            incident_manager: incident_manager.clone(),
2117            gitops_handler: None, // Can be initialized later if GitOps is configured
2118        };
2119
2120        app = app.merge(drift_budget_router(drift_state));
2121        debug!("Drift budget and incident management endpoints mounted at /api/v1/drift");
2122    }
2123
2124    // Add pipeline management endpoints (MockOps)
2125    #[cfg(feature = "pipelines")]
2126    {
2127        use crate::handlers::pipelines::{pipeline_router, PipelineState};
2128
2129        let pipeline_state = PipelineState::new();
2130        app = app.merge(pipeline_router(pipeline_state));
2131        debug!("Pipeline management endpoints mounted at /api/v1/pipelines");
2132    }
2133
2134    // Add governance endpoints (forecasting, semantic drift, threat modeling, contract health)
2135    {
2136        use crate::handlers::contract_health::{contract_health_router, ContractHealthState};
2137        use crate::handlers::forecasting::{forecasting_router, ForecastingState};
2138        use crate::handlers::semantic_drift::{semantic_drift_router, SemanticDriftState};
2139        use crate::handlers::threat_modeling::{threat_modeling_router, ThreatModelingState};
2140        use mockforge_core::contract_drift::forecasting::{Forecaster, ForecastingConfig};
2141        use mockforge_core::contract_drift::threat_modeling::{
2142            ThreatAnalyzer, ThreatModelingConfig,
2143        };
2144        use mockforge_core::incidents::semantic_manager::SemanticIncidentManager;
2145        use std::sync::Arc;
2146
2147        // Initialize forecasting
2148        let forecasting_config = ForecastingConfig::default();
2149        let forecaster = Arc::new(Forecaster::new(forecasting_config));
2150        let forecasting_state = ForecastingState {
2151            forecaster,
2152            database: database.clone(),
2153        };
2154
2155        // Initialize semantic drift manager
2156        let semantic_manager = Arc::new(SemanticIncidentManager::new());
2157        let semantic_state = SemanticDriftState {
2158            manager: semantic_manager,
2159            database: database.clone(),
2160        };
2161
2162        // Initialize threat analyzer
2163        let threat_config = ThreatModelingConfig::default();
2164        let threat_analyzer = match ThreatAnalyzer::new(threat_config) {
2165            Ok(analyzer) => Arc::new(analyzer),
2166            Err(e) => {
2167                warn!("Failed to create threat analyzer: {}. Using default.", e);
2168                Arc::new(ThreatAnalyzer::new(ThreatModelingConfig::default()).unwrap_or_else(
2169                    |_| {
2170                        // Fallback to a minimal config if default also fails
2171                        ThreatAnalyzer::new(ThreatModelingConfig {
2172                            enabled: false,
2173                            ..Default::default()
2174                        })
2175                        .expect("Failed to create fallback threat analyzer")
2176                    },
2177                ))
2178            }
2179        };
2180        // Load webhook configs from ServerConfig
2181        let mut webhook_configs = Vec::new();
2182        let config_paths = [
2183            "config.yaml",
2184            "mockforge.yaml",
2185            "tools/mockforge/config.yaml",
2186            "../tools/mockforge/config.yaml",
2187        ];
2188
2189        for path in &config_paths {
2190            if let Ok(config) = mockforge_core::config::load_config(path).await {
2191                if !config.incidents.webhooks.is_empty() {
2192                    webhook_configs = config.incidents.webhooks.clone();
2193                    info!("Loaded {} webhook configs from config: {}", webhook_configs.len(), path);
2194                    break;
2195                }
2196            }
2197        }
2198
2199        if webhook_configs.is_empty() {
2200            debug!("No webhook configs found in config files, using empty list");
2201        }
2202
2203        let threat_state = ThreatModelingState {
2204            analyzer: threat_analyzer,
2205            webhook_configs,
2206            database: database.clone(),
2207        };
2208
2209        // Initialize contract health state
2210        let contract_health_state = ContractHealthState {
2211            incident_manager: incident_manager.clone(),
2212            semantic_manager: Arc::new(SemanticIncidentManager::new()),
2213            database: database.clone(),
2214        };
2215
2216        // Register routers
2217        app = app.merge(forecasting_router(forecasting_state));
2218        debug!("Forecasting endpoints mounted at /api/v1/forecasts");
2219
2220        app = app.merge(semantic_drift_router(semantic_state));
2221        debug!("Semantic drift endpoints mounted at /api/v1/semantic-drift");
2222
2223        app = app.merge(threat_modeling_router(threat_state));
2224        debug!("Threat modeling endpoints mounted at /api/v1/threats");
2225
2226        app = app.merge(contract_health_router(contract_health_state));
2227        debug!("Contract health endpoints mounted at /api/v1/contract-health");
2228    }
2229
2230    // Add protocol contracts endpoints with fitness registry initialization
2231    {
2232        use crate::handlers::protocol_contracts::{
2233            protocol_contracts_router, ProtocolContractState,
2234        };
2235        use mockforge_core::contract_drift::{
2236            ConsumerImpactAnalyzer, FitnessFunctionRegistry, ProtocolContractRegistry,
2237        };
2238        use std::sync::Arc;
2239        use tokio::sync::RwLock;
2240
2241        // Initialize protocol contract registry
2242        let contract_registry = Arc::new(RwLock::new(ProtocolContractRegistry::new()));
2243
2244        // Initialize fitness function registry and load from config
2245        let mut fitness_registry = FitnessFunctionRegistry::new();
2246
2247        // Try to load config and populate fitness rules
2248        let config_paths = [
2249            "config.yaml",
2250            "mockforge.yaml",
2251            "tools/mockforge/config.yaml",
2252            "../tools/mockforge/config.yaml",
2253        ];
2254
2255        let mut config_loaded = false;
2256        for path in &config_paths {
2257            if let Ok(config) = mockforge_core::config::load_config(path).await {
2258                if !config.contracts.fitness_rules.is_empty() {
2259                    if let Err(e) =
2260                        fitness_registry.load_from_config(&config.contracts.fitness_rules)
2261                    {
2262                        warn!("Failed to load fitness rules from config {}: {}", path, e);
2263                    } else {
2264                        info!(
2265                            "Loaded {} fitness rules from config: {}",
2266                            config.contracts.fitness_rules.len(),
2267                            path
2268                        );
2269                        config_loaded = true;
2270                        break;
2271                    }
2272                }
2273            }
2274        }
2275
2276        if !config_loaded {
2277            debug!("No fitness rules found in config files, using empty registry");
2278        }
2279
2280        let fitness_registry = Arc::new(RwLock::new(fitness_registry));
2281
2282        // Reuse drift engine and incident manager from drift budget section
2283
2284        // Initialize consumer impact analyzer
2285        let consumer_mapping_registry =
2286            mockforge_core::contract_drift::ConsumerMappingRegistry::new();
2287        let consumer_analyzer =
2288            Arc::new(RwLock::new(ConsumerImpactAnalyzer::new(consumer_mapping_registry)));
2289
2290        let protocol_state = ProtocolContractState {
2291            registry: contract_registry,
2292            drift_engine: Some(drift_engine.clone()),
2293            incident_manager: Some(incident_manager.clone()),
2294            fitness_registry: Some(fitness_registry),
2295            consumer_analyzer: Some(consumer_analyzer),
2296        };
2297
2298        app = app.nest("/api/v1/contracts", protocol_contracts_router(protocol_state));
2299        debug!("Protocol contracts endpoints mounted at /api/v1/contracts");
2300    }
2301
2302    // Add behavioral cloning middleware (optional - applies learned behavior to requests)
2303    #[cfg(feature = "behavioral-cloning")]
2304    {
2305        use crate::middleware::behavioral_cloning::BehavioralCloningMiddlewareState;
2306        use std::path::PathBuf;
2307
2308        // Determine database path (defaults to ./recordings.db)
2309        let db_path = std::env::var("RECORDER_DATABASE_PATH")
2310            .ok()
2311            .map(PathBuf::from)
2312            .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2313
2314        let bc_middleware_state = if let Some(path) = db_path {
2315            BehavioralCloningMiddlewareState::with_database_path(path)
2316        } else {
2317            BehavioralCloningMiddlewareState::new()
2318        };
2319
2320        // Only enable if BEHAVIORAL_CLONING_ENABLED is set to true
2321        let enabled = std::env::var("BEHAVIORAL_CLONING_ENABLED")
2322            .ok()
2323            .and_then(|v| v.parse::<bool>().ok())
2324            .unwrap_or(false);
2325
2326        if enabled {
2327            let bc_state_clone = bc_middleware_state.clone();
2328            app = app.layer(axum::middleware::from_fn(
2329                move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2330                    let state = bc_state_clone.clone();
2331                    async move {
2332                        // Insert state into extensions if not already present
2333                        if req.extensions().get::<BehavioralCloningMiddlewareState>().is_none() {
2334                            req.extensions_mut().insert(state);
2335                        }
2336                        // Call the middleware function
2337                        crate::middleware::behavioral_cloning::behavioral_cloning_middleware(
2338                            req, next,
2339                        )
2340                        .await
2341                    }
2342                },
2343            ));
2344            debug!("Behavioral cloning middleware enabled (applies learned behavior to requests)");
2345        }
2346    }
2347
2348    // Add consumer contracts endpoints
2349    {
2350        use crate::handlers::consumer_contracts::{
2351            consumer_contracts_router, ConsumerContractsState,
2352        };
2353        use mockforge_core::consumer_contracts::{
2354            ConsumerBreakingChangeDetector, ConsumerRegistry, UsageRecorder,
2355        };
2356        use std::sync::Arc;
2357
2358        // Initialize consumer registry
2359        let registry = Arc::new(ConsumerRegistry::default());
2360
2361        // Initialize usage recorder
2362        let usage_recorder = Arc::new(UsageRecorder::default());
2363
2364        // Initialize breaking change detector
2365        let detector = Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2366
2367        let consumer_state = ConsumerContractsState {
2368            registry,
2369            usage_recorder,
2370            detector,
2371        };
2372
2373        app = app.merge(consumer_contracts_router(consumer_state));
2374        debug!("Consumer contracts endpoints mounted at /api/v1/consumers");
2375    }
2376
2377    // Add behavioral cloning endpoints
2378    #[cfg(feature = "behavioral-cloning")]
2379    {
2380        use crate::handlers::behavioral_cloning::{
2381            behavioral_cloning_router, BehavioralCloningState,
2382        };
2383        use std::path::PathBuf;
2384
2385        // Determine database path (defaults to ./recordings.db)
2386        let db_path = std::env::var("RECORDER_DATABASE_PATH")
2387            .ok()
2388            .map(PathBuf::from)
2389            .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2390
2391        let bc_state = if let Some(path) = db_path {
2392            BehavioralCloningState::with_database_path(path)
2393        } else {
2394            BehavioralCloningState::new()
2395        };
2396
2397        app = app.merge(behavioral_cloning_router(bc_state));
2398        debug!("Behavioral cloning endpoints mounted at /api/v1/behavioral-cloning");
2399    }
2400
2401    // Add consistency engine and cross-protocol state management
2402    {
2403        use crate::consistency::{ConsistencyMiddlewareState, HttpAdapter};
2404        use crate::handlers::consistency::{consistency_router, ConsistencyState};
2405        use mockforge_core::consistency::ConsistencyEngine;
2406        use std::sync::Arc;
2407
2408        // Initialize consistency engine
2409        let consistency_engine = Arc::new(ConsistencyEngine::new());
2410
2411        // Create and register HTTP adapter
2412        let http_adapter = Arc::new(HttpAdapter::new(consistency_engine.clone()));
2413        consistency_engine.register_adapter(http_adapter.clone()).await;
2414
2415        // Create consistency state for handlers
2416        let consistency_state = ConsistencyState {
2417            engine: consistency_engine.clone(),
2418        };
2419
2420        // Create X-Ray state first (needed for middleware)
2421        use crate::handlers::xray::XRayState;
2422        let xray_state = Arc::new(XRayState {
2423            engine: consistency_engine.clone(),
2424            request_contexts: std::sync::Arc::new(tokio::sync::RwLock::new(
2425                std::collections::HashMap::new(),
2426            )),
2427        });
2428
2429        // Create consistency middleware state
2430        let consistency_middleware_state = ConsistencyMiddlewareState {
2431            engine: consistency_engine.clone(),
2432            adapter: http_adapter,
2433            xray_state: Some(xray_state.clone()),
2434        };
2435
2436        // Add consistency middleware (before other middleware to inject state early)
2437        let consistency_middleware_state_clone = consistency_middleware_state.clone();
2438        app = app.layer(axum::middleware::from_fn(
2439            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2440                let state = consistency_middleware_state_clone.clone();
2441                async move {
2442                    // Insert state into extensions if not already present
2443                    if req.extensions().get::<ConsistencyMiddlewareState>().is_none() {
2444                        req.extensions_mut().insert(state);
2445                    }
2446                    // Call the middleware function
2447                    crate::consistency::middleware::consistency_middleware(req, next).await
2448                }
2449            },
2450        ));
2451
2452        // Add consistency API endpoints
2453        app = app.merge(consistency_router(consistency_state));
2454        debug!("Consistency engine initialized and endpoints mounted at /api/v1/consistency");
2455
2456        // Add fidelity score endpoints
2457        {
2458            use crate::handlers::fidelity::{fidelity_router, FidelityState};
2459            let fidelity_state = FidelityState::new();
2460            app = app.merge(fidelity_router(fidelity_state));
2461            debug!("Fidelity score endpoints mounted at /api/v1/workspace/:workspace_id/fidelity");
2462        }
2463
2464        // Add scenario studio endpoints
2465        {
2466            use crate::handlers::scenario_studio::{scenario_studio_router, ScenarioStudioState};
2467            let scenario_studio_state = ScenarioStudioState::new();
2468            app = app.merge(scenario_studio_router(scenario_studio_state));
2469            debug!("Scenario Studio endpoints mounted at /api/v1/scenario-studio");
2470        }
2471
2472        // Add performance mode endpoints
2473        {
2474            use crate::handlers::performance::{performance_router, PerformanceState};
2475            let performance_state = PerformanceState::new();
2476            app = app.nest("/api/performance", performance_router(performance_state));
2477            debug!("Performance mode endpoints mounted at /api/performance");
2478        }
2479
2480        // Add world state endpoints
2481        {
2482            use crate::handlers::world_state::{world_state_router, WorldStateState};
2483            use mockforge_world_state::WorldStateEngine;
2484            use std::sync::Arc;
2485            use tokio::sync::RwLock;
2486
2487            let world_state_engine = Arc::new(RwLock::new(WorldStateEngine::new()));
2488            let world_state_state = WorldStateState {
2489                engine: world_state_engine,
2490            };
2491            app = app.nest("/api/world-state", world_state_router().with_state(world_state_state));
2492            debug!("World state endpoints mounted at /api/world-state");
2493        }
2494
2495        // Add snapshot management endpoints
2496        {
2497            use crate::handlers::snapshots::{snapshot_router, SnapshotState};
2498            use mockforge_core::snapshots::SnapshotManager;
2499            use std::path::PathBuf;
2500
2501            let snapshot_dir = std::env::var("MOCKFORGE_SNAPSHOT_DIR").ok().map(PathBuf::from);
2502            let snapshot_manager = Arc::new(SnapshotManager::new(snapshot_dir));
2503
2504            let snapshot_state = SnapshotState {
2505                manager: snapshot_manager,
2506                consistency_engine: Some(consistency_engine.clone()),
2507                workspace_persistence: None, // Can be initialized later if workspace persistence is available
2508                vbr_engine: None, // Can be initialized when VBR engine is available in server state
2509                recorder: None, // Can be initialized when Recorder is available in server state
2510            };
2511
2512            app = app.merge(snapshot_router(snapshot_state));
2513            debug!("Snapshot management endpoints mounted at /api/v1/snapshots");
2514
2515            // Add X-Ray API endpoints for browser extension
2516            {
2517                use crate::handlers::xray::xray_router;
2518                app = app.merge(xray_router((*xray_state).clone()));
2519                debug!("X-Ray API endpoints mounted at /api/v1/xray");
2520            }
2521        }
2522
2523        // Add A/B testing endpoints and middleware
2524        {
2525            use crate::handlers::ab_testing::{ab_testing_router, ABTestingState};
2526            use crate::middleware::ab_testing::ab_testing_middleware;
2527
2528            let ab_testing_state = ABTestingState::new();
2529
2530            // Add A/B testing middleware (before other response middleware)
2531            let ab_testing_state_clone = ab_testing_state.clone();
2532            app = app.layer(axum::middleware::from_fn(
2533                move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2534                    let state = ab_testing_state_clone.clone();
2535                    async move {
2536                        // Insert state into extensions if not already present
2537                        if req.extensions().get::<ABTestingState>().is_none() {
2538                            req.extensions_mut().insert(state);
2539                        }
2540                        // Call the middleware function
2541                        ab_testing_middleware(req, next).await
2542                    }
2543                },
2544            ));
2545
2546            // Add A/B testing API endpoints
2547            app = app.merge(ab_testing_router(ab_testing_state));
2548            debug!("A/B testing endpoints mounted at /api/v1/ab-tests");
2549        }
2550    }
2551
2552    // Add PR generation endpoints (optional - only if configured)
2553    {
2554        use crate::handlers::pr_generation::{pr_generation_router, PRGenerationState};
2555        use mockforge_core::pr_generation::{PRGenerator, PRProvider};
2556        use std::sync::Arc;
2557
2558        // Load PR generation config from environment or use default
2559        let pr_config = mockforge_core::pr_generation::PRGenerationConfig::from_env();
2560
2561        let generator = if pr_config.enabled && pr_config.token.is_some() {
2562            let token = pr_config.token.as_ref().unwrap().clone();
2563            let generator = match pr_config.provider {
2564                PRProvider::GitHub => PRGenerator::new_github(
2565                    pr_config.owner.clone(),
2566                    pr_config.repo.clone(),
2567                    token,
2568                    pr_config.base_branch.clone(),
2569                ),
2570                PRProvider::GitLab => PRGenerator::new_gitlab(
2571                    pr_config.owner.clone(),
2572                    pr_config.repo.clone(),
2573                    token,
2574                    pr_config.base_branch.clone(),
2575                ),
2576            };
2577            Some(Arc::new(generator))
2578        } else {
2579            None
2580        };
2581
2582        let pr_state = PRGenerationState {
2583            generator: generator.clone(),
2584        };
2585
2586        app = app.merge(pr_generation_router(pr_state));
2587        if generator.is_some() {
2588            debug!(
2589                "PR generation endpoints mounted at /api/v1/pr (configured for {:?})",
2590                pr_config.provider
2591            );
2592        } else {
2593            debug!("PR generation endpoints mounted at /api/v1/pr (not configured - set GITHUB_TOKEN/GITLAB_TOKEN and PR_REPO_OWNER/PR_REPO_NAME)");
2594        }
2595    }
2596
2597    // Add management WebSocket endpoint
2598    app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
2599
2600    // Add workspace routing middleware if multi-tenant is enabled
2601    if let Some(mt_config) = multi_tenant_config {
2602        if mt_config.enabled {
2603            use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
2604            use std::sync::Arc;
2605
2606            info!(
2607                "Multi-tenant mode enabled with {} routing strategy",
2608                match mt_config.routing_strategy {
2609                    mockforge_core::RoutingStrategy::Path => "path-based",
2610                    mockforge_core::RoutingStrategy::Port => "port-based",
2611                    mockforge_core::RoutingStrategy::Both => "hybrid",
2612                }
2613            );
2614
2615            // Create the multi-tenant workspace registry
2616            let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
2617
2618            // Register the default workspace before wrapping in Arc
2619            let default_workspace =
2620                mockforge_core::Workspace::new(mt_config.default_workspace.clone());
2621            if let Err(e) =
2622                registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
2623            {
2624                warn!("Failed to register default workspace: {}", e);
2625            } else {
2626                info!("Registered default workspace: '{}'", mt_config.default_workspace);
2627            }
2628
2629            // Wrap registry in Arc for shared access
2630            let registry = Arc::new(registry);
2631
2632            // Create workspace router
2633            let _workspace_router = WorkspaceRouter::new(registry);
2634            info!("Workspace routing middleware initialized for HTTP server");
2635        }
2636    }
2637
2638    // Apply deceptive deploy configuration if enabled
2639    let mut final_cors_config = cors_config;
2640    let mut production_headers: Option<std::sync::Arc<std::collections::HashMap<String, String>>> =
2641        None;
2642    // Auth config from deceptive deploy OAuth (if configured)
2643    let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
2644    let mut rate_limit_config = crate::middleware::RateLimitConfig {
2645        requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
2646            .ok()
2647            .and_then(|v| v.parse().ok())
2648            .unwrap_or(1000),
2649        burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
2650            .ok()
2651            .and_then(|v| v.parse().ok())
2652            .unwrap_or(2000),
2653        per_ip: true,
2654        per_endpoint: false,
2655    };
2656
2657    if let Some(deploy_config) = &deceptive_deploy_config {
2658        if deploy_config.enabled {
2659            info!("Deceptive deploy mode enabled - applying production-like configuration");
2660
2661            // Override CORS config if provided
2662            if let Some(prod_cors) = &deploy_config.cors {
2663                final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
2664                    enabled: true,
2665                    allowed_origins: prod_cors.allowed_origins.clone(),
2666                    allowed_methods: prod_cors.allowed_methods.clone(),
2667                    allowed_headers: prod_cors.allowed_headers.clone(),
2668                    allow_credentials: prod_cors.allow_credentials,
2669                });
2670                info!("Applied production-like CORS configuration");
2671            }
2672
2673            // Override rate limit config if provided
2674            if let Some(prod_rate_limit) = &deploy_config.rate_limit {
2675                rate_limit_config = crate::middleware::RateLimitConfig {
2676                    requests_per_minute: prod_rate_limit.requests_per_minute,
2677                    burst: prod_rate_limit.burst,
2678                    per_ip: prod_rate_limit.per_ip,
2679                    per_endpoint: false,
2680                };
2681                info!(
2682                    "Applied production-like rate limiting: {} req/min, burst: {}",
2683                    prod_rate_limit.requests_per_minute, prod_rate_limit.burst
2684                );
2685            }
2686
2687            // Set production headers
2688            if !deploy_config.headers.is_empty() {
2689                let headers_map: std::collections::HashMap<String, String> =
2690                    deploy_config.headers.clone();
2691                production_headers = Some(std::sync::Arc::new(headers_map));
2692                info!("Configured {} production headers", deploy_config.headers.len());
2693            }
2694
2695            // Integrate OAuth config from deceptive deploy
2696            if let Some(prod_oauth) = &deploy_config.oauth {
2697                let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
2698                deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
2699                    oauth2: Some(oauth2_config),
2700                    ..Default::default()
2701                });
2702                info!("Applied production-like OAuth configuration for deceptive deploy");
2703            }
2704        }
2705    }
2706
2707    // Initialize rate limiter and state
2708    let rate_limiter =
2709        std::sync::Arc::new(crate::middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
2710
2711    let mut state = HttpServerState::new().with_rate_limiter(rate_limiter.clone());
2712
2713    // Add production headers to state if configured
2714    if let Some(headers) = production_headers.clone() {
2715        state = state.with_production_headers(headers);
2716    }
2717
2718    // Add rate limiting middleware
2719    app = app.layer(from_fn_with_state(state.clone(), crate::middleware::rate_limit_middleware));
2720
2721    // Add production headers middleware if configured
2722    if state.production_headers.is_some() {
2723        app = app.layer(from_fn_with_state(
2724            state.clone(),
2725            crate::middleware::production_headers_middleware,
2726        ));
2727    }
2728
2729    // Add authentication middleware if OAuth is configured via deceptive deploy
2730    if let Some(auth_config) = deceptive_deploy_auth_config {
2731        use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
2732        use std::collections::HashMap;
2733        use std::sync::Arc;
2734        use tokio::sync::RwLock;
2735
2736        // Create OAuth2 client if configured
2737        let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
2738            match create_oauth2_client(oauth2_config) {
2739                Ok(client) => Some(client),
2740                Err(e) => {
2741                    warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
2742                    None
2743                }
2744            }
2745        } else {
2746            None
2747        };
2748
2749        // Create auth state
2750        let auth_state = AuthState {
2751            config: auth_config,
2752            spec: None, // OpenAPI spec not available in this context
2753            oauth2_client,
2754            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
2755        };
2756
2757        // Apply auth middleware
2758        app = app.layer(axum::middleware::from_fn_with_state(auth_state, auth_middleware));
2759        info!("Applied OAuth authentication middleware from deceptive deploy configuration");
2760    }
2761
2762    // Add runtime daemon 404 detection middleware (if enabled)
2763    #[cfg(feature = "runtime-daemon")]
2764    {
2765        use mockforge_runtime_daemon::{AutoGenerator, NotFoundDetector, RuntimeDaemonConfig};
2766        use std::sync::Arc;
2767
2768        // Load runtime daemon config from environment
2769        let daemon_config = RuntimeDaemonConfig::from_env();
2770
2771        if daemon_config.enabled {
2772            info!("Runtime daemon enabled - auto-creating mocks from 404s");
2773
2774            // Determine management API URL (default to localhost:3000)
2775            let management_api_url =
2776                std::env::var("MOCKFORGE_MANAGEMENT_API_URL").unwrap_or_else(|_| {
2777                    let port =
2778                        std::env::var("MOCKFORGE_HTTP_PORT").unwrap_or_else(|_| "3000".to_string());
2779                    format!("http://localhost:{}", port)
2780                });
2781
2782            // Create auto-generator
2783            let generator = Arc::new(AutoGenerator::new(daemon_config.clone(), management_api_url));
2784
2785            // Create detector and set generator
2786            let detector = NotFoundDetector::new(daemon_config.clone());
2787            detector.set_generator(generator).await;
2788
2789            // Add middleware layer
2790            let detector_clone = detector.clone();
2791            app = app.layer(axum::middleware::from_fn(
2792                move |req: axum::extract::Request, next: axum::middleware::Next| {
2793                    let detector = detector_clone.clone();
2794                    async move { detector.detect_and_auto_create(req, next).await }
2795                },
2796            ));
2797
2798            debug!("Runtime daemon 404 detection middleware added");
2799        }
2800    }
2801
2802    // Add contract diff middleware for automatic request capture
2803    // This captures requests for contract diff analysis
2804    app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
2805
2806    // Add CORS middleware (use final_cors_config which may be overridden by deceptive deploy)
2807    app = apply_cors_middleware(app, final_cors_config);
2808
2809    app
2810}
2811
2812// Note: start_with_traffic_shaping function removed due to compilation issues
2813// Use build_router_with_traffic_shaping_and_multi_tenant directly instead
2814
2815#[test]
2816fn test_route_info_clone() {
2817    let route = RouteInfo {
2818        method: "POST".to_string(),
2819        path: "/users".to_string(),
2820        operation_id: Some("createUser".to_string()),
2821        summary: None,
2822        description: None,
2823        parameters: vec![],
2824    };
2825
2826    let cloned = route.clone();
2827    assert_eq!(route.method, cloned.method);
2828    assert_eq!(route.path, cloned.path);
2829    assert_eq!(route.operation_id, cloned.operation_id);
2830}
2831
2832#[test]
2833fn test_http_server_state_new() {
2834    let state = HttpServerState::new();
2835    assert_eq!(state.routes.len(), 0);
2836}
2837
2838#[test]
2839fn test_http_server_state_with_routes() {
2840    let routes = vec![
2841        RouteInfo {
2842            method: "GET".to_string(),
2843            path: "/users".to_string(),
2844            operation_id: Some("getUsers".to_string()),
2845            summary: None,
2846            description: None,
2847            parameters: vec![],
2848        },
2849        RouteInfo {
2850            method: "POST".to_string(),
2851            path: "/users".to_string(),
2852            operation_id: Some("createUser".to_string()),
2853            summary: None,
2854            description: None,
2855            parameters: vec![],
2856        },
2857    ];
2858
2859    let state = HttpServerState::with_routes(routes.clone());
2860    assert_eq!(state.routes.len(), 2);
2861    assert_eq!(state.routes[0].method, "GET");
2862    assert_eq!(state.routes[1].method, "POST");
2863}
2864
2865#[test]
2866fn test_http_server_state_clone() {
2867    let routes = vec![RouteInfo {
2868        method: "GET".to_string(),
2869        path: "/test".to_string(),
2870        operation_id: None,
2871        summary: None,
2872        description: None,
2873        parameters: vec![],
2874    }];
2875
2876    let state = HttpServerState::with_routes(routes);
2877    let cloned = state.clone();
2878
2879    assert_eq!(state.routes.len(), cloned.routes.len());
2880    assert_eq!(state.routes[0].method, cloned.routes[0].method);
2881}
2882
2883#[tokio::test]
2884async fn test_build_router_without_openapi() {
2885    let _router = build_router(None, None, None).await;
2886    // Should succeed without OpenAPI spec
2887}
2888
2889#[tokio::test]
2890async fn test_build_router_with_nonexistent_spec() {
2891    let _router = build_router(Some("/nonexistent/spec.yaml".to_string()), None, None).await;
2892    // Should succeed but log a warning
2893}
2894
2895#[tokio::test]
2896async fn test_build_router_with_auth_and_latency() {
2897    let _router = build_router_with_auth_and_latency(None, None, None, None).await;
2898    // Should succeed without parameters
2899}
2900
2901#[tokio::test]
2902async fn test_build_router_with_latency() {
2903    let _router = build_router_with_latency(None, None, None).await;
2904    // Should succeed without parameters
2905}
2906
2907#[tokio::test]
2908async fn test_build_router_with_auth() {
2909    let _router = build_router_with_auth(None, None, None).await;
2910    // Should succeed without parameters
2911}
2912
2913#[tokio::test]
2914async fn test_build_router_with_chains() {
2915    let _router = build_router_with_chains(None, None, None).await;
2916    // Should succeed without parameters
2917}
2918
2919#[test]
2920fn test_route_info_with_all_fields() {
2921    let route = RouteInfo {
2922        method: "PUT".to_string(),
2923        path: "/users/{id}".to_string(),
2924        operation_id: Some("updateUser".to_string()),
2925        summary: Some("Update user".to_string()),
2926        description: Some("Updates an existing user".to_string()),
2927        parameters: vec!["id".to_string(), "body".to_string()],
2928    };
2929
2930    assert!(route.operation_id.is_some());
2931    assert!(route.summary.is_some());
2932    assert!(route.description.is_some());
2933    assert_eq!(route.parameters.len(), 2);
2934}
2935
2936#[test]
2937fn test_route_info_with_minimal_fields() {
2938    let route = RouteInfo {
2939        method: "DELETE".to_string(),
2940        path: "/users/{id}".to_string(),
2941        operation_id: None,
2942        summary: None,
2943        description: None,
2944        parameters: vec![],
2945    };
2946
2947    assert!(route.operation_id.is_none());
2948    assert!(route.summary.is_none());
2949    assert!(route.description.is_none());
2950    assert_eq!(route.parameters.len(), 0);
2951}
2952
2953#[test]
2954fn test_http_server_state_empty_routes() {
2955    let state = HttpServerState::with_routes(vec![]);
2956    assert_eq!(state.routes.len(), 0);
2957}
2958
2959#[test]
2960fn test_http_server_state_multiple_routes() {
2961    let routes = vec![
2962        RouteInfo {
2963            method: "GET".to_string(),
2964            path: "/users".to_string(),
2965            operation_id: Some("listUsers".to_string()),
2966            summary: Some("List all users".to_string()),
2967            description: None,
2968            parameters: vec![],
2969        },
2970        RouteInfo {
2971            method: "GET".to_string(),
2972            path: "/users/{id}".to_string(),
2973            operation_id: Some("getUser".to_string()),
2974            summary: Some("Get a user".to_string()),
2975            description: None,
2976            parameters: vec!["id".to_string()],
2977        },
2978        RouteInfo {
2979            method: "POST".to_string(),
2980            path: "/users".to_string(),
2981            operation_id: Some("createUser".to_string()),
2982            summary: Some("Create a user".to_string()),
2983            description: None,
2984            parameters: vec!["body".to_string()],
2985        },
2986    ];
2987
2988    let state = HttpServerState::with_routes(routes);
2989    assert_eq!(state.routes.len(), 3);
2990
2991    // Verify different HTTP methods
2992    let methods: Vec<&str> = state.routes.iter().map(|r| r.method.as_str()).collect();
2993    assert!(methods.contains(&"GET"));
2994    assert!(methods.contains(&"POST"));
2995}
2996
2997#[test]
2998fn test_http_server_state_with_rate_limiter() {
2999    use std::sync::Arc;
3000
3001    let config = crate::middleware::RateLimitConfig::default();
3002    let rate_limiter = Arc::new(crate::middleware::GlobalRateLimiter::new(config));
3003
3004    let state = HttpServerState::new().with_rate_limiter(rate_limiter);
3005
3006    assert!(state.rate_limiter.is_some());
3007    assert_eq!(state.routes.len(), 0);
3008}
3009
3010#[tokio::test]
3011async fn test_build_router_includes_rate_limiter() {
3012    let _router = build_router(None, None, None).await;
3013    // Router should be created successfully with rate limiter initialized
3014}