-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathvalidateDoc.swift
More file actions
321 lines (304 loc) · 15.2 KB
/
validateDoc.swift
File metadata and controls
321 lines (304 loc) · 15.2 KB
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftOpenAPIGenerator open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import OpenAPIKit
/// Validates all content types from an OpenAPI document represented by a ParsedOpenAPIRepresentation.
///
/// This function iterates through the paths, endpoints, and components of the OpenAPI document,
/// checking and reporting any invalid content types using the provided validation closure.
///
/// - Parameters:
/// - doc: The OpenAPI document representation.
/// - validate: A closure to validate each content type.
/// - Throws: An error with diagnostic information if any invalid content types are found.
func validateContentTypes(in doc: ParsedOpenAPIRepresentation, validate: (String) -> Bool) throws {
for (path, pathValue) in doc.paths {
guard let pathItem = pathValue.pathItemValue else { continue }
for endpoint in pathItem.endpoints {
if let eitherRequest = endpoint.operation.requestBody {
if let actualRequest = eitherRequest.requestValue {
for contentType in actualRequest.content.keys {
if !validate(contentType.rawValue) {
throw Diagnostic.error(
message: "Invalid content type string.",
context: [
"contentType": contentType.rawValue,
"location": "\(path.rawValue)/\(endpoint.method.rawValue)/requestBody",
"recoverySuggestion":
"Must have 2 components separated by a slash '<type>/<subtype>'.",
]
)
}
}
}
}
for eitherResponse in endpoint.operation.responses.values {
if let actualResponse = eitherResponse.responseValue {
for contentType in actualResponse.content.keys {
if !validate(contentType.rawValue) {
throw Diagnostic.error(
message: "Invalid content type string.",
context: [
"contentType": contentType.rawValue,
"location": "\(path.rawValue)/\(endpoint.method.rawValue)/responses",
"recoverySuggestion":
"Must have 2 components separated by a slash '<type>/<subtype>'.",
]
)
}
}
}
}
}
}
for (key, component) in doc.components.requestBodies {
let component = try doc.components.assumeLookupOnce(component)
for contentType in component.content.keys {
if !validate(contentType.rawValue) {
throw Diagnostic.error(
message: "Invalid content type string.",
context: [
"contentType": contentType.rawValue, "location": "#/components/requestBodies/\(key.rawValue)",
"recoverySuggestion": "Must have 2 components separated by a slash '<type>/<subtype>'.",
]
)
}
}
}
for (key, component) in doc.components.responses {
let component = try doc.components.assumeLookupOnce(component)
for contentType in component.content.keys {
if !validate(contentType.rawValue) {
throw Diagnostic.error(
message: "Invalid content type string.",
context: [
"contentType": contentType.rawValue, "location": "#/components/responses/\(key.rawValue)",
"recoverySuggestion": "Must have 2 components separated by a slash '<type>/<subtype>'.",
]
)
}
}
}
}
/// Validates all references from an OpenAPI document represented by a ParsedOpenAPIRepresentation against its components.
///
/// This method traverses the OpenAPI document to ensure that all references
/// within the document are valid and point to existing components.
///
/// - Parameter doc: The OpenAPI document to validate.
/// - Throws: `Diagnostic.error` if an external reference is found or a reference is not found in components.
func validateReferences(in doc: ParsedOpenAPIRepresentation) throws {
func validateReference<ReferenceType: ComponentDictionaryLocatable>(
_ reference: OpenAPI.Reference<ReferenceType>,
in components: OpenAPI.Components,
location: String
) throws {
if reference.isExternal {
throw Diagnostic.error(
message: "External references are not suppported.",
context: ["reference": reference.absoluteString, "location": location]
)
}
if components[reference] == nil {
throw Diagnostic.error(
message: "Reference not found in components.",
context: ["reference": reference.absoluteString, "location": location]
)
}
}
func validateReferencesInContentTypes(_ content: OpenAPI.Content.Map, location: String) throws {
for (contentKey, contentType) in content {
switch contentType {
case .a(let ref):
try validateReference(
ref,
in: doc.components,
location: location + "/content/\(contentKey.rawValue)"
)
case .b(let contentType):
if let reference: JSONReference<JSONSchema> = contentType.schema?.reference {
try validateReference(
.init(reference),
in: doc.components,
location: location + "/content/\(contentKey.rawValue)/schema"
)
}
if let eitherExamples = contentType.examples?.values {
for example in eitherExamples {
if let reference = example.reference {
try validateReference(
reference,
in: doc.components,
location: location + "/content/\(contentKey.rawValue)/examples"
)
}
}
}
}
}
}
for (key, value) in doc.webhooks {
if let reference = value.reference { try validateReference(reference, in: doc.components, location: key) }
}
for (path, pathValue) in doc.paths {
if let reference = pathValue.reference {
try validateReference(reference, in: doc.components, location: path.rawValue)
} else if let pathItem = pathValue.pathItemValue {
for endpoint in pathItem.endpoints {
for (endpointKey, endpointValue) in endpoint.operation.callbacks {
if let reference = endpointValue.reference {
try validateReference(
reference,
in: doc.components,
location: "\(path.rawValue)/\(endpoint.method.rawValue)/callbacks/\(endpointKey)"
)
}
}
for eitherParameter in endpoint.operation.parameters {
if let reference = eitherParameter.reference {
try validateReference(
reference,
in: doc.components,
location: "\(path.rawValue)/\(endpoint.method.rawValue)/parameters"
)
} else if let parameter = eitherParameter.parameterValue {
if let reference = parameter.schemaOrContent.schemaReference {
try validateReference(
reference,
in: doc.components,
location: "\(path.rawValue)/\(endpoint.method.rawValue)/parameters/\(parameter.name)"
)
} else if let content = parameter.schemaOrContent.contentValue {
try validateReferencesInContentTypes(
content,
location: "\(path.rawValue)/\(endpoint.method.rawValue)/parameters/\(parameter.name)"
)
}
}
}
if let reference = endpoint.operation.requestBody?.reference {
try validateReference(
reference,
in: doc.components,
location: "\(path.rawValue)/\(endpoint.method.rawValue)/requestBody"
)
} else if let requestBodyValue = endpoint.operation.requestBody?.requestValue {
try validateReferencesInContentTypes(
requestBodyValue.content,
location: "\(path.rawValue)/\(endpoint.method.rawValue)/requestBody"
)
}
for (statusCode, eitherResponse) in endpoint.operation.responses {
if let reference = eitherResponse.reference {
try validateReference(
reference,
in: doc.components,
location: "\(path.rawValue)/\(endpoint.method.rawValue)/responses/\(statusCode.rawValue)"
)
} else if let responseValue = eitherResponse.responseValue {
try validateReferencesInContentTypes(
responseValue.content,
location: "\(path.rawValue)/\(endpoint.method.rawValue)/responses/\(statusCode.rawValue)"
)
}
if let headers = eitherResponse.responseValue?.headers {
for (headerKey, eitherHeader) in headers {
if let reference = eitherHeader.reference {
try validateReference(
reference,
in: doc.components,
location:
"\(path.rawValue)/\(endpoint.method.rawValue)/responses/\(statusCode.rawValue)/headers/\(headerKey)"
)
} else if let headerValue = eitherHeader.headerValue {
if let schemaReference = headerValue.schemaOrContent.schemaReference {
try validateReference(
schemaReference,
in: doc.components,
location:
"\(path.rawValue)/\(endpoint.method.rawValue)/responses/\(statusCode.rawValue)/headers/\(headerKey)"
)
} else if let contentValue = headerValue.schemaOrContent.contentValue {
try validateReferencesInContentTypes(
contentValue,
location:
"\(path.rawValue)/\(endpoint.method.rawValue)/responses/\(statusCode.rawValue)/headers/\(headerKey)"
)
}
}
}
}
}
}
for eitherParameter in pathItem.parameters {
if let reference = eitherParameter.reference {
try validateReference(reference, in: doc.components, location: "\(path.rawValue)/parameters")
}
}
}
}
}
/// Validates all type overrides from a Config are present in the components of a ParsedOpenAPIRepresentation.
///
/// This method iterates through the type overrides defined in the config and checks that for each of them a named schema is defined in the OpenAPI document.
///
/// - Parameters:
/// - doc: The OpenAPI document to validate.
/// - config: The generator config.
/// - Returns: An array of diagnostic messages representing type overrides for nonexistent schemas.
func validateTypeOverrides(_ doc: ParsedOpenAPIRepresentation, config: Config) -> [Diagnostic] {
let nonExistentOverrides = config.typeOverrides.schemas.keys
.filter { key in
guard let componentKey = OpenAPI.ComponentKey(rawValue: key) else { return false }
return !doc.components.schemas.contains(key: componentKey)
}
.sorted()
return nonExistentOverrides.map { override in
Diagnostic.warning(
message: "A type override defined for schema '\(override)' is not defined in the OpenAPI document."
)
}
}
/// Runs validation steps on the incoming OpenAPI document.
/// - Parameters:
/// - doc: The OpenAPI document to validate.
/// - config: The generator config.
/// - Returns: An array of diagnostic messages representing validation warnings.
/// - Throws: An error if a fatal issue is found.
func validateDoc(_ doc: ParsedOpenAPIRepresentation, config: Config) throws -> [Diagnostic] {
try validateReferences(in: doc)
try validateContentTypes(in: doc) { contentType in
(try? _OpenAPIGeneratorCore.ContentType(string: contentType)) != nil
}
let typeOverrideDiagnostics = validateTypeOverrides(doc, config: config)
// Run OpenAPIKit's built-in validation.
// Pass `false` to `strict`, however, because we don't
// want to turn schema loading warnings into errors.
// We already propagate the warnings to the generator's
// diagnostics, so they get surfaced to the user.
// But the warnings are often too strict and should not
// block the generator from running.
// Validation errors continue to be fatal, such as
// structural issues, like non-unique operationIds, etc.
let warnings = try doc.validate(using: Validator().validating(.operationsContainResponses), strict: false)
let diagnostics: [Diagnostic] = warnings.map { warning in
.warning(
message: "Validation warning: \(warning.description)",
context: [
"codingPath": warning.codingPathString ?? "<none>", "contextString": warning.contextString ?? "<none>",
"subjectName": warning.subjectName ?? "<none>",
]
)
}
return typeOverrideDiagnostics + diagnostics
}