mockforge-bench 0.3.165

Load and performance testing 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
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
//! Spec-level audits for the conformance self-test.
//!
//! Issue #79 round 17.4 — Srikanth's (17.4) ask: in addition to driving
//! a server with positive + negative *requests*, also audit the
//! OpenAPI document itself for things that will silently degrade
//! validator quality at runtime. These are not server-rejection
//! findings — they're spec-quality findings, surfaced before any
//! request is sent.
//!
//! Categories: `servers` (missing / localhost-only / relative-only),
//! `callbacks` (unsecured webhook operations), `polymorphism`
//! (`oneOf` / `anyOf` without a `discriminator`), `datatypes`
//! (coverage of every `(type, format)` combination in the spec).
//!
//! The audit is a pure function of `&openapiv3::OpenAPI`; no network
//! traffic, no server side-effects. Output ships alongside the
//! self-test JSON report.

use openapiv3::{
    OpenAPI, ReferenceOr, Schema, SchemaKind, StringFormat, Type, VariantOrUnknownOrEmpty,
};
use std::collections::BTreeMap;

/// Severity of a finding. Maps to traffic-light colours in the report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// Informational — not a defect, but useful coverage data.
    Info,
    /// Likely-degraded validator behaviour, but not a hard bug.
    Warning,
    /// Clear finding that the user should address.
    Error,
}

/// One audit finding.
#[derive(Debug, Clone, serde::Serialize)]
pub struct SpecFinding {
    pub category: String,
    pub severity: Severity,
    /// JSON-pointer-ish location, e.g. `#/paths/~1users/post/callbacks/onCreated`.
    pub location: String,
    pub message: String,
}

/// Roll-up of all findings + the datatype coverage map.
#[derive(Debug, Default, Clone, serde::Serialize)]
pub struct SpecAuditReport {
    pub findings: Vec<SpecFinding>,
    /// Per `(type, format)` count of how many schemas in the spec use it.
    /// Format `""` is used when no format is declared.
    pub datatype_coverage: BTreeMap<String, usize>,
    pub operations_audited: usize,
}

impl SpecAuditReport {
    /// Count of findings by severity. Useful for one-line summaries.
    pub fn counts_by_severity(&self) -> (usize, usize, usize) {
        let mut info = 0;
        let mut warn = 0;
        let mut err = 0;
        for f in &self.findings {
            match f.severity {
                Severity::Info => info += 1,
                Severity::Warning => warn += 1,
                Severity::Error => err += 1,
            }
        }
        (info, warn, err)
    }

    /// Human-readable single-paragraph summary.
    pub fn render_summary(&self) -> String {
        let (info, warn, err) = self.counts_by_severity();
        let coverage_kinds = self.datatype_coverage.len();
        format!(
            "Spec audit: {err} error(s), {warn} warning(s), {info} info; covered {coverage_kinds} datatype kind(s) across {} operation(s)",
            self.operations_audited
        )
    }
}

/// Walk the OpenAPI document and produce all findings + coverage.
/// Pure; no I/O.
pub fn audit_spec(spec: &OpenAPI) -> SpecAuditReport {
    let mut report = SpecAuditReport::default();
    audit_servers(spec, &mut report);
    audit_callbacks(spec, &mut report);
    audit_polymorphism_and_datatypes(spec, &mut report);
    report
}

