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)
`) 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(`