diff --git a/go.mod b/go.mod index 6af0b9af..f9732831 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,10 @@ module github.com/TwiN/gatus/v4 -go 1.18 +go 1.19 require ( - github.com/TwiN/g8 v1.3.0 - github.com/TwiN/gocache/v2 v2.1.0 + github.com/TwiN/g8 v1.4.0 + github.com/TwiN/gocache/v2 v2.1.1 github.com/TwiN/health v1.4.0 github.com/TwiN/whois v1.0.0 github.com/coreos/go-oidc/v3 v3.1.0 diff --git a/go.sum b/go.sum index f10dd9ff..82931081 100644 --- a/go.sum +++ b/go.sum @@ -33,10 +33,10 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/TwiN/g8 v1.3.0 h1:mNv3R35GhDn1gEV0BKMl1oupZ1tDtOWPTHUKu+W/k3U= -github.com/TwiN/g8 v1.3.0/go.mod h1:SiIdItS0agSUloFqdQQt/RObB2jGSq+nnE9WfFv3RIo= -github.com/TwiN/gocache/v2 v2.1.0 h1:AJnSX7Sgz22fsO7rdXYQzMQ4zWpMjBKqk70ADeqtLDU= -github.com/TwiN/gocache/v2 v2.1.0/go.mod h1:AKHAFZSwLLmoLm1a2siDOWmZ2RjIKqentRGfOFWkllY= +github.com/TwiN/g8 v1.4.0 h1:RUk5xTtxKCdMo0GGSbBVyjtAAfi2nqVbA9E0C4u5Cxo= +github.com/TwiN/g8 v1.4.0/go.mod h1:ECyGJsoIb99klUfvVQoS1StgRLte9yvvPigGrHdy284= +github.com/TwiN/gocache/v2 v2.1.1 h1:W/GLImqa+pZVIH9pcWEn1cBgy1KU66fUcBjOnPhjuno= +github.com/TwiN/gocache/v2 v2.1.1/go.mod h1:SnUuBsrwGQeNcDG6vhkOMJnqErZM0JGjgIkuKryokYA= github.com/TwiN/health v1.4.0 h1:Ts7lb4ihYDpVEbFSGAhSEZTSwuDOADnwJLFngFl4xzw= github.com/TwiN/health v1.4.0/go.mod h1:CSUh+ryfD2POS2vKtc/yO4IxgR58lKvQ0/8qnoPqPqs= github.com/TwiN/whois v1.0.0 h1:I+aQzXLPmhWovkFUzlPV2DdfLZUWDLrkMDlM6QwCv+Q= diff --git a/vendor/github.com/TwiN/g8/LICENSE b/vendor/github.com/TwiN/g8/LICENSE new file mode 100644 index 00000000..ea31ca11 --- /dev/null +++ b/vendor/github.com/TwiN/g8/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 TwiN + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/TwiN/g8/LICENSE.md b/vendor/github.com/TwiN/g8/LICENSE.md deleted file mode 100644 index ca64af38..00000000 --- a/vendor/github.com/TwiN/g8/LICENSE.md +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) 2021 TwiN - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/TwiN/g8/README.md b/vendor/github.com/TwiN/g8/README.md index 149fd5b1..056dc60d 100644 --- a/vendor/github.com/TwiN/g8/README.md +++ b/vendor/github.com/TwiN/g8/README.md @@ -1,6 +1,6 @@ # g8 -![build](https://github.com/TwiN/g8/workflows/build/badge.svg?branch=master) +![test](https://github.com/TwiN/g8/workflows/test/badge.svg?branch=master) [![Go Report Card](https://goreportcard.com/badge/github.com/TwiN/g8)](https://goreportcard.com/report/github.com/TwiN/g8) [![codecov](https://codecov.io/gh/TwiN/g8/branch/master/graph/badge.svg)](https://codecov.io/gh/TwiN/g8) [![Go version](https://img.shields.io/github/go-mod/go-version/TwiN/g8.svg)](https://github.com/TwiN/g8) @@ -177,13 +177,42 @@ have the `backup` permission: router.Handle("/backup", gate.ProtectWithPermissions(&testHandler{}, []string{"read", "backup"})) ``` +If you're using an HTTP library that supports middlewares like [mux](https://github.com/gorilla/mux), you can protect +an entire group of handlers instead using `gate.Protect` or `gate.PermissionMiddleware()`: +```go +router := mux.NewRouter() + +userRouter := router.PathPrefix("/").Subrouter() +userRouter.Use(gate.Protect) +userRouter.HandleFunc("/api/v1/users/me", getUserProfile).Methods("GET") +userRouter.HandleFunc("/api/v1/users/me/friends", getUserFriends).Methods("GET") +userRouter.HandleFunc("/api/v1/users/me/email", updateUserEmail).Methods("PATCH") + +adminRouter := router.PathPrefix("/").Subrouter() +adminRouter.Use(gate.PermissionMiddleware("admin")) +adminRouter.HandleFunc("/api/v1/users/{id}/ban", banUserByID).Methods("POST") +adminRouter.HandleFunc("/api/v1/users/{id}/delete", deleteUserByID).Methods("DELETE") +``` + + ## Rate limiting To add a rate limit of 100 requests per second: -``` +```go gate := g8.New().WithRateLimit(100) ``` -## Special use cases + +## Accessing the token from the protected handlers +If you need to access the token from the handlers you are protecting with g8, you can retrieve it from the +request context by using the key `g8.TokenContextKey`: +```go +http.Handle("/handle", gate.ProtectFunc(func(w http.ResponseWriter, r *http.Request) { + token, _ := r.Context().Value(g8.TokenContextKey).(string) + // ... +})) +``` + +## Examples ### Protecting a handler using session cookie If you want to only allow authenticated users to access a handler, you can use a custom token extractor function combined with a client provider. @@ -236,3 +265,23 @@ http.Handle("/handle", gate.ProtectFunc(func(w http.ResponseWriter, r *http.Requ // ... })) ``` + +### Using a custom header +The logic is the same as the example above: +```go +customTokenExtractorFunc := func(request *http.Request) string { + return request.Header.Get("X-API-Token") +} + +clientProvider := g8.NewClientProvider(func(token string) *g8.Client { + // We'll assume that the following function calls your database and returns a struct "User" that + // has the user's token as well as the permissions granted to said user + user := database.GetUserByToken(token) + if user != nil { + return g8.NewClient(user.Token).WithPermissions(user.Permissions) + } + return nil +}) +authorizationService := g8.NewAuthorizationService().WithClientProvider(clientProvider) +gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc) +``` diff --git a/vendor/github.com/TwiN/g8/gate.go b/vendor/github.com/TwiN/g8/gate.go index 08082c8b..2dad0b8f 100644 --- a/vendor/github.com/TwiN/g8/gate.go +++ b/vendor/github.com/TwiN/g8/gate.go @@ -66,15 +66,16 @@ func (gate *Gate) WithCustomUnauthorizedResponseBody(unauthorizedResponseBody [] // If a custom token extractor is not specified, the token will be extracted from the Authorization header. // // For instance, if you're using a session cookie, you can extract the token from the cookie like so: -// authorizationService := g8.NewAuthorizationService() -// customTokenExtractorFunc := func(request *http.Request) string { -// sessionCookie, err := request.Cookie("session") -// if err != nil { -// return "" -// } -// return sessionCookie.Value -// } -// gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc) +// +// authorizationService := g8.NewAuthorizationService() +// customTokenExtractorFunc := func(request *http.Request) string { +// sessionCookie, err := request.Cookie("session") +// if err != nil { +// return "" +// } +// return sessionCookie.Value +// } +// gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc) // // You would normally use this with a client provider that matches whatever need you have. // For example, if you're using a session cookie, your client provider would retrieve the user from the session ID @@ -90,8 +91,8 @@ func (gate *Gate) WithCustomTokenExtractor(customTokenExtractorFunc func(request // WithRateLimit adds rate limiting to the Gate // // If you just want to use a gate for rate limiting purposes: -// gate := g8.New().WithRateLimit(50) // +// gate := g8.New().WithRateLimit(50) func (gate *Gate) WithRateLimit(maximumRequestsPerSecond int) *Gate { gate.rateLimiter = NewRateLimiter(maximumRequestsPerSecond) return gate @@ -102,12 +103,13 @@ func (gate *Gate) WithRateLimit(maximumRequestsPerSecond int) *Gate { // or lack thereof. // // Example: -// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token")) -// router := http.NewServeMux() -// // Without protection -// router.Handle("/handle", yourHandler) -// // With protection -// router.Handle("/handle", gate.Protect(yourHandler)) +// +// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token")) +// router := http.NewServeMux() +// // Without protection +// router.Handle("/handle", yourHandler) +// // With protection +// router.Handle("/handle", gate.Protect(yourHandler)) // // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey func (gate *Gate) Protect(handler http.Handler) http.Handler { @@ -118,12 +120,13 @@ func (gate *Gate) Protect(handler http.Handler) http.Handler { // as well as a slice of permissions that must be met. // // Example: -// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("admin"))) -// router := http.NewServeMux() -// // Without protection -// router.Handle("/handle", yourHandler) -// // With protection -// router.Handle("/handle", gate.ProtectWithPermissions(yourHandler, []string{"admin"})) +// +// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("ADMIN"))) +// router := http.NewServeMux() +// // Without protection +// router.Handle("/handle", yourHandler) +// // With protection +// router.Handle("/handle", gate.ProtectWithPermissions(yourHandler, []string{"admin"})) // // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey func (gate *Gate) ProtectWithPermissions(handler http.Handler, permissions []string) http.Handler { @@ -147,12 +150,13 @@ func (gate *Gate) ProtectWithPermission(handler http.Handler, permission string) // permissions or lack thereof. // // Example: -// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token")) -// router := http.NewServeMux() -// // Without protection -// router.HandleFunc("/handle", yourHandlerFunc) -// // With protection -// router.HandleFunc("/handle", gate.ProtectFunc(yourHandlerFunc)) +// +// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token")) +// router := http.NewServeMux() +// // Without protection +// router.HandleFunc("/handle", yourHandlerFunc) +// // With protection +// router.HandleFunc("/handle", gate.ProtectFunc(yourHandlerFunc)) // // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey func (gate *Gate) ProtectFunc(handlerFunc http.HandlerFunc) http.HandlerFunc { @@ -163,12 +167,13 @@ func (gate *Gate) ProtectFunc(handlerFunc http.HandlerFunc) http.HandlerFunc { // token as well as a slice of permissions that must be met. // // Example: -// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("admin"))) -// router := http.NewServeMux() -// // Without protection -// router.HandleFunc("/handle", yourHandlerFunc) -// // With protection -// router.HandleFunc("/handle", gate.ProtectFuncWithPermissions(yourHandlerFunc, []string{"admin"})) +// +// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("admin"))) +// router := http.NewServeMux() +// // Without protection +// router.HandleFunc("/handle", yourHandlerFunc) +// // With protection +// router.HandleFunc("/handle", gate.ProtectFuncWithPermissions(yourHandlerFunc, []string{"admin"})) // // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey func (gate *Gate) ProtectFuncWithPermissions(handlerFunc http.HandlerFunc, permissions []string) http.HandlerFunc { @@ -215,3 +220,19 @@ func (gate *Gate) ExtractTokenFromRequest(request *http.Request) string { } return strings.TrimPrefix(request.Header.Get(AuthorizationHeader), "Bearer ") } + +// PermissionMiddleware is a middleware that behaves like ProtectWithPermission, but it is meant to be used +// as a middleware for libraries that support such a feature. +// +// For instance, if you are using github.com/gorilla/mux, you can use PermissionMiddleware like so: +// +// router := mux.NewRouter() +// router.Use(gate.PermissionMiddleware("admin")) +// router.Handle("/admin/handle", adminHandler) +// +// If you do not want to protect a router with a specific permission, you can use Gate.Protect instead. +func (gate *Gate) PermissionMiddleware(permissions ...string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return gate.ProtectWithPermissions(next, permissions) + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index ad582040..2a4a4b1c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,8 +1,8 @@ -# github.com/TwiN/g8 v1.3.0 -## explicit; go 1.17 +# github.com/TwiN/g8 v1.4.0 +## explicit; go 1.19 github.com/TwiN/g8 -# github.com/TwiN/gocache/v2 v2.1.0 -## explicit; go 1.18 +# github.com/TwiN/gocache/v2 v2.1.1 +## explicit; go 1.19 github.com/TwiN/gocache/v2 # github.com/TwiN/health v1.4.0 ## explicit; go 1.18