Skip to main content

mockforge_http/
lib.rs

1// Issue #555 extracted `mockforge-intelligence` and `mockforge-proxy`
2// out of this crate; both now exist as independent workspace members.
3// AI-touching handlers (ai_studio, forecasting, fidelity, deceptive_canary,
4// consistency, scenario_studio, xray, pr_generation, semantic_drift,
5// threat_modeling, rag_ai_generator, ai_handler) and proxy logic
6// (proxy_server, reality_proxy) all live in their target crates; the
7// files remaining here under those names are thin `pub use ...::*`
8// re-export shims kept for one minor version so external callers don't
9// break. (Issue #656 picked up `ai_handler` after #555's main run.)
10//
11// Deprecation allowances are scoped to individual handler files
12// (handlers/*.rs, middleware/drift_tracking.rs, management/ai_gen.rs)
13// and to specific build_router functions below, rather than being
14// crate-wide.
15//
16// What remains in `mockforge-http`:
17//   - HTTP-native machinery: routing, builders, middleware, SSE, TLS,
18//     fixtures/scenarios/state-machine/time-travel/contract-diff APIs,
19//     management UI, request logging, etc.
20//   - Governance/security HTTP handlers (access_review, change_management,
21//     compliance_dashboard, consent, privileged_access, …) which front
22//     `mockforge_core::security` services and so belong in the same
23//     crate as the rest of the security-services HTTP surface, not in
24//     mockforge-intelligence.
25//   - `handlers::behavioral_cloning` — wired into both
26//     `mockforge_intelligence::behavioral_cloning` (algorithms) and
27//     `mockforge_recorder::database` (trace I/O). Since
28//     `mockforge-recorder` already depends on `mockforge-intelligence`,
29//     intelligence cannot host the orchestration layer without a cycle,
30//     so this handler stays here intentionally.
31//   - `handlers::{contract_health, drift_budget, failure_designer,
32//     incident_replay, protocol_contracts}` — coupled to
33//     `mockforge_chaos`, the chaos crate would need its own #555-style
34//     bucket before these can follow.
35
36//! # MockForge HTTP
37//!
38//! HTTP/REST API mocking library for MockForge.
39//!
40//! This crate provides HTTP-specific functionality for creating mock REST APIs,
41//! including OpenAPI integration, request validation, AI-powered response generation,
42//! and management endpoints.
43//!
44//! ## Overview
45//!
46//! MockForge HTTP enables you to:
47//!
48//! - **Serve OpenAPI specs**: Automatically generate mock endpoints from OpenAPI/Swagger
49//! - **Validate requests**: Enforce schema validation with configurable modes
50//! - **AI-powered responses**: Generate intelligent responses using LLMs
51//! - **Management API**: Real-time monitoring, configuration, and control
52//! - **Request logging**: Comprehensive HTTP request/response logging
53//! - **Metrics collection**: Track performance and usage statistics
54//! - **Server-Sent Events**: Stream logs and metrics to clients
55//!
56//! ## Quick Start
57//!
58//! ### Basic HTTP Server from OpenAPI
59//!
60//! ```rust,no_run
61//! use axum::Router;
62//! use mockforge_openapi::openapi_routes::ValidationMode;
63//! use mockforge_openapi::openapi_routes::ValidationOptions;
64//! use mockforge_http::build_router;
65//!
66//! #[tokio::main]
67//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
68//!     // Build router from OpenAPI specification
69//!     let router = build_router(
70//!         Some("./api-spec.json".to_string()),
71//!         Some(ValidationOptions {
72//!             request_mode: ValidationMode::Enforce,
73//!             ..ValidationOptions::default()
74//!         }),
75//!         None,
76//!     ).await;
77//!
78//!     // Start the server
79//!     let addr: std::net::SocketAddr = "0.0.0.0:3000".parse()?;
80//!     let listener = tokio::net::TcpListener::bind(addr).await?;
81//!     axum::serve(listener, router).await?;
82//!
83//!     Ok(())
84//! }
85//! ```
86//!
87//! ### With Management API
88//!
89//! Enable real-time monitoring and configuration:
90//!
91//! ```rust,no_run
92//! use mockforge_http::{management_router, ManagementState};
93//!
94//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
95//! let state = ManagementState::new(None, None, 3000);
96//!
97//! // Build management router
98//! let mgmt_router = management_router(state);
99//!
100//! // Mount under your main router
101//! let app = axum::Router::new()
102//!     .nest("/__mockforge", mgmt_router);
103//! # Ok(())
104//! # }
105//! ```
106//!
107//! ### AI-Powered Responses
108//!
109//! Generate intelligent responses based on request context:
110//!
111//! ```rust,no_run
112//! use mockforge_data::intelligent_mock::{IntelligentMockConfig, ResponseMode};
113//! use mockforge_http::{process_response_with_ai, AiResponseConfig};
114//! use serde_json::json;
115//!
116//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
117//! let ai_config = AiResponseConfig {
118//!     intelligent: Some(
119//!         IntelligentMockConfig::new(ResponseMode::Intelligent)
120//!             .with_prompt("Generate realistic user data".to_string()),
121//!     ),
122//!     drift: None,
123//! };
124//!
125//! let response = process_response_with_ai(
126//!     Some(json!({"name": "Alice"})),
127//!     ai_config
128//!         .intelligent
129//!         .clone()
130//!         .map(serde_json::to_value)
131//!         .transpose()?,
132//!     ai_config
133//!         .drift
134//!         .clone()
135//!         .map(serde_json::to_value)
136//!         .transpose()?,
137//! )
138//! .await?;
139//! # Ok(())
140//! # }
141//! ```
142//!
143//! ## Key Features
144//!
145//! ### OpenAPI Integration
146//! - Automatic endpoint generation from specs
147//! - Request/response validation
148//! - Schema-based mock data generation
149//!
150//! ### Management & Monitoring
151//! - [`management`]: REST API for server control and monitoring
152//! - [`management_ws`]: WebSocket API for real-time updates
153//! - [`sse`]: Server-Sent Events for log streaming
154//! - [`request_logging`]: Comprehensive request/response logging
155//! - [`metrics_middleware`]: Performance metrics collection
156//!
157//! ### Advanced Features
158//! - [`ai_handler`]: AI-powered response generation
159//! - [`auth`]: Authentication and authorization
160//! - [`chain_handlers`]: Multi-step request workflows
161//! - [`latency_profiles`]: Configurable latency simulation
162//! - [`replay_listing`]: Fixture management
163//!
164//! ## Middleware
165//!
166//! MockForge HTTP includes several middleware layers:
167//!
168//! - **Request Tracing**: [`http_tracing_middleware`] - Distributed tracing integration
169//! - **Metrics Collection**: [`metrics_middleware`] - Prometheus-compatible metrics
170//! - **Operation Metadata**: [`op_middleware`] - OpenAPI operation tracking
171//!
172//! ## Management API Endpoints
173//!
174//! When using the management router, these endpoints are available:
175//!
176//! - `GET /health` - Health check
177//! - `GET /stats` - Server statistics
178//! - `GET /logs` - Request logs (SSE stream)
179//! - `GET /metrics` - Performance metrics
180//! - `GET /fixtures` - List available fixtures
181//! - `POST /config/*` - Update configuration
182//!
183//! ## Examples
184//!
185//! See the [examples directory](https://github.com/SaaSy-Solutions/mockforge/tree/main/examples)
186//! for complete working examples.
187//!
188//! ## Related Crates
189//!
190//! - [`mockforge-core`](https://docs.rs/mockforge-core): Core mocking functionality
191//! - [`mockforge-data`](https://docs.rs/mockforge-data): Synthetic data generation
192//! - [`mockforge-plugin-core`](https://docs.rs/mockforge-plugin-core): Plugin development
193//!
194//! ## Documentation
195//!
196//! - [MockForge Book](https://docs.mockforge.dev/)
197//! - [HTTP Mocking Guide](https://docs.mockforge.dev/user-guide/http-mocking.html)
198//! - [API Reference](https://docs.rs/mockforge-http)
199
200pub mod ai_handler;
201pub mod auth;
202pub mod chain_handlers;
203/// Cross-protocol consistency engine integration for HTTP
204pub mod consistency;
205/// Contract diff retrieval API
206pub mod contract_diff_api;
207/// Contract diff middleware for automatic request capture
208pub mod contract_diff_middleware;
209/// TCP-listener wrapper that bumps the global `record_accept()` counter,
210/// used by the dashboard sampler to derive connections-per-second.
211pub mod counting_listener;
212pub mod coverage;
213/// Database connection wrapper — moved to `mockforge_intelligence::database`
214/// under #555 (prereq for handler moves). Re-exported here so existing
215/// `mockforge_http::database::Database` callers (4 handler files + the
216/// router init code below) keep resolving. Gated by the `database` feature,
217/// which now plumbs `mockforge-intelligence/database` transitively.
218#[cfg(feature = "database")]
219pub mod database {
220    pub use mockforge_intelligence::database::*;
221}
222/// File generation service for creating mock PDF, CSV, JSON files
223pub mod file_generator;
224/// File serving for generated mock files
225pub mod file_server;
226/// Fixtures management API for hosted-mock deployments
227pub mod fixtures_api;
228/// Kubernetes-native health check endpoints (liveness, readiness, startup probes)
229pub mod health;
230pub mod http_tracing_middleware;
231/// Latency profile configuration for HTTP request simulation
232pub mod latency_profiles;
233
234/// Mock LLM endpoint (OpenAI/Anthropic-compatible) for agent testing (#912).
235pub mod llm_mock;
236
237/// Management API for server control and monitoring
238pub mod management;
239/// Runtime route-scoped chaos rules API
240pub mod management_auth;
241/// WebSocket-based management API for real-time updates
242pub mod management_ws;
243/// Mock MCP (Model Context Protocol) server for agent-as-MCP-client testing (#913).
244pub mod mcp_mock;
245pub mod metrics_middleware;
246pub mod middleware;
247/// Standalone MockAI HTTP API
248pub mod mockai_api;
249/// Runtime network-profile switching API
250pub mod network_profile_runtime;
251pub mod op_middleware;
252/// Unified protocol server lifecycle implementation
253pub mod protocol_server;
254/// Browser/Mobile Proxy Server
255pub mod proxy_server;
256/// Quick mock generation utilities
257pub mod quick_mock;
258/// RAG-powered AI response generation
259pub mod rag_ai_generator;
260/// Reality-slider-driven mock/proxy switching middleware (#222)
261pub mod reality_proxy;
262/// Replay listing and fixture management
263pub mod replay_listing;
264pub mod request_logging;
265pub mod route_chaos_runtime;
266/// Runtime named-scenario activation API
267#[cfg(feature = "scenario-engine")]
268pub mod scenarios_runtime;
269/// Specification import API for OpenAPI and AsyncAPI
270pub mod spec_import;
271/// Server-Sent Events for streaming logs and metrics
272pub mod sse;
273/// State machine API for scenario state machines
274pub mod state_machine_api;
275/// Time-travel runtime API mirrored from the admin server onto the main HTTP port
276pub mod time_travel_api;
277/// TLS/HTTPS support
278pub mod tls;
279/// Token response utilities
280pub mod token_response;
281/// UI Builder API for low-code mock endpoint creation
282pub mod ui_builder;
283/// Verification API for request verification
284pub mod verification;
285
286// Access review handlers
287pub mod handlers;
288
289// Re-export AI handler utilities
290pub use ai_handler::{process_response_with_ai, AiResponseConfig, AiResponseHandler};
291// Re-export health check utilities
292pub use health::{HealthManager, ServiceStatus};
293
294// Re-export management API utilities
295pub use management::{
296    management_router, management_router_with_ui_builder, ManagementState, MockConfig,
297    ServerConfig, ServerStats,
298};
299
300// Re-export UI Builder utilities
301pub use ui_builder::{create_ui_builder_router, EndpointConfig, UIBuilderState};
302
303// Re-export management WebSocket utilities
304pub use management_ws::{ws_management_router, MockEvent, WsManagementState};
305
306// Re-export verification API utilities
307pub use verification::verification_router;
308
309// Re-export metrics middleware
310pub use metrics_middleware::collect_http_metrics;
311
312// Re-export tracing middleware
313pub use http_tracing_middleware::http_tracing_middleware;
314
315// Re-export coverage utilities
316pub use coverage::{calculate_coverage, CoverageReport, MethodCoverage, RouteCoverage};
317
318/// Helper function to load persona from config file
319/// Tries to load from common config locations: config.yaml, mockforge.yaml, tools/mockforge/config.yaml
320async fn load_persona_from_config() -> Option<Arc<Persona>> {
321    use mockforge_core::config::load_config;
322
323    // Try common config file locations
324    let config_paths = [
325        "config.yaml",
326        "mockforge.yaml",
327        "tools/mockforge/config.yaml",
328        "../tools/mockforge/config.yaml",
329    ];
330
331    for path in &config_paths {
332        if let Ok(config) = load_config(path).await {
333            // Access intelligent_behavior through mockai config
334            // Note: Config structure is mockai.intelligent_behavior.personas
335            if let Some(persona) = config.mockai.intelligent_behavior.personas.get_active_persona()
336            {
337                tracing::info!(
338                    "Loaded active persona '{}' from config file: {}",
339                    persona.name,
340                    path
341                );
342                return Some(Arc::new(persona.clone()));
343            } else {
344                tracing::debug!(
345                    "No active persona found in config file: {} (personas count: {})",
346                    path,
347                    config.mockai.intelligent_behavior.personas.personas.len()
348                );
349            }
350        } else {
351            tracing::debug!("Could not load config from: {}", path);
352        }
353    }
354
355    tracing::debug!("No persona found in config files, persona-based generation will be disabled");
356    None
357}
358
359use axum::body::Body;
360use axum::extract::State;
361use axum::http::Request;
362use axum::middleware::from_fn_with_state;
363use axum::response::Json;
364use axum::Router;
365use mockforge_chaos::core_failure_injection::{FailureConfig, FailureInjector};
366use mockforge_core::intelligent_behavior::config::Persona;
367use mockforge_foundation::latency::LatencyInjector;
368use mockforge_openapi::openapi_routes::OpenApiRouteRegistry;
369use mockforge_openapi::openapi_routes::ValidationOptions;
370use mockforge_openapi::OpenApiSpec;
371use std::sync::Arc;
372use tower_http::cors::{Any, CorsLayer};
373
374#[cfg(feature = "data-faker")]
375use mockforge_data::provider::register_core_faker_provider;
376use mockforge_foundation::latency::LatencyProfile;
377use std::collections::HashMap;
378use std::ffi::OsStr;
379use std::path::Path;
380use tokio::fs;
381use tokio::sync::RwLock;
382use tracing::*;
383
384/// Route info for storing in state
385#[derive(Clone)]
386pub struct RouteInfo {
387    /// HTTP method (GET, POST, PUT, etc.)
388    pub method: String,
389    /// API path pattern (e.g., "/api/users/{id}")
390    pub path: String,
391    /// OpenAPI operation ID if available
392    pub operation_id: Option<String>,
393    /// Operation summary from OpenAPI spec
394    pub summary: Option<String>,
395    /// Operation description from OpenAPI spec
396    pub description: Option<String>,
397    /// List of parameter names for this route
398    pub parameters: Vec<String>,
399}
400
401/// Shared state for tracking OpenAPI routes
402#[derive(Clone)]
403pub struct HttpServerState {
404    /// List of registered routes from OpenAPI spec
405    pub routes: Vec<RouteInfo>,
406    /// Optional global rate limiter for request throttling
407    pub rate_limiter: Option<Arc<middleware::rate_limit::GlobalRateLimiter>>,
408    /// Production headers to add to all responses (for deceptive deploy)
409    pub production_headers: Option<Arc<HashMap<String, String>>>,
410}
411
412impl Default for HttpServerState {
413    fn default() -> Self {
414        Self::new()
415    }
416}
417
418impl HttpServerState {
419    /// Create a new empty HTTP server state
420    pub fn new() -> Self {
421        Self {
422            routes: Vec::new(),
423            rate_limiter: None,
424            production_headers: None,
425        }
426    }
427
428    /// Create HTTP server state with pre-configured routes
429    pub fn with_routes(routes: Vec<RouteInfo>) -> Self {
430        Self {
431            routes,
432            rate_limiter: None,
433            production_headers: None,
434        }
435    }
436
437    /// Add a rate limiter to the HTTP server state
438    pub fn with_rate_limiter(
439        mut self,
440        rate_limiter: Arc<middleware::rate_limit::GlobalRateLimiter>,
441    ) -> Self {
442        self.rate_limiter = Some(rate_limiter);
443        self
444    }
445
446    /// Add production headers to the HTTP server state
447    pub fn with_production_headers(mut self, headers: Arc<HashMap<String, String>>) -> Self {
448        self.production_headers = Some(headers);
449        self
450    }
451}
452
453/// Handler to return OpenAPI routes information
454async fn get_routes_handler(State(state): State<HttpServerState>) -> Json<serde_json::Value> {
455    let route_info: Vec<serde_json::Value> = state
456        .routes
457        .iter()
458        .map(|route| {
459            serde_json::json!({
460                "method": route.method,
461                "path": route.path,
462                "operation_id": route.operation_id,
463                "summary": route.summary,
464                "description": route.description,
465                "parameters": route.parameters
466            })
467        })
468        .collect();
469
470    Json(serde_json::json!({
471        "routes": route_info,
472        "total": state.routes.len()
473    }))
474}
475
476/// Handler to serve the Scalar API docs page
477async fn get_docs_handler() -> axum::response::Html<&'static str> {
478    axum::response::Html(include_str!("../static/docs.html"))
479}
480
481/// Build the base HTTP router, optionally from an OpenAPI spec.
482pub async fn build_router(
483    spec_path: Option<String>,
484    options: Option<ValidationOptions>,
485    failure_config: Option<FailureConfig>,
486) -> Router {
487    build_router_with_multi_tenant(
488        spec_path,
489        options,
490        failure_config,
491        None,
492        None,
493        None,
494        None,
495        None,
496        None,
497        None,
498    )
499    .await
500}
501
502/// Apply CORS middleware to the router based on configuration
503fn apply_cors_middleware(
504    app: Router,
505    cors_config: Option<mockforge_core::config::HttpCorsConfig>,
506) -> Router {
507    use http::Method;
508    use tower_http::cors::AllowOrigin;
509
510    if let Some(config) = cors_config {
511        if !config.enabled {
512            return app;
513        }
514
515        let mut cors_layer = CorsLayer::new();
516        let is_wildcard_origin;
517
518        // Configure allowed origins
519        if config.allowed_origins.contains(&"*".to_string()) {
520            cors_layer = cors_layer.allow_origin(Any);
521            is_wildcard_origin = true;
522        } else if !config.allowed_origins.is_empty() {
523            // Try to parse each origin, fallback to permissive if parsing fails
524            let origins: Vec<_> = config
525                .allowed_origins
526                .iter()
527                .filter_map(|origin| {
528                    origin.parse::<http::HeaderValue>().ok().map(AllowOrigin::exact)
529                })
530                .collect();
531
532            if origins.is_empty() {
533                // If no valid origins, use permissive for development
534                warn!("No valid CORS origins configured, using permissive CORS");
535                cors_layer = cors_layer.allow_origin(Any);
536                is_wildcard_origin = true;
537            } else {
538                // Use the first origin as exact match (tower-http limitation)
539                // For multiple origins, we'd need a custom implementation
540                if origins.len() == 1 {
541                    cors_layer = cors_layer.allow_origin(origins[0].clone());
542                    is_wildcard_origin = false;
543                } else {
544                    // Multiple origins - use permissive for now
545                    warn!(
546                        "Multiple CORS origins configured, using permissive CORS. \
547                        Consider using '*' for all origins."
548                    );
549                    cors_layer = cors_layer.allow_origin(Any);
550                    is_wildcard_origin = true;
551                }
552            }
553        } else {
554            // No origins specified, use permissive for development
555            cors_layer = cors_layer.allow_origin(Any);
556            is_wildcard_origin = true;
557        }
558
559        // Configure allowed methods
560        if !config.allowed_methods.is_empty() {
561            let methods: Vec<Method> =
562                config.allowed_methods.iter().filter_map(|m| m.parse().ok()).collect();
563            if !methods.is_empty() {
564                cors_layer = cors_layer.allow_methods(methods);
565            }
566        } else {
567            // Default to common HTTP methods
568            cors_layer = cors_layer.allow_methods([
569                Method::GET,
570                Method::POST,
571                Method::PUT,
572                Method::DELETE,
573                Method::PATCH,
574                Method::OPTIONS,
575            ]);
576        }
577
578        // Configure allowed headers
579        if !config.allowed_headers.is_empty() {
580            let headers: Vec<_> = config
581                .allowed_headers
582                .iter()
583                .filter_map(|h| h.parse::<http::HeaderName>().ok())
584                .collect();
585            if !headers.is_empty() {
586                cors_layer = cors_layer.allow_headers(headers);
587            }
588        } else {
589            // Default headers
590            cors_layer =
591                cors_layer.allow_headers([http::header::CONTENT_TYPE, http::header::AUTHORIZATION]);
592        }
593
594        // Configure credentials - cannot allow credentials with wildcard origin
595        // Determine if credentials should be allowed
596        // Cannot allow credentials with wildcard origin per CORS spec
597        let should_allow_credentials = if is_wildcard_origin {
598            // Wildcard origin - credentials must be false
599            false
600        } else {
601            // Specific origins - use config value (defaults to false)
602            config.allow_credentials
603        };
604
605        cors_layer = cors_layer.allow_credentials(should_allow_credentials);
606
607        info!(
608            "CORS middleware enabled with configured settings (credentials: {})",
609            should_allow_credentials
610        );
611        app.layer(cors_layer)
612    } else {
613        // No CORS config provided - use permissive CORS for development
614        // Note: permissive() allows credentials, but since it uses wildcard origin,
615        // we need to disable credentials to avoid CORS spec violation
616        debug!("No CORS config provided, using permissive CORS for development");
617        // Create a permissive CORS layer but disable credentials to avoid CORS spec violation
618        // (cannot combine credentials with wildcard origin)
619        app.layer(CorsLayer::permissive().allow_credentials(false))
620    }
621}
622
623/// Build the base HTTP router with multi-tenant workspace support
624#[allow(clippy::too_many_arguments)]
625#[allow(deprecated)] // uses MockAI, MultiTenantWorkspaceRegistry, WorkspaceRouter, Workspace (all stay in core)
626pub async fn build_router_with_multi_tenant(
627    spec_path: Option<String>,
628    options: Option<ValidationOptions>,
629    failure_config: Option<FailureConfig>,
630    multi_tenant_config: Option<mockforge_foundation::multi_tenant_types::MultiTenantConfig>,
631    _route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
632    cors_config: Option<mockforge_core::config::HttpCorsConfig>,
633    ai_generator: Option<Arc<dyn mockforge_openapi::response::AiGenerator + Send + Sync>>,
634    smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
635    mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
636    deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
637) -> Router {
638    use std::time::Instant;
639
640    let startup_start = Instant::now();
641
642    // Set up the basic router
643    let mut app = Router::new();
644
645    // Initialize rate limiter with default configuration
646    // Can be customized via environment variables or config
647    let mut rate_limit_config = middleware::RateLimitConfig {
648        requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
649            .ok()
650            .and_then(|v| v.parse().ok())
651            .unwrap_or(1000),
652        burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
653            .ok()
654            .and_then(|v| v.parse().ok())
655            .unwrap_or(2000),
656        per_ip: true,
657        per_endpoint: false,
658    };
659
660    // Apply deceptive deploy configuration if enabled
661    let mut final_cors_config = cors_config;
662    let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
663    // Auth config from deceptive deploy OAuth (if configured)
664    let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
665
666    if let Some(deploy_config) = &deceptive_deploy_config {
667        if deploy_config.enabled {
668            info!("Deceptive deploy mode enabled - applying production-like configuration");
669
670            // Override CORS config if provided
671            if let Some(prod_cors) = &deploy_config.cors {
672                final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
673                    enabled: true,
674                    allowed_origins: prod_cors.allowed_origins.clone(),
675                    allowed_methods: prod_cors.allowed_methods.clone(),
676                    allowed_headers: prod_cors.allowed_headers.clone(),
677                    allow_credentials: prod_cors.allow_credentials,
678                });
679                info!("Applied production-like CORS configuration");
680            }
681
682            // Override rate limit config if provided
683            if let Some(prod_rate_limit) = &deploy_config.rate_limit {
684                rate_limit_config = middleware::RateLimitConfig {
685                    requests_per_minute: prod_rate_limit.requests_per_minute,
686                    burst: prod_rate_limit.burst,
687                    per_ip: prod_rate_limit.per_ip,
688                    per_endpoint: false,
689                };
690                info!(
691                    "Applied production-like rate limiting: {} req/min, burst: {}",
692                    prod_rate_limit.requests_per_minute, prod_rate_limit.burst
693                );
694            }
695
696            // Set production headers
697            if !deploy_config.headers.is_empty() {
698                let headers_map: HashMap<String, String> = deploy_config.headers.clone();
699                production_headers = Some(std::sync::Arc::new(headers_map));
700                info!("Configured {} production headers", deploy_config.headers.len());
701            }
702
703            // Integrate OAuth config from deceptive deploy
704            if let Some(prod_oauth) = &deploy_config.oauth {
705                let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
706                deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
707                    oauth2: Some(oauth2_config),
708                    ..Default::default()
709                });
710                info!("Applied production-like OAuth configuration for deceptive deploy");
711            }
712        }
713    }
714
715    let rate_limit_disabled = middleware::is_rate_limit_disabled();
716    let rate_limiter =
717        std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
718
719    let mut state = HttpServerState::new();
720    if rate_limit_disabled {
721        info!(
722            "HTTP rate limiting disabled (MOCKFORGE_RATE_LIMIT_ENABLED=false or --no-rate-limit)"
723        );
724    } else {
725        state = state.with_rate_limiter(rate_limiter.clone());
726    }
727
728    // Add production headers to state if configured
729    if let Some(headers) = production_headers.clone() {
730        state = state.with_production_headers(headers);
731    }
732
733    // Clone spec_path for later use
734    let spec_path_for_mgmt = spec_path.clone();
735
736    // If an OpenAPI spec is provided, integrate it
737    if let Some(spec_path) = spec_path {
738        tracing::debug!("Processing OpenAPI spec path: {}", spec_path);
739
740        // Measure OpenAPI spec loading
741        let spec_load_start = Instant::now();
742        match OpenApiSpec::from_file(&spec_path).await {
743            Ok(openapi) => {
744                let spec_load_duration = spec_load_start.elapsed();
745                info!(
746                    "Successfully loaded OpenAPI spec from {} (took {:?})",
747                    spec_path, spec_load_duration
748                );
749
750                // Measure route registry creation
751                tracing::debug!("Creating OpenAPI route registry...");
752                let registry_start = Instant::now();
753
754                // Try to load persona from config if available
755                let persona = load_persona_from_config().await;
756
757                let registry = if let Some(opts) = options {
758                    tracing::debug!("Using custom validation options");
759                    if let Some(ref persona) = persona {
760                        tracing::info!("Using persona '{}' for route generation", persona.name);
761                    }
762                    OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
763                } else {
764                    tracing::debug!("Using environment-based options");
765                    if let Some(ref persona) = persona {
766                        tracing::info!("Using persona '{}' for route generation", persona.name);
767                    }
768                    OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
769                };
770                let registry_duration = registry_start.elapsed();
771                info!(
772                    "Created OpenAPI route registry with {} routes (took {:?})",
773                    registry.routes().len(),
774                    registry_duration
775                );
776
777                // Measure route extraction
778                let extract_start = Instant::now();
779                let route_info: Vec<RouteInfo> = registry
780                    .routes()
781                    .iter()
782                    .map(|route| RouteInfo {
783                        method: route.method.clone(),
784                        path: route.path.clone(),
785                        operation_id: route.operation.operation_id.clone(),
786                        summary: route.operation.summary.clone(),
787                        description: route.operation.description.clone(),
788                        parameters: route.parameters.clone(),
789                    })
790                    .collect();
791                state.routes = route_info;
792                let extract_duration = extract_start.elapsed();
793                debug!("Extracted route information (took {:?})", extract_duration);
794
795                let registry = registry.with_overrides(Arc::new(
796                    mockforge_core::SharedOverrides::load(Vec::new()).await,
797                ));
798                let router_build_start = Instant::now();
799                let response_rewriter: Option<
800                    std::sync::Arc<dyn mockforge_openapi::response_rewriter::ResponseRewriter>,
801                > = Some(std::sync::Arc::new(
802                    mockforge_core::openapi_rewriter::CoreResponseRewriter::new(),
803                ));
804                let openapi_router = if let Some(mockai_instance) = &mockai {
805                    tracing::debug!("Building router with MockAI support");
806                    registry.build_router_with_mockai(Some(mockai_instance.clone()))
807                } else if let Some(ai_generator) = &ai_generator {
808                    tracing::debug!("Building router with AI generator support");
809                    registry.build_router_with_ai(Some(ai_generator.clone()))
810                } else if let Some(failure_config) = &failure_config {
811                    tracing::debug!("Building router with failure injection and overrides");
812                    let failure_injector = FailureInjector::new(Some(failure_config.clone()), true);
813                    registry.build_router_with_injectors_and_rewriter(
814                        LatencyInjector::default(),
815                        Some(failure_injector),
816                        response_rewriter,
817                    )
818                } else {
819                    tracing::debug!("Building router with overrides");
820                    registry.build_router_with_injectors_and_rewriter(
821                        LatencyInjector::default(),
822                        None,
823                        response_rewriter,
824                    )
825                };
826                let router_build_duration = router_build_start.elapsed();
827                debug!("Built OpenAPI router (took {:?})", router_build_duration);
828
829                // Issue #79 — explicitly stamp the body-size limit on the
830                // openapi sub-router BEFORE merging it. The limit is also
831                // applied inside `OpenApiRouteRegistry::build_router_*`,
832                // but merging can drop nested layers in some axum
833                // configurations; redoing it at the merge site is cheap
834                // insurance against the "200 OK before body completes"
835                // bug Srikanth reported.
836                let body_limit_mb = std::env::var("MOCKFORGE_HTTP_BODY_LIMIT_MB")
837                    .ok()
838                    .and_then(|v| v.parse::<usize>().ok())
839                    .unwrap_or(50);
840                let body_limit_bytes = body_limit_mb.saturating_mul(1024 * 1024);
841                let openapi_router =
842                    openapi_router.layer(axum::extract::DefaultBodyLimit::max(body_limit_bytes));
843                tracing::info!(
844                    body_limit_mb = body_limit_mb,
845                    "Merging OpenAPI router with main router"
846                );
847                app = app.merge(openapi_router);
848                tracing::debug!("Router built successfully");
849            }
850            Err(e) => {
851                warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
852            }
853        }
854    }
855
856    // Add basic health check endpoint
857    app = app.route(
858        "/health",
859        axum::routing::get(|| async {
860            use mockforge_core::server_utils::health::HealthStatus;
861            {
862                // HealthStatus should always serialize, but handle errors gracefully
863                match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
864                    Ok(value) => Json(value),
865                    Err(e) => {
866                        // Log error but return a simple healthy response
867                        tracing::error!("Failed to serialize health status: {}", e);
868                        Json(serde_json::json!({
869                            "status": "healthy",
870                            "service": "mockforge-http",
871                            "uptime_seconds": 0
872                        }))
873                    }
874                }
875            }
876        }),
877    )
878    // Add SSE endpoints
879    .merge(sse::sse_router())
880    // Add file serving endpoints for generated mock files
881    .merge(file_server::file_serving_router());
882
883    // Clone state for routes_router since we'll use it for middleware too
884    let state_for_routes = state.clone();
885
886    // Create a router with state for the routes and coverage endpoints
887    let routes_router = Router::new()
888        .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
889        .route("/__mockforge/coverage", axum::routing::get(coverage::get_coverage_handler))
890        .with_state(state_for_routes);
891
892    // Merge the routes router with the main app
893    app = app.merge(routes_router);
894
895    // Add API docs page (Scalar-powered interactive explorer)
896    app = app.route("/__mockforge/docs", axum::routing::get(get_docs_handler));
897
898    // Add static coverage UI
899    // Determine the path to the coverage.html file
900    let coverage_html_path = std::env::var("MOCKFORGE_COVERAGE_UI_PATH")
901        .unwrap_or_else(|_| "crates/mockforge-http/static/coverage.html".to_string());
902
903    // Check if the file exists before serving it
904    if Path::new(&coverage_html_path).exists() {
905        app = app.nest_service(
906            "/__mockforge/coverage.html",
907            tower_http::services::ServeFile::new(&coverage_html_path),
908        );
909        debug!("Serving coverage UI from: {}", coverage_html_path);
910    } else {
911        debug!(
912            "Coverage UI file not found at: {}. Skipping static file serving.",
913            coverage_html_path
914        );
915    }
916
917    // Add management API endpoints
918    // Load spec for ManagementState so /__mockforge/api/spec can serve it
919    let mgmt_spec = if let Some(ref sp) = spec_path_for_mgmt {
920        match OpenApiSpec::from_file(sp).await {
921            Ok(s) => Some(Arc::new(s)),
922            Err(e) => {
923                debug!("Failed to load OpenAPI spec for management API: {}", e);
924                None
925            }
926        }
927    } else {
928        None
929    };
930    let mgmt_port = std::env::var("PORT")
931        .or_else(|_| std::env::var("MOCKFORGE_HTTP_PORT"))
932        .ok()
933        .and_then(|p| p.parse().ok())
934        .unwrap_or(3000);
935    let management_state = ManagementState::new(mgmt_spec, spec_path_for_mgmt, mgmt_port);
936
937    // Create WebSocket state and connect it to management state
938    use std::sync::Arc;
939    let ws_state = WsManagementState::new();
940    let ws_broadcast = Arc::new(ws_state.tx.clone());
941    let management_state = management_state.with_ws_broadcast(ws_broadcast);
942
943    // Note: ProxyConfig not available in this build function path
944    // Migration endpoints will work once ProxyConfig is passed to build_router_with_chains_and_multi_tenant
945
946    #[cfg(feature = "smtp")]
947    let management_state = {
948        if let Some(smtp_reg) = smtp_registry {
949            match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
950                Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
951                Err(e) => {
952                    error!(
953                        "Invalid SMTP registry type passed to HTTP management state: {:?}",
954                        e.type_id()
955                    );
956                    management_state
957                }
958            }
959        } else {
960            management_state
961        }
962    };
963    #[cfg(not(feature = "smtp"))]
964    let management_state = management_state;
965    #[cfg(not(feature = "smtp"))]
966    let _ = smtp_registry;
967    let management_state_for_fallback = management_state.clone();
968    app = app.nest("/__mockforge/api", management_router(management_state));
969    // Serve any request that the rest of the router doesn't handle as a dynamic
970    // mock lookup. Lets the Node/Rust SDK register stubs via the management
971    // API and have requests actually reach them. Falls through to 404 when
972    // no mock matches.
973    app = app.fallback_service(
974        axum::routing::any(management::dynamic_mock_fallback)
975            .with_state(management_state_for_fallback),
976    );
977
978    // Add verification API endpoint
979    app = app.merge(verification_router());
980
981    // Add OIDC well-known endpoints
982    use crate::auth::oidc::oidc_router;
983    app = app.merge(oidc_router());
984
985    // Add access review API if enabled
986    {
987        use mockforge_core::security::get_global_access_review_service;
988        if let Some(service) = get_global_access_review_service().await {
989            use crate::handlers::access_review::{access_review_router, AccessReviewState};
990            let review_state = AccessReviewState { service };
991            app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
992            debug!("Access review API mounted at /api/v1/security/access-reviews");
993        }
994    }
995
996    // Add privileged access API if enabled
997    {
998        use mockforge_core::security::get_global_privileged_access_manager;
999        if let Some(manager) = get_global_privileged_access_manager().await {
1000            use crate::handlers::privileged_access::{
1001                privileged_access_router, PrivilegedAccessState,
1002            };
1003            let privileged_state = PrivilegedAccessState { manager };
1004            app = app.nest(
1005                "/api/v1/security/privileged-access",
1006                privileged_access_router(privileged_state),
1007            );
1008            debug!("Privileged access API mounted at /api/v1/security/privileged-access");
1009        }
1010    }
1011
1012    // Add change management API if enabled
1013    {
1014        use mockforge_core::security::get_global_change_management_engine;
1015        if let Some(engine) = get_global_change_management_engine().await {
1016            use crate::handlers::change_management::{
1017                change_management_router, ChangeManagementState,
1018            };
1019            let change_state = ChangeManagementState { engine };
1020            app = app.nest("/api/v1/change-management", change_management_router(change_state));
1021            debug!("Change management API mounted at /api/v1/change-management");
1022        }
1023    }
1024
1025    // Add risk assessment API if enabled
1026    {
1027        use mockforge_core::security::get_global_risk_assessment_engine;
1028        if let Some(engine) = get_global_risk_assessment_engine().await {
1029            use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
1030            let risk_state = RiskAssessmentState { engine };
1031            app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
1032            debug!("Risk assessment API mounted at /api/v1/security/risks");
1033        }
1034    }
1035
1036    // Add token lifecycle API
1037    {
1038        use crate::auth::token_lifecycle::TokenLifecycleManager;
1039        use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
1040        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1041        let lifecycle_state = TokenLifecycleState {
1042            manager: lifecycle_manager,
1043        };
1044        app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
1045        debug!("Token lifecycle API mounted at /api/v1/auth");
1046    }
1047
1048    // Add OAuth2 server endpoints
1049    {
1050        use crate::auth::oidc::load_oidc_state;
1051        use crate::auth::token_lifecycle::TokenLifecycleManager;
1052        use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
1053        // Load OIDC state from configuration (environment variables or config file)
1054        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1055        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1056        let oauth2_state = OAuth2ServerState {
1057            oidc_state,
1058            lifecycle_manager,
1059            auth_codes: Arc::new(RwLock::new(HashMap::new())),
1060            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
1061        };
1062        app = app.merge(oauth2_server_router(oauth2_state));
1063        debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
1064    }
1065
1066    // Add consent screen endpoints
1067    {
1068        use crate::auth::oidc::load_oidc_state;
1069        use crate::auth::risk_engine::RiskEngine;
1070        use crate::auth::token_lifecycle::TokenLifecycleManager;
1071        use crate::handlers::consent::{consent_router, ConsentState};
1072        use crate::handlers::oauth2_server::OAuth2ServerState;
1073        // Load OIDC state from configuration (environment variables or config file)
1074        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
1075        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
1076        let oauth2_state = OAuth2ServerState {
1077            oidc_state: oidc_state.clone(),
1078            lifecycle_manager: lifecycle_manager.clone(),
1079            auth_codes: Arc::new(RwLock::new(HashMap::new())),
1080            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
1081        };
1082        let risk_engine = Arc::new(RiskEngine::default());
1083        let consent_state = ConsentState {
1084            oauth2_state,
1085            risk_engine,
1086        };
1087        app = app.merge(consent_router(consent_state));
1088        debug!("Consent screen endpoints mounted at /consent");
1089    }
1090
1091    // Add risk simulation API
1092    {
1093        use crate::auth::risk_engine::RiskEngine;
1094        use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
1095        let risk_engine = Arc::new(RiskEngine::default());
1096        let risk_state = RiskSimulationState { risk_engine };
1097        app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
1098        debug!("Risk simulation API mounted at /api/v1/auth/risk");
1099    }
1100
1101    // Add management WebSocket endpoint
1102    app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
1103
1104    // Add request logging middleware to capture all requests
1105    app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));
1106
1107    // Add security middleware for security event tracking (after logging, before contract diff)
1108    app = app.layer(axum::middleware::from_fn(middleware::security_middleware));
1109
1110    // Add contract diff middleware for automatic request capture
1111    // This captures requests for contract diff analysis (after logging)
1112    app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
1113
1114    // Add rate limiting middleware (before logging to rate limit early)
1115    app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));
1116
1117    // Add production headers middleware if configured
1118    if state.production_headers.is_some() {
1119        app =
1120            app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
1121    }
1122
1123    // Optionally advertise `Connection: keep-alive` + `Keep-Alive: timeout=N,
1124    // max=M` on every response. Useful when MockForge sits behind a reverse
1125    // proxy (F5/Avi/HAProxy/nginx) that pools upstream sockets based on those
1126    // headers — see issue #79 (proxy reset after FIN on HTTP/1.0 upstream).
1127    // Off by default; opt in via `MOCKFORGE_HTTP_KEEPALIVE_HINT=1`.
1128    if middleware::is_keepalive_hint_enabled() {
1129        info!(
1130            "MOCKFORGE_HTTP_KEEPALIVE_HINT enabled — emitting Connection: keep-alive + Keep-Alive headers on all responses (Issue #79 workaround)"
1131        );
1132        app = app.layer(axum::middleware::from_fn(middleware::keepalive_hint_middleware));
1133    }
1134
1135    // Issue #79 (round 5): per-request log line with HTTP version + Connection
1136    // header MockForge actually sees, so users debugging proxy ↔ MockForge
1137    // negotiation can confirm whether their proxy is speaking HTTP/1.1 with
1138    // keep-alive or HTTP/1.0 (which forces hyper to FIN after each response).
1139    if middleware::is_conn_log_enabled() {
1140        info!(
1141            "MOCKFORGE_HTTP_LOG_CONN enabled — logging HTTP version + Connection headers per request (Issue #79 diagnostic)"
1142        );
1143        app = app.layer(axum::middleware::from_fn(middleware::conn_diag_middleware));
1144    }
1145
1146    // Add authentication middleware if OAuth is configured via deceptive deploy
1147    if let Some(auth_config) = deceptive_deploy_auth_config {
1148        use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1149        use std::collections::HashMap;
1150        use std::sync::Arc;
1151        use tokio::sync::RwLock;
1152
1153        // Create OAuth2 client if configured
1154        let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
1155            match create_oauth2_client(oauth2_config) {
1156                Ok(client) => Some(client),
1157                Err(e) => {
1158                    warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
1159                    None
1160                }
1161            }
1162        } else {
1163            None
1164        };
1165
1166        // Create auth state
1167        let auth_state = AuthState {
1168            config: auth_config,
1169            spec: None, // OpenAPI spec not available in this context
1170            oauth2_client,
1171            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1172        };
1173
1174        // Apply auth middleware
1175        app = app.layer(from_fn_with_state(auth_state, auth_middleware));
1176        info!("Applied OAuth authentication middleware from deceptive deploy configuration");
1177    }
1178
1179    // Add CORS middleware (use final_cors_config which may be overridden by deceptive deploy)
1180    app = apply_cors_middleware(app, final_cors_config);
1181
1182    // Add workspace routing middleware if multi-tenant is enabled
1183    if let Some(mt_config) = multi_tenant_config {
1184        if mt_config.enabled {
1185            use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
1186            use std::sync::Arc;
1187
1188            info!(
1189                "Multi-tenant mode enabled with {} routing strategy",
1190                match mt_config.routing_strategy {
1191                    mockforge_foundation::multi_tenant_types::RoutingStrategy::Path => "path-based",
1192                    mockforge_foundation::multi_tenant_types::RoutingStrategy::Port => "port-based",
1193                    mockforge_foundation::multi_tenant_types::RoutingStrategy::Both => "hybrid",
1194                }
1195            );
1196
1197            // Create the multi-tenant workspace registry
1198            let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
1199
1200            // Register the default workspace before wrapping in Arc
1201            let default_workspace =
1202                mockforge_core::Workspace::new(mt_config.default_workspace.clone());
1203            if let Err(e) =
1204                registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
1205            {
1206                warn!("Failed to register default workspace: {}", e);
1207            } else {
1208                info!("Registered default workspace: '{}'", mt_config.default_workspace);
1209            }
1210
1211            // Auto-discover and register workspaces if configured
1212            if mt_config.auto_discover {
1213                if let Some(config_dir) = &mt_config.config_directory {
1214                    let config_path = Path::new(config_dir);
1215                    if config_path.exists() && config_path.is_dir() {
1216                        match fs::read_dir(config_path).await {
1217                            Ok(mut entries) => {
1218                                while let Ok(Some(entry)) = entries.next_entry().await {
1219                                    let path = entry.path();
1220                                    if path.extension() == Some(OsStr::new("yaml")) {
1221                                        match fs::read_to_string(&path).await {
1222                                            Ok(content) => {
1223                                                match serde_yaml::from_str::<
1224                                                    mockforge_core::Workspace,
1225                                                >(
1226                                                    &content
1227                                                ) {
1228                                                    Ok(workspace) => {
1229                                                        if let Err(e) = registry.register_workspace(
1230                                                            workspace.id.clone(),
1231                                                            workspace,
1232                                                        ) {
1233                                                            warn!("Failed to register auto-discovered workspace from {:?}: {}", path, e);
1234                                                        } else {
1235                                                            info!("Auto-registered workspace from {:?}", path);
1236                                                        }
1237                                                    }
1238                                                    Err(e) => {
1239                                                        warn!("Failed to parse workspace from {:?}: {}", path, e);
1240                                                    }
1241                                                }
1242                                            }
1243                                            Err(e) => {
1244                                                warn!(
1245                                                    "Failed to read workspace file {:?}: {}",
1246                                                    path, e
1247                                                );
1248                                            }
1249                                        }
1250                                    }
1251                                }
1252                            }
1253                            Err(e) => {
1254                                warn!("Failed to read config directory {:?}: {}", config_path, e);
1255                            }
1256                        }
1257                    } else {
1258                        warn!(
1259                            "Config directory {:?} does not exist or is not a directory",
1260                            config_path
1261                        );
1262                    }
1263                }
1264            }
1265
1266            // Wrap registry in Arc for shared access
1267            let registry = Arc::new(registry);
1268
1269            // Create workspace router and wrap the app with workspace middleware
1270            let _workspace_router = WorkspaceRouter::new(registry);
1271
1272            // Note: The actual middleware integration would need to be implemented
1273            // in the WorkspaceRouter to work with Axum's middleware system
1274            info!("Workspace routing middleware initialized for HTTP server");
1275        }
1276    }
1277
1278    let total_startup_duration = startup_start.elapsed();
1279    info!("HTTP router startup completed (total time: {:?})", total_startup_duration);
1280
1281    app
1282}
1283
1284/// Build the base HTTP router with authentication and latency support
1285pub async fn build_router_with_auth_and_latency(
1286    spec_path: Option<String>,
1287    _options: Option<()>,
1288    auth_config: Option<mockforge_core::config::AuthConfig>,
1289    latency_injector: Option<LatencyInjector>,
1290) -> Router {
1291    // Build auth router first, then layer latency on top
1292    let mut app = build_router_with_auth(spec_path.clone(), None, auth_config).await;
1293
1294    // Apply latency injection middleware if configured
1295    if let Some(injector) = latency_injector {
1296        let injector = Arc::new(injector);
1297        app = app.layer(axum::middleware::from_fn(move |req, next: axum::middleware::Next| {
1298            let injector = injector.clone();
1299            async move {
1300                let _ = injector.inject_latency(&[]).await;
1301                next.run(req).await
1302            }
1303        }));
1304    }
1305
1306    app
1307}
1308
1309/// Build the base HTTP router with latency injection support
1310pub async fn build_router_with_latency(
1311    spec_path: Option<String>,
1312    options: Option<ValidationOptions>,
1313    latency_injector: Option<LatencyInjector>,
1314) -> Router {
1315    if let Some(spec) = &spec_path {
1316        match OpenApiSpec::from_file(spec).await {
1317            Ok(openapi) => {
1318                let registry = if let Some(opts) = options {
1319                    OpenApiRouteRegistry::new_with_options(openapi, opts)
1320                } else {
1321                    OpenApiRouteRegistry::new_with_env(openapi)
1322                };
1323
1324                if let Some(injector) = latency_injector {
1325                    return registry.build_router_with_latency(injector);
1326                } else {
1327                    return registry.build_router();
1328                }
1329            }
1330            Err(e) => {
1331                warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec, e);
1332            }
1333        }
1334    }
1335
1336    build_router(None, None, None).await
1337}
1338
1339/// Build the base HTTP router with authentication support
1340pub async fn build_router_with_auth(
1341    spec_path: Option<String>,
1342    options: Option<ValidationOptions>,
1343    auth_config: Option<mockforge_core::config::AuthConfig>,
1344) -> Router {
1345    use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
1346    use std::sync::Arc;
1347
1348    // If richer faker is available, register provider once (idempotent)
1349    #[cfg(feature = "data-faker")]
1350    {
1351        register_core_faker_provider();
1352    }
1353
1354    // Set up authentication state
1355    let spec = if let Some(spec_path) = &spec_path {
1356        match OpenApiSpec::from_file(&spec_path).await {
1357            Ok(spec) => Some(Arc::new(spec)),
1358            Err(e) => {
1359                warn!("Failed to load OpenAPI spec for auth: {}", e);
1360                None
1361            }
1362        }
1363    } else {
1364        None
1365    };
1366
1367    // Create OAuth2 client if configured
1368    let oauth2_client = if let Some(auth_config) = &auth_config {
1369        if let Some(oauth2_config) = &auth_config.oauth2 {
1370            match create_oauth2_client(oauth2_config) {
1371                Ok(client) => Some(client),
1372                Err(e) => {
1373                    warn!("Failed to create OAuth2 client: {}", e);
1374                    None
1375                }
1376            }
1377        } else {
1378            None
1379        }
1380    } else {
1381        None
1382    };
1383
1384    let auth_state = AuthState {
1385        config: auth_config.unwrap_or_default(),
1386        spec,
1387        oauth2_client,
1388        introspection_cache: Arc::new(RwLock::new(HashMap::new())),
1389    };
1390
1391    // Set up the basic router with auth state
1392    let mut app = Router::new().with_state(auth_state.clone());
1393
1394    // If an OpenAPI spec is provided, integrate it
1395    if let Some(spec_path) = spec_path {
1396        match OpenApiSpec::from_file(&spec_path).await {
1397            Ok(openapi) => {
1398                info!("Loaded OpenAPI spec from {}", spec_path);
1399                let registry = if let Some(opts) = options {
1400                    OpenApiRouteRegistry::new_with_options(openapi, opts)
1401                } else {
1402                    OpenApiRouteRegistry::new_with_env(openapi)
1403                };
1404
1405                app = registry.build_router();
1406            }
1407            Err(e) => {
1408                warn!("Failed to load OpenAPI spec from {}: {}. Starting without OpenAPI integration.", spec_path, e);
1409            }
1410        }
1411    }
1412
1413    // Add basic health check endpoint
1414    app = app.route(
1415        "/health",
1416        axum::routing::get(|| async {
1417            use mockforge_core::server_utils::health::HealthStatus;
1418            {
1419                // HealthStatus should always serialize, but handle errors gracefully
1420                match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
1421                    Ok(value) => Json(value),
1422                    Err(e) => {
1423                        // Log error but return a simple healthy response
1424                        tracing::error!("Failed to serialize health status: {}", e);
1425                        Json(serde_json::json!({
1426                            "status": "healthy",
1427                            "service": "mockforge-http",
1428                            "uptime_seconds": 0
1429                        }))
1430                    }
1431                }
1432            }
1433        }),
1434    )
1435    // Add SSE endpoints
1436    .merge(sse::sse_router())
1437    // Add file serving endpoints for generated mock files
1438    .merge(file_server::file_serving_router())
1439    // Add authentication middleware (before logging)
1440    .layer(from_fn_with_state(auth_state.clone(), auth_middleware))
1441    // Add request logging middleware
1442    .layer(axum::middleware::from_fn(request_logging::log_http_requests));
1443
1444    app
1445}
1446
1447/// Serve a provided router on the given port.
1448pub async fn serve_router(
1449    port: u16,
1450    app: Router,
1451) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1452    serve_router_with_tls(port, app, None).await
1453}
1454
1455/// Serve a provided router on the given port with optional TLS support.
1456pub async fn serve_router_with_tls(
1457    port: u16,
1458    app: Router,
1459    tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1460) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1461    serve_router_with_tls_notify(port, app, tls_config, None).await
1462}
1463
1464/// Serve a provided router on the given port with optional TLS support, notifying
1465/// the caller via `bound_port_tx` with the actual OS-assigned port once the
1466/// listener has bound. This matters when the requested `port` is `0` (ephemeral),
1467/// because callers such as the `@mockforge-dev/sdk` need to learn the real port
1468/// to connect to it. On the TLS path, `bound_port_tx` is currently ignored and
1469/// the requested `port` is reported verbatim — callers that need dynamic TLS
1470/// ports should bind on a known port.
1471pub async fn serve_router_with_tls_notify(
1472    port: u16,
1473    app: Router,
1474    tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1475    bound_port_tx: Option<tokio::sync::oneshot::Sender<u16>>,
1476) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1477    serve_router_with_tls_notify_chaos(port, app, tls_config, bound_port_tx, None).await
1478}
1479
1480/// Serve a router with optional TLS *and* an optional shared chaos config.
1481///
1482/// When `chaos_config` is `Some`, the TCP listener is wrapped with
1483/// [`mockforge_chaos::ChaosTcpListener`], which can inject TCP-level
1484/// connection faults (RST or unclean FIN) before axum/hyper see the socket.
1485/// This is the only way to surface real transport-level failures rather than
1486/// HTTP 503 responses on healthy connections. TLS path does not yet support
1487/// chaos listener wrapping (axum-server uses its own accept loop).
1488pub async fn serve_router_with_tls_notify_chaos(
1489    port: u16,
1490    app: Router,
1491    tls_config: Option<mockforge_core::config::HttpTlsConfig>,
1492    bound_port_tx: Option<tokio::sync::oneshot::Sender<u16>>,
1493    chaos_config: Option<Arc<RwLock<mockforge_chaos::ChaosConfig>>>,
1494) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1495    use std::net::SocketAddr;
1496
1497    let addr = mockforge_core::wildcard_socket_addr(port);
1498
1499    if let Some(ref tls) = tls_config {
1500        if tls.enabled {
1501            info!("HTTPS listening on {}", addr);
1502            if let Some(tx) = bound_port_tx {
1503                let _ = tx.send(port);
1504            }
1505            return serve_with_tls(addr, app, tls).await;
1506        }
1507    }
1508
1509    let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
1510        format!(
1511            "Failed to bind HTTP server to port {}: {}\n\
1512             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 {}",
1513            port, e, port, port
1514        )
1515    })?;
1516
1517    let actual_port = listener.local_addr().map(|a| a.port()).unwrap_or(port);
1518    info!("HTTP listening on {}", listener.local_addr().unwrap_or(addr));
1519    if let Some(tx) = bound_port_tx {
1520        let _ = tx.send(actual_port);
1521    }
1522
1523    // Wrap the Router with OData URI rewrite.
1524    // Router::layer() only applies to matched routes, so we must wrap at the service level
1525    // to rewrite URIs BEFORE route matching occurs.
1526    let odata_app = tower::ServiceBuilder::new()
1527        .layer(mockforge_core::odata_rewrite::ODataRewriteLayer)
1528        .service(app);
1529    if let Some(cfg) = chaos_config {
1530        info!("HTTP listener wrapped with chaos TCP listener (RST/FIN injection enabled)");
1531        let chaos_listener = mockforge_chaos::ChaosTcpListener::new(listener, cfg);
1532        // Layer that copies ConnectInfo<ChaosClientAddr> → ConnectInfo<SocketAddr>
1533        // so existing handlers using `ConnectInfo<SocketAddr>` keep working.
1534        let app_with_addr_compat = tower::ServiceBuilder::new()
1535            .layer(axum::middleware::from_fn(copy_chaos_addr_to_socketaddr))
1536            .service(odata_app);
1537        let make_svc = axum::ServiceExt::<Request<Body>>::into_make_service_with_connect_info::<
1538            mockforge_chaos::ChaosClientAddr,
1539        >(app_with_addr_compat);
1540        // Bump the accept counter on each connection that gets through chaos.
1541        let counted = counting_listener::CountingMakeService::new(make_svc);
1542        axum::serve(chaos_listener, counted).await?;
1543    } else {
1544        let make_svc = axum::ServiceExt::<Request<Body>>::into_make_service_with_connect_info::<
1545            SocketAddr,
1546        >(odata_app);
1547        // Bump the accept counter once per accepted connection so the
1548        // dashboard sampler can derive CPS.
1549        let counted = counting_listener::CountingMakeService::new(make_svc);
1550        axum::serve(listener, counted).await?;
1551    }
1552    Ok(())
1553}
1554
1555/// Mirror `ConnectInfo<ChaosClientAddr>` (set by the chaos listener) onto
1556/// `ConnectInfo<SocketAddr>` so handlers extracting `ConnectInfo<SocketAddr>`
1557/// keep working when chaos TCP wrapping is enabled.
1558async fn copy_chaos_addr_to_socketaddr(
1559    mut req: Request<Body>,
1560    next: axum::middleware::Next,
1561) -> axum::response::Response {
1562    use axum::extract::ConnectInfo;
1563    if let Some(ConnectInfo(chaos_addr)) =
1564        req.extensions().get::<ConnectInfo<mockforge_chaos::ChaosClientAddr>>().copied()
1565    {
1566        let sock: std::net::SocketAddr = *chaos_addr;
1567        req.extensions_mut().insert(ConnectInfo(sock));
1568    }
1569    next.run(req).await
1570}
1571
1572/// Serve router with TLS/HTTPS support using axum-server
1573///
1574/// This function implements native TLS serving using axum-server and tokio-rustls.
1575/// It supports standard TLS and mutual TLS (mTLS) based on the configuration.
1576async fn serve_with_tls(
1577    addr: std::net::SocketAddr,
1578    app: Router,
1579    tls_config: &mockforge_core::config::HttpTlsConfig,
1580) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1581    use axum_server::tls_rustls::RustlsConfig;
1582    use std::net::SocketAddr;
1583
1584    // Initialize the rustls crypto provider (must be called before TLS operations)
1585    tls::init_crypto_provider();
1586
1587    info!("Loading TLS configuration for HTTPS server");
1588
1589    // Load TLS server configuration (supports mTLS)
1590    let server_config = tls::load_tls_server_config(tls_config)?;
1591
1592    // Create RustlsConfig from the ServerConfig
1593    // Note: axum-server's RustlsConfig can be created from a ServerConfig
1594    let rustls_config = RustlsConfig::from_config(server_config);
1595
1596    info!("Starting HTTPS server on {}", addr);
1597
1598    // Wrap the Router with OData URI rewrite (same as the non-TLS path).
1599    // Router::layer() only applies to matched routes, so we must wrap at the service level
1600    // to rewrite URIs BEFORE route matching occurs.
1601    let odata_app = tower::ServiceBuilder::new()
1602        .layer(mockforge_core::odata_rewrite::ODataRewriteLayer)
1603        .service(app);
1604    let make_svc = axum::ServiceExt::<Request<Body>>::into_make_service_with_connect_info::<
1605        SocketAddr,
1606    >(odata_app);
1607    // Bump the accept counter once per successful TLS handshake / connection
1608    // so the dashboard sampler can derive CPS for HTTPS-only setups.
1609    let counted = counting_listener::CountingMakeService::new(make_svc);
1610
1611    // Serve with TLS using axum-server
1612    axum_server::bind_rustls(addr, rustls_config)
1613        .serve(counted)
1614        .await
1615        .map_err(|e| format!("HTTPS server error: {}", e).into())
1616}
1617
1618/// Backwards-compatible start that builds + serves the base router.
1619pub async fn start(
1620    port: u16,
1621    spec_path: Option<String>,
1622    options: Option<ValidationOptions>,
1623) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1624    start_with_latency(port, spec_path, options, None).await
1625}
1626
1627/// Start HTTP server with authentication and latency support
1628pub async fn start_with_auth_and_latency(
1629    port: u16,
1630    spec_path: Option<String>,
1631    options: Option<ValidationOptions>,
1632    auth_config: Option<mockforge_core::config::AuthConfig>,
1633    latency_profile: Option<LatencyProfile>,
1634) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1635    start_with_auth_and_injectors(port, spec_path, options, auth_config, latency_profile, None)
1636        .await
1637}
1638
1639/// Start HTTP server with authentication and injectors support
1640pub async fn start_with_auth_and_injectors(
1641    port: u16,
1642    spec_path: Option<String>,
1643    options: Option<ValidationOptions>,
1644    auth_config: Option<mockforge_core::config::AuthConfig>,
1645    _latency_profile: Option<LatencyProfile>,
1646    _failure_injector: Option<FailureInjector>,
1647) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1648    // For now, ignore latency and failure injectors and just use auth
1649    let app = build_router_with_auth(spec_path, options, auth_config).await;
1650    serve_router(port, app).await
1651}
1652
1653/// Start HTTP server with latency injection support
1654pub async fn start_with_latency(
1655    port: u16,
1656    spec_path: Option<String>,
1657    options: Option<ValidationOptions>,
1658    latency_profile: Option<LatencyProfile>,
1659) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1660    let latency_injector =
1661        latency_profile.map(|profile| LatencyInjector::new(profile, Default::default()));
1662
1663    let app = build_router_with_latency(spec_path, options, latency_injector).await;
1664    serve_router(port, app).await
1665}
1666
1667/// Build the base HTTP router with chaining support
1668pub async fn build_router_with_chains(
1669    spec_path: Option<String>,
1670    options: Option<ValidationOptions>,
1671    circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1672) -> Router {
1673    build_router_with_chains_and_multi_tenant(
1674        spec_path,
1675        options,
1676        circling_config,
1677        None,
1678        None,
1679        None,
1680        None,
1681        None, // smtp_registry
1682        None, // mqtt_broker
1683        None, // amqp_broker
1684        None, // kafka_broker
1685        None, // traffic_shaper
1686        false,
1687        None, // health_manager
1688        None, // mockai
1689        None, // deceptive_deploy_config
1690        None, // proxy_config
1691        mockforge_core::SharedOverrides::load(Vec::new()).await,
1692    )
1693    .await
1694}
1695
1696// Template expansion is now handled by mockforge_core::template_expansion
1697// which is explicitly isolated from the templating module to avoid Send issues
1698
1699/// Helper function to apply route chaos injection (fault injection and latency)
1700/// This is extracted to avoid capturing RouteChaosInjector in the closure, which causes Send issues
1701/// Uses mockforge-route-chaos crate which is isolated from mockforge-core to avoid Send issues
1702/// Uses the RouteChaosInjectorTrait from mockforge-core to avoid circular dependency
1703async fn apply_route_chaos(
1704    injector: Option<&dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1705    method: &http::Method,
1706    uri: &http::Uri,
1707) -> Option<axum::response::Response> {
1708    use axum::http::StatusCode;
1709    use axum::response::IntoResponse;
1710
1711    if let Some(injector) = injector {
1712        // Check for fault injection first
1713        if let Some(fault_response) = injector.get_fault_response(method, uri) {
1714            // Return fault response
1715            let mut response = Json(serde_json::json!({
1716                "error": fault_response.error_message,
1717                "fault_type": fault_response.fault_type,
1718            }))
1719            .into_response();
1720            *response.status_mut() = StatusCode::from_u16(fault_response.status_code)
1721                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1722            return Some(response);
1723        }
1724
1725        // Inject latency if configured (this is async and may delay the request)
1726        if let Err(e) = injector.inject_latency(method, uri).await {
1727            tracing::warn!("Failed to inject latency: {}", e);
1728        }
1729    }
1730
1731    None // No fault response, processing should continue
1732}
1733
1734/// Build the base HTTP router with chaining and multi-tenant support
1735#[allow(clippy::too_many_arguments)]
1736#[allow(deprecated)] // uses core engines (DriftBudgetEngine, ThreatAnalyzer, Forecaster, ProtocolContractRegistry, MockAI, MultiTenantWorkspaceRegistry, etc.) that stay in core
1737pub async fn build_router_with_chains_and_multi_tenant(
1738    spec_path: Option<String>,
1739    options: Option<ValidationOptions>,
1740    _circling_config: Option<mockforge_core::request_chaining::ChainConfig>,
1741    multi_tenant_config: Option<mockforge_foundation::multi_tenant_types::MultiTenantConfig>,
1742    route_configs: Option<Vec<mockforge_core::config::RouteConfig>>,
1743    cors_config: Option<mockforge_core::config::HttpCorsConfig>,
1744    _ai_generator: Option<Arc<dyn mockforge_openapi::response::AiGenerator + Send + Sync>>,
1745    smtp_registry: Option<Arc<dyn std::any::Any + Send + Sync>>,
1746    mqtt_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
1747    amqp_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
1748    kafka_broker: Option<Arc<dyn std::any::Any + Send + Sync>>,
1749    traffic_shaper: Option<mockforge_core::traffic_shaping::TrafficShaper>,
1750    traffic_shaping_enabled: bool,
1751    health_manager: Option<Arc<HealthManager>>,
1752    mockai: Option<Arc<RwLock<mockforge_core::intelligent_behavior::MockAI>>>,
1753    deceptive_deploy_config: Option<mockforge_core::config::DeceptiveDeployConfig>,
1754    proxy_config: Option<mockforge_proxy::config::ProxyConfig>,
1755    overrides: mockforge_core::SharedOverrides,
1756) -> Router {
1757    use crate::latency_profiles::LatencyProfiles;
1758    use crate::op_middleware::Shared;
1759
1760    // Extract template expansion setting before options is moved (used in OpenAPI routes and custom routes)
1761    let template_expand =
1762        options.as_ref().map(|o| o.response_template_expand).unwrap_or_else(|| {
1763            std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
1764                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1765                .unwrap_or(false)
1766        });
1767
1768    let _shared = Shared {
1769        profiles: LatencyProfiles::default(),
1770        failure_injector: None,
1771        traffic_shaper,
1772        traffic_shaping_enabled,
1773    };
1774
1775    // Start with basic router
1776    let mut app = Router::new();
1777    let mut include_default_health = true;
1778    let mut captured_routes: Vec<RouteInfo> = Vec::new();
1779
1780    // If an OpenAPI spec is provided, integrate it
1781    if let Some(ref spec) = spec_path {
1782        match OpenApiSpec::from_file(&spec).await {
1783            Ok(openapi) => {
1784                info!("Loaded OpenAPI spec from {}", spec);
1785
1786                // Try to load persona from config if available
1787                let persona = load_persona_from_config().await;
1788
1789                let mut registry = if let Some(opts) = options {
1790                    tracing::debug!("Using custom validation options");
1791                    if let Some(ref persona) = persona {
1792                        tracing::info!("Using persona '{}' for route generation", persona.name);
1793                    }
1794                    OpenApiRouteRegistry::new_with_options_and_persona(openapi, opts, persona)
1795                } else {
1796                    tracing::debug!("Using environment-based options");
1797                    if let Some(ref persona) = persona {
1798                        tracing::info!("Using persona '{}' for route generation", persona.name);
1799                    }
1800                    OpenApiRouteRegistry::new_with_env_and_persona(openapi, persona)
1801                };
1802
1803                // Load custom fixtures if enabled
1804                let fixtures_dir = std::env::var("MOCKFORGE_FIXTURES_DIR")
1805                    .unwrap_or_else(|_| "/app/fixtures".to_string());
1806                let custom_fixtures_enabled = std::env::var("MOCKFORGE_CUSTOM_FIXTURES_ENABLED")
1807                    .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1808                    .unwrap_or(true); // Enabled by default
1809
1810                if custom_fixtures_enabled {
1811                    use mockforge_openapi::CustomFixtureLoader;
1812                    use std::path::PathBuf;
1813                    use std::sync::Arc;
1814
1815                    let fixtures_path = PathBuf::from(&fixtures_dir);
1816                    let mut custom_loader = CustomFixtureLoader::new(fixtures_path, true);
1817
1818                    if let Err(e) = custom_loader.load_fixtures().await {
1819                        tracing::warn!("Failed to load custom fixtures: {}", e);
1820                    } else {
1821                        tracing::info!("Custom fixtures loaded from {}", fixtures_dir);
1822                        registry = registry.with_custom_fixture_loader(Arc::new(custom_loader));
1823                    }
1824                }
1825                registry = registry.with_overrides(Arc::new(overrides.clone()));
1826
1827                if registry
1828                    .routes()
1829                    .iter()
1830                    .any(|route| route.method == "GET" && route.path == "/health")
1831                {
1832                    include_default_health = false;
1833                }
1834                // Capture route info for the /__mockforge/routes endpoint
1835                captured_routes = registry
1836                    .routes()
1837                    .iter()
1838                    .map(|r| RouteInfo {
1839                        method: r.method.clone(),
1840                        path: r.path.clone(),
1841                        operation_id: r.operation.operation_id.clone(),
1842                        summary: r.operation.summary.clone(),
1843                        description: r.operation.description.clone(),
1844                        parameters: r.parameters.clone(),
1845                    })
1846                    .collect();
1847
1848                // Store routes in the global route store so the admin server
1849                // can serve them without proxying back to the HTTP server.
1850                {
1851                    let global_routes: Vec<mockforge_core::request_logger::GlobalRouteInfo> =
1852                        captured_routes
1853                            .iter()
1854                            .map(|r| mockforge_core::request_logger::GlobalRouteInfo {
1855                                method: r.method.clone(),
1856                                path: r.path.clone(),
1857                                operation_id: r.operation_id.clone(),
1858                                summary: r.summary.clone(),
1859                                description: r.description.clone(),
1860                                parameters: r.parameters.clone(),
1861                            })
1862                            .collect();
1863                    mockforge_core::request_logger::set_global_routes(global_routes);
1864                    tracing::info!("Stored {} routes in global route store", captured_routes.len());
1865                }
1866
1867                // Use MockAI if available, otherwise use standard router
1868                let spec_router = if let Some(ref mockai_instance) = mockai {
1869                    tracing::debug!("Building router with MockAI support");
1870                    registry.build_router_with_mockai(Some(mockai_instance.clone()))
1871                } else {
1872                    registry.build_router()
1873                };
1874                // Issue #79 — explicitly stamp the body-size limit on the
1875                // openapi sub-router BEFORE merging. The limit is also
1876                // applied inside `OpenApiRouteRegistry::build_router_*`,
1877                // but axum's `merge` can drop nested layers in some
1878                // configurations; redoing it at the merge site is cheap
1879                // insurance against the "200 OK before body completes"
1880                // bug Srikanth reported on Issue #79.
1881                let body_limit_mb = std::env::var("MOCKFORGE_HTTP_BODY_LIMIT_MB")
1882                    .ok()
1883                    .and_then(|v| v.parse::<usize>().ok())
1884                    .unwrap_or(50);
1885                let body_limit_bytes = body_limit_mb.saturating_mul(1024 * 1024);
1886                let spec_router =
1887                    spec_router.layer(axum::extract::DefaultBodyLimit::max(body_limit_bytes));
1888                tracing::info!(
1889                    body_limit_mb = body_limit_mb,
1890                    "Merging OpenAPI router with main router"
1891                );
1892                app = app.merge(spec_router);
1893            }
1894            Err(e) => {
1895                warn!("Failed to load OpenAPI spec from {:?}: {}. Starting without OpenAPI integration.", spec_path, e);
1896            }
1897        }
1898    }
1899
1900    // Register custom routes from config with advanced routing features
1901    // Create RouteChaosInjector for advanced fault injection and latency
1902    // Store as trait object to avoid circular dependency (RouteChaosInjectorTrait is in mockforge-core)
1903    let route_chaos_injector: Option<
1904        std::sync::Arc<dyn mockforge_core::priority_handler::RouteChaosInjectorTrait>,
1905    > = if let Some(ref route_configs) = route_configs {
1906        if !route_configs.is_empty() {
1907            // Convert to the type expected by RouteChaosInjector
1908            // Note: Both use the same mockforge-core, but we need to ensure type compatibility
1909            let route_configs_converted: Vec<mockforge_core::config::RouteConfig> =
1910                route_configs.to_vec();
1911            match mockforge_route_chaos::RouteChaosInjector::new(route_configs_converted) {
1912                Ok(injector) => {
1913                    info!(
1914                        "Initialized advanced routing features for {} route(s)",
1915                        route_configs.len()
1916                    );
1917                    // RouteChaosInjector implements RouteChaosInjectorTrait, so we can cast it
1918                    // The trait is implemented in mockforge-route-chaos/src/lib.rs
1919                    Some(std::sync::Arc::new(injector)
1920                        as std::sync::Arc<
1921                            dyn mockforge_core::priority_handler::RouteChaosInjectorTrait,
1922                        >)
1923                }
1924                Err(e) => {
1925                    warn!(
1926                        "Failed to initialize advanced routing features: {}. Using basic routing.",
1927                        e
1928                    );
1929                    None
1930                }
1931            }
1932        } else {
1933            None
1934        }
1935    } else {
1936        None
1937    };
1938
1939    if let Some(route_configs) = route_configs {
1940        use axum::http::StatusCode;
1941        use axum::response::IntoResponse;
1942
1943        if !route_configs.is_empty() {
1944            info!("Registering {} custom route(s) from config", route_configs.len());
1945        }
1946
1947        let injector = route_chaos_injector.clone();
1948        for route_config in route_configs {
1949            let status = route_config.response.status;
1950            let body = route_config.response.body.clone();
1951            let headers = route_config.response.headers.clone();
1952            let path = route_config.path.clone();
1953            let method = route_config.method.clone();
1954
1955            // Create handler that returns the configured response with template expansion
1956            // Supports both basic templates ({{uuid}}, {{now}}) and request-aware templates
1957            // ({{request.query.name}}, {{request.path.id}}, {{request.headers.name}})
1958            // Register route using `any()` since we need full Request access for template expansion
1959            let expected_method = method.to_uppercase();
1960            // Clone Arc for the closure - Arc is Send-safe
1961            // Note: RouteChaosInjector is marked as Send+Sync via unsafe impl, so we have to
1962            // clone the Arc rather than move the inner injector into the route handler.
1963            let injector_clone = injector.clone();
1964            app = app.route(
1965                &path,
1966                #[allow(clippy::non_send_fields_in_send_ty)]
1967                axum::routing::any(move |req: Request<Body>| {
1968                    let body = body.clone();
1969                    let headers = headers.clone();
1970                    let expand = template_expand;
1971                    let expected = expected_method.clone();
1972                    let status_code = status;
1973                    // Clone Arc again for the async block
1974                    let injector_for_chaos = injector_clone.clone();
1975
1976                    async move {
1977                        // Check if request method matches expected method
1978                        if req.method().as_str() != expected.as_str() {
1979                            // Return 405 Method Not Allowed for wrong method
1980                            return axum::response::Response::builder()
1981                                .status(StatusCode::METHOD_NOT_ALLOWED)
1982                                .header("Allow", &expected)
1983                                .body(Body::empty())
1984                                .unwrap()
1985                                .into_response();
1986                        }
1987
1988                        // Apply advanced routing features (fault injection and latency) if available
1989                        // Use helper function to avoid capturing RouteChaosInjector in closure
1990                        // Pass the Arc as a reference to the helper function
1991                        if let Some(fault_response) = apply_route_chaos(
1992                            injector_for_chaos.as_deref(),
1993                            req.method(),
1994                            req.uri(),
1995                        )
1996                        .await
1997                        {
1998                            return fault_response;
1999                        }
2000
2001                        // Create JSON response from body, or empty object if None
2002                        let mut body_value = body.unwrap_or(serde_json::json!({}));
2003
2004                        // Apply template expansion if enabled
2005                        // Use mockforge-template-expansion crate which is completely isolated
2006                        // from mockforge-core to avoid Send issues (no rng() in dependency chain)
2007                        if expand {
2008                            use mockforge_template_expansion::RequestContext;
2009                            use serde_json::Value;
2010                            use std::collections::HashMap;
2011
2012                            // Extract request data for template expansion
2013                            let method = req.method().to_string();
2014                            let path = req.uri().path().to_string();
2015
2016                            // Extract query parameters
2017                            let query_params: HashMap<String, Value> = req
2018                                .uri()
2019                                .query()
2020                                .map(|q| {
2021                                    url::form_urlencoded::parse(q.as_bytes())
2022                                        .into_owned()
2023                                        .map(|(k, v)| (k, Value::String(v)))
2024                                        .collect()
2025                                })
2026                                .unwrap_or_default();
2027
2028                            // Extract headers
2029                            let headers: HashMap<String, Value> = req
2030                                .headers()
2031                                .iter()
2032                                .map(|(k, v)| {
2033                                    (
2034                                        k.to_string(),
2035                                        Value::String(v.to_str().unwrap_or_default().to_string()),
2036                                    )
2037                                })
2038                                .collect();
2039
2040                            // Create RequestContext for expand_prompt_template
2041                            // Using RequestContext from mockforge-template-expansion (not mockforge-core)
2042                            // to avoid bringing rng() into scope
2043                            let context = RequestContext {
2044                                method,
2045                                path,
2046                                query_params,
2047                                headers,
2048                                body: None, // Body extraction would require reading the request stream
2049                                path_params: HashMap::new(),
2050                                multipart_fields: HashMap::new(),
2051                                multipart_files: HashMap::new(),
2052                            };
2053
2054                            // Perform template expansion in spawn_blocking to ensure Send safety
2055                            // The template expansion crate is completely isolated from mockforge-core
2056                            // and doesn't have rng() in its dependency chain
2057                            let body_value_clone = body_value.clone();
2058                            let context_clone = context.clone();
2059                            body_value = match tokio::task::spawn_blocking(move || {
2060                                mockforge_template_expansion::expand_templates_in_json(
2061                                    body_value_clone,
2062                                    &context_clone,
2063                                )
2064                            })
2065                            .await
2066                            {
2067                                Ok(result) => result,
2068                                Err(_) => body_value, // Fallback to original on error
2069                            };
2070                        }
2071
2072                        let mut response = Json(body_value).into_response();
2073
2074                        // Set status code
2075                        *response.status_mut() =
2076                            StatusCode::from_u16(status_code).unwrap_or(StatusCode::OK);
2077
2078                        // Add custom headers
2079                        for (key, value) in headers {
2080                            if let Ok(header_name) = http::HeaderName::from_bytes(key.as_bytes()) {
2081                                if let Ok(header_value) = http::HeaderValue::from_str(&value) {
2082                                    response.headers_mut().insert(header_name, header_value);
2083                                }
2084                            }
2085                        }
2086
2087                        response
2088                    }
2089                }),
2090            );
2091
2092            debug!("Registered route: {} {}", method, path);
2093        }
2094    }
2095
2096    // Add health check endpoints
2097    if let Some(health) = health_manager {
2098        // Use comprehensive health check router with all probe endpoints
2099        app = app.merge(health::health_router(health));
2100        info!(
2101            "Health check endpoints enabled: /health, /health/live, /health/ready, /health/startup"
2102        );
2103    } else if include_default_health {
2104        // Fallback to basic health endpoint for backwards compatibility
2105        app = app.route(
2106            "/health",
2107            axum::routing::get(|| async {
2108                use mockforge_core::server_utils::health::HealthStatus;
2109                {
2110                    // HealthStatus should always serialize, but handle errors gracefully
2111                    match serde_json::to_value(HealthStatus::healthy(0, "mockforge-http")) {
2112                        Ok(value) => Json(value),
2113                        Err(e) => {
2114                            // Log error but return a simple healthy response
2115                            tracing::error!("Failed to serialize health status: {}", e);
2116                            Json(serde_json::json!({
2117                                "status": "healthy",
2118                                "service": "mockforge-http",
2119                                "uptime_seconds": 0
2120                            }))
2121                        }
2122                    }
2123                }
2124            }),
2125        );
2126    }
2127
2128    app = app.merge(sse::sse_router());
2129    // Add file serving endpoints for generated mock files
2130    app = app.merge(file_server::file_serving_router());
2131
2132    // Add management API endpoints
2133    // Load spec for ManagementState so /__mockforge/api/spec can serve it
2134    let mgmt_spec = if let Some(ref sp) = spec_path {
2135        match OpenApiSpec::from_file(sp).await {
2136            Ok(s) => Some(Arc::new(s)),
2137            Err(e) => {
2138                debug!("Failed to load OpenAPI spec for management API: {}", e);
2139                None
2140            }
2141        }
2142    } else {
2143        None
2144    };
2145    let spec_path_clone = spec_path.clone();
2146    let mgmt_port = std::env::var("PORT")
2147        .or_else(|_| std::env::var("MOCKFORGE_HTTP_PORT"))
2148        .ok()
2149        .and_then(|p| p.parse().ok())
2150        .unwrap_or(3000);
2151    let management_state = ManagementState::new(mgmt_spec, spec_path_clone, mgmt_port);
2152
2153    // Create WebSocket state and connect it to management state
2154    use std::sync::Arc;
2155    let ws_state = WsManagementState::new();
2156    let ws_broadcast = Arc::new(ws_state.tx.clone());
2157    let management_state = management_state.with_ws_broadcast(ws_broadcast);
2158
2159    // Add proxy config to management state if available
2160    let management_state = if let Some(proxy_cfg) = proxy_config {
2161        use tokio::sync::RwLock;
2162        let proxy_config_arc = Arc::new(RwLock::new(proxy_cfg));
2163        management_state.with_proxy_config(proxy_config_arc)
2164    } else {
2165        management_state
2166    };
2167
2168    #[cfg(feature = "smtp")]
2169    let management_state = {
2170        if let Some(smtp_reg) = smtp_registry {
2171            match smtp_reg.downcast::<mockforge_smtp::SmtpSpecRegistry>() {
2172                Ok(smtp_reg) => management_state.with_smtp_registry(smtp_reg),
2173                Err(e) => {
2174                    error!(
2175                        "Invalid SMTP registry type passed to HTTP management state: {:?}",
2176                        e.type_id()
2177                    );
2178                    management_state
2179                }
2180            }
2181        } else {
2182            management_state
2183        }
2184    };
2185    #[cfg(not(feature = "smtp"))]
2186    let management_state = {
2187        let _ = smtp_registry;
2188        management_state
2189    };
2190    #[cfg(feature = "mqtt")]
2191    let management_state = {
2192        // The `mqtt_broker` slot carries the live `Arc<SessionManager>` (the
2193        // running listener's state), not an `MqttBroker` — see issue #730.
2194        if let Some(sessions) = mqtt_broker {
2195            match sessions.downcast::<mockforge_mqtt::SessionManager>() {
2196                Ok(sessions) => management_state.with_mqtt_sessions(sessions),
2197                Err(e) => {
2198                    error!(
2199                        "Invalid MQTT session manager passed to HTTP management state: {:?}",
2200                        e.type_id()
2201                    );
2202                    management_state
2203                }
2204            }
2205        } else {
2206            management_state
2207        }
2208    };
2209    #[cfg(not(feature = "mqtt"))]
2210    let management_state = {
2211        let _ = mqtt_broker;
2212        management_state
2213    };
2214    #[cfg(feature = "amqp")]
2215    let management_state = {
2216        if let Some(broker) = amqp_broker {
2217            match broker.downcast::<mockforge_amqp::AmqpBroker>() {
2218                Ok(broker) => management_state.with_amqp_broker(broker),
2219                Err(e) => {
2220                    error!(
2221                        "Invalid AMQP broker passed to HTTP management state: {:?}",
2222                        e.type_id()
2223                    );
2224                    management_state
2225                }
2226            }
2227        } else {
2228            management_state
2229        }
2230    };
2231    #[cfg(not(feature = "amqp"))]
2232    let management_state = {
2233        let _ = amqp_broker;
2234        management_state
2235    };
2236    #[cfg(feature = "kafka")]
2237    let management_state = {
2238        if let Some(broker) = kafka_broker {
2239            match broker.downcast::<mockforge_kafka::KafkaMockBroker>() {
2240                Ok(broker) => management_state.with_kafka_broker(broker),
2241                Err(e) => {
2242                    error!(
2243                        "Invalid Kafka broker passed to HTTP management state: {:?}",
2244                        e.type_id()
2245                    );
2246                    management_state
2247                }
2248            }
2249        } else {
2250            management_state
2251        }
2252    };
2253    #[cfg(not(feature = "kafka"))]
2254    let management_state = {
2255        let _ = kafka_broker;
2256        management_state
2257    };
2258    let management_state_for_fallback = management_state.clone();
2259    app = app.nest("/__mockforge/api", management_router(management_state));
2260    // Dynamic-mock fallback; see identical block earlier in this file.
2261    app = app.fallback_service(
2262        axum::routing::any(management::dynamic_mock_fallback)
2263            .with_state(management_state_for_fallback),
2264    );
2265
2266    // Add verification API endpoint
2267    app = app.merge(verification_router());
2268
2269    // Mount the request-chains management API at the prefix the UI's
2270    // ChainsPage expects (`/__mockforge/chains/*`). Without this nest the
2271    // page 404s on every call. The registry/engine are constructed from
2272    // the chain_config param when supplied, otherwise from defaults.
2273    {
2274        use crate::chain_handlers::{chains_router, create_chain_state};
2275        let chain_config = _circling_config.clone().unwrap_or_default();
2276        let chain_registry = Arc::new(mockforge_core::request_chaining::RequestChainRegistry::new(
2277            chain_config.clone(),
2278        ));
2279        let chain_engine = Arc::new(mockforge_core::chain_execution::ChainExecutionEngine::new(
2280            chain_registry.clone(),
2281            chain_config,
2282        ));
2283        app = app.nest(
2284            "/__mockforge/chains",
2285            chains_router(create_chain_state(chain_registry, chain_engine)),
2286        );
2287    }
2288
2289    // Contract-diff retrieval API. The `capture_for_contract_diff`
2290    // middleware (layered earlier) populates the global capture manager
2291    // on every request; this surface lets operators read the captures
2292    // and run the analyser against the current OpenAPI spec.
2293    {
2294        use crate::contract_diff_api::{contract_diff_api_router, ContractDiffApiState};
2295        let cd_state = Arc::new(ContractDiffApiState::new(spec_path.clone()));
2296        app = app.nest("/__mockforge/api/contract-diff", contract_diff_api_router(cd_state));
2297    }
2298
2299    // Fixtures management API. Lives on the admin server too (port 9080),
2300    // but hosted-mock Fly machines only expose port 3000 publicly — so
2301    // we mount the same surface on the main HTTP app. Newly-uploaded
2302    // fixtures land in `MOCKFORGE_FIXTURES_DIR` and are picked up by
2303    // the startup-time loader on the next deploy/restart; live reload
2304    // is a separate concern.
2305    {
2306        use crate::fixtures_api::{fixtures_api_router, FixturesApiState};
2307        let fx_state = FixturesApiState::from_env();
2308        app = app.nest("/__mockforge/fixtures", fixtures_api_router(fx_state));
2309    }
2310
2311    // Standalone MockAI API. Until now MockAI was only invoked from the
2312    // OpenAPI route generator — so a hosted mock without a spec, or a
2313    // user wanting to prototype an "AI persona" mock without registering
2314    // routes, had no way to reach the engine. The endpoint surfaces 503
2315    // when MockAI isn't configured (no API key) so callers get a clear
2316    // signal rather than a silent failure.
2317    {
2318        use crate::mockai_api::{mockai_api_router, MockAiApiState};
2319        let api_state = MockAiApiState::new(mockai.clone());
2320        app = app.nest("/__mockforge/api/mockai", mockai_api_router(api_state));
2321    }
2322
2323    // Time-travel runtime API. The admin server mounts these routes on
2324    // its own port (9080), but hosted-mock Fly machines only expose
2325    // port 3000 publicly — so until now operators couldn't set / advance
2326    // virtual time on a deployed mock. The handlers consult a process-
2327    // wide TimeTravelManager that serve.rs initialises alongside the
2328    // existing admin-server registration; both paths see the same Arc.
2329    app = app.nest("/__mockforge/time-travel", time_travel_api::time_travel_router());
2330
2331    // Runtime route-chaos rules API + middleware. This sits in front of
2332    // the static per-route handlers so operators can add/remove fault and
2333    // latency rules without redeploying. Static rules from the YAML
2334    // config still apply to their routes; runtime rules are additive.
2335    {
2336        use crate::route_chaos_runtime::{
2337            route_chaos_api_router, runtime_route_chaos_middleware, RuntimeRouteChaosState,
2338        };
2339        let runtime_state = RuntimeRouteChaosState::new(Vec::new());
2340        let middleware_state = runtime_state.clone();
2341        app = app.layer(from_fn_with_state(middleware_state, runtime_route_chaos_middleware));
2342        app = app.nest("/__mockforge/api/route-chaos", route_chaos_api_router(runtime_state));
2343    }
2344
2345    // Runtime network-profile switching. Operators activate a named
2346    // catalog profile (e.g., "mobile_3g") and the middleware applies its
2347    // latency to every subsequent request — useful for "what does my
2348    // consumer look like under bad network" probes against a live
2349    // hosted mock without a redeploy.
2350    {
2351        use crate::network_profile_runtime::{
2352            network_profile_api_router, network_profile_middleware, NetworkProfileRuntimeState,
2353        };
2354        let runtime_state = NetworkProfileRuntimeState::new(
2355            mockforge_core::network_profiles::NetworkProfileCatalog::new(),
2356        );
2357        let middleware_state = runtime_state.clone();
2358        app = app.layer(from_fn_with_state(middleware_state, network_profile_middleware));
2359        app = app
2360            .nest("/__mockforge/api/network-profiles", network_profile_api_router(runtime_state));
2361    }
2362
2363    // Add OIDC well-known endpoints
2364    use crate::auth::oidc::oidc_router;
2365    app = app.merge(oidc_router());
2366
2367    // Add access review API if enabled
2368    {
2369        use mockforge_core::security::get_global_access_review_service;
2370        if let Some(service) = get_global_access_review_service().await {
2371            use crate::handlers::access_review::{access_review_router, AccessReviewState};
2372            let review_state = AccessReviewState { service };
2373            app = app.nest("/api/v1/security/access-reviews", access_review_router(review_state));
2374            debug!("Access review API mounted at /api/v1/security/access-reviews");
2375        }
2376    }
2377
2378    // Add privileged access API if enabled
2379    {
2380        use mockforge_core::security::get_global_privileged_access_manager;
2381        if let Some(manager) = get_global_privileged_access_manager().await {
2382            use crate::handlers::privileged_access::{
2383                privileged_access_router, PrivilegedAccessState,
2384            };
2385            let privileged_state = PrivilegedAccessState { manager };
2386            app = app.nest(
2387                "/api/v1/security/privileged-access",
2388                privileged_access_router(privileged_state),
2389            );
2390            debug!("Privileged access API mounted at /api/v1/security/privileged-access");
2391        }
2392    }
2393
2394    // Add change management API if enabled
2395    {
2396        use mockforge_core::security::get_global_change_management_engine;
2397        if let Some(engine) = get_global_change_management_engine().await {
2398            use crate::handlers::change_management::{
2399                change_management_router, ChangeManagementState,
2400            };
2401            let change_state = ChangeManagementState { engine };
2402            app = app.nest("/api/v1/change-management", change_management_router(change_state));
2403            debug!("Change management API mounted at /api/v1/change-management");
2404        }
2405    }
2406
2407    // Add risk assessment API if enabled
2408    {
2409        use mockforge_core::security::get_global_risk_assessment_engine;
2410        if let Some(engine) = get_global_risk_assessment_engine().await {
2411            use crate::handlers::risk_assessment::{risk_assessment_router, RiskAssessmentState};
2412            let risk_state = RiskAssessmentState { engine };
2413            app = app.nest("/api/v1/security", risk_assessment_router(risk_state));
2414            debug!("Risk assessment API mounted at /api/v1/security/risks");
2415        }
2416    }
2417
2418    // Add token lifecycle API
2419    {
2420        use crate::auth::token_lifecycle::TokenLifecycleManager;
2421        use crate::handlers::token_lifecycle::{token_lifecycle_router, TokenLifecycleState};
2422        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2423        let lifecycle_state = TokenLifecycleState {
2424            manager: lifecycle_manager,
2425        };
2426        app = app.nest("/api/v1/auth", token_lifecycle_router(lifecycle_state));
2427        debug!("Token lifecycle API mounted at /api/v1/auth");
2428    }
2429
2430    // Add OAuth2 server endpoints
2431    {
2432        use crate::auth::oidc::load_oidc_state;
2433        use crate::auth::token_lifecycle::TokenLifecycleManager;
2434        use crate::handlers::oauth2_server::{oauth2_server_router, OAuth2ServerState};
2435        // Load OIDC state from configuration (environment variables or config file)
2436        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
2437        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2438        let oauth2_state = OAuth2ServerState {
2439            oidc_state,
2440            lifecycle_manager,
2441            auth_codes: Arc::new(RwLock::new(HashMap::new())),
2442            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
2443        };
2444        app = app.merge(oauth2_server_router(oauth2_state));
2445        debug!("OAuth2 server endpoints mounted at /oauth2/authorize and /oauth2/token");
2446    }
2447
2448    // Add consent screen endpoints
2449    {
2450        use crate::auth::oidc::load_oidc_state;
2451        use crate::auth::risk_engine::RiskEngine;
2452        use crate::auth::token_lifecycle::TokenLifecycleManager;
2453        use crate::handlers::consent::{consent_router, ConsentState};
2454        use crate::handlers::oauth2_server::OAuth2ServerState;
2455        // Load OIDC state from configuration (environment variables or config file)
2456        let oidc_state = Arc::new(RwLock::new(load_oidc_state()));
2457        let lifecycle_manager = Arc::new(TokenLifecycleManager::default());
2458        let oauth2_state = OAuth2ServerState {
2459            oidc_state: oidc_state.clone(),
2460            lifecycle_manager: lifecycle_manager.clone(),
2461            auth_codes: Arc::new(RwLock::new(HashMap::new())),
2462            refresh_tokens: Arc::new(RwLock::new(HashMap::new())),
2463        };
2464        let risk_engine = Arc::new(RiskEngine::default());
2465        let consent_state = ConsentState {
2466            oauth2_state,
2467            risk_engine,
2468        };
2469        app = app.merge(consent_router(consent_state));
2470        debug!("Consent screen endpoints mounted at /consent");
2471    }
2472
2473    // Add risk simulation API
2474    {
2475        use crate::auth::risk_engine::RiskEngine;
2476        use crate::handlers::risk_simulation::{risk_simulation_router, RiskSimulationState};
2477        let risk_engine = Arc::new(RiskEngine::default());
2478        let risk_state = RiskSimulationState { risk_engine };
2479        app = app.nest("/api/v1/auth", risk_simulation_router(risk_state));
2480        debug!("Risk simulation API mounted at /api/v1/auth/risk");
2481    }
2482
2483    // Initialize database connection (optional)
2484    #[cfg(feature = "database")]
2485    let database = {
2486        use crate::database::Database;
2487        let database_url = std::env::var("DATABASE_URL").ok();
2488        match Database::connect_optional(database_url.as_deref()).await {
2489            Ok(db) => {
2490                if db.is_connected() {
2491                    // Run migrations if database is connected
2492                    if let Err(e) = db.migrate_if_connected().await {
2493                        warn!("Failed to run database migrations: {}", e);
2494                    } else {
2495                        info!("Database connected and migrations applied");
2496                    }
2497                }
2498                Some(db)
2499            }
2500            Err(e) => {
2501                warn!("Failed to connect to database: {}. Continuing without database support.", e);
2502                None
2503            }
2504        }
2505    };
2506
2507    // Add drift budget and incident management endpoints
2508    // Initialize shared components for drift tracking and protocol contracts
2509    let (drift_engine, incident_manager, drift_config) = {
2510        use mockforge_core::contract_drift::{DriftBudgetConfig, DriftBudgetEngine};
2511        use mockforge_core::incidents::{IncidentManager, IncidentStore};
2512        use std::sync::Arc;
2513
2514        // Initialize drift budget engine with default config
2515        let drift_config = DriftBudgetConfig::default();
2516        let drift_engine = Arc::new(DriftBudgetEngine::new(drift_config.clone()));
2517
2518        // Initialize incident store and manager
2519        let incident_store = Arc::new(IncidentStore::default());
2520        let incident_manager = Arc::new(IncidentManager::new(incident_store.clone()));
2521
2522        (drift_engine, incident_manager, drift_config)
2523    };
2524
2525    {
2526        use crate::handlers::drift_budget::{drift_budget_router, DriftBudgetState};
2527        use crate::middleware::drift_tracking::DriftTrackingState;
2528        use mockforge_contracts::consumer_contracts::{
2529            ConsumerBreakingChangeDetector, UsageRecorder,
2530        };
2531        use mockforge_core::ai_contract_diff::ContractDiffAnalyzer;
2532        use std::sync::Arc;
2533
2534        // Initialize usage recorder and consumer detector
2535        let usage_recorder = Arc::new(UsageRecorder::default());
2536        let consumer_detector =
2537            Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2538
2539        // Initialize contract diff analyzer if enabled
2540        let diff_analyzer = if drift_config.enabled {
2541            match ContractDiffAnalyzer::new(
2542                mockforge_core::ai_contract_diff::ContractDiffConfig::default(),
2543            ) {
2544                Ok(analyzer) => Some(Arc::new(analyzer)),
2545                Err(e) => {
2546                    warn!("Failed to create contract diff analyzer: {}", e);
2547                    None
2548                }
2549            }
2550        } else {
2551            None
2552        };
2553
2554        // Get OpenAPI spec if available
2555        // Note: Load from spec_path if available, or leave as None for manual configuration.
2556        let spec = if let Some(ref spec_path) = spec_path {
2557            match OpenApiSpec::from_file(spec_path).await {
2558                Ok(s) => Some(Arc::new(s)),
2559                Err(e) => {
2560                    debug!("Failed to load OpenAPI spec for drift tracking: {}", e);
2561                    None
2562                }
2563            }
2564        } else {
2565            None
2566        };
2567
2568        // Create drift tracking state
2569        let drift_tracking_state = DriftTrackingState {
2570            diff_analyzer,
2571            spec,
2572            drift_engine: drift_engine.clone(),
2573            incident_manager: incident_manager.clone(),
2574            usage_recorder,
2575            consumer_detector,
2576            enabled: drift_config.enabled,
2577        };
2578
2579        // Add response body buffering middleware (before drift tracking)
2580        app = app.layer(axum::middleware::from_fn(middleware::buffer_response_middleware));
2581
2582        // Add drift tracking middleware (after response buffering)
2583        // Use a wrapper that inserts state into extensions before calling the middleware
2584        let drift_tracking_state_clone = drift_tracking_state.clone();
2585        app = app.layer(axum::middleware::from_fn(
2586            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2587                let state = drift_tracking_state_clone.clone();
2588                async move {
2589                    // Insert state into extensions if not already present
2590                    if req.extensions().get::<DriftTrackingState>().is_none() {
2591                        req.extensions_mut().insert(state);
2592                    }
2593                    // Call the middleware function
2594                    middleware::drift_tracking::drift_tracking_middleware_with_extensions(req, next)
2595                        .await
2596                }
2597            },
2598        ));
2599
2600        let drift_state = DriftBudgetState {
2601            engine: drift_engine.clone(),
2602            incident_manager: incident_manager.clone(),
2603            gitops_handler: None, // Can be initialized later if GitOps is configured
2604        };
2605
2606        app = app.merge(drift_budget_router(drift_state));
2607        debug!("Drift budget and incident management endpoints mounted at /api/v1/drift");
2608    }
2609
2610    // Add pipeline management endpoints (MockOps)
2611    #[cfg(feature = "pipelines")]
2612    {
2613        use crate::handlers::pipelines::{pipeline_router, PipelineState};
2614
2615        let pipeline_state = PipelineState::new();
2616        app = app.merge(pipeline_router(pipeline_state));
2617        debug!("Pipeline management endpoints mounted at /api/v1/pipelines");
2618    }
2619
2620    // Add governance endpoints (forecasting, semantic drift, threat modeling, contract health)
2621    {
2622        use crate::handlers::contract_health::{contract_health_router, ContractHealthState};
2623        use mockforge_contracts::contract_drift::forecasting::{Forecaster, ForecastingConfig};
2624        use mockforge_core::contract_drift::threat_modeling::ThreatAnalyzer;
2625        use mockforge_core::incidents::semantic_manager::SemanticIncidentManager;
2626        use mockforge_foundation::threat_modeling_types::ThreatModelingConfig;
2627        use mockforge_intelligence::handlers::forecasting::{forecasting_router, ForecastingState};
2628        use mockforge_intelligence::handlers::semantic_drift::{
2629            semantic_drift_router, SemanticDriftState,
2630        };
2631        use mockforge_intelligence::handlers::threat_modeling::{
2632            threat_modeling_router, ThreatModelingState,
2633        };
2634        use std::sync::Arc;
2635
2636        // Initialize forecasting
2637        let forecasting_config = ForecastingConfig::default();
2638        let forecaster = Arc::new(Forecaster::new(forecasting_config));
2639        let forecasting_state = ForecastingState {
2640            forecaster,
2641            #[cfg(feature = "database")]
2642            database: database.clone(),
2643        };
2644
2645        // Initialize semantic drift manager
2646        let semantic_manager = Arc::new(SemanticIncidentManager::new());
2647        let semantic_state = SemanticDriftState {
2648            manager: semantic_manager,
2649            #[cfg(feature = "database")]
2650            database: database.clone(),
2651        };
2652
2653        // Initialize threat analyzer
2654        let threat_config = ThreatModelingConfig::default();
2655        let threat_analyzer = match ThreatAnalyzer::new(threat_config) {
2656            Ok(analyzer) => Arc::new(analyzer),
2657            Err(e) => {
2658                warn!("Failed to create threat analyzer: {}. Using default.", e);
2659                Arc::new(ThreatAnalyzer::new(ThreatModelingConfig::default()).unwrap_or_else(
2660                    |_| {
2661                        // Fallback to a minimal config if default also fails
2662                        ThreatAnalyzer::new(ThreatModelingConfig {
2663                            enabled: false,
2664                            ..Default::default()
2665                        })
2666                        .expect("Failed to create fallback threat analyzer")
2667                    },
2668                ))
2669            }
2670        };
2671        // Load webhook configs from ServerConfig
2672        let mut webhook_configs = Vec::new();
2673        let config_paths = [
2674            "config.yaml",
2675            "mockforge.yaml",
2676            "tools/mockforge/config.yaml",
2677            "../tools/mockforge/config.yaml",
2678        ];
2679
2680        for path in &config_paths {
2681            if let Ok(config) = mockforge_core::config::load_config(path).await {
2682                if !config.incidents.webhooks.is_empty() {
2683                    webhook_configs = config.incidents.webhooks.clone();
2684                    info!("Loaded {} webhook configs from config: {}", webhook_configs.len(), path);
2685                    break;
2686                }
2687            }
2688        }
2689
2690        if webhook_configs.is_empty() {
2691            debug!("No webhook configs found in config files, using empty list");
2692        }
2693
2694        let threat_state = ThreatModelingState {
2695            analyzer: threat_analyzer,
2696            webhook_configs,
2697            #[cfg(feature = "database")]
2698            database: database.clone(),
2699        };
2700
2701        // Initialize contract health state
2702        let contract_health_state = ContractHealthState {
2703            incident_manager: incident_manager.clone(),
2704            semantic_manager: Arc::new(SemanticIncidentManager::new()),
2705            #[cfg(feature = "database")]
2706            database: database.clone(),
2707        };
2708
2709        // Register routers
2710        app = app.merge(forecasting_router(forecasting_state));
2711        debug!("Forecasting endpoints mounted at /api/v1/forecasts");
2712
2713        app = app.merge(semantic_drift_router(semantic_state));
2714        debug!("Semantic drift endpoints mounted at /api/v1/semantic-drift");
2715
2716        app = app.merge(threat_modeling_router(threat_state));
2717        debug!("Threat modeling endpoints mounted at /api/v1/threats");
2718
2719        app = app.merge(contract_health_router(contract_health_state));
2720        debug!("Contract health endpoints mounted at /api/v1/contract-health");
2721    }
2722
2723    // Add protocol contracts endpoints with fitness registry initialization
2724    {
2725        use crate::handlers::protocol_contracts::{
2726            protocol_contracts_router, ProtocolContractState,
2727        };
2728        use mockforge_core::contract_drift::{
2729            ConsumerImpactAnalyzer, FitnessFunctionRegistry, ProtocolContractRegistry,
2730        };
2731        use std::sync::Arc;
2732        use tokio::sync::RwLock;
2733
2734        // Initialize protocol contract registry
2735        let contract_registry = Arc::new(RwLock::new(ProtocolContractRegistry::new()));
2736
2737        // Initialize fitness function registry and load from config
2738        let mut fitness_registry = FitnessFunctionRegistry::new();
2739
2740        // Try to load config and populate fitness rules
2741        let config_paths = [
2742            "config.yaml",
2743            "mockforge.yaml",
2744            "tools/mockforge/config.yaml",
2745            "../tools/mockforge/config.yaml",
2746        ];
2747
2748        let mut config_loaded = false;
2749        for path in &config_paths {
2750            if let Ok(config) = mockforge_core::config::load_config(path).await {
2751                if !config.contracts.fitness_rules.is_empty() {
2752                    if let Err(e) =
2753                        fitness_registry.load_from_config(&config.contracts.fitness_rules)
2754                    {
2755                        warn!("Failed to load fitness rules from config {}: {}", path, e);
2756                    } else {
2757                        info!(
2758                            "Loaded {} fitness rules from config: {}",
2759                            config.contracts.fitness_rules.len(),
2760                            path
2761                        );
2762                        config_loaded = true;
2763                        break;
2764                    }
2765                }
2766            }
2767        }
2768
2769        if !config_loaded {
2770            debug!("No fitness rules found in config files, using empty registry");
2771        }
2772
2773        let fitness_registry = Arc::new(RwLock::new(fitness_registry));
2774
2775        // Reuse drift engine and incident manager from drift budget section
2776
2777        // Initialize consumer impact analyzer
2778        let consumer_mapping_registry =
2779            mockforge_core::contract_drift::ConsumerMappingRegistry::new();
2780        let consumer_analyzer =
2781            Arc::new(RwLock::new(ConsumerImpactAnalyzer::new(consumer_mapping_registry)));
2782
2783        let protocol_state = ProtocolContractState {
2784            registry: contract_registry,
2785            drift_engine: Some(drift_engine.clone()),
2786            incident_manager: Some(incident_manager.clone()),
2787            fitness_registry: Some(fitness_registry),
2788            consumer_analyzer: Some(consumer_analyzer),
2789        };
2790
2791        app = app.nest("/api/v1/contracts", protocol_contracts_router(protocol_state));
2792        debug!("Protocol contracts endpoints mounted at /api/v1/contracts");
2793    }
2794
2795    // Add behavioral cloning middleware (optional - applies learned behavior to requests)
2796    #[cfg(feature = "behavioral-cloning")]
2797    {
2798        use crate::middleware::behavioral_cloning::BehavioralCloningMiddlewareState;
2799        use std::path::PathBuf;
2800
2801        // Determine database path (defaults to ./recordings.db)
2802        let db_path = std::env::var("RECORDER_DATABASE_PATH")
2803            .ok()
2804            .map(PathBuf::from)
2805            .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2806
2807        let bc_middleware_state = if let Some(path) = db_path {
2808            BehavioralCloningMiddlewareState::with_database_path(path)
2809        } else {
2810            BehavioralCloningMiddlewareState::new()
2811        };
2812
2813        // Only enable if BEHAVIORAL_CLONING_ENABLED is set to true
2814        let enabled = std::env::var("BEHAVIORAL_CLONING_ENABLED")
2815            .ok()
2816            .and_then(|v| v.parse::<bool>().ok())
2817            .unwrap_or(false);
2818
2819        if enabled {
2820            let bc_state_clone = bc_middleware_state.clone();
2821            app = app.layer(axum::middleware::from_fn(
2822                move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2823                    let state = bc_state_clone.clone();
2824                    async move {
2825                        // Insert state into extensions if not already present
2826                        if req.extensions().get::<BehavioralCloningMiddlewareState>().is_none() {
2827                            req.extensions_mut().insert(state);
2828                        }
2829                        // Call the middleware function
2830                        middleware::behavioral_cloning::behavioral_cloning_middleware(req, next)
2831                            .await
2832                    }
2833                },
2834            ));
2835            debug!("Behavioral cloning middleware enabled (applies learned behavior to requests)");
2836        }
2837    }
2838
2839    // Add consumer contracts endpoints
2840    {
2841        use crate::handlers::consumer_contracts::{
2842            consumer_contracts_router, ConsumerContractsState,
2843        };
2844        use mockforge_contracts::consumer_contracts::{
2845            ConsumerBreakingChangeDetector, ConsumerRegistry, UsageRecorder,
2846        };
2847        use std::sync::Arc;
2848
2849        // Initialize consumer registry
2850        let registry = Arc::new(ConsumerRegistry::default());
2851
2852        // Initialize usage recorder
2853        let usage_recorder = Arc::new(UsageRecorder::default());
2854
2855        // Initialize breaking change detector
2856        let detector = Arc::new(ConsumerBreakingChangeDetector::new(usage_recorder.clone()));
2857
2858        let consumer_state = ConsumerContractsState {
2859            registry,
2860            usage_recorder,
2861            detector,
2862            violations: Arc::new(RwLock::new(HashMap::new())),
2863        };
2864
2865        app = app.merge(consumer_contracts_router(consumer_state));
2866        debug!("Consumer contracts endpoints mounted at /api/v1/consumers");
2867    }
2868
2869    // Add behavioral cloning endpoints
2870    #[cfg(feature = "behavioral-cloning")]
2871    {
2872        use crate::handlers::behavioral_cloning::{
2873            behavioral_cloning_router, BehavioralCloningState,
2874        };
2875        use std::path::PathBuf;
2876
2877        // Determine database path (defaults to ./recordings.db)
2878        let db_path = std::env::var("RECORDER_DATABASE_PATH")
2879            .ok()
2880            .map(PathBuf::from)
2881            .or_else(|| std::env::current_dir().ok().map(|p| p.join("recordings.db")));
2882
2883        let bc_state = if let Some(path) = db_path {
2884            BehavioralCloningState::with_database_path(path)
2885        } else {
2886            BehavioralCloningState::new()
2887        };
2888
2889        app = app.merge(behavioral_cloning_router(bc_state));
2890        debug!("Behavioral cloning endpoints mounted at /api/v1/behavioral-cloning");
2891    }
2892
2893    // Add consistency engine and cross-protocol state management
2894    {
2895        use crate::consistency::{ConsistencyMiddlewareState, HttpAdapter};
2896        use mockforge_intelligence::consistency::ConsistencyEngine;
2897        use mockforge_intelligence::handlers::consistency::{consistency_router, ConsistencyState};
2898        use std::sync::Arc;
2899
2900        // Initialize consistency engine
2901        let consistency_engine = Arc::new(ConsistencyEngine::new());
2902
2903        // Create and register HTTP adapter
2904        let http_adapter = Arc::new(HttpAdapter::new(consistency_engine.clone()));
2905        consistency_engine.register_adapter(http_adapter.clone()).await;
2906
2907        // Create consistency state for handlers
2908        let consistency_state = ConsistencyState {
2909            engine: consistency_engine.clone(),
2910        };
2911
2912        // Create X-Ray state first (needed for middleware)
2913        use mockforge_intelligence::handlers::xray::XRayState;
2914        let xray_state = Arc::new(XRayState::new(consistency_engine.clone()));
2915
2916        // Create consistency middleware state
2917        let consistency_middleware_state = ConsistencyMiddlewareState {
2918            engine: consistency_engine.clone(),
2919            adapter: http_adapter,
2920            xray_state: Some(xray_state.clone()),
2921        };
2922
2923        // Reality-driven mock/proxy middleware (#222). Must be added
2924        // BEFORE the consistency layer so it ends up inner — that way
2925        // each request hits consistency first (which injects UnifiedState
2926        // including reality_continuum_ratio), then this middleware reads
2927        // that state and either forwards to upstream or falls through to
2928        // the mock chain. Activated only when MOCKFORGE_PROXY_UPSTREAM is
2929        // set; absent that, the layer isn't even installed.
2930        if let Some(reality_cfg) = reality_proxy::RealityProxyConfig::from_env() {
2931            tracing::info!(
2932                upstream = %reality_cfg.upstream_base,
2933                "Reality-driven proxy middleware enabled — requests will be split between mock and upstream based on reality_continuum_ratio"
2934            );
2935            app = app.layer(axum::middleware::from_fn(
2936                move |req: axum::extract::Request, next: axum::middleware::Next| {
2937                    let cfg = reality_cfg.clone();
2938                    async move { reality_proxy::reality_proxy_middleware(cfg, req, next).await }
2939                },
2940            ));
2941        }
2942
2943        // Add consistency middleware (before other middleware to inject state early)
2944        let consistency_middleware_state_clone = consistency_middleware_state.clone();
2945        app = app.layer(axum::middleware::from_fn(
2946            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
2947                let state = consistency_middleware_state_clone.clone();
2948                async move {
2949                    // Insert state into extensions if not already present
2950                    if req.extensions().get::<ConsistencyMiddlewareState>().is_none() {
2951                        req.extensions_mut().insert(state);
2952                    }
2953                    // Call the middleware function
2954                    consistency::middleware::consistency_middleware(req, next).await
2955                }
2956            },
2957        ));
2958
2959        // Add consistency API endpoints
2960        app = app.merge(consistency_router(consistency_state));
2961        debug!("Consistency engine initialized and endpoints mounted at /api/v1/consistency");
2962
2963        // Runtime named-scenario activation API. Locally-installed
2964        // scenarios (from `~/.mockforge/scenario-metadata/*.json`) become
2965        // listable + activatable via HTTP; activation writes through to
2966        // the consistency engine's active_scenario slot for the chosen
2967        // workspace. Failure to load the scenario index is non-fatal —
2968        // the API just shows an empty list, which matches the natural
2969        // state of a fresh deployment with no scenarios installed yet.
2970        #[cfg(feature = "scenario-engine")]
2971        {
2972            use crate::scenarios_runtime::{scenarios_api_router, ScenarioRuntimeState};
2973            let mut scenario_storage = match mockforge_scenarios::ScenarioStorage::new() {
2974                Ok(s) => s,
2975                Err(e) => {
2976                    tracing::warn!(
2977                        error = %e,
2978                        "Failed to init scenario storage; runtime scenarios API will list empty"
2979                    );
2980                    // Construct an isolated tempdir-backed storage so the
2981                    // API still mounts but lists nothing.
2982                    let tmp = std::env::temp_dir().join("mockforge-empty-scenarios");
2983                    mockforge_scenarios::ScenarioStorage::with_dir(&tmp)
2984                        .expect("temp scenario storage")
2985                }
2986            };
2987            if let Err(e) = scenario_storage.load().await {
2988                tracing::warn!(
2989                    error = %e,
2990                    "Failed to load installed scenarios; API will list empty until scenarios are installed"
2991                );
2992            }
2993            let scenarios_state =
2994                ScenarioRuntimeState::new(scenario_storage, consistency_engine.clone());
2995            app = app.nest("/__mockforge/api/scenarios", scenarios_api_router(scenarios_state));
2996            debug!("Scenario runtime API mounted at /__mockforge/api/scenarios");
2997        }
2998
2999        // Add fidelity score endpoints
3000        {
3001            use mockforge_intelligence::handlers::fidelity::{fidelity_router, FidelityState};
3002            let fidelity_state = FidelityState::new();
3003            app = app.merge(fidelity_router(fidelity_state));
3004            debug!("Fidelity score endpoints mounted at /api/v1/workspace/:workspace_id/fidelity");
3005        }
3006
3007        // Add scenario studio endpoints
3008        {
3009            use mockforge_intelligence::handlers::scenario_studio::{
3010                scenario_studio_router, ScenarioStudioState,
3011            };
3012            let scenario_studio_state = ScenarioStudioState::new();
3013            app = app.merge(scenario_studio_router(scenario_studio_state));
3014            debug!("Scenario Studio endpoints mounted at /api/v1/scenario-studio");
3015        }
3016
3017        // Add performance mode endpoints
3018        {
3019            use crate::handlers::performance::{performance_router, PerformanceState};
3020            let performance_state = PerformanceState::new();
3021            app = app.nest("/api/performance", performance_router(performance_state));
3022            debug!("Performance mode endpoints mounted at /api/performance");
3023        }
3024
3025        // Add world state endpoints
3026        {
3027            use crate::handlers::world_state::{world_state_router, WorldStateState};
3028            use mockforge_world_state::WorldStateEngine;
3029            use std::sync::Arc;
3030            use tokio::sync::RwLock;
3031
3032            let world_state_engine = Arc::new(RwLock::new(WorldStateEngine::new()));
3033            let world_state_state = WorldStateState {
3034                engine: world_state_engine,
3035            };
3036            app = app.nest("/api/world-state", world_state_router().with_state(world_state_state));
3037            debug!("World state endpoints mounted at /api/world-state");
3038        }
3039
3040        // Add snapshot management endpoints
3041        {
3042            use crate::handlers::snapshots::{snapshot_router, SnapshotState};
3043            use mockforge_core::snapshots::SnapshotManager;
3044            use std::path::PathBuf;
3045
3046            let snapshot_dir = std::env::var("MOCKFORGE_SNAPSHOT_DIR").ok().map(PathBuf::from);
3047            let snapshot_manager = Arc::new(SnapshotManager::new(snapshot_dir));
3048
3049            let snapshot_state = SnapshotState {
3050                manager: snapshot_manager,
3051                consistency_engine: Some(consistency_engine.clone()),
3052                workspace_persistence: None, // Can be initialized later if workspace persistence is available
3053                vbr_engine: None, // Can be initialized when VBR engine is available in server state
3054                recorder: None,   // Can be initialized when Recorder is available in server state
3055            };
3056
3057            app = app.merge(snapshot_router(snapshot_state));
3058            debug!("Snapshot management endpoints mounted at /api/v1/snapshots");
3059
3060            // Add X-Ray API endpoints for browser extension
3061            {
3062                use mockforge_intelligence::handlers::xray::xray_router;
3063                app = app.merge(xray_router((*xray_state).clone()));
3064                debug!("X-Ray API endpoints mounted at /api/v1/xray");
3065            }
3066        }
3067
3068        // Add A/B testing endpoints and middleware
3069        {
3070            use crate::handlers::ab_testing::{ab_testing_router, ABTestingState};
3071            use crate::middleware::ab_testing::ab_testing_middleware;
3072
3073            let ab_testing_state = ABTestingState::new();
3074
3075            // Add A/B testing middleware (before other response middleware)
3076            let ab_testing_state_clone = ab_testing_state.clone();
3077            app = app.layer(axum::middleware::from_fn(
3078                move |mut req: axum::extract::Request, next: axum::middleware::Next| {
3079                    let state = ab_testing_state_clone.clone();
3080                    async move {
3081                        // Insert state into extensions if not already present
3082                        if req.extensions().get::<ABTestingState>().is_none() {
3083                            req.extensions_mut().insert(state);
3084                        }
3085                        // Call the middleware function
3086                        ab_testing_middleware(req, next).await
3087                    }
3088                },
3089            ));
3090
3091            // Add A/B testing API endpoints
3092            app = app.merge(ab_testing_router(ab_testing_state));
3093            debug!("A/B testing endpoints mounted at /api/v1/ab-tests");
3094        }
3095    }
3096
3097    // Add PR generation endpoints (optional - only if configured)
3098    {
3099        use crate::handlers::pr_generation::{pr_generation_router, PRGenerationState};
3100        use mockforge_intelligence::pr_generation::{PRGenerator, PRProvider};
3101        use std::sync::Arc;
3102
3103        // Load PR generation config from environment or use default
3104        let pr_config = mockforge_intelligence::pr_generation::PRGenerationConfig::from_env();
3105
3106        // Arc-wrapped generator only when enabled AND a token is configured;
3107        // token presence is checked here rather than unwrapped below.
3108        let generator = pr_config.token.clone().filter(|_| pr_config.enabled).map(|token| {
3109            let generator = match pr_config.provider {
3110                PRProvider::GitHub => PRGenerator::new_github(
3111                    pr_config.owner.clone(),
3112                    pr_config.repo.clone(),
3113                    token,
3114                    pr_config.base_branch.clone(),
3115                ),
3116                PRProvider::GitLab => PRGenerator::new_gitlab(
3117                    pr_config.owner.clone(),
3118                    pr_config.repo.clone(),
3119                    token,
3120                    pr_config.base_branch.clone(),
3121                ),
3122            };
3123            Arc::new(generator)
3124        });
3125
3126        let pr_state = PRGenerationState {
3127            generator: generator.clone(),
3128        };
3129
3130        app = app.merge(pr_generation_router(pr_state));
3131        if generator.is_some() {
3132            debug!(
3133                "PR generation endpoints mounted at /api/v1/pr (configured for {:?})",
3134                pr_config.provider
3135            );
3136        } else {
3137            debug!("PR generation endpoints mounted at /api/v1/pr (not configured - set GITHUB_TOKEN/GITLAB_TOKEN and PR_REPO_OWNER/PR_REPO_NAME)");
3138        }
3139    }
3140
3141    // Add management WebSocket endpoint
3142    app = app.nest("/__mockforge/ws", ws_management_router(ws_state));
3143
3144    // Add workspace routing middleware if multi-tenant is enabled
3145    if let Some(mt_config) = multi_tenant_config {
3146        if mt_config.enabled {
3147            use mockforge_core::{MultiTenantWorkspaceRegistry, WorkspaceRouter};
3148            use std::sync::Arc;
3149
3150            info!(
3151                "Multi-tenant mode enabled with {} routing strategy",
3152                match mt_config.routing_strategy {
3153                    mockforge_foundation::multi_tenant_types::RoutingStrategy::Path => "path-based",
3154                    mockforge_foundation::multi_tenant_types::RoutingStrategy::Port => "port-based",
3155                    mockforge_foundation::multi_tenant_types::RoutingStrategy::Both => "hybrid",
3156                }
3157            );
3158
3159            // Create the multi-tenant workspace registry
3160            let mut registry = MultiTenantWorkspaceRegistry::new(mt_config.clone());
3161
3162            // Register the default workspace before wrapping in Arc
3163            let default_workspace =
3164                mockforge_core::Workspace::new(mt_config.default_workspace.clone());
3165            if let Err(e) =
3166                registry.register_workspace(mt_config.default_workspace.clone(), default_workspace)
3167            {
3168                warn!("Failed to register default workspace: {}", e);
3169            } else {
3170                info!("Registered default workspace: '{}'", mt_config.default_workspace);
3171            }
3172
3173            // Wrap registry in Arc for shared access
3174            let registry = Arc::new(registry);
3175
3176            // Create workspace router
3177            let _workspace_router = WorkspaceRouter::new(registry);
3178            info!("Workspace routing middleware initialized for HTTP server");
3179        }
3180    }
3181
3182    // Apply deceptive deploy configuration if enabled
3183    let mut final_cors_config = cors_config;
3184    let mut production_headers: Option<std::sync::Arc<HashMap<String, String>>> = None;
3185    // Auth config from deceptive deploy OAuth (if configured)
3186    let mut deceptive_deploy_auth_config: Option<mockforge_core::config::AuthConfig> = None;
3187    let mut rate_limit_config = middleware::RateLimitConfig {
3188        requests_per_minute: std::env::var("MOCKFORGE_RATE_LIMIT_RPM")
3189            .ok()
3190            .and_then(|v| v.parse().ok())
3191            .unwrap_or(1000),
3192        burst: std::env::var("MOCKFORGE_RATE_LIMIT_BURST")
3193            .ok()
3194            .and_then(|v| v.parse().ok())
3195            .unwrap_or(2000),
3196        per_ip: true,
3197        per_endpoint: false,
3198    };
3199
3200    if let Some(deploy_config) = &deceptive_deploy_config {
3201        if deploy_config.enabled {
3202            info!("Deceptive deploy mode enabled - applying production-like configuration");
3203
3204            // Override CORS config if provided
3205            if let Some(prod_cors) = &deploy_config.cors {
3206                final_cors_config = Some(mockforge_core::config::HttpCorsConfig {
3207                    enabled: true,
3208                    allowed_origins: prod_cors.allowed_origins.clone(),
3209                    allowed_methods: prod_cors.allowed_methods.clone(),
3210                    allowed_headers: prod_cors.allowed_headers.clone(),
3211                    allow_credentials: prod_cors.allow_credentials,
3212                });
3213                info!("Applied production-like CORS configuration");
3214            }
3215
3216            // Override rate limit config if provided
3217            if let Some(prod_rate_limit) = &deploy_config.rate_limit {
3218                rate_limit_config = middleware::RateLimitConfig {
3219                    requests_per_minute: prod_rate_limit.requests_per_minute,
3220                    burst: prod_rate_limit.burst,
3221                    per_ip: prod_rate_limit.per_ip,
3222                    per_endpoint: false,
3223                };
3224                info!(
3225                    "Applied production-like rate limiting: {} req/min, burst: {}",
3226                    prod_rate_limit.requests_per_minute, prod_rate_limit.burst
3227                );
3228            }
3229
3230            // Set production headers
3231            if !deploy_config.headers.is_empty() {
3232                let headers_map: HashMap<String, String> = deploy_config.headers.clone();
3233                production_headers = Some(std::sync::Arc::new(headers_map));
3234                info!("Configured {} production headers", deploy_config.headers.len());
3235            }
3236
3237            // Integrate OAuth config from deceptive deploy
3238            if let Some(prod_oauth) = &deploy_config.oauth {
3239                let oauth2_config: mockforge_core::config::OAuth2Config = prod_oauth.clone().into();
3240                deceptive_deploy_auth_config = Some(mockforge_core::config::AuthConfig {
3241                    oauth2: Some(oauth2_config),
3242                    ..Default::default()
3243                });
3244                info!("Applied production-like OAuth configuration for deceptive deploy");
3245            }
3246        }
3247    }
3248
3249    // Initialize rate limiter and state
3250    let rate_limit_disabled = middleware::is_rate_limit_disabled();
3251    let rate_limiter =
3252        std::sync::Arc::new(middleware::GlobalRateLimiter::new(rate_limit_config.clone()));
3253
3254    let mut state = HttpServerState::new();
3255    if rate_limit_disabled {
3256        info!(
3257            "HTTP rate limiting disabled (MOCKFORGE_RATE_LIMIT_ENABLED=false or --no-rate-limit)"
3258        );
3259    } else {
3260        state = state.with_rate_limiter(rate_limiter.clone());
3261    }
3262
3263    // Add production headers to state if configured
3264    if let Some(headers) = production_headers.clone() {
3265        state = state.with_production_headers(headers);
3266    }
3267
3268    // Add rate limiting middleware (no-op when state.rate_limiter is None)
3269    app = app.layer(from_fn_with_state(state.clone(), middleware::rate_limit_middleware));
3270
3271    // Add production headers middleware if configured
3272    if state.production_headers.is_some() {
3273        app =
3274            app.layer(from_fn_with_state(state.clone(), middleware::production_headers_middleware));
3275    }
3276
3277    // Optionally advertise `Connection: keep-alive` + `Keep-Alive: timeout=N,
3278    // max=M` on every response (Issue #79 workaround for HTTP/1.0 upstream
3279    // proxies that observe FIN from MockForge after each response). Opt in
3280    // via `MOCKFORGE_HTTP_KEEPALIVE_HINT=1`.
3281    if middleware::is_keepalive_hint_enabled() {
3282        info!(
3283            "MOCKFORGE_HTTP_KEEPALIVE_HINT enabled — emitting Connection: keep-alive + Keep-Alive headers on all responses (Issue #79 workaround)"
3284        );
3285        app = app.layer(axum::middleware::from_fn(middleware::keepalive_hint_middleware));
3286    }
3287
3288    // Issue #79 (round 5): per-request log line with HTTP version + Connection
3289    // header MockForge actually sees, so users debugging proxy ↔ MockForge
3290    // negotiation can confirm whether their proxy is speaking HTTP/1.1 with
3291    // keep-alive or HTTP/1.0 (which forces hyper to FIN after each response).
3292    if middleware::is_conn_log_enabled() {
3293        info!(
3294            "MOCKFORGE_HTTP_LOG_CONN enabled — logging HTTP version + Connection headers per request (Issue #79 diagnostic)"
3295        );
3296        app = app.layer(axum::middleware::from_fn(middleware::conn_diag_middleware));
3297    }
3298
3299    // Add authentication middleware if OAuth is configured via deceptive deploy
3300    if let Some(auth_config) = deceptive_deploy_auth_config {
3301        use crate::auth::{auth_middleware, create_oauth2_client, AuthState};
3302        use std::collections::HashMap;
3303        use std::sync::Arc;
3304        use tokio::sync::RwLock;
3305
3306        // Create OAuth2 client if configured
3307        let oauth2_client = if let Some(oauth2_config) = &auth_config.oauth2 {
3308            match create_oauth2_client(oauth2_config) {
3309                Ok(client) => Some(client),
3310                Err(e) => {
3311                    warn!("Failed to create OAuth2 client from deceptive deploy config: {}", e);
3312                    None
3313                }
3314            }
3315        } else {
3316            None
3317        };
3318
3319        // Create auth state
3320        let auth_state = AuthState {
3321            config: auth_config,
3322            spec: None, // OpenAPI spec not available in this context
3323            oauth2_client,
3324            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
3325        };
3326
3327        // Apply auth middleware
3328        app = app.layer(from_fn_with_state(auth_state, auth_middleware));
3329        info!("Applied OAuth authentication middleware from deceptive deploy configuration");
3330    }
3331
3332    // Add runtime daemon 404 detection middleware (if enabled)
3333    #[cfg(feature = "runtime-daemon")]
3334    {
3335        use mockforge_runtime_daemon::{AutoGenerator, NotFoundDetector, RuntimeDaemonConfig};
3336        use std::sync::Arc;
3337
3338        // Load runtime daemon config from environment
3339        let daemon_config = RuntimeDaemonConfig::from_env();
3340
3341        if daemon_config.enabled {
3342            info!("Runtime daemon enabled - auto-creating mocks from 404s");
3343
3344            // Determine management API URL (default to localhost:3000)
3345            let management_api_url =
3346                std::env::var("MOCKFORGE_MANAGEMENT_API_URL").unwrap_or_else(|_| {
3347                    let port =
3348                        std::env::var("MOCKFORGE_HTTP_PORT").unwrap_or_else(|_| "3000".to_string());
3349                    format!("http://localhost:{}", port)
3350                });
3351
3352            // Create auto-generator
3353            let generator = Arc::new(AutoGenerator::new(daemon_config.clone(), management_api_url));
3354
3355            // Create detector and set generator
3356            let detector = NotFoundDetector::new(daemon_config.clone());
3357            detector.set_generator(generator).await;
3358
3359            // Add middleware layer
3360            let detector_clone = detector.clone();
3361            app = app.layer(axum::middleware::from_fn(
3362                move |req: axum::extract::Request, next: axum::middleware::Next| {
3363                    let detector = detector_clone.clone();
3364                    async move { detector.detect_and_auto_create(req, next).await }
3365                },
3366            ));
3367
3368            debug!("Runtime daemon 404 detection middleware added");
3369        }
3370    }
3371
3372    // Add /__mockforge/routes endpoint so the admin UI can discover registered routes
3373    {
3374        let routes_state = HttpServerState::with_routes(captured_routes);
3375        let routes_router = Router::new()
3376            .route("/__mockforge/routes", axum::routing::get(get_routes_handler))
3377            .with_state(routes_state);
3378        app = app.merge(routes_router);
3379    }
3380
3381    // Add API docs page (Scalar-powered interactive explorer)
3382    app = app.route("/__mockforge/docs", axum::routing::get(get_docs_handler));
3383
3384    // Note: OData URI rewrite is applied at the service level in serve_router_with_tls()
3385    // because Router::layer() only applies to matched routes, not unmatched ones.
3386
3387    // Add request logging middleware to capture all requests for the admin dashboard
3388    app = app.layer(axum::middleware::from_fn(request_logging::log_http_requests));
3389
3390    // Add contract diff middleware for automatic request capture
3391    // This captures requests for contract diff analysis
3392    app = app.layer(axum::middleware::from_fn(contract_diff_middleware::capture_for_contract_diff));
3393
3394    // Add CORS middleware (use final_cors_config which may be overridden by deceptive deploy)
3395    app = apply_cors_middleware(app, final_cors_config);
3396
3397    app
3398}
3399
3400// Note: start_with_traffic_shaping function removed due to compilation issues
3401// Use build_router_with_traffic_shaping_and_multi_tenant directly instead
3402
3403#[test]
3404fn test_route_info_clone() {
3405    let route = RouteInfo {
3406        method: "POST".to_string(),
3407        path: "/users".to_string(),
3408        operation_id: Some("createUser".to_string()),
3409        summary: None,
3410        description: None,
3411        parameters: vec![],
3412    };
3413
3414    let cloned = route.clone();
3415    assert_eq!(route.method, cloned.method);
3416    assert_eq!(route.path, cloned.path);
3417    assert_eq!(route.operation_id, cloned.operation_id);
3418}
3419
3420#[test]
3421fn test_http_server_state_new() {
3422    let state = HttpServerState::new();
3423    assert_eq!(state.routes.len(), 0);
3424}
3425
3426#[test]
3427fn test_http_server_state_with_routes() {
3428    let routes = vec![
3429        RouteInfo {
3430            method: "GET".to_string(),
3431            path: "/users".to_string(),
3432            operation_id: Some("getUsers".to_string()),
3433            summary: None,
3434            description: None,
3435            parameters: vec![],
3436        },
3437        RouteInfo {
3438            method: "POST".to_string(),
3439            path: "/users".to_string(),
3440            operation_id: Some("createUser".to_string()),
3441            summary: None,
3442            description: None,
3443            parameters: vec![],
3444        },
3445    ];
3446
3447    let state = HttpServerState::with_routes(routes.clone());
3448    assert_eq!(state.routes.len(), 2);
3449    assert_eq!(state.routes[0].method, "GET");
3450    assert_eq!(state.routes[1].method, "POST");
3451}
3452
3453#[test]
3454fn test_http_server_state_clone() {
3455    let routes = vec![RouteInfo {
3456        method: "GET".to_string(),
3457        path: "/test".to_string(),
3458        operation_id: None,
3459        summary: None,
3460        description: None,
3461        parameters: vec![],
3462    }];
3463
3464    let state = HttpServerState::with_routes(routes);
3465    let cloned = state.clone();
3466
3467    assert_eq!(state.routes.len(), cloned.routes.len());
3468    assert_eq!(state.routes[0].method, cloned.routes[0].method);
3469}
3470
3471#[tokio::test]
3472async fn test_build_router_without_openapi() {
3473    let _router = build_router(None, None, None).await;
3474    // Should succeed without OpenAPI spec
3475}
3476
3477#[tokio::test]
3478async fn test_build_router_with_nonexistent_spec() {
3479    let _router = build_router(Some("/nonexistent/spec.yaml".to_string()), None, None).await;
3480    // Should succeed but log a warning
3481}
3482
3483#[tokio::test]
3484async fn test_build_router_with_auth_and_latency() {
3485    let _router = build_router_with_auth_and_latency(None, None, None, None).await;
3486    // Should succeed without parameters
3487}
3488
3489#[tokio::test]
3490async fn test_build_router_with_latency() {
3491    let _router = build_router_with_latency(None, None, None).await;
3492    // Should succeed without parameters
3493}
3494
3495#[tokio::test]
3496async fn test_build_router_with_auth() {
3497    let _router = build_router_with_auth(None, None, None).await;
3498    // Should succeed without parameters
3499}
3500
3501#[tokio::test]
3502async fn test_build_router_with_chains() {
3503    let _router = build_router_with_chains(None, None, None).await;
3504    // Should succeed without parameters
3505}
3506
3507#[test]
3508fn test_route_info_with_all_fields() {
3509    let route = RouteInfo {
3510        method: "PUT".to_string(),
3511        path: "/users/{id}".to_string(),
3512        operation_id: Some("updateUser".to_string()),
3513        summary: Some("Update user".to_string()),
3514        description: Some("Updates an existing user".to_string()),
3515        parameters: vec!["id".to_string(), "body".to_string()],
3516    };
3517
3518    assert!(route.operation_id.is_some());
3519    assert!(route.summary.is_some());
3520    assert!(route.description.is_some());
3521    assert_eq!(route.parameters.len(), 2);
3522}
3523
3524#[test]
3525fn test_route_info_with_minimal_fields() {
3526    let route = RouteInfo {
3527        method: "DELETE".to_string(),
3528        path: "/users/{id}".to_string(),
3529        operation_id: None,
3530        summary: None,
3531        description: None,
3532        parameters: vec![],
3533    };
3534
3535    assert!(route.operation_id.is_none());
3536    assert!(route.summary.is_none());
3537    assert!(route.description.is_none());
3538    assert_eq!(route.parameters.len(), 0);
3539}
3540
3541#[test]
3542fn test_http_server_state_empty_routes() {
3543    let state = HttpServerState::with_routes(vec![]);
3544    assert_eq!(state.routes.len(), 0);
3545}
3546
3547#[test]
3548fn test_http_server_state_multiple_routes() {
3549    let routes = vec![
3550        RouteInfo {
3551            method: "GET".to_string(),
3552            path: "/users".to_string(),
3553            operation_id: Some("listUsers".to_string()),
3554            summary: Some("List all users".to_string()),
3555            description: None,
3556            parameters: vec![],
3557        },
3558        RouteInfo {
3559            method: "GET".to_string(),
3560            path: "/users/{id}".to_string(),
3561            operation_id: Some("getUser".to_string()),
3562            summary: Some("Get a user".to_string()),
3563            description: None,
3564            parameters: vec!["id".to_string()],
3565        },
3566        RouteInfo {
3567            method: "POST".to_string(),
3568            path: "/users".to_string(),
3569            operation_id: Some("createUser".to_string()),
3570            summary: Some("Create a user".to_string()),
3571            description: None,
3572            parameters: vec!["body".to_string()],
3573        },
3574    ];
3575
3576    let state = HttpServerState::with_routes(routes);
3577    assert_eq!(state.routes.len(), 3);
3578
3579    // Verify different HTTP methods
3580    let methods: Vec<&str> = state.routes.iter().map(|r| r.method.as_str()).collect();
3581    assert!(methods.contains(&"GET"));
3582    assert!(methods.contains(&"POST"));
3583}
3584
3585#[test]
3586fn test_http_server_state_with_rate_limiter() {
3587    use std::sync::Arc;
3588
3589    let config = middleware::RateLimitConfig::default();
3590    let rate_limiter = Arc::new(middleware::GlobalRateLimiter::new(config));
3591
3592    let state = HttpServerState::new().with_rate_limiter(rate_limiter);
3593
3594    assert!(state.rate_limiter.is_some());
3595    assert_eq!(state.routes.len(), 0);
3596}
3597
3598#[tokio::test]
3599async fn test_build_router_includes_rate_limiter() {
3600    let _router = build_router(None, None, None).await;
3601    // Router should be created successfully with rate limiter initialized
3602}