-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
http_validator.go
331 lines (306 loc) · 8.17 KB
/
http_validator.go
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
322
323
324
325
326
327
328
329
330
331
package runn
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/goccy/go-yaml"
"github.com/pb33f/libopenapi"
validator "github.com/pb33f/libopenapi-validator"
verrors "github.com/pb33f/libopenapi-validator/errors"
"github.com/pb33f/libopenapi/datamodel"
)
type httpValidator interface { //nostyle:ifacenames
ValidateRequest(ctx context.Context, req *http.Request) error
ValidateResponse(ctx context.Context, req *http.Request, res *http.Response) error
}
type UnsupportedError struct {
Cause error
}
func (e *UnsupportedError) Error() string {
return e.Cause.Error()
}
func (e *UnsupportedError) Unwrap() error {
return e.Cause
}
func newHttpValidator(c *httpRunnerConfig) (httpValidator, error) {
if c.OpenAPI3DocLocation != "" || c.openAPI3Doc != nil {
return newOpenAPI3Validator(c)
}
return newNopValidator(), nil
}
type nopValidator struct{}
func (v *nopValidator) ValidateRequest(ctx context.Context, req *http.Request) error {
return nil
}
func (v *nopValidator) ValidateResponse(ctx context.Context, req *http.Request, res *http.Response) error {
return nil
}
func newNopValidator() *nopValidator {
return &nopValidator{}
}
// globalOpenAPI3DocRegistory - global registory of OpenAPI3 documents.
var globalOpenAPI3DocRegistory = map[string]libopenapi.Document{}
var globalOpenAPI3DocRegistoryMu sync.RWMutex
type openAPI3Validator struct {
skipValidateRequest bool
skipValidateResponse bool
doc libopenapi.Document
validator validator.Validator
}
func newOpenAPI3Validator(c *httpRunnerConfig) (*openAPI3Validator, error) {
if c.OpenAPI3DocLocation == "" && c.openAPI3Doc == nil {
return nil, errors.New("cannot load openapi3 document")
}
var hash string
if c.OpenAPI3DocLocation != "" {
l := c.OpenAPI3DocLocation
var doc libopenapi.Document
switch {
case strings.HasPrefix(l, "https://") || strings.HasPrefix(l, "http://"):
u, err := url.Parse(l)
if err != nil {
return nil, err
}
res, err := http.Get(u.String())
if err != nil {
return nil, err
}
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
hash = hashBytes(b)
globalOpenAPI3DocRegistoryMu.RLock()
od, ok := globalOpenAPI3DocRegistory[hash]
globalOpenAPI3DocRegistoryMu.RUnlock()
if ok {
v, errs := validator.NewValidator(od)
if len(errs) > 0 {
return nil, errors.Join(errs...)
}
return &openAPI3Validator{
skipValidateRequest: c.SkipValidateRequest,
skipValidateResponse: c.SkipValidateResponse,
doc: od,
validator: v,
}, nil
}
oc := &datamodel.DocumentConfiguration{
AllowFileReferences: true,
AllowRemoteReferences: true,
SkipCircularReferenceCheck: c.SkipCircularReferenceCheck,
}
doc, err = libopenapi.NewDocumentWithConfiguration(b, oc)
if err != nil {
return nil, err
}
default:
b, err := os.ReadFile(l)
if err != nil {
return nil, err
}
hash = hashBytes(b)
globalOpenAPI3DocRegistoryMu.RLock()
od, ok := globalOpenAPI3DocRegistory[hash]
globalOpenAPI3DocRegistoryMu.RUnlock()
if ok {
v, errs := validator.NewValidator(od)
if len(errs) > 0 {
return nil, errors.Join(errs...)
}
return &openAPI3Validator{
skipValidateRequest: c.SkipValidateRequest,
skipValidateResponse: c.SkipValidateResponse,
doc: od,
validator: v,
}, nil
}
oc := &datamodel.DocumentConfiguration{
AllowFileReferences: true,
AllowRemoteReferences: true,
SkipCircularReferenceCheck: c.SkipCircularReferenceCheck,
BasePath: filepath.Dir(l),
}
doc, err = libopenapi.NewDocumentWithConfiguration(b, oc)
if err != nil {
return nil, err
}
}
c.openAPI3Doc = doc
}
v, errs := validator.NewValidator(c.openAPI3Doc)
if len(errs) > 0 {
return nil, errors.Join(errs...)
}
if _, errs := v.ValidateDocument(); len(errs) > 0 {
var err error
for _, e := range errs {
err = errors.Join(err, e)
}
return nil, err
}
globalOpenAPI3DocRegistoryMu.Lock()
globalOpenAPI3DocRegistory[hash] = c.openAPI3Doc
globalOpenAPI3DocRegistoryMu.Unlock()
return &openAPI3Validator{
skipValidateRequest: c.SkipValidateRequest,
skipValidateResponse: c.SkipValidateResponse,
doc: c.openAPI3Doc,
validator: v,
}, nil
}
func (v *openAPI3Validator) ValidateRequest(ctx context.Context, req *http.Request) error {
if v.skipValidateRequest {
return nil
}
globalOpenAPI3DocRegistoryMu.Lock()
_, errs := v.validator.ValidateHttpRequest(req)
if len(errs) == 0 {
globalOpenAPI3DocRegistoryMu.Unlock()
return nil
}
{
// renew validator (workaround)
// ref: https://github.com/k1LoW/runn/issues/882
vv, errrs := validator.NewValidator(v.doc)
if len(errrs) > 0 {
globalOpenAPI3DocRegistoryMu.Unlock()
return errors.Join(errrs...)
}
v.validator = vv
}
globalOpenAPI3DocRegistoryMu.Unlock()
var err error
for _, e := range errs {
// nullable type workaround.
if nullableError(e) {
continue
}
err = errors.Join(err, e)
}
if err == nil {
return nil
}
b, errr := httputil.DumpRequest(req, true)
if errr != nil {
return fmt.Errorf("runn error: %w", errr)
}
return fmt.Errorf("openapi3 validation error: %w\n-----START HTTP REQUEST-----\n%s\n-----END HTTP REQUEST-----\n", err, string(b))
}
func (v *openAPI3Validator) ValidateResponse(ctx context.Context, req *http.Request, res *http.Response) error {
if v.skipValidateResponse {
return nil
}
globalOpenAPI3DocRegistoryMu.Lock()
_, errs := v.validator.ValidateHttpResponse(req, res)
if len(errs) == 0 {
globalOpenAPI3DocRegistoryMu.Unlock()
return nil
}
{
// renew validator (workaround)
// ref: https://github.com/k1LoW/runn/issues/882
vv, errrs := validator.NewValidator(v.doc)
if len(errrs) > 0 {
globalOpenAPI3DocRegistoryMu.Unlock()
return errors.Join(errrs...)
}
v.validator = vv
}
globalOpenAPI3DocRegistoryMu.Unlock()
var err error
for _, e := range errs {
// nullable type workaround.
if nullableError(e) {
continue
}
err = errors.Join(err, e)
}
if err == nil {
return nil
}
b, errr := httputil.DumpRequest(req, true)
if errr != nil {
return fmt.Errorf("runn error: %w", errr)
}
b2, errr := httputil.DumpResponse(res, true)
if errr != nil {
return fmt.Errorf("runn error: %w", errr)
}
return fmt.Errorf("openapi3 validation error: %w\n-----START HTTP REQUEST-----\n%s\n-----END HTTP REQUEST-----\n-----START HTTP RESPONSE-----\n%s\n-----END HTTP RESPONSE-----\n", err, string(b), string(b2))
}
func hashBytes(b []byte) string {
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}
// nullableTypeError returns whether the error is nullable type error or not.
func nullableError(e *verrors.ValidationError) bool {
if len(e.SchemaValidationErrors) > 0 {
for _, ve := range e.SchemaValidationErrors {
if strings.HasSuffix(ve.Reason, "but got null") && strings.HasSuffix(ve.Location, "/type") {
if nullableType(ve.ReferenceSchema, ve.Location) {
return true
}
}
}
}
return false
}
// nullableType returns whether the type is nullable or not.
func nullableType(schema, location string) bool {
splitted := strings.Split(strings.TrimPrefix(strings.TrimSuffix(location, "/type")+"/nullable", "/"), "/")
m := map[string]any{}
if err := yaml.Unmarshal([]byte(schema), &m); err != nil {
return false
}
v, ok := valueWithKeys(m, splitted...)
if !ok {
return false
}
if tf, ok := v.(bool); ok {
return tf
}
return false
}
func valueWithKeys(m any, keys ...string) (any, bool) {
if len(keys) == 0 {
return nil, false
}
switch m := m.(type) {
case map[string]any:
if v, ok := m[keys[0]]; ok {
if len(keys) == 1 {
return v, true
}
return valueWithKeys(v, keys[1:]...)
}
case []any:
i, err := strconv.Atoi(keys[0])
if err != nil {
return nil, false
}
if i < 0 || i >= len(m) {
return nil, false
}
v := m[i]
if len(keys) == 1 {
return v, true
}
return valueWithKeys(v, keys[1:]...)
default:
return nil, false
}
return nil, false
}