| 1 |
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
package schema_validation |
| 4 |
|
| 5 |
import ( |
| 6 |
"encoding/json" |
| 7 |
"fmt" |
| 8 |
"log/slog" |
| 9 |
"strconv" |
| 10 |
"strings" |
| 11 |
|
| 12 |
"github.com/pb33f/libopenapi/datamodel/high/base" |
| 13 |
|
| 14 |
xj "github.com/basgys/goxml2json" |
| 15 |
|
| 16 |
liberrors "github.com/pb33f/libopenapi-validator/errors" |
| 17 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 18 |
) |
| 19 |
|
| 20 |
func (x *xmlValidator) validateXMLWithVersion(schema *base.Schema, xmlString string, log *slog.Logger, version float32) (bool, []*liberrors.ValidationError) { |
| 21 |
if schema == nil { |
| 22 |
log.Info("schema is empty and cannot be validated") |
| 23 |
return false, nil |
| 24 |
} |
| 25 |
|
| 26 |
// parse xml and transform to json structure matching schema |
| 27 |
transformedJSON, prevalidationErrors := TransformXMLToSchemaJSON(xmlString, schema) |
| 28 |
if len(prevalidationErrors) > 0 { |
| 29 |
return false, prevalidationErrors |
| 30 |
} |
| 31 |
|
| 32 |
// validate transformed json against schema using existing validator |
| 33 |
return x.schemaValidator.validateSchemaWithVersion(schema, nil, transformedJSON, log, version) |
| 34 |
} |
| 35 |
|
| 36 |
// TransformXMLToSchemaJSON converts xml to json structure matching openapi schema. |
| 37 |
// applies xml object transformations: name, attribute, wrapped. |
| 38 |
func TransformXMLToSchemaJSON(xmlString string, schema *base.Schema) (any, []*liberrors.ValidationError) { |
| 39 |
if xmlString == "" { |
| 40 |
return nil, []*liberrors.ValidationError{liberrors.InvalidXMLParsing("empty xml content", xmlString)} |
| 41 |
} |
| 42 |
|
| 43 |
// parse xml using goxml2json. we convert types manually |
| 44 |
jsonBuf, err := xj.Convert(strings.NewReader(xmlString)) |
| 45 |
if err != nil { |
| 46 |
return nil, []*liberrors.ValidationError{liberrors.InvalidXMLParsing(fmt.Sprintf("malformed xml: %s", err.Error()), xmlString)} |
| 47 |
} |
| 48 |
|
| 49 |
jsonBytes := jsonBuf.Bytes() |
| 50 |
|
| 51 |
// the smallest valid XML possible "<a></a>" generates a 10 bytes buffer. |
| 52 |
// any other invalid XML generates a smaller buffer |
| 53 |
if len(jsonBytes) < 10 { |
| 54 |
return nil, []*liberrors.ValidationError{liberrors.InvalidXMLParsing("malformed xml", xmlString)} |
| 55 |
} |
| 56 |
|
| 57 |
var rawJSON any |
| 58 |
if err := json.Unmarshal(jsonBytes, &rawJSON); err != nil { |
| 59 |
return nil, []*liberrors.ValidationError{liberrors.InvalidXMLParsing(fmt.Sprintf("failed to decode converted xml to json: %s", err.Error()), xmlString)} |
| 60 |
} |
| 61 |
|
| 62 |
xmlNsMap := make(map[string]string, 2) |
| 63 |
|
| 64 |
// apply openapi xml object transformations |
| 65 |
return applyXMLTransformations(rawJSON, schema, &xmlNsMap) |
| 66 |
} |
| 67 |
|
| 68 |
func validateXmlNs(dataMap *map[string]any, schema *base.Schema, propName string, xmlNsMap *map[string]string) []*liberrors.ValidationError { |
| 69 |
var validationErrors []*liberrors.ValidationError |
| 70 |
|
| 71 |
if dataMap == nil || schema == nil || xmlNsMap == nil { |
| 72 |
return validationErrors |
| 73 |
} |
| 74 |
|
| 75 |
if propName != "" { |
| 76 |
if val, exists := (*dataMap)[propName]; exists { |
| 77 |
if converted, ok := val.(map[string]any); ok { |
| 78 |
dataMap = &converted |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
if schema.XML.Prefix != "" { |
| 84 |
attrKey := "-" + schema.XML.Prefix |
| 85 |
|
| 86 |
val, exists := (*dataMap)[attrKey] |
| 87 |
|
| 88 |
if exists { |
| 89 |
if ns, ok := val.(string); ok { |
| 90 |
(*xmlNsMap)[schema.XML.Prefix] = ns |
| 91 |
(*xmlNsMap)[ns] = schema.XML.Prefix |
| 92 |
|
| 93 |
if schema.XML.Namespace != "" && schema.XML.Namespace != ns { |
| 94 |
validationErrors = append(validationErrors, |
| 95 |
liberrors.InvalidNamespace(schema, ns, schema.XML.Namespace, schema.XML.Prefix)) |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
delete((*dataMap), attrKey) |
| 100 |
} else { |
| 101 |
validationErrors = append(validationErrors, liberrors.MissingPrefix(schema, schema.XML.Prefix)) |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
if schema.XML.Namespace != "" { |
| 106 |
_, exists := (*xmlNsMap)[schema.XML.Namespace] |
| 107 |
|
| 108 |
if !exists { |
| 109 |
validationErrors = append(validationErrors, liberrors.MissingNamespace(schema, schema.XML.Namespace)) |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
return validationErrors |
| 114 |
} |
| 115 |
|
| 116 |
func convertBasedOnSchema(propName, xmlName string, propValue any, schema *base.Schema, xmlNsMap *map[string]string) (any, []*liberrors.ValidationError) { |
| 117 |
var xmlNsErrors []*liberrors.ValidationError |
| 118 |
|
| 119 |
types := schema.Type |
| 120 |
|
| 121 |
extractTypes := func(proxies []*base.SchemaProxy) { |
| 122 |
for _, proxy := range proxies { |
| 123 |
sch := proxy.Schema() |
| 124 |
if len(sch.Type) > 0 { |
| 125 |
types = append(types, sch.Type...) |
| 126 |
} |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
extractTypes(schema.AllOf) |
| 131 |
extractTypes(schema.OneOf) |
| 132 |
extractTypes(schema.AnyOf) |
| 133 |
|
| 134 |
convertedValue := propValue |
| 135 |
|
| 136 |
typesLoop: |
| 137 |
for _, pType := range types { |
| 138 |
// because in XML everything is a string, we try to convert the value to the |
| 139 |
// actual expected type, so the normal schema validation should pass with correct types |
| 140 |
switch pType { |
| 141 |
case helpers.Integer: |
| 142 |
textValue, isString := propValue.(string) |
| 143 |
|
| 144 |
if isString { |
| 145 |
converted, err := strconv.ParseInt(textValue, 10, 64) |
| 146 |
|
| 147 |
if err == nil { |
| 148 |
convertedValue = converted |
| 149 |
break typesLoop |
| 150 |
} |
| 151 |
} |
| 152 |
case helpers.Number: |
| 153 |
textValue, isString := propValue.(string) |
| 154 |
|
| 155 |
if isString { |
| 156 |
converted, err := strconv.ParseFloat(textValue, 64) |
| 157 |
if err == nil { |
| 158 |
convertedValue = converted |
| 159 |
break typesLoop |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
case helpers.Boolean: |
| 164 |
textValue, isString := propValue.(string) |
| 165 |
|
| 166 |
if isString { |
| 167 |
converted, err := strconv.ParseBool(textValue) |
| 168 |
if err == nil { |
| 169 |
convertedValue = converted |
| 170 |
break typesLoop |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
case helpers.Array: |
| 175 |
convertedValue = propValue |
| 176 |
|
| 177 |
if schema.XML != nil && schema.XML.Wrapped { |
| 178 |
convertedValue = unwrapArrayElement(propValue, propName, schema) |
| 179 |
} |
| 180 |
|
| 181 |
if schema.Items != nil && schema.Items.A != nil { |
| 182 |
itemSchema := schema.Items.A.Schema() |
| 183 |
|
| 184 |
arr, isArr := convertedValue.([]any) |
| 185 |
|
| 186 |
if !isArr { |
| 187 |
arr = []any{ |
| 188 |
convertedValue, |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
for index, item := range arr { |
| 193 |
converted, errs := convertBasedOnSchema(propName, xmlName, item, itemSchema, xmlNsMap) |
| 194 |
|
| 195 |
if len(errs) > 0 { |
| 196 |
xmlNsErrors = append(xmlNsErrors, errs...) |
| 197 |
} |
| 198 |
|
| 199 |
arr[index] = converted |
| 200 |
} |
| 201 |
|
| 202 |
convertedValue = arr |
| 203 |
break typesLoop |
| 204 |
} |
| 205 |
case helpers.Object: |
| 206 |
objectValue, isObject := propValue.(map[string]any) |
| 207 |
|
| 208 |
if isObject { |
| 209 |
newValue, xmlErrors := applyXMLTransformations(objectValue, schema, xmlNsMap) |
| 210 |
|
| 211 |
if len(xmlErrors) > 0 { |
| 212 |
xmlNsErrors = append(xmlNsErrors, xmlErrors...) |
| 213 |
continue typesLoop |
| 214 |
} |
| 215 |
|
| 216 |
convertedValue = newValue |
| 217 |
break typesLoop |
| 218 |
} |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
return convertedValue, xmlNsErrors |
| 223 |
} |
| 224 |
|
| 225 |
// applyXMLTransformations applies openapi xml object rules to match json schema. |
| 226 |
// handles xml.name (root unwrapping), xml.attribute (dash prefix), xml.wrapped (array unwrapping), |
| 227 |
// xml.prefix (check existance), xml.namespace (check if exists and match). |
| 228 |
// we delete all attributes, prefixes, and namespaces found in the data interface; therefore, undeclared items |
| 229 |
// are sent in the body for validation, so that 'additionalProperties: false' can detect it. |
| 230 |
func applyXMLTransformations(data any, schema *base.Schema, xmlNsMap *map[string]string) (any, []*liberrors.ValidationError) { |
| 231 |
if schema == nil || data == nil || xmlNsMap == nil { |
| 232 |
return data, nil |
| 233 |
} |
| 234 |
|
| 235 |
// unwrap root element if xml.name is set on schema |
| 236 |
if schema.XML != nil && schema.XML.Name != "" { |
| 237 |
if dataMap, ok := data.(map[string]any); ok { |
| 238 |
if wrapped, exists := dataMap[schema.XML.Name]; exists { |
| 239 |
data = wrapped |
| 240 |
} |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
var xmlNsErrors []*liberrors.ValidationError |
| 245 |
|
| 246 |
// transform properties based on their xml configurations |
| 247 |
if dataMap, ok := data.(map[string]any); ok { |
| 248 |
if schema.Properties == nil || schema.Properties.Len() == 0 { |
| 249 |
if schema.XML != nil && (schema.XML.Prefix != "" || schema.XML.Namespace != "") { |
| 250 |
namespaceErrors := validateXmlNs(&dataMap, schema, "", xmlNsMap) |
| 251 |
|
| 252 |
if len(namespaceErrors) > 0 { |
| 253 |
xmlNsErrors = append(xmlNsErrors, namespaceErrors...) |
| 254 |
} else { |
| 255 |
if content, has := dataMap["#content"]; has { |
| 256 |
if stringContent, ok := content.(string); ok { |
| 257 |
data = stringContent |
| 258 |
} |
| 259 |
} |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
return data, xmlNsErrors |
| 264 |
} |
| 265 |
|
| 266 |
for pair := schema.Properties.First(); pair != nil; pair = pair.Next() { |
| 267 |
propName := pair.Key() |
| 268 |
propSchemaProxy := pair.Value() |
| 269 |
propSchema := propSchemaProxy.Schema() |
| 270 |
if propSchema == nil { |
| 271 |
continue |
| 272 |
} |
| 273 |
|
| 274 |
xmlName := propName |
| 275 |
|
| 276 |
if propSchema.XML != nil { |
| 277 |
// determine xml element name (defaults to property name) |
| 278 |
if propSchema.XML.Name != "" { |
| 279 |
xmlName = propSchema.XML.Name |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
if propSchema.XML != nil { |
| 284 |
namespaceErrors := validateXmlNs(&dataMap, propSchema, xmlName, xmlNsMap) |
| 285 |
|
| 286 |
if len(namespaceErrors) > 0 { |
| 287 |
xmlNsErrors = append(xmlNsErrors, namespaceErrors...) |
| 288 |
} |
| 289 |
|
| 290 |
// handle xml.attribute: true - attributes are prefixed with dash |
| 291 |
if propSchema.XML.Attribute { |
| 292 |
attrKey := "-" + xmlName |
| 293 |
if val, exists := dataMap[attrKey]; exists { |
| 294 |
// If the value is an attribute, it cannot have a namespace |
| 295 |
convertedValue, _ := convertBasedOnSchema(propName, xmlName, val, propSchema, xmlNsMap) |
| 296 |
dataMap[propName] = convertedValue |
| 297 |
delete(dataMap, attrKey) |
| 298 |
continue |
| 299 |
} |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
// handle regular elements |
| 304 |
if val, exists := dataMap[xmlName]; exists { |
| 305 |
if mapObject, ok := val.(map[string]any); ok { |
| 306 |
if content, has := mapObject["#content"]; has { |
| 307 |
if stringContent, ok := content.(string); ok { |
| 308 |
val = stringContent |
| 309 |
} |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
convertedValue, nsErrors := convertBasedOnSchema(propName, xmlName, val, propSchema, xmlNsMap) |
| 314 |
|
| 315 |
if len(nsErrors) > 0 { |
| 316 |
xmlNsErrors = append(xmlNsErrors, nsErrors...) |
| 317 |
} |
| 318 |
|
| 319 |
dataMap[propName] = convertedValue |
| 320 |
|
| 321 |
if propName != xmlName { |
| 322 |
delete(dataMap, xmlName) |
| 323 |
} |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
return data, xmlNsErrors |
| 329 |
} |
| 330 |
|
| 331 |
// unwrapArrayElement removes wrapping element from xml arrays when xml.wrapped is true. |
| 332 |
// example: {"items": {"item": [...]}} becomes [...] |
| 333 |
func unwrapArrayElement(val any, itemName string, propSchema *base.Schema) any { |
| 334 |
wrapMap, ok := val.(map[string]any) |
| 335 |
if !ok { |
| 336 |
return val |
| 337 |
} |
| 338 |
|
| 339 |
if propSchema.XML.Name != "" { |
| 340 |
itemName = propSchema.XML.Name |
| 341 |
} |
| 342 |
|
| 343 |
// determine item element name |
| 344 |
if propSchema.Items != nil && propSchema.Items.A != nil { |
| 345 |
itemSchema := propSchema.Items.A.Schema() |
| 346 |
if itemSchema != nil && itemSchema.XML != nil && itemSchema.XML.Name != "" { |
| 347 |
itemName = itemSchema.XML.Name |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
// unwrap: look for item element inside wrapper |
| 352 |
if unwrapped, exists := wrapMap[itemName]; exists { |
| 353 |
return unwrapped |
| 354 |
} |
| 355 |
|
| 356 |
return val |
| 357 |
} |
| 358 |
|
| 359 |
// IsXMLContentType checks if a media type string represents xml content. |
| 360 |
func IsXMLContentType(mediaType string) bool { |
| 361 |
mt := strings.ToLower(strings.TrimSpace(mediaType)) |
| 362 |
return strings.HasPrefix(mt, "application/xml") || |
| 363 |
strings.HasPrefix(mt, "text/xml") || |
| 364 |
strings.HasSuffix(mt, "+xml") |
| 365 |
} |