mockforge-http 0.3.151

HTTP/REST protocol support for MockForge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Drift tracking middleware
//!
//! This middleware integrates drift budget evaluation and consumer usage tracking
//! with contract diff analysis.

// Uses DriftBudgetEngine + ContractDiffAnalyzer which stay in core.
#![allow(deprecated)]

use axum::{body::Body, extract::Request, http::Response, middleware::Next};
use mockforge_contracts::consumer_contracts::{ConsumerBreakingChangeDetector, UsageRecorder};
use mockforge_core::{
    ai_contract_diff::ContractDiffAnalyzer,
    contract_drift::DriftBudgetEngine,
    incidents::{IncidentManager, IncidentSeverity, IncidentType},
    openapi::OpenApiSpec,
};
use mockforge_foundation::contract_drift_types::DriftResult;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use tracing::{debug, warn};

/// Maximum request body size to buffer for drift tracking.
///
/// Issue #79 — see `contract_diff_middleware`. Same root cause: the
/// old hard-coded 1 MiB cap, paired with the over-cap branch
/// substituting `Body::empty()`, broke downstream handlers on large
/// chunked uploads. Configurable via `MOCKFORGE_DRIFT_MAX_BODY_MB`.
fn max_drift_body_size() -> usize {
    const DEFAULT_MB: usize = 10;
    std::env::var("MOCKFORGE_DRIFT_MAX_BODY_MB")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(DEFAULT_MB)
        .saturating_mul(1024 * 1024)
}

/// State for drift tracking middleware
#[derive(Clone)]
pub struct DriftTrackingState {
    /// Contract diff analyzer
    pub diff_analyzer: Option<Arc<ContractDiffAnalyzer>>,
    /// OpenAPI spec (if available)
    pub spec: Option<Arc<OpenApiSpec>>,
    /// Drift budget engine
    pub drift_engine: Arc<DriftBudgetEngine>,
    /// Incident manager
    pub incident_manager: Arc<IncidentManager>,
    /// Usage recorder for consumer contracts
    pub usage_recorder: Arc<UsageRecorder>,
    /// Consumer breaking change detector
    pub consumer_detector: Arc<ConsumerBreakingChangeDetector>,
    /// Whether drift tracking is enabled
    pub enabled: bool,
}

