| 1 | # g8 |
| 2 | |
| 3 |  |
| 4 | [](https://goreportcard.com/report/github.com/TwiN/g8/v3) |
| 5 | [](https://codecov.io/gh/TwiN/g8) |
| 6 | [](https://github.com/TwiN/g8) |
| 7 | [](https://pkg.go.dev/github.com/TwiN/g8/v3) |
| 8 | [](https://github.com/TwiN) |
| 9 | |
| 10 | g8, pronounced gate, is a simple Go library for protecting HTTP handlers. |
| 11 | |
| 12 | Tired of constantly re-implementing a security layer for each application? Me too, that's why I made g8. |
| 13 | |
| 14 | |
| 15 | ## Installation |
| 16 | ```console |
| 17 | go get -u github.com/TwiN/g8/v3 |
| 18 | ``` |
| 19 | |
| 20 | |
| 21 | ## Usage |
| 22 | Because the entire purpose of g8 is to NOT waste time configuring the layer of security, the primary emphasis is to |
| 23 | keep it as simple as possible. |
| 24 | |
| 25 | |
| 26 | ### Simple |
| 27 | Just want a simple layer of security without the need for advanced permissions? This configuration is what you're |
| 28 | looking for. |
| 29 | |
| 30 | ```go |
| 31 | authorizationService := g8.NewAuthorizationService().WithToken("mytoken") |
| 32 | gate := g8.New().WithAuthorizationService(authorizationService) |
| 33 | |
| 34 | router := http.NewServeMux() |
| 35 | router.Handle("/unprotected", yourHandler) |
| 36 | router.Handle("/protected", gate.Protect(yourHandler)) |
| 37 | |
| 38 | http.ListenAndServe(":8080", router) |
| 39 | ``` |
| 40 | |
| 41 | The endpoint `/protected` is now only accessible if you pass the header `Authorization: Bearer mytoken`. |
| 42 | |
| 43 | If you use `http.HandleFunc` instead of `http.Handle`, you may use `gate.ProtectFunc(yourHandler)` instead. |
| 44 | |
| 45 | If you're not using the `Authorization` header, you can specify a custom token extractor. |
| 46 | This enables use cases like [Protecting a handler using session cookie](#protecting-a-handler-using-session-cookie) |
| 47 | |
| 48 | |
| 49 | ### Advanced permissions |
| 50 | If you have tokens with more permissions than others, g8's permission system will make managing authorization a breeze. |
| 51 | |
| 52 | Rather than registering tokens, think of it as registering clients, the only difference being that clients may be |
| 53 | configured with permissions while tokens cannot. |
| 54 | |
| 55 | ```go |
| 56 | authorizationService := g8.NewAuthorizationService().WithClient(g8.NewClient("mytoken").WithPermission("admin")) |
| 57 | gate := g8.New().WithAuthorizationService(authorizationService) |
| 58 | |
| 59 | router := http.NewServeMux() |
| 60 | router.Handle("/unprotected", yourHandler) |
| 61 | router.Handle("/protected-with-admin", gate.ProtectWithPermissions(yourHandler, []string{"admin"})) |
| 62 | |
| 63 | http.ListenAndServe(":8080", router) |
| 64 | ``` |
| 65 | |
| 66 | The endpoint `/protected-with-admin` is now only accessible if you pass the header `Authorization: Bearer mytoken`, |
| 67 | because the client with the token `mytoken` has the permission `admin`. Note that the following handler would also be |
| 68 | accessible with that token: |
| 69 | ```go |
| 70 | router.Handle("/protected", gate.Protect(yourHandler)) |
| 71 | ``` |
| 72 | |
| 73 | To clarify, both clients and tokens have access to handlers that aren't protected with extra permissions, and |
| 74 | essentially, tokens are registered as clients with no extra permissions in the background. |
| 75 | |
| 76 | Creating a token like so: |
| 77 | ```go |
| 78 | authorizationService := g8.NewAuthorizationService().WithToken("mytoken") |
| 79 | ``` |
| 80 | is the equivalent of creating the following client: |
| 81 | ```go |
| 82 | authorizationService := g8.NewAuthorizationService().WithClient(g8.NewClient("mytoken")) |
| 83 | ``` |
| 84 | |
| 85 | |
| 86 | ### With client provider |
| 87 | A client provider's task is to retrieve a Client from an external source (e.g. a database) when provided with a token. |
| 88 | You should use a client provider when you have a lot of tokens and it wouldn't make sense to register all of them using |
| 89 | `AuthorizationService`'s `WithToken`/`WithTokens`/`WithClient`/`WithClients`. |
| 90 | |
| 91 | Note that the provider is used as a fallback source. As such, if a token is explicitly registered using one of the 4 |
| 92 | aforementioned functions, the client provider will not be used. |
| 93 | |
| 94 | ```go |
| 95 | clientProvider := g8.NewClientProvider(func(token string) *g8.Client { |
| 96 | // We'll assume that the following function calls your database and returns a struct "User" that |
| 97 | // has the user's token as well as the permissions granted to said user |
| 98 | user := database.GetUserByToken(token) |
| 99 | if user != nil { |
| 100 | return g8.NewClient(user.Token).WithPermissions(user.Permissions) |
| 101 | } |
| 102 | return nil |
| 103 | }) |
| 104 | authorizationService := g8.NewAuthorizationService().WithClientProvider(clientProvider) |
| 105 | gate := g8.New().WithAuthorizationService(authorizationService) |
| 106 | ``` |
| 107 | |
| 108 | You can also configure the client provider to cache the output of the function you provide to retrieve clients by token: |
| 109 | ```go |
| 110 | clientProvider := g8.NewClientProvider(...).WithCache(ttl, maxSize) |
| 111 | ``` |
| 112 | |
| 113 | Since g8 leverages [TwiN/gocache](https://github.com/TwiN/gocache) (unless you're using `WithCustomCache`), |
| 114 | you can also use gocache's constants for configuring the TTL and the maximum size: |
| 115 | - Setting the TTL to `gocache.NoExpiration` (-1) will disable the TTL. |
| 116 | - Setting the maximum size to `gocache.NoMaxSize` (0) will disable the maximum cache size |
| 117 | |
| 118 | To avoid any misunderstandings, using a client provider is not mandatory. If you only have a few tokens and you can load |
| 119 | them on application start, you can just leverage `AuthorizationService`'s `WithToken`/`WithTokens`/`WithClient`/`WithClients`. |
| 120 | |
| 121 | |
| 122 | ## AuthorizationService |
| 123 | As the previous examples may have hinted, there are several ways to create clients. The one thing they have |
| 124 | in common is that they all go through AuthorizationService, which is in charge of both managing clients and determining |
| 125 | whether a request should be blocked or allowed through. |
| 126 | |
| 127 | | Function | Description | |
| 128 | |:-------------------|:---------------------------------------------------------------------------------------------------------------------------------| |
| 129 | | WithToken | Creates a single static client with no extra permissions | |
| 130 | | WithTokens | Creates a slice of static clients with no extra permissions | |
| 131 | | WithClient | Creates a single static client | |
| 132 | | WithClients | Creates a slice of static clients | |
| 133 | | WithClientProvider | Creates a client provider which will allow a fallback to a dynamic source (e.g. to a database) when a static client is not found | |
| 134 | |
| 135 | Except for `WithClientProvider`, every functions listed above can be called more than once. |
| 136 | As a result, you may safely perform actions like this: |
| 137 | ```go |
| 138 | authorizationService := g8.NewAuthorizationService(). |
| 139 | WithToken("123"). |
| 140 | WithToken("456"). |
| 141 | WithClient(g8.NewClient("789").WithPermission("admin")) |
| 142 | gate := g8.New().WithAuthorizationService(authorizationService) |
| 143 | ``` |
| 144 | |
| 145 | Be aware that g8.Client supports a list of permissions as well. You may call `WithPermission` several times, or call |
| 146 | `WithPermissions` with a slice of permissions instead. |
| 147 | |
| 148 | |
| 149 | ### Permissions |
| 150 | Unlike client permissions, handler permissions are requirements. |
| 151 | |
| 152 | A client may have as many permissions as you want, but for said client to have access to a handler protected by |
| 153 | permissions, the client must have all permissions defined by said handler in order to have access to it. |
| 154 | |
| 155 | In other words, a client with the permissions `create`, `read`, `update` and `delete` would have access to all of these handlers: |
| 156 | ```go |
| 157 | gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("mytoken").WithPermissions([]string{"create", "read", "update", "delete"}))) |
| 158 | router := http.NewServeMux() |
| 159 | router.Handle("/", gate.Protect(homeHandler)) // equivalent of gate.ProtectWithPermissions(homeHandler, []string{}) |
| 160 | router.Handle("/create", gate.ProtectWithPermissions(createHandler, []string{"create"})) |
| 161 | router.Handle("/read", gate.ProtectWithPermissions(readHandler, []string{"read"})) |
| 162 | router.Handle("/update", gate.ProtectWithPermissions(updateHandler, []string{"update"})) |
| 163 | router.Handle("/delete", gate.ProtectWithPermissions(deleteHandler, []string{"delete"})) |
| 164 | router.Handle("/crud", gate.ProtectWithPermissions(crudHandler, []string{"create", "read", "update", "delete"})) |
| 165 | ``` |
| 166 | But it would not have access to the following handler, because while `mytoken` has the `read` permission, it does not |
| 167 | have the `backup` permission: |
| 168 | ```go |
| 169 | router.Handle("/backup", gate.ProtectWithPermissions(&testHandler{}, []string{"read", "backup"})) |
| 170 | ``` |
| 171 | |
| 172 | If you're using an HTTP library that supports middlewares like [mux](https://github.com/gorilla/mux), you can protect |
| 173 | an entire group of handlers instead using `gate.Protect` or `gate.PermissionMiddleware()`: |
| 174 | ```go |
| 175 | router := mux.NewRouter() |
| 176 | |
| 177 | userRouter := router.PathPrefix("/").Subrouter() |
| 178 | userRouter.Use(gate.Protect) |
| 179 | userRouter.HandleFunc("/api/v1/users/me", getUserProfile).Methods("GET") |
| 180 | userRouter.HandleFunc("/api/v1/users/me/friends", getUserFriends).Methods("GET") |
| 181 | userRouter.HandleFunc("/api/v1/users/me/email", updateUserEmail).Methods("PATCH") |
| 182 | |
| 183 | adminRouter := router.PathPrefix("/").Subrouter() |
| 184 | adminRouter.Use(gate.PermissionMiddleware("admin")) |
| 185 | adminRouter.HandleFunc("/api/v1/users/{id}/ban", banUserByID).Methods("POST") |
| 186 | adminRouter.HandleFunc("/api/v1/users/{id}/delete", deleteUserByID).Methods("DELETE") |
| 187 | ``` |
| 188 | |
| 189 | |
| 190 | ## Rate limiting |
| 191 | To add a rate limit of 100 requests per second: |
| 192 | ```go |
| 193 | gate := g8.New().WithRateLimit(100) |
| 194 | ``` |
| 195 | |
| 196 | |
| 197 | ## Accessing the token from the protected handlers |
| 198 | If you need to access the token from the handlers you are protecting with g8, you can retrieve it from the |
| 199 | request context by using the key `g8.TokenContextKey`: |
| 200 | ```go |
| 201 | http.Handle("/handle", gate.ProtectFunc(func(w http.ResponseWriter, r *http.Request) { |
| 202 | token, _ := r.Context().Value(g8.TokenContextKey).(string) |
| 203 | // ... |
| 204 | })) |
| 205 | ``` |
| 206 | |
| 207 | ## Examples |
| 208 | ### Protecting a handler using session cookie |
| 209 | If you want to only allow authenticated users to access a handler, you can use a custom token extractor function |
| 210 | combined with a client provider. |
| 211 | |
| 212 | First, we'll create a function to extract the session ID from the session cookie. While a session ID does not |
| 213 | theoretically refer to a token, g8 uses the term `token` as a blanket term to refer to any string that can be used to |
| 214 | identify a client. |
| 215 | ```go |
| 216 | customTokenExtractorFunc := func(request *http.Request) string { |
| 217 | sessionCookie, err := request.Cookie("session") |
| 218 | if err != nil { |
| 219 | return "" |
| 220 | } |
| 221 | return sessionCookie.Value |
| 222 | } |
| 223 | ``` |
| 224 | |
| 225 | Next, we need to create a client provider that will validate our token, which refers to the session ID in this case. |
| 226 | ```go |
| 227 | clientProvider := g8.NewClientProvider(func(token string) *g8.Client { |
| 228 | // We'll assume that the following function calls your database and validates whether the session is valid. |
| 229 | isSessionValid := database.CheckIfSessionIsValid(token) |
| 230 | if !isSessionValid { |
| 231 | return nil // Returning nil will cause the gate to return a 401 Unauthorized. |
| 232 | } |
| 233 | // You could also retrieve the user and their permissions if you wanted instead, but for this example, |
| 234 | // all we care about is confirming whether the session is valid or not. |
| 235 | return g8.NewClient(token) |
| 236 | }) |
| 237 | ``` |
| 238 | |
| 239 | Keep in mind that you can get really creative with the client provider above. |
| 240 | For instance, you could refresh the session's expiration time, which will allow the user to stay logged in for |
| 241 | as long as they're active. |
| 242 | |
| 243 | You're also not limited to using something stateful like the example above. You could use a JWT and have your client |
| 244 | provider validate said JWT. |
| 245 | |
| 246 | Finally, we can create the authorization service and the gate: |
| 247 | ```go |
| 248 | authorizationService := g8.NewAuthorizationService().WithClientProvider(clientProvider) |
| 249 | gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc) |
| 250 | ``` |
| 251 | |
| 252 | If you need to access the token (session ID in this case) from the protected handlers, you can retrieve it from the |
| 253 | request context by using the key `g8.TokenContextKey`: |
| 254 | ```go |
| 255 | http.Handle("/handle", gate.ProtectFunc(func(w http.ResponseWriter, r *http.Request) { |
| 256 | sessionID, _ := r.Context().Value(g8.TokenContextKey).(string) |
| 257 | // ... |
| 258 | })) |
| 259 | ``` |
| 260 | |
| 261 | ### Using a custom header |
| 262 | The logic is the same as the example above: |
| 263 | ```go |
| 264 | customTokenExtractorFunc := func(request *http.Request) string { |
| 265 | return request.Header.Get("X-API-Token") |
| 266 | } |
| 267 | |
| 268 | clientProvider := g8.NewClientProvider(func(token string) *g8.Client { |
| 269 | // We'll assume that the following function calls your database and returns a struct "User" that |
| 270 | // has the user's token as well as the permissions granted to said user |
| 271 | user := database.GetUserByToken(token) |
| 272 | if user != nil { |
| 273 | return g8.NewClient(user.Token).WithPermissions(user.Permissions) |
| 274 | } |
| 275 | return nil |
| 276 | }) |
| 277 | authorizationService := g8.NewAuthorizationService().WithClientProvider(clientProvider) |
| 278 | gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc) |
| 279 | ``` |
| 280 | |
| 281 | ### Using a custom cache |
| 282 | |
| 283 | ```go |
| 284 | package main |
| 285 | |
| 286 | import ( |
| 287 | g8 "github.com/TwiN/g8/v3" |
| 288 | ) |
| 289 | |
| 290 | type customCache struct { |
| 291 | entries map[string]any |
| 292 | sync.Mutex |
| 293 | } |
| 294 | |
| 295 | func (c *customCache) Get(key string) (value any, exists bool) { |
| 296 | return nil, false |
| 297 | } |
| 298 | |
| 299 | func (c *customCache) Set(key string, value any) { |
| 300 | // ... |
| 301 | } |
| 302 | |
| 303 | // To verify the implementation |
| 304 | var _ g8.Cache = (*customCache)(nil) |
| 305 | |
| 306 | func main() { |
| 307 | getClientByTokenFunc := func(token string) *g8.Client { |
| 308 | // We'll assume that the following function calls your database and returns a struct "User" that |
| 309 | // has the user's token as well as the permissions granted to said user |
| 310 | user := database.GetUserByToken(token) |
| 311 | if user != nil { |
| 312 | return g8.NewClient(user.Token).WithPermissions(user.Permissions).WithData(user.Data) |
| 313 | } |
| 314 | return nil |
| 315 | } |
| 316 | // Create the provider with the custom cache |
| 317 | provider := g8.NewClientProvider(getClientByTokenFunc).WithCustomCache(&customCache{}) |
| 318 | } |
| 319 | ``` |