mockforge-openapi 0.3.213

OpenAPI 3.x / Swagger 2.0 spec loading, parsing, schema validation, and response selection 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
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! OpenAPI specification loading and parsing
//!
//! This module handles loading OpenAPI specifications from files,
//! parsing them, and providing basic operations on the specs.
//! It also supports Swagger 2.0 specifications by converting them
//! to OpenAPI 3.0 format automatically.

use crate::swagger_convert;
use mockforge_foundation::error::{Error, Result};
use openapiv3::{OpenAPI, ReferenceOr, Schema};
use std::collections::HashSet;
use std::path::Path;
use tokio::fs;
use tracing;

/// HTTP methods that make a `paths.<path>.<key>` entry an Operation Object.
const OPERATION_KEYS: [&str; 8] = [
    "get", "put", "post", "delete", "options", "head", "patch", "trace",
];

/// Insert an empty `responses` object into any operation that lacks one,
/// returning how many were repaired.
///
/// OpenAPI 3.x marks `responses` as REQUIRED on an Operation Object, and the
/// `openapiv3` crate enforces that, so a spec missing it fails to deserialize
/// with a bare `missing field \`responses\`` and no indication of WHERE. Specs
/// emitted by proxies and API-discovery tools routinely omit it: they observe
/// requests, so they know paths, methods and schemas, but have nothing to say
/// about responses.
///
/// Refusing those specs outright is the wrong trade for this codebase. Request
/// generation, load testing and conformance probing all derive from paths,
/// parameters and `requestBody`; none of them read `responses`. So a missing
/// `responses` costs nothing we actually use, while rejecting the document
/// costs the user their entire run.
///
/// Reported by Srikanth on #79: a proxy-generated spec where 63 of 70
/// operations had no `responses` failed to load at all.
///
/// The repair is deliberately narrow. It only fills in a field the spec says is
/// mandatory, never invents response *content*, and leaves every other
/// validation error to surface normally.
fn fill_missing_operation_responses(raw: &mut serde_json::Value) -> usize {
    let Some(paths) = raw.get_mut("paths").and_then(|p| p.as_object_mut()) else {
        return 0;
    };

    let mut repaired = 0;
    for (_path, item) in paths.iter_mut() {
        let Some(item) = item.as_object_mut() else {
            continue;
        };
        for method in OPERATION_KEYS {
            let Some(op) = item.get_mut(method).and_then(|o| o.as_object_mut()) else {
                continue;
            };
            if !op.contains_key("responses") {
                op.insert(
                    "responses".to_string(),
                    serde_json::Value::Object(serde_json::Map::new()),
                );
                repaired += 1;
            }
        }
    }
    repaired
}

/// Apply [`fill_missing_operation_responses`] and warn once if anything was
/// repaired, so a non-conformant spec is visible rather than silently accepted.
fn repair_spec_for_parsing(raw: &mut serde_json::Value, source: &str) {
    let repaired = fill_missing_operation_responses(raw);
    if repaired > 0 {
        tracing::warn!(
            "{source}: {repaired} operation(s) had no `responses` field, which OpenAPI 3.x \
             requires. Treating them as having no declared responses so the spec can load. \
             Request generation does not use `responses`, but response-schema validation \
             will have nothing to check for these operations."
        );
    }
}

/// OpenAPI specification loader and parser
#[derive(Debug, Clone)]
pub struct OpenApiSpec {
    /// The parsed OpenAPI specification
    pub spec: OpenAPI,
    /// Path to the original spec file
    pub file_path: Option<String>,
    /// Raw OpenAPI document preserved as JSON for resolving unsupported constructs
    pub raw_document: Option<serde_json::Value>,
}

impl OpenApiSpec {
    /// Load OpenAPI spec from a file path
    ///
    /// Supports both OpenAPI 3.x and Swagger 2.0 specifications.
    /// Swagger 2.0 specs are automatically converted to OpenAPI 3.0 format.
    pub async fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path_ref = path.as_ref();
        let content = fs::read_to_string(path_ref)
            .await
            .map_err(|e| Error::io_with_context("reading OpenAPI spec file", e.to_string()))?;

