Files
summercms/modules/bouncer/example_test.go
Jakub Zych a0f5b5e561 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
2026-11-18 19:39:50 +01:00

196 lines
6.7 KiB
Go

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
// secret from configuration and never commits it.
const testSecret = "test-only-secret-with-at-least-32-bytes"
func ExampleMint() {
const issuer = "http://127.0.0.1:8080/api/login"
token, _, err := bouncer.Mint(testSecret, "42", issuer, time.Hour)
if err != nil {
fmt.Println(err)
return
}
sub, iat, exp, _, err := bouncer.VerifyClaims(token, testSecret)
fmt.Println(sub, exp.Sub(iat), err)
// A frontend token never passes a backend check, and a wrong secret fails.
_, _, _, _, err = bouncer.VerifyClaimsAudience(token, testSecret, bouncer.AudienceBackend)
fmt.Println(err != nil)
_, err = bouncer.Verify(token, "another-secret-with-at-least-32-bytes")
fmt.Println(err != nil)
// Refresh reissues the token and blacklists the old jti after the grace.
bl := bouncer.NewMemoryBlacklist()
fresh, err := bouncer.Refresh(testSecret, token, 14*24*time.Hour, bl, 0, issuer)
fmt.Println(fresh != token, err)
_, _, _, jti, _ := bouncer.VerifyClaims(token, testSecret)
revoked, _ := bl.IsBlacklisted(context.Background(), jti)
fmt.Println(revoked)
// Output:
// 42 1h0m0s <nil>
// true
// true
// true <nil>
// true
}
// 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
}
func 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
}
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
}
func ExampleHashPassword() {
hash, err := bouncer.HashPassword(10, "correct horse battery staple")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bouncer.CheckPassword(hash, "correct horse battery staple"))
fmt.Println(bouncer.CheckPassword(hash, "wrong"))
// After raising the configured cost, rehash on the next successful login.
fmt.Println(bouncer.NeedsRehash(hash, 12))
// Output:
// true
// 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)
}
}