/
middleware.go
283 lines (244 loc) · 7.34 KB
/
middleware.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
package openapi3filter
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/http"
"github.com/getkin/kin-openapi/routers"
)
// Validator provides HTTP request and response validation middleware.
type Validator struct {
router routers.Router
errFunc ErrFunc
logFunc LogFunc
strict bool
options Options
}
// ErrFunc handles errors that may occur during validation.
type ErrFunc func(w http.ResponseWriter, status int, code ErrCode, err error)
// LogFunc handles log messages that may occur during validation.
type LogFunc func(message string, err error)
// ErrCode is used for classification of different types of errors that may
// occur during validation. These may be used to write an appropriate response
// in ErrFunc.
type ErrCode int
const (
// ErrCodeOK indicates no error. It is also the default value.
ErrCodeOK = 0
// ErrCodeCannotFindRoute happens when the validator fails to resolve the
// request to a defined OpenAPI route.
ErrCodeCannotFindRoute = iota
// ErrCodeRequestInvalid happens when the inbound request does not conform
// to the OpenAPI 3 specification.
ErrCodeRequestInvalid = iota
// ErrCodeResponseInvalid happens when the wrapped handler response does
// not conform to the OpenAPI 3 specification.
ErrCodeResponseInvalid = iota
)
func (e ErrCode) responseText() string {
switch e {
case ErrCodeOK:
return "OK"
case ErrCodeCannotFindRoute:
return "not found"
case ErrCodeRequestInvalid:
return "bad request"
default:
return "server error"
}
}
// NewValidator returns a new response validation middlware, using the given
// routes from an OpenAPI 3 specification.
func NewValidator(router routers.Router, options ...ValidatorOption) *Validator {
v := &Validator{
router: router,
errFunc: func(w http.ResponseWriter, status int, code ErrCode, _ error) {
http.Error(w, code.responseText(), status)
},
logFunc: func(message string, err error) {
log.Printf("%s: %v", message, err)
},
}
for i := range options {
options[i](v)
}
return v
}
// ValidatorOption defines an option that may be specified when creating a
// Validator.
type ValidatorOption func(*Validator)
// OnErr provides a callback that handles writing an HTTP response on a
// validation error. This allows customization of error responses without
// prescribing a particular form. This callback is only called on response
// validator errors in Strict mode.
func OnErr(f ErrFunc) ValidatorOption {
return func(v *Validator) {
v.errFunc = f
}
}
// OnLog provides a callback that handles logging in the Validator. This allows
// the validator to integrate with a services' existing logging system without
// prescribing a particular one.
func OnLog(f LogFunc) ValidatorOption {
return func(v *Validator) {
v.logFunc = f
}
}
// Strict, if set, causes an internal server error to be sent if the wrapped
// handler response fails response validation. If not set, the response is sent
// and the error is only logged.
func Strict(strict bool) ValidatorOption {
return func(v *Validator) {
v.strict = strict
}
}
// ValidationOptions sets request/response validation options on the validator.
func ValidationOptions(options Options) ValidatorOption {
return func(v *Validator) {
v.options = options
}
}
// Middleware returns an http.Handler which wraps the given handler with
// request and response validation.
func (v *Validator) Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route, pathParams, err := v.router.FindRoute(r)
if err != nil {
v.logFunc("validation error: failed to find route for "+r.URL.String(), err)
v.errFunc(w, http.StatusNotFound, ErrCodeCannotFindRoute, err)
return
}
requestValidationInput := &RequestValidationInput{
Request: r,
PathParams: pathParams,
Route: route,
Options: &v.options,
}
if err = ValidateRequest(r.Context(), requestValidationInput); err != nil {
v.logFunc("invalid request", err)
v.errFunc(w, http.StatusBadRequest, ErrCodeRequestInvalid, err)
return
}
var wr responseWrapper
if v.strict {
wr = &strictResponseWrapper{w: w}
} else {
wr = newWarnResponseWrapper(w)
}
h.ServeHTTP(wr, r)
if err = ValidateResponse(r.Context(), &ResponseValidationInput{
RequestValidationInput: requestValidationInput,
Status: wr.statusCode(),
Header: wr.Header(),
Body: ioutil.NopCloser(bytes.NewBuffer(wr.bodyContents())),
Options: &v.options,
}); err != nil {
v.logFunc("invalid response", err)
if v.strict {
v.errFunc(w, http.StatusInternalServerError, ErrCodeResponseInvalid, err)
}
return
}
if err = wr.flushBodyContents(); err != nil {
v.logFunc("failed to write response", err)
}
})
}
type responseWrapper interface {
http.ResponseWriter
// flushBodyContents writes the buffered response to the client, if it has
// not yet been written.
flushBodyContents() error
// statusCode returns the response status code, 0 if not set yet.
statusCode() int
// bodyContents returns the buffered
bodyContents() []byte
}
type warnResponseWrapper struct {
w http.ResponseWriter
headerWritten bool
status int
body bytes.Buffer
tee io.Writer
}
func newWarnResponseWrapper(w http.ResponseWriter) *warnResponseWrapper {
wr := &warnResponseWrapper{
w: w,
}
wr.tee = io.MultiWriter(w, &wr.body)
return wr
}
// Write implements http.ResponseWriter.
func (wr *warnResponseWrapper) Write(b []byte) (int, error) {
if !wr.headerWritten {
wr.WriteHeader(http.StatusOK)
}
return wr.tee.Write(b)
}
// WriteHeader implements http.ResponseWriter.
func (wr *warnResponseWrapper) WriteHeader(status int) {
if !wr.headerWritten {
// If the header hasn't been written, record the status for response
// validation.
wr.status = status
wr.headerWritten = true
}
wr.w.WriteHeader(wr.status)
}
// Header implements http.ResponseWriter.
func (wr *warnResponseWrapper) Header() http.Header {
return wr.w.Header()
}
// Flush implements the optional http.Flusher interface.
func (wr *warnResponseWrapper) Flush() {
// If the wrapped http.ResponseWriter implements optional http.Flusher,
// pass through.
if fl, ok := wr.w.(http.Flusher); ok {
fl.Flush()
}
}
func (wr *warnResponseWrapper) flushBodyContents() error {
return nil
}
func (wr *warnResponseWrapper) statusCode() int {
return wr.status
}
func (wr *warnResponseWrapper) bodyContents() []byte {
return wr.body.Bytes()
}
type strictResponseWrapper struct {
w http.ResponseWriter
headerWritten bool
status int
body bytes.Buffer
}
// Write implements http.ResponseWriter.
func (wr *strictResponseWrapper) Write(b []byte) (int, error) {
if !wr.headerWritten {
wr.WriteHeader(http.StatusOK)
}
return wr.body.Write(b)
}
// WriteHeader implements http.ResponseWriter.
func (wr *strictResponseWrapper) WriteHeader(status int) {
if !wr.headerWritten {
wr.status = status
wr.headerWritten = true
}
}
// Header implements http.ResponseWriter.
func (wr *strictResponseWrapper) Header() http.Header {
return wr.w.Header()
}
func (wr *strictResponseWrapper) flushBodyContents() error {
wr.w.WriteHeader(wr.status)
_, err := wr.w.Write(wr.body.Bytes())
return err
}
func (wr *strictResponseWrapper) statusCode() int {
return wr.status
}
func (wr *strictResponseWrapper) bodyContents() []byte {
return wr.body.Bytes()
}