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
This commit is contained in:
Jakub Zych
2026-11-18 19:39:50 +01:00
parent 48527e4206
commit a0f5b5e561
9 changed files with 366 additions and 125 deletions

View File

@@ -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)
}
}