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
|
package openapi3filter
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"sort"
"github.com/getkin/kin-openapi/openapi3"
)
func ValidateRequest(c context.Context, input *RequestValidationInput) error {
options := input.Options
if options == nil {
options = DefaultOptions
}
route := input.Route
if route == nil {
return errors.New("invalid route")
}
operation := route.Operation
if operation == nil {
return errRouteMissingOperation
}
operationParameters := operation.Parameters
pathItemParameters := route.PathItem.Parameters
// For each parameter of the PathItem
for _, parameterRef := range pathItemParameters {
parameter := parameterRef.Value
if operationParameters != nil {
if override := operationParameters.GetByInAndName(parameter.In, parameter.Name); override != nil {
continue
}
if err := ValidateParameter(c, input, parameter); err != nil {
return err
}
}
}
// For each parameter of the Operation
for _, parameter := range operationParameters {
if err := ValidateParameter(c, input, parameter.Value); err != nil {
return err
}
}
// RequestBody
requestBody := operation.RequestBody
if requestBody != nil && !options.ExcludeRequestBody {
if err := ValidateRequestBody(c, input, requestBody.Value); err != nil {
return err
}
}
// Security
security := operation.Security
if security != nil {
if err := ValidateSecurityRequirements(c, input, *security); err != nil {
return err
}
}
return nil
}
func ValidateParameter(c context.Context, input *RequestValidationInput, parameter *openapi3.Parameter) error {
req := input.Request
name := parameter.Name
var value string
var found bool
switch parameter.In {
case openapi3.ParameterInPath:
pathParams := input.PathParams
if pathParams != nil {
value, found = pathParams[name]
}
case openapi3.ParameterInQuery:
values := input.GetQueryParams()[name]
if len(values) > 0 {
value = values[0]
found = true
}
case openapi3.ParameterInHeader:
var values []string
values, found = req.Header[http.CanonicalHeaderKey(name)]
if len(values) > 0 {
value = values[0]
}
case openapi3.ParameterInCookie:
cookie, err := req.Cookie(name)
if err == nil {
value = cookie.Value
found = true
} else {
if err != http.ErrNoCookie {
return &RequestError{
Input: input,
Parameter: parameter,
Reason: "parsing failed",
Err: err,
}
}
}
default:
return &RequestError{
Input: input,
Parameter: parameter,
Reason: "unsupported 'in'",
}
}
if !found {
if parameter.Required {
return &RequestError{
Input: input,
Parameter: parameter,
Reason: "must have a value",
}
}
return nil
}
if schemaRef := parameter.Schema; schemaRef != nil {
// Only check schema if no transformation is needed
if schema := schemaRef.Value; schema.Type == "string" {
if err := schema.VisitJSONString(value); err != nil {
return &RequestError{
Input: input,
Parameter: parameter,
Err: err,
}
}
}
}
return nil
}
func ValidateRequestBody(c context.Context, input *RequestValidationInput, requestBody *openapi3.RequestBody) error {
req := input.Request
content := requestBody.Content
if content != nil && len(content) > 0 {
inputMIME := req.Header.Get("Content-Type")
mediaType := parseMediaType(inputMIME)
contentType := requestBody.Content[mediaType]
if contentType == nil {
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: "header 'Content-type' has unexpected value",
}
}
schemaRef := contentType.Schema
if schemaRef != nil && isMediaTypeJSON(mediaType) {
schema := schemaRef.Value
body := req.Body
defer body.Close()
data, err := ioutil.ReadAll(body)
if err != nil {
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: "reading failed",
Err: err,
}
}
// Put the data back into the input
req.Body = ioutil.NopCloser(bytes.NewReader(data))
// Decode JSON
var value interface{}
if err := json.Unmarshal(data, &value); err != nil {
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: "decoding JSON failed",
Err: err,
}
}
// Validate JSON with the schema
if err := schema.VisitJSON(value); err != nil {
return &RequestError{
Input: input,
RequestBody: requestBody,
Reason: "doesn't input the schema",
Err: err,
}
}
}
}
return nil
}
// ValidateSecurityRequirements validates a multiple OpenAPI 3 security requirements.
// Returns nil if one of them inputed.
// Otherwise returns an error describing the security failures.
func ValidateSecurityRequirements(c context.Context, input *RequestValidationInput, srs openapi3.SecurityRequirements) error {
// Alternative requirements
if len(srs) == 0 {
return nil
}
doneChan := make(chan bool, len(srs))
errs := make([]error, len(srs))
// For each alternative
for i, securityRequirement := range srs {
// Capture index from iteration variable
currentIndex := i
currentSecurityRequirement := securityRequirement
go func() {
defer func() {
v := recover()
if v != nil {
if err, ok := v.(error); ok {
errs[currentIndex] = err
} else {
errs[currentIndex] = errors.New("Panicked")
}
doneChan <- false
}
}()
if err := validateSecurityRequirement(c, input, currentSecurityRequirement); err == nil {
doneChan <- true
} else {
errs[currentIndex] = err
doneChan <- false
}
}()
}
// Wait for all
for i := 0; i < len(srs); i++ {
ok := <-doneChan
if ok {
close(doneChan)
return nil
}
}
return &SecurityRequirementsError{
SecurityRequirements: srs,
Errors: errs,
}
}
// validateSecurityRequirement validates a single OpenAPI 3 security requirement
func validateSecurityRequirement(c context.Context, input *RequestValidationInput, securityRequirement openapi3.SecurityRequirement) error {
swagger := input.Route.Swagger
if swagger == nil {
return errRouteMissingSwagger
}
securitySchemes := swagger.Components.SecuritySchemes
// Ensure deterministic order
names := make([]string, 0, len(securityRequirement))
for name := range securityRequirement {
names = append(names, name)
}
sort.Strings(names)
// Get authentication function
options := input.Options
if options == nil {
options = DefaultOptions
}
f := options.AuthenticationFunc
if f == nil {
return ErrAuthenticationServiceMissing
}
if len(names) > 0 {
name := names[0]
var securityScheme *openapi3.SecurityScheme
if securitySchemes != nil {
if ref := securitySchemes[name]; ref != nil {
securityScheme = ref.Value
}
}
if securityScheme == nil {
return &RequestError{
Input: input,
Err: fmt.Errorf("Security scheme '%s' is not declared", name),
}
}
scopes := securityRequirement[name]
return f(c, &AuthenticationInput{
RequestValidationInput: input,
SecuritySchemeName: name,
SecurityScheme: securityScheme,
Scopes: scopes,
})
}
return nil
}
|