package fichastest // Helpers for the smart door's tests (signin_door_*_test.go): a browser's // cookie jar over httptest, a sign-in walked the way a person walks it, // and a second app over the same database with a different owners list, // which is how a session or a link for an address taken off FICHAS_OWNERS // is made from the outside. import ( "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "regexp" "strings" "testing" fichas "amadan.net/oficina/fichas/internal/fichas" "amadan.net/rastrillo/rastrillo/db" ) // TestOther is a second address, an owner of the wider instance only. const TestOther = "bo@example.com" // browser is a cookie jar: what a browser would send back. type browser struct { cookies map[string]*http.Cookie } func newBrowser() *browser { return &browser{cookies: map[string]*http.Cookie{}} } // keep applies a response's Set-Cookie headers as a browser would. func (b *browser) keep(rec *httptest.ResponseRecorder) { for _, c := range rec.Result().Cookies() { if c.MaxAge < 0 || c.Value == "" { delete(b.cookies, c.Name) continue } b.cookies[c.Name] = c } } func (b *browser) has(name string) bool { _, ok := b.cookies[name]; return ok } func (b *browser) send(req *http.Request) { for _, c := range b.cookies { req.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value}) } } func (b *browser) get(t *testing.T, h http.Handler, target string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodGet, target, nil) b.send(req) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) b.keep(rec) return rec } func (b *browser) post(t *testing.T, h http.Handler, target string, form url.Values) *httptest.ResponseRecorder { t.Helper() return b.postRaw(t, h, target, form.Encode()) } // postRaw posts body as it is, so a test can send one that does not parse. func (b *browser) postRaw(t *testing.T, h http.Handler, target, body string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body)) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", testOrigin) b.send(req) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) b.keep(rec) return rec } // crossSitePost is a form post from another site, carrying b's cookies. func crossSitePost(t *testing.T, h http.Handler, b *browser, target string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodPost, target, strings.NewReader("")) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", "https://evil.example") req.Header.Set("Sec-Fetch-Site", "cross-site") b.send(req) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) b.keep(rec) return rec } // getWith is a GET carrying cookies. func getWith(t *testing.T, h http.Handler, target string, cookies []*http.Cookie) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodGet, target, nil) for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } // cookie names, as auth names them on testOrigin (http, so no __Host-). const ( sessionCookie = "rastrillo_session" returnCookie = "rastrillo_return_to" rememberName = "rastrillo_last_signin" ) // sharedApps is two apps over one database, as main.go wires them, with // the same keys: wide admits TestOwner and TestOther, narrow TestOwner // only. A link sent by wide and opened on narrow, or a session minted by // wide and presented to narrow, is an address taken off the owners list. func sharedApps(t *testing.T) (wide, narrow http.Handler, mailer *capturingMailer, d *db.DB) { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) mailer = &capturingMailer{} build := func(owners ...string) http.Handler { cfg := testConfig(t) cfg.Owners = owners mux, app, err := fichas.App(d, cfg, logger) if err != nil { t.Fatalf("App: %v", err) } au, err := fichas.NewAuth(d.Writer(), fichas.AuthEnv{Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: mailer}, logger, app) if err != nil { t.Fatalf("NewAuth: %v", err) } app.UseAuth(au) return mux } return build(TestOwner, TestOther), build(TestOwner), mailer, d } // linkFor asks h for a link to address (force=1: no classifier, no dial) // and returns the emailed token. func linkFor(t *testing.T, h http.Handler, b *browser, m *capturingMailer, address string, extra url.Values) string { t.Helper() form := url.Values{"address": {address}, "force": {"1"}} for k, v := range extra { form[k] = v } rec := b.post(t, h, "/auth/begin", form) if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/signin?sent=1&attempt=") { t.Fatalf("POST /auth/begin: %d %q", rec.Code, rec.Header().Get("Location")) } mail := m.last(t) if !strings.HasPrefix(mail, address+"\n") { t.Fatalf("the last mail went elsewhere:\n%s", mail) } match := linkToken.FindStringSubmatch(mail) if match == nil { t.Fatalf("no link in:\n%s", mail) } tok, err := url.QueryUnescape(match[1]) if err != nil { t.Fatal(err) } return tok } // signIn walks the email path in b on h, link to landing, and returns the // landing's answer. func signIn(t *testing.T, h http.Handler, b *browser, m *capturingMailer, address string, extra url.Values) *httptest.ResponseRecorder { t.Helper() tok := linkFor(t, h, b, m, address, extra) return b.post(t, h, "/auth/verify", url.Values{"token": {tok}}) } var titleRE = regexp.MustCompile(`