| 1 | //go:build browser |
| 2 | |
| 3 | package browsertest |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "path/filepath" |
| 13 | "sort" |
| 14 | "sync" |
| 15 | "testing" |
| 16 | |
| 17 | "github.com/chromedp/cdproto/cdp" |
| 18 | "github.com/chromedp/cdproto/security" |
| 19 | "github.com/chromedp/chromedp" |
| 20 | |
| 21 | "amadan.net/rastrillo/rastrillo/crypto" |
| 22 | "amadan.net/rastrillo/rastrillo/db" |
| 23 | "amadan.net/rastrillo/rastrillo/harness" |
| 24 | "amadan.net/rastrillo/rastrillo/migrate" |
| 25 | |
| 26 | "amadan.net/oficina/base/internal/consumer" |
| 27 | "amadan.net/oficina/base/internal/install" |
| 28 | "amadan.net/oficina/base/internal/scratchpad" |
| 29 | "amadan.net/oficina/base/internal/store" |
| 30 | "amadan.net/oficina/base/internal/welcome" |
| 31 | ) |
| 32 | |
| 33 | // world is Base and the apps it installed, each on its own https hostname, |
| 34 | // in one Chromium. |
| 35 | // |
| 36 | // Every name is under .localhost, which Chromium resolves to the loopback |
| 37 | // address by itself, so nothing outside the test is touched: no hosts file, |
| 38 | // no DNS, no launch flags. One TLS listener on 127.0.0.1 serves them all and |
| 39 | // routes by Host, as the platform's edge does; its port is in every origin. |
| 40 | // The certificate is httptest's own, so the browser is told to accept |
| 41 | // certificate errors. |
| 42 | type world struct { |
| 43 | t *testing.T |
| 44 | rig *harness.Rig |
| 45 | base *baseApp |
| 46 | // Origins, each "https://<name>.localhost:<port>". |
| 47 | baseOrigin, padOrigin, welcomeOrigin string |
| 48 | // pad is what Scratchpad's sign-in requests carried as they arrived. |
| 49 | pad *recorder |
| 50 | } |
| 51 | |
| 52 | // hostRouter sends each request to the handler for its Host. |
| 53 | type hostRouter struct { |
| 54 | mu sync.RWMutex |
| 55 | routes map[string]http.Handler |
| 56 | } |
| 57 | |
| 58 | func (h *hostRouter) add(host string, next http.Handler) { |
| 59 | h.mu.Lock() |
| 60 | defer h.mu.Unlock() |
| 61 | h.routes[host] = next |
| 62 | } |
| 63 | |
| 64 | func (h *hostRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 65 | h.mu.RLock() |
| 66 | next, ok := h.routes[r.Host] |
| 67 | h.mu.RUnlock() |
| 68 | if !ok { |
| 69 | http.Error(w, "no such host", http.StatusMisdirectedRequest) |
| 70 | return |
| 71 | } |
| 72 | next.ServeHTTP(w, r) |
| 73 | } |
| 74 | |
| 75 | // seen is one request as the server received it. |
| 76 | type seen struct { |
| 77 | method, path, origin, fetchSite string |
| 78 | cookies []string // names only |
| 79 | } |
| 80 | |
| 81 | // recorder keeps the requests made to a few paths. |
| 82 | type recorder struct { |
| 83 | mu sync.Mutex |
| 84 | paths map[string]bool |
| 85 | reqs []seen |
| 86 | } |
| 87 | |
| 88 | func newRecorder(paths ...string) *recorder { |
| 89 | r := &recorder{paths: map[string]bool{}} |
| 90 | for _, p := range paths { |
| 91 | r.paths[p] = true |
| 92 | } |
| 93 | return r |
| 94 | } |
| 95 | |
| 96 | func (rec *recorder) wrap(next http.Handler) http.Handler { |
| 97 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 98 | if rec.paths[r.URL.Path] { |
| 99 | var names []string |
| 100 | for _, c := range r.Cookies() { |
| 101 | names = append(names, c.Name) |
| 102 | } |
| 103 | sort.Strings(names) |
| 104 | rec.mu.Lock() |
| 105 | rec.reqs = append(rec.reqs, seen{r.Method, r.URL.Path, r.Header.Get("Origin"), r.Header.Get("Sec-Fetch-Site"), names}) |
| 106 | rec.mu.Unlock() |
| 107 | } |
| 108 | next.ServeHTTP(w, r) |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | func (rec *recorder) all() []seen { |
| 113 | rec.mu.Lock() |
| 114 | defer rec.mu.Unlock() |
| 115 | return append([]seen(nil), rec.reqs...) |
| 116 | } |
| 117 | |
| 118 | // newWorld builds Base with Scratchpad and Welcome installed, as the Installer |
| 119 | // leaves them, and opens a browser that trusts the test certificate. |
| 120 | func newWorld(t *testing.T) *world { |
| 121 | t.Helper() |
| 122 | hosts := &hostRouter{routes: map[string]http.Handler{}} |
| 123 | srv := httptest.NewUnstartedServer(hosts) // 127.0.0.1 only |
| 124 | srv.Config.ErrorLog = slog.NewLogLogger(quiet.Handler(), slog.LevelError) |
| 125 | srv.StartTLS() |
| 126 | t.Cleanup(srv.Close) |
| 127 | port := srv.Listener.Addr().(*net.TCPAddr).Port |
| 128 | |
| 129 | key, err := crypto.Generate() |
| 130 | if err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | cfg := baseConfig(fmt.Sprintf("https://base.localhost:%d", port)) |
| 134 | cfg.AppsDomain = fmt.Sprintf("localhost:%d", port) |
| 135 | cfg.AssertionKey = key |
| 136 | w := &world{t: t, base: newBase(t, cfg), baseOrigin: cfg.Origin, pad: newRecorder(consumer.AssertionPath, consumer.FinishPath, consumer.SignOutPath)} |
| 137 | hosts.add("base.localhost:"+fmt.Sprint(port), w.base.handler) |
| 138 | |
| 139 | ctx := context.Background() |
| 140 | for _, app := range []string{"scratchpad", "welcome"} { |
| 141 | _, host := install.HostFor(cfg, app) |
| 142 | if _, err := store.ClaimInstall(ctx, w.base.db, app, host); err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | if err := store.SetInstallState(ctx, w.base.db, app, "installed", ""); err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | // The app's configuration is exactly the four variables Base writes. |
| 149 | vars := install.AppVars(cfg, app, "https://"+host) |
| 150 | ccfg, err := consumer.Load(func(k string) string { return vars[k] }) |
| 151 | if err != nil { |
| 152 | t.Fatalf("consumer.Load for %s: %v", app, err) |
| 153 | } |
| 154 | schema, build := scratchpad.BootSchema, scratchpad.App |
| 155 | if app == "welcome" { |
| 156 | schema, build = welcome.BootSchema, welcome.App |
| 157 | } |
| 158 | d, err := db.Open(filepath.Join(t.TempDir(), app+".db"), quiet) |
| 159 | if err != nil { |
| 160 | t.Fatal(err) |
| 161 | } |
| 162 | t.Cleanup(func() { d.Close() }) |
| 163 | if _, err := migrate.Apply(ctx, d, schema); err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | ccfg.Logger = quiet |
| 167 | h, err := build(d, ccfg, quiet) |
| 168 | if err != nil { |
| 169 | t.Fatalf("%s.App: %v", app, err) |
| 170 | } |
| 171 | served := served(t, h) |
| 172 | if app == "scratchpad" { |
| 173 | w.padOrigin = "https://" + host |
| 174 | served = w.pad.wrap(served) |
| 175 | } else { |
| 176 | w.welcomeOrigin = "https://" + host |
| 177 | } |
| 178 | hosts.add(host, served) |
| 179 | } |
| 180 | |
| 181 | // The rig's own localhost server is not used: every page is on the |
| 182 | // listener above. |
| 183 | w.rig = newRig(t, func(string) http.Handler { return http.NotFoundHandler() }) |
| 184 | drive(t, w.rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| 185 | _, err := cdp.Call(ctx, target, security.SetIgnoreCertificateErrors, |
| 186 | security.SetIgnoreCertificateErrorsParams{Ignore: true}) |
| 187 | return err |
| 188 | })) |
| 189 | return w |
| 190 | } |
| 191 | |