package calls // Helpers for the smart door's tests (signin_door_*_test.go): a browser on // an instance with Home or without, its remembered way in, its sessions. import ( "bytes" "encoding/base64" "html" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "regexp" "strings" "testing" "time" "amadan.net/oficina/home/connect" rauth "amadan.net/rastrillo/rastrillo/auth" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/lastsignin" "amadan.net/rastrillo/rastrillo/sessions" ) // newStandaloneDoor is homeRouterFixture's browser on an instance without // Home: email is the only way in, and alice@example.test the one member. // The origin is https, so the door's __Host- cookies behave as in // production. func newStandaloneDoor(t *testing.T) *homeRouterFixture { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "calls.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) mail := &homeTestMail{} mux, a, err := buildForTest(t, d, Config{Origin: homeTestOrigin, InstanceKey: "test-only-instance", DEK: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)), AllowedAddresses: []string{"alice@example.test"}, Mailer: mail, Logger: logger}) if err != nil { t.Fatal(err) } return &homeRouterFixture{a, mux, nil, mail, map[string]*http.Cookie{}} } // doorModes runs fn once with Home and once without. func doorModes(t *testing.T, fn func(t *testing.T, f *homeRouterFixture)) { t.Run("home", func(t *testing.T) { fn(t, newHomeRouterFixture(t)) }) t.Run("standalone", func(t *testing.T) { fn(t, newStandaloneDoor(t)) }) } // fresh is another browser on f's app: the same instance, an empty jar. func (f *homeRouterFixture) fresh() *homeRouterFixture { return &homeRouterFixture{f.app, f.handler, f.key, f.mail, map[string]*http.Cookie{}} } // get is do("GET", path, ""). func (f *homeRouterFixture) get(path string) *httptest.ResponseRecorder { return f.do(http.MethodGet, path, "") } // remember gives the browser a remembered way in, sealed by Calls' own // jar, as rastrillo would have after a sign-in. func (f *homeRouterFixture) remember(t *testing.T, rec lastsignin.Record) { t.Helper() w := httptest.NewRecorder() f.app.auth.RememberJar().Remember(w, rec) cookies := w.Result().Cookies() if len(cookies) != 1 { t.Fatalf("the jar refused %+v", rec) } f.cookies[cookies[0].Name] = cookies[0] } // remembered is the browser's remembered way in, read by Calls' jar. func (f *homeRouterFixture) remembered() (lastsignin.Record, lastsignin.ReadResult) { return f.app.auth.RememberJar().Read(f.jarRequest()) } // returnPath is the page the browser's return memory holds, "" for none. func (f *homeRouterFixture) returnPath() string { p, _ := f.app.rememberedReturn(f.jarRequest()) return p } func (f *homeRouterFixture) jarRequest() *http.Request { r := httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil) for _, c := range f.cookies { r.AddCookie(c) } return r } // session puts a session for subject, signed in by method, in the jar, as // a finished sign-in would, verified at authTime. func (f *homeRouterFixture) session(t *testing.T, subject, method string, authTime time.Time) { t.Helper() w := httptest.NewRecorder() if err := f.app.nativeAuth.sessions.SignIn(w, httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil), sessions.Session{Subject: subject, Method: method, AuthTime: authTime}); err != nil { t.Fatal(err) } for _, c := range w.Result().Cookies() { f.cookies[c.Name] = c } } // sessionCookie is the session cookie in the jar, or nil. func (f *homeRouterFixture) sessionCookie() *http.Cookie { return f.cookies[f.app.sessionCookie()] } // liveSession reports whether value is a session cookie that still // resolves. func (f *homeRouterFixture) liveSession(value string) bool { r := httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil) r.AddCookie(&http.Cookie{Name: f.app.sessionCookie(), Value: value}) _, ok := f.app.nativeAuth.sessions.From(r) return ok } // signinLink is the emailed sign-in link in the last mail, as a path. var signinLink = regexp.MustCompile(`https://[^\s<>"]+/auth/verify\?[^\s<>"]+`) // emailSignin signs the browser in by the emailed link, posting form to // the door, and returns where it lands: the page /continue sends it to. func (f *homeRouterFixture) emailSignin(t *testing.T, form url.Values) string { t.Helper() f.mail.body = "" if w := f.do(http.MethodPost, "/signin", form.Encode()); w.Code != http.StatusSeeOther { t.Fatalf("POST /signin: %d", w.Code) } link := signinLink.FindString(f.mailBody()) if link == "" { t.Fatal("no sign-in link mailed") } verify := f.followLink(t, link) next := homeRedirect(t, verify) for range 4 { if next != connect.LocalCompletePath && next != "/continue" { return next } next = homeRedirect(t, f.get(next)) } t.Fatalf("the landing never settled: %q", next) return "" } // oficinaSignin runs Continue with Oficina ID for subject from path, and // returns the exchange's last answer. func (f *homeRouterFixture) oficinaSignin(t *testing.T, path, subject string) *httptest.ResponseRecorder { t.Helper() start := f.get(path) if start.Code != http.StatusSeeOther || !strings.HasPrefix(start.Header().Get("Location"), "/auth/start") { t.Fatalf("GET %s: %d %q, want the Home exchange", path, start.Code, start.Header().Get("Location")) } return f.exchange(t, start.Header().Get("Location"), subject) } // redirectsTo fails unless rec is a 303 to want. func redirectsTo(t *testing.T, rec *httptest.ResponseRecorder, want string) { t.Helper() if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != want { t.Fatalf("got %d %q, want 303 %q", rec.Code, rec.Header().Get("Location"), want) } } // door is the sign-in card's own content: rastrillo's section inside // estilo-signin-screen, unescaped, followed by its text alone (the markup // taken out, so "Continue as x" reads "Continue as x"). func door(t *testing.T, body string) string { t.Helper() start := strings.Index(body, "
") if start < 0 { t.Fatalf("no estilo-signin-screen:\n%s", body) } end := strings.Index(body[start:], "") card := html.UnescapeString(body[start : start+end]) return card + "\n" + regexp.MustCompile(`<[^>]*>`).ReplaceAllString(card, "") } // titleOf is the page's , unescaped. func titleOf(t *testing.T, body string) string { t.Helper() m := regexp.MustCompile(`<title>([^<]*)`).FindStringSubmatch(body) if m == nil { t.Fatalf("no :\n%s", body) } return html.UnescapeString(m[1]) } // clears reports whether rec clears the named cookie. func clears(rec *httptest.ResponseRecorder, name string) bool { for _, c := range rec.Result().Cookies() { if c.Name == name && c.MaxAge < 0 { return true } } return false } // sets reports whether rec sets the named cookie to a value. func sets(rec *httptest.ResponseRecorder, name string) bool { for _, c := range rec.Result().Cookies() { if c.Name == name && c.MaxAge >= 0 && c.Value != "" { return true } } return false } // What the door's markup says, for the tests to look for. const ( oficinaButton = "Continue with Oficina ID" otherWays = "Other ways to sign in" emailField = `id="rst-signin-email" name="address"` appProblem = `id="rst-signin-app-problem"` ) // rauthIdentity is a verified address, as auth hands its Refused hook. func rauthIdentity(address string) rauth.Identity { return rauth.Identity{Address: address} }