mockforge-core 0.3.114

Shared logic for MockForge - routing, validation, latency, proxy
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! Pillars: [Contracts]
//!
//! Contract validation for CI/CD pipelines
//!
//! Validates that mock configurations match live API responses
//! and detects breaking changes in API contracts
use serde::{Deserialize, Serialize};

/// Result of contract validation with detailed breakdown
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    /// Whether all validation checks passed
    pub passed: bool,
    /// Total number of validation checks performed
    pub total_checks: usize,
    /// Number of checks that passed
    pub passed_checks: usize,
    /// Number of checks that failed
    pub failed_checks: usize,
    /// Non-blocking warnings encountered during validation
    pub warnings: Vec<ValidationWarning>,
    /// Validation errors that prevent the contract from being valid
    pub errors: Vec<ValidationError>,
    /// Breaking changes detected compared to previous contract version
    pub breaking_changes: Vec<BreakingChange>,
}

impl ValidationResult {
    /// Create a new empty validation result
    pub fn new() -> Self {
        Self {
            passed: true,
            total_checks: 0,
            passed_checks: 0,
            failed_checks: 0,
            warnings: Vec::new(),
            errors: Vec::new(),
            breaking_changes: Vec::new(),
        }
    }

    /// Add a validation error (marks result as failed)
    pub fn add_error(&mut self, error: ValidationError) {
        self.errors.push(error);
        self.failed_checks += 1;
        self.total_checks += 1;
        self.passed = false;
    }

    /// Add a validation warning (does not fail the result)
    pub fn add_warning(&mut self, warning: ValidationWarning) {
        self.warnings.push(warning);
        self.passed_checks += 1;
        self.total_checks += 1;
    }

    /// Add a breaking change (marks result as failed)
    pub fn add_breaking_change(&mut self, change: BreakingChange) {
        self.breaking_changes.push(change);
        self.passed = false;
    }

    /// Record a successful validation check
    pub fn add_success(&mut self) {
        self.passed_checks += 1;
        self.total_checks += 1;
    }
}

impl Default for ValidationResult {
    fn default() -> Self {
        Self::new()
    }
}

/// Validation warning for non-blocking issues
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationWarning {
    /// JSON path or endpoint path where the warning occurred
    pub path: String,
    /// Human-readable warning message
    pub message: String,
    /// Severity level of the warning
    pub severity: WarningSeverity,
}

/// Severity level for validation warnings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WarningSeverity {
    /// Informational message (low priority)
    Info,
    /// Warning that should be reviewed (medium priority)
    Warning,
}

/// Validation error for contract violations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    /// JSON path or endpoint path where the error occurred
    pub path: String,
    /// Human-readable error message
    pub message: String,
    /// Expected value or format (if applicable)
    pub expected: Option<String>,
    /// Actual value found (if applicable)
    pub actual: Option<String>,
    /// Link to contract diff entry (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contract_diff_id: Option<String>,
    /// Whether this is a breaking change
    #[serde(default)]
    pub is_breaking_change: bool,
}

/// Breaking change detected between contract versions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BreakingChange {
    /// Type of breaking change detected
    pub change_type: BreakingChangeType,
    /// Path or endpoint affected by the change
    pub path: String,
    /// Human-readable description of the breaking change
    pub description: String,
    /// Severity of the breaking change
    pub severity: ChangeSeverity,
}

/// Types of breaking changes that can be detected
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BreakingChangeType {
    /// An API endpoint was removed
    EndpointRemoved,
    /// A required field was added to a request/response
    RequiredFieldAdded,
    /// A field's data type was changed
    FieldTypeChanged,
    /// A field was removed from a request/response
    FieldRemoved,
    /// An HTTP response status code was changed
    ResponseCodeChanged,
    /// Authentication requirements were changed
    AuthenticationChanged,
}

/// Severity level for breaking changes
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ChangeSeverity {
    /// Critical breaking change - will break all clients
    Critical,
    /// Major breaking change - will break most clients
    Major,
    /// Minor breaking change - may break some clients
    Minor,
}

