-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.go
250 lines (225 loc) · 7.31 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
package openapi3middleware
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)
type middleware = func(next http.Handler) http.Handler
type MiddlewareOptions struct {
Router routers.Router
ValidationOptions *openapi3filter.Options
ReportFindRouteError func(w http.ResponseWriter, r *http.Request, err error)
ReportRequestValidationError func(w http.ResponseWriter, r *http.Request, err error)
ReportResponseValidationError func(w http.ResponseWriter, r *http.Request, err error)
TracerProvider trace.TracerProvider
}
func (o MiddlewareOptions) reportFindRouteError(w http.ResponseWriter, r *http.Request, err error) {
if f := o.ReportFindRouteError; f != nil {
f(w, r, err)
return
}
defaultReportFindRouteError(w, err)
}
func (o MiddlewareOptions) reportReqError(w http.ResponseWriter, r *http.Request, err error) {
if f := o.ReportRequestValidationError; f != nil {
f(w, r, err)
return
}
defaultReportRequestError(w, err)
}
func (o MiddlewareOptions) reportRespError(w http.ResponseWriter, r *http.Request, err error) {
if f := o.ReportResponseValidationError; f != nil {
f(w, r, err)
return
}
defaultReportResponseError(w, err)
}
// WithValidation returns a middleware that validates against both request and response.
func WithValidation(options MiddlewareOptions) middleware {
req := WithRequestValidation(options)
resp := WithResponseValidation(options)
return func(next http.Handler) http.Handler {
return req(resp(next))
}
}
// WithResponseValidation returns a middleware that validates against response.
// It may consume larger memory because it holds entire response body to validate it later.
func WithResponseValidation(options MiddlewareOptions) middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx, span := getTracer(ctx, options).Start(ctx, "ResponseValidation")
defer span.End()
irw := newBufferingResponseWriter(w)
next.ServeHTTP(irw, r.WithContext(ctx))
ri, err := buildRequestValidationInputFromRequest(options.Router, r, options.ValidationOptions)
if frErr := new(findRouteErr); errors.As(err, &frErr) {
actualErr := frErr.Unwrap()
span.RecordError(actualErr)
options.reportFindRouteError(w, r, actualErr)
return
} else if err != nil {
span.RecordError(err)
respondErrorJSON(w, http.StatusInternalServerError, err)
return
}
input := &openapi3filter.ResponseValidationInput{
RequestValidationInput: ri,
Status: irw.statusCode,
Header: irw.Header(),
}
if input.Status == 0 {
input.Status = http.StatusOK
}
bodyBytes := irw.buf.Bytes()
input.SetBodyBytes(bodyBytes)
if err := openapi3filter.ValidateResponse(ctx, input); err != nil {
span.RecordError(err)
options.reportRespError(w, r, err)
return
}
irw.emit()
})
}
}
// WithRequestValidation returns a middleware that validates against request.
// It immediately returns an error response and does not call next handler if validation failed.
func WithRequestValidation(options MiddlewareOptions) middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx, span := getTracer(ctx, options).Start(ctx, "RequestValidation")
defer span.End()
input, err := buildRequestValidationInputFromRequest(options.Router, r, options.ValidationOptions)
if frErr := new(findRouteErr); errors.As(err, &frErr) {
actualErr := frErr.Unwrap()
span.RecordError(actualErr)
options.reportFindRouteError(w, r, actualErr)
return
} else if err != nil {
span.RecordError(err)
respondErrorJSON(w, http.StatusInternalServerError, err)
return
}
if err := openapi3filter.ValidateRequest(ctx, input); err != nil {
span.RecordError(err)
options.reportReqError(w, r, err)
return
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
type findRouteErr struct {
err error
}
func (e *findRouteErr) Unwrap() error {
return e.err
}
func (e *findRouteErr) Error() string {
return e.err.Error()
}
func buildRequestValidationInputFromRequest(router routers.Router, r *http.Request, options *openapi3filter.Options) (*openapi3filter.RequestValidationInput, error) {
route, pathParams, err := router.FindRoute(r)
if err != nil {
return nil, &findRouteErr{err: err}
}
input := &openapi3filter.RequestValidationInput{
Request: r,
PathParams: pathParams,
Route: route,
Options: options,
}
return input, nil
}
type report struct {
Reason string `json:"reason"`
Field string `json:"field"`
Value interface{} `json:"value"`
Schema *openapi3.Schema `json:"schema"`
OriginError string `json:"origin,omitempty"`
}
func defaultReportFindRouteError(w http.ResponseWriter, err error) {
respondErrorJSON(w, http.StatusInternalServerError, err)
}
func defaultReportRequestError(w http.ResponseWriter, err error) {
requestErr := new(openapi3filter.RequestError)
if !errors.As(err, &requestErr) {
return
}
schemaErr := new(openapi3.SchemaError)
if errors.As(requestErr.Err, &schemaErr) {
_ = respondJSON(w, http.StatusBadRequest, rootError{
Error: errorAggregate{
Request: toReport(schemaErr),
}})
return
}
respondErrorJSON(w, http.StatusBadRequest, requestErr)
}
func defaultReportResponseError(w http.ResponseWriter, err error) {
responseErr := new(openapi3filter.ResponseError)
if !errors.As(err, &responseErr) {
return
}
if schemaErr := new(openapi3.SchemaError); errors.As(responseErr.Err, &schemaErr) {
_ = respondJSON(w, http.StatusInternalServerError, rootError{
Error: errorAggregate{
Response: toReport(schemaErr),
}})
return
}
respondErrorJSON(w, http.StatusInternalServerError, responseErr)
}
type rootError struct {
Error errorAggregate `json:"error"`
}
type errorAggregate struct {
Request *report `json:"request,omitempty"`
Response *report `json:"response,omitempty"`
}
func toReport(schemaErr *openapi3.SchemaError) *report {
if schemaErr == nil {
return nil
}
return &report{
Reason: schemaErr.Reason,
Field: schemaErr.SchemaField,
Value: schemaErr.Value,
Schema: schemaErr.Schema,
}
}
func respondErrorJSON(w http.ResponseWriter, statusCode int, err error) {
type errorStruct struct {
Message string
Kind string
}
type payload struct {
Error *errorStruct
}
_ = respondJSON(w, statusCode, payload{Error: &errorStruct{Message: err.Error(), Kind: fmt.Sprintf("%T", err)}})
}
func respondJSON(w http.ResponseWriter, statusCode int, payload interface{}) error {
w.Header().Set("content-type", "application/json")
w.WriteHeader(statusCode)
return json.NewEncoder(w).Encode(payload)
}
const tracerName = "github.com/aereal/go-openapi3-validation-middleware"
func getTracer(ctx context.Context, opts MiddlewareOptions) trace.Tracer {
tp := opts.TracerProvider
if tp == nil {
if span := trace.SpanFromContext(ctx); span.SpanContext().IsValid() {
tp = span.TracerProvider()
} else {
tp = otel.GetTracerProvider()
}
}
return tp.Tracer(tracerName)
}