Repository navigation
Expand file tree
/
Copy pathoapi_validate.go
More file actions
237 lines (203 loc) · 8.27 KB
/
Copy pathoapi_validate.go
File metadata and controls
237 lines (203 loc) · 8.27 KB
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
// Package middleware implements middleware function for server implementations,
// which validates incoming HTTP requests to make sure that they conform to the given OAPI 3.0 specification.
// When OAPI validation fails on the request, we return an HTTP/400.
package fibermiddleware
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"strings"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers"
"github.com/getkin/kin-openapi/routers/gorillamux"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor"
)
type ctxKeyFiberContext struct{}
type ctxKeyUserData struct{}
// OapiValidatorFromYamlFile creates a validator middleware from a YAML file path
func OapiValidatorFromYamlFile(path string) (fiber.Handler, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("error reading %s: %s", path, err)
}
swagger, err := openapi3.NewLoader().LoadFromData(data)
if err != nil {
return nil, fmt.Errorf("error parsing %s as Swagger YAML: %s",
path, err)
}
return OapiRequestValidator(swagger), nil
}
// OapiRequestValidator is a fiber middleware function which validates incoming HTTP requests
// to make sure that they conform to the given OAPI 3.0 specification. When
// OAPI validation fails on the request, we return an HTTP/400 with error message
func OapiRequestValidator(swagger *openapi3.T) fiber.Handler {
return OapiRequestValidatorWithOptions(swagger, nil)
}
// ErrorHandler is called when there is an error in validation
type ErrorHandler func(c fiber.Ctx, message string, statusCode int)
// MultiErrorHandler is called when oapi returns a MultiError type
type MultiErrorHandler func(openapi3.MultiError) error
// Options to customize request validation. These are passed through to
// openapi3filter.
type Options struct {
Options openapi3filter.Options
ErrorHandler ErrorHandler
ParamDecoder openapi3filter.ContentParameterDecoder
UserData interface{}
MultiErrorHandler MultiErrorHandler
// DiscardValidatedValue turns off openapi3filter.Options.KeepValidatedValue,
// which this middleware enables by default. With it enabled, the decoded
// request body value that passed validation is stored in the Fiber context
// under ValidatedBodyLocalsKey, so a handler (for example an oapi-codegen
// strict server) can bind that value instead of decoding the body a second
// time. Set this to drop the decoded value after validation, for instance to
// limit memory retention for very large request bodies.
//
// Options.Options.KeepValidatedValue is overridden by this setting.
DiscardValidatedValue bool
}
// ValidatedBodyLocalsKey is the c.Locals key under which the middleware stores
// the decoded request body value that passed validation (see
// Options.DiscardValidatedValue). The value is what kin-openapi validated:
// nil, bool, string, json.Number, []any or map[string]any.
//
// Strict servers generated by oapi-codegen look the value up under this same
// key, where it is defined independently so generated code does not import
// this module. Keep the two in sync.
const ValidatedBodyLocalsKey = "x-oapi-codegen-validated-body"
// ValidatedBody returns the request body value that passed validation, as
// stored by the middleware under ValidatedBodyLocalsKey, and whether one was
// stored for this request.
func ValidatedBody(c fiber.Ctx) (any, bool) {
v := c.Locals(ValidatedBodyLocalsKey)
return v, v != nil
}
// OapiRequestValidatorWithOptions creates a validator from a swagger object, with validation options
func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) fiber.Handler {
router, err := gorillamux.NewRouter(swagger)
if err != nil {
panic(err)
}
return func(c fiber.Ctx) error {
err := ValidateRequestFromContext(c, router, options)
if err != nil {
if options != nil && options.ErrorHandler != nil {
options.ErrorHandler(c, err.Error(), http.StatusBadRequest)
// in case the handler didn't internally call Abort, stop the chain
return nil
} else {
// note: I am not sure if this is the best way to handle this
return fiber.NewError(http.StatusBadRequest, err.Error())
}
}
return c.Next()
}
}
// ValidateRequestFromContext is called from the middleware above and actually does the work
// of validating a request.
func ValidateRequestFromContext(c fiber.Ctx, router routers.Router, options *Options) error {
r, err := adaptor.ConvertRequest(c, false)
if err != nil {
return err
}
route, pathParams, err := router.FindRoute(r)
// We failed to find a matching route for the request.
if err != nil {
switch e := err.(type) {
case *routers.RouteError:
// We've got a bad request, the path requested doesn't match
// either server, or path, or something.
return errors.New(e.Reason)
default:
// This should never happen today, but if our upstream code changes,
// we don't want to crash the server, so handle the unexpected error.
return fmt.Errorf("error validating route: %s", err.Error())
}
}
// Validate request
requestValidationInput := &openapi3filter.RequestValidationInput{
Request: r,
PathParams: pathParams,
Route: route,
}
// Pass the fiber context into the request validator, so that any callbacks
// which it invokes make it available.
requestContext := context.WithValue(context.Background(), ctxKeyFiberContext{}, c) //nolint:staticcheck
if options != nil {
// Copy the openapi3filter options so the caller's struct is not
// mutated when applying our KeepValidatedValue default.
filterOptions := options.Options
filterOptions.KeepValidatedValue = !options.DiscardValidatedValue
requestValidationInput.Options = &filterOptions
requestValidationInput.ParamDecoder = options.ParamDecoder
requestContext = context.WithValue(requestContext, ctxKeyUserData{}, options.UserData) //nolint:staticcheck
} else {
requestValidationInput.Options = &openapi3filter.Options{KeepValidatedValue: true}
}
err = openapi3filter.ValidateRequest(requestContext, requestValidationInput)
if err != nil {
me := openapi3.MultiError{}
if errors.As(err, &me) {
errFunc := getMultiErrorHandlerFromOptions(options)
return errFunc(me)
}
switch e := err.(type) {
case *openapi3filter.RequestError:
// We've got a bad request
// Split up the verbose error by lines and return the first one
// openapi errors seem to be multi-line with a decent message on the first
errorLines := strings.Split(e.Error(), "\n")
return fmt.Errorf("error in openapi3filter.RequestError: %s", errorLines[0])
case *openapi3filter.SecurityRequirementsError:
return fmt.Errorf("error in openapi3filter.SecurityRequirementsError: %s", e.Error())
default:
// This should never happen today, but if our upstream code changes,
// we don't want to crash the server, so handle the unexpected error.
return fmt.Errorf("error validating request: %w", err)
}
}
// The validator ran on a net/http copy of the request, so the validated
// value it left on that copy's body has to be carried over to the Fiber
// context by hand for handlers to reach it.
if vb, ok := r.Body.(interface{ ValidatedValue() any }); ok {
c.Locals(ValidatedBodyLocalsKey, vb.ValidatedValue())
}
return nil
}
// GetFiberContext gets the fiber context from within requests. It returns
// nil if not found or wrong type.
func GetFiberContext(c context.Context) fiber.Ctx {
iface := c.Value(ctxKeyFiberContext{})
if iface == nil {
return nil
}
fiberCtx, ok := iface.(fiber.Ctx)
if ok {
return fiberCtx
}
return nil
}
func GetUserData(c context.Context) interface{} {
return c.Value(ctxKeyUserData{})
}
// getMultiErrorHandlerFromOptions attempts to get the MultiErrorHandler from the options. If it is not set,
// return a default handler
func getMultiErrorHandlerFromOptions(options *Options) MultiErrorHandler {
if options == nil {
return defaultMultiErrorHandler
}
if options.MultiErrorHandler == nil {
return defaultMultiErrorHandler
}
return options.MultiErrorHandler
}
// defaultMultiErrorHandler returns a StatusBadRequest (400) and a list
// of all the errors. This method is called if there are no other
// methods defined on the options.
func defaultMultiErrorHandler(me openapi3.MultiError) error {
return fmt.Errorf("multiple errors encountered: %s", me)
}