        let raw_json = if path_ref.extension().and_then(|s| s.to_str()) == Some("yaml")
            || path_ref.extension().and_then(|s| s.to_str()) == Some("yml")
        {
            let yaml_value: serde_yaml::Value = serde_yaml::from_str(&content)
                .map_err(|e| Error::config(format!("Failed to parse YAML OpenAPI spec: {}", e)))?;
            serde_json::to_value(&yaml_value).map_err(|e| {
                Error::config(format!("Failed to convert YAML OpenAPI spec to JSON: {}", e))
            })?
        } else {
            serde_json::from_str(&content)
                .map_err(|e| Error::config(format!("Failed to parse JSON OpenAPI spec: {}", e)))?
        };

        // Check if this is a Swagger 2.0 spec and convert if necessary
        let (raw_document, spec) = if swagger_convert::is_swagger_2(&raw_json) {
            tracing::info!("Detected Swagger 2.0 specification, converting to OpenAPI 3.0");
            let converted =
                swagger_convert::convert_swagger_to_openapi3(&raw_json).map_err(|e| {
                    Error::config(format!("Failed to convert Swagger 2.0 to OpenAPI 3.0: {}", e))
                })?;
            let spec: OpenAPI = serde_json::from_value(converted.clone()).map_err(|e| {
                Error::config(format!("Failed to parse converted OpenAPI spec: {}", e))
            })?;
            (converted, spec)
        } else {
            let mut raw_json = raw_json;
            repair_spec_for_parsing(&mut raw_json, "OpenAPI spec");
            let spec: OpenAPI = serde_json::from_value(raw_json.clone()).map_err(|e| {
                // Enhanced error reporting for debugging missing field errors
                let error_str = format!("{}", e);
                let mut error_msg = format!("Failed to read OpenAPI spec: {}", e);

                // If it's a missing field error, add diagnostic information
                if error_str.contains("missing field") {
                    tracing::error!("OpenAPI deserialization error: {}", error_str);

                    // Add context about the spec structure
                    if let Some(info) = raw_json.get("info") {
                        if let Some(info_obj) = info.as_object() {
                            let has_desc = info_obj.contains_key("description");
                            error_msg
                                .push_str(&format!(" | Info.description present: {}", has_desc));
                        }
                    }
                    if let Some(servers) = raw_json.get("servers") {
                        if let Some(servers_arr) = servers.as_array() {
                            error_msg.push_str(&format!(" | Servers count: {}", servers_arr.len()));
                        }
                    }
                }

                Error::config(error_msg)
            })?;
            (raw_json, spec)
        };

