| 1 |
package requests |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"io" |
| 6 |
"net/http" |
| 7 |
"net/url" |
| 8 |
"strings" |
| 9 |
"testing" |
| 10 |
|
| 11 |
"github.com/pb33f/libopenapi" |
| 12 |
"github.com/pb33f/libopenapi/datamodel/high/base" |
| 13 |
"github.com/stretchr/testify/assert" |
| 14 |
"github.com/stretchr/testify/require" |
| 15 |
|
| 16 |
"github.com/pb33f/libopenapi-validator/config" |
| 17 |
) |
| 18 |
|
| 19 |
func TestValidateRequestSchema(t *testing.T) { |
| 20 |
for name, tc := range map[string]struct { |
| 21 |
request *http.Request |
| 22 |
schemaYAML string |
| 23 |
version float32 |
| 24 |
assertValidRequestSchema assert.BoolAssertionFunc |
| 25 |
expectedErrorsCount int |
| 26 |
}{ |
| 27 |
"FailOnBooleanExclusiveMinimum": { |
| 28 |
request: postRequestWithBody(`{"exclusiveNumber": 10}`), |
| 29 |
schemaYAML: `type: object |
| 30 |
properties: |
| 31 |
exclusiveNumber: |
| 32 |
type: number |
| 33 |
description: This number starts its journey where most numbers are too scared to begin! |
| 34 |
exclusiveMinimum: true |
| 35 |
minimum: !!float 10`, |
| 36 |
version: 3.0, |
| 37 |
assertValidRequestSchema: assert.False, |
| 38 |
expectedErrorsCount: 1, |
| 39 |
}, |
| 40 |
"PassWithCorrectExclusiveMinimum": { |
| 41 |
request: postRequestWithBody(`{"exclusiveNumber": 15}`), |
| 42 |
schemaYAML: `type: object |
| 43 |
properties: |
| 44 |
exclusiveNumber: |
| 45 |
type: number |
| 46 |
description: This number is properly constrained by a numeric exclusive minimum. |
| 47 |
exclusiveMinimum: 12 |
| 48 |
minimum: 12`, |
| 49 |
version: 3.1, |
| 50 |
assertValidRequestSchema: assert.True, |
| 51 |
expectedErrorsCount: 0, |
| 52 |
}, |
| 53 |
"PassWithValidStringType": { |
| 54 |
request: postRequestWithBody(`{"greeting": "Hello, world!"}`), |
| 55 |
schemaYAML: `type: object |
| 56 |
properties: |
| 57 |
greeting: |
| 58 |
type: string |
| 59 |
description: A simple greeting |
| 60 |
example: "Hello, world!"`, |
| 61 |
version: 3.1, |
| 62 |
assertValidRequestSchema: assert.True, |
| 63 |
expectedErrorsCount: 0, |
| 64 |
}, |
| 65 |
"PassWithNullablePropertyInOpenAPI30": { |
| 66 |
request: postRequestWithBody(`{"name": "John", "middleName": null}`), |
| 67 |
schemaYAML: `type: object |
| 68 |
properties: |
| 69 |
name: |
| 70 |
type: string |
| 71 |
description: User's first name |
| 72 |
middleName: |
| 73 |
type: string |
| 74 |
nullable: true |
| 75 |
description: User's middle name (optional)`, |
| 76 |
version: 3.0, |
| 77 |
assertValidRequestSchema: assert.True, |
| 78 |
expectedErrorsCount: 0, |
| 79 |
}, |
| 80 |
"PassWithNullablePropertyInOpenAPI31": { |
| 81 |
request: postRequestWithBody(`{"name": "John", "middleName": null}`), |
| 82 |
schemaYAML: `type: object |
| 83 |
properties: |
| 84 |
name: |
| 85 |
type: string |
| 86 |
description: User's first name |
| 87 |
middleName: |
| 88 |
type: string |
| 89 |
nullable: true |
| 90 |
description: User's middle name (optional)`, |
| 91 |
version: 3.1, |
| 92 |
assertValidRequestSchema: assert.False, |
| 93 |
expectedErrorsCount: 1, |
| 94 |
}, |
| 95 |
} { |
| 96 |
t.Run(name, func(t *testing.T) { |
| 97 |
t.Parallel() |
| 98 |
|
| 99 |
schema := parseSchemaFromSpec(t, tc.schemaYAML, tc.version) |
| 100 |
|
| 101 |
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 102 |
Request: tc.request, |
| 103 |
Schema: schema, |
| 104 |
Version: tc.version, |
| 105 |
}) |
| 106 |
|
| 107 |
tc.assertValidRequestSchema(t, valid) |
| 108 |
assert.Len(t, errors, tc.expectedErrorsCount) |
| 109 |
}) |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
func TestBooleanExclusiveMin_ValidValue(t *testing.T) { |
| 114 |
openAPIVersion := float32(3.0) |
| 115 |
schema := parseSchemaFromSpec(t, `type: object |
| 116 |
properties: |
| 117 |
exclusiveNumber: |
| 118 |
type: number |
| 119 |
description: This number starts its journey where most numbers are too scared to begin! |
| 120 |
exclusiveMinimum: true |
| 121 |
minimum: 10`, openAPIVersion) |
| 122 |
|
| 123 |
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 124 |
Request: postRequestWithBody(`{"exclusiveNumber": 13}`), |
| 125 |
Schema: schema, |
| 126 |
Version: openAPIVersion, |
| 127 |
}) |
| 128 |
|
| 129 |
assert.True(t, valid) |
| 130 |
assert.Empty(t, errors) |
| 131 |
} |
| 132 |
|
| 133 |
func TestValidateRequestSchema_CachePopulation(t *testing.T) { |
| 134 |
openAPIVersion := float32(3.1) |
| 135 |
schema := parseSchemaFromSpec(t, `type: object |
| 136 |
properties: |
| 137 |
name: |
| 138 |
type: string`, openAPIVersion) |
| 139 |
|
| 140 |
// Create options with a cache |
| 141 |
opts := config.NewValidationOptions() |
| 142 |
require.NotNil(t, opts.SchemaCache) |
| 143 |
|
| 144 |
// First call should populate the cache |
| 145 |
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 146 |
Request: postRequestWithBody(`{"name": "test"}`), |
| 147 |
Schema: schema, |
| 148 |
Version: openAPIVersion, |
| 149 |
Options: []config.Option{config.WithExistingOpts(opts)}, |
| 150 |
}) |
| 151 |
|
| 152 |
assert.True(t, valid) |
| 153 |
assert.Len(t, errors, 0) |
| 154 |
|
| 155 |
// Verify cache was populated |
| 156 |
hash := schema.GoLow().Hash() |
| 157 |
cached, ok := opts.SchemaCache.Load(hash) |
| 158 |
assert.True(t, ok, "Schema should be in cache") |
| 159 |
assert.NotNil(t, cached, "Cached entry should not be nil") |
| 160 |
assert.NotNil(t, cached.CompiledSchema, "Compiled schema should be cached") |
| 161 |
assert.NotNil(t, cached.RenderedInline, "Rendered schema should be cached") |
| 162 |
assert.NotNil(t, cached.RenderedJSON, "JSON schema should be cached") |
| 163 |
} |
| 164 |
|
| 165 |
func TestValidateRequestSchema_NilSchema(t *testing.T) { |
| 166 |
// Test when schema is nil |
| 167 |
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 168 |
Request: postRequestWithBody(`{"name": "test"}`), |
| 169 |
Schema: nil, |
| 170 |
Version: 3.1, |
| 171 |
}) |
| 172 |
|
| 173 |
assert.False(t, valid) |
| 174 |
require.Len(t, errors, 1) |
| 175 |
assert.Equal(t, "schema is nil", errors[0].Message) |
| 176 |
assert.Equal(t, "The schema to validate against is nil", errors[0].Reason) |
| 177 |
} |
| 178 |
|
| 179 |
func TestValidateRequestSchema_NilSchemaGoLow(t *testing.T) { |
| 180 |
// Test when schema.GoLow() is nil by creating a schema without low-level data |
| 181 |
schema := &base.Schema{} // Empty schema without GoLow() data |
| 182 |
|
| 183 |
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 184 |
Request: postRequestWithBody(`{"name": "test"}`), |
| 185 |
Schema: schema, |
| 186 |
Version: 3.1, |
| 187 |
}) |
| 188 |
|
| 189 |
assert.False(t, valid) |
| 190 |
require.Len(t, errors, 1) |
| 191 |
assert.Equal(t, "schema cannot be rendered", errors[0].Message) |
| 192 |
assert.Contains(t, errors[0].Reason, "does not have low-level information") |
| 193 |
} |
| 194 |
|
| 195 |
func TestValidateRequestSchema_EmptyBodyOptional(t *testing.T) { |
| 196 |
schema := parseSchemaFromSpec(t, `type: object |
| 197 |
properties: |
| 198 |
name: |
| 199 |
type: string`, 3.1) |
| 200 |
|
| 201 |
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 202 |
Request: emptyPostRequest(), |
| 203 |
Schema: schema, |
| 204 |
Version: 3.1, |
| 205 |
BodyRequired: false, |
| 206 |
}) |
| 207 |
|
| 208 |
assert.True(t, valid) |
| 209 |
assert.Empty(t, errors) |
| 210 |
} |
| 211 |
|
| 212 |
func TestValidateRequestSchema_EmptyBodyRequired(t *testing.T) { |
| 213 |
schema := parseSchemaFromSpec(t, `type: object |
| 214 |
properties: |
| 215 |
name: |
| 216 |
type: string`, 3.1) |
| 217 |
|
| 218 |
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 219 |
Request: emptyPostRequest(), |
| 220 |
Schema: schema, |
| 221 |
Version: 3.1, |
| 222 |
BodyRequired: true, |
| 223 |
}) |
| 224 |
|
| 225 |
assert.False(t, valid) |
| 226 |
require.Len(t, errors, 1) |
| 227 |
assert.Contains(t, errors[0].Message, "request body is empty") |
| 228 |
} |
| 229 |
|
| 230 |
func postRequestWithBody(payload string) *http.Request { |
| 231 |
return &http.Request{ |
| 232 |
Method: http.MethodPost, |
| 233 |
URL: &url.URL{Path: "/test"}, |
| 234 |
Body: io.NopCloser(strings.NewReader(payload)), |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
func emptyPostRequest() *http.Request { |
| 239 |
return &http.Request{ |
| 240 |
Method: http.MethodPost, |
| 241 |
URL: &url.URL{Path: "/test"}, |
| 242 |
Body: http.NoBody, |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
// parseSchemaFromSpec creates a base.Schema from an OpenAPI spec YAML string. |
| 247 |
// This ensures that we're using the native libopenapi logic for generating the schema. |
| 248 |
func parseSchemaFromSpec(t *testing.T, schemaYAML string, version float32) *base.Schema { |
| 249 |
// Convert version to API version string (3.0 -> "3.0.0", 3.1 -> "3.1.0") |
| 250 |
apiVersion := fmt.Sprintf("%.1f.0", version) |
| 251 |
|
| 252 |
spec := fmt.Sprintf(`openapi: %s |
| 253 |
info: |
| 254 |
title: Test |
| 255 |
version: 1.0.0 |
| 256 |
components: |
| 257 |
schemas: |
| 258 |
TestSchema: |
| 259 |
%s`, apiVersion, indentLines(schemaYAML, " ")) |
| 260 |
|
| 261 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 262 |
require.NoError(t, err) |
| 263 |
model, errs := doc.BuildV3Model() |
| 264 |
require.Empty(t, errs) |
| 265 |
schema := model.Model.Components.Schemas.GetOrZero("TestSchema") |
| 266 |
require.NotNil(t, schema) |
| 267 |
return schema.Schema() |
| 268 |
} |
| 269 |
|
| 270 |
// indentLines adds the specified indentation to each line of the input string |
| 271 |
func indentLines(s string, indent string) string { |
| 272 |
lines := strings.Split(strings.TrimSpace(s), "\n") |
| 273 |
for i, line := range lines { |
| 274 |
if line != "" { |
| 275 |
lines[i] = indent + line |
| 276 |
} |
| 277 |
} |
| 278 |
return strings.Join(lines, "\n") |
| 279 |
} |
| 280 |
|
| 281 |
func TestValidateRequestSchema_CircularReference(t *testing.T) { |
| 282 |
// Test when schema has a circular reference that causes render failure |
| 283 |
spec := `openapi: 3.1.0 |
| 284 |
info: |
| 285 |
title: Test |
| 286 |
version: 1.0.0 |
| 287 |
components: |
| 288 |
schemas: |
| 289 |
Error: |
| 290 |
type: object |
| 291 |
properties: |
| 292 |
code: |
| 293 |
type: string |
| 294 |
details: |
| 295 |
type: array |
| 296 |
items: |
| 297 |
$ref: '#/components/schemas/Error'` |
| 298 |
|
| 299 |
doc, err := libopenapi.NewDocument([]byte(spec)) |
| 300 |
require.NoError(t, err) |
| 301 |
model, errs := doc.BuildV3Model() |
| 302 |
require.Empty(t, errs) |
| 303 |
|
| 304 |
// Verify circular reference was detected |
| 305 |
require.Len(t, model.Index.GetCircularReferences(), 1) |
| 306 |
|
| 307 |
schema := model.Model.Components.Schemas.GetOrZero("Error") |
| 308 |
require.NotNil(t, schema) |
| 309 |
|
| 310 |
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 311 |
Request: postRequestWithBody(`{"code": "abc", "details": [{"code": "def"}]}`), |
| 312 |
Schema: schema.Schema(), |
| 313 |
Version: 3.1, |
| 314 |
}) |
| 315 |
|
| 316 |
assert.False(t, valid) |
| 317 |
require.Len(t, errors, 1) |
| 318 |
assert.Contains(t, errors[0].Message, "failed schema rendering") |
| 319 |
assert.Contains(t, errors[0].Reason, "circular reference") |
| 320 |
} |
| 321 |
|
| 322 |
func TestValidateRequestSchema_NilParentProxy(t *testing.T) { |
| 323 |
// Schema with nil ParentProxy and empty body — should not panic (fix for wiretap #134) |
| 324 |
schema := &base.Schema{ |
| 325 |
Type: []string{"object"}, |
| 326 |
} |
| 327 |
|
| 328 |
valid, errs := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 329 |
Request: postRequestWithBody(""), |
| 330 |
Schema: schema, |
| 331 |
Version: 3.1, |
| 332 |
BodyRequired: true, |
| 333 |
}) |
| 334 |
|
| 335 |
// Should return error about nil schema low-level info, not panic |
| 336 |
assert.False(t, valid) |
| 337 |
assert.NotEmpty(t, errs) |
| 338 |
} |