| 1 |
package parameters |
| 2 |
|
| 3 |
import ( |
| 4 |
"net/http" |
| 5 |
"strings" |
| 6 |
"sync" |
| 7 |
"testing" |
| 8 |
|
| 9 |
"github.com/pb33f/libopenapi" |
| 10 |
"github.com/pb33f/libopenapi/datamodel/high/base" |
| 11 |
lowv3 "github.com/pb33f/libopenapi/datamodel/low/v3" |
| 12 |
"github.com/stretchr/testify/assert" |
| 13 |
"github.com/stretchr/testify/require" |
| 14 |
|
| 15 |
"github.com/pb33f/libopenapi-validator/cache" |
| 16 |
"github.com/pb33f/libopenapi-validator/config" |
| 17 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 18 |
) |
| 19 |
|
| 20 |
func Test_ForceCompilerError(t *testing.T) { |
| 21 |
// Try to force a panic |
| 22 |
result := ValidateSingleParameterSchema(nil, nil, "", "", "", "", "", nil, "", "") |
| 23 |
|
| 24 |
// Ideally this would result in an error response, current behavior swallows the error |
| 25 |
require.Empty(t, result) |
| 26 |
} |
| 27 |
|
| 28 |
func TestHeaderSchemaNoType(t *testing.T) { |
| 29 |
bytes := []byte(`{ |
| 30 |
"openapi": "3.0.0", |
| 31 |
"info": { |
| 32 |
"title": "API Spec With Mandatory Header", |
| 33 |
"version": "1.0.0" |
| 34 |
}, |
| 35 |
"paths": { |
| 36 |
"/api-endpoint": { |
| 37 |
"get": { |
| 38 |
"summary": "Restricted API Endpoint", |
| 39 |
"parameters": [ |
| 40 |
{ |
| 41 |
"name": "apiKey", |
| 42 |
"in": "header", |
| 43 |
"required": true, |
| 44 |
"schema": { |
| 45 |
"oneOf": [ |
| 46 |
{ |
| 47 |
"type": "boolean" |
| 48 |
}, |
| 49 |
{ |
| 50 |
"type": "integer" |
| 51 |
} |
| 52 |
] |
| 53 |
} |
| 54 |
} |
| 55 |
], |
| 56 |
"responses": { |
| 57 |
"200": { |
| 58 |
"description": "Successful response" |
| 59 |
} |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
}, |
| 64 |
"components": { |
| 65 |
"securitySchemes": { |
| 66 |
"ApiKeyHeader": { |
| 67 |
"type": "apiKey", |
| 68 |
"name": "apiKey", |
| 69 |
"in": "header" |
| 70 |
} |
| 71 |
} |
| 72 |
}, |
| 73 |
"security": [ |
| 74 |
{ |
| 75 |
"ApiKeyHeader": [] |
| 76 |
} |
| 77 |
] |
| 78 |
}`) |
| 79 |
|
| 80 |
doc, err := libopenapi.NewDocument(bytes) |
| 81 |
if err != nil { |
| 82 |
t.Fatalf("error while creating open api spec document: %v", err) |
| 83 |
} |
| 84 |
|
| 85 |
req, err := http.NewRequest("GET", "/api-endpoint", nil) |
| 86 |
if err != nil { |
| 87 |
t.Fatalf("error while creating request: %v", err) |
| 88 |
} |
| 89 |
|
| 90 |
req.Header.Set("Content-Type", "application/json") |
| 91 |
req.Header.Set("apiKey", "headerValue") |
| 92 |
|
| 93 |
v3Model, errs := doc.BuildV3Model() |
| 94 |
if errs != nil { |
| 95 |
t.Fatalf("error while building v3 model: %v", errs) |
| 96 |
} |
| 97 |
|
| 98 |
v3Model.Model.Servers = nil |
| 99 |
// render the document back to bytes and reload the model. |
| 100 |
_, _, v3Model, _ = doc.RenderAndReload() |
| 101 |
|
| 102 |
validator := NewParameterValidator(&v3Model.Model) |
| 103 |
|
| 104 |
isSuccess, valErrs := validator.ValidateHeaderParams(req) |
| 105 |
|
| 106 |
assert.False(t, isSuccess) |
| 107 |
assert.Len(t, valErrs, 1) |
| 108 |
assert.Equal(t, "schema 'apiKey' is defined as an boolean or integer, however it failed to pass a schema validation", valErrs[0].Reason) |
| 109 |
assert.Len(t, valErrs[0].SchemaValidationErrors, 2) |
| 110 |
assert.Equal(t, "got string, want boolean", valErrs[0].SchemaValidationErrors[0].Reason) |
| 111 |
assert.Equal(t, "got string, want integer", valErrs[0].SchemaValidationErrors[1].Reason) |
| 112 |
} |
| 113 |
|
| 114 |
func TestHeaderSchemaNoType_AllPoly(t *testing.T) { |
| 115 |
bytes := []byte(`{ |
| 116 |
"openapi": "3.0.0", |
| 117 |
"info": { |
| 118 |
"title": "API Spec With Mandatory Header", |
| 119 |
"version": "1.0.0" |
| 120 |
}, |
| 121 |
"paths": { |
| 122 |
"/api-endpoint": { |
| 123 |
"get": { |
| 124 |
"summary": "Restricted API Endpoint", |
| 125 |
"parameters": [ |
| 126 |
{ |
| 127 |
"name": "apiKey", |
| 128 |
"in": "header", |
| 129 |
"required": true, |
| 130 |
"schema": { |
| 131 |
"oneOf": [ |
| 132 |
{ |
| 133 |
"type": "boolean" |
| 134 |
}, |
| 135 |
{ |
| 136 |
"type": "integer" |
| 137 |
} |
| 138 |
], |
| 139 |
"allOf": [ |
| 140 |
{ |
| 141 |
"type": "boolean" |
| 142 |
} |
| 143 |
] |
| 144 |
} |
| 145 |
} |
| 146 |
], |
| 147 |
"responses": { |
| 148 |
"200": { |
| 149 |
"description": "Successful response" |
| 150 |
} |
| 151 |
} |
| 152 |
} |
| 153 |
} |
| 154 |
}, |
| 155 |
"components": { |
| 156 |
"securitySchemes": { |
| 157 |
"ApiKeyHeader": { |
| 158 |
"type": "apiKey", |
| 159 |
"name": "apiKey", |
| 160 |
"in": "header" |
| 161 |
} |
| 162 |
} |
| 163 |
}, |
| 164 |
"security": [ |
| 165 |
{ |
| 166 |
"ApiKeyHeader": [] |
| 167 |
} |
| 168 |
] |
| 169 |
}`) |
| 170 |
|
| 171 |
doc, err := libopenapi.NewDocument(bytes) |
| 172 |
if err != nil { |
| 173 |
t.Fatalf("error while creating open api spec document: %v", err) |
| 174 |
} |
| 175 |
|
| 176 |
req, err := http.NewRequest("GET", "/api-endpoint", nil) |
| 177 |
if err != nil { |
| 178 |
t.Fatalf("error while creating request: %v", err) |
| 179 |
} |
| 180 |
|
| 181 |
req.Header.Set("Content-Type", "application/json") |
| 182 |
req.Header.Set("apiKey", "headerValue") |
| 183 |
|
| 184 |
v3Model, errs := doc.BuildV3Model() |
| 185 |
if errs != nil { |
| 186 |
t.Fatalf("error while building v3 model: %v", errs) |
| 187 |
} |
| 188 |
|
| 189 |
v3Model.Model.Servers = nil |
| 190 |
// render the document back to bytes and reload the model. |
| 191 |
_, _, v3Model, _ = doc.RenderAndReload() |
| 192 |
|
| 193 |
validator := NewParameterValidator(&v3Model.Model) |
| 194 |
|
| 195 |
isSuccess, valErrs := validator.ValidateHeaderParams(req) |
| 196 |
|
| 197 |
assert.False(t, isSuccess) |
| 198 |
assert.Len(t, valErrs, 1) |
| 199 |
assert.Equal(t, "schema 'apiKey' is defined as an boolean and a integer, however it failed to pass a schema validation", valErrs[0].Reason) |
| 200 |
assert.Len(t, valErrs[0].SchemaValidationErrors, 3) |
| 201 |
} |
| 202 |
|
| 203 |
// TestUnifiedErrorFormatWithFormatValidation tests that format validation errors |
| 204 |
// use the unified SchemaValidationFailure format consistently |
| 205 |
// https://github.com/pb33f/libopenapi-validator/issues/168 |
| 206 |
func TestUnifiedErrorFormatWithFormatValidation(t *testing.T) { |
| 207 |
bytes := []byte(`{ |
| 208 |
"openapi": "3.0.0", |
| 209 |
"info": { |
| 210 |
"title": "API Spec With Format Validation", |
| 211 |
"version": "1.0.0" |
| 212 |
}, |
| 213 |
"paths": { |
| 214 |
"/test": { |
| 215 |
"get": { |
| 216 |
"parameters": [ |
| 217 |
{ |
| 218 |
"name": "email_param", |
| 219 |
"in": "query", |
| 220 |
"required": true, |
| 221 |
"schema": { |
| 222 |
"type": "string", |
| 223 |
"format": "email" |
| 224 |
} |
| 225 |
} |
| 226 |
], |
| 227 |
"responses": { |
| 228 |
"200": { |
| 229 |
"description": "Success" |
| 230 |
} |
| 231 |
} |
| 232 |
} |
| 233 |
} |
| 234 |
} |
| 235 |
}`) |
| 236 |
|
| 237 |
doc, err := libopenapi.NewDocument(bytes) |
| 238 |
if err != nil { |
| 239 |
t.Fatalf("error while creating open api spec document: %v", err) |
| 240 |
} |
| 241 |
|
| 242 |
req, err := http.NewRequest("GET", "/test?email_param=invalid-email-format", nil) |
| 243 |
if err != nil { |
| 244 |
t.Fatalf("error while creating request: %v", err) |
| 245 |
} |
| 246 |
|
| 247 |
v3Model, errs := doc.BuildV3Model() |
| 248 |
if errs != nil { |
| 249 |
t.Fatalf("error while building v3 model: %v", errs) |
| 250 |
} |
| 251 |
|
| 252 |
v3Model.Model.Servers = nil |
| 253 |
_, _, v3Model, _ = doc.RenderAndReload() |
| 254 |
|
| 255 |
validator := NewParameterValidator(&v3Model.Model, config.WithFormatAssertions()) |
| 256 |
|
| 257 |
isSuccess, valErrs := validator.ValidateQueryParams(req) |
| 258 |
|
| 259 |
assert.False(t, isSuccess) |
| 260 |
assert.Len(t, valErrs, 1) |
| 261 |
assert.Equal(t, "Query parameter 'email_param' failed to validate", valErrs[0].Message) |
| 262 |
|
| 263 |
// verify ParameterName is populated for easy programmatic access |
| 264 |
assert.Equal(t, "email_param", valErrs[0].ParameterName) |
| 265 |
|
| 266 |
// verify unified error format - SchemaValidationErrors should be populated |
| 267 |
assert.Len(t, valErrs[0].SchemaValidationErrors, 1) |
| 268 |
assert.Contains(t, valErrs[0].SchemaValidationErrors[0].Reason, "is not valid email") |
| 269 |
assert.Equal(t, "/paths/test/get/parameters/email_param/schema/format", valErrs[0].SchemaValidationErrors[0].KeywordLocation) |
| 270 |
assert.NotEmpty(t, valErrs[0].SchemaValidationErrors[0].ReferenceSchema) |
| 271 |
} |
| 272 |
|
| 273 |
// TestParameterNameFieldPopulation tests that ParameterName field is consistently populated |
| 274 |
// for both basic validation errors and JSONSchema validation errors |
| 275 |
func TestParameterNameFieldPopulation(t *testing.T) { |
| 276 |
bytes := []byte(`{ |
| 277 |
"openapi": "3.0.0", |
| 278 |
"info": { |
| 279 |
"title": "Parameter Name Test", |
| 280 |
"version": "1.0.0" |
| 281 |
}, |
| 282 |
"paths": { |
| 283 |
"/test": { |
| 284 |
"get": { |
| 285 |
"parameters": [ |
| 286 |
{ |
| 287 |
"name": "integer_param", |
| 288 |
"in": "query", |
| 289 |
"required": true, |
| 290 |
"schema": { |
| 291 |
"type": "integer" |
| 292 |
} |
| 293 |
} |
| 294 |
], |
| 295 |
"responses": { |
| 296 |
"200": { |
| 297 |
"description": "Success" |
| 298 |
} |
| 299 |
} |
| 300 |
} |
| 301 |
} |
| 302 |
} |
| 303 |
}`) |
| 304 |
|
| 305 |
doc, err := libopenapi.NewDocument(bytes) |
| 306 |
require.NoError(t, err) |
| 307 |
|
| 308 |
req, err := http.NewRequest("GET", "/test?integer_param=not_a_number", nil) |
| 309 |
require.NoError(t, err) |
| 310 |
|
| 311 |
v3Model, errs := doc.BuildV3Model() |
| 312 |
require.Empty(t, errs) |
| 313 |
|
| 314 |
validator := NewParameterValidator(&v3Model.Model) |
| 315 |
isSuccess, valErrs := validator.ValidateQueryParams(req) |
| 316 |
|
| 317 |
assert.False(t, isSuccess) |
| 318 |
assert.Len(t, valErrs, 1) |
| 319 |
|
| 320 |
// verify ParameterName is populated for basic type validation errors |
| 321 |
assert.Equal(t, "integer_param", valErrs[0].ParameterName) |
| 322 |
assert.Equal(t, "Query parameter 'integer_param' is not a valid integer", valErrs[0].Message) |
| 323 |
|
| 324 |
// basic type errors SHOULD have SchemaValidationErrors because we know the parameter schema |
| 325 |
assert.Len(t, valErrs[0].SchemaValidationErrors, 1) |
| 326 |
assert.Equal(t, "integer_param", valErrs[0].SchemaValidationErrors[0].FieldName) |
| 327 |
} |
| 328 |
|
| 329 |
func TestHeaderSchemaStringNoJSON(t *testing.T) { |
| 330 |
bytes := []byte(`{ |
| 331 |
"openapi": "3.0.0", |
| 332 |
"info": { |
| 333 |
"title": "API Spec With Mandatory Header", |
| 334 |
"version": "1.0.0" |
| 335 |
}, |
| 336 |
"paths": { |
| 337 |
"/api-endpoint": { |
| 338 |
"get": { |
| 339 |
"summary": "Restricted API Endpoint", |
| 340 |
|
| 341 |
"responses": { |
| 342 |
"200": { |
| 343 |
"description": "Successful response", |
| 344 |
"headers": { |
| 345 |
"chicken-nuggets": { |
| 346 |
"required": true, |
| 347 |
"schema": { |
| 348 |
"oneOf": [ |
| 349 |
{ |
| 350 |
"type": "boolean" |
| 351 |
}, |
| 352 |
{ |
| 353 |
"type": "integer" |
| 354 |
} |
| 355 |
] |
| 356 |
} |
| 357 |
} |
| 358 |
} |
| 359 |
} |
| 360 |
} |
| 361 |
} |
| 362 |
} |
| 363 |
}, |
| 364 |
"components": { |
| 365 |
"securitySchemes": { |
| 366 |
"ApiKeyHeader": { |
| 367 |
"type": "apiKey", |
| 368 |
"name": "apiKey", |
| 369 |
"in": "header" |
| 370 |
} |
| 371 |
} |
| 372 |
}, |
| 373 |
"security": [ |
| 374 |
{ |
| 375 |
"ApiKeyHeader": [] |
| 376 |
} |
| 377 |
] |
| 378 |
}`) |
| 379 |
|
| 380 |
doc, err := libopenapi.NewDocument(bytes) |
| 381 |
if err != nil { |
| 382 |
t.Fatalf("error while creating open api spec document: %v", err) |
| 383 |
} |
| 384 |
|
| 385 |
req, err := http.NewRequest("GET", "/api-endpoint", nil) |
| 386 |
if err != nil { |
| 387 |
t.Fatalf("error while creating request: %v", err) |
| 388 |
} |
| 389 |
|
| 390 |
req.Header.Set("Content-Type", "application/json") |
| 391 |
req.Header.Set("apiKey", "headerValue") |
| 392 |
|
| 393 |
v3Model, errs := doc.BuildV3Model() |
| 394 |
if errs != nil { |
| 395 |
t.Fatalf("error while building v3 model: %v", errs) |
| 396 |
} |
| 397 |
|
| 398 |
v3Model.Model.Servers = nil |
| 399 |
// render the document back to bytes and reload the model. |
| 400 |
_, _, v3Model, _ = doc.RenderAndReload() |
| 401 |
|
| 402 |
headers := v3Model.Model.Paths.PathItems.GetOrZero("/api-endpoint").Get.Responses.Codes.GetOrZero("200").Headers |
| 403 |
headerSchema := headers.GetOrZero("chicken-nuggets").Schema.Schema() |
| 404 |
|
| 405 |
headerErrors := ValidateParameterSchema(headerSchema, nil, "bubbles", "header", |
| 406 |
"response header", "chicken-nuggets", helpers.ResponseBodyValidation, lowv3.HeadersLabel, nil) |
| 407 |
|
| 408 |
assert.Len(t, headerErrors, 1) |
| 409 |
assert.Equal(t, "response header 'chicken-nuggets' is defined as an boolean or integer, however it failed to pass a schema validation", headerErrors[0].Reason) |
| 410 |
} |
| 411 |
|
| 412 |
// TestComplexRegexSchemaCompilationError tests that complex regex patterns in parameter schemas |
| 413 |
// that cause schema compilation to fail are handled gracefully instead of causing panics |
| 414 |
func TestComplexRegexSchemaCompilationError(t *testing.T) { |
| 415 |
bytes := []byte(`{ |
| 416 |
"openapi": "3.0.0", |
| 417 |
"info": { |
| 418 |
"title": "API Spec With Complex Regex Pattern", |
| 419 |
"version": "1.0.0" |
| 420 |
}, |
| 421 |
"paths": { |
| 422 |
"/api-endpoint": { |
| 423 |
"get": { |
| 424 |
"summary": "API Endpoint with complex regex", |
| 425 |
"parameters": [ |
| 426 |
{ |
| 427 |
"name": "complexParam", |
| 428 |
"in": "query", |
| 429 |
"required": true, |
| 430 |
"schema": { |
| 431 |
"type": "string", |
| 432 |
"pattern": "[\\w\\W]{1,1024}$" |
| 433 |
} |
| 434 |
} |
| 435 |
], |
| 436 |
"responses": { |
| 437 |
"200": { |
| 438 |
"description": "Successful response" |
| 439 |
} |
| 440 |
} |
| 441 |
} |
| 442 |
} |
| 443 |
} |
| 444 |
}`) |
| 445 |
|
| 446 |
doc, err := libopenapi.NewDocument(bytes) |
| 447 |
if err != nil { |
| 448 |
t.Fatalf("error while creating open api spec document: %v", err) |
| 449 |
} |
| 450 |
|
| 451 |
req, err := http.NewRequest("GET", "/api-endpoint?complexParam=testvalue", nil) |
| 452 |
if err != nil { |
| 453 |
t.Fatalf("error while creating request: %v", err) |
| 454 |
} |
| 455 |
|
| 456 |
v3Model, errs := doc.BuildV3Model() |
| 457 |
if errs != nil { |
| 458 |
t.Fatalf("error while building v3 model: %v", errs) |
| 459 |
} |
| 460 |
|
| 461 |
validator := NewParameterValidator(&v3Model.Model) |
| 462 |
|
| 463 |
// validate - this should not panic even if schema compilation fails due to complex regex |
| 464 |
isSuccess, valErrs := validator.ValidateQueryParams(req) |
| 465 |
|
| 466 |
// if schema compilation failed, we should get validation errors instead of a panic |
| 467 |
if !isSuccess { |
| 468 |
// verify we got schema compilation errors instead of a panic |
| 469 |
assert.NotEmpty(t, valErrs) |
| 470 |
found := false |
| 471 |
for _, err := range valErrs { |
| 472 |
if err.ParameterName == "complexParam" && |
| 473 |
len(err.SchemaValidationErrors) == 0 { |
| 474 |
// Schema compilation errors don't have SchemaValidationFailure objects |
| 475 |
if strings.Contains(err.Reason, "failed to compile JSON schema") { |
| 476 |
found = true |
| 477 |
assert.Contains(t, err.Reason, "failed to compile JSON schema") |
| 478 |
assert.Contains(t, err.HowToFix, "complex regex patterns") |
| 479 |
break |
| 480 |
} |
| 481 |
} |
| 482 |
} |
| 483 |
if !found { |
| 484 |
// if it didn't fail compilation, it should have succeeded or failed with a different error |
| 485 |
t.Logf("Schema compilation succeeded or failed with different error, validation result: %v, errors: %v", isSuccess, valErrs) |
| 486 |
} |
| 487 |
} else { |
| 488 |
// schema compiled and validated successfully |
| 489 |
assert.True(t, isSuccess) |
| 490 |
assert.Empty(t, valErrs) |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
// TestValidateParameterSchema_SchemaCompilationFailure tests that ValidateParameterSchema |
| 495 |
// handles schema compilation failures gracefully instead of causing panics |
| 496 |
func TestValidateParameterSchema_SchemaCompilationFailure(t *testing.T) { |
| 497 |
bytes := []byte(`{ |
| 498 |
"openapi": "3.0.0", |
| 499 |
"info": { |
| 500 |
"title": "API Spec With Complex Regex Pattern", |
| 501 |
"version": "1.0.0" |
| 502 |
}, |
| 503 |
"paths": { |
| 504 |
"/api-endpoint": { |
| 505 |
"get": { |
| 506 |
"summary": "API Endpoint with complex regex that causes compilation failure", |
| 507 |
"parameters": [ |
| 508 |
{ |
| 509 |
"name": "failParam", |
| 510 |
"in": "query", |
| 511 |
"required": true, |
| 512 |
"schema": { |
| 513 |
"type": "string", |
| 514 |
"pattern": "[\\w\\W]{1,2048}$" |
| 515 |
} |
| 516 |
} |
| 517 |
], |
| 518 |
"responses": { |
| 519 |
"200": { |
| 520 |
"description": "Successful response" |
| 521 |
} |
| 522 |
} |
| 523 |
} |
| 524 |
} |
| 525 |
} |
| 526 |
}`) |
| 527 |
|
| 528 |
doc, err := libopenapi.NewDocument(bytes) |
| 529 |
require.NoError(t, err) |
| 530 |
|
| 531 |
v3Model, errs := doc.BuildV3Model() |
| 532 |
require.Empty(t, errs) |
| 533 |
|
| 534 |
// get the parameter schema that should cause compilation failure |
| 535 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/api-endpoint") |
| 536 |
param := pathItem.Get.Parameters[0] |
| 537 |
schema := param.Schema.Schema() |
| 538 |
|
| 539 |
// call ValidateParameterSchema directly with the problematic schema |
| 540 |
validationErrors := ValidateParameterSchema( |
| 541 |
schema, |
| 542 |
"test-value", |
| 543 |
"", |
| 544 |
"Query parameter", |
| 545 |
"query parameter", |
| 546 |
"failParam", |
| 547 |
helpers.ParameterValidation, |
| 548 |
helpers.ParameterValidationQuery, |
| 549 |
nil, |
| 550 |
) |
| 551 |
|
| 552 |
// should get schema compilation error instead of panic |
| 553 |
if len(validationErrors) > 0 { |
| 554 |
found := false |
| 555 |
for _, validationError := range validationErrors { |
| 556 |
if validationError.ParameterName == "failParam" && |
| 557 |
validationError.ValidationSubType == helpers.ParameterValidationQuery && |
| 558 |
len(validationError.SchemaValidationErrors) == 0 { |
| 559 |
// Schema compilation errors don't have SchemaValidationFailure objects |
| 560 |
if strings.Contains(validationError.Reason, "failed to compile JSON schema") { |
| 561 |
assert.Contains(t, validationError.Reason, "failed to compile JSON schema") |
| 562 |
assert.Contains(t, validationError.HowToFix, "complex regex patterns") |
| 563 |
assert.Equal(t, "Query parameter 'failParam' failed schema compilation", validationError.Message) |
| 564 |
found = true |
| 565 |
break |
| 566 |
} |
| 567 |
} |
| 568 |
} |
| 569 |
if !found { |
| 570 |
// schema compilation succeeded, might have failed for other reasons or succeeded |
| 571 |
t.Logf("Schema compilation succeeded or failed for different reasons: %v", validationErrors) |
| 572 |
} |
| 573 |
} else { |
| 574 |
// no validation errors - schema compiled and validated successfully |
| 575 |
t.Logf("Schema compiled and validated successfully") |
| 576 |
} |
| 577 |
} |
| 578 |
|
| 579 |
func preparePathsBenchmark(b *testing.B, cache config.RegexCache) (ParameterValidator, *http.Request) { |
| 580 |
bytes := []byte(`{ |
| 581 |
"openapi": "3.0.0", |
| 582 |
"info": { |
| 583 |
"title": "API Spec With Complex Regex Pattern", |
| 584 |
"version": "1.0.0" |
| 585 |
}, |
| 586 |
"paths": { |
| 587 |
"/test/other/path": { |
| 588 |
"get": {"responses": {"200": {"description": "test"}}} |
| 589 |
}, |
| 590 |
"/static/test/{imageName}": { |
| 591 |
"get": {"responses": {"200": {"description": "test"}}} |
| 592 |
}, |
| 593 |
"/request/to/my/image.png": { |
| 594 |
"get": {"responses": {"200": {"description": "test"}}} |
| 595 |
}, |
| 596 |
"/api/v2/{url}/{other}/{oncemore}/{url}": { |
| 597 |
"get": {"responses": {"200": {"description": "test"}}} |
| 598 |
}, |
| 599 |
"/api/v1/{path}": { |
| 600 |
"get": {"responses": {"200": {"description": "test"}}} |
| 601 |
}, |
| 602 |
"/each/url/{is}/{a_new_regex}": { |
| 603 |
"get": {"responses": {"200": {"description": "test"}}} |
| 604 |
}, |
| 605 |
"/my-test/with-so-many/urls": { |
| 606 |
"get": {"responses": {"200": {"description": "test"}}} |
| 607 |
}, |
| 608 |
"/test/other/path": { |
| 609 |
"get": {"responses": {"200": {"description": "test"}}} |
| 610 |
}, |
| 611 |
"/api/endpoint/{address}/{domain}": { |
| 612 |
"get": { |
| 613 |
"summary": "API Endpoint with complex regex", |
| 614 |
"parameters": [ |
| 615 |
{ |
| 616 |
"name": "complexParam", |
| 617 |
"in": "query", |
| 618 |
"required": true, |
| 619 |
"schema": { |
| 620 |
"type": "string", |
| 621 |
"pattern": "[\\w\\W]{1,1024}$" |
| 622 |
} |
| 623 |
} |
| 624 |
], |
| 625 |
"responses": { |
| 626 |
"200": { |
| 627 |
"description": "Successful response" |
| 628 |
} |
| 629 |
} |
| 630 |
} |
| 631 |
} |
| 632 |
} |
| 633 |
}`) |
| 634 |
|
| 635 |
doc, err := libopenapi.NewDocument(bytes) |
| 636 |
if err != nil { |
| 637 |
b.Fatalf("error while creating open api spec document: %v", err) |
| 638 |
} |
| 639 |
|
| 640 |
req, err := http.NewRequest("GET", "/api/endpoint/127.0.0.1/domain.com?complexParam=testvalue", nil) |
| 641 |
if err != nil { |
| 642 |
b.Fatalf("error while creating request: %v", err) |
| 643 |
} |
| 644 |
|
| 645 |
v3Model, errs := doc.BuildV3Model() |
| 646 |
if errs != nil { |
| 647 |
b.Fatalf("error while building v3 model: %v", errs) |
| 648 |
} |
| 649 |
|
| 650 |
validator := NewParameterValidator(&v3Model.Model, config.WithRegexCache(cache)) |
| 651 |
|
| 652 |
return validator, req |
| 653 |
} |
| 654 |
|
| 655 |
func BenchmarkValidationWithoutCache(b *testing.B) { |
| 656 |
validator, req := preparePathsBenchmark(b, nil) |
| 657 |
|
| 658 |
b.ResetTimer() |
| 659 |
|
| 660 |
for b.Loop() { |
| 661 |
validator.ValidateHeaderParams(req) |
| 662 |
validator.ValidateCookieParams(req) |
| 663 |
validator.ValidateQueryParams(req) |
| 664 |
validator.ValidateSecurity(req) |
| 665 |
validator.ValidatePathParams(req) |
| 666 |
} |
| 667 |
} |
| 668 |
|
| 669 |
func BenchmarkValidationWithRegexCache(b *testing.B) { |
| 670 |
validator, req := preparePathsBenchmark(b, &sync.Map{}) |
| 671 |
|
| 672 |
b.ResetTimer() |
| 673 |
|
| 674 |
for b.Loop() { |
| 675 |
validator.ValidateHeaderParams(req) |
| 676 |
validator.ValidateCookieParams(req) |
| 677 |
validator.ValidateQueryParams(req) |
| 678 |
validator.ValidateSecurity(req) |
| 679 |
validator.ValidatePathParams(req) |
| 680 |
} |
| 681 |
} |
| 682 |
|
| 683 |
// cacheTestSpec is an OpenAPI spec for testing cache behavior |
| 684 |
var cacheTestSpec = []byte(`{ |
| 685 |
"openapi": "3.1.0", |
| 686 |
"info": { |
| 687 |
"title": "Cache Test API", |
| 688 |
"version": "1.0.0" |
| 689 |
}, |
| 690 |
"paths": { |
| 691 |
"/items/{id}": { |
| 692 |
"get": { |
| 693 |
"operationId": "getItem", |
| 694 |
"parameters": [ |
| 695 |
{ |
| 696 |
"name": "id", |
| 697 |
"in": "path", |
| 698 |
"required": true, |
| 699 |
"schema": { |
| 700 |
"type": "string", |
| 701 |
"minLength": 1, |
| 702 |
"maxLength": 64 |
| 703 |
} |
| 704 |
}, |
| 705 |
{ |
| 706 |
"name": "limit", |
| 707 |
"in": "query", |
| 708 |
"schema": { |
| 709 |
"type": "integer", |
| 710 |
"minimum": 1, |
| 711 |
"maximum": 100 |
| 712 |
} |
| 713 |
} |
| 714 |
], |
| 715 |
"responses": { |
| 716 |
"200": { |
| 717 |
"description": "OK" |
| 718 |
} |
| 719 |
} |
| 720 |
} |
| 721 |
} |
| 722 |
} |
| 723 |
}`) |
| 724 |
|
| 725 |
// Test_ParameterValidation_CacheUsage verifies that parameter validation uses the schema cache. |
| 726 |
// This test validates that: |
| 727 |
// 1. Cache is populated after the first validation |
| 728 |
// 2. Subsequent validations reuse the cached compiled schemas |
| 729 |
// 3. Validation still produces correct results when using cached schemas |
| 730 |
func Test_ParameterValidation_CacheUsage(t *testing.T) { |
| 731 |
doc, err := libopenapi.NewDocument(cacheTestSpec) |
| 732 |
require.NoError(t, err, "Failed to create document") |
| 733 |
|
| 734 |
v3Model, errs := doc.BuildV3Model() |
| 735 |
require.Nil(t, errs, "Failed to build v3 model") |
| 736 |
|
| 737 |
// Create options with cache (default behavior) |
| 738 |
opts := config.NewValidationOptions() |
| 739 |
require.NotNil(t, opts.SchemaCache, "Schema cache should be initialized by default") |
| 740 |
|
| 741 |
validator := NewParameterValidator(&v3Model.Model, config.WithExistingOpts(opts)) |
| 742 |
|
| 743 |
// First request - should populate cache |
| 744 |
req1, _ := http.NewRequest("GET", "/items/abc123?limit=50", nil) |
| 745 |
isSuccess1, errors1 := validator.ValidateQueryParams(req1) |
| 746 |
assert.True(t, isSuccess1, "First validation should succeed") |
| 747 |
assert.Empty(t, errors1, "First validation should have no errors") |
| 748 |
|
| 749 |
// Count cached entries (should have at least the limit parameter schema) |
| 750 |
cacheCount := 0 |
| 751 |
opts.SchemaCache.Range(func(key uint64, value *cache.SchemaCacheEntry) bool { |
| 752 |
cacheCount++ |
| 753 |
return true |
| 754 |
}) |
| 755 |
assert.Greater(t, cacheCount, 0, "Cache should have entries after first validation") |
| 756 |
|
| 757 |
// Second request with different valid value - should use cached schema |
| 758 |
req2, _ := http.NewRequest("GET", "/items/xyz789?limit=75", nil) |
| 759 |
isSuccess2, errors2 := validator.ValidateQueryParams(req2) |
| 760 |
assert.True(t, isSuccess2, "Second validation should succeed") |
| 761 |
assert.Empty(t, errors2, "Second validation should have no errors") |
| 762 |
|
| 763 |
// Third request with invalid value - should still use cached schema but fail validation |
| 764 |
req3, _ := http.NewRequest("GET", "/items/test?limit=999", nil) |
| 765 |
isSuccess3, errors3 := validator.ValidateQueryParams(req3) |
| 766 |
assert.False(t, isSuccess3, "Third validation should fail (limit > maximum)") |
| 767 |
assert.NotEmpty(t, errors3, "Third validation should have errors") |
| 768 |
} |
| 769 |
|
| 770 |
// Test_ParameterValidation_WithoutCache verifies that validation works when cache is disabled. |
| 771 |
func Test_ParameterValidation_WithoutCache(t *testing.T) { |
| 772 |
doc, err := libopenapi.NewDocument(cacheTestSpec) |
| 773 |
require.NoError(t, err, "Failed to create document") |
| 774 |
|
| 775 |
v3Model, errs := doc.BuildV3Model() |
| 776 |
require.Nil(t, errs, "Failed to build v3 model") |
| 777 |
|
| 778 |
// Create options without cache |
| 779 |
opts := config.NewValidationOptions(config.WithSchemaCache(nil)) |
| 780 |
require.Nil(t, opts.SchemaCache, "Schema cache should be nil") |
| 781 |
|
| 782 |
validator := NewParameterValidator(&v3Model.Model, config.WithExistingOpts(opts)) |
| 783 |
|
| 784 |
// Validation should still work without cache |
| 785 |
req, _ := http.NewRequest("GET", "/items/abc123?limit=50", nil) |
| 786 |
isSuccess, errors := validator.ValidateQueryParams(req) |
| 787 |
assert.True(t, isSuccess, "Validation should succeed without cache") |
| 788 |
assert.Empty(t, errors, "Validation should have no errors") |
| 789 |
|
| 790 |
// Validation with invalid value should fail |
| 791 |
req2, _ := http.NewRequest("GET", "/items/abc123?limit=999", nil) |
| 792 |
isSuccess2, errors2 := validator.ValidateQueryParams(req2) |
| 793 |
assert.False(t, isSuccess2, "Validation should fail for invalid value") |
| 794 |
assert.NotEmpty(t, errors2, "Validation should report errors") |
| 795 |
} |
| 796 |
|
| 797 |
// Test_ParameterValidation_CacheConsistency verifies that cached schemas produce |
| 798 |
// the same validation results as freshly compiled schemas. |
| 799 |
func Test_ParameterValidation_CacheConsistency(t *testing.T) { |
| 800 |
doc, err := libopenapi.NewDocument(cacheTestSpec) |
| 801 |
require.NoError(t, err, "Failed to create document") |
| 802 |
|
| 803 |
v3Model, errs := doc.BuildV3Model() |
| 804 |
require.Nil(t, errs, "Failed to build v3 model") |
| 805 |
|
| 806 |
// Run the same validations with and without cache |
| 807 |
testCases := []struct { |
| 808 |
name string |
| 809 |
url string |
| 810 |
expected bool |
| 811 |
}{ |
| 812 |
{"valid_limit", "/items/abc?limit=50", true}, |
| 813 |
{"limit_at_max", "/items/abc?limit=100", true}, |
| 814 |
{"limit_at_min", "/items/abc?limit=1", true}, |
| 815 |
{"limit_too_high", "/items/abc?limit=101", false}, |
| 816 |
{"limit_too_low", "/items/abc?limit=0", false}, |
| 817 |
} |
| 818 |
|
| 819 |
// First run with cache |
| 820 |
optsWithCache := config.NewValidationOptions() |
| 821 |
validatorWithCache := NewParameterValidator(&v3Model.Model, config.WithExistingOpts(optsWithCache)) |
| 822 |
|
| 823 |
// Second run without cache |
| 824 |
optsNoCache := config.NewValidationOptions(config.WithSchemaCache(nil)) |
| 825 |
validatorNoCache := NewParameterValidator(&v3Model.Model, config.WithExistingOpts(optsNoCache)) |
| 826 |
|
| 827 |
for _, tc := range testCases { |
| 828 |
t.Run(tc.name, func(t *testing.T) { |
| 829 |
req, _ := http.NewRequest("GET", tc.url, nil) |
| 830 |
|
| 831 |
successWithCache, errorsWithCache := validatorWithCache.ValidateQueryParams(req) |
| 832 |
successNoCache, errorsNoCache := validatorNoCache.ValidateQueryParams(req) |
| 833 |
|
| 834 |
assert.Equal(t, tc.expected, successWithCache, "Cached validation result mismatch for %s", tc.name) |
| 835 |
assert.Equal(t, successWithCache, successNoCache, "Cache vs no-cache results should match for %s", tc.name) |
| 836 |
assert.Equal(t, len(errorsWithCache), len(errorsNoCache), "Error count should match for %s", tc.name) |
| 837 |
}) |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
// Test_GetRenderedSchema_NilSchema verifies GetRenderedSchema handles nil schema gracefully. |
| 842 |
func Test_GetRenderedSchema_NilSchema(t *testing.T) { |
| 843 |
opts := config.NewValidationOptions() |
| 844 |
result := GetRenderedSchema(nil, opts) |
| 845 |
assert.Empty(t, result, "GetRenderedSchema should return empty string for nil schema") |
| 846 |
} |
| 847 |
|
| 848 |
// Test_GetRenderedSchema_NilOptions verifies GetRenderedSchema works without options. |
| 849 |
func Test_GetRenderedSchema_NilOptions(t *testing.T) { |
| 850 |
spec := []byte(`{ |
| 851 |
"openapi": "3.1.0", |
| 852 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 853 |
"paths": { |
| 854 |
"/test": { |
| 855 |
"get": { |
| 856 |
"parameters": [{ |
| 857 |
"name": "id", |
| 858 |
"in": "query", |
| 859 |
"schema": {"type": "string", "minLength": 1} |
| 860 |
}], |
| 861 |
"responses": {"200": {"description": "OK"}} |
| 862 |
} |
| 863 |
} |
| 864 |
} |
| 865 |
}`) |
| 866 |
|
| 867 |
doc, err := libopenapi.NewDocument(spec) |
| 868 |
require.NoError(t, err) |
| 869 |
|
| 870 |
v3Model, errs := doc.BuildV3Model() |
| 871 |
require.Nil(t, errs) |
| 872 |
|
| 873 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/test") |
| 874 |
schema := pathItem.Get.Parameters[0].Schema.Schema() |
| 875 |
|
| 876 |
// Ground truth |
| 877 |
rendered, _ := schema.RenderInline() |
| 878 |
expected := string(rendered) |
| 879 |
|
| 880 |
// With nil options should match ground truth |
| 881 |
result := GetRenderedSchema(schema, nil) |
| 882 |
assert.Equal(t, expected, result) |
| 883 |
} |
| 884 |
|
| 885 |
// Test_GetRenderedSchema_CacheHit verifies GetRenderedSchema uses cached data when available. |
| 886 |
func Test_GetRenderedSchema_CacheHit(t *testing.T) { |
| 887 |
spec := []byte(`{ |
| 888 |
"openapi": "3.1.0", |
| 889 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 890 |
"paths": { |
| 891 |
"/test": { |
| 892 |
"get": { |
| 893 |
"parameters": [{ |
| 894 |
"name": "id", |
| 895 |
"in": "query", |
| 896 |
"schema": {"type": "integer", "minimum": 1} |
| 897 |
}], |
| 898 |
"responses": {"200": {"description": "OK"}} |
| 899 |
} |
| 900 |
} |
| 901 |
} |
| 902 |
}`) |
| 903 |
|
| 904 |
doc, err := libopenapi.NewDocument(spec) |
| 905 |
require.NoError(t, err) |
| 906 |
|
| 907 |
v3Model, errs := doc.BuildV3Model() |
| 908 |
require.Nil(t, errs) |
| 909 |
|
| 910 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/test") |
| 911 |
schema := pathItem.Get.Parameters[0].Schema.Schema() |
| 912 |
|
| 913 |
// Ground truth |
| 914 |
rendered, _ := schema.RenderInline() |
| 915 |
expected := string(rendered) |
| 916 |
|
| 917 |
// Pre-populate cache with RenderedInline |
| 918 |
opts := config.NewValidationOptions() |
| 919 |
hash := schema.GoLow().Hash() |
| 920 |
opts.SchemaCache.Store(hash, &cache.SchemaCacheEntry{ |
| 921 |
Schema: schema, |
| 922 |
RenderedInline: rendered, |
| 923 |
}) |
| 924 |
|
| 925 |
// Cache hit should match ground truth |
| 926 |
result := GetRenderedSchema(schema, opts) |
| 927 |
assert.Equal(t, expected, result) |
| 928 |
} |
| 929 |
|
| 930 |
// Test_GetRenderedSchema_NilCache verifies GetRenderedSchema works when cache is disabled. |
| 931 |
func Test_GetRenderedSchema_NilCache(t *testing.T) { |
| 932 |
spec := []byte(`{ |
| 933 |
"openapi": "3.1.0", |
| 934 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 935 |
"paths": { |
| 936 |
"/test": { |
| 937 |
"get": { |
| 938 |
"parameters": [{ |
| 939 |
"name": "id", |
| 940 |
"in": "query", |
| 941 |
"schema": {"type": "boolean"} |
| 942 |
}], |
| 943 |
"responses": {"200": {"description": "OK"}} |
| 944 |
} |
| 945 |
} |
| 946 |
} |
| 947 |
}`) |
| 948 |
|
| 949 |
doc, err := libopenapi.NewDocument(spec) |
| 950 |
require.NoError(t, err) |
| 951 |
|
| 952 |
v3Model, errs := doc.BuildV3Model() |
| 953 |
require.Nil(t, errs) |
| 954 |
|
| 955 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/test") |
| 956 |
schema := pathItem.Get.Parameters[0].Schema.Schema() |
| 957 |
|
| 958 |
// Ground truth |
| 959 |
rendered, _ := schema.RenderInline() |
| 960 |
expected := string(rendered) |
| 961 |
|
| 962 |
// With nil cache should match ground truth |
| 963 |
opts := config.NewValidationOptions(config.WithSchemaCache(nil)) |
| 964 |
result := GetRenderedSchema(schema, opts) |
| 965 |
assert.Equal(t, expected, result) |
| 966 |
} |
| 967 |
|
| 968 |
// Test_GetRenderedSchema_CacheMiss verifies GetRenderedSchema renders fresh when cache entry has empty RenderedInline. |
| 969 |
// This tests the code path where cache lookup succeeds but RenderedInline is empty. |
| 970 |
func Test_GetRenderedSchema_CacheMiss(t *testing.T) { |
| 971 |
spec := []byte(`{ |
| 972 |
"openapi": "3.1.0", |
| 973 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 974 |
"paths": { |
| 975 |
"/test": { |
| 976 |
"get": { |
| 977 |
"parameters": [{ |
| 978 |
"name": "id", |
| 979 |
"in": "query", |
| 980 |
"schema": {"type": "integer"} |
| 981 |
}], |
| 982 |
"responses": {"200": {"description": "OK"}} |
| 983 |
} |
| 984 |
} |
| 985 |
} |
| 986 |
}`) |
| 987 |
|
| 988 |
doc, err := libopenapi.NewDocument(spec) |
| 989 |
require.NoError(t, err) |
| 990 |
|
| 991 |
v3Model, errs := doc.BuildV3Model() |
| 992 |
require.Nil(t, errs) |
| 993 |
|
| 994 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/test") |
| 995 |
schema := pathItem.Get.Parameters[0].Schema.Schema() |
| 996 |
|
| 997 |
// Ground truth |
| 998 |
rendered, _ := schema.RenderInline() |
| 999 |
expected := string(rendered) |
| 1000 |
|
| 1001 |
// Store entry with empty RenderedInline to force cache miss |
| 1002 |
opts := config.NewValidationOptions() |
| 1003 |
hash := schema.GoLow().Hash() |
| 1004 |
opts.SchemaCache.Store(hash, &cache.SchemaCacheEntry{ |
| 1005 |
Schema: schema, |
| 1006 |
RenderedInline: nil, // Empty - should trigger fresh rendering |
| 1007 |
}) |
| 1008 |
|
| 1009 |
// Cache miss should still match ground truth |
| 1010 |
result := GetRenderedSchema(schema, opts) |
| 1011 |
assert.Equal(t, expected, result) |
| 1012 |
} |
| 1013 |
|
| 1014 |
// Test_GetRenderedSchema_Deterministic verifies that GetRenderedSchema returns the same |
| 1015 |
// output regardless of cache state (cache hit vs cache miss). |
| 1016 |
func Test_GetRenderedSchema_Deterministic(t *testing.T) { |
| 1017 |
spec := []byte(`{ |
| 1018 |
"openapi": "3.1.0", |
| 1019 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 1020 |
"paths": { |
| 1021 |
"/test": { |
| 1022 |
"get": { |
| 1023 |
"parameters": [{ |
| 1024 |
"name": "status", |
| 1025 |
"in": "query", |
| 1026 |
"schema": {"type": "string", "enum": ["active", "inactive"]} |
| 1027 |
}], |
| 1028 |
"responses": {"200": {"description": "OK"}} |
| 1029 |
} |
| 1030 |
} |
| 1031 |
} |
| 1032 |
}`) |
| 1033 |
|
| 1034 |
doc, err := libopenapi.NewDocument(spec) |
| 1035 |
require.NoError(t, err) |
| 1036 |
|
| 1037 |
v3Model, errs := doc.BuildV3Model() |
| 1038 |
require.Nil(t, errs) |
| 1039 |
|
| 1040 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/test") |
| 1041 |
schema := pathItem.Get.Parameters[0].Schema.Schema() |
| 1042 |
|
| 1043 |
// Ground truth |
| 1044 |
rendered, _ := schema.RenderInline() |
| 1045 |
expected := string(rendered) |
| 1046 |
|
| 1047 |
// Cache miss path (no cache) |
| 1048 |
optsNoCache := config.NewValidationOptions(config.WithSchemaCache(nil)) |
| 1049 |
resultMiss := GetRenderedSchema(schema, optsNoCache) |
| 1050 |
assert.Equal(t, expected, resultMiss) |
| 1051 |
|
| 1052 |
// Cache hit path (pre-populated cache) |
| 1053 |
optsWithCache := config.NewValidationOptions() |
| 1054 |
hash := schema.GoLow().Hash() |
| 1055 |
optsWithCache.SchemaCache.Store(hash, &cache.SchemaCacheEntry{ |
| 1056 |
RenderedInline: rendered, |
| 1057 |
}) |
| 1058 |
resultHit := GetRenderedSchema(schema, optsWithCache) |
| 1059 |
assert.Equal(t, expected, resultHit) |
| 1060 |
} |
| 1061 |
|
| 1062 |
// Test_ValidateSingleParameterSchema_CacheMissCompiledSchema tests the path where cache entry |
| 1063 |
// exists but CompiledSchema is nil, forcing recompilation. |
| 1064 |
func Test_ValidateSingleParameterSchema_CacheMissCompiledSchema(t *testing.T) { |
| 1065 |
spec := []byte(`{ |
| 1066 |
"openapi": "3.1.0", |
| 1067 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 1068 |
"paths": { |
| 1069 |
"/test/{id}": { |
| 1070 |
"get": { |
| 1071 |
"parameters": [{ |
| 1072 |
"name": "id", |
| 1073 |
"in": "path", |
| 1074 |
"required": true, |
| 1075 |
"schema": {"type": "integer", "minimum": 1} |
| 1076 |
}], |
| 1077 |
"responses": {"200": {"description": "OK"}} |
| 1078 |
} |
| 1079 |
} |
| 1080 |
} |
| 1081 |
}`) |
| 1082 |
|
| 1083 |
doc, err := libopenapi.NewDocument(spec) |
| 1084 |
require.NoError(t, err) |
| 1085 |
|
| 1086 |
v3Model, errs := doc.BuildV3Model() |
| 1087 |
require.Nil(t, errs) |
| 1088 |
|
| 1089 |
// Get the parameter schema |
| 1090 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/test/{id}") |
| 1091 |
param := pathItem.Get.Parameters[0] |
| 1092 |
schema := param.Schema.Schema() |
| 1093 |
|
| 1094 |
// Create options with cache enabled |
| 1095 |
opts := config.NewValidationOptions() |
| 1096 |
require.NotNil(t, opts.SchemaCache) |
| 1097 |
|
| 1098 |
// Store an entry with nil CompiledSchema to force recompilation |
| 1099 |
hash := schema.GoLow().Hash() |
| 1100 |
opts.SchemaCache.Store(hash, &cache.SchemaCacheEntry{ |
| 1101 |
Schema: schema, |
| 1102 |
CompiledSchema: nil, // nil - should trigger recompilation |
| 1103 |
}) |
| 1104 |
|
| 1105 |
// Validate should still work by recompiling the schema |
| 1106 |
result := ValidateSingleParameterSchema( |
| 1107 |
schema, |
| 1108 |
int64(5), // valid integer |
| 1109 |
"Path parameter", |
| 1110 |
"The path parameter", |
| 1111 |
"id", |
| 1112 |
helpers.ParameterValidation, |
| 1113 |
helpers.ParameterValidationPath, |
| 1114 |
opts, |
| 1115 |
"/test/{id}", |
| 1116 |
"get", |
| 1117 |
) |
| 1118 |
assert.Empty(t, result, "Validation should pass for valid integer") |
| 1119 |
|
| 1120 |
// Now verify the cache was populated with the compiled schema |
| 1121 |
cached, ok := opts.SchemaCache.Load(hash) |
| 1122 |
assert.True(t, ok, "Cache entry should exist") |
| 1123 |
assert.NotNil(t, cached.CompiledSchema, "CompiledSchema should be populated after validation") |
| 1124 |
} |
| 1125 |
|
| 1126 |
// arrayValidationSpec is used to test array parameter validation with the updated function signatures |
| 1127 |
var arrayValidationSpec = []byte(`{ |
| 1128 |
"openapi": "3.1.0", |
| 1129 |
"info": {"title": "Array Test", "version": "1.0.0"}, |
| 1130 |
"paths": { |
| 1131 |
"/test": { |
| 1132 |
"get": { |
| 1133 |
"parameters": [{ |
| 1134 |
"name": "ids", |
| 1135 |
"in": "query", |
| 1136 |
"schema": { |
| 1137 |
"type": "array", |
| 1138 |
"items": {"type": "integer", "minimum": 1} |
| 1139 |
} |
| 1140 |
}], |
| 1141 |
"responses": {"200": {"description": "OK"}} |
| 1142 |
} |
| 1143 |
} |
| 1144 |
} |
| 1145 |
}`) |
| 1146 |
|
| 1147 |
// Test_ArrayValidation_ErrorContainsRenderedSchema verifies that array validation errors |
| 1148 |
// still contain the rendered schema after the rendering optimization. |
| 1149 |
func Test_ArrayValidation_ErrorContainsRenderedSchema(t *testing.T) { |
| 1150 |
doc, err := libopenapi.NewDocument(arrayValidationSpec) |
| 1151 |
require.NoError(t, err) |
| 1152 |
|
| 1153 |
v3Model, errs := doc.BuildV3Model() |
| 1154 |
require.Nil(t, errs) |
| 1155 |
|
| 1156 |
validator := NewParameterValidator(&v3Model.Model) |
| 1157 |
|
| 1158 |
// Request with invalid array values (strings instead of integers) |
| 1159 |
req, _ := http.NewRequest("GET", "/test?ids=abc,def", nil) |
| 1160 |
|
| 1161 |
success, validationErrors := validator.ValidateQueryParams(req) |
| 1162 |
assert.False(t, success, "Validation should fail for non-integer array values") |
| 1163 |
assert.NotEmpty(t, validationErrors, "Should have validation errors") |
| 1164 |
|
| 1165 |
// Verify error message is properly formatted |
| 1166 |
assert.Contains(t, validationErrors[0].Message, "ids", "Error should reference parameter name") |
| 1167 |
} |
| 1168 |
|
| 1169 |
// Test_ParameterValidation_CompleteCacheEntry verifies that parameter validation |
| 1170 |
// writes complete cache entries. |
| 1171 |
func Test_ParameterValidation_CompleteCacheEntry(t *testing.T) { |
| 1172 |
spec := []byte(`{ |
| 1173 |
"openapi": "3.1.0", |
| 1174 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 1175 |
"paths": { |
| 1176 |
"/test": { |
| 1177 |
"get": { |
| 1178 |
"parameters": [{ |
| 1179 |
"name": "id", |
| 1180 |
"in": "query", |
| 1181 |
"schema": {"type": "string", "minLength": 1} |
| 1182 |
}], |
| 1183 |
"responses": {"200": {"description": "OK"}} |
| 1184 |
} |
| 1185 |
} |
| 1186 |
} |
| 1187 |
}`) |
| 1188 |
|
| 1189 |
doc, err := libopenapi.NewDocument(spec) |
| 1190 |
require.NoError(t, err) |
| 1191 |
|
| 1192 |
v3Model, errs := doc.BuildV3Model() |
| 1193 |
require.Nil(t, errs) |
| 1194 |
|
| 1195 |
opts := config.NewValidationOptions() |
| 1196 |
validator := NewParameterValidator(&v3Model.Model, config.WithExistingOpts(opts)) |
| 1197 |
|
| 1198 |
req, _ := http.NewRequest("GET", "/test?id=abc", nil) |
| 1199 |
valid, _ := validator.ValidateQueryParams(req) |
| 1200 |
assert.True(t, valid) |
| 1201 |
|
| 1202 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/test") |
| 1203 |
schema := pathItem.Get.Parameters[0].Schema.Schema() |
| 1204 |
hash := schema.GoLow().Hash() |
| 1205 |
|
| 1206 |
cached, ok := opts.SchemaCache.Load(hash) |
| 1207 |
require.True(t, ok, "Cache entry should exist") |
| 1208 |
|
| 1209 |
// Check that all fields of the cache entry are populated |
| 1210 |
assert.NotNil(t, cached.Schema, "Schema should be populated") |
| 1211 |
assert.NotEmpty(t, cached.RenderedInline, "RenderedInline should be populated") |
| 1212 |
assert.NotEmpty(t, cached.ReferenceSchema, "ReferenceSchema should be populated") |
| 1213 |
assert.NotEmpty(t, cached.RenderedJSON, "RenderedJSON should be populated") |
| 1214 |
assert.NotNil(t, cached.CompiledSchema, "CompiledSchema should be populated") |
| 1215 |
assert.NotNil(t, cached.RenderedNode, "RenderedNode should be populated") |
| 1216 |
} |
| 1217 |
|
| 1218 |
// Test_ReferenceSchema_ConsistentFormat verifies that ReferenceSchema has the same |
| 1219 |
// format whether the error comes from GetRenderedSchema or formatJsonSchemaValidationError. |
| 1220 |
func Test_ReferenceSchema_ConsistentFormat(t *testing.T) { |
| 1221 |
spec := []byte(`{ |
| 1222 |
"openapi": "3.1.0", |
| 1223 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 1224 |
"paths": { |
| 1225 |
"/test": { |
| 1226 |
"get": { |
| 1227 |
"parameters": [{ |
| 1228 |
"name": "count", |
| 1229 |
"in": "query", |
| 1230 |
"required": true, |
| 1231 |
"schema": {"type": "integer", "minimum": 1, "maximum": 100} |
| 1232 |
}], |
| 1233 |
"responses": {"200": {"description": "OK"}} |
| 1234 |
} |
| 1235 |
} |
| 1236 |
} |
| 1237 |
}`) |
| 1238 |
|
| 1239 |
doc, err := libopenapi.NewDocument(spec) |
| 1240 |
require.NoError(t, err) |
| 1241 |
|
| 1242 |
v3Model, errs := doc.BuildV3Model() |
| 1243 |
require.Nil(t, errs) |
| 1244 |
|
| 1245 |
validator := NewParameterValidator(&v3Model.Model) |
| 1246 |
|
| 1247 |
// Error path 1: Missing required parameter (uses GetRenderedSchema) |
| 1248 |
req1, _ := http.NewRequest(http.MethodGet, "/test", nil) |
| 1249 |
_, errors1 := validator.ValidateQueryParams(req1) |
| 1250 |
require.NotEmpty(t, errors1) |
| 1251 |
require.NotEmpty(t, errors1[0].SchemaValidationErrors) |
| 1252 |
refSchema1 := errors1[0].SchemaValidationErrors[0].ReferenceSchema |
| 1253 |
|
| 1254 |
// Error path 2: Value outside range (uses formatJsonSchemaValidationError) |
| 1255 |
req2, _ := http.NewRequest(http.MethodGet, "/test?count=999", nil) |
| 1256 |
_, errors2 := validator.ValidateQueryParams(req2) |
| 1257 |
require.NotEmpty(t, errors2) |
| 1258 |
require.NotEmpty(t, errors2[0].SchemaValidationErrors) |
| 1259 |
refSchema2 := errors2[0].SchemaValidationErrors[0].ReferenceSchema |
| 1260 |
|
| 1261 |
// Both should be plain YAML with the same content |
| 1262 |
assert.Equal(t, refSchema1, refSchema2, |
| 1263 |
"ReferenceSchema should be consistent regardless of error path") |
| 1264 |
} |
| 1265 |
|
| 1266 |
// Test_GetRenderedSchema_ValidationModeConsistency verifies that GetRenderedSchema produces |
| 1267 |
// identical output on cache hit vs cache miss for schemas with discriminators. The cache |
| 1268 |
// stores schemas rendered with validation mode, so cache misses must also use validation |
| 1269 |
// mode for consistency. |
| 1270 |
func Test_GetRenderedSchema_ValidationModeConsistency(t *testing.T) { |
| 1271 |
spec := []byte(`{ |
| 1272 |
"openapi": "3.1.0", |
| 1273 |
"info": {"title": "Test", "version": "1.0.0"}, |
| 1274 |
"paths": { |
| 1275 |
"/test": { |
| 1276 |
"get": { |
| 1277 |
"parameters": [{ |
| 1278 |
"name": "pet", |
| 1279 |
"in": "query", |
| 1280 |
"required": true, |
| 1281 |
"schema": { |
| 1282 |
"discriminator": { |
| 1283 |
"propertyName": "petType", |
| 1284 |
"mapping": { |
| 1285 |
"cat": "#/components/schemas/Cat", |
| 1286 |
"dog": "#/components/schemas/Dog" |
| 1287 |
} |
| 1288 |
}, |
| 1289 |
"oneOf": [ |
| 1290 |
{"$ref": "#/components/schemas/Cat"}, |
| 1291 |
{"$ref": "#/components/schemas/Dog"} |
| 1292 |
] |
| 1293 |
} |
| 1294 |
}], |
| 1295 |
"responses": {"200": {"description": "OK"}} |
| 1296 |
} |
| 1297 |
} |
| 1298 |
}, |
| 1299 |
"components": { |
| 1300 |
"schemas": { |
| 1301 |
"Cat": { |
| 1302 |
"type": "object", |
| 1303 |
"properties": { |
| 1304 |
"petType": {"type": "string"}, |
| 1305 |
"meow": {"type": "boolean"} |
| 1306 |
}, |
| 1307 |
"required": ["petType"] |
| 1308 |
}, |
| 1309 |
"Dog": { |
| 1310 |
"type": "object", |
| 1311 |
"properties": { |
| 1312 |
"petType": {"type": "string"}, |
| 1313 |
"bark": {"type": "boolean"} |
| 1314 |
}, |
| 1315 |
"required": ["petType"] |
| 1316 |
} |
| 1317 |
} |
| 1318 |
} |
| 1319 |
}`) |
| 1320 |
|
| 1321 |
doc, err := libopenapi.NewDocument(spec) |
| 1322 |
require.NoError(t, err) |
| 1323 |
|
| 1324 |
v3Model, errs := doc.BuildV3Model() |
| 1325 |
require.Nil(t, errs) |
| 1326 |
|
| 1327 |
// Get the discriminator schema |
| 1328 |
pathItem := v3Model.Model.Paths.PathItems.GetOrZero("/test") |
| 1329 |
schema := pathItem.Get.Parameters[0].Schema.Schema() |
| 1330 |
|
| 1331 |
// Get ground truth: what the cache would store (validation mode) |
| 1332 |
renderCtx := base.NewInlineRenderContextForValidation() |
| 1333 |
expectedRendered, err := schema.RenderInlineWithContext(renderCtx) |
| 1334 |
require.NoError(t, err) |
| 1335 |
expected := string(expectedRendered) |
| 1336 |
|
| 1337 |
// Test cache miss path |
| 1338 |
optsNoCache := config.NewValidationOptions(config.WithSchemaCache(nil)) |
| 1339 |
resultCacheMiss := GetRenderedSchema(schema, optsNoCache) |
| 1340 |
|
| 1341 |
assert.Equal(t, expected, resultCacheMiss, |
| 1342 |
"Cache miss should produce same output as validation mode rendering") |
| 1343 |
|
| 1344 |
// Test cache hit path |
| 1345 |
optsWithCache := config.NewValidationOptions() |
| 1346 |
hash := schema.GoLow().Hash() |
| 1347 |
optsWithCache.SchemaCache.Store(hash, &cache.SchemaCacheEntry{ |
| 1348 |
RenderedInline: expectedRendered, |
| 1349 |
}) |
| 1350 |
resultCacheHit := GetRenderedSchema(schema, optsWithCache) |
| 1351 |
|
| 1352 |
assert.Equal(t, expected, resultCacheHit, |
| 1353 |
"Cache hit should return the cached validation mode rendering") |
| 1354 |
|
| 1355 |
// Test both paths are identical |
| 1356 |
assert.Equal(t, resultCacheHit, resultCacheMiss, |
| 1357 |
"GetRenderedSchema should produce identical output regardless of cache state") |
| 1358 |
} |