oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1// Package e2e runs Base and the apps it installs together, in process, the
2// way a browser meets them: one cookie jar, each app on its own origin.
3package e2e
4
5import (
6 "context"
7 "crypto/tls"
8 "html"
9 "io"
10 "log/slog"
11 "net"
12 "net/http"
13 "net/http/cookiejar"
14 "net/http/httptest"
15 "net/url"
16 "os"
17 "regexp"
18 "strings"
19 "sync"
20 "sync/atomic"
21 "testing"
22 "time"
23
24 "amadan.net/rastrillo/rastrillo/budget"
25 "amadan.net/rastrillo/rastrillo/crypto"
26 "amadan.net/rastrillo/rastrillo/db"
27 "amadan.net/rastrillo/rastrillo/dbtest"
28
29 "amadan.net/oficina/base/internal/config"
30 "amadan.net/oficina/base/internal/consumer"
31 "amadan.net/oficina/base/internal/install"
32 "amadan.net/oficina/base/internal/scratchpad"
33 "amadan.net/oficina/base/internal/store"
34 "amadan.net/oficina/base/internal/web"
35 "amadan.net/oficina/base/internal/welcome"
36)
37
38const (
39 baseOrigin = "https://base.test"
40 ownerAddress = "paul@acme.test"
41)
42
43var (
44 baseSchema = dbtest.FromSet(store.BootSchema)
45 padSchema = dbtest.FromSet(scratchpad.BootSchema)
46 welSchema = dbtest.FromSet(welcome.BootSchema)
47)
48
49func TestMain(m *testing.M) {
50 code := budget.Main(m)
51 baseSchema.Remove()
52 padSchema.Remove()
53 welSchema.Remove()
54 os.Exit(code)
55}
56
57type mailbox struct {
58 mu sync.Mutex
59 last string
60}
61
62func (m *mailbox) Send(_ context.Context, _, _, body string) error {
63 m.mu.Lock()
64 defer m.mu.Unlock()
65 m.last = body
66 return nil
67}
68
69func (m *mailbox) body() string { m.mu.Lock(); defer m.mu.Unlock(); return m.last }
70
71type noInstaller struct{}
72
73func (noInstaller) Start(context.Context, string) error { return nil }
74func (noInstaller) Uninstall(context.Context, string) error { return nil }
75
76// swappable lets a test replace a running server's handler.
77type swappable struct{ h atomic.Pointer[http.Handler] }
78
79func (s *swappable) set(h http.Handler) { s.h.Store(&h) }
80func (s *swappable) ServeHTTP(w http.ResponseWriter, r *http.Request) {
81 (*s.h.Load()).ServeHTTP(w, r)
82}
83
84// world is Base plus installed apps, each behind TLS on its own test
85// server. The browser dials each origin's host to its server.
86type world struct {
87 t *testing.T
88 cfg config.Config
89 base *swappable
90 mail *mailbox
91 addrs map[string]string // host -> listener address
92 browser *http.Client
93}
94
95func newWorld(t *testing.T) *world {
96 t.Helper()
97 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
98 key, err := crypto.Generate()
99 if err != nil {
100 t.Fatal(err)
101 }
102 cfg := config.Config{Origin: baseOrigin, Name: "Acme Ltd", Owner: ownerAddress, InstanceKey: "test-instance-key",
103 AllowLoggedMail: true, Slug: "acme", AppsDomain: "test", Timezone: time.UTC, AssertionKey: key}
104 d, err := db.Open(baseSchema.Path(t), logger)
105 if err != nil {
106 t.Fatal(err)
107 }
108 t.Cleanup(func() { d.Close() })
109 ctx := context.Background()
110 if err := store.Bootstrap(ctx, d.Writer(), ownerAddress); err != nil {
111 t.Fatal(err)
112 }
113 if _, err := d.Writer().Exec(`UPDATE members SET name = 'Paul'`); err != nil {
114 t.Fatal(err)
115 }
116 w := &world{t: t, cfg: cfg, base: &swappable{}, mail: &mailbox{}, addrs: map[string]string{}}
117 h, err := web.App(d, cfg, w.mail, noInstaller{}, logger)
118 if err != nil {
119 t.Fatalf("web.App: %v", err)
120 }
121 w.base.set(h)
122 w.serve("base.test", w.base)
123
124 // Base's installs, seeded as the Installer would leave them.
125 for _, app := range []string{"scratchpad", "welcome"} {
126 _, host := install.HostFor(cfg, app)
127 if _, err := store.ClaimInstall(ctx, d.Writer(), app, host); err != nil {
128 t.Fatal(err)
129 }
130 if err := store.SetInstallState(ctx, d.Writer(), app, "installed", ""); err != nil {
131 t.Fatal(err)
132 }
133 ccfg := w.appConfig(app, host)
134 ad, err := db.Open(map[string]*dbtest.Template{"scratchpad": padSchema, "welcome": welSchema}[app].Path(t), logger)
135 if err != nil {
136 t.Fatal(err)
137 }
138 t.Cleanup(func() { ad.Close() })
139 var ah http.Handler
140 if app == "scratchpad" {
141 ah, err = scratchpad.App(ad, ccfg, logger)
142 } else {
143 ah, err = welcome.App(ad, ccfg, logger)
144 }
145 if err != nil {
146 t.Fatalf("%s.App: %v", app, err)
147 }
148 w.serve(host, ah)
149 }
150
151 jar, _ := cookiejar.New(nil)
152 tr := &http.Transport{
153 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
154 host, _, _ := net.SplitHostPort(addr)
155 to, ok := w.addrs[host]
156 if !ok {
157 return nil, &net.AddrError{Err: "no test server", Addr: addr}
158 }
159 return (&net.Dialer{}).DialContext(ctx, network, to)
160 },
161 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test servers' own certificate
162 }
163 t.Cleanup(tr.CloseIdleConnections)
164 w.browser = &http.Client{Jar: jar, Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
165 return w
166}
167
168// appConfig is the app's configuration from exactly what Base writes at install.
169func (w *world) appConfig(app, host string) consumer.Config {
170 w.t.Helper()
171 vars := install.AppVars(w.cfg, app, "https://"+host)
172 cfg, err := consumer.Load(func(k string) string { return vars[k] })
173 if err != nil {
174 w.t.Fatalf("consumer.Load for %s: %v", app, err)
175 }
176 return cfg
177}
178
179func (w *world) serve(host string, h http.Handler) {
180 srv := httptest.NewTLSServer(h) // 127.0.0.1 only
181 w.t.Cleanup(srv.Close)
182 w.addrs[host] = srv.Listener.Addr().String()
183}
184
185type resp struct {
186 Code int
187 Header http.Header
188 Body string
189}
190
191func (r resp) Location() string { return r.Header.Get("Location") }
192
193// do sends one request. A form is posted with the Origin a browser would
194// send: the origin of the page the form was on.
195func (w *world) do(method, target string, form url.Values, origin string) resp {
196 w.t.Helper()
197 var body io.Reader
198 if form != nil {
199 body = strings.NewReader(form.Encode())
200 }
201 req, err := http.NewRequest(method, target, body)
202 if err != nil {
203 w.t.Fatal(err)
204 }
205 if form != nil {
206 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
207 req.Header.Set("Origin", origin)
208 }
209 res, err := w.browser.Do(req)
210 if err != nil {
211 w.t.Fatal(err)
212 }
213 defer res.Body.Close()
214 raw, _ := io.ReadAll(res.Body)
215 return resp{res.StatusCode, res.Header, string(raw)}
216}
217
218func (w *world) get(target string) resp { w.t.Helper(); return w.do(http.MethodGet, target, nil, "") }
219
220// follow GETs target and every same-method redirect after it, resolving
221// relative locations, and returns the last response and its URL.
222func (w *world) follow(target string) (resp, string) {
223 w.t.Helper()
224 for range 10 {
225 r := w.get(target)
226 if r.Code != http.StatusSeeOther && r.Code != http.StatusFound {
227 return r, target
228 }
229 base, _ := url.Parse(target)
230 next, err := base.Parse(r.Location())
231 if err != nil {
232 w.t.Fatalf("bad redirect %q", r.Location())
233 }
234 target = next.String()
235 }
236 w.t.Fatalf("too many redirects at %s", target)
237 return resp{}, ""
238}
239
240var (
241 formRE = regexp.MustCompile(`(?s)<form[^>]*action="([^"]*)"[^>]*>(.*?)</form>`)
242 inputRE = regexp.MustCompile(`<input[^>]*>`)
243 attrRE = regexp.MustCompile(`(\w[\w-]*)="([^"]*)"`)
244 linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`)
245)
246
247// form returns the action and named inputs of the first form whose action
248// satisfies match.
249func form(t *testing.T, body string, match func(string) bool) (string, url.Values) {
250 t.Helper()
251 for _, m := range formRE.FindAllStringSubmatch(body, -1) {
252 action := html.UnescapeString(m[1])
253 if !match(action) {
254 continue
255 }
256 v := url.Values{}
257 for _, in := range inputRE.FindAllString(m[2], -1) {
258 attrs := map[string]string{}
259 for _, kv := range attrRE.FindAllStringSubmatch(in, -1) {
260 attrs[kv[1]] = html.UnescapeString(kv[2])
261 }
262 if attrs["name"] != "" {
263 v.Set(attrs["name"], attrs["value"])
264 }
265 }
266 return action, v
267 }
268 t.Fatalf("no matching form in:\n%s", body)
269 return "", nil
270}
271
272func is(want string) func(string) bool { return func(s string) bool { return s == want } }
273
274// signInToBase signs the browser in to Base with an emailed link (Ruling R3:
275// this suite's own helper, not webtest's).
276func (w *world) signInToBase(email string) {
277 w.t.Helper()
278 page := w.get(baseOrigin + "/signin?rec=1&force=1")
279 _, v := form(w.t, page.Body, is("/auth/begin"))
280 v.Set("address", email)
281 if r := w.do(http.MethodPost, baseOrigin+"/auth/begin", v, baseOrigin); r.Code != http.StatusSeeOther {
282 w.t.Fatalf("begin: %d %s", r.Code, r.Body)
283 }
284 link := linkRE.FindString(html.UnescapeString(w.mail.body()))
285 if link == "" {
286 w.t.Fatalf("no sign-in link in %q", w.mail.body())
287 }
288 confirm := w.get(link)
289 _, cv := form(w.t, confirm.Body, is("/auth/verify"))
290 if r := w.do(http.MethodPost, baseOrigin+"/auth/verify", cv, baseOrigin); r.Code != http.StatusSeeOther || r.Location() != "/" {
291 w.t.Fatalf("verify: %d %q", r.Code, r.Location())
292 }
293}
294
295// openApp opens an app as its Home tile does and goes through the handoff:
296// the app sends the browser to Base, Base answers with its handoff page,
297// and the browser submits that form to the app. It returns the app's page.
298func (w *world) openApp(origin string) resp {
299 w.t.Helper()
300 page, at := w.follow(origin + "/")
301 if !strings.HasPrefix(at, baseOrigin+"/authorize?") || page.Code != 200 {
302 w.t.Fatalf("opening %s ended at %s: %d\n%s", origin, at, page.Code, page.Body)
303 }
304 if got := page.Header.Get("Referrer-Policy"); got != "origin" {
305 w.t.Fatalf("handoff Referrer-Policy %q", got)
306 }
307 action, v := form(w.t, page.Body, is(origin+consumer.AssertionPath))
308 // With Referrer-Policy: origin the browser sends Base's origin (R21).
309 r := w.do(http.MethodPost, action, v, baseOrigin)
310 if r.Code != http.StatusSeeOther || r.Location() != consumer.FinishPath {
311 w.t.Fatalf("assertion post: %d %q %s", r.Code, r.Location(), r.Body)
312 }
313 final, at := w.follow(origin + r.Location())
314 if at != origin+"/" {
315 w.t.Fatalf("handoff ended at %s", at)
316 }
317 return final
318}
319
320const padOrigin = "https://acme-scratchpad.test"
321
322func TestHandoffEndToEnd(t *testing.T) {
323 w := newWorld(t)
324 if _, host := install.HostFor(w.cfg, "scratchpad"); "https://"+host != padOrigin {
325 t.Fatalf("Scratchpad's host is %s", host)
326 }
327 w.signInToBase(ownerAddress)
328
329 // Home's tile links straight to the app's origin.
330 home := w.get(baseOrigin + "/")
331 if !strings.Contains(home.Body, `href="`+padOrigin+`/"`) {
332 t.Fatalf("Home has no Scratchpad tile:\n%s", home.Body)
333 }
334 page := w.openApp(padOrigin)
335 if page.Code != 200 || !strings.Contains(page.Body, "Signed in as Paul, Acme Ltd") {
336 t.Fatalf("Scratchpad: %d\n%s", page.Code, page.Body)
337 }
338}
339
340func TestSessionOutlivesBase(t *testing.T) {
341 w := newWorld(t)
342 w.signInToBase(ownerAddress)
343 w.openApp(padOrigin)
344
345 w.base.set(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
346 http.Error(rw, "down", http.StatusServiceUnavailable)
347 }))
348 if r := w.get(baseOrigin + "/"); r.Code != http.StatusServiceUnavailable {
349 t.Fatalf("Base still answers: %d", r.Code)
350 }
351 r := w.get(padOrigin + "/")
352 if r.Code != 200 || !strings.Contains(r.Body, "Signed in as Paul, Acme Ltd") {
353 t.Fatalf("Scratchpad with Base down: %d\n%s", r.Code, r.Body)
354 }
355}
356
357func TestWelcomeEndToEnd(t *testing.T) {
358 w := newWorld(t)
359 w.signInToBase(ownerAddress)
360 page := w.openApp("https://acme-welcome.test")
361 if page.Code != 200 || !strings.Contains(page.Body, "Acme Ltd") || !strings.Contains(page.Body, "Paul") {
362 t.Fatalf("Welcome: %d\n%s", page.Code, page.Body)
363 }
364 if !strings.Contains(page.Body, `href="`+baseOrigin+`/"`) {
365 t.Errorf("Welcome has no link back to Home:\n%s", page.Body)
366 }
367}
368
369func TestAssertionForOneAppRefusedByAnother(t *testing.T) {
370 w := newWorld(t)
371 w.signInToBase(ownerAddress)
372 // Start a sign-in at Scratchpad, but take Welcome's assertion there.
373 _, at := w.follow(padOrigin + "/")
374 u, _ := url.Parse(at)
375 n := u.Query().Get("nonce")
376 page := w.get(baseOrigin + "/authorize?" + url.Values{"consumer": {"welcome"}, "nonce": {n}}.Encode())
377 _, v := form(t, page.Body, is("https://acme-welcome.test"+consumer.AssertionPath))
378 if r := w.do(http.MethodPost, padOrigin+consumer.AssertionPath, v, baseOrigin); r.Code == http.StatusSeeOther {
379 t.Fatalf("Scratchpad took Welcome's assertion")
380 }
381 w.get(padOrigin + consumer.FinishPath)
382 if r := w.get(padOrigin + "/"); r.Code == 200 {
383 t.Fatalf("signed in to Scratchpad with Welcome's assertion")
384 }
385}
386