        Ok(Self {
            spec,
            file_path: path_ref.to_str().map(|s| s.to_string()),
            raw_document: Some(raw_document),
        })
    }

    /// Load OpenAPI spec from string content
    ///
    /// Supports both OpenAPI 3.x and Swagger 2.0 specifications.
    /// Swagger 2.0 specs are automatically converted to OpenAPI 3.0 format.
    pub fn from_string(content: &str, format: Option<&str>) -> Result<Self> {
        let raw_json = if format == Some("yaml") || format == Some("yml") {
            let yaml_value: serde_yaml::Value = serde_yaml::from_str(content)
                .map_err(|e| Error::config(format!("Failed to parse YAML OpenAPI spec: {}", e)))?;
            serde_json::to_value(&yaml_value).map_err(|e| {
                Error::config(format!("Failed to convert YAML OpenAPI spec to JSON: {}", e))
            })?
        } else {
            serde_json::from_str(content)
                .map_err(|e| Error::config(format!("Failed to parse JSON OpenAPI spec: {}", e)))?
        };

        // Check if this is a Swagger 2.0 spec and convert if necessary
        let (raw_document, spec) = if swagger_convert::is_swagger_2(&raw_json) {
            let converted =
                swagger_convert::convert_swagger_to_openapi3(&raw_json).map_err(|e| {
                    Error::config(format!("Failed to convert Swagger 2.0 to OpenAPI 3.0: {}", e))
                })?;
            let spec: OpenAPI = serde_json::from_value(converted.clone()).map_err(|e| {
                Error::config(format!("Failed to parse converted OpenAPI spec: {}", e))
            })?;
            (converted, spec)
        } else {
            let mut raw_json = raw_json;
            repair_spec_for_parsing(&mut raw_json, "OpenAPI spec");
            let spec: OpenAPI = serde_json::from_value(raw_json.clone())
                .map_err(|e| Error::io_with_context("reading OpenAPI spec", e.to_string()))?;
            (raw_json, spec)
        };

        Ok(Self {
            spec,
            file_path: None,
            raw_document: Some(raw_document),
        })
    }

    /// Load OpenAPI spec from JSON value
    ///
    /// Supports both OpenAPI 3.x and Swagger 2.0 specifications.
    /// Swagger 2.0 specs are automatically converted to OpenAPI 3.0 format.
    pub fn from_json(json: serde_json::Value) -> Result<Self> {
        // Check if this is a Swagger 2.0 spec and convert if necessary
        let (raw_document, spec) = if swagger_convert::is_swagger_2(&json) {
            let converted = swagger_convert::convert_swagger_to_openapi3(&json).map_err(|e| {
                Error::config(format!("Failed to convert Swagger 2.0 to OpenAPI 3.0: {}", e))
            })?;
            let spec: OpenAPI = serde_json::from_value(converted.clone()).map_err(|e| {
                Error::config(format!("Failed to parse converted OpenAPI spec: {}", e))
            })?;
            (converted, spec)
        } else {
            let json_for_doc = json.clone();
            let spec: OpenAPI = serde_json::from_value(json)
                .map_err(|e| Error::config(format!("Failed to parse JSON OpenAPI spec: {}", e)))?;
            (json_for_doc, spec)
        };

        Ok(Self {
            spec,
            file_path: None,
            raw_document: Some(raw_document),
        })
    }

    /// Validate the OpenAPI specification
    ///
    /// This method provides basic validation. For comprehensive validation
    /// with detailed error messages, use `spec_parser::OpenApiValidator::validate()`.
    pub fn validate(&self) -> Result<()> {
        // Basic validation - check that we have at least one path
        if self.spec.paths.paths.is_empty() {
            return Err(Error::validation("OpenAPI spec must contain at least one path"));
        }

        // Check that info section has required fields
        if self.spec.info.title.is_empty() {
            return Err(Error::validation("OpenAPI spec info must have a title"));
        }

        if self.spec.info.version.is_empty() {
            return Err(Error::validation("OpenAPI spec info must have a version"));
        }

        Ok(())
    }

    /// Enhanced validation with detailed error reporting
    pub fn validate_enhanced(&self) -> crate::spec_parser::ValidationResult {
        // Convert to JSON value for enhanced validator
        if let Some(raw) = &self.raw_document {
            let format = if raw.get("swagger").is_some() {
                crate::spec_parser::SpecFormat::OpenApi20
            } else if let Some(version) = raw.get("openapi").and_then(|v| v.as_str()) {
                if version.starts_with("3.1") {
                    crate::spec_parser::SpecFormat::OpenApi31
                } else {
                    crate::spec_parser::SpecFormat::OpenApi30
                }
            } else {
                // Default to 3.0 if we can't determine
                crate::spec_parser::SpecFormat::OpenApi30
            };
            crate::spec_parser::OpenApiValidator::validate(raw, format)
        } else {
            // Fallback to basic validation if no raw document
            crate::spec_parser::ValidationResult::failure(vec![
                crate::spec_parser::ValidationError::new(
                    "Cannot perform enhanced validation without raw document".to_string(),
                ),
            ])
        }
    }

    /// Get the OpenAPI version
    pub fn version(&self) -> &str {
        &self.spec.openapi
    }

    /// Get the API title
    pub fn title(&self) -> &str {
        &self.spec.info.title
    }

    /// Get the API description
    pub fn description(&self) -> Option<&str> {
        self.spec.info.description.as_deref()
    }

    /// Get the API version
    pub fn api_version(&self) -> &str {
        &self.spec.info.version
    }

    /// Get the server URLs
    pub fn servers(&self) -> &[openapiv3::Server] {
        &self.spec.servers
    }

    /// Get all paths defined in the spec
    pub fn paths(&self) -> &openapiv3::Paths {
        &self.spec.paths
    }

    /// Get all schemas defined in the spec
    pub fn schemas(&self) -> Option<&indexmap::IndexMap<String, ReferenceOr<Schema>>> {
        self.spec.components.as_ref().map(|c| &c.schemas)
    }

    /// Get all security schemes defined in the spec
    pub fn security_schemes(
        &self,
    ) -> Option<&indexmap::IndexMap<String, ReferenceOr<openapiv3::SecurityScheme>>> {
        self.spec.components.as_ref().map(|c| &c.security_schemes)
    }

    /// Get all operations for a given path
    pub fn operations_for_path(
        &self,
        path: &str,
    ) -> std::collections::HashMap<String, openapiv3::Operation> {
        let mut operations = std::collections::HashMap::new();

        if let Some(path_item_ref) = self.spec.paths.paths.get(path) {
            // Handle the ReferenceOr<PathItem> case
            if let Some(path_item) = path_item_ref.as_item() {
                // Round 40 (#888 / #79) — Srikanth's Google Apigee
                // spec puts the shared auth / format query
                // parameters at PATH level, not on each operation.
                // OpenAPI 3.0 §4.7.10.1: "Parameters that are
                // included in the Operation Object inherit the
                // parameters defined in the Path Item Object. If a
                // parameter is already defined at the Path Item, the
                // new definition will override it but can never
                // remove it." We materialise that inheritance HERE
                // (the lowest common point under both registry
                // builders), so a request that violates a path-level
                // `enum` or `type: boolean` reaches the validator's
                // parameter loop instead of silently passing. We
                // also resolve `$ref` parameters via
                // `components.parameters` so the validator's loop
                // (which skips `ReferenceOr::Reference` entries via
                // `as_item()`) actually sees them.
                let resolved_path_params: Vec<ReferenceOr<openapiv3::Parameter>> =
                    path_item.parameters.iter().map(|p| self.resolve_parameter_ref(p)).collect();
                let merge = |op: &openapiv3::Operation| -> openapiv3::Operation {
                    // Resolve op-level refs too — same as path-level.
                    let mut resolved_op = op.clone();
                    resolved_op.parameters =
                        op.parameters.iter().map(|p| self.resolve_parameter_ref(p)).collect();
                    merge_path_params_into_operation(&resolved_op, &resolved_path_params)
                };
                if let Some(op) = &path_item.get {
                    operations.insert("GET".to_string(), merge(op));
                }
                if let Some(op) = &path_item.post {
                    operations.insert("POST".to_string(), merge(op));
                }
                if let Some(op) = &path_item.put {
                    operations.insert("PUT".to_string(), merge(op));
                }
                if let Some(op) = &path_item.delete {
                    operations.insert("DELETE".to_string(), merge(op));
                }
                if let Some(op) = &path_item.patch {
                    operations.insert("PATCH".to_string(), merge(op));
                }
                if let Some(op) = &path_item.head {
                    operations.insert("HEAD".to_string(), merge(op));
                }
                if let Some(op) = &path_item.options {
                    operations.insert("OPTIONS".to_string(), merge(op));
                }
                if let Some(op) = &path_item.trace {
                    operations.insert("TRACE".to_string(), merge(op));
                }
            }
        }

        operations
    }

    /// Get all paths with their operations
    pub fn all_paths_and_operations(
        &self,
    ) -> std::collections::HashMap<String, std::collections::HashMap<String, openapiv3::Operation>>
    {
        self.spec
            .paths
            .paths
            .iter()
            .map(|(path, _)| (path.clone(), self.operations_for_path(path)))
            .collect()
    }

    /// Get a schema by reference (returns wrapped OpenApiSchema)
    pub fn get_schema(&self, reference: &str) -> Option<crate::schema::OpenApiSchema> {
        self.resolve_schema(reference).map(crate::schema::OpenApiSchema::new)
    }

    /// Resolve a schema reference to the raw Schema
    ///
    /// This resolves `$ref` references like `#/components/schemas/User` to the
    /// actual schema definition, handling nested references recursively.
    pub fn resolve_schema_ref(&self, reference: &str) -> Option<Schema> {
        self.resolve_schema(reference)
    }

    /// Round 40 (#888 / #79) — resolve a parameter `$ref` (typically
    /// `#/components/parameters/foo`) into the inline `Parameter`
    /// item it points at. Returns the input unchanged when the
    /// reference can't be resolved (e.g. external `$ref`) so the
    /// validator can fall back to its prior behaviour (skip via
    /// `as_item()`) instead of panicking. Used by
    /// `operations_for_path` to materialise refs at registry build
    /// time, since the validator's parameter loop skips
    /// `ReferenceOr::Reference` entries — which was why Srikanth's
    /// Google Apigee spec silently passed every path-level param
    /// violation: the path-level `parameters:` list is entirely
    /// `$ref:` to shared common params like `_.xgafv`,
    /// `prettyPrint`, etc.
    pub fn resolve_parameter_ref(
        &self,
        p_ref: &ReferenceOr<openapiv3::Parameter>,
    ) -> ReferenceOr<openapiv3::Parameter> {
        match p_ref {
            ReferenceOr::Item(_) => p_ref.clone(),
            ReferenceOr::Reference { reference } => {
                let Some(name) = reference.strip_prefix("#/components/parameters/") else {
                    return p_ref.clone();
                };
                let Some(components) = self.spec.components.as_ref() else {
                    return p_ref.clone();
                };
                match components.parameters.get(name) {
                    Some(ReferenceOr::Item(p)) => ReferenceOr::Item(p.clone()),
                    Some(ReferenceOr::Reference { reference: nested }) => {
                        // Tail-resolve a chained ref (rare in practice
                        // but allowed by the spec).
                        let Some(nested_name) = nested.strip_prefix("#/components/parameters/")
                        else {
                            return p_ref.clone();
                        };
                        match components.parameters.get(nested_name) {
                            Some(ReferenceOr::Item(p)) => ReferenceOr::Item(p.clone()),
                            _ => p_ref.clone(),
                        }
                    }
                    None => p_ref.clone(),
                }
            }
        }
    }

    /// Validate security requirements
    pub fn validate_security_requirements(
        &self,
        security_requirements: &[openapiv3::SecurityRequirement],
        auth_header: Option<&str>,
        api_key: Option<&str>,
    ) -> Result<()> {
        if security_requirements.is_empty() {
            return Ok(());
        }

        // Security requirements are OR'd - if any requirement is satisfied, pass
        for requirement in security_requirements {
            if self.is_security_requirement_satisfied(requirement, auth_header, api_key)? {
                return Ok(());
            }
        }

        Err(Error::validation(
            "Security validation failed: no valid authentication provided",
        ))
    }

    fn resolve_schema(&self, reference: &str) -> Option<Schema> {
        let mut visited = HashSet::new();
        self.resolve_schema_recursive(reference, &mut visited)
    }

    fn resolve_schema_recursive(
        &self,
        reference: &str,
        visited: &mut HashSet<String>,
    ) -> Option<Schema> {
        if !visited.insert(reference.to_string()) {
            tracing::warn!("Detected recursive schema reference: {}", reference);
            return None;
        }

        let schema_name = reference.strip_prefix("#/components/schemas/")?;
        let components = self.spec.components.as_ref()?;
        let schema_ref = components.schemas.get(schema_name)?;

        match schema_ref {
            ReferenceOr::Item(schema) => Some(schema.clone()),
            ReferenceOr::Reference { reference: nested } => {
                self.resolve_schema_recursive(nested, visited)
            }
        }
    }

    /// Check if a single security requirement is satisfied
    fn is_security_requirement_satisfied(
        &self,
        requirement: &openapiv3::SecurityRequirement,
        auth_header: Option<&str>,
        api_key: Option<&str>,
    ) -> Result<bool> {
        // All schemes in the requirement must be satisfied (AND)
        for (scheme_name, _scopes) in requirement {
            if !self.is_security_scheme_satisfied(scheme_name, auth_header, api_key)? {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Check if a security scheme is satisfied
    fn is_security_scheme_satisfied(
        &self,
        scheme_name: &str,
        auth_header: Option<&str>,
        api_key: Option<&str>,
    ) -> Result<bool> {
        let security_schemes = match self.security_schemes() {
            Some(schemes) => schemes,
            None => return Ok(false),
        };

        let scheme = match security_schemes.get(scheme_name) {
            Some(scheme) => scheme,
            None => {
                return Err(Error::config(format!("Security scheme '{}' not found", scheme_name)))
            }
        };

        let scheme = match scheme {
            ReferenceOr::Item(s) => s,
            ReferenceOr::Reference { reference } => {
                // Resolve $ref like "#/components/securitySchemes/BearerAuth"
                let ref_name =
                    reference.strip_prefix("#/components/securitySchemes/").ok_or_else(|| {
                        Error::config(format!(
                            "Unsupported security scheme reference format: {}",
                            reference
                        ))
                    })?;
                match security_schemes.get(ref_name) {
                    Some(ReferenceOr::Item(resolved)) => resolved,
                    Some(ReferenceOr::Reference { .. }) => {
                        return Err(Error::config(format!(
                            "Nested security scheme reference not supported: {}",
                            ref_name
                        )))
                    }
                    None => {
                        return Err(Error::config(format!(
                            "Security scheme '{}' not found",
                            ref_name
                        )))
                    }
                }
            }
        };

        match scheme {
            openapiv3::SecurityScheme::HTTP { scheme, .. } => {
                match scheme.as_str() {
                    "bearer" => match auth_header {
                        Some(header) if header.starts_with("Bearer ") => Ok(true),
                        _ => Ok(false),
                    },
                    "basic" => match auth_header {
                        Some(header) if header.starts_with("Basic ") => Ok(true),
                        _ => Ok(false),
                    },
                    _ => Ok(false), // Unsupported scheme
                }
            }
            openapiv3::SecurityScheme::APIKey { location, .. } => match location {
                openapiv3::APIKeyLocation::Header => Ok(auth_header.is_some()),
                openapiv3::APIKeyLocation::Query => Ok(api_key.is_some()),
                openapiv3::APIKeyLocation::Cookie => Ok(api_key.is_some()),
            },
            openapiv3::SecurityScheme::OpenIDConnect { .. } => {
                // OpenID Connect uses Bearer tokens, same as OAuth2
                match auth_header {
                    Some(header) if header.starts_with("Bearer ") => Ok(true),
                    _ => Ok(false),
                }
            }
            openapiv3::SecurityScheme::OAuth2 { .. } => {
                // For OAuth2, check if Bearer token is provided
                match auth_header {
                    Some(header) if header.starts_with("Bearer ") => Ok(true),
                    _ => Ok(false),
                }
            }
        }
    }

    /// Get global security requirements
    pub fn get_global_security_requirements(&self) -> Vec<openapiv3::SecurityRequirement> {
        self.spec.security.clone().unwrap_or_default()
    }

    /// Resolve a request body reference
    pub fn get_request_body(&self, reference: &str) -> Option<&openapiv3::RequestBody> {
        if let Some(components) = &self.spec.components {
            if let Some(param_name) = reference.strip_prefix("#/components/requestBodies/") {
                if let Some(request_body_ref) = components.request_bodies.get(param_name) {
                    return request_body_ref.as_item();
                }
            }
        }
        None
    }

    /// Resolve a response reference
    pub fn get_response(&self, reference: &str) -> Option<&openapiv3::Response> {
        if let Some(components) = &self.spec.components {
            if let Some(response_name) = reference.strip_prefix("#/components/responses/") {
                if let Some(response_ref) = components.responses.get(response_name) {
                    return response_ref.as_item();
                }
            }
        }
        None
    }

    /// Resolve an example reference
    pub fn get_example(&self, reference: &str) -> Option<&openapiv3::Example> {
        if let Some(components) = &self.spec.components {
            if let Some(example_name) = reference.strip_prefix("#/components/examples/") {
                if let Some(example_ref) = components.examples.get(example_name) {
                    return example_ref.as_item();
                }
            }
        }
        None
    }
}

/// Round 40 (#888 / #79) — merge path-level parameters from a
/// `PathItem` into an `Operation`'s own parameters per OpenAPI 3.0
/// §4.7.10.1. Returns a cloned `Operation` whose `parameters` list
/// contains every path-level entry, followed by every operation-level
/// entry, with collisions on `(name, in)` resolved in favour of the
/// operation-level definition. The original `Operation` is not
/// mutated. Lives in `spec.rs` so every registry builder that calls
/// `operations_for_path` benefits from the merge automatically.
pub(crate) fn merge_path_params_into_operation(
    operation: &openapiv3::Operation,
    path_level_params: &[ReferenceOr<openapiv3::Parameter>],
) -> openapiv3::Operation {
    use std::collections::HashSet;
    if path_level_params.is_empty() {
        return operation.clone();
    }
    let mut op_keys: HashSet<(String, String)> = HashSet::new();
    for p_ref in &operation.parameters {
        if let Some(key) = parameter_key(p_ref) {
            op_keys.insert(key);
        }
    }
    let mut merged: Vec<ReferenceOr<openapiv3::Parameter>> =
        Vec::with_capacity(path_level_params.len() + operation.parameters.len());
    for p_ref in path_level_params {
        match parameter_key(p_ref) {
            Some(key) if op_keys.contains(&key) => {}
            _ => merged.push(p_ref.clone()),
        }
    }
    merged.extend(operation.parameters.iter().cloned());
    let mut cloned = operation.clone();
    cloned.parameters = merged;
    cloned
}

fn parameter_key(p_ref: &ReferenceOr<openapiv3::Parameter>) -> Option<(String, String)> {
    let p = p_ref.as_item()?;
    let (name, in_loc) = match p {
        openapiv3::Parameter::Path { parameter_data, .. } => (parameter_data.name.clone(), "path"),
        openapiv3::Parameter::Query { parameter_data, .. } => {
            (parameter_data.name.clone(), "query")
        }
        openapiv3::Parameter::Header { parameter_data, .. } => {
            (parameter_data.name.clone(), "header")
        }
        openapiv3::Parameter::Cookie { parameter_data, .. } => {
            (parameter_data.name.clone(), "cookie")
        }
    };
    Some((name, in_loc.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use openapiv3::{SchemaKind, Type};

    #[test]
    fn resolves_security_scheme_ref() {
        let yaml = r#"
openapi: 3.0.3
info:
  title: Test API
  version: "1.0.0"
paths:
  /test:
    get:
      security:
        - BearerRef: []
      responses:
        '200':
          description: OK
components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
    BearerRef:
      $ref: '#/components/securitySchemes/BearerAuth'
        "#;

        let spec = OpenApiSpec::from_string(yaml, Some("yaml")).expect("spec parses");

        // Bearer token should satisfy the referenced scheme
        let result = spec
            .is_security_scheme_satisfied("BearerRef", Some("Bearer token123"), None)
            .expect("should resolve ref");
        assert!(result);

        // Missing token should fail
        let result = spec
            .is_security_scheme_satisfied("BearerRef", None, None)
            .expect("should resolve ref");
        assert!(!result);
    }

    #[test]
    fn resolves_nested_schema_references() {
        let yaml = r#"
openapi: 3.0.3
info:
  title: Test API
  version: "1.0.0"
paths: {}
components:
  schemas:
    Apiary:
      type: object
      properties:
        id:
          type: string
        hive:
          $ref: '#/components/schemas/Hive'
    Hive:
      type: object
      properties:
        name:
          type: string
    HiveWrapper:
      $ref: '#/components/schemas/Hive'
        "#;

        let spec = OpenApiSpec::from_string(yaml, Some("yaml")).expect("spec parses");

        let apiary = spec.get_schema("#/components/schemas/Apiary").expect("resolve apiary schema");
        assert!(matches!(apiary.schema.schema_kind, SchemaKind::Type(Type::Object(_))));

        let wrapper = spec
            .get_schema("#/components/schemas/HiveWrapper")
            .expect("resolve wrapper schema");
        assert!(matches!(wrapper.schema.schema_kind, SchemaKind::Type(Type::Object(_))));
    }
}

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

    /// A proxy-generated spec with no `responses` on its operations must load.
    /// Reported on #79: 63 of 70 operations lacked the field and the whole run
    /// aborted with `missing field \`responses\``.
    #[test]
    fn spec_without_operation_responses_loads() {
        let raw = r#"{
            "openapi": "3.0.0",
            "info": { "title": "proxy-generated", "version": "1.0.0" },
            "paths": {
                "/orders": {
                    "get": { "summary": "list" },
                    "post": {
                        "summary": "create",
                        "requestBody": {
                            "content": { "application/json": { "schema": { "type": "object" } } }
                        }
                    }
                }
            }
        }"#;

        let spec = OpenApiSpec::from_string(raw, Some("json"))
            .expect("a spec missing `responses` should still load for bench/load use");

        let item = spec.spec.paths.paths.get("/orders").expect("path present");
        let ReferenceOr::Item(item) = item else {
            panic!("expected inline path item");
        };
        assert!(item.get.is_some(), "GET survived the repair");
        assert!(item.post.is_some(), "POST survived the repair");
        assert!(
            item.post.as_ref().unwrap().request_body.is_some(),
            "requestBody must be preserved — it is what request generation actually reads"
        );
    }

    /// The repair must only add the mandatory field, never touch a spec that
    /// already declares responses.
    #[test]
    fn existing_responses_are_left_alone() {
        let mut raw: serde_json::Value = serde_json::from_str(
            r#"{"paths": {"/a": {"get": {"responses": {"200": {"description": "ok"}}}}}}"#,
        )
        .unwrap();
        let before = raw.clone();
        assert_eq!(fill_missing_operation_responses(&mut raw), 0);
        assert_eq!(raw, before, "a conformant spec must be byte-identical after the pass");
    }

    /// Non-operation keys under a path item (parameters, servers, $ref) must not
    /// be mistaken for operations.
    #[test]
    fn non_operation_keys_are_not_touched() {
        let mut raw: serde_json::Value = serde_json::from_str(
            r#"{"paths": {"/a": {"parameters": [], "servers": [], "get": {}}}}"#,
        )
        .unwrap();
        assert_eq!(fill_missing_operation_responses(&mut raw), 1, "only `get` is an operation");
        let path = &raw["paths"]["/a"];
        assert!(path["parameters"].is_array(), "parameters untouched");
        assert!(path["servers"].is_array(), "servers untouched");
        assert!(path["get"]["responses"].is_object(), "get repaired");
    }
}