oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calls
2
3// Helpers for the smart door's tests (signin_door_*_test.go): a browser on
4// an instance with Home or without, its remembered way in, its sessions.
5
6import (
7 "bytes"
8 "encoding/base64"
9 "html"
10 "io"
11 "log/slog"
12 "net/http"
13 "net/http/httptest"
14 "net/url"
15 "path/filepath"
16 "regexp"
17 "strings"
18 "testing"
19 "time"
20
21 "amadan.net/oficina/home/connect"
22 rauth "amadan.net/rastrillo/rastrillo/auth"
23 "amadan.net/rastrillo/rastrillo/db"
24 "amadan.net/rastrillo/rastrillo/lastsignin"
25 "amadan.net/rastrillo/rastrillo/sessions"
26)
27
28// newStandaloneDoor is homeRouterFixture's browser on an instance without
29// Home: email is the only way in, and alice@example.test the one member.
30// The origin is https, so the door's __Host- cookies behave as in
31// production.
32func newStandaloneDoor(t *testing.T) *homeRouterFixture {
33 t.Helper()
34 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
35 d, err := db.Open(filepath.Join(t.TempDir(), "calls.db"), logger)
36 if err != nil {
37 t.Fatal(err)
38 }
39 t.Cleanup(func() { d.Close() })
40 mail := &homeTestMail{}
41 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})
42 if err != nil {
43 t.Fatal(err)
44 }
45 return &homeRouterFixture{a, mux, nil, mail, map[string]*http.Cookie{}}
46}
47
48// doorModes runs fn once with Home and once without.
49func doorModes(t *testing.T, fn func(t *testing.T, f *homeRouterFixture)) {
50 t.Run("home", func(t *testing.T) { fn(t, newHomeRouterFixture(t)) })
51 t.Run("standalone", func(t *testing.T) { fn(t, newStandaloneDoor(t)) })
52}
53
54// fresh is another browser on f's app: the same instance, an empty jar.
55func (f *homeRouterFixture) fresh() *homeRouterFixture {
56 return &homeRouterFixture{f.app, f.handler, f.key, f.mail, map[string]*http.Cookie{}}
57}
58
59// get is do("GET", path, "").
60func (f *homeRouterFixture) get(path string) *httptest.ResponseRecorder {
61 return f.do(http.MethodGet, path, "")
62}
63
64// remember gives the browser a remembered way in, sealed by Calls' own
65// jar, as rastrillo would have after a sign-in.
66func (f *homeRouterFixture) remember(t *testing.T, rec lastsignin.Record) {
67 t.Helper()
68 w := httptest.NewRecorder()
69 f.app.auth.RememberJar().Remember(w, rec)
70 cookies := w.Result().Cookies()
71 if len(cookies) != 1 {
72 t.Fatalf("the jar refused %+v", rec)
73 }
74 f.cookies[cookies[0].Name] = cookies[0]
75}
76
77// remembered is the browser's remembered way in, read by Calls' jar.
78func (f *homeRouterFixture) remembered() (lastsignin.Record, lastsignin.ReadResult) {
79 return f.app.auth.RememberJar().Read(f.jarRequest())
80}
81
82// returnPath is the page the browser's return memory holds, "" for none.
83func (f *homeRouterFixture) returnPath() string {
84 p, _ := f.app.rememberedReturn(f.jarRequest())
85 return p
86}
87
88func (f *homeRouterFixture) jarRequest() *http.Request {
89 r := httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil)
90 for _, c := range f.cookies {
91 r.AddCookie(c)
92 }
93 return r
94}
95
96// session puts a session for subject, signed in by method, in the jar, as
97// a finished sign-in would, verified at authTime.
98func (f *homeRouterFixture) session(t *testing.T, subject, method string, authTime time.Time) {
99 t.Helper()
100 w := httptest.NewRecorder()
101 if err := f.app.nativeAuth.sessions.SignIn(w, httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil), sessions.Session{Subject: subject, Method: method, AuthTime: authTime}); err != nil {
102 t.Fatal(err)
103 }
104 for _, c := range w.Result().Cookies() {
105 f.cookies[c.Name] = c
106 }
107}
108
109// sessionCookie is the session cookie in the jar, or nil.
110func (f *homeRouterFixture) sessionCookie() *http.Cookie {
111 return f.cookies[f.app.sessionCookie()]
112}
113
114// liveSession reports whether value is a session cookie that still
115// resolves.
116func (f *homeRouterFixture) liveSession(value string) bool {
117 r := httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil)
118 r.AddCookie(&http.Cookie{Name: f.app.sessionCookie(), Value: value})
119 _, ok := f.app.nativeAuth.sessions.From(r)
120 return ok
121}
122
123// signinLink is the emailed sign-in link in the last mail, as a path.
124var signinLink = regexp.MustCompile(`https://[^\s<>"]+/auth/verify\?[^\s<>"]+`)
125
126// emailSignin signs the browser in by the emailed link, posting form to
127// the door, and returns where it lands: the page /continue sends it to.
128func (f *homeRouterFixture) emailSignin(t *testing.T, form url.Values) string {
129 t.Helper()
130 f.mail.body = ""
131 if w := f.do(http.MethodPost, "/signin", form.Encode()); w.Code != http.StatusSeeOther {
132 t.Fatalf("POST /signin: %d", w.Code)
133 }
134 link := signinLink.FindString(f.mailBody())
135 if link == "" {
136 t.Fatal("no sign-in link mailed")
137 }
138 verify := f.followLink(t, link)
139 next := homeRedirect(t, verify)
140 for range 4 {
141 if next != connect.LocalCompletePath && next != "/continue" {
142 return next
143 }
144 next = homeRedirect(t, f.get(next))
145 }
146 t.Fatalf("the landing never settled: %q", next)
147 return ""
148}
149
150// oficinaSignin runs Continue with Oficina ID for subject from path, and
151// returns the exchange's last answer.
152func (f *homeRouterFixture) oficinaSignin(t *testing.T, path, subject string) *httptest.ResponseRecorder {
153 t.Helper()
154 start := f.get(path)
155 if start.Code != http.StatusSeeOther || !strings.HasPrefix(start.Header().Get("Location"), "/auth/start") {
156 t.Fatalf("GET %s: %d %q, want the Home exchange", path, start.Code, start.Header().Get("Location"))
157 }
158 return f.exchange(t, start.Header().Get("Location"), subject)
159}
160
161// redirectsTo fails unless rec is a 303 to want.
162func redirectsTo(t *testing.T, rec *httptest.ResponseRecorder, want string) {
163 t.Helper()
164 if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != want {
165 t.Fatalf("got %d %q, want 303 %q", rec.Code, rec.Header().Get("Location"), want)
166 }
167}
168
169// door is the sign-in card's own content: rastrillo's section inside
170// estilo-signin-screen, unescaped, followed by its text alone (the markup
171// taken out, so "Continue as <bdi>x</bdi>" reads "Continue as x").
172func door(t *testing.T, body string) string {
173 t.Helper()
174 start := strings.Index(body, "<div estilo-signin-screen>")
175 if start < 0 {
176 t.Fatalf("no estilo-signin-screen:\n%s", body)
177 }
178 end := strings.Index(body[start:], "</section>")
179 card := html.UnescapeString(body[start : start+end])
180 return card + "\n" + regexp.MustCompile(`<[^>]*>`).ReplaceAllString(card, "")
181}
182
183// titleOf is the page's <title>, unescaped.
184func titleOf(t *testing.T, body string) string {
185 t.Helper()
186 m := regexp.MustCompile(`<title>([^<]*)</title>`).FindStringSubmatch(body)
187 if m == nil {
188 t.Fatalf("no <title>:\n%s", body)
189 }
190 return html.UnescapeString(m[1])
191}
192
193// clears reports whether rec clears the named cookie.
194func clears(rec *httptest.ResponseRecorder, name string) bool {
195 for _, c := range rec.Result().Cookies() {
196 if c.Name == name && c.MaxAge < 0 {
197 return true
198 }
199 }
200 return false
201}
202
203// sets reports whether rec sets the named cookie to a value.
204func sets(rec *httptest.ResponseRecorder, name string) bool {
205 for _, c := range rec.Result().Cookies() {
206 if c.Name == name && c.MaxAge >= 0 && c.Value != "" {
207 return true
208 }
209 }
210 return false
211}
212
213// What the door's markup says, for the tests to look for.
214const (
215 oficinaButton = "Continue with Oficina ID"
216 otherWays = "Other ways to sign in"
217 emailField = `id="rst-signin-email" name="address"`
218 appProblem = `id="rst-signin-app-problem"`
219)
220
221// rauthIdentity is a verified address, as auth hands its Refused hook.
222func rauthIdentity(address string) rauth.Identity { return rauth.Identity{Address: address} }
223