Check the handoff and every screen in a real browser
TestHandoffInRealBrowser serves Base and Scratchpad on two https hostnames under .localhost through rastrillo's serving stack, signs in and opens Scratchpad from Home, with scripts on and off. It checks the handoff page's CSP and Referrer-Policy as the browser received them, that the assertion POST carries Base's Origin and is cross-site, and that the app's cookies come back on the GET after the 303. TestScreenshots saves full-page PNGs of each first-slice screen to BASE_BROWSER_ARTIFACTS. make browser runs the suite.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+434
−1
Makefile+7 −1internal/browsertest/handoff_test.go+143 −0internal/browsertest/screenshots_test.go+94 −0internal/browsertest/world_test.go+190 −0
diff --git a/Makefile b/Makefile| index 9ab28fb..a69a8f1 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -12,7 +12,7 @@ RELEASE_VERSION = $(shell git rev-parse --short HEAD) |
| # One target at a time, even under make -j. |
| .NOTPARALLEL: |
| -.PHONY: fonts build release test vet fmt-check staticcheck govulncheck gitleaks budget ci |
| +.PHONY: fonts build release test browser vet fmt-check staticcheck govulncheck gitleaks budget ci |
| RASTRILLO := go run amadan.net/rastrillo/rastrillo/cmd/rastrillo |
| @@ -41,6 +41,12 @@ budget: |
| test: |
| $(RASTRILLO) budget test -count=1 ./... |
| +# The real-browser suite (internal/browsertest): Chromium drives Base and the |
| +# apps it installs. Set RASTRILLO_CHROME to a Chromium, and |
| +# BASE_BROWSER_ARTIFACTS to a directory to keep the screenshots it takes. |
| +browser: |
| + go test -tags browser -count=1 ./... |
| + |
| vet: |
| go vet ./... |
diff --git a/internal/browsertest/handoff_test.go b/internal/browsertest/handoff_test.go| new file mode 100644 |
| index 0000000..797880e |
| --- /dev/null |
| +++ b/internal/browsertest/handoff_test.go |
| @@ -0,0 +1,143 @@ |
| +//go:build browser |
| + |
| +package browsertest |
| + |
| +import ( |
| + "fmt" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/chromedp" |
| + |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + |
| + "amadan.net/carlos/base/internal/consumer" |
| +) |
| + |
| +// headersSeen keeps the headers the browser received with responses whose URL |
| +// starts with prefix. |
| +type headersSeen struct { |
| + mu sync.Mutex |
| + seen []map[string]string |
| +} |
| + |
| +func watchHeaders(rig *harness.Rig, prefix string) *headersSeen { |
| + h := &headersSeen{} |
| + harness.Listen(rig, rig.Context(), network.ResponseReceived, func(e *network.EventResponseReceived) { |
| + if !strings.HasPrefix(e.Response.URL, prefix) { |
| + return |
| + } |
| + got := map[string]string{} |
| + for k, v := range e.Response.Headers { |
| + if s, ok := v.(string); ok { |
| + got[strings.ToLower(k)] = s |
| + } |
| + } |
| + h.mu.Lock() |
| + h.seen = append(h.seen, got) |
| + h.mu.Unlock() |
| + }) |
| + return h |
| +} |
| + |
| +func (h *headersSeen) all() []map[string]string { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return append([]map[string]string(nil), h.seen...) |
| +} |
| + |
| +// Signed in to Base, the owner opens Scratchpad from Home and lands on it |
| +// signed in. Base and Scratchpad are different sites, both served through |
| +// rastrillo's production stack, so this is the browser's own verdict on |
| +// Base's handoff page (its form-action override and Referrer-Policy: origin) |
| +// and on the app's cookies across the cross-site POST, 303 and GET. |
| +func TestHandoffInRealBrowser(t *testing.T) { |
| + for _, scripts := range []bool{true, false} { |
| + name := "scripts on" |
| + if !scripts { |
| + name = "scripts off" |
| + } |
| + t.Run(name, func(t *testing.T) { |
| + w := newWorld(t) |
| + if !scripts { |
| + drive(t, w.rig, scriptsDisabled(true)) |
| + } |
| + authorize := watchHeaders(w.rig, w.baseOrigin+"/authorize?") |
| + signInByEmail(t, w.rig, w.baseOrigin, w.base.mail) |
| + |
| + tile := chromedp.CSS(fmt.Sprintf(`a.app[href=%q]`, w.padOrigin+"/")) |
| + note := chromedp.CSS(`textarea[name="note"]`) |
| + if scripts { |
| + // The handoff page's script posts its form; nobody presses anything. |
| + drive(t, w.rig, chromedp.Click(tile), chromedp.WaitVisible(note)) |
| + } else { |
| + button := chromedp.CSS(`form#handoff button[type="submit"]`) |
| + drive(t, w.rig, chromedp.Click(tile), chromedp.WaitVisible(button)) |
| + w.rig.Screen(".card", "the handoff page, scripts off") |
| + if here := harness.Read(w.rig, chromedp.Location()); !strings.HasPrefix(here, w.baseOrigin+"/authorize?") { |
| + t.Fatalf("the Continue button is on %s, not Base's /authorize", here) |
| + } |
| + drive(t, w.rig, chromedp.Click(button), chromedp.WaitVisible(note)) |
| + } |
| + w.rig.Screen("main", "Scratchpad") |
| + if here := harness.Read(w.rig, chromedp.Location()); here != w.padOrigin+"/" { |
| + t.Fatalf("the handoff ended at %s, want %s/", here, w.padOrigin) |
| + } |
| + want := "Signed in as " + ownerName + ", " + baseName |
| + if got := harness.Evaluate[string](w.rig, `document.querySelector(".lead").textContent`); got != want { |
| + t.Fatalf("Scratchpad says %q, want %q", got, want) |
| + } |
| + |
| + // What the browser was told on Base's handoff page. |
| + pages := authorize.all() |
| + if len(pages) != 1 { |
| + t.Fatalf("the browser loaded Base's /authorize %d times, want once", len(pages)) |
| + } |
| + if got := pages[0]["referrer-policy"]; got != "origin" { |
| + t.Errorf("handoff page Referrer-Policy %q, want origin", got) |
| + } |
| + if got := pages[0]["content-security-policy"]; !strings.HasSuffix(got, "; form-action "+w.padOrigin) || strings.Contains(got, "form-action 'self'") { |
| + t.Errorf("handoff page CSP %q, want form-action %s only", got, w.padOrigin) |
| + } |
| + |
| + // What Scratchpad received. |
| + var posts, finishes []seen |
| + for _, r := range w.pad.all() { |
| + switch { |
| + case r.method == "POST" && r.path == consumer.AssertionPath: |
| + posts = append(posts, r) |
| + case r.method == "GET" && r.path == consumer.FinishPath: |
| + finishes = append(finishes, r) |
| + } |
| + } |
| + if len(posts) != 1 || len(finishes) != 1 { |
| + t.Fatalf("Scratchpad got %d assertion POSTs and %d finish GETs, want one each: %+v", len(posts), len(finishes), w.pad.all()) |
| + } |
| + post, finish := posts[0], finishes[0] |
| + t.Logf("handoff page: Referrer-Policy %q; CSP %q", pages[0]["referrer-policy"], pages[0]["content-security-policy"]) |
| + t.Logf("assertion POST: Origin %q, Sec-Fetch-Site %q, cookies %v", post.origin, post.fetchSite, post.cookies) |
| + t.Logf("finish GET: Sec-Fetch-Site %q, cookies %v", finish.fetchSite, finish.cookies) |
| + if post.origin != w.baseOrigin { |
| + t.Errorf("the assertion POST carried Origin %q, want Base's %q", post.origin, w.baseOrigin) |
| + } |
| + // The control for everything about cookies below: the browser |
| + // itself counts Base and Scratchpad as different sites. |
| + if post.fetchSite != "cross-site" { |
| + t.Errorf("the assertion POST is %q to the browser, want cross-site", post.fetchSite) |
| + } |
| + // SameSite=Lax keeps the app's cookies off a cross-site POST, which |
| + // is why the assertion waits in an inbox for the same-site GET. |
| + if slices.Contains(post.cookies, "__Host-base-pending") { |
| + t.Errorf("the cross-site POST carried the pending cookie: %v", post.cookies) |
| + } |
| + for _, c := range []string{"__Host-base-pending", "__Host-base-inbox"} { |
| + if !slices.Contains(finish.cookies, c) { |
| + t.Errorf("GET %s after the 303 lacks %s: it carried %v", consumer.FinishPath, c, finish.cookies) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/browsertest/screenshots_test.go b/internal/browsertest/screenshots_test.go| new file mode 100644 |
| index 0000000..7fe0622 |
| --- /dev/null |
| +++ b/internal/browsertest/screenshots_test.go |
| @@ -0,0 +1,94 @@ |
| +//go:build browser |
| + |
| +package browsertest |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/chromedp/chromedp" |
| + |
| + "amadan.net/carlos/base/internal/store" |
| +) |
| + |
| +// TestScreenshots walks the first slice's screens as a signed-in owner and, |
| +// when BASE_BROWSER_ARTIFACTS names a directory, saves a full-page PNG of |
| +// each there for a person to compare with the approved mockup. Nothing here |
| +// judges pixels; each screen still passes the harness's checks. |
| +func TestScreenshots(t *testing.T) { |
| + dir := os.Getenv("BASE_BROWSER_ARTIFACTS") |
| + if dir == "" { |
| + t.Log("BASE_BROWSER_ARTIFACTS is not set: walking the screens without saving them") |
| + } else if err := os.MkdirAll(dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := newWorld(t) |
| + rig := w.rig |
| + drive(t, rig, chromedp.EmulateViewport(1280, 800)) |
| + |
| + shot := func(name, selector, note string) { |
| + t.Helper() |
| + rig.Screen(selector, note) |
| + // The page is drawn in its own face, not a fallback caught mid-load. |
| + drive(t, rig, chromedp.Poll[chromedp.Void](`document.readyState === "complete"`, chromedp.WithPollingTimeout(10*time.Second)), |
| + chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, err := chromedp.Evaluate[bool](`document.fonts.ready.then(() => true)`, chromedp.EvalAwaitPromise)(ctx, target) |
| + return err |
| + })) |
| + if dir == "" { |
| + return |
| + } |
| + var png []byte |
| + drive(t, rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + var err error |
| + png, err = chromedp.FullScreenshot(100)(ctx, target) |
| + return err |
| + })) |
| + if err := os.WriteFile(filepath.Join(dir, name+".png"), png, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + setInstall := func(app, state string) { |
| + t.Helper() |
| + if err := store.SetInstallState(context.Background(), w.base.db, app, state, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + |
| + drive(t, rig, chromedp.Navigate(w.baseOrigin+"/signin"), chromedp.WaitVisible(chromedp.CSS(passkeyDoor))) |
| + shot("1-signin", ".card", "Sign in") |
| + |
| + signInByEmail(t, rig, w.baseOrigin, w.base.mail) |
| + drive(t, rig, chromedp.WaitVisible(chromedp.CSS(fmt.Sprintf(`a.app[href=%q]`, w.padOrigin+"/"))), |
| + chromedp.WaitVisible(chromedp.CSS(fmt.Sprintf(`a.app[href=%q]`, w.welcomeOrigin+"/")))) |
| + shot("2-home", "main", "Home, Welcome and Scratchpad installed") |
| + |
| + invite := chromedp.CSS(`form[action="/people"] input[name="email"]`) |
| + drive(t, rig, chromedp.Navigate(w.baseOrigin+"/people"), chromedp.WaitVisible(invite), |
| + chromedp.SendKeys(invite, "maria@acme.co"), |
| + chromedp.Click(chromedp.CSS(`form[action="/people"] button[type="submit"]`)), |
| + // The invited member's face, drawn only once the invite has landed. |
| + chromedp.WaitVisible(chromedp.CSS(`.people .face.off`))) |
| + shot("3-people", ".sheet", "People, one member invited") |
| + |
| + // Store: Welcome installed, Scratchpad on its way. |
| + setInstall("scratchpad", "installing") |
| + drive(t, rig, chromedp.Navigate(w.baseOrigin+"/store"), chromedp.WaitVisible(chromedp.CSS(`button.installing`))) |
| + shot("4-store", ".sheet", "Store, one app installed and one installing") |
| + setInstall("scratchpad", "installed") |
| + |
| + drive(t, rig, chromedp.Navigate(w.baseOrigin+"/settings"), chromedp.WaitVisible(chromedp.CSS(addPasskey))) |
| + shot("5-settings", ".sheet", "Settings") |
| + |
| + drive(t, rig, chromedp.Navigate(w.baseOrigin+"/"), |
| + chromedp.Click(chromedp.CSS(fmt.Sprintf(`a.app[href=%q]`, w.padOrigin+"/"))), |
| + chromedp.WaitVisible(chromedp.CSS(`textarea[name="note"]`))) |
| + shot("6-scratchpad", ".sheet", "Scratchpad") |
| + if dir != "" { |
| + t.Logf("screenshots in %s", dir) |
| + } |
| +} |
diff --git a/internal/browsertest/world_test.go b/internal/browsertest/world_test.go| new file mode 100644 |
| index 0000000..b60ba4c |
| --- /dev/null |
| +++ b/internal/browsertest/world_test.go |
| @@ -0,0 +1,190 @@ |
| +//go:build browser |
| + |
| +package browsertest |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "log/slog" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "sort" |
| + "sync" |
| + "testing" |
| + |
| + "github.com/chromedp/cdproto/cdp" |
| + "github.com/chromedp/cdproto/security" |
| + "github.com/chromedp/chromedp" |
| + |
| + "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/carlos/base/internal/consumer" |
| + "amadan.net/carlos/base/internal/install" |
| + "amadan.net/carlos/base/internal/scratchpad" |
| + "amadan.net/carlos/base/internal/store" |
| + "amadan.net/carlos/base/internal/welcome" |
| +) |
| + |
| +// world is Base and the apps it installed, each on its own https hostname, |
| +// in one Chromium. |
| +// |
| +// Every name is under .localhost, which Chromium resolves to the loopback |
| +// address by itself, so nothing outside the test is touched: no hosts file, |
| +// no DNS, no launch flags. One TLS listener on 127.0.0.1 serves them all and |
| +// routes by Host, as the platform's edge does; its port is in every origin. |
| +// The certificate is httptest's own, so the browser is told to accept |
| +// certificate errors. |
| +type world struct { |
| + t *testing.T |
| + rig *harness.Rig |
| + base *baseApp |
| + // Origins, each "https://<name>.localhost:<port>". |
| + baseOrigin, padOrigin, welcomeOrigin string |
| + // pad is what Scratchpad's sign-in requests carried as they arrived. |
| + pad *recorder |
| +} |
| + |
| +// hostRouter sends each request to the handler for its Host. |
| +type hostRouter struct { |
| + mu sync.RWMutex |
| + routes map[string]http.Handler |
| +} |
| + |
| +func (h *hostRouter) add(host string, next http.Handler) { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + h.routes[host] = next |
| +} |
| + |
| +func (h *hostRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + h.mu.RLock() |
| + next, ok := h.routes[r.Host] |
| + h.mu.RUnlock() |
| + if !ok { |
| + http.Error(w, "no such host", http.StatusMisdirectedRequest) |
| + return |
| + } |
| + next.ServeHTTP(w, r) |
| +} |
| + |
| +// seen is one request as the server received it. |
| +type seen struct { |
| + method, path, origin, fetchSite string |
| + cookies []string // names only |
| +} |
| + |
| +// recorder keeps the requests made to a few paths. |
| +type recorder struct { |
| + mu sync.Mutex |
| + paths map[string]bool |
| + reqs []seen |
| +} |
| + |
| +func newRecorder(paths ...string) *recorder { |
| + r := &recorder{paths: map[string]bool{}} |
| + for _, p := range paths { |
| + r.paths[p] = true |
| + } |
| + return r |
| +} |
| + |
| +func (rec *recorder) wrap(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if rec.paths[r.URL.Path] { |
| + var names []string |
| + for _, c := range r.Cookies() { |
| + names = append(names, c.Name) |
| + } |
| + sort.Strings(names) |
| + rec.mu.Lock() |
| + rec.reqs = append(rec.reqs, seen{r.Method, r.URL.Path, r.Header.Get("Origin"), r.Header.Get("Sec-Fetch-Site"), names}) |
| + rec.mu.Unlock() |
| + } |
| + next.ServeHTTP(w, r) |
| + }) |
| +} |
| + |
| +func (rec *recorder) all() []seen { |
| + rec.mu.Lock() |
| + defer rec.mu.Unlock() |
| + return append([]seen(nil), rec.reqs...) |
| +} |
| + |
| +// newWorld builds Base with Scratchpad and Welcome installed, as the Installer |
| +// leaves them, and opens a browser that trusts the test certificate. |
| +func newWorld(t *testing.T) *world { |
| + t.Helper() |
| + hosts := &hostRouter{routes: map[string]http.Handler{}} |
| + srv := httptest.NewUnstartedServer(hosts) // 127.0.0.1 only |
| + srv.Config.ErrorLog = slog.NewLogLogger(quiet.Handler(), slog.LevelError) |
| + srv.StartTLS() |
| + t.Cleanup(srv.Close) |
| + port := srv.Listener.Addr().(*net.TCPAddr).Port |
| + |
| + key, err := crypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := baseConfig(fmt.Sprintf("https://base.localhost:%d", port)) |
| + cfg.AppsDomain = fmt.Sprintf("localhost:%d", port) |
| + cfg.AssertionKey = key |
| + w := &world{t: t, base: newBase(t, cfg), baseOrigin: cfg.Origin, pad: newRecorder(consumer.AssertionPath, consumer.FinishPath)} |
| + hosts.add("base.localhost:"+fmt.Sprint(port), w.base.handler) |
| + |
| + ctx := context.Background() |
| + for _, app := range []string{"scratchpad", "welcome"} { |
| + _, host := install.HostFor(cfg, app) |
| + if _, err := store.ClaimInstall(ctx, w.base.db, app, host); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := store.SetInstallState(ctx, w.base.db, app, "installed", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The app's configuration is exactly the four variables Base writes. |
| + vars := install.AppVars(cfg, app, "https://"+host) |
| + ccfg, err := consumer.Load(func(k string) string { return vars[k] }) |
| + if err != nil { |
| + t.Fatalf("consumer.Load for %s: %v", app, err) |
| + } |
| + schema, build := scratchpad.BootSchema, scratchpad.App |
| + if app == "welcome" { |
| + schema, build = welcome.BootSchema, welcome.App |
| + } |
| + d, err := db.Open(filepath.Join(t.TempDir(), app+".db"), quiet) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + if _, err := migrate.Apply(ctx, d, schema); err != nil { |
| + t.Fatal(err) |
| + } |
| + ccfg.Logger = quiet |
| + h, err := build(d, ccfg, quiet) |
| + if err != nil { |
| + t.Fatalf("%s.App: %v", app, err) |
| + } |
| + served := served(t, h) |
| + if app == "scratchpad" { |
| + w.padOrigin = "https://" + host |
| + served = w.pad.wrap(served) |
| + } else { |
| + w.welcomeOrigin = "https://" + host |
| + } |
| + hosts.add(host, served) |
| + } |
| + |
| + // The rig's own localhost server is not used: every page is on the |
| + // listener above. |
| + w.rig = newRig(t, func(string) http.Handler { return http.NotFoundHandler() }) |
| + drive(t, w.rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, err := cdp.Call(ctx, target, security.SetIgnoreCertificateErrors, |
| + security.SetIgnoreCertificateErrorsParams{Ignore: true}) |
| + return err |
| + })) |
| + return w |
| +} |