fn audit_servers(spec: &OpenAPI, report: &mut SpecAuditReport) {
    if spec.servers.is_empty() {
        report.findings.push(SpecFinding {
            category: "servers".into(),
            severity: Severity::Warning,
            location: "#/servers".into(),
            message: "No `servers` declared — clients have to guess the base URL".into(),
        });
        return;
    }
    let mut all_localhost = true;
    let mut all_relative = true;
    for s in &spec.servers {
        let url = s.url.as_str();
        let is_local = url.contains("localhost") || url.contains("127.0.0.1");
        let is_rel = !url.starts_with("http://") && !url.starts_with("https://");
        if !is_local {
            all_localhost = false;
        }
        if !is_rel {
            all_relative = false;
        }
    }
    if all_localhost && !spec.servers.is_empty() {
        report.findings.push(SpecFinding {
            category: "servers".into(),
            severity: Severity::Warning,
            location: "#/servers".into(),
            message: format!(
                "All {} declared server(s) are localhost — production base URL missing",
                spec.servers.len()
            ),
        });
    }
    if all_relative && !spec.servers.is_empty() {
        report.findings.push(SpecFinding {
            category: "servers".into(),
            severity: Severity::Warning,
            location: "#/servers".into(),
            message: "All declared servers use relative URLs — clients must resolve against the spec's host".into(),
        });
    }
}

fn audit_callbacks(spec: &OpenAPI, report: &mut SpecAuditReport) {
    for (path, path_item_ref) in &spec.paths.paths {
        let path_item = match path_item_ref {
            ReferenceOr::Item(p) => p,
            ReferenceOr::Reference { .. } => continue,
        };
        for (method, op) in operations_of(path_item) {
            for (cb_name, cb) in &op.callbacks {
                // `Callback = IndexMap<String, PathItem>` — no ReferenceOr
                // on the value, so we walk directly.
                for (cb_path, cb_path_item) in cb {
                    for (cb_method, cb_op) in operations_of(cb_path_item) {
                        if cb_op.security.as_ref().is_none_or(|s| s.is_empty()) {
                            report.findings.push(SpecFinding {
                                category: "callbacks".into(),
                                severity: Severity::Warning,
                                location: format!(
                                    "#/paths/{}/{}/callbacks/{}/{}/{}",
                                    path, method, cb_name, cb_path, cb_method
                                ),
                                message: format!(
                                    "Callback `{}` on `{} {}` has no security requirement — webhook deliveries are unauthenticated",
                                    cb_name, method.to_uppercase(), path
                                ),
                            });
                        }
                    }
                }
            }
        }
    }
}

fn audit_polymorphism_and_datatypes(spec: &OpenAPI, report: &mut SpecAuditReport) {
    // Walk all schemas in components + every inline request/response
    // body schema. Single pass — we count datatype coverage and find
    // polymorphism findings at the same time.
    if let Some(components) = &spec.components {
        for (name, schema_ref) in &components.schemas {
            if let ReferenceOr::Item(schema) = schema_ref {
                walk_schema(schema, &format!("#/components/schemas/{}", name), report);
            }
        }
    }
    for (path, path_item_ref) in &spec.paths.paths {
        let path_item = match path_item_ref {
            ReferenceOr::Item(p) => p,
            ReferenceOr::Reference { .. } => continue,
        };
        report.operations_audited += operations_of(path_item).len();
        for (method, op) in operations_of(path_item) {
            if let Some(ReferenceOr::Item(rb)) = &op.request_body {
                for (ct, mt) in &rb.content {
                    if let Some(ReferenceOr::Item(schema)) = &mt.schema {
                        walk_schema(
                            schema,
                            &format!("#/paths/{}/{}/requestBody/{}", path, method, ct),
                            report,
                        );
                    }
                }
            }
            for (status, resp_ref) in &op.responses.responses {
                if let ReferenceOr::Item(resp) = resp_ref {
                    for (ct, mt) in &resp.content {
                        if let Some(ReferenceOr::Item(schema)) = &mt.schema {
                            walk_schema(
                                schema,
                                &format!(
                                    "#/paths/{}/{}/responses/{:?}/{}",
                                    path, method, status, ct
                                ),
                                report,
                            );
                        }
                    }
                }
            }
        }
    }
}

