//go:build browser package browsertest import ( "context" "database/sql" "html" "io" "log/slog" "net/http" "path/filepath" "regexp" "sync" "testing" "time" "github.com/chromedp/chromedp" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/harness" _ "amadan.net/rastrillo/rastrillo/locales/en" "amadan.net/rastrillo/rastrillo/migrate" "amadan.net/rastrillo/rastrillo/pow" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/store" "amadan.net/oficina/base/internal/web" ) const ( ownerAddress = "paul@acme.test" ownerName = "Paul Campbell" baseName = "Acme Ltd" // timelessFont is preloaded by every page. It is git-ignored and fetched // by make fonts, so on a machine without it the browser gets a 404 and // the page falls back to DM Sans, as designed. timelessFont = "/static/fonts/timeless/1.094/TimelessSansVF.woff2" ) var quiet = slog.New(slog.NewTextHandler(io.Discard, nil)) // mailbox keeps every message Base sends. type mailbox struct { mu sync.Mutex bodies []string } func (m *mailbox) Send(_ context.Context, _, _, body string) error { m.mu.Lock() defer m.mu.Unlock() m.bodies = append(m.bodies, body) return nil } func (m *mailbox) count() int { m.mu.Lock(); defer m.mu.Unlock(); return len(m.bodies) } var linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`) // lastLink is the sign-in link in the latest message. func (m *mailbox) lastLink(t *testing.T) string { t.Helper() m.mu.Lock() defer m.mu.Unlock() if len(m.bodies) == 0 { t.Fatal("Base sent no email") } body := html.UnescapeString(m.bodies[len(m.bodies)-1]) link := linkRE.FindString(body) if link == "" { t.Fatalf("no sign-in link in:\n%s", body) } return link } type noInstaller struct{} func (noInstaller) Start(context.Context, string) error { return nil } func (noInstaller) Uninstall(context.Context, string) error { return nil } // baseApp is one Base over its own database, with the owner seeded. type baseApp struct { cfg config.Config db *sql.DB mail *mailbox handler http.Handler // wrapped as production wraps it } // baseConfig is the configuration every test starts from. func baseConfig(origin string) config.Config { return config.Config{Origin: origin, Name: baseName, Owner: ownerAddress, InstanceKey: "browser-instance-key", AllowLoggedMail: true, Slug: "acme", AppsDomain: "test", Timezone: time.UTC} } // newBase builds Base as cmd/base/main.go does: BootSchema applied, the owner // bootstrapped, web.App wrapped by rastrillo's serving stack. func newBase(t *testing.T, cfg config.Config) *baseApp { t.Helper() d, err := db.Open(filepath.Join(t.TempDir(), "base.db"), quiet) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) ctx := context.Background() if _, err := migrate.Apply(ctx, d, store.BootSchema); err != nil { t.Fatal(err) } if err := store.Bootstrap(ctx, d.Writer(), cfg.Owner); err != nil { t.Fatal(err) } if _, err := d.Writer().Exec(`UPDATE members SET name = ?`, ownerName); err != nil { t.Fatal(err) } b := &baseApp{cfg: cfg, db: d.Writer(), mail: &mailbox{}} h, err := web.App(d, cfg, b.mail, noInstaller{}, quiet) if err != nil { t.Fatalf("web.App: %v", err) } b.handler = served(t, h) return b } // served wraps h in what rastrillo.Serve puts around an app in production // (cmd/base and appboot): the framework's endpoints, panic recovery and the // security headers, default CSP and Referrer-Policy included. Only the // listener differs. func served(t *testing.T, h http.Handler) http.Handler { t.Helper() mux := http.NewServeMux() mux.Handle("/", h) out, closeAll, err := rastrillo.Handler(rastrillo.Options{Mux: mux, Logger: quiet}) if err != nil { t.Fatalf("rastrillo.Handler: %v", err) } t.Cleanup(func() { closeAll() }) return out } // driveBudget bounds one drive: a wait for something that never comes fails // as itself instead of hanging the suite until go test's own timeout. const driveBudget = 30 * time.Second // drive runs steps under driveBudget and fails the test with what was on // screen, as the harness's own Run does. func drive(t *testing.T, rig *harness.Rig, steps ...chromedp.Action[chromedp.Void]) { t.Helper() ctx, cancel := context.WithTimeout(rig.Context(), driveBudget) defer cancel() if err := chromedp.Do(ctx, steps...); err != nil { here, _ := chromedp.Run(rig.Context(), chromedp.Location()) text, _ := chromedp.Run(rig.Context(), chromedp.Evaluate[string](`document.body ? document.body.innerText : ""`)) t.Fatalf("drive failed at %s: %v\non screen:\n%s", here, err, text) } } // newRig starts Chromium with the harness's watchers. The font every page // preloads may be missing on this machine; that 404 is expected. func newRig(t *testing.T, build func(origin string) http.Handler) *harness.Rig { t.Helper() rig := harness.New(t, build) rig.Allow(http.MethodGet, timelessFont, http.StatusNotFound) return rig } // signInByEmail signs the owner in at origin the way a person does: type the // address, press Continue, open the emailed link and press Sign in. It ends // on Home. func signInByEmail(t *testing.T, rig *harness.Rig, origin string, mail *mailbox) { t.Helper() address := `input[name="address"]` drive(t, rig, chromedp.Navigate(origin+"/signin"), chromedp.WaitVisible(chromedp.CSS(address))) rig.Screen(".card", "the sign-in page") drive(t, rig, chromedp.SendKeys(chromedp.CSS(address), ownerAddress), // Base refuses a sign-in form sent sooner than a person could read it. chromedp.Sleep(pow.DefaultMinAge+300*time.Millisecond), chromedp.Click(chromedp.CSS(`form[action="/auth/begin"] button[type="submit"]`)), chromedp.WaitVisible(chromedp.CSS(`form[action="/auth/forget"]`)), ) rig.Screen(".card", "Check your email") signIn := `form[action$="/auth/verify"] button[type="submit"]` drive(t, rig, chromedp.Navigate(mail.lastLink(t)), chromedp.WaitVisible(chromedp.CSS(signIn))) rig.Screen(".card", "the emailed link's page") drive(t, rig, chromedp.Click(chromedp.CSS(signIn)), chromedp.WaitVisible(chromedp.CSS(".hello"))) rig.Screen("main", "Home") if here := harness.Read(rig, chromedp.Location()); here != origin+"/" { t.Fatalf("signing in by email ended at %s", here) } }