From 4aebd2cf361d0245f3e20f7de444eaa427182e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E6=B3=BD?= Date: Wed, 4 Oct 2023 13:39:41 +0800 Subject: [PATCH] init session max age --- .traefik.yml | 12 +-- demo.go | 66 ------------- demo_test.go | 49 ---------- go.mod | 2 +- max_age.go | 71 ++++++++++++++ max_age_test.go | 8 ++ readme.md | 244 ++---------------------------------------------- 7 files changed, 95 insertions(+), 357 deletions(-) delete mode 100644 demo.go delete mode 100644 demo_test.go create mode 100644 max_age.go create mode 100644 max_age_test.go diff --git a/.traefik.yml b/.traefik.yml index 57fb70e..cbdf681 100644 --- a/.traefik.yml +++ b/.traefik.yml @@ -1,12 +1,10 @@ -displayName: Demo Plugin +displayName: Sticky Session Max Age type: middleware -iconPath: .assets/icon.png -import: github.com/traefik/plugindemo +import: github.com/patrick0308/traefik-session-max-age -summary: '[Demo] Add Request Header' +summary: "Set sticky session cookie's max age" testData: - Headers: - X-Demo: test - X-URL: '{{URL}}' + cookieName: _traefik_session + maxAge: 10000 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..1aaaff4 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module github.com/traefik/plugindemo +module github.com/patrick0308/traefik-session-max-age go 1.19 diff --git a/max_age.go b/max_age.go new file mode 100644 index 0000000..a1d70e8 --- /dev/null +++ b/max_age.go @@ -0,0 +1,71 @@ +package session_max_age + +import ( + "context" + "net/http" +) + +// Config the plugin configuration. +type Config struct { + CookieName string `json:"cookieName,omitempty"` + MaxAge int `json:"maxAge,omitempty"` +} + +// CreateConfig creates the default plugin configuration. +func CreateConfig() *Config { + return &Config{} +} + +type ResponseWriterWrapper struct { + http.ResponseWriter + cookieName string + maxAge int +} + +func (rww ResponseWriterWrapper) Header() http.Header { + return rww.ResponseWriter.Header() +} + +func (rww ResponseWriterWrapper) WriteHeader(code int) { + if rww.cookieName != "" { + res := http.Response{Header: rww.ResponseWriter.Header()} + cookies := res.Cookies() + for _, cookie := range cookies { + if cookie.Name == rww.cookieName { + cookie.MaxAge = rww.maxAge + http.SetCookie(rww.ResponseWriter, cookie) + } + } + } + rww.ResponseWriter.WriteHeader(code) +} + +func (rww ResponseWriterWrapper) Write(b []byte) (int, error) { + return rww.ResponseWriter.Write(b) +} + +type HeaderWrapper http.Header + +func (h HeaderWrapper) Add(key, value string) { + h.Add(key, value) +} + +type SessionMaxAge struct { + next http.Handler + cookieName string + maxAge int + name string +} + +func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { + return &SessionMaxAge{ + next: next, + name: name, + maxAge: config.MaxAge, + cookieName: config.CookieName, + }, nil +} + +func (a *SessionMaxAge) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + a.next.ServeHTTP(ResponseWriterWrapper{ResponseWriter: rw, cookieName: a.cookieName, maxAge: a.maxAge}, req) +} diff --git a/max_age_test.go b/max_age_test.go new file mode 100644 index 0000000..0e28dc2 --- /dev/null +++ b/max_age_test.go @@ -0,0 +1,8 @@ +package session_max_age_test + +import ( + "testing" +) + +func TestDemo(t *testing.T) { +} diff --git a/readme.md b/readme.md index 353f34d..21db5f7 100644 --- a/readme.md +++ b/readme.md @@ -1,35 +1,8 @@ -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.) +This repository includes traefik plugin which sets sticky session cookie's max age. ### Configuration -For each plugin, the Traefik static configuration must define the module name (as is usual for Go packages). +For traefik plugin, static configuration must define the module name (as is usual for Go packages). The following declaration (given here in YAML) defines a plugin: @@ -38,9 +11,9 @@ The following declaration (given here in YAML) defines a plugin: experimental: plugins: - example: - moduleName: github.com/traefik/plugindemo - version: v0.2.1 + session-max-age: + moduleName: github.com/patrick0308/traefik-session-max-age + 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: @@ -59,212 +32,15 @@ http: - my-plugin services: - service-foo: + 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: + session-max-age: plugin: - example: - headers: - Foo: Bar + session-max-age: + cookieName: traefik_cookie + maxAge: 100000 ``` - -## 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.