fn walk_schema(schema: &Schema, location: &str, report: &mut SpecAuditReport) {
    match &schema.schema_kind {
        SchemaKind::Type(t) => {
            count_datatype(t, &mut report.datatype_coverage);
            // Recurse into object properties + array items.
            match t {
                Type::Object(obj) => {
                    for (k, v) in &obj.properties {
                        if let ReferenceOr::Item(inner) = v {
                            walk_schema(inner, &format!("{}.{}", location, k), report);
                        }
                    }
                }
                Type::Array(arr) => {
                    if let Some(ReferenceOr::Item(inner)) = &arr.items {
                        walk_schema(inner, &format!("{}[]", location), report);
                    }
                }
                _ => {}
            }
        }
        SchemaKind::OneOf { one_of } | SchemaKind::AnyOf { any_of: one_of } => {
            let kind = if matches!(schema.schema_kind, SchemaKind::OneOf { .. }) {
                "oneOf"
            } else {
                "anyOf"
            };
            if schema.schema_data.discriminator.is_none() {
                report.findings.push(SpecFinding {
                    category: "polymorphism".into(),
                    severity: Severity::Warning,
                    location: location.to_string(),
                    message: format!(
                        "{} composition has no `discriminator` — validator cannot pick the variant deterministically",
                        kind
                    ),
                });
            }
            for (i, variant) in one_of.iter().enumerate() {
                if let ReferenceOr::Item(inner) = variant {
                    walk_schema(inner, &format!("{}/{}/{}", location, kind, i), report);
                }
            }
        }
        SchemaKind::AllOf { all_of } => {
            for (i, variant) in all_of.iter().enumerate() {
                if let ReferenceOr::Item(inner) = variant {
                    walk_schema(inner, &format!("{}/allOf/{}", location, i), report);
                }
            }
        }
        _ => {}
    }
}

fn count_datatype(t: &Type, coverage: &mut BTreeMap<String, usize>) {
    let key = match t {
        Type::String(s) => match &s.format {
            VariantOrUnknownOrEmpty::Item(StringFormat::Date) => "string:date".to_string(),
            VariantOrUnknownOrEmpty::Item(StringFormat::DateTime) => "string:date-time".to_string(),
            VariantOrUnknownOrEmpty::Item(StringFormat::Password) => "string:password".to_string(),
            VariantOrUnknownOrEmpty::Item(StringFormat::Byte) => "string:byte".to_string(),
            VariantOrUnknownOrEmpty::Item(StringFormat::Binary) => "string:binary".to_string(),
            VariantOrUnknownOrEmpty::Unknown(f) => format!("string:{}", f),
            VariantOrUnknownOrEmpty::Empty => "string".to_string(),
        },
        Type::Number(_) => "number".to_string(),
        Type::Integer(_) => "integer".to_string(),
        Type::Boolean(_) => "boolean".to_string(),
        Type::Object(_) => "object".to_string(),
        Type::Array(_) => "array".to_string(),
    };
    *coverage.entry(key).or_insert(0) += 1;
}