/// Middleware to track drift and consumer usage (with state from extensions)
///
/// This middleware requires response body buffering middleware to be applied first.
/// The response body is extracted from buffered response extensions.
pub async fn drift_tracking_middleware_with_extensions(
    req: Request<Body>,
    next: Next,
) -> Response<Body> {
    // Extract state from request extensions
    let state = req.extensions().get::<DriftTrackingState>().cloned();

    let state = if let Some(state) = state {
        state
    } else {
        // No state available, skip drift tracking
        return next.run(req).await;
    };

    if !state.enabled {
        return next.run(req).await;
    }

    let method = req.method().to_string();
    let path = req.uri().path().to_string();
    let max_body = max_drift_body_size();

    // Issue #79 — pre-check Content-Length so we skip capture cleanly
    // for over-cap requests instead of consuming the body and then
    // substituting `Body::empty()` (which broke downstream handlers).
    let content_length = req
        .headers()
        .get(http::header::CONTENT_LENGTH)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<usize>().ok());
    if let Some(len) = content_length {
        if len > max_body {
            debug!(
                "drift_tracking: skipping capture for {} {} — content-length {} > cap {}",
                method, path, len, max_body
            );
            return next.run(req).await;
        }
    }

    // Extract consumer identifier and headers from request
    let consumer_id = extract_consumer_id(&req);

    // Extract headers for capture
    let captured_headers = extract_headers_for_capture(&req);

    // Buffer the request body so we can capture it and still forward it
    let (parts, body) = req.into_parts();
    let body_bytes = match axum::body::to_bytes(body, max_body).await {
        Ok(b) => b,
        Err(_) => {
            // Chunked over-cap body — body partially consumed and we
            // cannot rebuild. 413 PayloadTooLarge instead of the old
            // silent `Body::empty()` substitution. Issue #79.
            return Response::builder()
                .status(http::StatusCode::PAYLOAD_TOO_LARGE)
                .header(
                    http::header::CONTENT_TYPE,
                    "application/json",
                )
                .body(Body::from(format!(
                    r#"{{"error":"PAYLOAD_TOO_LARGE","message":"chunked request body exceeded drift_tracking capture cap (~{} MiB); raise MOCKFORGE_DRIFT_MAX_BODY_MB or send Content-Length"}}"#,
                    max_body / (1024 * 1024)
                )))
                .unwrap_or_else(|_| Response::new(Body::from("payload too large")));
        }
    };

    // Try to parse body as JSON for structured capture
    let captured_body = if !body_bytes.is_empty() {
        serde_json::from_slice::<Value>(&body_bytes).ok()
    } else {
        None
    };

    // Reconstruct the request with the buffered body
    let req = Request::from_parts(parts, Body::from(body_bytes));

    // Process request and get response
    let response = next.run(req).await;

    // Extract response body for consumer usage tracking
    let response_body = extract_response_body(&response);

    // Record consumer usage if consumer is identified
    if let Some(ref consumer_id) = consumer_id {
        if let Some(body) = &response_body {
            state.usage_recorder.record_usage(consumer_id, &path, &method, Some(body)).await;
        }
    }

    // Perform contract diff analysis if analyzer and spec are available
    if let (Some(ref analyzer), Some(ref spec)) = (&state.diff_analyzer, &state.spec) {
        // Create captured request with body and headers
        let mut captured = mockforge_core::ai_contract_diff::CapturedRequest::new(
            &method,
            &path,
            "drift_tracking",
        )
        .with_headers(captured_headers)
        .with_response(response.status().as_u16(), response_body.clone());

        if let Some(body_value) = captured_body {
            captured = captured.with_body(body_value);
        }

        // Analyze request against contract
        match analyzer.analyze(&captured, spec).await {
            Ok(diff_result) => {
                // Evaluate drift budget
                let drift_result = state.drift_engine.evaluate(&diff_result, &path, &method);

                // Emit Prometheus gauges for the drift dashboard (#678). The
                // workspace_id is not yet plumbed through the middleware —
                // pass an empty label so a single global series records,
                // matching the pattern used for the non-workspace
                // `pillar_tracking` calls below. When workspace identification
                // lands we can switch this label to the resolved id.
                mockforge_observability::get_global_registry().record_drift_evaluation(
                    mockforge_observability::DriftEvaluationSample {
                        workspace_id: "",
                        endpoint: &path,
                        method: &method,
                        total: drift_result.metrics.total_changes,
                        breaking: drift_result.breaking_changes,
                        potentially_breaking: drift_result.potentially_breaking_changes,
                        budget_exceeded: drift_result.budget_exceeded,
                    },
                );

                // #677 — when analytics is installed, fire a drift_percentage
                // sample at the analytics sqlite. Stays a no-op when the
                // global DB hasn't been initialised, so OSS quick-start
                // doesn't accidentally create a sqlite file.
                //
                // Heuristic for total/drifting: total_changes counts the
                // observed mismatches (the "denominator" for how many things
                // we looked at this request), and breaking + potentially-
                // breaking is what counts as drift. Recorded per-request so
                // the dashboard's time-series view shows the live trend.
                let total = i64::from(drift_result.metrics.total_changes);
                let drifting = i64::from(drift_result.breaking_changes)
                    + i64::from(drift_result.potentially_breaking_changes);
                mockforge_analytics::record_drift_percentage_async(
                    String::new(), // workspace_id — see Prometheus emission note
                    None,
                    total,
                    drifting,
                );

                // Record contracts pillar usage for drift detection
                mockforge_core::pillar_tracking::record_contracts_usage(
                    None, // workspace_id could be extracted from request if available
                    None,
                    "drift_detection",
                    serde_json::json!({
                        "endpoint": path,
                        "method": method,
                        "breaking_changes": drift_result.breaking_changes,
                        "non_breaking_changes": drift_result.non_breaking_changes,
                        "incident": drift_result.should_create_incident
                    }),
                )
                .await;

                // If this endpoint has a drift budget configured, record that so
                // the Contracts pillar dashboard can count distinct budgeted endpoints.
                let endpoint_key = format!("{} {}", method, path);
                let budget_config = state.drift_engine.config();
                if budget_config.enabled
                    && (budget_config.per_endpoint_budgets.contains_key(&endpoint_key)
                        || budget_config.default_budget.is_some())
                {
                    mockforge_core::pillar_tracking::record_contracts_usage(
                        None,
                        None,
                        "drift_budget_configured",
                        serde_json::json!({
                            "endpoint": endpoint_key,
                        }),
                    )
                    .await;
                }

                // Create incident if budget is exceeded or breaking changes detected
                if drift_result.should_create_incident {
                    let incident_type = if drift_result.breaking_changes > 0 {
                        IncidentType::BreakingChange
                    } else {
                        IncidentType::ThresholdExceeded
                    };

                    let severity = determine_severity(&drift_result);

                    let details = serde_json::json!({
                        "breaking_changes": drift_result.breaking_changes,
                        "non_breaking_changes": drift_result.non_breaking_changes,
                        "breaking_mismatches": drift_result.breaking_mismatches,
                        "non_breaking_mismatches": drift_result.non_breaking_mismatches,
                        "budget_exceeded": drift_result.budget_exceeded,
                    });

                    // Create incident with before/after samples
                    // Extract before/after samples from diff result if available
                    let before_sample = Some(serde_json::json!({
                        "contract_format": diff_result.metadata.contract_format,
                        "contract_version": diff_result.metadata.contract_version,
                        "endpoint": path,
                        "method": method,
                    }));

                    let after_sample = Some(serde_json::json!({
                        "mismatches": diff_result.mismatches,
                        "recommendations": diff_result.recommendations,
                        "corrections": diff_result.corrections,
                    }));

                    let _incident = state
                        .incident_manager
                        .create_incident_with_samples(
                            path.clone(),
                            method.clone(),
                            incident_type,
                            severity,
                            details,
                            None, // budget_id
                            None, // workspace_id
                            None, // sync_cycle_id
                            None, // contract_diff_id (could be generated from diff_result)
                            before_sample,
                            after_sample,
                            Some(drift_result.fitness_test_results.clone()), // fitness_test_results
                            drift_result.consumer_impact.clone(),            // affected_consumers
                            Some(mockforge_foundation::protocol::Protocol::Http), // protocol
                        )
                        .await;

                    warn!(
                        "Drift incident created: {} {} - {} breaking changes, {} non-breaking changes",
                        method, path, drift_result.breaking_changes, drift_result.non_breaking_changes
                    );
                }

                // Check for consumer-specific violations
                if let Some(ref consumer_id) = consumer_id {
                    let violations = state
                        .consumer_detector
                        .detect_violations(consumer_id, &path, &method, &diff_result, None)
                        .await;

                    if !violations.is_empty() {
                        warn!(
                            "Consumer {} has {} violations on {} {}",
                            consumer_id,
                            violations.len(),
                            method,
                            path
                        );
                    }
                }
            }
            Err(e) => {
                debug!("Contract diff analysis failed: {}", e);
            }
        }
    }

    response
}

