// Package e2e runs Base and the apps it installs together, in process, the // way a browser meets them: one cookie jar, each app on its own origin. package e2e import ( "context" "crypto/tls" "html" "io" "log/slog" "net" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "os" "regexp" "strings" "sync" "sync/atomic" "testing" "time" "amadan.net/rastrillo/rastrillo/budget" "amadan.net/rastrillo/rastrillo/crypto" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/dbtest" "amadan.net/oficina/base/internal/config" "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/web" "amadan.net/oficina/base/internal/welcome" ) const ( baseOrigin = "https://base.test" ownerAddress = "paul@acme.test" ) var ( baseSchema = dbtest.FromSet(store.BootSchema) padSchema = dbtest.FromSet(scratchpad.BootSchema) welSchema = dbtest.FromSet(welcome.BootSchema) ) func TestMain(m *testing.M) { code := budget.Main(m) baseSchema.Remove() padSchema.Remove() welSchema.Remove() os.Exit(code) } type mailbox struct { mu sync.Mutex last string } func (m *mailbox) Send(_ context.Context, _, _, body string) error { m.mu.Lock() defer m.mu.Unlock() m.last = body return nil } func (m *mailbox) body() string { m.mu.Lock(); defer m.mu.Unlock(); return m.last } type noInstaller struct{} func (noInstaller) Start(context.Context, string) error { return nil } func (noInstaller) Uninstall(context.Context, string) error { return nil } // swappable lets a test replace a running server's handler. type swappable struct{ h atomic.Pointer[http.Handler] } func (s *swappable) set(h http.Handler) { s.h.Store(&h) } func (s *swappable) ServeHTTP(w http.ResponseWriter, r *http.Request) { (*s.h.Load()).ServeHTTP(w, r) } // world is Base plus installed apps, each behind TLS on its own test // server. The browser dials each origin's host to its server. type world struct { t *testing.T cfg config.Config base *swappable mail *mailbox addrs map[string]string // host -> listener address browser *http.Client } func newWorld(t *testing.T) *world { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) key, err := crypto.Generate() if err != nil { t.Fatal(err) } cfg := config.Config{Origin: baseOrigin, Name: "Acme Ltd", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true, Slug: "acme", AppsDomain: "test", Timezone: time.UTC, AssertionKey: key} d, err := db.Open(baseSchema.Path(t), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) ctx := context.Background() if err := store.Bootstrap(ctx, d.Writer(), ownerAddress); err != nil { t.Fatal(err) } if _, err := d.Writer().Exec(`UPDATE members SET name = 'Paul'`); err != nil { t.Fatal(err) } w := &world{t: t, cfg: cfg, base: &swappable{}, mail: &mailbox{}, addrs: map[string]string{}} h, err := web.App(d, cfg, w.mail, noInstaller{}, logger) if err != nil { t.Fatalf("web.App: %v", err) } w.base.set(h) w.serve("base.test", w.base) // Base's installs, seeded as the Installer would leave them. for _, app := range []string{"scratchpad", "welcome"} { _, host := install.HostFor(cfg, app) if _, err := store.ClaimInstall(ctx, d.Writer(), app, host); err != nil { t.Fatal(err) } if err := store.SetInstallState(ctx, d.Writer(), app, "installed", ""); err != nil { t.Fatal(err) } ccfg := w.appConfig(app, host) ad, err := db.Open(map[string]*dbtest.Template{"scratchpad": padSchema, "welcome": welSchema}[app].Path(t), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { ad.Close() }) var ah http.Handler if app == "scratchpad" { ah, err = scratchpad.App(ad, ccfg, logger) } else { ah, err = welcome.App(ad, ccfg, logger) } if err != nil { t.Fatalf("%s.App: %v", app, err) } w.serve(host, ah) } jar, _ := cookiejar.New(nil) tr := &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { host, _, _ := net.SplitHostPort(addr) to, ok := w.addrs[host] if !ok { return nil, &net.AddrError{Err: "no test server", Addr: addr} } return (&net.Dialer{}).DialContext(ctx, network, to) }, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test servers' own certificate } t.Cleanup(tr.CloseIdleConnections) w.browser = &http.Client{Jar: jar, Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} return w } // appConfig is the app's configuration from exactly what Base writes at install. func (w *world) appConfig(app, host string) consumer.Config { w.t.Helper() vars := install.AppVars(w.cfg, app, "https://"+host) cfg, err := consumer.Load(func(k string) string { return vars[k] }) if err != nil { w.t.Fatalf("consumer.Load for %s: %v", app, err) } return cfg } func (w *world) serve(host string, h http.Handler) { srv := httptest.NewTLSServer(h) // 127.0.0.1 only w.t.Cleanup(srv.Close) w.addrs[host] = srv.Listener.Addr().String() } type resp struct { Code int Header http.Header Body string } func (r resp) Location() string { return r.Header.Get("Location") } // do sends one request. A form is posted with the Origin a browser would // send: the origin of the page the form was on. func (w *world) do(method, target string, form url.Values, origin string) resp { w.t.Helper() var body io.Reader if form != nil { body = strings.NewReader(form.Encode()) } req, err := http.NewRequest(method, target, body) if err != nil { w.t.Fatal(err) } if form != nil { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", origin) } res, err := w.browser.Do(req) if err != nil { w.t.Fatal(err) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) return resp{res.StatusCode, res.Header, string(raw)} } func (w *world) get(target string) resp { w.t.Helper(); return w.do(http.MethodGet, target, nil, "") } // follow GETs target and every same-method redirect after it, resolving // relative locations, and returns the last response and its URL. func (w *world) follow(target string) (resp, string) { w.t.Helper() for range 10 { r := w.get(target) if r.Code != http.StatusSeeOther && r.Code != http.StatusFound { return r, target } base, _ := url.Parse(target) next, err := base.Parse(r.Location()) if err != nil { w.t.Fatalf("bad redirect %q", r.Location()) } target = next.String() } w.t.Fatalf("too many redirects at %s", target) return resp{}, "" } var ( formRE = regexp.MustCompile(`(?s)]*action="([^"]*)"[^>]*>(.*?)`) inputRE = regexp.MustCompile(`]*>`) attrRE = regexp.MustCompile(`(\w[\w-]*)="([^"]*)"`) linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`) ) // form returns the action and named inputs of the first form whose action // satisfies match. func form(t *testing.T, body string, match func(string) bool) (string, url.Values) { t.Helper() for _, m := range formRE.FindAllStringSubmatch(body, -1) { action := html.UnescapeString(m[1]) if !match(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 action, v } t.Fatalf("no matching form in:\n%s", body) return "", nil } func is(want string) func(string) bool { return func(s string) bool { return s == want } } // signInToBase signs the browser in to Base with an emailed link (Ruling R3: // this suite's own helper, not webtest's). func (w *world) signInToBase(email string) { w.t.Helper() page := w.get(baseOrigin + "/signin?rec=1&force=1") _, v := form(w.t, page.Body, is("/auth/begin")) v.Set("address", email) if r := w.do(http.MethodPost, baseOrigin+"/auth/begin", v, baseOrigin); r.Code != http.StatusSeeOther { w.t.Fatalf("begin: %d %s", r.Code, r.Body) } link := linkRE.FindString(html.UnescapeString(w.mail.body())) if link == "" { w.t.Fatalf("no sign-in link in %q", w.mail.body()) } confirm := w.get(link) _, cv := form(w.t, confirm.Body, is("/auth/verify")) if r := w.do(http.MethodPost, baseOrigin+"/auth/verify", cv, baseOrigin); r.Code != http.StatusSeeOther || r.Location() != "/" { w.t.Fatalf("verify: %d %q", r.Code, r.Location()) } } // openApp opens an app as its Home tile does and goes through the handoff: // the app sends the browser to Base, Base answers with its handoff page, // and the browser submits that form to the app. It returns the app's page. func (w *world) openApp(origin string) resp { w.t.Helper() page, at := w.follow(origin + "/") if !strings.HasPrefix(at, baseOrigin+"/authorize?") || page.Code != 200 { w.t.Fatalf("opening %s ended at %s: %d\n%s", origin, at, page.Code, page.Body) } if got := page.Header.Get("Referrer-Policy"); got != "origin" { w.t.Fatalf("handoff Referrer-Policy %q", got) } action, v := form(w.t, page.Body, is(origin+consumer.AssertionPath)) // With Referrer-Policy: origin the browser sends Base's origin (R21). r := w.do(http.MethodPost, action, v, baseOrigin) if r.Code != http.StatusSeeOther || r.Location() != consumer.FinishPath { w.t.Fatalf("assertion post: %d %q %s", r.Code, r.Location(), r.Body) } final, at := w.follow(origin + r.Location()) if at != origin+"/" { w.t.Fatalf("handoff ended at %s", at) } return final } const padOrigin = "https://acme-scratchpad.test" func TestHandoffEndToEnd(t *testing.T) { w := newWorld(t) if _, host := install.HostFor(w.cfg, "scratchpad"); "https://"+host != padOrigin { t.Fatalf("Scratchpad's host is %s", host) } w.signInToBase(ownerAddress) // Home's tile links straight to the app's origin. home := w.get(baseOrigin + "/") if !strings.Contains(home.Body, `href="`+padOrigin+`/"`) { t.Fatalf("Home has no Scratchpad tile:\n%s", home.Body) } page := w.openApp(padOrigin) if page.Code != 200 || !strings.Contains(page.Body, "Signed in as Paul, Acme Ltd") { t.Fatalf("Scratchpad: %d\n%s", page.Code, page.Body) } } func TestSessionOutlivesBase(t *testing.T) { w := newWorld(t) w.signInToBase(ownerAddress) w.openApp(padOrigin) w.base.set(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { http.Error(rw, "down", http.StatusServiceUnavailable) })) if r := w.get(baseOrigin + "/"); r.Code != http.StatusServiceUnavailable { t.Fatalf("Base still answers: %d", r.Code) } r := w.get(padOrigin + "/") if r.Code != 200 || !strings.Contains(r.Body, "Signed in as Paul, Acme Ltd") { t.Fatalf("Scratchpad with Base down: %d\n%s", r.Code, r.Body) } } func TestWelcomeEndToEnd(t *testing.T) { w := newWorld(t) w.signInToBase(ownerAddress) page := w.openApp("https://acme-welcome.test") if page.Code != 200 || !strings.Contains(page.Body, "Acme Ltd") || !strings.Contains(page.Body, "Paul") { t.Fatalf("Welcome: %d\n%s", page.Code, page.Body) } if !strings.Contains(page.Body, `href="`+baseOrigin+`/"`) { t.Errorf("Welcome has no link back to Home:\n%s", page.Body) } } func TestAssertionForOneAppRefusedByAnother(t *testing.T) { w := newWorld(t) w.signInToBase(ownerAddress) // Start a sign-in at Scratchpad, but take Welcome's assertion there. _, at := w.follow(padOrigin + "/") u, _ := url.Parse(at) n := u.Query().Get("nonce") page := w.get(baseOrigin + "/authorize?" + url.Values{"consumer": {"welcome"}, "nonce": {n}}.Encode()) _, v := form(t, page.Body, is("https://acme-welcome.test"+consumer.AssertionPath)) if r := w.do(http.MethodPost, padOrigin+consumer.AssertionPath, v, baseOrigin); r.Code == http.StatusSeeOther { t.Fatalf("Scratchpad took Welcome's assertion") } w.get(padOrigin + consumer.FinishPath) if r := w.get(padOrigin + "/"); r.Code == 200 { t.Fatalf("signed in to Scratchpad with Welcome's assertion") } }