1// Copyright 2015 go-swagger maintainers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package middleware
16
17import (
18	"mime"
19	"net/http"
20	"strings"
21
22	"github.com/go-openapi/errors"
23	"github.com/go-openapi/runtime"
24	"github.com/go-openapi/swag"
25)
26
27// NewValidation starts a new validation middleware
28func newValidation(ctx *Context, next http.Handler) http.Handler {
29
30	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
31		matched, _ := ctx.RouteInfo(r)
32		if matched == nil {
33			ctx.NotFound(rw, r)
34			return
35		}
36		_, result := ctx.BindAndValidate(r, matched)
37
38		if result != nil {
39			ctx.Respond(rw, r, matched.Produces, matched, result)
40			return
41		}
42
43		debugLog("no result for %s %s", r.Method, r.URL.EscapedPath())
44		next.ServeHTTP(rw, r)
45	})
46}
47
48type validation struct {
49	context *Context
50	result  []error
51	request *http.Request
52	route   *MatchedRoute
53	bound   map[string]interface{}
54}
55
56type untypedBinder map[string]interface{}
57
58func (ub untypedBinder) BindRequest(r *http.Request, route *MatchedRoute, consumer runtime.Consumer) error {
59	if err := route.Binder.Bind(r, route.Params, consumer, ub); err != nil {
60		return err
61	}
62	return nil
63}
64
65// ContentType validates the content type of a request
66func validateContentType(allowed []string, actual string) error {
67	debugLog("validating content type for %q against [%s]", actual, strings.Join(allowed, ", "))
68	if len(allowed) == 0 {
69		return nil
70	}
71	mt, _, err := mime.ParseMediaType(actual)
72	if err != nil {
73		return errors.InvalidContentType(actual, allowed)
74	}
75	if swag.ContainsStringsCI(allowed, mt) {
76		return nil
77	}
78	return errors.InvalidContentType(actual, allowed)
79}
80
81func validateRequest(ctx *Context, request *http.Request, route *MatchedRoute) *validation {
82	debugLog("validating request %s %s", request.Method, request.URL.EscapedPath())
83	validate := &validation{
84		context: ctx,
85		request: request,
86		route:   route,
87		bound:   make(map[string]interface{}),
88	}
89
90	validate.contentType()
91	if len(validate.result) == 0 {
92		validate.responseFormat()
93	}
94	if len(validate.result) == 0 {
95		validate.parameters()
96	}
97
98	return validate
99}
100
101func (v *validation) parameters() {
102	debugLog("validating request parameters for %s %s", v.request.Method, v.request.URL.EscapedPath())
103	if result := v.route.Binder.Bind(v.request, v.route.Params, v.route.Consumer, v.bound); result != nil {
104		if result.Error() == "validation failure list" {
105			for _, e := range result.(*errors.Validation).Value.([]interface{}) {
106				v.result = append(v.result, e.(error))
107			}
108			return
109		}
110		v.result = append(v.result, result)
111	}
112}
113
114func (v *validation) contentType() {
115	if len(v.result) == 0 && runtime.HasBody(v.request) {
116		debugLog("validating body content type for %s %s", v.request.Method, v.request.URL.EscapedPath())
117		ct, _, err := v.context.ContentType(v.request)
118		if err != nil {
119			v.result = append(v.result, err)
120		}
121		if len(v.result) == 0 {
122			if err := validateContentType(v.route.Consumes, ct); err != nil {
123				v.result = append(v.result, err)
124			}
125		}
126		if ct != "" && v.route.Consumer == nil {
127			cons, ok := v.route.Consumers[ct]
128			if !ok {
129				v.result = append(v.result, errors.New(500, "no consumer registered for %s", ct))
130			} else {
131				v.route.Consumer = cons
132			}
133		}
134	}
135}
136
137func (v *validation) responseFormat() {
138	if str := v.context.ResponseFormat(v.request, v.route.Produces); str == "" && runtime.HasBody(v.request) {
139		v.result = append(v.result, errors.InvalidResponseFormat(v.request.Header.Get(runtime.HeaderAccept), v.route.Produces))
140	}
141}
142