diff --git a/.traefik.yml b/.traefik.yml index 55a5579..9bf1420 100644 --- a/.traefik.yml +++ b/.traefik.yml @@ -1,4 +1,4 @@ -displayName: Fifteen +displayName: JWT Field as Header type: middleware iconPath: .assets/icon.png @@ -7,9 +7,10 @@ import: github.com/birotaio/traefik-plugins summary: 'Make custom header from JWT data, can be used for user-based ratelimiting' testData: - jwt-header-name: X-ApiKey - jwt-field: customer_id - value-header-name: X-UserId-RateLimit - fallback-type: ip + jwtHeaderName: X-ApiKey + jwtField: customer_id + valueHeaderName: X-UserId-RateLimit + fallbacks: + - type: ip debug: true diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a380fb0 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,2 @@ +FROM traefik:v2.10.4 +COPY . /plugins-local/src/github.com/birotaio/traefik-plugins/ diff --git a/fifteen.go b/fifteen.go index ea52214..862cbc7 100644 --- a/fifteen.go +++ b/fifteen.go @@ -5,27 +5,33 @@ import ( "fmt" "net/http" "os" + "strings" "github.com/golang-jwt/jwt/v5" ) -type Fallback string +type FallbackType string const ( - FallbackError Fallback = "error" - FallbackPass Fallback = "pass" - FallbackIp Fallback = "ip" - FallbackHeader Fallback = "header" + FallbackError FallbackType = "error" + FallbackPass FallbackType = "pass" + FallbackIp FallbackType = "ip" + FallbackHeader FallbackType = "header" ) +type Fallback struct { + Type FallbackType `yaml:"type,omitempty"` + Value string `yaml:"value,omitempty"` + KeepIfEmpty bool `yaml:"keepIfEmpty,omitempty"` +} + // Config the plugin configuration. type Config struct { - JwtHeaderName string `json:"jwt-header-name,omitempty"` - JwtField string `json:"jwt-field,omitempty"` - ValueHeaderName string `json:"value-header-name,omitempty"` - FallbackType Fallback `json:"fallback-type,omitempty"` - FallbackHeaderName string `json:"fallback-header-name,omitempty"` - Debug bool `json:"debug,omitempty"` + JwtHeaderName string `yaml:"jwtHeaderName,omitempty"` + JwtField string `yaml:"jwtField,omitempty"` + ValueHeaderName string `yaml:"valueHeaderName,omitempty"` + Fallbacks []Fallback `yaml:"fallbacks,omitempty"` + Debug bool `yaml:"debug,omitempty"` } // CreateConfig creates the default plugin configuration. @@ -56,7 +62,11 @@ func (a *Fifteen) ServeHTTP(rw http.ResponseWriter, req *http.Request) { return } - rawToken := req.Header.Get(a.cfg.JwtHeaderName) + rawHeader := req.Header.Get(a.cfg.JwtHeaderName) + rawToken := "" + if strings.HasPrefix(rawHeader, "Bearer ") { + rawToken = rawHeader[len("Bearer "):] + } parsedToken, _, err := jwt.NewParser().ParseUnverified(rawToken, jwt.MapClaims{}) if err != nil { a.logDebug("Could not parse non-empty jwt token, falling back: %s", err.Error()) @@ -84,26 +94,52 @@ func (a *Fifteen) ServeHTTP(rw http.ResponseWriter, req *http.Request) { return } } else { - a.logDebug("JWT field value has an unexpected type, falling back") + a.logDebug("JWT field value does not hold field %s, falling back", a.cfg.JwtField) a.ServeFallback(rw, req) return } - a.next.ServeHTTP(rw, req) + a.end(rw, req) } func (a *Fifteen) ServeFallback(rw http.ResponseWriter, req *http.Request) { - a.logDebug("Fallbacked because JWT was not set, invalid or has unexpected value on field. Using fallback strategy: %s", a.cfg.FallbackType) - switch a.cfg.FallbackType { - case FallbackError: - rw.WriteHeader(http.StatusBadRequest) - case FallbackIp: - req.Header.Set(a.cfg.ValueHeaderName, req.RemoteAddr) - case FallbackHeader: - req.Header.Set(a.cfg.ValueHeaderName, req.Header.Get(a.cfg.FallbackHeaderName)) - default: - a.next.ServeHTTP(rw, req) + if len(a.cfg.Fallbacks) == 0 { + a.logDebug("Fallbacked because JWT was not set, invalid or has unexpected value on field. No fallback strategies, ignoring...") + } else { + a.logDebug("Fallbacked because JWT was not set, invalid or has unexpected value on field. Finding right fallback strategy") + for i, fallback := range a.cfg.Fallbacks { + a.logDebug("Strategy %d: %+v", i, fallback) + var success bool + switch fallback.Type { + case FallbackError: + rw.Header().Set("Content-Type", "text/plain") + rw.WriteHeader(http.StatusBadRequest) + rw.Write([]byte("Bad request")) + return + case FallbackPass: + a.logDebug("Passing through") + success = true + case FallbackIp: + req.Header.Set(a.cfg.ValueHeaderName, ipWithNoPort(req.RemoteAddr)) + success = true + case FallbackHeader: + headerValue := req.Header.Get(fallback.Value) + if headerValue == "" && !fallback.KeepIfEmpty { + a.logDebug("Header %s was empty, skipping...", fallback.Value) + continue + } + req.Header.Set(a.cfg.ValueHeaderName, headerValue) + success = true + default: + a.logDebug("Unknown fallback type, skipping...") + } + if success { + a.logDebug("Fallback strategy %d was successful", i) + break + } + } } + a.end(rw, req) } func (a *Fifteen) logDebug(format string, args ...any) { @@ -112,3 +148,15 @@ func (a *Fifteen) logDebug(format string, args ...any) { } os.Stderr.WriteString("[Fifteen middleware]: " + fmt.Sprintf(format, args...) + "\n") } + +func (a *Fifteen) end(rw http.ResponseWriter, req *http.Request) { + a.logDebug("ending with request headers: %+v", req.Header) + a.next.ServeHTTP(rw, req) +} + +func ipWithNoPort(addr string) string { + if colon := strings.LastIndex(addr, ":"); colon != -1 { + return addr[:colon] + } + return addr +} diff --git a/fifteen_test.go b/fifteen_test.go index 1e0d19d..d2771d9 100644 --- a/fifteen_test.go +++ b/fifteen_test.go @@ -12,7 +12,9 @@ func TestDemo(t *testing.T) { cfg.JwtHeaderName = "X-ApiKey" cfg.JwtField = "customer_id" cfg.ValueHeaderName = "X-UserId-RateLimit" - cfg.FallbackType = FallbackIp + cfg.Fallbacks = []Fallback{ + {Type: FallbackIp}, + } cfg.Debug = false ctx := context.Background() diff --git a/readme.md b/readme.md index 353f34d..4105e43 100644 --- a/readme.md +++ b/readme.md @@ -1,270 +1,23 @@ -This repository includes an example plugin, `demo`, for you to use as a reference for developing your own plugins. +# JWT Field as Header -[![Build Status](https://github.com/traefik/plugindemo/workflows/Main/badge.svg?branch=master)](https://github.com/traefik/plugindemo/actions) - -The existing plugins can be browsed into the [Plugin Catalog](https://plugins.traefik.io). - -# Developing a Traefik plugin - -[Traefik](https://traefik.io) plugins are developed using the [Go language](https://golang.org). - -A [Traefik](https://traefik.io) middleware plugin is just a [Go package](https://golang.org/ref/spec#Packages) that provides an `http.Handler` to perform specific processing of requests and responses. - -Rather than being pre-compiled and linked, however, plugins are executed on the fly by [Yaegi](https://github.com/traefik/yaegi), an embedded Go interpreter. +Use a JWT field as header value to, for example, use it as a rate limiting key. +This middleware will add the JWT field as header value to the request or if the jwt is not set/valid it will use different fallback strategies. ## Usage -For a plugin to be active for a given Traefik instance, it must be declared in the static configuration. - -Plugins are parsed and loaded exclusively during startup, which allows Traefik to check the integrity of the code and catch errors early on. -If an error occurs during loading, the plugin is disabled. - -For security reasons, it is not possible to start a new plugin or modify an existing one while Traefik is running. - -Once loaded, middleware plugins behave exactly like statically compiled middlewares. -Their instantiation and behavior are driven by the dynamic configuration. - -Plugin dependencies must be [vendored](https://golang.org/ref/mod#vendoring) for each plugin. -Vendored packages should be included in the plugin's GitHub repository. ([Go modules](https://blog.golang.org/using-go-modules) are not supported.) - -### Configuration - -For each plugin, the Traefik static configuration must define the module name (as is usual for Go packages). - -The following declaration (given here in YAML) defines a plugin: - -```yaml -# Static configuration - -experimental: - plugins: - example: - moduleName: github.com/traefik/plugindemo - version: v0.2.1 -``` - -Here is an example of a file provider dynamic configuration (given here in YAML), where the interesting part is the `http.middlewares` section: - +- Install the plugin +- Configure it with the following fields ```yaml -# Dynamic configuration - -http: - routers: - my-router: - rule: host(`demo.localhost`) - service: service-foo - entryPoints: - - web - middlewares: - - my-plugin - - services: - service-foo: - loadBalancer: - servers: - - url: http://127.0.0.1:5000 - - middlewares: - my-plugin: - plugin: - example: - headers: - Foo: Bar -``` - -### Local Mode - -Traefik also offers a developer mode that can be used for temporary testing of plugins not hosted on GitHub. -To use a plugin in local mode, the Traefik static configuration must define the module name (as is usual for Go packages) and a path to a [Go workspace](https://golang.org/doc/gopath_code.html#Workspaces), which can be the local GOPATH or any directory. - -The plugins must be placed in `./plugins-local` directory, -which should be in the working directory of the process running the Traefik binary. -The source code of the plugin should be organized as follows: - -``` -./plugins-local/ - └── src - └── github.com - └── traefik - └── plugindemo - ├── demo.go - ├── demo_test.go - ├── go.mod - ├── LICENSE - ├── Makefile - └── readme.md -``` - -```yaml -# Static configuration - -experimental: - localPlugins: - example: - moduleName: github.com/traefik/plugindemo -``` - -(In the above example, the `plugindemo` plugin will be loaded from the path `./plugins-local/src/github.com/traefik/plugindemo`.) - -```yaml -# Dynamic configuration - -http: - routers: - my-router: - rule: host(`demo.localhost`) - service: service-foo - entryPoints: - - web - middlewares: - - my-plugin - - services: - service-foo: - loadBalancer: - servers: - - url: http://127.0.0.1:5000 - - middlewares: - my-plugin: - plugin: - example: - headers: - Foo: Bar -``` - -## Defining a Plugin - -A plugin package must define the following exported Go objects: - -- A type `type Config struct { ... }`. The struct fields are arbitrary. -- A function `func CreateConfig() *Config`. -- A function `func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error)`. - -```go -// Package example a example plugin. -package example - -import ( - "context" - "net/http" -) - -// Config the plugin configuration. -type Config struct { - // ... -} - -// CreateConfig creates the default plugin configuration. -func CreateConfig() *Config { - return &Config{ - // ... - } -} - -// Example a plugin. -type Example struct { - next http.Handler - name string - // ... -} - -// New created a new plugin. -func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { - // ... - return &Example{ - // ... - }, nil -} - -func (e *Example) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - // ... - e.next.ServeHTTP(rw, req) -} -``` - -## Logs - -Currently, the only way to send logs to Traefik is to use `os.Stdout.WriteString("...")` or `os.Stderr.WriteString("...")`. - -In the future, we will try to provide something better and based on levels. - -## Plugins Catalog - -Traefik plugins are stored and hosted as public GitHub repositories. - -Every 30 minutes, the Plugins Catalog online service polls Github to find plugins and add them to its catalog. - -### Prerequisites - -To be recognized by Plugins Catalog, your repository must meet the following criteria: - -- The `traefik-plugin` topic must be set. -- The `.traefik.yml` manifest must exist, and be filled with valid contents. - -If your repository fails to meet either of these prerequisites, Plugins Catalog will not see it. - -### Manifest - -A manifest is also mandatory, and it should be named `.traefik.yml` and stored at the root of your project. - -This YAML file provides Plugins Catalog with information about your plugin, such as a description, a full name, and so on. - -Here is an example of a typical `.traefik.yml`file: - -```yaml -# The name of your plugin as displayed in the Plugins Catalog web UI. -displayName: Name of your plugin - -# For now, `middleware` is the only type available. -type: middleware - -# The import path of your plugin. -import: github.com/username/my-plugin - -# A brief description of what your plugin is doing. -summary: Description of what my plugin is doing - -# Medias associated to the plugin (optional) -iconPath: foo/icon.png -bannerPath: foo/banner.png - -# Configuration data for your plugin. -# This is mandatory, -# and Plugins Catalog will try to execute the plugin with the data you provide as part of its startup validity tests. -testData: - Headers: - Foo: Bar -``` - -Properties include: - -- `displayName` (required): The name of your plugin as displayed in the Plugins Catalog web UI. -- `type` (required): For now, `middleware` is the only type available. -- `import` (required): The import path of your plugin. -- `summary` (required): A brief description of what your plugin is doing. -- `testData` (required): Configuration data for your plugin. This is mandatory, and Plugins Catalog will try to execute the plugin with the data you provide as part of its startup validity tests. -- `iconPath` (optional): A local path in the repository to the icon of the project. -- `bannerPath` (optional): A local path in the repository to the image that will be used when you will share your plugin page in social medias. - -There should also be a `go.mod` file at the root of your project. Plugins Catalog will use this file to validate the name of the project. - -### Tags and Dependencies - -Plugins Catalog gets your sources from a Go module proxy, so your plugins need to be versioned with a git tag. - -Last but not least, if your plugin middleware has Go package dependencies, you need to vendor them and add them to your GitHub repository. - -If something goes wrong with the integration of your plugin, Plugins Catalog will create an issue inside your Github repository and will stop trying to add your repo until you close the issue. - -## Troubleshooting - -If Plugins Catalog fails to recognize your plugin, you will need to make one or more changes to your GitHub repository. - -In order for your plugin to be successfully imported by Plugins Catalog, consult this checklist: - -- The `traefik-plugin` topic must be set on your repository. -- There must be a `.traefik.yml` file at the root of your project describing your plugin, and it must have a valid `testData` property for testing purposes. -- There must be a valid `go.mod` file at the root of your project. -- Your plugin must be versioned with a git tag. -- If you have package dependencies, they must be vendored and added to your GitHub repository. + debug: "true" # Boolean to enable debug mode, prints debug messages to the traefik log + jwtHeaderName: Authorization # Name of the header that contains the JWT + jwtField: customer_id # Name of the JWT field that will be used as header value + valueHeaderName: X-Rate-Limit # Name of the header that will be added to the request + fallbacks: # List of fallback strategies + - type: header # Type of the fallback strategy, one of: header, ip, pass, error + value: x-apikey # For the header strategy, the name of the header that will be used as header value + keepIfEmpty: "true" # If true uses this fallback strategy even if the header is empty + - type: ip # For the ip strategy, the remote address will be used as header value + - type: error # For the error strategy, the request will be aborted with a 400 error + - type: pass # For the pass strategy, the request will be passed without adding a header +``` +- Use it as the middleware in one of your routes