mockforge_core/openapi/
spec.rs

1//! OpenAPI specification loading and parsing
2//!
3//! This module handles loading OpenAPI specifications from files,
4//! parsing them, and providing basic operations on the specs.
5//! It also supports Swagger 2.0 specifications by converting them
6//! to OpenAPI 3.0 format automatically.
7
8use crate::openapi::swagger_convert;
9use crate::{Error, Result};
10use openapiv3::{OpenAPI, ReferenceOr, Schema};
11use std::collections::HashSet;
12use std::path::Path;
13use tokio::fs;
14use tracing;
15
16/// OpenAPI specification loader and parser
17#[derive(Debug, Clone)]
18pub struct OpenApiSpec {
19    /// The parsed OpenAPI specification
20    pub spec: OpenAPI,
21    /// Path to the original spec file
22    pub file_path: Option<String>,
23    /// Raw OpenAPI document preserved as JSON for resolving unsupported constructs
24    pub raw_document: Option<serde_json::Value>,
25}
26
27impl OpenApiSpec {
28    /// Load OpenAPI spec from a file path
29    ///
30    /// Supports both OpenAPI 3.x and Swagger 2.0 specifications.
31    /// Swagger 2.0 specs are automatically converted to OpenAPI 3.0 format.
32    pub async fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
33        let path_ref = path.as_ref();
34        let content = fs::read_to_string(path_ref)
35            .await
36            .map_err(|e| Error::generic(format!("Failed to read OpenAPI spec file: {}", e)))?;
37
38        let raw_json = if path_ref.extension().and_then(|s| s.to_str()) == Some("yaml")
39            || path_ref.extension().and_then(|s| s.to_str()) == Some("yml")
40        {
41            let yaml_value: serde_yaml::Value = serde_yaml::from_str(&content)
42                .map_err(|e| Error::generic(format!("Failed to parse YAML OpenAPI spec: {}", e)))?;
43            serde_json::to_value(&yaml_value).map_err(|e| {
44                Error::generic(format!("Failed to convert YAML OpenAPI spec to JSON: {}", e))
45            })?
46        } else {
47            serde_json::from_str(&content)
48                .map_err(|e| Error::generic(format!("Failed to parse JSON OpenAPI spec: {}", e)))?
49        };
50
51        // Check if this is a Swagger 2.0 spec and convert if necessary
52        let (raw_document, spec) = if swagger_convert::is_swagger_2(&raw_json) {
53            tracing::info!("Detected Swagger 2.0 specification, converting to OpenAPI 3.0");
54            let converted =
55                swagger_convert::convert_swagger_to_openapi3(&raw_json).map_err(|e| {
56                    Error::generic(format!("Failed to convert Swagger 2.0 to OpenAPI 3.0: {}", e))
57                })?;
58            let spec: OpenAPI = serde_json::from_value(converted.clone()).map_err(|e| {
59                Error::generic(format!("Failed to parse converted OpenAPI spec: {}", e))
60            })?;
61            (converted, spec)
62        } else {
63            let spec: OpenAPI = serde_json::from_value(raw_json.clone()).map_err(|e| {
64                // Enhanced error reporting for debugging missing field errors
65                let error_str = format!("{}", e);
66                let mut error_msg = format!("Failed to read OpenAPI spec: {}", e);
67
68                // If it's a missing field error, add diagnostic information
69                if error_str.contains("missing field") {
70                    tracing::error!("OpenAPI deserialization error: {}", error_str);
71
72                    // Add context about the spec structure
73                    if let Some(info) = raw_json.get("info") {
74                        if let Some(info_obj) = info.as_object() {
75                            let has_desc = info_obj.contains_key("description");
76                            error_msg
77                                .push_str(&format!(" | Info.description present: {}", has_desc));
78                        }
79                    }
80                    if let Some(servers) = raw_json.get("servers") {
81                        if let Some(servers_arr) = servers.as_array() {
82                            error_msg.push_str(&format!(" | Servers count: {}", servers_arr.len()));
83                        }
84                    }
85                }
86
87                Error::generic(error_msg)
88            })?;
89            (raw_json, spec)
90        };
91
92        Ok(Self {
93            spec,
94            file_path: path_ref.to_str().map(|s| s.to_string()),
95            raw_document: Some(raw_document),
96        })
97    }
98
99    /// Load OpenAPI spec from string content
100    ///
101    /// Supports both OpenAPI 3.x and Swagger 2.0 specifications.
102    /// Swagger 2.0 specs are automatically converted to OpenAPI 3.0 format.
103    pub fn from_string(content: &str, format: Option<&str>) -> Result<Self> {
104        let raw_json = if format == Some("yaml") || format == Some("yml") {
105            let yaml_value: serde_yaml::Value = serde_yaml::from_str(content)
106                .map_err(|e| Error::generic(format!("Failed to parse YAML OpenAPI spec: {}", e)))?;
107            serde_json::to_value(&yaml_value).map_err(|e| {
108                Error::generic(format!("Failed to convert YAML OpenAPI spec to JSON: {}", e))
109            })?
110        } else {
111            serde_json::from_str(content)
112                .map_err(|e| Error::generic(format!("Failed to parse JSON OpenAPI spec: {}", e)))?
113        };
114
115        // Check if this is a Swagger 2.0 spec and convert if necessary
116        let (raw_document, spec) = if swagger_convert::is_swagger_2(&raw_json) {
117            let converted =
118                swagger_convert::convert_swagger_to_openapi3(&raw_json).map_err(|e| {
119                    Error::generic(format!("Failed to convert Swagger 2.0 to OpenAPI 3.0: {}", e))
120                })?;
121            let spec: OpenAPI = serde_json::from_value(converted.clone()).map_err(|e| {
122                Error::generic(format!("Failed to parse converted OpenAPI spec: {}", e))
123            })?;
124            (converted, spec)
125        } else {
126            let spec: OpenAPI = serde_json::from_value(raw_json.clone())
127                .map_err(|e| Error::generic(format!("Failed to read OpenAPI spec: {}", e)))?;
128            (raw_json, spec)
129        };
130
131        Ok(Self {
132            spec,
133            file_path: None,
134            raw_document: Some(raw_document),
135        })
136    }
137
138    /// Load OpenAPI spec from JSON value
139    ///
140    /// Supports both OpenAPI 3.x and Swagger 2.0 specifications.
141    /// Swagger 2.0 specs are automatically converted to OpenAPI 3.0 format.
142    pub fn from_json(json: serde_json::Value) -> Result<Self> {
143        // Check if this is a Swagger 2.0 spec and convert if necessary
144        let (raw_document, spec) = if swagger_convert::is_swagger_2(&json) {
145            let converted = swagger_convert::convert_swagger_to_openapi3(&json).map_err(|e| {
146                Error::generic(format!("Failed to convert Swagger 2.0 to OpenAPI 3.0: {}", e))
147            })?;
148            let spec: OpenAPI = serde_json::from_value(converted.clone()).map_err(|e| {
149                Error::generic(format!("Failed to parse converted OpenAPI spec: {}", e))
150            })?;
151            (converted, spec)
152        } else {
153            let json_for_doc = json.clone();
154            let spec: OpenAPI = serde_json::from_value(json)
155                .map_err(|e| Error::generic(format!("Failed to parse JSON OpenAPI spec: {}", e)))?;
156            (json_for_doc, spec)
157        };
158
159        Ok(Self {
160            spec,
161            file_path: None,
162            raw_document: Some(raw_document),
163        })
164    }
165
166    /// Validate the OpenAPI specification
167    ///
168    /// This method provides basic validation. For comprehensive validation
169    /// with detailed error messages, use `spec_parser::OpenApiValidator::validate()`.
170    pub fn validate(&self) -> Result<()> {
171        // Basic validation - check that we have at least one path
172        if self.spec.paths.paths.is_empty() {
173            return Err(Error::generic("OpenAPI spec must contain at least one path"));
174        }
175
176        // Check that info section has required fields
177        if self.spec.info.title.is_empty() {
178            return Err(Error::generic("OpenAPI spec info must have a title"));
179        }
180
181        if self.spec.info.version.is_empty() {
182            return Err(Error::generic("OpenAPI spec info must have a version"));
183        }
184
185        Ok(())
186    }
187
188    /// Enhanced validation with detailed error reporting
189    pub fn validate_enhanced(&self) -> crate::spec_parser::ValidationResult {
190        // Convert to JSON value for enhanced validator
191        if let Some(raw) = &self.raw_document {
192            let format = if raw.get("swagger").is_some() {
193                crate::spec_parser::SpecFormat::OpenApi20
194            } else if let Some(version) = raw.get("openapi").and_then(|v| v.as_str()) {
195                if version.starts_with("3.1") {
196                    crate::spec_parser::SpecFormat::OpenApi31
197                } else {
198                    crate::spec_parser::SpecFormat::OpenApi30
199                }
200            } else {
201                // Default to 3.0 if we can't determine
202                crate::spec_parser::SpecFormat::OpenApi30
203            };
204            crate::spec_parser::OpenApiValidator::validate(raw, format)
205        } else {
206            // Fallback to basic validation if no raw document
207            crate::spec_parser::ValidationResult::failure(vec![
208                crate::spec_parser::ValidationError::new(
209                    "Cannot perform enhanced validation without raw document".to_string(),
210                ),
211            ])
212        }
213    }
214
215    /// Get the OpenAPI version
216    pub fn version(&self) -> &str {
217        &self.spec.openapi
218    }
219
220    /// Get the API title
221    pub fn title(&self) -> &str {
222        &self.spec.info.title
223    }
224
225    /// Get the API description
226    pub fn description(&self) -> Option<&str> {
227        self.spec.info.description.as_deref()
228    }
229
230    /// Get the API version
231    pub fn api_version(&self) -> &str {
232        &self.spec.info.version
233    }
234
235    /// Get the server URLs
236    pub fn servers(&self) -> &[openapiv3::Server] {
237        &self.spec.servers
238    }
239
240    /// Get all paths defined in the spec
241    pub fn paths(&self) -> &openapiv3::Paths {
242        &self.spec.paths
243    }
244
245    /// Get all schemas defined in the spec
246    pub fn schemas(
247        &self,
248    ) -> Option<&indexmap::IndexMap<String, openapiv3::ReferenceOr<openapiv3::Schema>>> {
249        self.spec.components.as_ref().map(|c| &c.schemas)
250    }
251
252    /// Get all security schemes defined in the spec
253    pub fn security_schemes(
254        &self,
255    ) -> Option<&indexmap::IndexMap<String, openapiv3::ReferenceOr<openapiv3::SecurityScheme>>>
256    {
257        self.spec.components.as_ref().map(|c| &c.security_schemes)
258    }
259
260    /// Get all operations for a given path
261    pub fn operations_for_path(
262        &self,
263        path: &str,
264    ) -> std::collections::HashMap<String, openapiv3::Operation> {
265        let mut operations = std::collections::HashMap::new();
266
267        if let Some(path_item_ref) = self.spec.paths.paths.get(path) {
268            // Handle the ReferenceOr<PathItem> case
269            if let Some(path_item) = path_item_ref.as_item() {
270                if let Some(op) = &path_item.get {
271                    operations.insert("GET".to_string(), op.clone());
272                }
273                if let Some(op) = &path_item.post {
274                    operations.insert("POST".to_string(), op.clone());
275                }
276                if let Some(op) = &path_item.put {
277                    operations.insert("PUT".to_string(), op.clone());
278                }
279                if let Some(op) = &path_item.delete {
280                    operations.insert("DELETE".to_string(), op.clone());
281                }
282                if let Some(op) = &path_item.patch {
283                    operations.insert("PATCH".to_string(), op.clone());
284                }
285                if let Some(op) = &path_item.head {
286                    operations.insert("HEAD".to_string(), op.clone());
287                }
288                if let Some(op) = &path_item.options {
289                    operations.insert("OPTIONS".to_string(), op.clone());
290                }
291                if let Some(op) = &path_item.trace {
292                    operations.insert("TRACE".to_string(), op.clone());
293                }
294            }
295        }
296
297        operations
298    }
299
300    /// Get all paths with their operations
301    pub fn all_paths_and_operations(
302        &self,
303    ) -> std::collections::HashMap<String, std::collections::HashMap<String, openapiv3::Operation>>
304    {
305        self.spec
306            .paths
307            .paths
308            .iter()
309            .map(|(path, _)| (path.clone(), self.operations_for_path(path)))
310            .collect()
311    }
312
313    /// Get a schema by reference
314    pub fn get_schema(&self, reference: &str) -> Option<crate::openapi::schema::OpenApiSchema> {
315        self.resolve_schema(reference).map(crate::openapi::schema::OpenApiSchema::new)
316    }
317
318    /// Validate security requirements
319    pub fn validate_security_requirements(
320        &self,
321        security_requirements: &[openapiv3::SecurityRequirement],
322        auth_header: Option<&str>,
323        api_key: Option<&str>,
324    ) -> Result<()> {
325        if security_requirements.is_empty() {
326            return Ok(());
327        }
328
329        // Security requirements are OR'd - if any requirement is satisfied, pass
330        for requirement in security_requirements {
331            if self.is_security_requirement_satisfied(requirement, auth_header, api_key)? {
332                return Ok(());
333            }
334        }
335
336        Err(Error::generic("Security validation failed: no valid authentication provided"))
337    }
338
339    fn resolve_schema(&self, reference: &str) -> Option<Schema> {
340        let mut visited = HashSet::new();
341        self.resolve_schema_recursive(reference, &mut visited)
342    }
343
344    fn resolve_schema_recursive(
345        &self,
346        reference: &str,
347        visited: &mut HashSet<String>,
348    ) -> Option<Schema> {
349        if !visited.insert(reference.to_string()) {
350            tracing::warn!("Detected recursive schema reference: {}", reference);
351            return None;
352        }
353
354        let schema_name = reference.strip_prefix("#/components/schemas/")?;
355        let components = self.spec.components.as_ref()?;
356        let schema_ref = components.schemas.get(schema_name)?;
357
358        match schema_ref {
359            ReferenceOr::Item(schema) => Some(schema.clone()),
360            ReferenceOr::Reference { reference: nested } => {
361                self.resolve_schema_recursive(nested, visited)
362            }
363        }
364    }
365
366    /// Check if a single security requirement is satisfied
367    fn is_security_requirement_satisfied(
368        &self,
369        requirement: &openapiv3::SecurityRequirement,
370        auth_header: Option<&str>,
371        api_key: Option<&str>,
372    ) -> Result<bool> {
373        // All schemes in the requirement must be satisfied (AND)
374        for (scheme_name, _scopes) in requirement {
375            if !self.is_security_scheme_satisfied(scheme_name, auth_header, api_key)? {
376                return Ok(false);
377            }
378        }
379        Ok(true)
380    }
381
382    /// Check if a security scheme is satisfied
383    fn is_security_scheme_satisfied(
384        &self,
385        scheme_name: &str,
386        auth_header: Option<&str>,
387        api_key: Option<&str>,
388    ) -> Result<bool> {
389        let security_schemes = match self.security_schemes() {
390            Some(schemes) => schemes,
391            None => return Ok(false),
392        };
393
394        let scheme = match security_schemes.get(scheme_name) {
395            Some(scheme) => scheme,
396            None => {
397                return Err(Error::generic(format!("Security scheme '{}' not found", scheme_name)))
398            }
399        };
400
401        let scheme = match scheme {
402            openapiv3::ReferenceOr::Item(s) => s,
403            openapiv3::ReferenceOr::Reference { .. } => {
404                return Err(Error::generic("Referenced security schemes not supported"))
405            }
406        };
407
408        match scheme {
409            openapiv3::SecurityScheme::HTTP { scheme, .. } => {
410                match scheme.as_str() {
411                    "bearer" => match auth_header {
412                        Some(header) if header.starts_with("Bearer ") => Ok(true),
413                        _ => Ok(false),
414                    },
415                    "basic" => match auth_header {
416                        Some(header) if header.starts_with("Basic ") => Ok(true),
417                        _ => Ok(false),
418                    },
419                    _ => Ok(false), // Unsupported scheme
420                }
421            }
422            openapiv3::SecurityScheme::APIKey { location, .. } => {
423                match location {
424                    openapiv3::APIKeyLocation::Header => Ok(auth_header.is_some()),
425                    openapiv3::APIKeyLocation::Query => Ok(api_key.is_some()),
426                    _ => Ok(false), // Cookie not supported
427                }
428            }
429            openapiv3::SecurityScheme::OpenIDConnect { .. } => Ok(false), // Not implemented
430            openapiv3::SecurityScheme::OAuth2 { .. } => {
431                // For OAuth2, check if Bearer token is provided
432                match auth_header {
433                    Some(header) if header.starts_with("Bearer ") => Ok(true),
434                    _ => Ok(false),
435                }
436            }
437        }
438    }
439
440    /// Get global security requirements
441    pub fn get_global_security_requirements(&self) -> Vec<openapiv3::SecurityRequirement> {
442        self.spec.security.clone().unwrap_or_default()
443    }
444
445    /// Resolve a request body reference
446    pub fn get_request_body(&self, reference: &str) -> Option<&openapiv3::RequestBody> {
447        if let Some(components) = &self.spec.components {
448            if let Some(param_name) = reference.strip_prefix("#/components/requestBodies/") {
449                if let Some(request_body_ref) = components.request_bodies.get(param_name) {
450                    return request_body_ref.as_item();
451                }
452            }
453        }
454        None
455    }
456
457    /// Resolve a response reference
458    pub fn get_response(&self, reference: &str) -> Option<&openapiv3::Response> {
459        if let Some(components) = &self.spec.components {
460            if let Some(response_name) = reference.strip_prefix("#/components/responses/") {
461                if let Some(response_ref) = components.responses.get(response_name) {
462                    return response_ref.as_item();
463                }
464            }
465        }
466        None
467    }
468
469    /// Resolve an example reference
470    pub fn get_example(&self, reference: &str) -> Option<&openapiv3::Example> {
471        if let Some(components) = &self.spec.components {
472            if let Some(example_name) = reference.strip_prefix("#/components/examples/") {
473                if let Some(example_ref) = components.examples.get(example_name) {
474                    return example_ref.as_item();
475                }
476            }
477        }
478        None
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485    use openapiv3::{SchemaKind, Type};
486
487    #[test]
488    fn resolves_nested_schema_references() {
489        let yaml = r#"
490openapi: 3.0.3
491info:
492  title: Test API
493  version: "1.0.0"
494paths: {}
495components:
496  schemas:
497    Apiary:
498      type: object
499      properties:
500        id:
501          type: string
502        hive:
503          $ref: '#/components/schemas/Hive'
504    Hive:
505      type: object
506      properties:
507        name:
508          type: string
509    HiveWrapper:
510      $ref: '#/components/schemas/Hive'
511        "#;
512
513        let spec = OpenApiSpec::from_string(yaml, Some("yaml")).expect("spec parses");
514
515        let apiary = spec.get_schema("#/components/schemas/Apiary").expect("resolve apiary schema");
516        assert!(matches!(apiary.schema.schema_kind, SchemaKind::Type(Type::Object(_))));
517
518        let wrapper = spec
519            .get_schema("#/components/schemas/HiveWrapper")
520            .expect("resolve wrapper schema");
521        assert!(matches!(wrapper.schema.schema_kind, SchemaKind::Type(Type::Object(_))));
522    }
523}