Add the consumer side, Scratchpad and Welcome
internal/consumer is the app side of Base's handoff, shared by every installed app: GET /auth/start, POST /auth/assertion (exact Base Origin) and GET /auth/finish, which matches the nonce, consumes the pending request and records the jti in one transaction before starting the session. Lifetimes: pending 600 s, inbox 120 s. Scratchpad is one shared note; Welcome is one page with a link back to Home. Both use the look package. An e2e suite runs Base and both apps together in process.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+2,393
−0
cmd/scratchpad/main.go+56 −0cmd/welcome/main.go+56 −0docs/copy-pending.md+23 −0internal/consumer/consumer.go+674 −0internal/consumer/consumer_test.go+636 −0internal/consumer/migrations/0001_consumer.sql+42 −0internal/e2e/handoff_test.go+385 −0internal/look/static/app.css+5 −0internal/scratchpad/README.md+25 −0internal/scratchpad/migrations/0001_notes.sql+7 −0internal/scratchpad/scratchpad.go+136 −0internal/scratchpad/scratchpad_test.go+248 −0internal/scratchpad/templates/notes.html+13 −0internal/welcome/templates/welcome.html+9 −0internal/welcome/welcome.go+78 −0
diff --git a/cmd/scratchpad/main.go b/cmd/scratchpad/main.go| new file mode 100644 |
| index 0000000..6147402 |
| --- /dev/null |
| +++ b/cmd/scratchpad/main.go |
| @@ -0,0 +1,56 @@ |
| +// Command scratchpad runs Scratchpad, an app Base installs. Base sets its four |
| +// BASE_APP_* variables at install time. |
| +package main |
| + |
| +import ( |
| + "context" |
| + "log/slog" |
| + "net/http" |
| + "os" |
| + |
| + "amadan.net/rastrillo/rastrillo" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + _ "amadan.net/rastrillo/rastrillo/locales/en" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/carlos/base/internal/consumer" |
| + "amadan.net/carlos/base/internal/scratchpad" |
| +) |
| + |
| +func main() { |
| + logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) |
| + if err := run(logger); err != nil { |
| + logger.Error("scratchpad failed to start", "err", err) |
| + os.Exit(1) |
| + } |
| +} |
| + |
| +// Returning to main lets the database close on failed construction too. |
| +func run(logger *slog.Logger) error { |
| + cfg, err := consumer.Load(os.Getenv) |
| + if err != nil { |
| + return err |
| + } |
| + opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: "scratchpad.db", Logger: logger}) |
| + if err != nil { |
| + return err |
| + } |
| + d, err := db.Open(opts.DBPath, logger) |
| + if err != nil { |
| + return err |
| + } |
| + defer d.Close() |
| + if _, err := migrate.Apply(context.Background(), d, scratchpad.BootSchema); err != nil { |
| + return err |
| + } |
| + handler, err := scratchpad.App(d, cfg, logger) |
| + if err != nil { |
| + return err |
| + } |
| + // rastrillo.Serve wants a *http.ServeMux; the chi router takes every path. |
| + mux := http.NewServeMux() |
| + mux.Handle("/", handler) |
| + opts.Mux = mux |
| + opts.DBPath = "" |
| + return rastrillo.Serve(opts) |
| +} |
diff --git a/cmd/welcome/main.go b/cmd/welcome/main.go| new file mode 100644 |
| index 0000000..db11bdf |
| --- /dev/null |
| +++ b/cmd/welcome/main.go |
| @@ -0,0 +1,56 @@ |
| +// Command welcome runs Welcome, an app Base installs. Base sets its four |
| +// BASE_APP_* variables at install time. |
| +package main |
| + |
| +import ( |
| + "context" |
| + "log/slog" |
| + "net/http" |
| + "os" |
| + |
| + "amadan.net/rastrillo/rastrillo" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + _ "amadan.net/rastrillo/rastrillo/locales/en" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/carlos/base/internal/consumer" |
| + "amadan.net/carlos/base/internal/welcome" |
| +) |
| + |
| +func main() { |
| + logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) |
| + if err := run(logger); err != nil { |
| + logger.Error("welcome failed to start", "err", err) |
| + os.Exit(1) |
| + } |
| +} |
| + |
| +// Returning to main lets the database close on failed construction too. |
| +func run(logger *slog.Logger) error { |
| + cfg, err := consumer.Load(os.Getenv) |
| + if err != nil { |
| + return err |
| + } |
| + opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: "welcome.db", Logger: logger}) |
| + if err != nil { |
| + return err |
| + } |
| + d, err := db.Open(opts.DBPath, logger) |
| + if err != nil { |
| + return err |
| + } |
| + defer d.Close() |
| + if _, err := migrate.Apply(context.Background(), d, welcome.BootSchema); err != nil { |
| + return err |
| + } |
| + handler, err := welcome.App(d, cfg, logger) |
| + if err != nil { |
| + return err |
| + } |
| + // rastrillo.Serve wants a *http.ServeMux; the chi router takes every path. |
| + mux := http.NewServeMux() |
| + mux.Handle("/", handler) |
| + opts.Mux = mux |
| + opts.DBPath = "" |
| + return rastrillo.Serve(opts) |
| +} |
diff --git a/docs/copy-pending.md b/docs/copy-pending.md| index 73c26a3..cab203f 100644 |
| --- a/docs/copy-pending.md |
| +++ b/docs/copy-pending.md |
| @@ -108,3 +108,26 @@ Handing a member to an installed app (`GET /authorize`): |
| | internal/issuer/issuer.go | Install lookup failed (503) | unavailable | |
| | internal/issuer/issuer.go | Signing or rendering failed (500) | something went wrong | |
| | internal/web/app.go | `/authorize` while BASE_ASSERTION_KEY is unset (503) | unavailable | |
| + |
| +Installed apps: the shared sign-in (`internal/consumer`), Scratchpad and Welcome: |
| + |
| +| File | Context | Text | |
| +|---|---|---| |
| +| internal/consumer/consumer.go | Sign-in from Base refused or failed (400, 403 or 503) | Unable to sign in. Start again. | |
| +| internal/consumer/consumer.go | Signed-out POST to an app page (403) | signed out | |
| +| internal/consumer/consumer.go | Person lookup failed (503) | unavailable | |
| +| internal/scratchpad/templates/notes.html | Scratchpad page, title | Scratchpad · {Base name} | |
| +| internal/scratchpad/templates/notes.html | Scratchpad page, heading and crumb | Scratchpad | |
| +| internal/scratchpad/templates/notes.html | Note field, label (screen readers) | Shared note | |
| +| internal/scratchpad/templates/notes.html | Note button | Save | |
| +| internal/scratchpad/scratchpad.go | Note over 64 KiB (413) | The note is too long. | |
| +| internal/scratchpad/scratchpad.go | Note read or save failed (503) | unavailable | |
| +| internal/scratchpad/scratchpad.go | Page failed to render (500) | something went wrong | |
| +| internal/welcome/templates/welcome.html | Welcome page, title | Welcome · {Base name} | |
| +| internal/welcome/templates/welcome.html | Welcome page, crumb | Welcome | |
| +| internal/welcome/templates/welcome.html | Welcome page, heading | Welcome, {name} | |
| +| internal/welcome/templates/welcome.html | Welcome page, lead | This is {Base name} on Base. Your team's apps are on Home. | |
| +| internal/welcome/templates/welcome.html | Link back to Base | Back to Home | |
| +| internal/welcome/welcome.go | Page failed to render (500) | something went wrong | |
| + |
| +"Signed in as {name}, {Base name}" on Scratchpad is the spec's own wording (5.8). When Base has no name for a person, their email stands in for {name}. |
diff --git a/internal/consumer/consumer.go b/internal/consumer/consumer.go| new file mode 100644 |
| index 0000000..52eb6e2 |
| --- /dev/null |
| +++ b/internal/consumer/consumer.go |
| @@ -0,0 +1,674 @@ |
| +// Package consumer is the side of Base's sign-in handoff that every app Base |
| +// installs shares. It accepts Base's identity assertion and starts the app's |
| +// own session. |
| +// |
| +// The exchange has three steps, all on the app's own origin: |
| +// |
| +// 1. GET /auth/start sets a pending cookie holding a random secret, records |
| +// a fresh nonce against that secret, and sends the browser to Base's |
| +// /authorize with the nonce. |
| +// 2. Base answers with a form that posts the signed assertion to |
| +// POST /auth/assertion. That request comes from Base's page, so it may |
| +// carry no cookies of ours. It must carry Base's exact Origin. The |
| +// assertion is verified, held in an inbox under a second random cookie, |
| +// and the browser is sent on with a same-origin 303. |
| +// 3. GET /auth/finish arrives with both cookies. The assertion's nonce must |
| +// match the one recorded for this browser's pending request, and in one |
| +// transaction the pending request and inbox entry are consumed and the |
| +// assertion's ID is recorded so it can never be used again. Only then is |
| +// the session started. |
| +// |
| +// An assertion says who the person is. It grants nothing: each app decides |
| +// what that person may do. |
| +package consumer |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "database/sql" |
| + "embed" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "math" |
| + "mime" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "github.com/go-chi/chi/v5" |
| + |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// The handoff's routes. |
| +const ( |
| + StartPath = "/auth/start" |
| + AssertionPath = "/auth/assertion" |
| + FinishPath = "/auth/finish" |
| +) |
| + |
| +const ( |
| + pendingCookie = "__Host-base-pending" |
| + inboxCookie = "__Host-base-inbox" |
| + |
| + // A sign-in can take several minutes when Base must email a link. |
| + pendingLifetime = int64(600) |
| + // The inbox never needs to outlive the assertion it holds. |
| + inboxLifetime = int64(120) |
| + // How far the clock may step back. Replay rows are kept this long past |
| + // their expiry, so a clock moved back cannot make a used assertion valid. |
| + clockTolerance = int64(30) |
| + // Bounds what unauthenticated requests can make the tables hold. |
| + rowLimit = 10000 |
| + |
| + // sessionMethod marks sessions this package started. |
| + sessionMethod = "base" |
| +) |
| + |
| +var ( |
| + errRefused = errors.New("consumer: refused") |
| + errStorage = errors.New("consumer: storage") |
| + errClock = errors.New("consumer: clock") |
| + errFull = errors.New("consumer: capacity") |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrationFS embed.FS |
| + |
| +// Schema is the handoff's tables. Apply it with sessions.Schema before Mount. |
| +var Schema = migrate.MustFromFS(migrationFS, "consumer") |
| + |
| +// Config is what an installed app knows about the Base that installed it. |
| +type Config struct { |
| + Origin string // BASE_APP_ORIGIN: this app's own origin, the assertions' audience |
| + Issuer string // BASE_APP_ISSUER: Base's origin |
| + ConsumerID string // BASE_APP_CONSUMER_ID: this app's id in Base's catalogue |
| + Verifier *assertion.Verifier |
| + |
| + now func() time.Time // tests only; time.Now when nil |
| +} |
| + |
| +// Load reads the four BASE_APP_* variables Base writes at install time and |
| +// builds the verifier. getenv is os.Getenv in production. BASE_APP_KEYS is |
| +// the base64 of a JSON object mapping each key id to the base64 of its |
| +// 65-byte P-256 public key. |
| +func Load(getenv func(string) string) (Config, error) { |
| + get := func(k string) string { return strings.TrimSpace(getenv(k)) } |
| + cfg := Config{Origin: get("BASE_APP_ORIGIN"), Issuer: get("BASE_APP_ISSUER"), ConsumerID: get("BASE_APP_CONSUMER_ID")} |
| + raw := get("BASE_APP_KEYS") |
| + for _, v := range []struct{ name, value string }{ |
| + {"BASE_APP_ORIGIN", cfg.Origin}, {"BASE_APP_ISSUER", cfg.Issuer}, |
| + {"BASE_APP_CONSUMER_ID", cfg.ConsumerID}, {"BASE_APP_KEYS", raw}, |
| + } { |
| + if v.value == "" { |
| + return Config{}, fmt.Errorf("%s is required; Base sets it when it installs the app", v.name) |
| + } |
| + } |
| + if !consumerID(cfg.ConsumerID) { |
| + return Config{}, errors.New("BASE_APP_CONSUMER_ID must be 1 to 64 characters of a-z, A-Z, 0-9, _ and -") |
| + } |
| + doc, err := base64.StdEncoding.DecodeString(raw) |
| + if err != nil { |
| + return Config{}, errors.New("BASE_APP_KEYS is not base64") |
| + } |
| + var encoded map[string]string |
| + if err := json.Unmarshal(doc, &encoded); err != nil { |
| + return Config{}, errors.New("BASE_APP_KEYS is not a JSON object of key ids to keys") |
| + } |
| + keys := make(map[string][]byte, len(encoded)) |
| + for kid, b64 := range encoded { |
| + pub, err := base64.StdEncoding.DecodeString(b64) |
| + if err != nil || len(pub) != 65 { |
| + return Config{}, errors.New("BASE_APP_KEYS holds a key that is not the base64 of a 65-byte public key") |
| + } |
| + keys[kid] = pub |
| + } |
| + if cfg.Verifier, err = assertion.NewVerifier(cfg.Issuer, cfg.Origin, keys); err != nil { |
| + return Config{}, errors.New("BASE_APP_ORIGIN and BASE_APP_ISSUER must be different https origins (hostnames, no path), and BASE_APP_KEYS 1 to 8 valid keys") |
| + } |
| + return cfg, nil |
| +} |
| + |
| +func consumerID(s string) bool { |
| + if len(s) == 0 || len(s) > 64 { |
| + return false |
| + } |
| + for _, b := range []byte(s) { |
| + if !(b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || b == '_' || b == '-') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +type handoff struct { |
| + db *sql.DB |
| + cfg Config |
| + sess *sessions.Sessions |
| + host string |
| + logger *slog.Logger |
| +} |
| + |
| +// Mount adds the handoff to r: a middleware that puts the signed-in person |
| +// on every request, and the three routes. Call it before adding any route to |
| +// r (chi requires middleware first). db is the writer handle with Schema |
| +// applied; sess must be built for cfg.Origin on the same database. |
| +// |
| +// POST /auth/assertion arrives from Base's page, so the app's CSRF guard must |
| +// exempt it, as csrf.Protect(origin, csrf.Exempt(consumer.AssertionPath)) |
| +// does. That handler makes its own, stricter check: Origin must be exactly |
| +// Base's. |
| +// |
| +// Mount panics on a missing database, session store or verifier. |
| +func Mount(r chi.Router, db *sql.DB, cfg Config, sess *sessions.Sessions) { |
| + if db == nil || sess == nil || cfg.Verifier == nil { |
| + panic("consumer.Mount: needs a database, a session store and a Config from Load") |
| + } |
| + if cfg.now == nil { |
| + cfg.now = time.Now |
| + } |
| + h := &handoff{db: db, cfg: cfg, sess: sess, host: strings.TrimPrefix(cfg.Origin, "https://"), logger: slog.Default()} |
| + r.Use(h.identify) |
| + r.Get(StartPath, h.start) |
| + r.Post(AssertionPath, h.assertion) |
| + r.Get(FinishPath, h.finish) |
| +} |
| + |
| +type ctxKey struct{} |
| + |
| +// who is the signed-in person, as the request context carries them. |
| +type who struct { |
| + sub, name, base string |
| + broken bool // the lookup failed; Require answers 503 |
| +} |
| + |
| +// identify resolves the request's session and the person behind it. |
| +func (h *handoff) identify(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + s, ok := h.sess.FromContext(r.Context(), r) |
| + if !ok || s.Method != sessionMethod { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + r = sessions.WithSession(r, s) |
| + p, found, err := h.person(r.Context(), s.Subject) |
| + switch { |
| + case err != nil: |
| + h.logger.Error("consumer: person lookup", "err", err) |
| + r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, who{broken: true})) |
| + case found: |
| + r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)) |
| + } |
| + next.ServeHTTP(w, r) |
| + }) |
| +} |
| + |
| +func (h *handoff) person(ctx context.Context, sub string) (who, bool, error) { |
| + var p who |
| + var email string |
| + err := h.db.QueryRowContext(ctx, `SELECT subject, name, email, base FROM base_consumer_people WHERE subject = ?`, sub). |
| + Scan(&p.sub, &p.name, &email, &p.base) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return who{}, false, nil |
| + } |
| + if err != nil { |
| + return who{}, false, err |
| + } |
| + if p.name == "" { |
| + p.name = email |
| + } |
| + return p, true, nil |
| +} |
| + |
| +// Require lets through only a request with a signed-in person. A signed-out |
| +// page request goes to /auth/start with the page as return_to; anything |
| +// else gets 403. Signed-in responses are marked no-store. Use it on routes |
| +// of a router Mount was called on. |
| +func Require(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + p, ok := r.Context().Value(ctxKey{}).(who) |
| + switch { |
| + case ok && p.broken: |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + case ok: |
| + next.ServeHTTP(w, r) |
| + case r.Method == http.MethodGet || r.Method == http.MethodHead: |
| + to := r.URL.RequestURI() |
| + if !safePath(to) { |
| + to = "/" |
| + } |
| + http.Redirect(w, r, StartPath+"?return_to="+url.QueryEscape(to), http.StatusSeeOther) |
| + default: |
| + http.Error(w, "signed out", http.StatusForbidden) |
| + } |
| + }) |
| +} |
| + |
| +// Person is the signed-in person on a request that passed Require: Base's |
| +// member id, their name (their email when Base has no name for them) and |
| +// the Base's name. The name and Base name are for display only. |
| +func Person(r *http.Request) (sub, name, base string, ok bool) { |
| + p, ok := r.Context().Value(ctxKey{}).(who) |
| + if !ok || p.broken { |
| + return "", "", "", false |
| + } |
| + return p.sub, p.name, p.base, true |
| +} |
| + |
| +// guard refuses a request for another host: the cookies set here belong to |
| +// this origin only. |
| +func (h *handoff) guard(w http.ResponseWriter, r *http.Request) bool { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if r.Host != h.host { |
| + http.NotFound(w, r) |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +func (h *handoff) fail(w http.ResponseWriter, err error) { |
| + status := http.StatusBadRequest |
| + if errors.Is(err, errStorage) || errors.Is(err, errClock) || errors.Is(err, errFull) { |
| + status = http.StatusServiceUnavailable |
| + h.logger.Error("consumer: sign-in failed", "err", err) |
| + } |
| + http.Error(w, "Unable to sign in. Start again.", status) |
| +} |
| + |
| +// cookie returns the named cookie's value when the request carries exactly |
| +// one of that name and it has a handle's shape. |
| +func cookie(r *http.Request, name string) (string, bool) { |
| + value, count := "", 0 |
| + for _, c := range r.Cookies() { |
| + if c.Name == name { |
| + count++ |
| + value = c.Value |
| + } |
| + } |
| + return value, count == 1 && validHandle(value) |
| +} |
| + |
| +// setCookie writes a __Host- cookie: Secure, Path=/ and no Domain, as the |
| +// prefix requires. Lax, so the top-level GET to /auth/finish carries it. |
| +func setCookie(w http.ResponseWriter, name, value string, seconds int) { |
| + http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, |
| + Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| +} |
| + |
| +// start begins a sign-in for this browser and sends it to Base. |
| +func (h *handoff) start(w http.ResponseWriter, r *http.Request) { |
| + if !h.guard(w, r) { |
| + return |
| + } |
| + q, err := url.ParseQuery(r.URL.RawQuery) |
| + if err != nil || len(q) > 1 { |
| + h.fail(w, errRefused) |
| + return |
| + } |
| + to := "/" |
| + if len(q) == 1 { |
| + v, ok := q["return_to"] |
| + if !ok || len(v) != 1 { |
| + h.fail(w, errRefused) |
| + return |
| + } |
| + to = v[0] |
| + } |
| + if !safePath(to) { |
| + h.fail(w, errRefused) |
| + return |
| + } |
| + previous, _ := cookie(r, pendingCookie) |
| + secret, nonce, err := h.beginPending(r.Context(), to, previous, h.cfg.now()) |
| + if err != nil { |
| + h.fail(w, err) |
| + return |
| + } |
| + setCookie(w, pendingCookie, secret, int(pendingLifetime)) |
| + target := h.cfg.Issuer + "/authorize?" + url.Values{"consumer": {h.cfg.ConsumerID}, "nonce": {nonce}}.Encode() |
| + http.Redirect(w, r, target, http.StatusSeeOther) |
| +} |
| + |
| +// assertion receives Base's form post. It needs no cookie and must not rely |
| +// on one: the post comes from Base's page. |
| +func (h *handoff) assertion(w http.ResponseWriter, r *http.Request) { |
| + if !h.guard(w, r) { |
| + return |
| + } |
| + // Exactly Base's origin. A missing Origin or "null" is refused. |
| + if o := r.Header.Values("Origin"); len(o) != 1 || o[0] != h.cfg.Issuer { |
| + http.Error(w, "Unable to sign in. Start again.", http.StatusForbidden) |
| + return |
| + } |
| + if r.URL.RawQuery != "" { |
| + h.fail(w, errRefused) |
| + return |
| + } |
| + if media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || media != "application/x-www-form-urlencoded" { |
| + h.fail(w, errRefused) |
| + return |
| + } |
| + // A token is at most 8192 bytes; form encoding leaves it as is (it is |
| + // base64url and one dot), so 12 KiB bounds the body before any parsing. |
| + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024)) |
| + if err != nil { |
| + h.fail(w, errRefused) |
| + return |
| + } |
| + form, err := url.ParseQuery(string(body)) |
| + if err != nil || len(form) != 1 || len(form["assertion"]) != 1 { |
| + h.fail(w, errRefused) |
| + return |
| + } |
| + handle, err := h.receive(r.Context(), form["assertion"][0], h.cfg.now()) |
| + if err != nil { |
| + h.fail(w, err) |
| + return |
| + } |
| + setCookie(w, inboxCookie, handle, int(inboxLifetime)) |
| + // Same origin, relative: Base's CSP lets its form post only here, and a |
| + // redirect anywhere else would be refused. |
| + http.Redirect(w, r, FinishPath, http.StatusSeeOther) |
| +} |
| + |
| +// finish binds the held assertion to this browser's pending request and, once |
| +// its use is recorded, starts the session. |
| +func (h *handoff) finish(w http.ResponseWriter, r *http.Request) { |
| + if !h.guard(w, r) { |
| + return |
| + } |
| + secret, okSecret := cookie(r, pendingCookie) |
| + handle, okHandle := cookie(r, inboxCookie) |
| + // Both are single-use whatever happens next. |
| + setCookie(w, pendingCookie, "", -1) |
| + setCookie(w, inboxCookie, "", -1) |
| + if r.URL.RawQuery != "" || !okSecret || !okHandle { |
| + h.fail(w, errRefused) |
| + return |
| + } |
| + // Read before the transaction: the writer pool has one connection. |
| + existing := "" |
| + if s, ok := sessions.Current(r); ok { |
| + existing = s.Subject |
| + } |
| + claims, to, err := h.consume(r.Context(), secret, handle, existing, h.cfg.now()) |
| + if err != nil { |
| + h.fail(w, err) |
| + return |
| + } |
| + s := sessions.Session{Subject: claims.Subject, Method: sessionMethod, AuthTime: time.Unix(claims.AuthTime, 0)} |
| + if err := h.sess.SignIn(w, r, s); err != nil { |
| + h.fail(w, fmt.Errorf("%w: session: %v", errStorage, err)) |
| + return |
| + } |
| + h.logger.Info("signed in through Base", "subject", claims.Subject, "jti", claims.ID) |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
| + |
| +func digest(s string) string { sum := sha256.Sum256([]byte(s)); return hex.EncodeToString(sum[:]) } |
| + |
| +func jtiHash(c assertion.Claims) string { return digest(c.Issuer + "\x00" + c.ID) } |
| + |
| +func randomHandle() (string, error) { |
| + var b [32]byte |
| + if _, err := rand.Read(b[:]); err != nil { |
| + return "", errStorage |
| + } |
| + return base64.RawURLEncoding.EncodeToString(b[:]), nil |
| +} |
| + |
| +func validHandle(s string) bool { |
| + if len(s) != 43 { |
| + return false |
| + } |
| + b, err := base64.RawURLEncoding.Strict().DecodeString(s) |
| + return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == s |
| +} |
| + |
| +// safePath accepts only a local path on this origin, outside the sign-in |
| +// routes: one leading slash, no scheme or host, no backslash, control |
| +// character, space, fragment or dot segment. |
| +func safePath(s string) bool { |
| + if len(s) == 0 || len(s) > 2048 || !utf8.ValidString(s) || !strings.HasPrefix(s, "/") || strings.HasPrefix(s, "//") || strings.Contains(s, "#") { |
| + return false |
| + } |
| + for _, b := range []byte(s) { |
| + if b <= ' ' || b == 127 || b == '\\' { |
| + return false |
| + } |
| + } |
| + u, err := url.ParseRequestURI(s) |
| + if err != nil || u.IsAbs() || u.Host != "" || u.Opaque != "" { |
| + return false |
| + } |
| + p := u.Path |
| + if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") || strings.ContainsAny(p, "\\\x00\r\n\t") { |
| + return false |
| + } |
| + for _, part := range strings.Split(p, "/") { |
| + if part == "." || part == ".." { |
| + return false |
| + } |
| + } |
| + return p != "/auth" && !strings.HasPrefix(p, "/auth/") |
| +} |
| + |
| +// begin opens a transaction, moves the clock fence forward, and prunes what |
| +// has expired. It refuses a clock more than clockTolerance behind the fence. |
| +func (h *handoff) begin(ctx context.Context, now time.Time) (*sql.Tx, int64, error) { |
| + n := now.Unix() |
| + if n <= 0 || n > math.MaxInt64-pendingLifetime { |
| + return nil, 0, errClock |
| + } |
| + tx, err := h.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return nil, 0, errStorage |
| + } |
| + res, err := tx.ExecContext(ctx, `UPDATE base_consumer_clock SET observed = MAX(observed, ?) WHERE id = 1 AND observed <= ?`, n, n+clockTolerance) |
| + if err != nil { |
| + tx.Rollback() |
| + return nil, 0, errStorage |
| + } |
| + if rows, err := res.RowsAffected(); err != nil || rows != 1 { |
| + tx.Rollback() |
| + return nil, 0, errClock |
| + } |
| + var fence int64 |
| + if err := tx.QueryRowContext(ctx, `SELECT observed FROM base_consumer_clock WHERE id = 1`).Scan(&fence); err != nil { |
| + tx.Rollback() |
| + return nil, 0, errStorage |
| + } |
| + for _, q := range []struct { |
| + sql string |
| + at int64 |
| + }{ |
| + {`DELETE FROM base_consumer_pending WHERE expires_at <= ?`, n}, |
| + {`DELETE FROM base_consumer_inbox WHERE expires_at <= ?`, n}, |
| + {`DELETE FROM base_consumer_replay WHERE expires_at < ?`, fence - clockTolerance}, |
| + } { |
| + if _, err := tx.ExecContext(ctx, q.sql, q.at); err != nil { |
| + tx.Rollback() |
| + return nil, 0, errStorage |
| + } |
| + } |
| + return tx, n, nil |
| +} |
| + |
| +// beginPending records a new pending request, replacing this browser's |
| +// previous one. Only hashes of the secret and nonce are stored. |
| +func (h *handoff) beginPending(ctx context.Context, to, previous string, now time.Time) (secret, nonce string, err error) { |
| + if secret, err = randomHandle(); err != nil { |
| + return "", "", err |
| + } |
| + if nonce, err = assertion.RandomID(); err != nil { |
| + return "", "", errStorage |
| + } |
| + tx, n, err := h.begin(ctx, now) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + defer tx.Rollback() |
| + if validHandle(previous) { |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM base_consumer_pending WHERE secret_hash = ?`, digest(previous)); err != nil { |
| + return "", "", errStorage |
| + } |
| + } |
| + var count int |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM base_consumer_pending`).Scan(&count); err != nil { |
| + return "", "", errStorage |
| + } |
| + if count >= rowLimit { |
| + // Evicting the oldest only loses someone's navigation, never a proof. |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM base_consumer_pending WHERE secret_hash IN |
| + (SELECT secret_hash FROM base_consumer_pending ORDER BY created_at, secret_hash LIMIT ?)`, count-rowLimit+1); err != nil { |
| + return "", "", errStorage |
| + } |
| + } |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_pending (secret_hash, nonce_hash, return_to, created_at, expires_at) |
| + VALUES (?, ?, ?, ?, ?)`, digest(secret), digest(nonce), to, n, n+pendingLifetime); err != nil { |
| + return "", "", errStorage |
| + } |
| + if err := tx.Commit(); err != nil { |
| + return "", "", errStorage |
| + } |
| + return secret, nonce, nil |
| +} |
| + |
| +// receive verifies token and holds it in the inbox under a new handle. An |
| +// assertion already used, or already waiting, is refused. |
| +func (h *handoff) receive(ctx context.Context, token string, now time.Time) (string, error) { |
| + claims, err := h.cfg.Verifier.Verify(token, now) |
| + if err != nil { |
| + h.logger.Info("consumer: assertion refused", "err", err) |
| + return "", errRefused |
| + } |
| + handle, err := randomHandle() |
| + if err != nil { |
| + return "", err |
| + } |
| + jti := jtiHash(claims) |
| + tx, n, err := h.begin(ctx, now) |
| + if err != nil { |
| + return "", err |
| + } |
| + defer tx.Rollback() |
| + var used int |
| + if err := tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM base_consumer_replay WHERE jti_hash = ?) |
| + + (SELECT COUNT(*) FROM base_consumer_inbox WHERE jti_hash = ?)`, jti, jti).Scan(&used); err != nil { |
| + return "", errStorage |
| + } |
| + if used != 0 { |
| + h.logger.Warn("consumer: assertion replayed", "jti", claims.ID) |
| + return "", errRefused |
| + } |
| + var count int |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM base_consumer_inbox`).Scan(&count); err != nil { |
| + return "", errStorage |
| + } |
| + if count >= rowLimit { |
| + return "", errFull |
| + } |
| + expires := min(claims.ExpiresAt, n+inboxLifetime) |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_inbox (handle_hash, jti_hash, token, created_at, expires_at) |
| + VALUES (?, ?, ?, ?, ?)`, digest(handle), jti, token, n, expires); err != nil { |
| + return "", errStorage |
| + } |
| + if err := tx.Commit(); err != nil { |
| + return "", errStorage |
| + } |
| + return handle, nil |
| +} |
| + |
| +// consume checks the held assertion against the pending request and, in one |
| +// transaction, records its ID, deletes both rows and stores the person's |
| +// display fields. existing is the subject of a live session already on this |
| +// browser; an assertion for anyone else is refused rather than swapped in. |
| +func (h *handoff) consume(ctx context.Context, secret, handle, existing string, now time.Time) (assertion.Claims, string, error) { |
| + var zero assertion.Claims |
| + tx, n, err := h.begin(ctx, now) |
| + if err != nil { |
| + return zero, "", err |
| + } |
| + defer tx.Rollback() |
| + secretHash, handleHash := digest(secret), digest(handle) |
| + var nonceHash, to, token string |
| + if err := tx.QueryRowContext(ctx, `SELECT nonce_hash, return_to FROM base_consumer_pending WHERE secret_hash = ? AND expires_at > ?`, |
| + secretHash, n).Scan(&nonceHash, &to); err != nil { |
| + return zero, "", readError(err) |
| + } |
| + if err := tx.QueryRowContext(ctx, `SELECT token FROM base_consumer_inbox WHERE handle_hash = ? AND expires_at > ?`, |
| + handleHash, n).Scan(&token); err != nil { |
| + return zero, "", readError(err) |
| + } |
| + claims, err := h.cfg.Verifier.Verify(token, now) |
| + if err != nil { |
| + return zero, "", errRefused |
| + } |
| + if subtle.ConstantTimeCompare([]byte(nonceHash), []byte(digest(claims.Nonce))) != 1 { |
| + h.logger.Warn("consumer: assertion for another pending request", "jti", claims.ID) |
| + return zero, "", errRefused |
| + } |
| + if existing != "" && existing != claims.Subject { |
| + return zero, "", errRefused |
| + } |
| + if !safePath(to) { |
| + return zero, "", errRefused |
| + } |
| + res, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_replay (jti_hash, expires_at) VALUES (?, ?) ON CONFLICT DO NOTHING`, |
| + jtiHash(claims), claims.ExpiresAt) |
| + if err != nil { |
| + return zero, "", errStorage |
| + } |
| + if rows, err := res.RowsAffected(); err != nil { |
| + return zero, "", errStorage |
| + } else if rows != 1 { |
| + return zero, "", errRefused |
| + } |
| + for _, q := range []struct{ sql, key string }{ |
| + {`DELETE FROM base_consumer_pending WHERE secret_hash = ?`, secretHash}, |
| + {`DELETE FROM base_consumer_inbox WHERE handle_hash = ?`, handleHash}, |
| + } { |
| + res, err := tx.ExecContext(ctx, q.sql, q.key) |
| + if err != nil { |
| + return zero, "", errStorage |
| + } |
| + if rows, err := res.RowsAffected(); err != nil || rows != 1 { |
| + return zero, "", errStorage |
| + } |
| + } |
| + // Display only: Ext grants nothing, and a malformed one shows blanks. |
| + var ext struct { |
| + Name string `json:"name"` |
| + Email string `json:"email"` |
| + Base string `json:"base"` |
| + } |
| + _ = json.Unmarshal(claims.Ext, &ext) |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_people (subject, name, email, base, updated_at) VALUES (?, ?, ?, ?, ?) |
| + ON CONFLICT (subject) DO UPDATE SET name = excluded.name, email = excluded.email, base = excluded.base, updated_at = excluded.updated_at`, |
| + claims.Subject, ext.Name, ext.Email, ext.Base, n); err != nil { |
| + return zero, "", errStorage |
| + } |
| + if err := tx.Commit(); err != nil { |
| + return zero, "", errStorage |
| + } |
| + return claims, to, nil |
| +} |
| + |
| +func readError(err error) error { |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return errRefused |
| + } |
| + return errStorage |
| +} |
diff --git a/internal/consumer/consumer_test.go b/internal/consumer/consumer_test.go| new file mode 100644 |
| index 0000000..73430a1 |
| --- /dev/null |
| +++ b/internal/consumer/consumer_test.go |
| @@ -0,0 +1,636 @@ |
| +package consumer |
| + |
| +import ( |
| + "context" |
| + "crypto/tls" |
| + "encoding/base64" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "net" |
| + "net/http" |
| + "net/http/cookiejar" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/go-chi/chi/v5" |
| + |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/csrf" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/dbtest" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/install" |
| +) |
| + |
| +const ( |
| + issuerOrigin = "https://base.test" |
| + appOrigin = "https://acme-scratchpad.test" |
| + appID = "scratchpad" |
| +) |
| + |
| +var schema = dbtest.FromSet(migrate.Merge(sessions.Schema, Schema)) |
| + |
| +func TestMain(m *testing.M) { |
| + code := budget.Main(m) |
| + schema.Remove() |
| + os.Exit(code) |
| +} |
| + |
| +// clock is a settable time shared by the consumer and the session store. |
| +type clock struct { |
| + mu sync.Mutex |
| + t time.Time |
| +} |
| + |
| +func (c *clock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } |
| +func (c *clock) Add(d time.Duration) { c.mu.Lock(); defer c.mu.Unlock(); c.t = c.t.Add(d) } |
| + |
| +type testApp struct { |
| + t *testing.T |
| + key *crypto.Keypair |
| + kid string |
| + clock *clock |
| + addr string |
| +} |
| + |
| +// newApp serves a consumer over TLS, configured from exactly the variables |
| +// Base writes at install time, with one guarded page that prints Person. |
| +func newApp(t *testing.T) *testApp { |
| + t.Helper() |
| + key, err := crypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + vars := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, appID, appOrigin) |
| + cfg, err := Load(func(k string) string { return vars[k] }) |
| + if err != nil { |
| + t.Fatalf("Load: %v", err) |
| + } |
| + clk := &clock{t: time.Now()} |
| + cfg.now = clk.Now |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(schema.Path(t), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: appOrigin, SigninPath: StartPath, Logger: logger, Now: clk.Now}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r := chi.NewRouter() |
| + r.Use(csrf.Protect(appOrigin, csrf.Exempt(AssertionPath))) |
| + Mount(r, d.Writer(), cfg, sess) |
| + page := func(w http.ResponseWriter, r *http.Request) { |
| + sub, name, base, ok := Person(r) |
| + if !ok { |
| + http.Error(w, "no person", http.StatusInternalServerError) |
| + return |
| + } |
| + fmt.Fprintf(w, "Signed in as %s, %s (%s)", name, base, sub) |
| + } |
| + r.With(Require).Get("/", page) |
| + r.With(Require).Get("/notes", page) |
| + r.With(Require).Post("/", page) |
| + srv := httptest.NewTLSServer(r) // 127.0.0.1 only |
| + t.Cleanup(srv.Close) |
| + kid, _ := install.KeySet(key) |
| + return &testApp{t: t, key: key, kid: kid, clock: clk, addr: srv.Listener.Addr().String()} |
| +} |
| + |
| +type resp struct { |
| + Code int |
| + Header http.Header |
| + Body string |
| +} |
| + |
| +func (r resp) Location() string { return r.Header.Get("Location") } |
| + |
| +// cookie returns the Set-Cookie for name, if the response set one. |
| +func (r resp) cookie(name string) (*http.Cookie, bool) { |
| + for _, c := range (&http.Response{Header: r.Header}).Cookies() { |
| + if c.Name == name { |
| + return c, true |
| + } |
| + } |
| + return nil, false |
| +} |
| + |
| +// browser is one cookie jar talking to the app at appOrigin. |
| +type browser struct { |
| + a *testApp |
| + jar *cookiejar.Jar |
| + client *http.Client |
| +} |
| + |
| +func (a *testApp) browser() *browser { |
| + jar, _ := cookiejar.New(nil) |
| + tr := &http.Transport{ |
| + DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, network, a.addr) |
| + }, |
| + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test server's own certificate |
| + } |
| + a.t.Cleanup(tr.CloseIdleConnections) |
| + return &browser{a: a, jar: jar, client: &http.Client{Jar: jar, Transport: tr, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} |
| +} |
| + |
| +func (b *browser) do(req *http.Request) resp { |
| + b.a.t.Helper() |
| + res, err := b.client.Do(req) |
| + if err != nil { |
| + b.a.t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + raw, _ := io.ReadAll(res.Body) |
| + return resp{res.StatusCode, res.Header, string(raw)} |
| +} |
| + |
| +func (b *browser) get(path string) resp { |
| + b.a.t.Helper() |
| + req, _ := http.NewRequest(http.MethodGet, appOrigin+path, nil) |
| + return b.do(req) |
| +} |
| + |
| +// post sends a form with the given Origin headers (none if empty). |
| +func (b *browser) post(path string, form url.Values, origins ...string) resp { |
| + b.a.t.Helper() |
| + req, _ := http.NewRequest(http.MethodPost, appOrigin+path, strings.NewReader(form.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + for _, o := range origins { |
| + req.Header.Add("Origin", o) |
| + } |
| + return b.do(req) |
| +} |
| + |
| +// postAssertion is Base's handoff form arriving with Base's Origin. |
| +func (b *browser) postAssertion(token string) resp { |
| + b.a.t.Helper() |
| + return b.post(AssertionPath, url.Values{"assertion": {token}}, issuerOrigin) |
| +} |
| + |
| +// start begins a sign-in and returns the nonce the browser was sent to Base with. |
| +func (b *browser) start(returnTo string) string { |
| + b.a.t.Helper() |
| + r := b.get(StartPath + "?" + url.Values{"return_to": {returnTo}}.Encode()) |
| + if r.Code != http.StatusSeeOther { |
| + b.a.t.Fatalf("start: %d %s", r.Code, r.Body) |
| + } |
| + u, err := url.Parse(r.Location()) |
| + if err != nil || u.Scheme+"://"+u.Host != issuerOrigin || u.Path != "/authorize" { |
| + b.a.t.Fatalf("start redirected to %q", r.Location()) |
| + } |
| + q := u.Query() |
| + if len(q) != 2 || q.Get("consumer") != appID || len(q.Get("nonce")) != 22 { |
| + b.a.t.Fatalf("authorize query %q", u.RawQuery) |
| + } |
| + return q.Get("nonce") |
| +} |
| + |
| +type person struct{ sub, name, email, base string } |
| + |
| +var paul = person{"member-paul", "Paul", "paul@acme.test", "Acme Ltd"} |
| + |
| +// sign issues an assertion as Base would, at the app's current clock. |
| +// edit may change the claims before signing. |
| +func (a *testApp) sign(nonce string, p person, edit func(*assertion.Claims)) string { |
| + a.t.Helper() |
| + jti, err := assertion.RandomID() |
| + if err != nil { |
| + a.t.Fatal(err) |
| + } |
| + ext, _ := json.Marshal(map[string]string{"name": p.name, "email": p.email, "base": p.base}) |
| + iat := a.clock.Now().Unix() |
| + c := assertion.Claims{Version: 1, Issuer: issuerOrigin, Audience: appOrigin, Subject: p.sub, KeyID: a.kid, |
| + ID: jti, Nonce: nonce, IssuedAt: iat, ExpiresAt: iat + 120, AuthTime: iat, Ext: ext} |
| + if edit != nil { |
| + edit(&c) |
| + } |
| + token, err := assertion.Sign(a.key, c) |
| + if err != nil { |
| + a.t.Fatalf("sign: %v", err) |
| + } |
| + return token |
| +} |
| + |
| +// signIn runs the whole handoff for p and checks it lands on returnTo. |
| +func (b *browser) signIn(p person, returnTo string) { |
| + b.a.t.Helper() |
| + n := b.start(returnTo) |
| + if r := b.postAssertion(b.a.sign(n, p, nil)); r.Code != http.StatusSeeOther || r.Location() != FinishPath { |
| + b.a.t.Fatalf("assertion: %d %q %s", r.Code, r.Location(), r.Body) |
| + } |
| + if r := b.get(FinishPath); r.Code != http.StatusSeeOther || r.Location() != returnTo { |
| + b.a.t.Fatalf("finish: %d %q %s", r.Code, r.Location(), r.Body) |
| + } |
| +} |
| + |
| +// signedOut checks the browser has no session: the guarded page sends it to start. |
| +func (b *browser) signedOut() { |
| + b.a.t.Helper() |
| + if r := b.get("/"); r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Location(), StartPath) { |
| + b.a.t.Fatalf("want no session, got %d %q %s", r.Code, r.Location(), r.Body) |
| + } |
| +} |
| + |
| +func checkCookie(t *testing.T, r resp, name string, maxAge int) { |
| + t.Helper() |
| + c, ok := r.cookie(name) |
| + if !ok { |
| + t.Fatalf("no %s cookie set; headers %v", name, r.Header["Set-Cookie"]) |
| + } |
| + if !c.Secure || !c.HttpOnly || c.Path != "/" || c.Domain != "" || c.SameSite != http.SameSiteLaxMode || c.MaxAge != maxAge { |
| + t.Errorf("%s cookie: %+v", name, c) |
| + } |
| +} |
| + |
| +func TestHandoffSignsIn(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + if r := b.get("/notes?x=1"); r.Code != http.StatusSeeOther || r.Location() != StartPath+"?return_to=%2Fnotes%3Fx%3D1" { |
| + t.Fatalf("guarded page: %d %q", r.Code, r.Location()) |
| + } |
| + |
| + r := b.get(StartPath + "?return_to=%2Fnotes%3Fx%3D1") |
| + if r.Code != http.StatusSeeOther { |
| + t.Fatalf("start: %d %s", r.Code, r.Body) |
| + } |
| + checkCookie(t, r, "__Host-base-pending", 600) |
| + if got := r.Header.Get("Cache-Control"); got != "no-store" { |
| + t.Errorf("start Cache-Control %q", got) |
| + } |
| + u, _ := url.Parse(r.Location()) |
| + n := u.Query().Get("nonce") |
| + if c, _ := r.cookie("__Host-base-pending"); c != nil && strings.Contains(c.Value, n) { |
| + t.Errorf("the pending cookie carries the nonce itself; it must be an independent secret") |
| + } |
| + |
| + r = b.postAssertion(a.sign(n, paul, nil)) |
| + if r.Code != http.StatusSeeOther || r.Location() != FinishPath { |
| + t.Fatalf("assertion: %d %q %s", r.Code, r.Location(), r.Body) |
| + } |
| + checkCookie(t, r, "__Host-base-inbox", 120) |
| + |
| + r = b.get(FinishPath) |
| + if r.Code != http.StatusSeeOther || r.Location() != "/notes?x=1" { |
| + t.Fatalf("finish: %d %q %s", r.Code, r.Location(), r.Body) |
| + } |
| + checkCookie(t, r, "__Host-rastrillo_session", int((30 * 24 * time.Hour).Seconds())) |
| + for _, name := range []string{"__Host-base-pending", "__Host-base-inbox"} { |
| + if c, ok := r.cookie(name); !ok || c.MaxAge >= 0 { |
| + t.Errorf("finish did not clear %s: %+v", name, c) |
| + } |
| + } |
| + |
| + if r := b.get("/notes?x=1"); r.Code != 200 || r.Body != "Signed in as Paul, Acme Ltd (member-paul)" { |
| + t.Fatalf("signed-in page: %d %q", r.Code, r.Body) |
| + } |
| +} |
| + |
| +func TestAssertionReplayRefused(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + n := b.start("/") |
| + token := a.sign(n, paul, nil) |
| + // A second browser holding a copy of the same pending cookie, as a thief |
| + // who took both the cookie and the assertion would. |
| + thief := a.browser() |
| + u, _ := url.Parse(appOrigin) |
| + thief.jar.SetCookies(u, b.jar.Cookies(u)) |
| + |
| + if r := b.postAssertion(token); r.Code != http.StatusSeeOther { |
| + t.Fatalf("first post: %d %s", r.Code, r.Body) |
| + } |
| + if r := b.get(FinishPath); r.Code != http.StatusSeeOther { |
| + t.Fatalf("first finish: %d %s", r.Code, r.Body) |
| + } |
| + |
| + r := thief.postAssertion(token) |
| + if r.Code == http.StatusSeeOther { |
| + t.Fatalf("second post of the same assertion was accepted: %q", r.Location()) |
| + } |
| + if _, ok := r.cookie("__Host-base-inbox"); ok { |
| + t.Errorf("a refused assertion set an inbox cookie") |
| + } |
| + if r := thief.get(FinishPath); r.Code == http.StatusSeeOther { |
| + t.Fatalf("finish after replay: %q", r.Location()) |
| + } |
| + thief.signedOut() |
| + |
| + // The same browser posting it again gets nothing either. |
| + if r := b.postAssertion(token); r.Code == http.StatusSeeOther { |
| + t.Fatalf("same browser replay accepted") |
| + } |
| +} |
| + |
| +func TestAssertionReplayRefusedBeforeFinish(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + token := a.sign(b.start("/"), paul, nil) |
| + if r := b.postAssertion(token); r.Code != http.StatusSeeOther { |
| + t.Fatalf("first post: %d", r.Code) |
| + } |
| + // Still in the inbox, not yet finished: a second post is refused. |
| + if r := a.browser().postAssertion(token); r.Code == http.StatusSeeOther { |
| + t.Fatalf("second post while the first waits in the inbox was accepted") |
| + } |
| +} |
| + |
| +func TestAssertionExpiredRefused(t *testing.T) { |
| + t.Run("posted late", func(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + token := a.sign(b.start("/"), paul, nil) |
| + a.clock.Add(121 * time.Second) |
| + if r := b.postAssertion(token); r.Code == http.StatusSeeOther { |
| + t.Fatalf("expired assertion accepted") |
| + } |
| + b.get(FinishPath) |
| + b.signedOut() |
| + }) |
| + t.Run("finished late", func(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + token := a.sign(b.start("/"), paul, nil) |
| + a.clock.Add(60 * time.Second) |
| + if r := b.postAssertion(token); r.Code != http.StatusSeeOther { |
| + t.Fatalf("post within lifetime: %d %s", r.Code, r.Body) |
| + } |
| + a.clock.Add(61 * time.Second) // iat + 121 |
| + if r := b.get(FinishPath); r.Code == http.StatusSeeOther { |
| + t.Fatalf("finish after expiry accepted: %q", r.Location()) |
| + } |
| + b.signedOut() |
| + }) |
| + t.Run("pending expired", func(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + n := b.start("/") |
| + a.clock.Add(601 * time.Second) |
| + if r := b.postAssertion(a.sign(n, paul, nil)); r.Code != http.StatusSeeOther { |
| + t.Fatalf("post: %d", r.Code) |
| + } |
| + if r := b.get(FinishPath); r.Code == http.StatusSeeOther { |
| + t.Fatalf("finish after the pending request expired was accepted") |
| + } |
| + b.signedOut() |
| + }) |
| +} |
| + |
| +func TestAssertionWrongOriginRefused(t *testing.T) { |
| + a := newApp(t) |
| + for name, origins := range map[string][]string{ |
| + "other site": {"https://evil.test"}, |
| + "suffix": {"https://base.test.evil.test"}, |
| + "plain http": {"http://base.test"}, |
| + "trailing slash": {"https://base.test/"}, |
| + "null": {"null"}, |
| + "missing": nil, |
| + "the app itself": {appOrigin}, |
| + "two headers": {issuerOrigin, "https://evil.test"}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + b := a.browser() |
| + token := a.sign(b.start("/"), paul, nil) |
| + r := b.post(AssertionPath, url.Values{"assertion": {token}}, origins...) |
| + if r.Code != http.StatusForbidden { |
| + t.Fatalf("Origin %q: %d %q, want 403", origins, r.Code, r.Location()) |
| + } |
| + if _, ok := r.cookie("__Host-base-inbox"); ok { |
| + t.Errorf("refused post set an inbox cookie") |
| + } |
| + b.get(FinishPath) |
| + b.signedOut() |
| + }) |
| + } |
| +} |
| + |
| +func TestAssertionForAnotherAudienceRefused(t *testing.T) { |
| + a := newApp(t) |
| + for name, edit := range map[string]func(*assertion.Claims){ |
| + "another app": func(c *assertion.Claims) { c.Audience = "https://acme-welcome.test" }, |
| + "another issuer": func(c *assertion.Claims) { c.Issuer = "https://other-base.test" }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + b := a.browser() |
| + if r := b.postAssertion(a.sign(b.start("/"), paul, edit)); r.Code == http.StatusSeeOther { |
| + t.Fatalf("assertion accepted") |
| + } |
| + b.get(FinishPath) |
| + b.signedOut() |
| + }) |
| + } |
| + t.Run("another key", func(t *testing.T) { |
| + b := a.browser() |
| + other, _ := crypto.Generate() |
| + forged := &testApp{t: t, key: other, kid: a.kid, clock: a.clock} |
| + token := forged.sign(b.start("/"), paul, nil) |
| + if r := b.postAssertion(token); r.Code == http.StatusSeeOther { |
| + t.Fatalf("assertion signed by another key accepted") |
| + } |
| + }) |
| +} |
| + |
| +func TestNonceFromAnotherTabRefused(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + first := b.start("/") |
| + second := b.start("/") // a second tab replaces the first's pending request |
| + if first == second { |
| + t.Fatal("two starts gave one nonce") |
| + } |
| + if r := b.postAssertion(a.sign(first, paul, nil)); r.Code != http.StatusSeeOther { |
| + t.Fatalf("post: %d", r.Code) |
| + } |
| + if r := b.get(FinishPath); r.Code == http.StatusSeeOther { |
| + t.Fatalf("assertion for the replaced request finished: %q", r.Location()) |
| + } |
| + b.signedOut() |
| +} |
| + |
| +func TestLoginCSRFRefused(t *testing.T) { |
| + a := newApp(t) |
| + // The attacker gets an assertion for themselves in their own browser... |
| + attacker := a.browser() |
| + mallory := person{"member-mallory", "Mallory", "m@evil.test", "Evil"} |
| + token := a.sign(attacker.start("/"), mallory, nil) |
| + |
| + // ...and makes the victim's browser deliver it, with and without a |
| + // sign-in of the victim's own in flight. |
| + for _, pending := range []bool{false, true} { |
| + victim := a.browser() |
| + if pending { |
| + victim.start("/") |
| + } |
| + // Even with Base's Origin (the strongest an attacker could manage). |
| + if r := victim.postAssertion(token); r.Code != http.StatusSeeOther { |
| + continue // refused outright is fine too |
| + } |
| + if r := victim.get(FinishPath); r.Code == http.StatusSeeOther { |
| + t.Fatalf("victim (pending=%v) signed in as the attacker", pending) |
| + } |
| + victim.signedOut() |
| + } |
| +} |
| + |
| +func TestStartRefusesOffsiteReturn(t *testing.T) { |
| + a := newApp(t) |
| + for _, to := range []string{ |
| + "", "//evil.test/", "https://evil.test/", "/\\evil.test", "\\\\evil.test", "/\t/evil.test", |
| + "evil.test", "/a\r\nSet-Cookie: x=1", "/a#frag", "/auth/finish", "/auth/start?return_to=/", "/./auth/finish", |
| + "/%2e%2e/auth/finish", "javascript:alert(1)", |
| + } { |
| + b := a.browser() |
| + r := b.get(StartPath + "?" + url.Values{"return_to": {to}}.Encode()) |
| + if r.Code == http.StatusSeeOther { |
| + t.Errorf("return_to %q accepted, redirect %q", to, r.Location()) |
| + } |
| + if _, ok := r.cookie("__Host-base-pending"); ok { |
| + t.Errorf("return_to %q set a pending cookie", to) |
| + } |
| + } |
| + // Extra or repeated parameters are refused too. |
| + for _, q := range []string{"return_to=/&return_to=/x", "return_to=/&nonce=abc"} { |
| + if r := a.browser().get(StartPath + "?" + q); r.Code == http.StatusSeeOther { |
| + t.Errorf("start?%s accepted", q) |
| + } |
| + } |
| + // No return_to means Home. |
| + b := a.browser() |
| + r := b.get(StartPath) |
| + if r.Code != http.StatusSeeOther { |
| + t.Fatalf("bare start: %d", r.Code) |
| + } |
| +} |
| + |
| +func TestStartWithoutReturnLandsHome(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + r := b.get(StartPath) |
| + u, _ := url.Parse(r.Location()) |
| + b.postAssertion(a.sign(u.Query().Get("nonce"), paul, nil)) |
| + if r := b.get(FinishPath); r.Code != http.StatusSeeOther || r.Location() != "/" { |
| + t.Fatalf("finish: %d %q", r.Code, r.Location()) |
| + } |
| +} |
| + |
| +func TestRequire(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + if r := b.post("/", url.Values{}, appOrigin); r.Code != http.StatusForbidden { |
| + t.Errorf("signed-out POST: %d, want 403", r.Code) |
| + } |
| + b.signIn(paul, "/") |
| + if r := b.post("/", url.Values{}, appOrigin); r.Code != 200 { |
| + t.Errorf("signed-in POST: %d %s", r.Code, r.Body) |
| + } |
| +} |
| + |
| +func TestSecondPersonSeesThemselves(t *testing.T) { |
| + a := newApp(t) |
| + one, two := a.browser(), a.browser() |
| + one.signIn(paul, "/") |
| + ana := person{"member-ana", "", "ana@acme.test", "Acme Ltd"} |
| + two.signIn(ana, "/") |
| + if r := one.get("/"); r.Body != "Signed in as Paul, Acme Ltd (member-paul)" { |
| + t.Errorf("one: %q", r.Body) |
| + } |
| + // No name yet: the email stands in. |
| + if r := two.get("/"); r.Body != "Signed in as ana@acme.test, Acme Ltd (member-ana)" { |
| + t.Errorf("two: %q", r.Body) |
| + } |
| +} |
| + |
| +func TestFinishRefusesAnotherSubjectOverALiveSession(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + b.signIn(paul, "/") |
| + n := b.start("/") |
| + b.postAssertion(a.sign(n, person{"member-ana", "Ana", "ana@acme.test", "Acme Ltd"}, nil)) |
| + if r := b.get(FinishPath); r.Code == http.StatusSeeOther { |
| + t.Fatalf("a live session was swapped for another person") |
| + } |
| + if r := b.get("/"); r.Body != "Signed in as Paul, Acme Ltd (member-paul)" { |
| + t.Errorf("after refused swap: %d %q", r.Code, r.Body) |
| + } |
| +} |
| + |
| +func TestLoad(t *testing.T) { |
| + key, _ := crypto.Generate() |
| + good := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, appID, appOrigin) |
| + cfg, err := Load(func(k string) string { return good[k] }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cfg.Origin != appOrigin || cfg.Issuer != issuerOrigin || cfg.ConsumerID != appID || cfg.Verifier == nil { |
| + t.Errorf("cfg: %+v", cfg) |
| + } |
| + keysJSON := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } |
| + for name, change := range map[string][2]string{ |
| + "no origin": {"BASE_APP_ORIGIN", ""}, |
| + "http origin": {"BASE_APP_ORIGIN", "http://acme-scratchpad.test"}, |
| + "no issuer": {"BASE_APP_ISSUER", ""}, |
| + "issuer is origin": {"BASE_APP_ISSUER", appOrigin}, |
| + "no consumer": {"BASE_APP_CONSUMER_ID", ""}, |
| + "bad consumer": {"BASE_APP_CONSUMER_ID", "scratch pad"}, |
| + "no keys": {"BASE_APP_KEYS", ""}, |
| + "keys not base64": {"BASE_APP_KEYS", "!!"}, |
| + "keys not JSON": {"BASE_APP_KEYS", keysJSON("nope")}, |
| + "empty key set": {"BASE_APP_KEYS", keysJSON("{}")}, |
| + "key not base64": {"BASE_APP_KEYS", keysJSON(`{"abc":"!!"}`)}, |
| + "key wrong length": {"BASE_APP_KEYS", keysJSON(`{"abc":"AAAA"}`)}, |
| + "origin with path": {"BASE_APP_ORIGIN", appOrigin + "/x"}, |
| + "issuer with slash": {"BASE_APP_ISSUER", issuerOrigin + "/"}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + _, err := Load(func(k string) string { |
| + if k == change[0] { |
| + return change[1] |
| + } |
| + return good[k] |
| + }) |
| + if err == nil { |
| + t.Fatalf("Load accepted %s=%q", change[0], change[1]) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestClockSteppedBackRefused(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + b.start("/") |
| + a.clock.Add(-31 * time.Second) |
| + if r := b.get(StartPath); r.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("start with the clock 31 s behind: %d, want 503", r.Code) |
| + } |
| + a.clock.Add(2 * time.Second) // within the tolerance again |
| + if r := b.get(StartPath); r.Code != http.StatusSeeOther { |
| + t.Fatalf("start with the clock 29 s behind: %d", r.Code) |
| + } |
| +} |
| + |
| +func TestHandoffRefusesAnotherHost(t *testing.T) { |
| + a := newApp(t) |
| + b := a.browser() |
| + for _, path := range []string{StartPath, FinishPath} { |
| + req, _ := http.NewRequest(http.MethodGet, appOrigin+path, nil) |
| + req.Host = "acme-scratchpad.test.evil.test" |
| + if r := b.do(req); r.Code != http.StatusNotFound { |
| + t.Errorf("%s on another host: %d, want 404", path, r.Code) |
| + } |
| + } |
| +} |
diff --git a/internal/consumer/migrations/0001_consumer.sql b/internal/consumer/migrations/0001_consumer.sql| new file mode 100644 |
| index 0000000..cadb90b |
| --- /dev/null |
| +++ b/internal/consumer/migrations/0001_consumer.sql |
| @@ -0,0 +1,42 @@ |
| +-- clock is the highest time any exchange has seen. A clock that moves back |
| +-- more than 30 s refuses exchanges rather than reopening the replay window. |
| +CREATE TABLE base_consumer_clock ( |
| + id INTEGER PRIMARY KEY CHECK (id = 1), |
| + observed INTEGER NOT NULL |
| +); |
| +INSERT INTO base_consumer_clock (id, observed) VALUES (1, 0); |
| +-- pending is one browser's sign-in in flight: the hash of its cookie secret, |
| +-- the hash of the nonce sent to Base, and where to go afterwards. |
| +CREATE TABLE base_consumer_pending ( |
| + secret_hash TEXT PRIMARY KEY, |
| + nonce_hash TEXT NOT NULL UNIQUE, |
| + return_to TEXT NOT NULL, |
| + created_at INTEGER NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX base_consumer_pending_expiry ON base_consumer_pending (expires_at); |
| +-- inbox holds a verified assertion between the cross-site POST, which carries |
| +-- no cookies, and the same-origin finish, which does. |
| +CREATE TABLE base_consumer_inbox ( |
| + handle_hash TEXT PRIMARY KEY, |
| + jti_hash TEXT NOT NULL UNIQUE, |
| + token TEXT NOT NULL, |
| + created_at INTEGER NOT NULL, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX base_consumer_inbox_expiry ON base_consumer_inbox (expires_at); |
| +-- replay holds every assertion ID used to start a session, until it expires. |
| +CREATE TABLE base_consumer_replay ( |
| + jti_hash TEXT PRIMARY KEY, |
| + expires_at INTEGER NOT NULL |
| +); |
| +CREATE INDEX base_consumer_replay_expiry ON base_consumer_replay (expires_at); |
| +-- people holds the display fields from each person's latest assertion. They |
| +-- are for showing, never for deciding access. |
| +CREATE TABLE base_consumer_people ( |
| + subject TEXT PRIMARY KEY, |
| + name TEXT NOT NULL, |
| + email TEXT NOT NULL, |
| + base TEXT NOT NULL, |
| + updated_at INTEGER NOT NULL |
| +); |
diff --git a/internal/e2e/handoff_test.go b/internal/e2e/handoff_test.go| new file mode 100644 |
| index 0000000..32367be |
| --- /dev/null |
| +++ b/internal/e2e/handoff_test.go |
| @@ -0,0 +1,385 @@ |
| +// Package e2e runs Base and the apps it installs together, in process, the |
| +// way a browser meets them: one cookie jar, each app on its own origin. |
| +package e2e |
| + |
| +import ( |
| + "context" |
| + "crypto/tls" |
| + "html" |
| + "io" |
| + "log/slog" |
| + "net" |
| + "net/http" |
| + "net/http/cookiejar" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/dbtest" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/consumer" |
| + "amadan.net/carlos/base/internal/install" |
| + "amadan.net/carlos/base/internal/scratchpad" |
| + "amadan.net/carlos/base/internal/store" |
| + "amadan.net/carlos/base/internal/web" |
| + "amadan.net/carlos/base/internal/welcome" |
| +) |
| + |
| +const ( |
| + baseOrigin = "https://base.test" |
| + ownerAddress = "paul@acme.test" |
| +) |
| + |
| +var ( |
| + baseSchema = dbtest.FromSet(store.BootSchema) |
| + padSchema = dbtest.FromSet(scratchpad.BootSchema) |
| + welSchema = dbtest.FromSet(welcome.BootSchema) |
| +) |
| + |
| +func TestMain(m *testing.M) { |
| + code := budget.Main(m) |
| + baseSchema.Remove() |
| + padSchema.Remove() |
| + welSchema.Remove() |
| + os.Exit(code) |
| +} |
| + |
| +type mailbox struct { |
| + mu sync.Mutex |
| + last string |
| +} |
| + |
| +func (m *mailbox) Send(_ context.Context, _, _, body string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.last = body |
| + return nil |
| +} |
| + |
| +func (m *mailbox) body() string { m.mu.Lock(); defer m.mu.Unlock(); return m.last } |
| + |
| +type noInstaller struct{} |
| + |
| +func (noInstaller) Install(context.Context, string) error { return nil } |
| +func (noInstaller) Uninstall(context.Context, string) error { return nil } |
| + |
| +// swappable lets a test replace a running server's handler. |
| +type swappable struct{ h atomic.Pointer[http.Handler] } |
| + |
| +func (s *swappable) set(h http.Handler) { s.h.Store(&h) } |
| +func (s *swappable) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + (*s.h.Load()).ServeHTTP(w, r) |
| +} |
| + |
| +// world is Base plus installed apps, each behind TLS on its own test |
| +// server. The browser dials each origin's host to its server. |
| +type world struct { |
| + t *testing.T |
| + cfg config.Config |
| + base *swappable |
| + mail *mailbox |
| + addrs map[string]string // host -> listener address |
| + browser *http.Client |
| +} |
| + |
| +func newWorld(t *testing.T) *world { |
| + t.Helper() |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + key, err := crypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := config.Config{Origin: baseOrigin, Name: "Acme Ltd", Owner: ownerAddress, InstanceKey: "test-instance-key", |
| + AllowLoggedMail: true, Slug: "acme", AppsDomain: "test", Timezone: time.UTC, AssertionKey: key} |
| + d, err := db.Open(baseSchema.Path(t), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + ctx := context.Background() |
| + if err := store.Bootstrap(ctx, d.Writer(), ownerAddress); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec(`UPDATE members SET name = 'Paul'`); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := &world{t: t, cfg: cfg, base: &swappable{}, mail: &mailbox{}, addrs: map[string]string{}} |
| + h, err := web.App(d, cfg, w.mail, noInstaller{}, logger) |
| + if err != nil { |
| + t.Fatalf("web.App: %v", err) |
| + } |
| + w.base.set(h) |
| + w.serve("base.test", w.base) |
| + |
| + // Base's installs, seeded as the Installer would leave them. |
| + for _, app := range []string{"scratchpad", "welcome"} { |
| + _, host := install.HostFor(cfg, app) |
| + if _, err := store.ClaimInstall(ctx, d.Writer(), app, host); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := store.SetInstallState(ctx, d.Writer(), app, "installed", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + ccfg := w.appConfig(app, host) |
| + ad, err := db.Open(map[string]*dbtest.Template{"scratchpad": padSchema, "welcome": welSchema}[app].Path(t), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { ad.Close() }) |
| + var ah http.Handler |
| + if app == "scratchpad" { |
| + ah, err = scratchpad.App(ad, ccfg, logger) |
| + } else { |
| + ah, err = welcome.App(ad, ccfg, logger) |
| + } |
| + if err != nil { |
| + t.Fatalf("%s.App: %v", app, err) |
| + } |
| + w.serve(host, ah) |
| + } |
| + |
| + jar, _ := cookiejar.New(nil) |
| + tr := &http.Transport{ |
| + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + host, _, _ := net.SplitHostPort(addr) |
| + to, ok := w.addrs[host] |
| + if !ok { |
| + return nil, &net.AddrError{Err: "no test server", Addr: addr} |
| + } |
| + return (&net.Dialer{}).DialContext(ctx, network, to) |
| + }, |
| + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test servers' own certificate |
| + } |
| + t.Cleanup(tr.CloseIdleConnections) |
| + w.browser = &http.Client{Jar: jar, Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + return w |
| +} |
| + |
| +// appConfig is the app's configuration from exactly what Base writes at install. |
| +func (w *world) appConfig(app, host string) consumer.Config { |
| + w.t.Helper() |
| + vars := install.AppVars(w.cfg, app, "https://"+host) |
| + cfg, err := consumer.Load(func(k string) string { return vars[k] }) |
| + if err != nil { |
| + w.t.Fatalf("consumer.Load for %s: %v", app, err) |
| + } |
| + return cfg |
| +} |
| + |
| +func (w *world) serve(host string, h http.Handler) { |
| + srv := httptest.NewTLSServer(h) // 127.0.0.1 only |
| + w.t.Cleanup(srv.Close) |
| + w.addrs[host] = srv.Listener.Addr().String() |
| +} |
| + |
| +type resp struct { |
| + Code int |
| + Header http.Header |
| + Body string |
| +} |
| + |
| +func (r resp) Location() string { return r.Header.Get("Location") } |
| + |
| +// do sends one request. A form is posted with the Origin a browser would |
| +// send: the origin of the page the form was on. |
| +func (w *world) do(method, target string, form url.Values, origin string) resp { |
| + w.t.Helper() |
| + var body io.Reader |
| + if form != nil { |
| + body = strings.NewReader(form.Encode()) |
| + } |
| + req, err := http.NewRequest(method, target, body) |
| + if err != nil { |
| + w.t.Fatal(err) |
| + } |
| + if form != nil { |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", origin) |
| + } |
| + res, err := w.browser.Do(req) |
| + if err != nil { |
| + w.t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + raw, _ := io.ReadAll(res.Body) |
| + return resp{res.StatusCode, res.Header, string(raw)} |
| +} |
| + |
| +func (w *world) get(target string) resp { w.t.Helper(); return w.do(http.MethodGet, target, nil, "") } |
| + |
| +// follow GETs target and every same-method redirect after it, resolving |
| +// relative locations, and returns the last response and its URL. |
| +func (w *world) follow(target string) (resp, string) { |
| + w.t.Helper() |
| + for range 10 { |
| + r := w.get(target) |
| + if r.Code != http.StatusSeeOther && r.Code != http.StatusFound { |
| + return r, target |
| + } |
| + base, _ := url.Parse(target) |
| + next, err := base.Parse(r.Location()) |
| + if err != nil { |
| + w.t.Fatalf("bad redirect %q", r.Location()) |
| + } |
| + target = next.String() |
| + } |
| + w.t.Fatalf("too many redirects at %s", target) |
| + return resp{}, "" |
| +} |
| + |
| +var ( |
| + formRE = regexp.MustCompile(`(?s)<form[^>]*action="([^"]*)"[^>]*>(.*?)</form>`) |
| + inputRE = regexp.MustCompile(`<input[^>]*>`) |
| + attrRE = regexp.MustCompile(`(\w[\w-]*)="([^"]*)"`) |
| + linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`) |
| +) |
| + |
| +// form returns the action and named inputs of the first form whose action |
| +// satisfies match. |
| +func form(t *testing.T, body string, match func(string) bool) (string, url.Values) { |
| + t.Helper() |
| + for _, m := range formRE.FindAllStringSubmatch(body, -1) { |
| + action := html.UnescapeString(m[1]) |
| + if !match(action) { |
| + continue |
| + } |
| + v := url.Values{} |
| + for _, in := range inputRE.FindAllString(m[2], -1) { |
| + attrs := map[string]string{} |
| + for _, kv := range attrRE.FindAllStringSubmatch(in, -1) { |
| + attrs[kv[1]] = html.UnescapeString(kv[2]) |
| + } |
| + if attrs["name"] != "" { |
| + v.Set(attrs["name"], attrs["value"]) |
| + } |
| + } |
| + return action, v |
| + } |
| + t.Fatalf("no matching form in:\n%s", body) |
| + return "", nil |
| +} |
| + |
| +func is(want string) func(string) bool { return func(s string) bool { return s == want } } |
| + |
| +// signInToBase signs the browser in to Base with an emailed link (Ruling R3: |
| +// this suite's own helper, not webtest's). |
| +func (w *world) signInToBase(email string) { |
| + w.t.Helper() |
| + page := w.get(baseOrigin + "/signin?rec=1&force=1") |
| + _, v := form(w.t, page.Body, is("/auth/begin")) |
| + v.Set("address", email) |
| + if r := w.do(http.MethodPost, baseOrigin+"/auth/begin", v, baseOrigin); r.Code != http.StatusSeeOther { |
| + w.t.Fatalf("begin: %d %s", r.Code, r.Body) |
| + } |
| + link := linkRE.FindString(html.UnescapeString(w.mail.body())) |
| + if link == "" { |
| + w.t.Fatalf("no sign-in link in %q", w.mail.body()) |
| + } |
| + confirm := w.get(link) |
| + _, cv := form(w.t, confirm.Body, is("/auth/verify")) |
| + if r := w.do(http.MethodPost, baseOrigin+"/auth/verify", cv, baseOrigin); r.Code != http.StatusSeeOther || r.Location() != "/" { |
| + w.t.Fatalf("verify: %d %q", r.Code, r.Location()) |
| + } |
| +} |
| + |
| +// openApp opens an app as its Home tile does and goes through the handoff: |
| +// the app sends the browser to Base, Base answers with its handoff page, |
| +// and the browser submits that form to the app. It returns the app's page. |
| +func (w *world) openApp(origin string) resp { |
| + w.t.Helper() |
| + page, at := w.follow(origin + "/") |
| + if !strings.HasPrefix(at, baseOrigin+"/authorize?") || page.Code != 200 { |
| + w.t.Fatalf("opening %s ended at %s: %d\n%s", origin, at, page.Code, page.Body) |
| + } |
| + if got := page.Header.Get("Referrer-Policy"); got != "origin" { |
| + w.t.Fatalf("handoff Referrer-Policy %q", got) |
| + } |
| + action, v := form(w.t, page.Body, is(origin+consumer.AssertionPath)) |
| + // With Referrer-Policy: origin the browser sends Base's origin (R21). |
| + r := w.do(http.MethodPost, action, v, baseOrigin) |
| + if r.Code != http.StatusSeeOther || r.Location() != consumer.FinishPath { |
| + w.t.Fatalf("assertion post: %d %q %s", r.Code, r.Location(), r.Body) |
| + } |
| + final, at := w.follow(origin + r.Location()) |
| + if at != origin+"/" { |
| + w.t.Fatalf("handoff ended at %s", at) |
| + } |
| + return final |
| +} |
| + |
| +const padOrigin = "https://acme-scratchpad.test" |
| + |
| +func TestHandoffEndToEnd(t *testing.T) { |
| + w := newWorld(t) |
| + if _, host := install.HostFor(w.cfg, "scratchpad"); "https://"+host != padOrigin { |
| + t.Fatalf("Scratchpad's host is %s", host) |
| + } |
| + w.signInToBase(ownerAddress) |
| + |
| + // Home's tile links straight to the app's origin. |
| + home := w.get(baseOrigin + "/") |
| + if !strings.Contains(home.Body, `href="`+padOrigin+`/"`) { |
| + t.Fatalf("Home has no Scratchpad tile:\n%s", home.Body) |
| + } |
| + page := w.openApp(padOrigin) |
| + if page.Code != 200 || !strings.Contains(page.Body, "Signed in as Paul, Acme Ltd") { |
| + t.Fatalf("Scratchpad: %d\n%s", page.Code, page.Body) |
| + } |
| +} |
| + |
| +func TestSessionOutlivesBase(t *testing.T) { |
| + w := newWorld(t) |
| + w.signInToBase(ownerAddress) |
| + w.openApp(padOrigin) |
| + |
| + w.base.set(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { |
| + http.Error(rw, "down", http.StatusServiceUnavailable) |
| + })) |
| + if r := w.get(baseOrigin + "/"); r.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("Base still answers: %d", r.Code) |
| + } |
| + r := w.get(padOrigin + "/") |
| + if r.Code != 200 || !strings.Contains(r.Body, "Signed in as Paul, Acme Ltd") { |
| + t.Fatalf("Scratchpad with Base down: %d\n%s", r.Code, r.Body) |
| + } |
| +} |
| + |
| +func TestWelcomeEndToEnd(t *testing.T) { |
| + w := newWorld(t) |
| + w.signInToBase(ownerAddress) |
| + page := w.openApp("https://acme-welcome.test") |
| + if page.Code != 200 || !strings.Contains(page.Body, "Acme Ltd") || !strings.Contains(page.Body, "Paul") { |
| + t.Fatalf("Welcome: %d\n%s", page.Code, page.Body) |
| + } |
| + if !strings.Contains(page.Body, `href="`+baseOrigin+`/"`) { |
| + t.Errorf("Welcome has no link back to Home:\n%s", page.Body) |
| + } |
| +} |
| + |
| +func TestAssertionForOneAppRefusedByAnother(t *testing.T) { |
| + w := newWorld(t) |
| + w.signInToBase(ownerAddress) |
| + // Start a sign-in at Scratchpad, but take Welcome's assertion there. |
| + _, at := w.follow(padOrigin + "/") |
| + u, _ := url.Parse(at) |
| + n := u.Query().Get("nonce") |
| + page := w.get(baseOrigin + "/authorize?" + url.Values{"consumer": {"welcome"}, "nonce": {n}}.Encode()) |
| + _, v := form(t, page.Body, is("https://acme-welcome.test"+consumer.AssertionPath)) |
| + if r := w.do(http.MethodPost, padOrigin+consumer.AssertionPath, v, baseOrigin); r.Code == http.StatusSeeOther { |
| + t.Fatalf("Scratchpad took Welcome's assertion") |
| + } |
| + w.get(padOrigin + consumer.FinishPath) |
| + if r := w.get(padOrigin + "/"); r.Code == 200 { |
| + t.Fatalf("signed in to Scratchpad with Welcome's assertion") |
| + } |
| +} |
diff --git a/internal/look/static/app.css b/internal/look/static/app.css| index 42b38be..c3ae354 100644 |
| --- a/internal/look/static/app.css |
| +++ b/internal/look/static/app.css |
| @@ -157,3 +157,8 @@ button, input { font: inherit; } |
| a.app, a.me { color: inherit; text-decoration: none; } |
| a.btn { display: inline-flex; align-items: center; text-decoration: none; } |
| .ask:disabled { cursor: not-allowed; font: inherit; font-size: 14px; } |
| + |
| +/* Scratchpad's shared note: a field that grows past one control height. */ |
| +.notepad { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; } |
| +.notepad textarea.input { font: inherit; width: 100%; height: auto; min-height: 280px; padding: 12px 14px; |
| + line-height: 1.5; resize: vertical; } |
diff --git a/internal/scratchpad/README.md b/internal/scratchpad/README.md| new file mode 100644 |
| index 0000000..76c518f |
| --- /dev/null |
| +++ b/internal/scratchpad/README.md |
| @@ -0,0 +1,25 @@ |
| +# Scratchpad |
| + |
| +Scratchpad is the small app Base installs to prove that installing, signing |
| +in and uninstalling work. It has one page: a line saying who you're signed |
| +in as, and one note that everyone shares. |
| + |
| +## Who can use it |
| + |
| +Anyone the Base that installed it vouches for can read and change the note. |
| +Scratchpad trusts one Base, the one named in `BASE_APP_ISSUER`, and checks |
| +each sign-in against the keys in `BASE_APP_KEYS`. It has no roles: every |
| +member of that Base sees the same note and can change it. (CARLOS app spec |
| +1.7: Base says who someone is, and each app decides what they may do.) |
| + |
| +A sign-in lasts 12 hours, so people stay signed in while Base is briefly |
| +down, and someone removed from Base loses access within a day. |
| + |
| +## Settings |
| + |
| +Base writes all four when it installs the app: |
| + |
| +- `BASE_APP_ORIGIN`: Scratchpad's own address, such as `https://acme-scratchpad.example.com` |
| +- `BASE_APP_ISSUER`: Base's address |
| +- `BASE_APP_CONSUMER_ID`: `scratchpad` |
| +- `BASE_APP_KEYS`: Base's public keys, for checking sign-ins |
diff --git a/internal/scratchpad/migrations/0001_notes.sql b/internal/scratchpad/migrations/0001_notes.sql| new file mode 100644 |
| index 0000000..2088301 |
| --- /dev/null |
| +++ b/internal/scratchpad/migrations/0001_notes.sql |
| @@ -0,0 +1,7 @@ |
| +-- One shared note for everyone the configured Base vouches for. |
| +CREATE TABLE notes ( |
| + id INTEGER PRIMARY KEY CHECK (id = 1), |
| + body TEXT NOT NULL, |
| + updated_by TEXT NOT NULL, |
| + updated_at INTEGER NOT NULL |
| +); |
diff --git a/internal/scratchpad/scratchpad.go b/internal/scratchpad/scratchpad.go| new file mode 100644 |
| index 0000000..f8bf1f1 |
| --- /dev/null |
| +++ b/internal/scratchpad/scratchpad.go |
| @@ -0,0 +1,136 @@ |
| +// Package scratchpad is Scratchpad, the small app Base installs to prove |
| +// install, identity and uninstall: one shared note and a line saying who |
| +// you are signed in as. |
| +// |
| +// Access rule (CARLOS app spec 1.7: each app decides what a person may do): |
| +// anyone the configured Base vouches for may read and write the note. A |
| +// valid assertion from BASE_APP_ISSUER is the whole test; there are no |
| +// roles, and every member of that Base sees and edits the same note. |
| +package scratchpad |
| + |
| +import ( |
| + "database/sql" |
| + "embed" |
| + "errors" |
| + "io/fs" |
| + "log/slog" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/go-chi/chi/v5" |
| + |
| + "amadan.net/rastrillo/rastrillo/csrf" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + |
| + "amadan.net/carlos/base/internal/consumer" |
| + "amadan.net/carlos/base/internal/look" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrationFS embed.FS |
| + |
| +//go:embed templates/*.html |
| +var templateFS embed.FS |
| + |
| +// Schema is Scratchpad's own table. |
| +var Schema = migrate.MustFromFS(migrationFS, "scratchpad") |
| + |
| +// BootSchema is everything Scratchpad's database needs. |
| +var BootSchema = migrate.Merge(sessions.Schema, consumer.Schema, Schema) |
| + |
| +const ( |
| + // maxNote bounds the note, in bytes. |
| + maxNote = 64 * 1024 |
| + // sessionTTL is how long a sign-in lasts here. It outlives Base being |
| + // down for a while, and a person Base removes is gone within a day. |
| + sessionTTL = 12 * time.Hour |
| +) |
| + |
| +type app struct { |
| + db *sql.DB |
| + pages *look.Renderer |
| + logger *slog.Logger |
| +} |
| + |
| +// App builds Scratchpad's router. d must have BootSchema applied. |
| +func App(d *db.DB, cfg consumer.Config, logger *slog.Logger) (http.Handler, error) { |
| + if d == nil || cfg.Verifier == nil { |
| + return nil, errors.New("scratchpad: a database and a Config from consumer.Load are required") |
| + } |
| + if logger == nil { |
| + logger = slog.Default() |
| + } |
| + sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, TTL: sessionTTL, |
| + SigninPath: consumer.StartPath, Logger: logger}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + sub, err := fs.Sub(templateFS, "templates") |
| + if err != nil { |
| + return nil, err |
| + } |
| + pages, err := look.NewRenderer(sub, nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + a := &app{db: d.Writer(), pages: pages, logger: logger} |
| + |
| + r := chi.NewRouter() |
| + // Base's form posts the assertion cross-origin; that one handler checks |
| + // for Base's exact Origin itself. |
| + r.Use(csrf.Protect(cfg.Origin, csrf.Exempt(consumer.AssertionPath))) |
| + consumer.Mount(r, d.Writer(), cfg, sess) |
| + r.Get("/static/fonts/*", look.FontHandler().ServeHTTP) |
| + r.Get("/static/*", look.Assets.Handler().ServeHTTP) |
| + r.Group(func(r chi.Router) { |
| + r.Use(consumer.Require) |
| + r.Get("/", a.notes) |
| + r.Post("/", a.save) |
| + }) |
| + return r, nil |
| +} |
| + |
| +type notesPage struct { |
| + Name, Base, Note string |
| +} |
| + |
| +func (a *app) notes(w http.ResponseWriter, r *http.Request) { |
| + _, name, base, _ := consumer.Person(r) |
| + var note string |
| + err := a.db.QueryRowContext(r.Context(), `SELECT body FROM notes WHERE id = 1`).Scan(¬e) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + a.logger.Error("scratchpad: reading the note", "err", err) |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + return |
| + } |
| + if err := a.pages.Page(w, "notes", notesPage{Name: name, Base: base, Note: note}); err != nil { |
| + a.logger.Error("scratchpad: render", "err", err) |
| + http.Error(w, "something went wrong", http.StatusInternalServerError) |
| + } |
| +} |
| + |
| +// save replaces the shared note, then sends the browser back to it. |
| +func (a *app) save(w http.ResponseWriter, r *http.Request) { |
| + sub, _, _, _ := consumer.Person(r) |
| + r.Body = http.MaxBytesReader(w, r.Body, 4*maxNote) // form encoding can triple a byte |
| + if err := r.ParseForm(); err != nil { |
| + http.Error(w, "The note is too long.", http.StatusRequestEntityTooLarge) |
| + return |
| + } |
| + note := r.PostForm.Get("note") |
| + if len(note) > maxNote { |
| + http.Error(w, "The note is too long.", http.StatusRequestEntityTooLarge) |
| + return |
| + } |
| + _, err := a.db.ExecContext(r.Context(), `INSERT INTO notes (id, body, updated_by, updated_at) VALUES (1, ?, ?, ?) |
| + ON CONFLICT (id) DO UPDATE SET body = excluded.body, updated_by = excluded.updated_by, updated_at = excluded.updated_at`, |
| + note, sub, time.Now().Unix()) |
| + if err != nil { |
| + a.logger.Error("scratchpad: saving the note", "err", err) |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + return |
| + } |
| + http.Redirect(w, r, "/", http.StatusSeeOther) |
| +} |
diff --git a/internal/scratchpad/scratchpad_test.go b/internal/scratchpad/scratchpad_test.go| new file mode 100644 |
| index 0000000..04ae2b7 |
| --- /dev/null |
| +++ b/internal/scratchpad/scratchpad_test.go |
| @@ -0,0 +1,248 @@ |
| +package scratchpad_test |
| + |
| +import ( |
| + "context" |
| + "crypto/tls" |
| + "encoding/json" |
| + "html" |
| + "io" |
| + "log/slog" |
| + "net" |
| + "net/http" |
| + "net/http/cookiejar" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/dbtest" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/consumer" |
| + "amadan.net/carlos/base/internal/install" |
| + "amadan.net/carlos/base/internal/scratchpad" |
| +) |
| + |
| +const ( |
| + issuerOrigin = "https://base.test" |
| + appOrigin = "https://acme-scratchpad.test" |
| +) |
| + |
| +var schema = dbtest.FromSet(scratchpad.BootSchema) |
| + |
| +func TestMain(m *testing.M) { |
| + code := budget.Main(m) |
| + schema.Remove() |
| + os.Exit(code) |
| +} |
| + |
| +type pad struct { |
| + t *testing.T |
| + key *crypto.Keypair |
| + addr string |
| +} |
| + |
| +// newPad serves Scratchpad over TLS, configured as Base would install it. |
| +func newPad(t *testing.T) *pad { |
| + t.Helper() |
| + key, err := crypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + vars := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, "scratchpad", appOrigin) |
| + cfg, err := consumer.Load(func(k string) string { return vars[k] }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(schema.Path(t), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + h, err := scratchpad.App(d, cfg, logger) |
| + if err != nil { |
| + t.Fatalf("App: %v", err) |
| + } |
| + srv := httptest.NewTLSServer(h) // 127.0.0.1 only |
| + t.Cleanup(srv.Close) |
| + return &pad{t: t, key: key, addr: srv.Listener.Addr().String()} |
| +} |
| + |
| +type resp struct { |
| + Code int |
| + Header http.Header |
| + Body string |
| +} |
| + |
| +type browser struct { |
| + p *pad |
| + client *http.Client |
| +} |
| + |
| +func (p *pad) browser() *browser { |
| + jar, _ := cookiejar.New(nil) |
| + tr := &http.Transport{ |
| + DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, network, p.addr) |
| + }, |
| + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test server's own certificate |
| + } |
| + p.t.Cleanup(tr.CloseIdleConnections) |
| + return &browser{p: p, client: &http.Client{Jar: jar, Transport: tr, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} |
| +} |
| + |
| +func (b *browser) do(method, path string, form url.Values, origin string) resp { |
| + b.p.t.Helper() |
| + var body io.Reader |
| + if form != nil { |
| + body = strings.NewReader(form.Encode()) |
| + } |
| + req, _ := http.NewRequest(method, appOrigin+path, body) |
| + if form != nil { |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + } |
| + if origin != "" { |
| + req.Header.Set("Origin", origin) |
| + } |
| + res, err := b.client.Do(req) |
| + if err != nil { |
| + b.p.t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + raw, _ := io.ReadAll(res.Body) |
| + return resp{res.StatusCode, res.Header, string(raw)} |
| +} |
| + |
| +func (b *browser) get(path string) resp { b.p.t.Helper(); return b.do(http.MethodGet, path, nil, "") } |
| + |
| +// save posts the notepad form as Scratchpad's own page would. |
| +func (b *browser) save(note string) resp { |
| + b.p.t.Helper() |
| + return b.do(http.MethodPost, "/", url.Values{"note": {note}}, appOrigin) |
| +} |
| + |
| +// signIn runs the handoff with an assertion signed as Base would sign it. |
| +func (b *browser) signIn(sub, name, base string) { |
| + b.p.t.Helper() |
| + r := b.get("/") |
| + if r.Code != http.StatusSeeOther { |
| + b.p.t.Fatalf("signed-out page: %d", r.Code) |
| + } |
| + r = b.get(r.Header.Get("Location")) |
| + u, _ := url.Parse(r.Header.Get("Location")) |
| + if r.Code != http.StatusSeeOther || u.Host != "base.test" { |
| + b.p.t.Fatalf("start: %d %q", r.Code, r.Header.Get("Location")) |
| + } |
| + kid, _ := install.KeySet(b.p.key) |
| + jti, _ := assertion.RandomID() |
| + ext, _ := json.Marshal(map[string]string{"name": name, "email": sub + "@acme.test", "base": base}) |
| + now := time.Now().Unix() |
| + token, err := assertion.Sign(b.p.key, assertion.Claims{Version: 1, Issuer: issuerOrigin, Audience: appOrigin, |
| + Subject: sub, KeyID: kid, ID: jti, Nonce: u.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 120, AuthTime: now, Ext: ext}) |
| + if err != nil { |
| + b.p.t.Fatal(err) |
| + } |
| + if r := b.do(http.MethodPost, consumer.AssertionPath, url.Values{"assertion": {token}}, issuerOrigin); r.Code != http.StatusSeeOther { |
| + b.p.t.Fatalf("assertion: %d %s", r.Code, r.Body) |
| + } |
| + if r := b.get(consumer.FinishPath); r.Code != http.StatusSeeOther || r.Header.Get("Location") != "/" { |
| + b.p.t.Fatalf("finish: %d %q", r.Code, r.Header.Get("Location")) |
| + } |
| +} |
| + |
| +func TestNotesSharedAcrossMembers(t *testing.T) { |
| + p := newPad(t) |
| + paul, ana := p.browser(), p.browser() |
| + paul.signIn("member-paul", "Paul", "Acme Ltd") |
| + ana.signIn("member-ana", "Ana", "Acme Ltd") |
| + |
| + page := paul.get("/") |
| + if page.Code != 200 || !strings.Contains(page.Body, "Signed in as Paul, Acme Ltd") { |
| + t.Fatalf("Paul's page: %d\n%s", page.Code, page.Body) |
| + } |
| + if !strings.Contains(page.Body, `<textarea`) || !strings.Contains(page.Body, `name="note"`) || !strings.Contains(page.Body, `method="post"`) { |
| + t.Fatalf("no notepad form:\n%s", page.Body) |
| + } |
| + |
| + note := "Order more coffee <b>today</b> & tomorrow" |
| + if r := paul.save(note); r.Code != http.StatusSeeOther || r.Header.Get("Location") != "/" { |
| + t.Fatalf("save: %d %q %s", r.Code, r.Header.Get("Location"), r.Body) |
| + } |
| + page = ana.get("/") |
| + if page.Code != 200 || !strings.Contains(page.Body, "Signed in as Ana, Acme Ltd") { |
| + t.Fatalf("Ana's page: %d\n%s", page.Code, page.Body) |
| + } |
| + if !strings.Contains(page.Body, html.EscapeString(note)) { |
| + t.Fatalf("Ana does not see Paul's note:\n%s", page.Body) |
| + } |
| + if strings.Contains(page.Body, "<b>today</b>") { |
| + t.Errorf("the note is not escaped") |
| + } |
| + |
| + // Ana's edit replaces it for Paul too. |
| + if r := ana.save("Coffee ordered"); r.Code != http.StatusSeeOther { |
| + t.Fatalf("Ana's save: %d", r.Code) |
| + } |
| + if page := paul.get("/"); !strings.Contains(page.Body, "Coffee ordered") || strings.Contains(page.Body, "tomorrow") { |
| + t.Errorf("Paul's page after Ana's edit:\n%s", page.Body) |
| + } |
| +} |
| + |
| +func TestNotesNeedSignIn(t *testing.T) { |
| + p := newPad(t) |
| + b := p.browser() |
| + if r := b.get("/"); r.Code != http.StatusSeeOther || r.Header.Get("Location") != consumer.StartPath+"?return_to=%2F" { |
| + t.Fatalf("signed-out page: %d %q", r.Code, r.Header.Get("Location")) |
| + } |
| + if r := b.save("hello"); r.Code != http.StatusForbidden { |
| + t.Fatalf("signed-out save: %d", r.Code) |
| + } |
| +} |
| + |
| +func TestNotesRefuseCrossOriginSave(t *testing.T) { |
| + p := newPad(t) |
| + b := p.browser() |
| + b.signIn("member-paul", "Paul", "Acme Ltd") |
| + b.save("kept") |
| + for _, origin := range []string{"https://evil.test", issuerOrigin} { |
| + if r := b.do(http.MethodPost, "/", url.Values{"note": {"defaced"}}, origin); r.Code != http.StatusForbidden { |
| + t.Errorf("save from %s: %d, want 403", origin, r.Code) |
| + } |
| + } |
| + if page := b.get("/"); !strings.Contains(page.Body, "kept") || strings.Contains(page.Body, "defaced") { |
| + t.Errorf("note changed by a cross-origin post:\n%s", page.Body) |
| + } |
| +} |
| + |
| +func TestNotesRefuseOversizedNote(t *testing.T) { |
| + p := newPad(t) |
| + b := p.browser() |
| + b.signIn("member-paul", "Paul", "Acme Ltd") |
| + if r := b.save(strings.Repeat("x", 70*1024)); r.Code == http.StatusSeeOther { |
| + t.Fatalf("a 70 KiB note was saved") |
| + } |
| +} |
| + |
| +func TestScratchpadServesTheLook(t *testing.T) { |
| + p := newPad(t) |
| + b := p.browser() |
| + b.signIn("member-paul", "Paul", "Acme Ltd") |
| + page := b.get("/") |
| + i := strings.Index(page.Body, `href="/static/app.`) |
| + if i < 0 { |
| + t.Fatalf("no stylesheet link:\n%s", page.Body) |
| + } |
| + href := page.Body[i+len(`href="`):] |
| + href = href[:strings.Index(href, `"`)] |
| + if r := b.get(href); r.Code != 200 || !strings.Contains(r.Header.Get("Content-Type"), "css") { |
| + t.Errorf("stylesheet %s: %d %q", href, r.Code, r.Header.Get("Content-Type")) |
| + } |
| +} |
diff --git a/internal/scratchpad/templates/notes.html b/internal/scratchpad/templates/notes.html| new file mode 100644 |
| index 0000000..eb16b6d |
| --- /dev/null |
| +++ b/internal/scratchpad/templates/notes.html |
| @@ -0,0 +1,13 @@ |
| +{{define "title"}}Scratchpad · {{.Base}}{{end}} |
| +{{define "main"}}<main class="inner"> |
| +<div class="sheet glass"> |
| +<div class="crumb"><div class="wordmark">base</div><span>Scratchpad</span></div> |
| +<h2>Scratchpad</h2> |
| +<p class="lead">Signed in as {{.Name}}, {{.Base}}</p> |
| +<form class="notepad" method="post" action="/"> |
| +{{/* The newline after the opening tag is dropped by the parser, so a note that starts with one keeps it. */}}<textarea class="input" name="note" rows="14" aria-label="Shared note"> |
| +{{.Note}}</textarea> |
| +<button class="btn" type="submit">Save</button> |
| +</form> |
| +</div> |
| +</main>{{end}} |
diff --git a/internal/welcome/templates/welcome.html b/internal/welcome/templates/welcome.html| new file mode 100644 |
| index 0000000..2892f45 |
| --- /dev/null |
| +++ b/internal/welcome/templates/welcome.html |
| @@ -0,0 +1,9 @@ |
| +{{define "title"}}Welcome · {{.Base}}{{end}} |
| +{{define "main"}}<main class="inner"> |
| +<div class="sheet glass"> |
| +<div class="crumb"><div class="wordmark">base</div><span>Welcome</span></div> |
| +<h2>Welcome, {{.Name}}</h2> |
| +<p class="lead">This is {{.Base}} on Base. Your team's apps are on Home.</p> |
| +<a class="btn" href="{{.Home}}">Back to Home</a> |
| +</div> |
| +</main>{{end}} |
diff --git a/internal/welcome/welcome.go b/internal/welcome/welcome.go| new file mode 100644 |
| index 0000000..4e08ec7 |
| --- /dev/null |
| +++ b/internal/welcome/welcome.go |
| @@ -0,0 +1,78 @@ |
| +// Package welcome is Welcome, the app every Base installs first: one page |
| +// that greets the person, names their Base and links back to Home. |
| +// |
| +// Access rule (CARLOS app spec 1.7): anyone the configured Base vouches for |
| +// may see the page. It holds no data of its own. |
| +package welcome |
| + |
| +import ( |
| + "embed" |
| + "errors" |
| + "io/fs" |
| + "log/slog" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/go-chi/chi/v5" |
| + |
| + "amadan.net/rastrillo/rastrillo/csrf" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + |
| + "amadan.net/carlos/base/internal/consumer" |
| + "amadan.net/carlos/base/internal/look" |
| +) |
| + |
| +//go:embed templates/*.html |
| +var templateFS embed.FS |
| + |
| +// BootSchema is everything Welcome's database needs: sessions and the |
| +// handoff's tables. |
| +var BootSchema = migrate.Merge(sessions.Schema, consumer.Schema) |
| + |
| +// sessionTTL matches Scratchpad's: long enough to outlive Base being down |
| +// for a while, short enough that a removed member is gone within a day. |
| +const sessionTTL = 12 * time.Hour |
| + |
| +type welcomePage struct { |
| + Name, Base, Home string |
| +} |
| + |
| +// App builds Welcome's router. d must have BootSchema applied. |
| +func App(d *db.DB, cfg consumer.Config, logger *slog.Logger) (http.Handler, error) { |
| + if d == nil || cfg.Verifier == nil { |
| + return nil, errors.New("welcome: a database and a Config from consumer.Load are required") |
| + } |
| + if logger == nil { |
| + logger = slog.Default() |
| + } |
| + sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, TTL: sessionTTL, |
| + SigninPath: consumer.StartPath, Logger: logger}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + sub, err := fs.Sub(templateFS, "templates") |
| + if err != nil { |
| + return nil, err |
| + } |
| + pages, err := look.NewRenderer(sub, nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + home := cfg.Issuer + "/" |
| + |
| + r := chi.NewRouter() |
| + r.Use(csrf.Protect(cfg.Origin, csrf.Exempt(consumer.AssertionPath))) |
| + consumer.Mount(r, d.Writer(), cfg, sess) |
| + r.Get("/static/fonts/*", look.FontHandler().ServeHTTP) |
| + r.Get("/static/*", look.Assets.Handler().ServeHTTP) |
| + r.With(consumer.Require).Get("/", func(w http.ResponseWriter, r *http.Request) { |
| + _, name, base, _ := consumer.Person(r) |
| + if err := pages.Page(w, "welcome", welcomePage{Name: name, Base: base, Home: home}); err != nil { |
| + logger.Error("welcome: render", "err", err) |
| + http.Error(w, "something went wrong", http.StatusInternalServerError) |
| + } |
| + }) |
| + return r, nil |
| +} |