oficina / base Public

Issue identity assertions to installed apps

GET /authorize?consumer=<app>&nonce=<n>, behind the member gate, signs a
120-second assertion for the signed-in member with aud set to the
installed app's origin (from config, never the request) and renders a
form that posts it to {aud}/auth/assertion. A deferred static script
submits it; the Continue button does without scripts.

The handoff page sets no-store, no-referrer and a CSP whose form-action
allows only that app's origin. Nonces must have RandomID's shape.
auth_time is the session's sign-in time, else iat. Package issuer does
not import web; web.App passes CurrentMember and signedInAt in.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev dc53e5c3eccb4d9795cd3a0a1970ff642b087e38 parent 7626244
6 files changed, +743 −0
  • docs/copy-pending.md +14 −0
  • internal/issuer/issuer.go +212 −0
  • internal/issuer/issuer_test.go +475 −0
  • internal/issuer/templates/handoff.html +13 −0
  • internal/look/static/handoff.js +3 −0
  • internal/web/app.go +26 −0
diff --git a/docs/copy-pending.md b/docs/copy-pending.md
index 997fc72..73c26a3 100644
--- a/docs/copy-pending.md
+++ b/docs/copy-pending.md
@@ -94,3 +94,17 @@ People and invitations:
| internal/web/templates/settings.html | Settings label | Base name |
| internal/web/templates/settings.html | Settings label | Signed in as |
| internal/web/templates/settings.html | Settings button | Sign out |
+
+Handing a member to an installed app (`GET /authorize`):
+
+| File | Context | Text |
+|---|---|---|
+| internal/issuer/templates/handoff.html | Handoff page, title and heading (shown for a moment before the app opens) | Taking you to {App} |
+| internal/issuer/templates/handoff.html | Handoff button, used when scripts are off | Continue |
+| internal/issuer/issuer.go | Refusal: nonce missing or malformed, or consumer given twice (400) | bad request |
+| internal/issuer/issuer.go | Refusal: app unknown or not installed (404) | not installed |
+| internal/issuer/issuer.go | Refusal: no member on the request (403) | forbidden |
+| internal/issuer/issuer.go | Refusal: not a GET (405) | method not allowed |
+| 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 |
diff --git a/internal/issuer/issuer.go b/internal/issuer/issuer.go
new file mode 100644
index 0000000..8caf57c
--- /dev/null
+++ b/internal/issuer/issuer.go
@@ -0,0 +1,212 @@
+// Package issuer hands installed apps a signed identity assertion for the
+// member using Base.
+//
+// An app sends the browser to GET /authorize?consumer=<app>&nonce=<n>. Base
+// answers with a page whose form posts the assertion to the app's own
+// /auth/assertion, submitted by a deferred script or the Continue button.
+// The audience is always the installed app's origin, derived from config and
+// the app id, never from the request.
+package issuer
+
+import (
+ "database/sql"
+ "embed"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "io/fs"
+ "log/slog"
+ "net/http"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/assertion"
+
+ "amadan.net/carlos/base/internal/catalog"
+ "amadan.net/carlos/base/internal/config"
+ "amadan.net/carlos/base/internal/install"
+ "amadan.net/carlos/base/internal/look"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// Lifetime is how long an assertion is valid: the most rastrillo allows.
+const Lifetime = 120 * time.Second
+
+//go:embed templates/*.html
+var templateFS embed.FS
+
+type issuer struct {
+ db *sql.DB
+ cfg config.Config
+ kid string
+ member func(*http.Request) (store.Member, bool)
+ signedInAt func(*http.Request) (time.Time, bool)
+ logger *slog.Logger
+ pages *look.Renderer
+ now func() time.Time
+}
+
+// New returns the GET /authorize handler. Mount it behind the member gate:
+// member reports the signed-in member the gate admitted, and signedInAt when
+// the session signed in (false if unknown). db is the writer handle.
+func New(db *sql.DB, cfg config.Config, member func(*http.Request) (store.Member, bool), signedInAt func(*http.Request) (time.Time, bool), logger *slog.Logger) (http.Handler, error) {
+ if db == nil || member == nil || signedInAt == nil {
+ return nil, errors.New("issuer: db, member and signedInAt are required")
+ }
+ if cfg.AssertionKey == nil {
+ return nil, errors.New("issuer: BASE_ASSERTION_KEY is required")
+ }
+ if logger == nil {
+ logger = slog.Default()
+ }
+ sub, err := fs.Sub(templateFS, "templates")
+ if err != nil {
+ return nil, err
+ }
+ pages, err := look.NewRenderer(sub, nil)
+ if err != nil {
+ return nil, err
+ }
+ kid, _ := install.KeySet(cfg.AssertionKey)
+ return &issuer{db: db, cfg: cfg, kid: kid, member: member, signedInAt: signedInAt,
+ logger: logger, pages: pages, now: time.Now}, nil
+}
+
+type handoff struct {
+ AppName string
+ Action string
+ Assertion string
+}
+
+func (s *issuer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if r.Method != http.MethodGet {
+ w.Header().Set("Allow", http.MethodGet)
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ m, ok := s.member(r)
+ if !ok {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
+ q := r.URL.Query()
+ if len(q["consumer"]) > 1 || len(q["nonce"]) != 1 || !nonceShape(q["nonce"][0]) {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ app := q.Get("consumer")
+ aud, found, err := s.installedOrigin(r, app)
+ if err != nil {
+ s.logger.Error("authorize: installs", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ if !found {
+ http.Error(w, "not installed", http.StatusNotFound)
+ return
+ }
+
+ now := s.now()
+ iat := now.Unix()
+ authTime := iat
+ if at, ok := s.signedInAt(r); ok && at.Unix() > 0 && at.Unix() <= iat {
+ authTime = at.Unix()
+ }
+ ext, err := json.Marshal(struct {
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Base string `json:"base"`
+ }{m.Name, m.Email, s.cfg.Name})
+ if err != nil {
+ s.fail(w, app, err)
+ return
+ }
+ jti, err := assertion.RandomID()
+ if err != nil {
+ s.fail(w, app, err)
+ return
+ }
+ token, err := assertion.Sign(s.cfg.AssertionKey, assertion.Claims{
+ Version: 1,
+ Issuer: s.cfg.Origin,
+ Audience: aud,
+ Subject: m.ID,
+ KeyID: s.kid,
+ ID: jti,
+ Nonce: q.Get("nonce"),
+ IssuedAt: iat,
+ ExpiresAt: iat + int64(Lifetime/time.Second),
+ AuthTime: authTime,
+ Ext: ext,
+ })
+ if err != nil {
+ s.fail(w, app, err)
+ return
+ }
+ name := app
+ if e, ok := catalog.Get(app); ok {
+ name = e.Name
+ }
+ h := w.Header()
+ h.Set("Referrer-Policy", "no-referrer")
+ h.Set("Content-Security-Policy", handoffCSP(aud))
+ if err := s.pages.Page(w, "handoff", handoff{AppName: name, Action: aud + "/auth/assertion", Assertion: token}); err != nil {
+ s.fail(w, app, err)
+ return
+ }
+ // Never the token or the nonce: the jti is enough to match the app's logs.
+ s.logger.Info("assertion issued", "app", app, "member", m.ID, "jti", jti)
+}
+
+// fail answers 500. The error text never carries the token: assertion's
+// errors are fixed strings.
+func (s *issuer) fail(w http.ResponseWriter, app string, err error) {
+ s.logger.Error("authorize: signing", "app", app, "err", err)
+ http.Error(w, "something went wrong", http.StatusInternalServerError)
+}
+
+// installedOrigin returns https://<host> for app when its install row is
+// "installed" and was made for the host config names now. A row recorded
+// for another host (the slug or apps domain changed since) is refused, so an
+// assertion only ever goes where Base put the app.
+func (s *issuer) installedOrigin(r *http.Request, app string) (string, bool, error) {
+ if app == "" {
+ return "", false, nil
+ }
+ installs, err := store.Installs(r.Context(), s.db)
+ if err != nil {
+ return "", false, err
+ }
+ _, host := install.HostFor(s.cfg, app)
+ for _, in := range installs {
+ if in.App != app {
+ continue
+ }
+ if in.State != "installed" {
+ return "", false, nil
+ }
+ if in.Host != host {
+ s.logger.Warn("authorize: install host differs from config", "app", app)
+ return "", false, nil
+ }
+ return "https://" + host, true, nil
+ }
+ return "", false, nil
+}
+
+// nonceShape accepts exactly what assertion.RandomID produces: 16 bytes as
+// 22 unpadded, canonical base64url characters.
+func nonceShape(s string) bool {
+ if len(s) != 22 {
+ return false
+ }
+ b, err := base64.RawURLEncoding.Strict().DecodeString(s)
+ return err == nil && len(b) == 16 && base64.RawURLEncoding.EncodeToString(b) == s
+}
+
+// handoffCSP is rastrillo's default policy with two changes: forms may post
+// only to the app's origin, and the pow honeypot's style hash is dropped
+// because this page has no pow form. Scripts stay 'self'.
+func handoffCSP(aud string) string {
+ return "default-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action " + aud
+}
diff --git a/internal/issuer/issuer_test.go b/internal/issuer/issuer_test.go
new file mode 100644
index 0000000..fbd83bb
--- /dev/null
+++ b/internal/issuer/issuer_test.go
@@ -0,0 +1,475 @@
+package issuer_test
+
+import (
+ "context"
+ "crypto/tls"
+ "database/sql"
+ "encoding/json"
+ "html"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/http/cookiejar"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "regexp"
+ "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/install"
+ "amadan.net/carlos/base/internal/issuer"
+ "amadan.net/carlos/base/internal/store"
+ "amadan.net/carlos/base/internal/web"
+)
+
+const (
+ baseOrigin = "https://base.acme.test"
+ appOrigin = "https://acme-scratchpad.bab.oncarlos.com"
+ ownerAddress = "owner@acme.test"
+ handoffCSP = "default-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action " + appOrigin
+)
+
+var schema = dbtest.FromSet(store.BootSchema)
+
+func TestMain(m *testing.M) {
+ code := budget.Main(m)
+ schema.Remove()
+ os.Exit(code)
+}
+
+func testConfig(t *testing.T) config.Config {
+ t.Helper()
+ kp, err := crypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return config.Config{Origin: baseOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key",
+ AllowLoggedMail: true, Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC, AssertionKey: kp}
+}
+
+func openDB(t *testing.T) *db.DB {
+ t.Helper()
+ d, err := db.Open(schema.Path(t), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { d.Close() })
+ if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil {
+ t.Fatal(err)
+ }
+ return d
+}
+
+// setInstall gives app an install row in state.
+func setInstall(t *testing.T, sdb *sql.DB, cfg config.Config, app, state string) {
+ t.Helper()
+ ctx := context.Background()
+ _, host := install.HostFor(cfg, app)
+ if _, err := store.ClaimInstall(ctx, sdb, app, host); err != nil {
+ t.Fatal(err)
+ }
+ if state != "installing" {
+ if err := store.SetInstallState(ctx, sdb, app, state, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+type mailbox struct{ last string }
+
+func (m *mailbox) Send(_ context.Context, _, _, body string) error { m.last = body; return nil }
+
+type noInstaller struct{}
+
+func (noInstaller) Install(context.Context, string) error { return nil }
+func (noInstaller) Uninstall(context.Context, string) error { return nil }
+
+type resp struct {
+ Code int
+ Header http.Header
+ Body string
+}
+
+// base is the whole app behind TLS. Requests name cfg.Origin's host and are
+// dialled to the test server, so cookies and origins are what a browser
+// would see.
+type base struct {
+ t *testing.T
+ cfg config.Config
+ db *sql.DB
+ mail *mailbox
+ client *http.Client
+}
+
+func newBase(t *testing.T) *base {
+ t.Helper()
+ cfg := testConfig(t)
+ d := openDB(t)
+ mail := &mailbox{}
+ h, err := web.App(d, cfg, mail, noInstaller{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatalf("web.App: %v", err)
+ }
+ srv := httptest.NewTLSServer(h) // 127.0.0.1 only
+ t.Cleanup(srv.Close)
+ b := &base{t: t, cfg: cfg, db: d.Writer(), mail: mail}
+ b.client = b.newClient(srv.Listener.Addr().String())
+ return b
+}
+
+func (b *base) newClient(addr string) *http.Client {
+ jar, _ := cookiejar.New(nil)
+ tr := &http.Transport{
+ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, addr)
+ },
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test server's own certificate
+ }
+ b.t.Cleanup(tr.CloseIdleConnections)
+ return &http.Client{Jar: jar, Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+}
+
+func (b *base) do(c *http.Client, method, path string, form url.Values) resp {
+ b.t.Helper()
+ var body io.Reader
+ if form != nil {
+ body = strings.NewReader(form.Encode())
+ }
+ req, _ := http.NewRequest(method, b.cfg.Origin+path, body)
+ if form != nil {
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", b.cfg.Origin)
+ }
+ res, err := c.Do(req)
+ if err != nil {
+ b.t.Fatal(err)
+ }
+ defer res.Body.Close()
+ raw, _ := io.ReadAll(res.Body)
+ return resp{res.StatusCode, res.Header, string(raw)}
+}
+
+func (b *base) get(path string) resp { b.t.Helper(); return b.do(b.client, http.MethodGet, path, nil) }
+
+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"<>]+`)
+ tokenRE = regexp.MustCompile(`[A-Za-z0-9_-]{40,}\.[A-Za-z0-9_-]{86}`)
+)
+
+// fields returns the named inputs of the form posting to action, and whether
+// there is one.
+func fields(body, action string) (url.Values, bool) {
+ for _, m := range formRE.FindAllStringSubmatch(body, -1) {
+ if html.UnescapeString(m[1]) != 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 v, true
+ }
+ return nil, false
+}
+
+// signIn follows an emailed link for email, as webtest's helper does.
+func (b *base) signIn(email string) {
+ b.t.Helper()
+ page := b.get("/signin?rec=1&force=1")
+ v, ok := fields(page.Body, "/auth/begin")
+ if page.Code != 200 || !ok {
+ b.t.Fatalf("signin page: %d\n%s", page.Code, page.Body)
+ }
+ v.Set("address", email)
+ if r := b.do(b.client, http.MethodPost, "/auth/begin", v); r.Code != 303 {
+ b.t.Fatalf("begin: %d %s", r.Code, r.Body)
+ }
+ link := linkRE.FindString(html.UnescapeString(b.mail.last))
+ if link == "" {
+ b.t.Fatalf("no sign-in link in %q", b.mail.last)
+ }
+ u, _ := url.Parse(link)
+ confirm := b.get(u.RequestURI())
+ cv, ok := fields(confirm.Body, "/auth/verify")
+ if confirm.Code != 200 || !ok {
+ b.t.Fatalf("confirm page: %d", confirm.Code)
+ }
+ if r := b.do(b.client, http.MethodPost, "/auth/verify", cv); r.Code != 303 || r.Location() != "/" {
+ b.t.Fatalf("verify: %d %q", r.Code, r.Location())
+ }
+}
+
+func (r resp) Location() string { return r.Header.Get("Location") }
+
+func owner(t *testing.T, sdb *sql.DB) store.Member {
+ t.Helper()
+ m, ok, err := store.MemberByEmail(context.Background(), sdb, ownerAddress)
+ if err != nil || !ok {
+ t.Fatalf("owner: %v %v", ok, err)
+ }
+ return m
+}
+
+func nonce(t *testing.T) string {
+ t.Helper()
+ n, err := assertion.RandomID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func verifier(t *testing.T, cfg config.Config) *assertion.Verifier {
+ t.Helper()
+ kid, pub := install.KeySet(cfg.AssertionKey)
+ v, err := assertion.NewVerifier(cfg.Origin, appOrigin, map[string][]byte{kid: pub})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v
+}
+
+func authorizePath(consumer, n string) string {
+ return "/authorize?" + url.Values{"consumer": {consumer}, "nonce": {n}}.Encode()
+}
+
+func TestAuthorizeSignsForInstalledApp(t *testing.T) {
+ b := newBase(t)
+ setInstall(t, b.db, b.cfg, "scratchpad", "installed")
+ before := time.Now().Unix()
+ b.signIn(ownerAddress)
+ signedIn := time.Now().Unix()
+ // Cross a second boundary so auth_time (sign-in) and iat (now) differ.
+ time.Sleep(time.Until(time.Now().Truncate(time.Second).Add(time.Second + 10*time.Millisecond)))
+ n := nonce(t)
+ page := b.get(authorizePath("scratchpad", n))
+ if page.Code != 200 {
+ t.Fatalf("authorize: %d %s", page.Code, page.Body)
+ }
+ v, ok := fields(page.Body, appOrigin+"/auth/assertion")
+ if !ok {
+ t.Fatalf("no form posting to the app:\n%s", page.Body)
+ }
+ if !regexp.MustCompile(`<form[^>]*method="post"`).MatchString(page.Body) {
+ t.Errorf("the form does not POST:\n%s", page.Body)
+ }
+ claims, err := verifier(t, b.cfg).Verify(v.Get("assertion"), time.Now())
+ if err != nil {
+ t.Fatalf("verify: %v", err)
+ }
+ m := owner(t, b.db)
+ kid, _ := install.KeySet(b.cfg.AssertionKey)
+ if claims.Audience != appOrigin || claims.Issuer != baseOrigin || claims.Subject != m.ID || claims.Nonce != n || claims.KeyID != kid {
+ t.Errorf("claims: %+v", claims)
+ }
+ if claims.ExpiresAt-claims.IssuedAt != 120 || claims.IssuedAt <= signedIn || claims.IssuedAt > time.Now().Unix() {
+ t.Errorf("lifetime: iat %d exp %d", claims.IssuedAt, claims.ExpiresAt)
+ }
+ if claims.AuthTime < before || claims.AuthTime > signedIn || claims.AuthTime >= claims.IssuedAt {
+ t.Errorf("auth_time %d, iat %d", claims.AuthTime, claims.IssuedAt)
+ }
+ var ext map[string]string
+ if err := json.Unmarshal(claims.Ext, &ext); err != nil {
+ t.Fatalf("ext: %v", err)
+ }
+ if len(ext) != 3 || ext["name"] != m.Name || ext["email"] != ownerAddress || ext["base"] != "Acme" {
+ t.Errorf("ext: %s", claims.Ext)
+ }
+ if len(claims.ID) != 22 || claims.ID == claims.Nonce {
+ t.Errorf("jti %q", claims.ID)
+ }
+
+ if got := page.Header.Get("Cache-Control"); got != "no-store" {
+ t.Errorf("Cache-Control %q", got)
+ }
+ if got := page.Header.Get("Referrer-Policy"); got != "no-referrer" {
+ t.Errorf("Referrer-Policy %q", got)
+ }
+ if got := page.Header.Values("Content-Security-Policy"); len(got) != 1 || got[0] != handoffCSP {
+ t.Errorf("CSP %q, want %q", got, handoffCSP)
+ }
+ if !strings.Contains(page.Body, `type="submit"`) || !strings.Contains(page.Body, ">Continue<") {
+ t.Errorf("no Continue button:\n%s", page.Body)
+ }
+ // The only script is a deferred file of Base's own; nothing inline.
+ scripts := regexp.MustCompile(`<script[^>]*>`).FindAllString(page.Body, -1)
+ if len(scripts) != 1 || !strings.Contains(scripts[0], " defer") {
+ t.Fatalf("scripts: %q", scripts)
+ }
+ src := regexp.MustCompile(`src="(/static/[^"]+\.js)"`).FindStringSubmatch(scripts[0])
+ if src == nil || !strings.Contains(page.Body, `<script defer src="`+src[1]+`"></script>`) {
+ t.Fatalf("script is not an empty external tag: %q", scripts)
+ }
+ js := b.get(src[1])
+ if js.Code != 200 || !strings.Contains(js.Header.Get("Content-Type"), "javascript") || !strings.Contains(js.Body, "submit()") {
+ t.Errorf("script %s: %d %q\n%s", src[1], js.Code, js.Header.Get("Content-Type"), js.Body)
+ }
+
+ // A second visit is a fresh assertion with a fresh jti.
+ again, _ := fields(b.get(authorizePath("scratchpad", n)).Body, appOrigin+"/auth/assertion")
+ c2, err := verifier(t, b.cfg).Verify(again.Get("assertion"), time.Now())
+ if err != nil || c2.ID == claims.ID {
+ t.Errorf("second assertion: %v, jti %q then %q", err, claims.ID, c2.ID)
+ }
+}
+
+// noAssertion fails if body carries anything that looks like a token or the
+// handoff form.
+func noAssertion(t *testing.T, body string) {
+ t.Helper()
+ if strings.Contains(body, `name="assertion"`) || strings.Contains(body, "/auth/assertion") || tokenRE.MatchString(body) {
+ t.Errorf("refusal carries an assertion:\n%s", body)
+ }
+}
+
+func TestAuthorizeRefusals(t *testing.T) {
+ good := "AAAAAAAAAAAAAAAAAAAAAA" // a 16-byte value, as RandomID encodes it
+ cases := []struct {
+ name string
+ path func(t *testing.T) string
+ signIn bool
+ before func(t *testing.T, b *base) // after sign-in
+ code int
+ }{
+ {name: "no session", path: func(t *testing.T) string { return authorizePath("scratchpad", nonce(t)) }, code: http.StatusSeeOther},
+ {name: "unknown consumer", signIn: true, path: func(t *testing.T) string { return authorizePath("nope", nonce(t)) }, code: http.StatusNotFound},
+ {name: "consumer path trick", signIn: true, path: func(t *testing.T) string { return authorizePath("../scratchpad", nonce(t)) }, code: http.StatusNotFound},
+ {name: "consumer missing", signIn: true, path: func(t *testing.T) string { return "/authorize?nonce=" + nonce(t) }, code: http.StatusNotFound},
+ {name: "consumer twice", signIn: true, path: func(t *testing.T) string {
+ return "/authorize?consumer=scratchpad&consumer=welcome&nonce=" + nonce(t)
+ }, code: http.StatusBadRequest},
+ {name: "consumer installing", signIn: true, path: func(t *testing.T) string { return authorizePath("welcome", nonce(t)) }, code: http.StatusNotFound},
+ {name: "consumer failed", signIn: true, path: func(t *testing.T) string { return authorizePath("broken", nonce(t)) }, code: http.StatusNotFound},
+ {name: "nonce missing", signIn: true, path: func(*testing.T) string { return "/authorize?consumer=scratchpad" }, code: http.StatusBadRequest},
+ {name: "nonce empty", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", "") }, code: http.StatusBadRequest},
+ {name: "nonce short", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good[:21]) }, code: http.StatusBadRequest},
+ {name: "nonce long", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good+"A") }, code: http.StatusBadRequest},
+ {name: "nonce padded", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good[:20]+"==") }, code: http.StatusBadRequest},
+ {name: "nonce std alphabet", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good[:21]+"+") }, code: http.StatusBadRequest},
+ {name: "nonce noncanonical", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good[:21]+"B") }, code: http.StatusBadRequest},
+ {name: "nonce with space", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good+" ") }, code: http.StatusBadRequest},
+ {name: "nonce twice", signIn: true, path: func(t *testing.T) string {
+ return "/authorize?consumer=scratchpad&nonce=" + nonce(t) + "&nonce=" + nonce(t)
+ }, code: http.StatusBadRequest},
+ {name: "member removed after signing in", signIn: true, path: func(t *testing.T) string { return authorizePath("scratchpad", nonce(t)) },
+ before: func(t *testing.T, b *base) {
+ if _, err := b.db.Exec(`DELETE FROM members WHERE email = ?`, ownerAddress); err != nil {
+ t.Fatal(err)
+ }
+ }, code: http.StatusForbidden},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ b := newBase(t)
+ setInstall(t, b.db, b.cfg, "scratchpad", "installed")
+ setInstall(t, b.db, b.cfg, "welcome", "installing")
+ setInstall(t, b.db, b.cfg, "broken", "failed")
+ if tc.signIn {
+ b.signIn(ownerAddress)
+ }
+ if tc.before != nil {
+ tc.before(t, b)
+ }
+ r := b.get(tc.path(t))
+ if r.Code != tc.code {
+ t.Errorf("status %d, want %d\n%s", r.Code, tc.code, r.Body)
+ }
+ if tc.code == http.StatusSeeOther && !strings.HasPrefix(r.Location(), "/signin") {
+ t.Errorf("redirect to %q, want sign-in", r.Location())
+ }
+ noAssertion(t, r.Body)
+ })
+ }
+}
+
+// TestAuthorizeAuthTime drives the handler directly to pin auth_time: the
+// session's sign-in time when known, else iat.
+func TestAuthorizeAuthTime(t *testing.T) {
+ cfg := testConfig(t)
+ d := openDB(t)
+ setInstall(t, d.Writer(), cfg, "scratchpad", "installed")
+ m := owner(t, d.Writer())
+ signedIn := time.Now().Add(-3 * time.Hour).Truncate(time.Second)
+ cases := []struct {
+ name string
+ at time.Time
+ ok bool
+ want func(iat int64) int64
+ }{
+ {"sign-in time", signedIn, true, func(int64) int64 { return signedIn.Unix() }},
+ {"unknown", time.Time{}, false, func(iat int64) int64 { return iat }},
+ {"in the future", time.Now().Add(time.Hour), true, func(iat int64) int64 { return iat }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ h, err := issuer.New(d.Writer(), cfg,
+ func(*http.Request) (store.Member, bool) { return m, true },
+ func(*http.Request) (time.Time, bool) { return tc.at, tc.ok },
+ slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, authorizePath("scratchpad", nonce(t)), nil))
+ v, ok := fields(w.Body.String(), appOrigin+"/auth/assertion")
+ if w.Code != 200 || !ok {
+ t.Fatalf("%d\n%s", w.Code, w.Body)
+ }
+ c, err := verifier(t, cfg).Verify(v.Get("assertion"), time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if c.AuthTime != tc.want(c.IssuedAt) {
+ t.Errorf("auth_time %d, want %d (iat %d)", c.AuthTime, tc.want(c.IssuedAt), c.IssuedAt)
+ }
+ })
+ }
+}
+
+func TestAuthorizeWithoutMemberRefuses(t *testing.T) {
+ cfg := testConfig(t)
+ d := openDB(t)
+ setInstall(t, d.Writer(), cfg, "scratchpad", "installed")
+ h, err := issuer.New(d.Writer(), cfg,
+ func(*http.Request) (store.Member, bool) { return store.Member{}, false },
+ func(*http.Request) (time.Time, bool) { return time.Now(), true },
+ slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, authorizePath("scratchpad", nonce(t)), nil))
+ if w.Code != http.StatusForbidden {
+ t.Errorf("status %d", w.Code)
+ }
+ noAssertion(t, w.Body.String())
+}
+
+func TestNewNeedsKey(t *testing.T) {
+ cfg := testConfig(t)
+ cfg.AssertionKey = nil
+ d := openDB(t)
+ _, err := issuer.New(d.Writer(), cfg, web.CurrentMember, func(*http.Request) (time.Time, bool) { return time.Time{}, false }, nil)
+ if err == nil {
+ t.Fatal("New accepted a missing assertion key")
+ }
+}
diff --git a/internal/issuer/templates/handoff.html b/internal/issuer/templates/handoff.html
new file mode 100644
index 0000000..d0dd307
--- /dev/null
+++ b/internal/issuer/templates/handoff.html
@@ -0,0 +1,13 @@
+{{define "title"}}Taking you to {{.AppName}}{{end}}
+{{define "head"}}<meta name="referrer" content="no-referrer">
+<script defer src="{{asset "static/handoff.js"}}"></script>{{end}}
+{{define "main"}}<main class="signin">
+<div class="card glass">
+<div class="wordmark">base</div>
+<h2>Taking you to {{.AppName}}</h2>
+<form id="handoff" method="post" action="{{.Action}}">
+<input type="hidden" name="assertion" value="{{.Assertion}}">
+<button class="btn" type="submit">Continue</button>
+</form>
+</div>
+</main>{{end}}
diff --git a/internal/look/static/handoff.js b/internal/look/static/handoff.js
new file mode 100644
index 0000000..ed22a42
--- /dev/null
+++ b/internal/look/static/handoff.js
@@ -0,0 +1,3 @@
+// Posts Base's handoff form as soon as the page has parsed. Without scripts
+// the Continue button does the same.
+document.getElementById("handoff").submit();
diff --git a/internal/web/app.go b/internal/web/app.go
index 1305400..5a9ec7a 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -21,6 +21,7 @@ import (
"amadan.net/rastrillo/rastrillo/pow"
"amadan.net/carlos/base/internal/config"
+ "amadan.net/carlos/base/internal/issuer"
"amadan.net/carlos/base/internal/look"
"amadan.net/carlos/base/internal/store"
)
@@ -87,6 +88,16 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
return nil, err
}
+ // Without an assertion key there are no installs to hand off to.
+ var authorize http.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ })
+ if cfg.AssertionKey != nil {
+ if authorize, err = issuer.New(d.Writer(), cfg, CurrentMember, signedInAt, logger); err != nil {
+ return nil, err
+ }
+ }
+
r := chi.NewRouter()
r.Use(csrf.Protect(cfg.Origin))
r.Get("/static/fonts/*", look.FontHandler().ServeHTTP)
@@ -108,6 +119,7 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.Get("/store/{app}/uninstall", a.uninstallPage)
r.Post("/store/{app}/uninstall", a.storeUninstall)
r.Get("/settings", a.settings)
+ r.Method(http.MethodGet, "/authorize", authorize)
})
return r, nil
}
@@ -163,3 +175,17 @@ func (a *app) requireMember(next http.Handler) http.Handler {
}
}))
}
+
+// signedInAt is when the request's session signed in: the credential's own
+// verification time when the sign-in method records one (Keymail), else when
+// the session was created, which is the moment a magic link was confirmed.
+func signedInAt(r *http.Request) (time.Time, bool) {
+ id, ok := auth.From(r)
+ if !ok {
+ return time.Time{}, false
+ }
+ if !id.AuthTime.IsZero() {
+ return id.AuthTime, true
+ }
+ return id.At, !id.At.IsZero()
+}