From a0f5b5e561c1c4dbd5b43883a2f290c82187c3c6 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Wed, 18 Nov 2026 19:39:50 +0100 Subject: [PATCH] docs(backpack,beachcomber,boardwalk,bonfire,bouncer): compile README Go examples via src= (quick-261118-qsd) - backpack: Greeter and ExampleApp_Publish replace the whole-file fence - beachcomber: Post's Searchable methods plus a new SearchIndexSchema, a Plugin.Boot that installs the gate, and the existing gate/search regions - boardwalk: new example_test.go; the mount region runs in ExampleHandler - bonfire: importPostsCommand and acmeMain (the binary's main as a function returning the exit code), run by ExampleExecute; ExampleCatalog_Has - bouncer: users/FindByID and ExampleNewJWTGuard; RefreshRoute run by TestDocsRefreshRoute on a production compass config --- modules/backpack/README.md | 57 ++++++++---------- modules/beachcomber/README.md | 62 ++++++++++++-------- modules/beachcomber/example_test.go | 35 ++++++++++- modules/boardwalk/README.md | 2 +- modules/boardwalk/example_test.go | 45 +++++++++++++++ modules/bonfire/README.md | 49 +++++++++------- modules/bonfire/example_test.go | 67 +++++++++++++++++++++ modules/bouncer/README.md | 84 ++++++++++++--------------- modules/bouncer/example_test.go | 90 +++++++++++++++++++++++++++++ 9 files changed, 366 insertions(+), 125 deletions(-) create mode 100644 modules/boardwalk/example_test.go diff --git a/modules/backpack/README.md b/modules/backpack/README.md index 85a884a3..e4a60700 100644 --- a/modules/backpack/README.md +++ b/modules/backpack/README.md @@ -30,45 +30,36 @@ Use cases: ## Usage -```go -package blog +```go src=modules/backpack/example_test.go#Greeter +// Greeter is a service the acme.greeter plugin offers to other plugins. +type Greeter interface { + Greet(name string) string +} +``` -import ( - "git.golem15.com/golem15/summercms/modules/backpack" - "git.golem15.com/golem15/summercms/modules/compass" -) +```go src=modules/backpack/example_test.go#ExampleApp_Publish +app := backpack.New(&compass.Config{}) +app.SetPlugins([]string{"acme.greeter", "acme.blog"}) -// Feed is a service the blog plugin offers to other plugins. -type Feed interface { - Latest(n int) []string +// acme.greeter, in its Register step: publish under the interface type. +var greeter Greeter = englishGreeter{} +if err := app.Publish(greeter); err != nil { + fmt.Println(err) + return } -type staticFeed struct{} - -func (staticFeed) Latest(n int) []string { return []string{"hello-world"} } - -func setup() error { - cfg, err := compass.Load("config") - if err != nil { - return err +// acme.blog, in its Boot step: look the service up by the same type. +if app.HasPlugin("acme.greeter") { + if found, ok := app.Lookup[Greeter](); ok { + fmt.Println(found.Greet("blog")) } - app := backpack.New(cfg) - app.SetPlugins([]string{"acme.blog", "acme.search"}) - - // Provider side, usually in the plugin's Register step. - var feed Feed = staticFeed{} - if err := app.Publish(feed); err != nil { // published under Feed, not staticFeed - return err - } - - // Consumer side, usually in another plugin's Boot step. - if app.HasPlugin("acme.blog") { - if found, ok := app.Lookup[Feed](); ok { - _ = found.Latest(5) - } - } - return nil } + +// A second Publish under the same type is refused. +fmt.Println(app.Publish(greeter) != nil) +// Output: +// Hello, blog +// true ``` Publish under an interface type when consumers should not depend on the concrete implementation; the lookup must use exactly the same type argument. diff --git a/modules/beachcomber/README.md b/modules/beachcomber/README.md index d7a02e49..b03d4d6f 100644 --- a/modules/beachcomber/README.md +++ b/modules/beachcomber/README.md @@ -81,12 +81,18 @@ typesense: A model implements `beachcomber.Searchable` without importing beachcomber: -```go -package models +```go src=modules/beachcomber/example_test.go#Post.SearchableAs +// SearchableAs is the index name, before search.prefix. +func (Post) SearchableAs() string { return "acme_blog_posts" } +``` -func (Post) SearchableAs() string { return "acme_blog_posts" } -func (Post) ShouldBeSearchable() bool { return true } +```go src=modules/beachcomber/example_test.go#Post.ShouldBeSearchable +// ShouldBeSearchable keeps drafts out of the index. +func (p *Post) ShouldBeSearchable() bool { return p.Published } +``` +```go src=modules/beachcomber/example_test.go#Post.ToSearchableArray +// ToSearchableArray builds the document from the committed row. func (p *Post) ToSearchableArray(ctx context.Context, db *gorm.DB) (map[string]any, error) { return map[string]any{ "id": strconv.FormatUint(uint64(p.ID), 10), @@ -94,7 +100,10 @@ func (p *Post) ToSearchableArray(ctx context.Context, db *gorm.DB) (map[string]a "title": p.Title, }, nil } +``` +```go src=modules/beachcomber/example_test.go#Post.SearchIndexSchema +// SearchIndexSchema is the schema a missing index is created with. func (Post) SearchIndexSchema() map[string]any { return map[string]any{ "fields": []map[string]any{ @@ -106,40 +115,47 @@ func (Post) SearchIndexSchema() map[string]any { } ``` -The plugin imports the engine package for its side effect, builds the service at Boot and installs its kill-switch: - -```go -package acme - -import ( - "context" - - "git.golem15.com/golem15/summercms/modules/backpack" - "git.golem15.com/golem15/summercms/modules/beachcomber" - _ "git.golem15.com/golem15/summercms/modules/beachcomber/typesense" - "gorm.io/gorm" -) +The application imports the engine package (for example `beachcomber/typesense`) for its side effect. The plugin builds the service at Boot and installs its kill-switch: +```go src=modules/beachcomber/example_test.go#Plugin.Boot +// Boot builds the search service and installs its kill-switch. func (p *Plugin) Boot(app *backpack.App) error { svc, err := beachcomber.From(app) if err != nil { return err } - svc.SetGate(beachcomber.GateFunc(func(ctx context.Context, db *gorm.DB) bool { - return acmeSearchEnabled(ctx, db) // false on any read error - })) + installGate(svc) return nil } ``` -A search endpoint asks the engine for candidate ids: +```go src=modules/beachcomber/example_test.go#gate +svc.SetGate(beachcomber.GateFunc(func(ctx context.Context, db *gorm.DB) bool { + var enabled bool + err := db.WithContext(ctx).Raw(`SELECT search_enabled FROM acme_blog_settings WHERE id = 1`).Scan(&enabled).Error + return err == nil && enabled +})) +``` -```go -ids, err := svc.Engine().SearchIDs(ctx, svc.IndexName(&models.Post{}), beachcomber.Query{ +A search endpoint asks the engine for candidate ids and re-checks them in SQL: + +```go src=modules/beachcomber/example_test.go#search +ids, err := svc.Engine().SearchIDs(ctx, svc.IndexName(&Post{}), beachcomber.Query{ Q: term, QueryBy: []string{"title"}, FilterBy: "blog_id:=" + strconv.FormatUint(uint64(blogID), 10), }) +if err != nil { + return nil, err +} +// The ids are candidates from an index that may be stale or loosely +// filtered: re-check every one in SQL before exposing a row. +var posts []Post +err = db.WithContext(ctx). + Where("id IN ? AND blog_id = ? AND published", ids, blogID). + Order("id"). + Find(&posts).Error +return posts, err ``` ## API reference diff --git a/modules/beachcomber/example_test.go b/modules/beachcomber/example_test.go index 9cbf07d0..7cb35a13 100644 --- a/modules/beachcomber/example_test.go +++ b/modules/beachcomber/example_test.go @@ -42,6 +42,17 @@ func (p *Post) ToSearchableArray(ctx context.Context, db *gorm.DB) (map[string]a }, nil } +// SearchIndexSchema is the schema a missing index is created with. +func (Post) SearchIndexSchema() map[string]any { + return map[string]any{ + "fields": []map[string]any{ + {"name": "id", "type": "string"}, + {"name": "blog_id", "type": "int64"}, + {"name": "title", "type": "string"}, + }, + } +} + // memoryEngine is a toy engine: it matches Q against the title and ignores // FilterBy, so its answers are loose candidates, as a stale index's are. type memoryEngine struct { @@ -120,6 +131,19 @@ func ExampleFrom() { // true } +// Plugin is the acme.blog plugin. +type Plugin struct{} + +// Boot builds the search service and installs its kill-switch. +func (p *Plugin) Boot(app *backpack.App) error { + svc, err := beachcomber.From(app) + if err != nil { + return err + } + installGate(svc) + return nil +} + // installGate turns search sync on only while the blog's search setting is // on; a failed read counts as off. func installGate(svc *beachcomber.Service) { @@ -167,7 +191,10 @@ func TestDocsSearch(t *testing.T) { t.Fatal(err) } } - svc, err := beachcomber.From(app) + if err := (&Plugin{}).Boot(app); err != nil { + t.Fatal(err) + } + svc, err := beachcomber.From(app) // the service Boot built if err != nil { t.Fatal(err) } @@ -175,7 +202,6 @@ func TestDocsSearch(t *testing.T) { // test installs the toy engine directly, so the global engine list the // package's own tests check stays unchanged. beachcomber.DocsUseEngine(svc, memory) - installGate(svc) ctx := t.Context() indexed := func() int { memory.mu.Lock() @@ -255,4 +281,9 @@ func TestDocsDeclarations(t *testing.T) { if err != nil || doc["id"] != "5" || doc["blog_id"] != int64(7) { t.Fatalf("ToSearchableArray = %v, %v", doc, err) } + var _ beachcomber.IndexSchemaProvider = Post{} + fields, _ := p.SearchIndexSchema()["fields"].([]map[string]any) + if len(fields) != 3 || fields[0]["name"] != "id" { + t.Fatalf("SearchIndexSchema fields = %v", fields) + } } diff --git a/modules/boardwalk/README.md b/modules/boardwalk/README.md index c79906cd..a53a83e1 100644 --- a/modules/boardwalk/README.md +++ b/modules/boardwalk/README.md @@ -36,7 +36,7 @@ Use cases: ## Usage -```go +```go src=modules/boardwalk/example_test.go#mount notFoundAPI := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusNotFound) diff --git a/modules/boardwalk/example_test.go b/modules/boardwalk/example_test.go new file mode 100644 index 00000000..b6d0b302 --- /dev/null +++ b/modules/boardwalk/example_test.go @@ -0,0 +1,45 @@ +package boardwalk_test + +import ( + "fmt" + "net/http" + "net/http/httptest" + + "git.golem15.com/golem15/summercms/modules/boardwalk" +) + +// mountAdmin serves the embedded admin SPA under /backend; admin API paths +// it does not know answer JSON. +func mountAdmin(mux *http.ServeMux) error { + // docs:start mount + notFoundAPI := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":"not found"}`)) + }) + + spa, err := boardwalk.Handler("/backend", notFoundAPI) + if err != nil { + return err + } + mux.Handle("/backend/", spa) + // docs:end mount + return nil +} + +func ExampleHandler() { + mux := http.NewServeMux() + if err := mountAdmin(mux); err != nil { + fmt.Println(err) + return + } + for _, path := range []string{"/backend/", "/backend/posts/7", "/backend/api/missing"} { + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + fmt.Println(path, rec.Code, rec.Header().Get("Content-Type"), rec.Header().Get(boardwalk.BuildHeader) != "") + } + // Output: + // /backend/ 200 text/html; charset=utf-8 true + // /backend/posts/7 200 text/html; charset=utf-8 true + // /backend/api/missing 404 application/json true +} diff --git a/modules/bonfire/README.md b/modules/bonfire/README.md index 4ead38f3..b7a44450 100644 --- a/modules/bonfire/README.md +++ b/modules/bonfire/README.md @@ -53,18 +53,12 @@ Use cases: ## Usage -```go -package main +A command declares its arguments and flags and gets an injected console: -import ( - "context" - "os" - - "git.golem15.com/golem15/summercms/modules/bonfire" -) - -func main() { - importPosts := bonfire.Command{ +```go src=modules/bonfire/example_test.go#importPostsCommand +// importPostsCommand is the blog:import command of the acme binary. +func importPostsCommand() bonfire.Command { + return bonfire.Command{ Name: "blog:import", Description: "Import posts from a feed", Args: []bonfire.Arg{{Name: "url", Description: "Feed URL", Required: true}}, @@ -84,28 +78,43 @@ func main() { }) }, } +} +``` - args := os.Args[1:] +The binary's main function calls this with os.Args[1:], os.Stdout and os.Stderr and exits with the code it returns: + +```go src=modules/bonfire/example_test.go#acmeMain +// acmeMain is the body of the acme binary's main function, which calls +// os.Exit(acmeMain(os.Args[1:], os.Stdout, os.Stderr)). +func acmeMain(args []string, stdout, stderr io.Writer) int { g := bonfire.PeekGlobals(args) - root, err := bonfire.NewRoot("acme", []bonfire.Command{importPosts}, os.Stdout, + root, err := bonfire.NewRoot("acme", []bonfire.Command{importPostsCommand()}, stdout, bonfire.WithVersion(bonfire.BuildVersion())) if err != nil { - os.Exit(bonfire.Fail(os.Stderr, "acme", err, g)) + return bonfire.Fail(stderr, "acme", err, g) } - os.Exit(bonfire.Execute(context.Background(), root, args)) + return bonfire.Execute(context.Background(), root, args) } ``` Running a command in-process, with empty stdin so prompts take their defaults: -```go -catalog := bonfire.NewCatalog(commands) +```go src=modules/bonfire/example_test.go#ExampleCatalog_Has +ctx := context.Background() +catalog := bonfire.NewCatalog([]bonfire.Command{importPostsCommand()}) if catalog.Has("blog:import") { err := catalog.Call(ctx, "blog:import", []string{"--dry-run", "https://example.com/feed"}, os.Stdout) - if errors.Is(err, bonfire.ErrUnknownCommand) { - // not registered in this binary - } + fmt.Println(err) } +err := catalog.Call(ctx, "blog:export", nil, os.Stdout) +fmt.Println(errors.Is(err, bonfire.ErrUnknownCommand)) // not registered in this binary +// Output: +// [...] Importing https://example.com/feed +// Tag +// news +// ⚠ dry run: nothing written +// +// true ``` ## API reference diff --git a/modules/bonfire/example_test.go b/modules/bonfire/example_test.go index ee8c3b06..b1d7323b 100644 --- a/modules/bonfire/example_test.go +++ b/modules/bonfire/example_test.go @@ -2,7 +2,9 @@ package bonfire_test import ( "context" + "errors" "fmt" + "io" "os" "strings" @@ -160,3 +162,68 @@ func ExampleCheckDocs() { } // Output: blog:reindex: missing long help, examples, option --batch description } + +// importPostsCommand is the blog:import command of the acme binary. +func importPostsCommand() bonfire.Command { + return bonfire.Command{ + Name: "blog:import", + Description: "Import posts from a feed", + Args: []bonfire.Arg{{Name: "url", Description: "Feed URL", Required: true}}, + Flags: []bonfire.Flag{ + {Name: "dry-run", Description: "Report without writing", Bare: true}, + {Name: "tag", Description: "Tag to apply (repeatable)", Repeatable: true}, + }, + Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error { + url, _ := in.Argument("url") + dryRun := bonfire.FlagBool(in, "dry-run") + return out.Spinner("Importing "+url, func() error { + out.Table([]string{"Tag"}, [][]string{{"news"}}) + if dryRun { + out.Warning("dry run: nothing written") + } + return nil + }) + }, + } +} + +// acmeMain is the body of the acme binary's main function, which calls +// os.Exit(acmeMain(os.Args[1:], os.Stdout, os.Stderr)). +func acmeMain(args []string, stdout, stderr io.Writer) int { + g := bonfire.PeekGlobals(args) + root, err := bonfire.NewRoot("acme", []bonfire.Command{importPostsCommand()}, stdout, + bonfire.WithVersion(bonfire.BuildVersion())) + if err != nil { + return bonfire.Fail(stderr, "acme", err, g) + } + return bonfire.Execute(context.Background(), root, args) +} + +func ExampleExecute() { + code := acmeMain([]string{"blog:import", "--dry-run", "https://example.com/feed"}, os.Stdout, os.Stdout) + fmt.Println("exit code:", code) + // Output: + // [...] Importing https://example.com/feed + // Tag + // news + // ⚠ dry run: nothing written + // exit code: 0 +} + +func ExampleCatalog_Has() { + ctx := context.Background() + catalog := bonfire.NewCatalog([]bonfire.Command{importPostsCommand()}) + if catalog.Has("blog:import") { + err := catalog.Call(ctx, "blog:import", []string{"--dry-run", "https://example.com/feed"}, os.Stdout) + fmt.Println(err) + } + err := catalog.Call(ctx, "blog:export", nil, os.Stdout) + fmt.Println(errors.Is(err, bonfire.ErrUnknownCommand)) // not registered in this binary + // Output: + // [...] Importing https://example.com/feed + // Tag + // news + // ⚠ dry run: nothing written + // + // true +} diff --git a/modules/bouncer/README.md b/modules/bouncer/README.md index e7653da3..259c2253 100644 --- a/modules/bouncer/README.md +++ b/modules/bouncer/README.md @@ -39,64 +39,56 @@ Use cases: ## Usage -```go -package blog - -import ( - "context" - "fmt" - "net/http" - "time" - - "git.golem15.com/golem15/summercms/modules/bouncer" -) - +```go src=modules/bouncer/example_test.go#users +// users loads the principal behind a token subject. type users struct{} +``` +```go src=modules/bouncer/example_test.go#users.FindByID // FindByID loads the user behind a token subject; nil means "not found". func (users) FindByID(ctx context.Context, id uint) (*bouncer.Principal, error) { - return &bouncer.Principal{ID: id, PreferredLocale: "en"}, nil + return &bouncer.Principal{ID: id, PreferredLocale: "pl"}, nil } +``` -func Routes(secret string) (http.Handler, error) { - guards := bouncer.NewRegistry() - guard := bouncer.NewJWTGuard(secret, users{}, bouncer.NewMemoryBlacklist(), "token") - if err := guards.Register("acme.blog", "jwt", guard); err != nil { - return nil, err - } - auth, err := guards.Middleware("jwt") - if err != nil { - return nil, err - } - - mux := http.NewServeMux() - mux.Handle("GET /api/me", auth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - user, _ := bouncer.User(r.Context()) - fmt.Fprintf(w, "user %d", user.ID) - }))) - return mux, nil +```go src=modules/bouncer/example_test.go#ExampleNewJWTGuard +guards := bouncer.NewRegistry() +guard := bouncer.NewJWTGuard(testSecret, users{}, bouncer.NewMemoryBlacklist(), "token") +if err := guards.Register("acme.blog", "acme.auth", guard); err != nil { + fmt.Println(err) + return } - -func Login(secret string) (string, error) { - token, _, err := bouncer.Mint(secret, "42", "https://example.com/api/login", time.Hour) - return token, err +auth, err := guards.Middleware("acme.auth") +if err != nil { + fmt.Println(err) + return } +me := auth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, _ := bouncer.User(r.Context()) + fmt.Fprintf(w, "user %d, locale %s", user.ID, user.PreferredLocale) +})) + +token, _, _ := bouncer.Mint(testSecret, "42", "http://127.0.0.1:8080/api/login", time.Hour) +for _, set := range []func(*http.Request){ + func(r *http.Request) {}, + func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) }, + func(r *http.Request) { r.AddCookie(&http.Cookie{Name: "token", Value: token}) }, +} { + req := httptest.NewRequest("GET", "/api/me", nil) + set(req) + rec := httptest.NewRecorder() + me.ServeHTTP(rec, req) + fmt.Println(rec.Code, strings.TrimSpace(rec.Body.String())) +} +// Output: +// 401 {"error":true,"message":"Token not provided"} +// 200 user 42, locale pl +// 200 user 42, locale pl ``` An application that keeps the token in an httpOnly cookie, for a frontend on `www.example.com` calling the API on `api.example.com`, loads the cookie config at boot and mounts the refresh handler on a POST route: -```go -package acme - -import ( - "context" - "encoding/json" - "net/http" - "time" - - "git.golem15.com/golem15/summercms/modules/bouncer" -) - +```go src=modules/bouncer/example_test.go#RefreshRoute // RefreshRoute rotates the cookie's token. cfg is the app config // (app.Config); users, secret and bl are the guard's; refreshTTL is its // refresh_ttl. diff --git a/modules/bouncer/example_test.go b/modules/bouncer/example_test.go index d65a02eb..945a5843 100644 --- a/modules/bouncer/example_test.go +++ b/modules/bouncer/example_test.go @@ -2,13 +2,16 @@ package bouncer_test import ( "context" + "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" + "testing" "time" "git.golem15.com/golem15/summercms/modules/bouncer" + "git.golem15.com/golem15/summercms/modules/compass" ) // testSecret is a test-only signing secret. A real application reads its @@ -49,6 +52,7 @@ func ExampleMint() { // users loads the principal behind a token subject. type users struct{} +// FindByID loads the user behind a token subject; nil means "not found". func (users) FindByID(ctx context.Context, id uint) (*bouncer.Principal, error) { return &bouncer.Principal{ID: id, PreferredLocale: "pl"}, nil } @@ -103,3 +107,89 @@ func ExampleHashPassword() { // false // true } + +// RefreshRoute rotates the cookie's token. cfg is the app config +// (app.Config); users, secret and bl are the guard's; refreshTTL is its +// refresh_ttl. +func RefreshRoute(cfg bouncer.CookieConfigSource, users bouncer.UserProvider, secret string, bl bouncer.BlacklistStore, refreshTTL time.Duration) (http.Handler, error) { + cookie, err := bouncer.LoadCookieConfig(cfg) // a bad auth.cookie block fails boot + if err != nil { + return nil, err + } + return bouncer.CookieRefreshHandler(bouncer.CookieRefreshOptions{ + Cookie: cookie, + RefreshTTL: refreshTTL, + Refresh: func(ctx context.Context, token string) (string, error) { + return bouncer.RefreshAudienceFor(ctx, users, secret, token, bouncer.AudienceUser, refreshTTL, bl, 0, "https://api.example.com/api/auth/refresh") + }, + Write: func(w http.ResponseWriter, r *http.Request, res bouncer.CookieResult) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(res.Status) + if res.Err != nil { + _ = json.NewEncoder(w).Encode(map[string]any{"success": false, "error": "UNAUTHENTICATED"}) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true}) + }, + }) +} + +// TestDocsRefreshRoute runs RefreshRoute on a production config for a +// frontend on www.example.com and an API on api.example.com: the cookie +// rotates once, and the replaced token is refused. +func TestDocsRefreshRoute(t *testing.T) { + cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Env: "production", Environ: []string{}}) + if err != nil { + t.Fatal(err) + } + for k, v := range map[string]any{"app.url": "https://api.example.com", "auth.cookie.domain": "example.com"} { + if err := cfg.Set(k, v); err != nil { + t.Fatal(err) + } + } + refreshTTL := 14 * 24 * time.Hour + h, err := RefreshRoute(cfg, users{}, testSecret, bouncer.NewMemoryBlacklist(), refreshTTL) + if err != nil { + t.Fatal(err) + } + token, _, err := bouncer.Mint(testSecret, "42", "https://api.example.com/api/auth/login", time.Hour) + if err != nil { + t.Fatal(err) + } + refresh := func(token string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "https://api.example.com/api/auth/refresh", nil) + req.AddCookie(&http.Cookie{Name: bouncer.DefaultCookieName, Value: token}) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec + } + + rec := refresh(token) + if rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != `{"success":true}` { + t.Fatalf("refresh = %d %s", rec.Code, rec.Body) + } + cookies := rec.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("cookies = %v", cookies) + } + c := cookies[0] + if c.Name != bouncer.DefaultCookieName || c.Value == "" || c.Value == token || c.Domain != "example.com" || + !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.MaxAge != int(refreshTTL.Seconds()) { + t.Fatalf("cookie = %+v", c) + } + + // The old token was blacklisted by the rotation. + if rec := refresh(token); rec.Code != http.StatusUnauthorized || + strings.TrimSpace(rec.Body.String()) != `{"error":"UNAUTHENTICATED","success":false}` || len(rec.Result().Cookies()) != 0 { + t.Fatalf("second refresh = %d %s %v", rec.Code, rec.Body, rec.Result().Cookies()) + } +} + +// TestDocsDeclarations checks the user provider the README shows. +func TestDocsDeclarations(t *testing.T) { + var _ bouncer.UserProvider = users{} + user, err := users{}.FindByID(t.Context(), 42) + if err != nil || user == nil || user.ID != 42 || user.PreferredLocale != "pl" { + t.Fatalf("FindByID = %+v, %v", user, err) + } +}