/// `(method_name, &Operation)` for each declared HTTP method on a path
/// item. Mirrors what `openapiv3::PathItem` exposes individually.
fn operations_of(p: &openapiv3::PathItem) -> Vec<(&'static str, &openapiv3::Operation)> {
    let mut out = Vec::new();
    if let Some(o) = &p.get {
        out.push(("get", o));
    }
    if let Some(o) = &p.post {
        out.push(("post", o));
    }
    if let Some(o) = &p.put {
        out.push(("put", o));
    }
    if let Some(o) = &p.patch {
        out.push(("patch", o));
    }
    if let Some(o) = &p.delete {
        out.push(("delete", o));
    }
    if let Some(o) = &p.head {
        out.push(("head", o));
    }
    if let Some(o) = &p.options {
        out.push(("options", o));
    }
    if let Some(o) = &p.trace {
        out.push(("trace", o));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use openapiv3::{ObjectType, SchemaData, Server};

    fn empty_spec() -> OpenAPI {
        OpenAPI {
            openapi: "3.0.0".into(),
            info: Default::default(),
            ..Default::default()
        }
    }

    #[test]
    fn no_servers_yields_servers_warning() {
        let spec = empty_spec();
        let report = audit_spec(&spec);
        assert!(report
            .findings
            .iter()
            .any(|f| f.category == "servers" && f.severity == Severity::Warning));
    }

    #[test]
    fn localhost_only_servers_warn() {
        let mut spec = empty_spec();
        spec.servers = vec![
            Server {
                url: "http://localhost:3000".into(),
                ..Default::default()
            },
            Server {
                url: "http://127.0.0.1:8080".into(),
                ..Default::default()
            },
        ];
        let report = audit_spec(&spec);
        assert!(report
            .findings
            .iter()
            .any(|f| f.category == "servers" && f.message.contains("localhost")));
    }

    #[test]
    fn relative_only_servers_warn() {
        let mut spec = empty_spec();
        spec.servers = vec![Server {
            url: "/v1".into(),
            ..Default::default()
        }];
        let report = audit_spec(&spec);
        assert!(report
            .findings
            .iter()
            .any(|f| f.category == "servers" && f.message.contains("relative URLs")));
    }

    #[test]
    fn production_servers_no_warning() {
        let mut spec = empty_spec();
        spec.servers = vec![Server {
            url: "https://api.example.com".into(),
            ..Default::default()
        }];
        let report = audit_spec(&spec);
        assert!(!report.findings.iter().any(|f| f.category == "servers"));
    }

    #[test]
    fn datatype_coverage_records_string_format() {
        use openapiv3::{Components, StringType};
        let mut spec = empty_spec();
        let mut components = Components::default();
        let mut email_schema = Schema {
            schema_data: SchemaData::default(),
            schema_kind: SchemaKind::Type(Type::String(StringType {
                format: VariantOrUnknownOrEmpty::Unknown("email".into()),
                ..Default::default()
            })),
        };
        // Reuse the same shape with no format for a second schema.
        components
            .schemas
            .insert("Email".into(), ReferenceOr::Item(email_schema.clone()));
        email_schema.schema_kind = SchemaKind::Type(Type::String(Default::default()));
        components.schemas.insert("Plain".into(), ReferenceOr::Item(email_schema));
        spec.components = Some(components);
        let report = audit_spec(&spec);
        assert_eq!(report.datatype_coverage.get("string:email"), Some(&1));
        assert_eq!(report.datatype_coverage.get("string"), Some(&1));
    }

    #[test]
    fn oneof_without_discriminator_flags_polymorphism() {
        use openapiv3::Components;
        let mut spec = empty_spec();
        let mut components = Components::default();
        let one_of_schema = Schema {
            schema_data: SchemaData::default(),
            schema_kind: SchemaKind::OneOf {
                one_of: vec![
                    ReferenceOr::Item(Schema {
                        schema_data: SchemaData::default(),
                        schema_kind: SchemaKind::Type(Type::Object(ObjectType::default())),
                    }),
                    ReferenceOr::Item(Schema {
                        schema_data: SchemaData::default(),
                        schema_kind: SchemaKind::Type(Type::Object(ObjectType::default())),
                    }),
                ],
            },
        };
        components.schemas.insert("Shape".into(), ReferenceOr::Item(one_of_schema));
        spec.components = Some(components);
        let report = audit_spec(&spec);
        assert!(report
            .findings
            .iter()
            .any(|f| f.category == "polymorphism" && f.message.contains("oneOf")));
    }

    #[test]
    fn summary_counts_severities() {
        let report = SpecAuditReport {
            findings: vec![
                SpecFinding {
                    category: "servers".into(),
                    severity: Severity::Warning,
                    location: "#/servers".into(),
                    message: "x".into(),
                },
                SpecFinding {
                    category: "callbacks".into(),
                    severity: Severity::Error,
                    location: "#/x".into(),
                    message: "y".into(),
                },
            ],
            datatype_coverage: BTreeMap::from([("string".into(), 5)]),
            operations_audited: 3,
        };
        let (info, warn, err) = report.counts_by_severity();
        assert_eq!((info, warn, err), (0, 1, 1));
        let s = report.render_summary();
        assert!(s.contains("1 error"));
        assert!(s.contains("1 warning"));
        assert!(s.contains("3 operation"));
    }
}