//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/oficina/base/internal/consumer" "amadan.net/oficina/base/internal/install" "amadan.net/oficina/base/internal/scratchpad" "amadan.net/oficina/base/internal/store" "amadan.net/oficina/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://.localhost:". 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, consumer.SignOutPath)} 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 }