/// Contract validator for validating OpenAPI specs against live APIs
pub struct ContractValidator {
    /// Whether to use strict validation mode (fails on warnings)
    strict_mode: bool,
    /// Whether to ignore optional fields during validation
    ignore_optional_fields: bool,
}

impl ContractValidator {
    /// Create a new contract validator with default settings
    pub fn new() -> Self {
        Self {
            strict_mode: false,
            ignore_optional_fields: false,
        }
    }

    /// Configure strict validation mode (fails validation on warnings)
    pub fn with_strict_mode(mut self, strict: bool) -> Self {
        self.strict_mode = strict;
        self
    }

    /// Configure whether to ignore optional fields during validation
    pub fn with_ignore_optional_fields(mut self, ignore: bool) -> Self {
        self.ignore_optional_fields = ignore;
        self
    }

    /// Validate OpenAPI spec against live API
    pub async fn validate_openapi(
        &self,
        spec: &crate::openapi::OpenApiSpec,
        base_url: &str,
    ) -> ValidationResult {
        let mut result = ValidationResult::new();

        for (path, path_item_ref) in &spec.spec.paths.paths {
            if let openapiv3::ReferenceOr::Item(path_item) = path_item_ref {
                let operations = vec![
                    ("GET", path_item.get.as_ref()),
                    ("POST", path_item.post.as_ref()),
                    ("PUT", path_item.put.as_ref()),
                    ("DELETE", path_item.delete.as_ref()),
                    ("PATCH", path_item.patch.as_ref()),
                ];

                for (method, op_opt) in operations {
                    if let Some(op) = op_opt {
                        self.validate_endpoint(&mut result, base_url, method, path, op).await;
                    }
                }
            }
        }

        result
    }

    async fn validate_endpoint(
        &self,
        result: &mut ValidationResult,
        base_url: &str,
        method: &str,
        path: &str,
        operation: &openapiv3::Operation,
    ) {
        let url = format!("{}{}", base_url, path);

        // Try to make a request to the endpoint
        let client = reqwest::Client::new();
        let request = match method {
            "GET" => client.get(&url),
            "POST" => client.post(&url),
            "PUT" => client.put(&url),
            "DELETE" => client.delete(&url),
            "PATCH" => client.patch(&url),
            _ => {
                result.add_error(ValidationError {
                    path: path.to_string(),
                    message: format!("Unsupported HTTP method: {}", method),
                    expected: None,
                    actual: None,
                    contract_diff_id: None,
                    is_breaking_change: false,
                });
                return;
            }
        };

        match request.send().await {
            Ok(response) => {
                let status = response.status();

                // Check if status code matches spec
                let expected_codes: Vec<u16> = operation
                    .responses
                    .responses
                    .keys()
                    .filter_map(|k| match k {
                        openapiv3::StatusCode::Code(code) => Some(*code),
                        _ => None,
                    })
                    .collect();

                if !expected_codes.contains(&status.as_u16()) {
                    result.add_warning(ValidationWarning {
                        path: format!("{} {}", method, path),
                        message: format!(
                            "Status code {} not in spec (expected: {:?})",
                            status.as_u16(),
                            expected_codes
                        ),
                        severity: WarningSeverity::Warning,
                    });
                } else {
                    result.add_success();
                }
            }
            Err(e) => {
                if self.strict_mode {
                    result.add_error(ValidationError {
                        path: format!("{} {}", method, path),
                        message: format!("Failed to reach endpoint: {}", e),
                        expected: Some("2xx response".to_string()),
                        actual: Some("connection error".to_string()),
                        contract_diff_id: None,
                        is_breaking_change: false,
                    });
                } else {
                    result.add_warning(ValidationWarning {
                        path: format!("{} {}", method, path),
                        message: format!("Endpoint not reachable: {}", e),
                        severity: WarningSeverity::Info,
                    });
                    result.add_success();
                }
            }
        }
    }

