| 1 |
package helpers |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/json" |
| 6 |
"fmt" |
| 7 |
|
| 8 |
"github.com/santhosh-tekuri/jsonschema/v6" |
| 9 |
|
| 10 |
"github.com/pb33f/libopenapi-validator/config" |
| 11 |
"github.com/pb33f/libopenapi-validator/openapi_vocabulary" |
| 12 |
) |
| 13 |
|
| 14 |
// ConfigureCompiler configures a JSON Schema compiler with the desired behavior. |
| 15 |
func ConfigureCompiler(c *jsonschema.Compiler, o *config.ValidationOptions) { |
| 16 |
if o == nil { |
| 17 |
// Sanity |
| 18 |
return |
| 19 |
} |
| 20 |
|
| 21 |
// nil is the default so this is OK. |
| 22 |
c.UseRegexpEngine(o.RegexEngine) |
| 23 |
|
| 24 |
if o.FormatAssertions { |
| 25 |
c.AssertFormat() |
| 26 |
} |
| 27 |
|
| 28 |
if o.ContentAssertions { |
| 29 |
c.AssertContent() |
| 30 |
} |
| 31 |
|
| 32 |
for n, v := range o.Formats { |
| 33 |
c.RegisterFormat(&jsonschema.Format{ |
| 34 |
Name: n, |
| 35 |
Validate: v, |
| 36 |
}) |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
// NewCompilerWithOptions mints a new JSON schema compiler with custom configuration. |
| 41 |
func NewCompilerWithOptions(o *config.ValidationOptions) *jsonschema.Compiler { |
| 42 |
c := jsonschema.NewCompiler() |
| 43 |
ConfigureCompiler(c, o) |
| 44 |
return c |
| 45 |
} |
| 46 |
|
| 47 |
// NewCompiledSchema establishes a programmatic representation of a JSON Schema document that is used for validation. |
| 48 |
// Defaults to OpenAPI 3.1+ behavior (strict JSON Schema compliance). |
| 49 |
func NewCompiledSchema(name string, jsonSchema []byte, o *config.ValidationOptions) (*jsonschema.Schema, error) { |
| 50 |
return NewCompiledSchemaWithVersion(name, jsonSchema, o, 3.1) |
| 51 |
} |
| 52 |
|
| 53 |
// NewCompiledSchemaWithVersion establishes a programmatic representation of a JSON Schema document that is used for validation. |
| 54 |
// The version parameter determines which OpenAPI keywords are allowed: |
| 55 |
// - version 3.0: Allows OpenAPI 3.0 keywords like 'nullable' |
| 56 |
// - version 3.1+: Rejects OpenAPI 3.0 keywords like 'nullable' (strict JSON Schema compliance) |
| 57 |
func NewCompiledSchemaWithVersion(name string, jsonSchema []byte, options *config.ValidationOptions, version float32) (*jsonschema.Schema, error) { |
| 58 |
compiler := NewCompilerWithOptions(options) |
| 59 |
compiler.UseLoader(NewCompilerLoader()) |
| 60 |
|
| 61 |
// register OpenAPI vocabulary with appropriate version and coercion settings |
| 62 |
if options != nil && options.OpenAPIMode { |
| 63 |
var vocabVersion openapi_vocabulary.VersionType |
| 64 |
if version >= 3.15 { // use 3.15 to avoid floating point precision issues (3.2+) |
| 65 |
vocabVersion = openapi_vocabulary.Version32 |
| 66 |
} else if version >= 3.05 { // use 3.05 to avoid floating point precision issues (3.1) |
| 67 |
vocabVersion = openapi_vocabulary.Version31 |
| 68 |
} else { |
| 69 |
vocabVersion = openapi_vocabulary.Version30 |
| 70 |
} |
| 71 |
|
| 72 |
vocab := openapi_vocabulary.NewOpenAPIVocabularyWithCoercion(vocabVersion, options.AllowScalarCoercion) |
| 73 |
compiler.RegisterVocabulary(vocab) |
| 74 |
compiler.AssertVocabs() |
| 75 |
|
| 76 |
if version < 3.05 { |
| 77 |
jsonSchema = transformOpenAPI30Schema(jsonSchema) |
| 78 |
} |
| 79 |
|
| 80 |
if options.AllowScalarCoercion { |
| 81 |
jsonSchema = transformSchemaForCoercion(jsonSchema) |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
decodedSchema, err := jsonschema.UnmarshalJSON(bytes.NewReader(jsonSchema)) |
| 86 |
if err != nil { |
| 87 |
return nil, fmt.Errorf("failed to unmarshal JSON schema: %w", err) |
| 88 |
} |
| 89 |
|
| 90 |
if err = compiler.AddResource(name, decodedSchema); err != nil { |
| 91 |
return nil, fmt.Errorf("failed to add resource to schema compiler: %w", err) |
| 92 |
} |
| 93 |
|
| 94 |
jsch, err := compiler.Compile(name) |
| 95 |
if err != nil { |
| 96 |
return nil, fmt.Errorf("JSON schema compile failed: %s", err.Error()) |
| 97 |
} |
| 98 |
|
| 99 |
return jsch, nil |
| 100 |
} |
| 101 |
|
| 102 |
// transformOpenAPI30Schema transforms OpenAPI 3.0 schemas to JSON Schema 2020-12 compatible format. |
| 103 |
// Handles OAS 3.0-specific keywords: |
| 104 |
// - nullable: true → type array with "null" |
| 105 |
// - exclusiveMinimum/exclusiveMaximum: bool → numeric (draft-04 → 2020-12) |
| 106 |
func transformOpenAPI30Schema(jsonSchema []byte) []byte { |
| 107 |
var schema map[string]interface{} |
| 108 |
if err := json.Unmarshal(jsonSchema, &schema); err != nil { |
| 109 |
return jsonSchema |
| 110 |
} |
| 111 |
|
| 112 |
transformed := transformOAS30Keywords(schema) |
| 113 |
|
| 114 |
result, err := json.Marshal(transformed) |
| 115 |
if err != nil { |
| 116 |
return jsonSchema |
| 117 |
} |
| 118 |
|
| 119 |
return result |
| 120 |
} |
| 121 |
|
| 122 |
// transformOAS30Keywords recursively transforms OAS 3.0-specific keywords in a schema object |
| 123 |
func transformOAS30Keywords(schema interface{}) interface{} { |
| 124 |
switch s := schema.(type) { |
| 125 |
case map[string]interface{}: |
| 126 |
result := make(map[string]interface{}) |
| 127 |
|
| 128 |
// copy all properties first, recursing into nested schemas |
| 129 |
for key, value := range s { |
| 130 |
result[key] = transformOAS30Keywords(value) |
| 131 |
} |
| 132 |
|
| 133 |
// handle nullable keyword |
| 134 |
if nullable, ok := s["nullable"]; ok { |
| 135 |
if nullableBool, ok := nullable.(bool); ok { |
| 136 |
if nullableBool { |
| 137 |
result = transformNullableSchema(result) |
| 138 |
} else { |
| 139 |
delete(result, "nullable") |
| 140 |
} |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
// handle exclusiveMinimum: bool → numeric |
| 145 |
transformExclusiveBound(result, "exclusiveMinimum", "minimum") |
| 146 |
|
| 147 |
// handle exclusiveMaximum: bool → numeric |
| 148 |
transformExclusiveBound(result, "exclusiveMaximum", "maximum") |
| 149 |
|
| 150 |
return result |
| 151 |
|
| 152 |
case []interface{}: |
| 153 |
result := make([]interface{}, len(s)) |
| 154 |
for i, item := range s { |
| 155 |
result[i] = transformOAS30Keywords(item) |
| 156 |
} |
| 157 |
return result |
| 158 |
|
| 159 |
default: |
| 160 |
return schema |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
// transformExclusiveBound converts OAS 3.0 boolean exclusiveMinimum/exclusiveMaximum |
| 165 |
// to JSON Schema 2020-12 numeric form. |
| 166 |
// |
| 167 |
// OAS 3.0 (draft-04): minimum: 10, exclusiveMinimum: true → value must be > 10 |
| 168 |
// JSON Schema 2020-12: exclusiveMinimum: 10 → value must be > 10 |
| 169 |
func transformExclusiveBound(schema map[string]interface{}, exclusiveKey, boundKey string) { |
| 170 |
exVal, ok := schema[exclusiveKey] |
| 171 |
if !ok { |
| 172 |
return |
| 173 |
} |
| 174 |
exBool, isBool := exVal.(bool) |
| 175 |
if !isBool { |
| 176 |
return // already numeric (3.1 style), leave as-is |
| 177 |
} |
| 178 |
if exBool { |
| 179 |
// exclusiveMinimum: true + minimum: X → exclusiveMinimum: X (remove minimum) |
| 180 |
if bound, hasBound := schema[boundKey]; hasBound { |
| 181 |
schema[exclusiveKey] = bound |
| 182 |
delete(schema, boundKey) |
| 183 |
} else { |
| 184 |
// boolean true without a corresponding bound is invalid, just remove it |
| 185 |
delete(schema, exclusiveKey) |
| 186 |
} |
| 187 |
} else { |
| 188 |
// exclusiveMinimum: false is a no-op, just remove the keyword |
| 189 |
delete(schema, exclusiveKey) |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
// transformNullableSchema transforms a schema with nullable: true to JSON Schema compatible format |
| 194 |
func transformNullableSchema(schema map[string]interface{}) map[string]interface{} { |
| 195 |
delete(schema, "nullable") |
| 196 |
|
| 197 |
// get the current type |
| 198 |
currentType, hasType := schema["type"] |
| 199 |
|
| 200 |
if hasType { |
| 201 |
// if there's already a type, convert it to include null |
| 202 |
switch t := currentType.(type) { |
| 203 |
case string: |
| 204 |
// convert "string" to ["string", "null"] |
| 205 |
schema["type"] = []interface{}{t, "null"} |
| 206 |
case []interface{}: |
| 207 |
// if it's already an array, add null if not present |
| 208 |
found := false |
| 209 |
for _, item := range t { |
| 210 |
if str, ok := item.(string); ok && str == "null" { |
| 211 |
found = true |
| 212 |
break |
| 213 |
} |
| 214 |
} |
| 215 |
if !found { |
| 216 |
newTypes := make([]interface{}, len(t)+1) |
| 217 |
copy(newTypes, t) |
| 218 |
newTypes[len(t)] = "null" |
| 219 |
schema["type"] = newTypes |
| 220 |
} |
| 221 |
} |
| 222 |
} |
| 223 |
allOf, hasAllOf := schema["allOf"] |
| 224 |
if hasAllOf { |
| 225 |
delete(schema, "allOf") |
| 226 |
oneOfAdditions := []interface{}{ |
| 227 |
map[string]interface{}{ |
| 228 |
"allOf": allOf, |
| 229 |
}, |
| 230 |
map[string]interface{}{ |
| 231 |
"type": "null", |
| 232 |
}, |
| 233 |
} |
| 234 |
var oneOfSlice []interface{} |
| 235 |
oneOf, hasOneOf := schema["oneOf"] |
| 236 |
if hasOneOf { |
| 237 |
oneOfSlice, _ = oneOf.([]interface{}) |
| 238 |
} |
| 239 |
oneOfSlice = append(oneOfSlice, oneOfAdditions...) |
| 240 |
schema["oneOf"] = oneOfSlice |
| 241 |
} |
| 242 |
|
| 243 |
// Handle enum values - add null if nullable but not already in enum |
| 244 |
enum, hasEnum := schema["enum"] |
| 245 |
if hasEnum { |
| 246 |
if enumSlice, ok := enum.([]interface{}); ok { |
| 247 |
// Check if null is already in enum |
| 248 |
hasNull := false |
| 249 |
for _, v := range enumSlice { |
| 250 |
if v == nil { |
| 251 |
hasNull = true |
| 252 |
break |
| 253 |
} |
| 254 |
} |
| 255 |
// Add null if not present |
| 256 |
if !hasNull { |
| 257 |
enumSlice = append(enumSlice, nil) |
| 258 |
schema["enum"] = enumSlice |
| 259 |
} |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
return schema |
| 264 |
} |
| 265 |
|
| 266 |
// transformSchemaForCoercion transforms schemas to allow scalar coercion (string->boolean/number) |
| 267 |
func transformSchemaForCoercion(jsonSchema []byte) []byte { |
| 268 |
var schema map[string]interface{} |
| 269 |
if err := json.Unmarshal(jsonSchema, &schema); err != nil { |
| 270 |
// If we can't parse it, return as-is |
| 271 |
return jsonSchema |
| 272 |
} |
| 273 |
|
| 274 |
transformed := transformCoercionInSchema(schema) |
| 275 |
|
| 276 |
result, err := json.Marshal(transformed) |
| 277 |
if err != nil { |
| 278 |
return jsonSchema |
| 279 |
} |
| 280 |
|
| 281 |
return result |
| 282 |
} |
| 283 |
|
| 284 |
// transformCoercionInSchema recursively transforms schemas to support scalar coercion |
| 285 |
func transformCoercionInSchema(schema interface{}) interface{} { |
| 286 |
switch s := schema.(type) { |
| 287 |
case map[string]interface{}: |
| 288 |
result := make(map[string]interface{}) |
| 289 |
|
| 290 |
// copy all properties first |
| 291 |
for key, value := range s { |
| 292 |
result[key] = transformCoercionInSchema(value) |
| 293 |
} |
| 294 |
|
| 295 |
// transform type to allow string coercion for coercible types |
| 296 |
if schemaType, hasType := s["type"]; hasType { |
| 297 |
result["type"] = transformTypeForCoercion(schemaType) |
| 298 |
} |
| 299 |
|
| 300 |
return result |
| 301 |
|
| 302 |
case []interface{}: |
| 303 |
result := make([]interface{}, len(s)) |
| 304 |
for i, item := range s { |
| 305 |
result[i] = transformCoercionInSchema(item) |
| 306 |
} |
| 307 |
return result |
| 308 |
|
| 309 |
default: |
| 310 |
return schema |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
// transformTypeForCoercion transforms type fields to allow string coercion |
| 315 |
func transformTypeForCoercion(schemaType interface{}) interface{} { |
| 316 |
switch t := schemaType.(type) { |
| 317 |
case string: |
| 318 |
// transform scalar types to include string for coercion |
| 319 |
if t == "boolean" || t == "number" || t == "integer" { |
| 320 |
return []interface{}{t, "string"} |
| 321 |
} |
| 322 |
return t |
| 323 |
|
| 324 |
case []interface{}: |
| 325 |
// if already an array, add string if it contains coercible types and doesn't already have string |
| 326 |
hasCoercibleType := false |
| 327 |
hasString := false |
| 328 |
|
| 329 |
for _, item := range t { |
| 330 |
if str, ok := item.(string); ok { |
| 331 |
if str == "boolean" || str == "number" || str == "integer" { |
| 332 |
hasCoercibleType = true |
| 333 |
} |
| 334 |
if str == "string" { |
| 335 |
hasString = true |
| 336 |
} |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
if hasCoercibleType && !hasString { |
| 341 |
newTypes := make([]interface{}, len(t)+1) |
| 342 |
copy(newTypes, t) |
| 343 |
newTypes[len(t)] = "string" |
| 344 |
return newTypes |
| 345 |
} |
| 346 |
|
| 347 |
return t |
| 348 |
|
| 349 |
default: |
| 350 |
return schemaType |
| 351 |
} |
| 352 |
} |