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" "unicode/utf8" "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/oficina/base/internal/config" "amadan.net/oficina/base/internal/install" "amadan.net/oficina/base/internal/issuer" "amadan.net/oficina/base/internal/store" "amadan.net/oficina/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) Start(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)]*action="([^"]*)"[^>]*>(.*?)`) inputRE = regexp.MustCompile(`]*>`) 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(`]*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) } // origin, not no-referrer: the app checks that the POST's Origin is Base, // and no-referrer would make browsers send Origin: null (R21). if got := page.Header.Get("Referrer-Policy"); got != "origin" { t.Errorf("Referrer-Policy %q, want origin", got) } if metas := regexp.MustCompile(`]*>`).FindAllString(page.Body, -1); len(metas) != 1 || metas[0] != `` { t.Errorf("referrer meta: %q", metas) } 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(`]*>`).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, ``) { 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") } } // Finding 1: the assertion goes to the host Base installed the app at, which // is where the app was told its own origin is, even after the slug or apps // domain changed. It still never comes from the request. func TestAuthorizeUsesRecordedHost(t *testing.T) { b := newBase(t) ctx := context.Background() const old = "https://oldco-scratchpad.old.example" if _, err := store.ClaimInstall(ctx, b.db, "scratchpad", strings.TrimPrefix(old, "https://")); err != nil { t.Fatal(err) } if err := store.SetInstallState(ctx, b.db, "scratchpad", "installed", ""); err != nil { t.Fatal(err) } b.signIn(ownerAddress) page := b.get(authorizePath("scratchpad", nonce(t))) v, ok := fields(page.Body, old+"/auth/assertion") if page.Code != 200 || !ok { t.Fatalf("authorize: %d\n%s", page.Code, page.Body) } kid, pub := install.KeySet(b.cfg.AssertionKey) ver, err := assertion.NewVerifier(b.cfg.Origin, old, map[string][]byte{kid: pub}) if err != nil { t.Fatal(err) } if c, err := ver.Verify(v.Get("assertion"), time.Now()); err != nil || c.Audience != old { t.Fatalf("assertion for %q: %v", c.Audience, err) } if got := page.Header.Get("Content-Security-Policy"); !strings.HasSuffix(got, "form-action "+old) { t.Errorf("CSP %q", got) } } // Finding 10: display fields are cut to fit rastrillo's 1 KiB limit on Ext, // at a character boundary, so a very long name never breaks the handoff. func TestAuthorizeBoundsDisplayFields(t *testing.T) { for name, tc := range map[string]struct{ member, base string }{ "long name": {strings.Repeat("Ana María ", 300), "Acme"}, "name that escapes": {strings.Repeat("<&>", 400), "Acme"}, "long base name": {"Paul", strings.Repeat("Acme Holdings ", 200)}, "multibyte at the edge": {strings.Repeat("é", 1000), strings.Repeat("日本", 400)}, } { t.Run(name, func(t *testing.T) { cfg := testConfig(t) cfg.Name = tc.base d := openDB(t) setInstall(t, d.Writer(), cfg, "scratchpad", "installed") m := owner(t, d.Writer()) m.Name = tc.member m.Email = strings.Repeat("x", 400) + "@acme.test" h, err := issuer.New(d.Writer(), cfg, func(*http.Request) (store.Member, bool) { return m, true }, func(*http.Request) (time.Time, bool) { return time.Time{}, false }, 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("authorize: %d\n%s", w.Code, w.Body) } c, err := verifier(t, cfg).Verify(v.Get("assertion"), time.Now()) if err != nil { t.Fatal(err) } var ext map[string]string if err := json.Unmarshal(c.Ext, &ext); err != nil || len(c.Ext) > 1024 { t.Fatalf("ext %d bytes: %v", len(c.Ext), err) } for field, full := range map[string]string{"name": tc.member, "email": m.Email, "base": tc.base} { got := ext[field] if got == "" || !utf8.ValidString(got) { t.Errorf("%s = %q", field, got) } if got != full && !strings.HasPrefix(full, strings.TrimSuffix(got, "…")) { t.Errorf("%s %q is not a prefix of the original", field, got) } } }) } }