    /// Compare two OpenAPI specs and detect breaking changes
    pub fn compare_specs(
        &self,
        old_spec: &crate::openapi::OpenApiSpec,
        new_spec: &crate::openapi::OpenApiSpec,
    ) -> ValidationResult {
        let mut result = ValidationResult::new();

        // Check for removed endpoints
        for (path, _) in &old_spec.spec.paths.paths {
            if !new_spec.spec.paths.paths.contains_key(path) {
                result.add_breaking_change(BreakingChange {
                    change_type: BreakingChangeType::EndpointRemoved,
                    path: path.clone(),
                    description: format!("Endpoint {} was removed", path),
                    severity: ChangeSeverity::Critical,
                });
            }
        }

        // Compare operations for each path present in both specs
        for (path, new_path_item_ref) in &new_spec.spec.paths.paths {
            if let openapiv3::ReferenceOr::Item(new_path_item) = new_path_item_ref {
                if let Some(openapiv3::ReferenceOr::Item(old_path_item)) =
                    old_spec.spec.paths.paths.get(path)
                {
                    let operations = [
                        ("GET", old_path_item.get.as_ref(), new_path_item.get.as_ref()),
                        ("POST", old_path_item.post.as_ref(), new_path_item.post.as_ref()),
                        ("PUT", old_path_item.put.as_ref(), new_path_item.put.as_ref()),
                        ("DELETE", old_path_item.delete.as_ref(), new_path_item.delete.as_ref()),
                        ("PATCH", old_path_item.patch.as_ref(), new_path_item.patch.as_ref()),
                    ];

                    for (method, old_op, new_op) in &operations {
                        match (old_op, new_op) {
                            (Some(_), None) => {
                                // Operation was removed
                                result.add_breaking_change(BreakingChange {
                                    change_type: BreakingChangeType::EndpointRemoved,
                                    path: format!("{} {}", method, path),
                                    description: format!(
                                        "{} {} operation was removed",
                                        method, path
                                    ),
                                    severity: ChangeSeverity::Critical,
                                });
                            }
                            (Some(old), Some(new)) => {
                                // Check for new required parameters
                                for new_param_ref in &new.parameters {
                                    if let openapiv3::ReferenceOr::Item(new_param) = new_param_ref {
                                        let is_required = match new_param {
                                            openapiv3::Parameter::Query {
                                                parameter_data, ..
                                            }
                                            | openapiv3::Parameter::Header {
                                                parameter_data, ..
                                            }
                                            | openapiv3::Parameter::Path {
                                                parameter_data, ..
                                            }
                                            | openapiv3::Parameter::Cookie {
                                                parameter_data, ..
                                            } => parameter_data.required,
                                        };
                                        if is_required {
                                            let param_name = match new_param {
                                                openapiv3::Parameter::Query {
                                                    parameter_data,
                                                    ..
                                                }
                                                | openapiv3::Parameter::Header {
                                                    parameter_data,
                                                    ..
                                                }
                                                | openapiv3::Parameter::Path {
                                                    parameter_data,
                                                    ..
                                                }
                                                | openapiv3::Parameter::Cookie {
                                                    parameter_data,
                                                    ..
                                                } => &parameter_data.name,
                                            };
                                            // Check if this required param existed in old spec
                                            let existed_before = old.parameters.iter().any(|p| {
                                                if let openapiv3::ReferenceOr::Item(old_p) = p {
                                                    let old_name = match old_p {
                                                        openapiv3::Parameter::Query {
                                                            parameter_data,
                                                            ..
                                                        }
                                                        | openapiv3::Parameter::Header {
                                                            parameter_data,
                                                            ..
                                                        }
                                                        | openapiv3::Parameter::Path {
                                                            parameter_data,
                                                            ..
                                                        }
                                                        | openapiv3::Parameter::Cookie {
                                                            parameter_data,
                                                            ..
                                                        } => &parameter_data.name,
                                                    };
                                                    old_name == param_name
                                                } else {
                                                    false
                                                }
                                            });
                                            if !existed_before {
                                                result.add_breaking_change(BreakingChange {
                                                    change_type: BreakingChangeType::RequiredFieldAdded,
                                                    path: format!("{} {}", method, path),
                                                    description: format!(
                                                        "New required parameter '{}' added to {} {}",
                                                        param_name, method, path
                                                    ),
                                                    severity: ChangeSeverity::Major,
                                                });
                                            }
                                        }
                                    }
                                }
                                result.add_success();
                            }
                            _ => {
                                // New operation added (not breaking) or both absent
                                result.add_success();
                            }
                        }
                    }
                }
            }
        }

        result
    }

