| 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") |
| + } |
| +} |