/// Extract consumer identifier from request
fn extract_consumer_id(req: &Request<Body>) -> Option<String> {
    // Try to extract from various sources:
    // 1. X-Consumer-ID header
    if let Some(consumer_id) = req.headers().get("x-consumer-id").and_then(|h| h.to_str().ok()) {
        return Some(consumer_id.to_string());
    }

    // 2. X-Workspace-ID header (for workspace-based consumers)
    if let Some(workspace_id) = req.headers().get("x-workspace-id").and_then(|h| h.to_str().ok()) {
        return Some(format!("workspace:{}", workspace_id));
    }

    // 3. API key from header
    if let Some(api_key) = req
        .headers()
        .get("x-api-key")
        .or_else(|| req.headers().get("authorization"))
        .and_then(|h| h.to_str().ok())
    {
        // Hash the API key for privacy
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(api_key.as_bytes());
        let hash = format!("{:x}", hasher.finalize());
        return Some(format!("api_key:{}", hash));
    }

    None
}

/// Extract safe headers for drift capture
fn extract_headers_for_capture(req: &Request<Body>) -> HashMap<String, String> {
    let safe_headers = [
        "accept",
        "accept-encoding",
        "content-type",
        "content-length",
        "user-agent",
    ];
    let mut captured = HashMap::new();
    for name in safe_headers {
        if let Some(value) = req.headers().get(name).and_then(|v| v.to_str().ok()) {
            captured.insert(name.to_string(), value.to_string());
        }
    }
    captured
}

/// Extract response body as JSON value
fn extract_response_body(response: &Response<Body>) -> Option<Value> {
    // Try to get buffered response from extensions
    if let Some(buffered) = crate::middleware::get_buffered_response(response) {
        return buffered.json();
    }

    // If not buffered, try to parse from response body
    // Note: This requires the response body to be buffered by upstream middleware
    None
}

/// Determine incident severity from drift result
fn determine_severity(drift_result: &DriftResult) -> IncidentSeverity {
    if drift_result.breaking_changes > 0 {
        // Check if any breaking mismatch is critical
        if drift_result
            .breaking_mismatches
            .iter()
            .any(|m| m.severity == mockforge_core::ai_contract_diff::MismatchSeverity::Critical)
        {
            return IncidentSeverity::Critical;
        }
        // Check if any breaking mismatch is high
        if drift_result
            .breaking_mismatches
            .iter()
            .any(|m| m.severity == mockforge_core::ai_contract_diff::MismatchSeverity::High)
        {
            return IncidentSeverity::High;
        }
        return IncidentSeverity::Medium;
    }

    // Non-breaking changes are lower severity
    if drift_result.non_breaking_changes > 5 {
        IncidentSeverity::Medium
    } else {
        IncidentSeverity::Low
    }
}