    /// Generate validation report
    pub fn generate_report(&self, result: &ValidationResult) -> String {
        let mut report = String::new();

        report.push_str("# Contract Validation Report\n\n");
        report.push_str(&format!(
            "**Status**: {}\n",
            if result.passed {
                "✓ PASSED"
            } else {
                "✗ FAILED"
            }
        ));
        report.push_str(&format!("**Total Checks**: {}\n", result.total_checks));
        report.push_str(&format!("**Passed**: {}\n", result.passed_checks));
        report.push_str(&format!("**Failed**: {}\n\n", result.failed_checks));

        if !result.breaking_changes.is_empty() {
            report.push_str("## Breaking Changes\n\n");
            for change in &result.breaking_changes {
                report.push_str(&format!(
                    "- **{:?}** ({:?}): {} - {}\n",
                    change.change_type, change.severity, change.path, change.description
                ));
            }
            report.push('\n');
        }

        if !result.errors.is_empty() {
            report.push_str("## Errors\n\n");
            for error in &result.errors {
                report.push_str(&format!("- **{}**: {}\n", error.path, error.message));
                if let Some(expected) = &error.expected {
                    report.push_str(&format!("  - Expected: {}\n", expected));
                }
                if let Some(actual) = &error.actual {
                    report.push_str(&format!("  - Actual: {}\n", actual));
                }
            }
            report.push('\n');
        }

        if !result.warnings.is_empty() {
            report.push_str("## Warnings\n\n");
            for warning in &result.warnings {
                report.push_str(&format!(
                    "- **{}** ({:?}): {}\n",
                    warning.path, warning.severity, warning.message
                ));
            }
        }

        report
    }
}

impl Default for ContractValidator {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validation_result_creation() {
        let result = ValidationResult::new();
        assert!(result.passed);
        assert_eq!(result.total_checks, 0);
        assert_eq!(result.errors.len(), 0);
    }

    #[test]
    fn test_add_error() {
        let mut result = ValidationResult::new();
        result.add_error(ValidationError {
            path: "/api/test".to_string(),
            message: "Test error".to_string(),
            expected: None,
            actual: None,
            contract_diff_id: None,
            is_breaking_change: false,
        });

        assert!(!result.passed);
        assert_eq!(result.failed_checks, 1);
        assert_eq!(result.errors.len(), 1);
    }

    #[test]
    fn test_add_breaking_change() {
        let mut result = ValidationResult::new();
        result.add_breaking_change(BreakingChange {
            change_type: BreakingChangeType::EndpointRemoved,
            path: "/api/removed".to_string(),
            description: "Endpoint was removed".to_string(),
            severity: ChangeSeverity::Critical,
        });

        assert!(!result.passed);
        assert_eq!(result.breaking_changes.len(), 1);
    }

    #[test]
    fn test_contract_validator_creation() {
        let validator = ContractValidator::new();
        assert!(!validator.strict_mode);
        assert!(!validator.ignore_optional_fields);
    }

    #[test]
    fn test_contract_validator_with_options() {
        let validator = ContractValidator::new()
            .with_strict_mode(true)
            .with_ignore_optional_fields(true);

        assert!(validator.strict_mode);
        assert!(validator.ignore_optional_fields);
    }

    #[test]
    fn test_generate_report() {
        let mut result = ValidationResult::new();
        result.add_error(ValidationError {
            path: "/api/test".to_string(),
            message: "Test failed".to_string(),
            expected: Some("200".to_string()),
            actual: Some("404".to_string()),
            contract_diff_id: None,
            is_breaking_change: false,
        });

        let validator = ContractValidator::new();
        let report = validator.generate_report(&result);

        assert!(report.contains("FAILED"));
        assert!(report.contains("/api/test"));
        assert!(report.contains("Test failed"));
    }
}