// Package webtest tests Base from the outside: real HTTP requests against // the real router, wired as cmd/base/main.go wires it. package webtest import ( "bytes" "context" "database/sql" "errors" "html" "io" "log/slog" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "os" "regexp" "strings" "sync" "testing" "time" "amadan.net/rastrillo/rastrillo/budget" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/dbtest" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/store" "amadan.net/oficina/base/internal/web" ) // testOrigin is the origin newApp wires and post presents as its // same-origin evidence: the pair a browser form submission would be. const ( testOrigin = "http://127.0.0.1:8080" ownerAddress = "owner@acme.test" ) // schema is migrated once per test binary and copied for each test. var schema = dbtest.FromSet(store.BootSchema) func TestMain(m *testing.M) { code := budget.Main(m) schema.Remove() homeSchema.Remove() os.Exit(code) } // Mail is one captured message. type Mail struct{ To, Subject, Body string } type capturingMailer struct { mu sync.Mutex sent []Mail fail bool // when set, Send returns an error and records nothing } func (c *capturingMailer) Send(_ context.Context, to, subject, body string) error { c.mu.Lock() defer c.mu.Unlock() if c.fail { return errors.New("smtp down") } c.sent = append(c.sent, Mail{to, subject, body}) return nil } type noInstaller struct{} func (noInstaller) Start(context.Context, string) error { return nil } func (noInstaller) Uninstall(context.Context, string) error { return nil } // Resp is a fully read response. type Resp struct { Code int Header http.Header Body string } func (r Resp) Location() string { return r.Header.Get("Location") } type testApp struct { t *testing.T srv *httptest.Server // nil for an app served in-process (newHomeApp) client *http.Client mail *capturingMailer DB *sql.DB // base prefixes every request path; origin is the same-origin evidence // post presents; localSignin is the page with the email form. base, origin, localSignin string home *oficina // set by newHomeApp // seen is every response so far, for checks that a secret never // reached the browser. seen []Resp // seenMu guards seen; a pointer, so newBrowser's copy shares it. seenMu *sync.Mutex // logs is everything the app logged. logs *logBuffer // header is sent with every request this browser makes (the native // app's Base-Client-Capabilities), unless the request sets it itself. header http.Header } // logBuffer is the app's log, written by its handlers and read by a test. type logBuffer struct { mu sync.Mutex b bytes.Buffer } func (l *logBuffer) Write(p []byte) (int, error) { l.mu.Lock() defer l.mu.Unlock() return l.b.Write(p) } func (l *logBuffer) String() string { l.mu.Lock() defer l.mu.Unlock() return l.b.String() } // newApp builds the whole app per test over its own copy of the migrated // database, exactly as main.go does, with the owner bootstrapped. func newApp(t *testing.T) *testApp { return newAppWith(t, noInstaller{}, time.UTC) } // newAppWith is newApp with the Installer and time zone of the caller's choice. func newAppWith(t *testing.T, inst web.Installer, tz *time.Location) *testApp { t.Helper() return newAppBuilt(t, func(*sql.DB, config.Config) web.Installer { return inst }, tz) } // newAppBuilt is newAppWith for an Installer that needs the app's database // and configuration. func newAppBuilt(t *testing.T, build func(*sql.DB, config.Config) web.Installer, tz *time.Location) *testApp { t.Helper() return newAppConfigured(t, build, tz, nil) } // newAppConfigured is newAppBuilt with a last say over the configuration. func newAppConfigured(t *testing.T, build func(*sql.DB, config.Config) web.Installer, tz *time.Location, tweak func(*config.Config)) *testApp { t.Helper() logs := &logBuffer{} logger := slog.New(slog.NewTextHandler(logs, nil)) d, err := db.Open(schema.Path(t), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil { t.Fatal(err) } cfg := config.Config{Origin: testOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true, Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: tz} if tweak != nil { tweak(&cfg) } mailer := &capturingMailer{} h, err := web.App(d, cfg, mailer, build(d.Writer(), cfg), logger) if err != nil { t.Fatalf("web.App: %v", err) } srv := httptest.NewServer(h) // 127.0.0.1 only t.Cleanup(srv.Close) jar, _ := cookiejar.New(nil) client := &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} return &testApp{seenMu: &sync.Mutex{}, logs: logs, t: t, srv: srv, client: client, mail: mailer, DB: d.Writer(), base: srv.URL, origin: testOrigin, localSignin: "/signin"} } func (a *testApp) do(req *http.Request) Resp { a.t.Helper() a.addHeader(req) res, err := a.client.Do(req) if err != nil { a.t.Fatal(err) } defer res.Body.Close() b, _ := io.ReadAll(res.Body) out := Resp{res.StatusCode, res.Header, string(b)} a.seenMu.Lock() a.seen = append(a.seen, out) a.seenMu.Unlock() return out } // addHeader sets a.header's fields on req where req has none of its own. func (a *testApp) addHeader(req *http.Request) { for k, v := range a.header { if _, ok := req.Header[k]; !ok { req.Header[k] = v } } } func (a *testApp) get(target string) Resp { a.t.Helper() req, _ := http.NewRequest(http.MethodGet, a.base+target, nil) return a.do(req) } // post presents the same-origin evidence csrf.Protect requires: every // browser sends Origin on a form POST; a test client must too. func (a *testApp) post(target string, form url.Values) Resp { a.t.Helper() req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", a.origin) return a.do(req) } func (a *testApp) mailbox() []Mail { a.mail.mu.Lock() defer a.mail.mu.Unlock() return append([]Mail(nil), a.mail.sent...) } var ( formRE = regexp.MustCompile(`(?s)
`) inputRE = regexp.MustCompile(`]*>`) attrRE = regexp.MustCompile(`(\w[\w-]*)="([^"]*)"`) linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`) ) // formFields returns the hidden and text inputs of the form posting to action. func formFields(t *testing.T, body, action string) url.Values { t.Helper() 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 } t.Fatalf("no form posting to %s in:\n%s", action, body) return nil } // requestLink asks for a sign-in link as a visitor would. ?rec=1 renders the // recovery form, which is usable at once; the ordinary one makes a person wait // three seconds before it will be accepted. func (a *testApp) requestLink(email string) Resp { a.t.Helper() page := a.get(a.localSignin + "?rec=1&force=1") if page.Code != 200 { a.t.Fatalf("signin page: %d", page.Code) } v := formFields(a.t, page.Body, "/auth/begin") v.Set("address", email) return a.post("/auth/begin", v) } // signIn requests a link, follows it from the mailbox and confirms it. It // returns the response to the confirm POST: a 303 to "/" on success. func (a *testApp) signIn(email string) Resp { a.t.Helper() before := len(a.mailbox()) if r := a.requestLink(email); r.Code != 303 { a.t.Fatalf("begin: %d %s", r.Code, r.Body) } box := a.mailbox() if len(box) != before+1 { a.t.Fatalf("want one new email, mailbox has %d (was %d)", len(box), before) } link := linkRE.FindString(html.UnescapeString(box[len(box)-1].Body)) if link == "" { a.t.Fatalf("no sign-in link in:\n%s", box[len(box)-1].Body) } u, _ := url.Parse(link) confirm := a.get(u.RequestURI()) if confirm.Code != 200 { a.t.Fatalf("confirm page: %d", confirm.Code) } return a.post("/auth/verify", formFields(a.t, confirm.Body, "/auth/verify")) }