From d11da6fa54cb5477366f8711fc88de498df1408a Mon Sep 17 00:00:00 2001 From: Nicolas Carlier Date: Mon, 7 Jan 2019 10:37:13 +0000 Subject: [PATCH] feat(api): add method whitelist --- pkg/api/router.go | 1 + pkg/api/routes.go | 8 ++++---- pkg/middleware/method.go | 23 +++++++++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 pkg/middleware/method.go diff --git a/pkg/api/router.go b/pkg/api/router.go index 34eaecc..bfff429 100644 --- a/pkg/api/router.go +++ b/pkg/api/router.go @@ -23,6 +23,7 @@ func NewRouter(conf *config.Config) *http.ServeMux { var handler http.Handler handler = route.HandlerFunc(conf) + handler = middleware.Method(handler, route.Methods) handler = middleware.Cors(handler) handler = middleware.Logger(handler) handler = middleware.Tracing(nextRequestID)(handler) diff --git a/pkg/api/routes.go b/pkg/api/routes.go index d3425e6..ab20c3f 100644 --- a/pkg/api/routes.go +++ b/pkg/api/routes.go @@ -11,7 +11,7 @@ type HandlerFunc func(conf *config.Config) http.Handler // Route is the structure of an HTTP route definition type Route struct { - Method string + Methods []string Path string HandlerFunc HandlerFunc } @@ -21,17 +21,17 @@ type Routes []Route var routes = Routes{ Route{ - "GET", + []string{"GET", "POST"}, "/", index, }, Route{ - "GET", + []string{"GET"}, "/healtz", healthz, }, Route{ - "GET", + []string{"GET"}, "/varz", varz, }, diff --git a/pkg/middleware/method.go b/pkg/middleware/method.go new file mode 100644 index 0000000..d229d8a --- /dev/null +++ b/pkg/middleware/method.go @@ -0,0 +1,23 @@ +package middleware + +import ( + "net/http" +) + +// Method is a middleware to check that the request use the correct HTTP method +func Method(inner http.Handler, methods []string) http.Handler { + allowedMethods := make(map[string]struct{}, len(methods)) + for _, s := range methods { + allowedMethods[s] = struct{}{} + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if _, ok := allowedMethods[r.Method]; ok { + inner.ServeHTTP(w, r) + return + } + w.WriteHeader(405) + w.Write([]byte("405 Method Not Allowed\n")) + return + }) +}