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:
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user