Debian Codegraph @

gate.go

raw symbols SCIP
1 package g8
2
3 import (
4 "context"
5 "net/http"
6 "strings"
7 )
8
9 const (
10 // AuthorizationHeader is the header in which g8 looks for the authorization bearer token
11 AuthorizationHeader = "Authorization"
12
13 // DefaultUnauthorizedResponseBody is the default response body returned if a request was sent with a missing or invalid token
14 DefaultUnauthorizedResponseBody = "token is missing or invalid"
15
16 // DefaultTooManyRequestsResponseBody is the default response body returned if a request exceeded the allowed rate limit
17 DefaultTooManyRequestsResponseBody = "too many requests"
18
19 // TokenContextKey is the key used to store the client's token in the context.
20 TokenContextKey = "g8.token"
21
22 // DataContextKey is the key used to store the client's data in the context.
23 DataContextKey = "g8.data"
24 )
25
26 // Gate is lock to the front door of your API, letting only those you allow through.
27 type Gate struct {
28 authorizationService *AuthorizationService
29 unauthorizedResponseBody []byte
30
31 customTokenExtractorFunc func(request *http.Request) string
32
33 rateLimiter *RateLimiter
34 tooManyRequestsResponseBody []byte
35 }
36
37 // Deprecated: use New instead.
38 func NewGate(authorizationService *AuthorizationService) *Gate {
39 return &Gate{
40 authorizationService: authorizationService,
41 unauthorizedResponseBody: []byte(DefaultUnauthorizedResponseBody),
42 tooManyRequestsResponseBody: []byte(DefaultTooManyRequestsResponseBody),
43 }
44 }
45
46 // New creates a new Gate.
47 func New() *Gate {
48 return &Gate{
49 unauthorizedResponseBody: []byte(DefaultUnauthorizedResponseBody),
50 tooManyRequestsResponseBody: []byte(DefaultTooManyRequestsResponseBody),
51 }
52 }
53
54 // WithAuthorizationService sets the authorization service to use.
55 //
56 // If there is no authorization service, Gate will not enforce authorization.
57 func (gate *Gate) WithAuthorizationService(authorizationService *AuthorizationService) *Gate {
58 gate.authorizationService = authorizationService
59 return gate
60 }
61
62 // WithCustomUnauthorizedResponseBody sets a custom response body when Gate determines that a request must be blocked
63 func (gate *Gate) WithCustomUnauthorizedResponseBody(unauthorizedResponseBody []byte) *Gate {
64 gate.unauthorizedResponseBody = unauthorizedResponseBody
65 return gate
66 }
67
68 // WithCustomTokenExtractor allows the specification of a custom function to extract a token from a request.
69 // If a custom token extractor is not specified, the token will be extracted from the Authorization header.
70 //
71 // For instance, if you're using a session cookie, you can extract the token from the cookie like so:
72 //
73 // authorizationService := g8.NewAuthorizationService()
74 // customTokenExtractorFunc := func(request *http.Request) string {
75 // sessionCookie, err := request.Cookie("session")
76 // if err != nil {
77 // return ""
78 // }
79 // return sessionCookie.Value
80 // }
81 // gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc)
82 //
83 // You would normally use this with a client provider that matches whatever need you have.
84 // For example, if you're using a session cookie, your client provider would retrieve the user from the session ID
85 // extracted by this custom token extractor.
86 //
87 // Note that for the sake of convenience, the token extracted from the request is passed the protected handlers request
88 // context under the key TokenContextKey. This is especially useful if the token is in fact a session ID.
89 func (gate *Gate) WithCustomTokenExtractor(customTokenExtractorFunc func(request *http.Request) string) *Gate {
90 gate.customTokenExtractorFunc = customTokenExtractorFunc
91 return gate
92 }
93
94 // WithRateLimit adds rate limiting to the Gate
95 //
96 // If you just want to use a gate for rate limiting purposes:
97 //
98 // gate := g8.New().WithRateLimit(50)
99 func (gate *Gate) WithRateLimit(maximumRequestsPerSecond int) *Gate {
100 gate.rateLimiter = NewRateLimiter(maximumRequestsPerSecond)
101 return gate
102 }
103
104 // Protect secures a handler, requiring requests going through to have a valid Authorization Bearer token.
105 // Unlike ProtectWithPermissions, Protect will allow access to any registered tokens, regardless of their permissions
106 // or lack thereof.
107 //
108 // Example:
109 //
110 // gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token"))
111 // router := http.NewServeMux()
112 // // Without protection
113 // router.Handle("/handle", yourHandler)
114 // // With protection
115 // router.Handle("/handle", gate.Protect(yourHandler))
116 //
117 // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey
118 func (gate *Gate) Protect(handler http.Handler) http.Handler {
119 return gate.ProtectWithPermissions(handler, nil)
120 }
121
122 // ProtectWithPermissions secures a handler, requiring requests going through to have a valid Authorization Bearer token
123 // as well as a slice of permissions that must be met.
124 //
125 // Example:
126 //
127 // gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("ADMIN")))
128 // router := http.NewServeMux()
129 // // Without protection
130 // router.Handle("/handle", yourHandler)
131 // // With protection
132 // router.Handle("/handle", gate.ProtectWithPermissions(yourHandler, []string{"admin"}))
133 //
134 // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey
135 func (gate *Gate) ProtectWithPermissions(handler http.Handler, permissions []string) http.Handler {
136 return gate.ProtectFuncWithPermissions(func(writer http.ResponseWriter, request *http.Request) {
137 handler.ServeHTTP(writer, request)
138 }, permissions)
139 }
140
141 // ProtectWithPermission does the same thing as ProtectWithPermissions, but for a single permission instead of a
142 // slice of permissions
143 //
144 // See ProtectWithPermissions for further documentation
145 func (gate *Gate) ProtectWithPermission(handler http.Handler, permission string) http.Handler {
146 return gate.ProtectFuncWithPermissions(func(writer http.ResponseWriter, request *http.Request) {
147 handler.ServeHTTP(writer, request)
148 }, []string{permission})
149 }
150
151 // ProtectFunc secures a handlerFunc, requiring requests going through to have a valid Authorization Bearer token.
152 // Unlike ProtectFuncWithPermissions, ProtectFunc will allow access to any registered tokens, regardless of their
153 // permissions or lack thereof.
154 //
155 // Example:
156 //
157 // gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token"))
158 // router := http.NewServeMux()
159 // // Without protection
160 // router.HandleFunc("/handle", yourHandlerFunc)
161 // // With protection
162 // router.HandleFunc("/handle", gate.ProtectFunc(yourHandlerFunc))
163 //
164 // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey
165 func (gate *Gate) ProtectFunc(handlerFunc http.HandlerFunc) http.HandlerFunc {
166 return gate.ProtectFuncWithPermissions(handlerFunc, nil)
167 }
168
169 // ProtectFuncWithPermissions secures a handler, requiring requests going through to have a valid Authorization Bearer
170 // token as well as a slice of permissions that must be met.
171 //
172 // Example:
173 //
174 // gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("admin")))
175 // router := http.NewServeMux()
176 // // Without protection
177 // router.HandleFunc("/handle", yourHandlerFunc)
178 // // With protection
179 // router.HandleFunc("/handle", gate.ProtectFuncWithPermissions(yourHandlerFunc, []string{"admin"}))
180 //
181 // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey
182 func (gate *Gate) ProtectFuncWithPermissions(handlerFunc http.HandlerFunc, permissions []string) http.HandlerFunc {
183 return func(writer http.ResponseWriter, request *http.Request) {
184 if gate.rateLimiter != nil {
185 if !gate.rateLimiter.Try() {
186 writer.WriteHeader(http.StatusTooManyRequests)
187 _, _ = writer.Write(gate.tooManyRequestsResponseBody)
188 return
189 }
190 }
191 if gate.authorizationService != nil {
192 token := gate.ExtractTokenFromRequest(request)
193 if client, authorized := gate.authorizationService.Authorize(token, permissions); !authorized {
194 writer.WriteHeader(http.StatusUnauthorized)
195 _, _ = writer.Write(gate.unauthorizedResponseBody)
196 return
197 } else {
198 request = request.WithContext(context.WithValue(request.Context(), TokenContextKey, token))
199 if client != nil && client.Data != nil {
200 request = request.WithContext(context.WithValue(request.Context(), DataContextKey, client.Data))
201 }
202 }
203 }
204 handlerFunc(writer, request)
205 }
206 }
207
208 // ProtectFuncWithPermission does the same thing as ProtectFuncWithPermissions, but for a single permission instead of a
209 // slice of permissions
210 //
211 // See ProtectFuncWithPermissions for further documentation
212 func (gate *Gate) ProtectFuncWithPermission(handlerFunc http.HandlerFunc, permission string) http.HandlerFunc {
213 return gate.ProtectFuncWithPermissions(handlerFunc, []string{permission})
214 }
215
216 // ExtractTokenFromRequest extracts a token from a request.
217 //
218 // By default, it extracts the bearer token from the AuthorizationHeader, but if a customTokenExtractorFunc is defined,
219 // it will use that instead.
220 //
221 // Note that this method is internally used by Protect, ProtectWithPermission, ProtectFunc and
222 // ProtectFuncWithPermissions, but it is exposed in case you need to use it directly.
223 func (gate *Gate) ExtractTokenFromRequest(request *http.Request) string {
224 if gate.customTokenExtractorFunc != nil {
225 // A custom token extractor function is defined, so we'll use it instead of the default token extraction logic
226 return gate.customTokenExtractorFunc(request)
227 }
228 return strings.TrimPrefix(request.Header.Get(AuthorizationHeader), "Bearer ")
229 }
230
231 // PermissionMiddleware is a middleware that behaves like ProtectWithPermission, but it is meant to be used
232 // as a middleware for libraries that support such a feature.
233 //
234 // For instance, if you are using github.com/gorilla/mux, you can use PermissionMiddleware like so:
235 //
236 // router := mux.NewRouter()
237 // router.Use(gate.PermissionMiddleware("admin"))
238 // router.Handle("/admin/handle", adminHandler)
239 //
240 // If you do not want to protect a router with a specific permission, you can use Gate.Protect instead.
241 func (gate *Gate) PermissionMiddleware(permissions ...string) func(http.Handler) http.Handler {
242 return func(next http.Handler) http.Handler {
243 return gate.ProtectWithPermissions(next, permissions)
244 }
245 }