diff --git a/.golangci.yml b/.golangci.yml
index cc994d7..22f9e5a 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -25,21 +25,16 @@ linters-settings:
- FIXME
gofumpt:
extra-rules: true
+ depguard:
+ rules:
+ main:
+ allow:
+ - $gostd
+ - "github.com/RiskIdent/traefik-remoteaddr-plugin"
linters:
enable-all: true
disable:
- - deadcode # deprecated
- - exhaustivestruct # deprecated
- - golint # deprecated
- - ifshort # deprecated
- - interfacer # deprecated
- - maligned # deprecated
- - nosnakecase # deprecated
- - scopelint # deprecated
- - scopelint # deprecated
- - structcheck # deprecated
- - varcheck # deprecated
- sqlclosecheck # not relevant (SQL)
- rowserrcheck # not relevant (SQL)
- execinquery # not relevant (SQL)
@@ -53,9 +48,7 @@ linters:
- wsl
- exhaustive
- exhaustruct
- - goerr113
- wrapcheck
- - ifshort
- noctx
- lll
- gomnd
diff --git a/.traefik.yml b/.traefik.yml
index 57fb70e..ef44571 100644
--- a/.traefik.yml
+++ b/.traefik.yml
@@ -1,12 +1,11 @@
-displayName: Demo Plugin
+displayName: RemoteAddr (fix X-Forwarded-Port)
type: middleware
iconPath: .assets/icon.png
-import: github.com/traefik/plugindemo
+import: github.com/RiskIdent/traefik-remoteaddr-plugin
-summary: '[Demo] Add Request Header'
+summary: "Add request header for the client port, to make X-Forwarded-Port act like in nginx"
testData:
- Headers:
- X-Demo: test
- X-URL: '{{URL}}'
+ headers:
+ port: X-Forwarded-Port
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..4511fe3
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,6 @@
+ARG TRAEFIK_VERSION=v3.0.0
+ARG BASE_IMAGE=docker.io/traefik:${TRAEFIK_VERSION}
+FROM ${BASE_IMAGE}
+
+COPY . plugins-local/src/github.com/RiskIdent/traefik-remoteaddr-plugin/
+ENV TRAEFIK_EXPERIMENTAL_LOCALPLUGINS_remoteaddr_MODULENAME="github.com/RiskIdent/traefik-remoteaddr-plugin""
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..2fdde18
--- /dev/null
+++ b/README.md
@@ -0,0 +1,157 @@
+# Traefik RemoteAddr plugin
+
+[![Build Status](https://github.com/RiskIdent/traefik-remoteaddr-plugin/workflows/Main/badge.svg?branch=master)](https://github.com/RiskIdent/traefik-remoteaddr-plugin/actions)
+
+## Usage
+
+This plugin is very simple: take the **client** IP and port and write them to some headers.
+This is done by using the Go field [`net/http.Request.RemoteAddr`](https://pkg.go.dev/net/http#Request)
+which is composed of `IP:port` of the client connection.
+
+To mimic nginx's behaviour of `X-Forwarded-Port`, where it sets that header to the client's port, then use the dynamic middleware config:
+
+```yaml
+middlewares:
+ my-middleware:
+ plugin:
+ remoteaddr:
+ headers:
+ port: X-Forwarded-Port
+```
+
+Alternatively, you could use the non-standard `X-Real-Port` to not override Traefik's behavior:
+
+```yaml
+middlewares:
+ my-middleware:
+ plugin:
+ remoteaddr:
+ headers:
+ port: X-Real-Port
+```
+
+### Configuration
+
+Traefik static configuration must define the module name (as is usual for Go packages).
+
+The following declaration (given here in YAML) defines a plugin:
+
+File (YAML)
+
+```yaml
+# Static configuration
+
+experimental:
+ plugins:
+ remoteaddr:
+ moduleName: github.com/RiskIdent/traefik-remoteaddr-plugin
+ version: v0.1.0
+```
+
+
+
+CLI
+
+```bash
+# Static configuration
+
+--experimental.plugins.remoteaddr.moduleName=github.com/RiskIdent/traefik-remoteaddr-plugin
+--experimental.plugins.remoteaddr.version=v0.1.0
+```
+
+
+
+Here is an example of a file provider dynamic configuration (given here in YAML), where the interesting part is the `http.middlewares` section:
+
+File (YAML)
+
+```yaml
+# Dynamic configuration
+
+http:
+ middlewares:
+ my-middleware:
+ plugin:
+ remoteaddr:
+ headers:
+ # if set, then set header "X-Real-Address" to the RemoteAddr (e.g "192.168.1.2:1234")
+ address: X-Real-Address
+ # if set, then set header "X-Real-Ip" to the IP of RemoteAddr (e.g "192.168.1.2")
+ ip: X-Real-Ip
+ # if set, then set header "X-Real-Port" to the port of RemoteAddr (e.g "1234")
+ port: X-Real-Port
+```
+
+
+
+Kubernetes
+
+```yaml
+# Dynamic configuration
+
+apiVersion: traefik.io/v1alpha1
+kind: Middleware
+metadata:
+ name: my-middleware
+spec:
+ plugin:
+ remoteaddr:
+ headers:
+ # if set, then set header "X-Real-Address" to the RemoteAddr (e.g "192.168.1.2:1234")
+ address: X-Real-Address
+ # if set, then set header "X-Real-Ip" to the IP of RemoteAddr (e.g "192.168.1.2")
+ ip: X-Real-Ip
+ # if set, then set header "X-Real-Port" to the port of RemoteAddr (e.g "1234")
+ port: X-Real-Port
+```
+
+
+
+### 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:
+
+```console
+$ tree ./plugins-local/
+./plugins-local/
+ └── src
+ └── github.com
+ └── RiskIdent
+ └── traefik-remoteaddr-plugin
+ ├── plugin.go
+ ├── plugin_test.go
+ ├── go.mod
+ ├── LICENSE
+ ├── Makefile
+ └── README.md
+```
+
+File (YAML)
+
+```yaml
+# Static configuration
+
+experimental:
+ localPlugins:
+ remoteaddr:
+ moduleName: github.com/RiskIdent/traefik-remoteaddr-plugin
+```
+
+
+
+CLI
+
+```bash
+# Static configuration
+
+--experimental.localPlugins.remoteaddr.moduleName=github.com/RiskIdent/traefik-remoteaddr-plugin
+```
+
+
+
+(In the above example, the `traefik-remoteaddr-plugin` plugin will be loaded from the path `./plugins-local/src/github.com/RiskIdent/traefik-remoteaddr-plugin`.)
diff --git a/demo.go b/demo.go
deleted file mode 100644
index 88d8c18..0000000
--- a/demo.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Package plugindemo a demo plugin.
-package plugindemo
-
-import (
- "bytes"
- "context"
- "fmt"
- "net/http"
- "text/template"
-)
-
-// Config the plugin configuration.
-type Config struct {
- Headers map[string]string `json:"headers,omitempty"`
-}
-
-// CreateConfig creates the default plugin configuration.
-func CreateConfig() *Config {
- return &Config{
- Headers: make(map[string]string),
- }
-}
-
-// Demo a Demo plugin.
-type Demo struct {
- next http.Handler
- headers map[string]string
- name string
- template *template.Template
-}
-
-// New created a new Demo plugin.
-func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
- if len(config.Headers) == 0 {
- return nil, fmt.Errorf("headers cannot be empty")
- }
-
- return &Demo{
- headers: config.Headers,
- next: next,
- name: name,
- template: template.New("demo").Delims("[[", "]]"),
- }, nil
-}
-
-func (a *Demo) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
- for key, value := range a.headers {
- tmpl, err := a.template.Parse(value)
- if err != nil {
- http.Error(rw, err.Error(), http.StatusInternalServerError)
- return
- }
-
- writer := &bytes.Buffer{}
-
- err = tmpl.Execute(writer, req)
- if err != nil {
- http.Error(rw, err.Error(), http.StatusInternalServerError)
- return
- }
-
- req.Header.Set(key, writer.String())
- }
-
- a.next.ServeHTTP(rw, req)
-}
diff --git a/demo_test.go b/demo_test.go
deleted file mode 100644
index dd0edcf..0000000
--- a/demo_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package plugindemo_test
-
-import (
- "context"
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/traefik/plugindemo"
-)
-
-func TestDemo(t *testing.T) {
- cfg := plugindemo.CreateConfig()
- cfg.Headers["X-Host"] = "[[.Host]]"
- cfg.Headers["X-Method"] = "[[.Method]]"
- cfg.Headers["X-URL"] = "[[.URL]]"
- cfg.Headers["X-URL"] = "[[.URL]]"
- cfg.Headers["X-Demo"] = "test"
-
- ctx := context.Background()
- next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {})
-
- handler, err := plugindemo.New(ctx, next, cfg, "demo-plugin")
- if err != nil {
- t.Fatal(err)
- }
-
- recorder := httptest.NewRecorder()
-
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- handler.ServeHTTP(recorder, req)
-
- assertHeader(t, req, "X-Host", "localhost")
- assertHeader(t, req, "X-URL", "http://localhost")
- assertHeader(t, req, "X-Method", "GET")
- assertHeader(t, req, "X-Demo", "test")
-}
-
-func assertHeader(t *testing.T, req *http.Request, key, expected string) {
- t.Helper()
-
- if req.Header.Get(key) != expected {
- t.Errorf("invalid header value: %s", req.Header.Get(key))
- }
-}
diff --git a/go.mod b/go.mod
index 38181bb..16b3d48 100644
--- a/go.mod
+++ b/go.mod
@@ -1,3 +1,3 @@
-module github.com/traefik/plugindemo
+module github.com/RiskIdent/traefik-remoteaddr-plugin
go 1.19
diff --git a/plugin.go b/plugin.go
new file mode 100644
index 0000000..7a7ed10
--- /dev/null
+++ b/plugin.go
@@ -0,0 +1,66 @@
+// Package plugin a demo plugin.
+package plugin
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "strings"
+)
+
+var errMissingHeaderConfig = errors.New("missing header config: must set at least one of headers.port, headers.ip, or headers.address")
+
+// Config the plugin configuration.
+type Config struct {
+ Headers ConfigHeaders `json:"headers,omitempty"`
+}
+
+// ConfigHeaders defines the headers to use for the different values.
+type ConfigHeaders struct {
+ Port string `json:"port,omitempty"`
+ IP string `json:"ip,omitempty"`
+ Address string `json:"address,omitempty"`
+}
+
+// CreateConfig creates the default plugin configuration.
+func CreateConfig() *Config {
+ return &Config{
+ Headers: ConfigHeaders{},
+ }
+}
+
+// RemoteAddrPlugin a RemoteAddrPlugin plugin.
+type RemoteAddrPlugin struct {
+ next http.Handler
+ headers ConfigHeaders
+ name string
+}
+
+// New created a new RemoteAddrPlugin.
+func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
+ if config.Headers == (ConfigHeaders{}) {
+ return nil, errMissingHeaderConfig
+ }
+
+ return &RemoteAddrPlugin{
+ headers: config.Headers,
+ next: next,
+ name: name,
+ }, nil
+}
+
+func (a *RemoteAddrPlugin) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
+ ip, port, _ := strings.Cut(req.RemoteAddr, ":")
+
+ if a.headers.IP != "" {
+ req.Header.Set(a.headers.IP, ip)
+ }
+ if a.headers.Port != "" {
+ req.Header.Set(a.headers.Port, port)
+ }
+ if a.headers.Address != "" {
+ req.Header.Set(a.headers.Address, req.RemoteAddr)
+ }
+
+ a.next.ServeHTTP(rw, req)
+}
diff --git a/plugin_test.go b/plugin_test.go
new file mode 100644
index 0000000..d9d1abf
--- /dev/null
+++ b/plugin_test.go
@@ -0,0 +1,78 @@
+package plugin_test
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ plugin "github.com/RiskIdent/traefik-remoteaddr-plugin"
+)
+
+func TestInvalidConfig(t *testing.T) {
+ cfg := plugin.CreateConfig()
+ next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
+ _, err := plugin.New(context.Background(), next, cfg, "traefik-remoteaddr-plugin")
+ if err == nil {
+ t.Fatal("expected error")
+ }
+}
+
+func TestHeaderAddress(t *testing.T) {
+ cfg := plugin.CreateConfig()
+ cfg.Headers.Address = "X-Real-Address"
+ req := testPlugin(t, cfg)
+ assertHeader(t, req.Header, "X-Real-Address", "localhost:1234")
+}
+
+func TestHeaderIP(t *testing.T) {
+ cfg := plugin.CreateConfig()
+ cfg.Headers.IP = "X-Real-IP"
+ req := testPlugin(t, cfg)
+ assertHeader(t, req.Header, "X-Real-IP", "localhost")
+}
+
+func TestHeaderPort(t *testing.T) {
+ cfg := plugin.CreateConfig()
+ cfg.Headers.Port = "X-Real-Port"
+ req := testPlugin(t, cfg)
+ assertHeader(t, req.Header, "X-Real-Port", "1234")
+}
+
+func testPlugin(t *testing.T, cfg *plugin.Config) *http.Request {
+ t.Helper()
+ ctx := context.Background()
+ next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
+
+ handler, err := plugin.New(ctx, next, cfg, "traefik-remoteaddr-plugin")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ recorder := httptest.NewRecorder()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ req.RemoteAddr = "localhost:1234"
+ handler.ServeHTTP(recorder, req)
+
+ t.Logf("request headers: %d", len(req.Header))
+ for k, vals := range req.Header {
+ for _, v := range vals {
+ t.Logf(" %s=%q", k, v)
+ }
+ }
+
+ return req
+}
+
+func assertHeader(t *testing.T, header http.Header, key, expected string) {
+ t.Helper()
+
+ if header.Get(key) != expected {
+ t.Errorf("invalid header value\nwant: %s=%q\ngot: %s=%q", key, expected, key, header.Get(key))
+ }
+}
diff --git a/readme.md b/readme.md
deleted file mode 100644
index 353f34d..0000000
--- a/readme.md
+++ /dev/null
@@ -1,270 +0,0 @@
-This repository includes an example plugin, `demo`, for you to use as a reference for developing your own plugins.
-
-[![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.
-
-## 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:
-
-```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.