-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
openapi3.go
184 lines (170 loc) · 4.12 KB
/
openapi3.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
package httpstub
import (
"bytes"
"errors"
"io"
"net/http"
"strconv"
"strings"
validator "github.com/pb33f/libopenapi-validator"
verrors "github.com/pb33f/libopenapi-validator/errors"
"gopkg.in/yaml.v3"
)
var _ http.ResponseWriter = (*recorder)(nil)
type recorder struct {
rw http.ResponseWriter
statusCode int
body *bytes.Buffer
}
func newRecorder(rw http.ResponseWriter) *recorder {
return &recorder{
rw: rw,
body: bytes.NewBuffer(nil),
}
}
func (r *recorder) Header() http.Header {
return r.rw.Header()
}
func (r *recorder) Write(b []byte) (int, error) {
if n, err := r.body.Write(b); err != nil {
return n, err
}
return r.rw.Write(b)
}
func (r *recorder) WriteHeader(statusCode int) {
r.statusCode = statusCode
r.rw.WriteHeader(statusCode)
}
func (r *recorder) toResponse() *http.Response {
return &http.Response{
Status: http.StatusText(r.statusCode),
StatusCode: r.statusCode,
Body: io.NopCloser(r.body),
Header: r.rw.Header().Clone(),
}
}
func (rt *Router) setOpenApi3Vaildator() error {
rt.t.Helper()
rt.mu.Lock()
defer rt.mu.Unlock()
if rt.openAPI3Doc == nil {
return nil
}
mw := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
v := rt.openAPI3Validator
if !rt.skipValidateRequest {
_, errs := v.ValidateHttpRequest(r)
if len(errs) > 0 {
{
// renew validator (workaround)
// ref: https://github.com/k1LoW/runn/issues/882
vv, errrs := validator.NewValidator(rt.openAPI3Doc)
if len(errrs) > 0 {
rt.t.Errorf("failed to renew validator: %v", errors.Join(errrs...))
return
}
rt.openAPI3Validator = vv
v = rt.openAPI3Validator
}
var err error
for _, e := range errs {
// nullable type workaround.
if nullableError(e) {
continue
}
err = errors.Join(err, e)
}
rt.t.Errorf("failed to validate response: %v", err)
}
}
rec := newRecorder(w)
next.ServeHTTP(rec, r)
if !rt.skipValidateResponse {
_, errs := v.ValidateHttpResponse(r, rec.toResponse())
if len(errs) > 0 {
{
// renew validator (workaround)
// ref: https://github.com/k1LoW/runn/issues/882
vv, errrs := validator.NewValidator(rt.openAPI3Doc)
if len(errrs) > 0 {
rt.t.Errorf("failed to renew validator: %v", errors.Join(errrs...))
return
}
rt.openAPI3Validator = vv
}
var err error
for _, e := range errs {
// nullable type workaround.
if nullableError(e) {
continue
}
err = errors.Join(err, e)
}
rt.t.Errorf("failed to validate response: %v", err)
}
}
}
}
rt.middlewares = append(rt.middlewares, mw)
return nil
}
// 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
}