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
3import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "fmt"
8 "html"
9 "io"
10 "log/slog"
11 "net/http"
12 "net/http/httptest"
13 "net/url"
14 "os"
15 "path/filepath"
16 "regexp"
17 "strings"
18 "sync"
19 "testing"
20 "time"
21
22 "amadan.net/oficina/calls/internal/calls/keymailtest"
23 "amadan.net/oficina/home/connect"
24 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
25 "amadan.net/rastrillo/rastrillo/db"
26)
27
28// TestMain keeps Keymail classification inside the process: every DNS
29// query is answered NXDOMAIN and only the Keymail fixtures a test
30// registers answer HTTPS (keymailtest).
31func TestMain(m *testing.M) {
32 restore, err := keymailtest.Install()
33 if err != nil {
34 fmt.Fprintln(os.Stderr, "keymailtest.Install:", err)
35 os.Exit(1)
36 }
37 code := m.Run()
38 // No test may leave a sign-in mail worker running: every app a test
39 // builds has its queue closed in cleanup (Runtime.Close, a
40 // TestHandle's stop, or buildForTest).
41 if code == 0 {
42 deadline := time.Now().Add(5 * time.Second)
43 for mailWorkers() > 0 && time.Now().Before(deadline) {
44 time.Sleep(10 * time.Millisecond)
45 }
46 if n := mailWorkers(); n > 0 {
47 fmt.Fprintf(os.Stderr, "FAIL: %d sign-in mail queue goroutines still running after the tests\n", n)
48 code = 1
49 }
50 }
51 restore()
52 os.Exit(code)
53}
54
55const (
56 keymailHost = "keymail.calls.test"
57 keymailMember = "paul@" + keymailHost
58 keymailStranger = "stranger@" + keymailHost
59 plainMember = "paul@example.test"
60 keymailOrigin = "https://calls.example.test"
61)
62
63type countingMailer struct {
64 mu sync.Mutex
65 to []string
66 waits []func() // the sign-in mail queues in front of it
67}
68
69func (m *countingMailer) AttachSigninQueue(wait func()) {
70 m.mu.Lock()
71 m.waits = append(m.waits, wait)
72 m.mu.Unlock()
73}
74
75func (m *countingMailer) Send(_ context.Context, to, _, _ string) error {
76 m.mu.Lock()
77 defer m.mu.Unlock()
78 m.to = append(m.to, to)
79 return nil
80}
81
82func (m *countingMailer) sent() []string {
83 m.mu.Lock()
84 waits := append([]func(){}, m.waits...)
85 m.mu.Unlock()
86 for _, w := range waits {
87 w()
88 }
89 m.mu.Lock()
90 defer m.mu.Unlock()
91 return append([]string(nil), m.to...)
92}
93
94type keymailFixture struct {
95 handler http.Handler
96 mail *countingMailer
97 km *keymailtest.Server
98}
99
100// newKeymailFixture builds Calls with plainMember and keymailMember on
101// the allowlist, beside a Keymail deployment holding keymailMember and
102// keymailStranger; home configures Home sign-in.
103func newKeymailFixture(t *testing.T, home bool) *keymailFixture {
104 t.Helper()
105 km := keymailtest.Serve(t, keymailHost, keymailMember, keymailStranger)
106 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
107 d, err := db.Open(filepath.Join(t.TempDir(), "calls.db"), logger)
108 if err != nil {
109 t.Fatal(err)
110 }
111 t.Cleanup(func() { d.Close() })
112 mail := &countingMailer{}
113 cfg := Config{Origin: keymailOrigin, InstanceKey: "test-only-instance", DEK: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)),
114 AllowedAddresses: []string{plainMember, keymailMember}, Mailer: mail, Logger: logger}
115 if home {
116 key, err := assertioncrypto.Generate()
117 if err != nil {
118 t.Fatal(err)
119 }
120 cfg.Home = &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: "calls-test", KeysBase64: homeKeysBase64(key), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))}
121 }
122 mux, _, err := buildForTest(t, d, cfg)
123 if err != nil {
124 t.Fatal(err)
125 }
126 return &keymailFixture{handler: mux, mail: mail, km: km}
127}
128
129func (f *keymailFixture) post(form url.Values, cookies ...*http.Cookie) *httptest.ResponseRecorder {
130 r := httptest.NewRequest(http.MethodPost, keymailOrigin+"/signin", strings.NewReader(form.Encode()))
131 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
132 r.Header.Set("Origin", keymailOrigin)
133 r.Header.Set("Sec-Fetch-Site", "same-origin")
134 for _, c := range cookies {
135 r.AddCookie(c)
136 }
137 w := httptest.NewRecorder()
138 f.handler.ServeHTTP(w, r)
139 return w
140}
141
142func (f *keymailFixture) get(path string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
143 r := httptest.NewRequest(http.MethodGet, keymailOrigin+path, nil)
144 for _, c := range cookies {
145 r.AddCookie(c)
146 }
147 w := httptest.NewRecorder()
148 f.handler.ServeHTTP(w, r)
149 return w
150}
151
152var authorizeHref = regexp.MustCompile(`href="(https://` + regexp.QuoteMeta(keymailHost) + `/oauth/authorize\?[^"]+)"`)
153
154// continuation asserts rec is the way from the form to Keymail: never a
155// 303 out of the form POST (Safari applies form-action to that redirect),
156// but a 303 to the door's own continuation (/signin?continue=), which is a
157// 200 document with a meta refresh to Keymail. It returns the authorize
158// URL that page carries, and the page.
159func continuation(t *testing.T, f *keymailFixture, label string, rec *httptest.ResponseRecorder) (*url.URL, *httptest.ResponseRecorder) {
160 t.Helper()
161 loc := rec.Header().Get("Location")
162 if rec.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "/signin?continue=") {
163 t.Fatalf("%s: %d %q, want 303 to the door's Keymail continuation", label, rec.Code, loc)
164 }
165 page := f.get(loc, rec.Result().Cookies()...)
166 if page.Code != http.StatusOK {
167 t.Fatalf("%s: the continuation = %d %q", label, page.Code, page.Header().Get("Location"))
168 }
169 body := page.Body.String()
170 m := authorizeHref.FindStringSubmatch(body)
171 if m == nil || !strings.Contains(body, `http-equiv="refresh"`) {
172 t.Fatalf("%s: no Keymail continuation on the page:\n%s", label, body)
173 }
174 u, err := url.Parse(html.UnescapeString(m[1]))
175 if err != nil {
176 t.Fatal(err)
177 }
178 return u, page
179}
180
181// sentAnswer reports whether loc is Begin's Sent: /signin?sent=1 with the
182// attempt rastrillo's screen names the address by (attempt=, different
183// every time, and the same shape for any address).
184func sentAnswer(loc string) bool {
185 u, err := url.Parse(loc)
186 if err != nil || u.Path != "/signin" {
187 return false
188 }
189 q := u.Query()
190 attempt := q.Get("attempt")
191 q.Del("attempt")
192 return q.Encode() == "sent=1" && attempt != ""
193}
194
195// TestKeymailAddressGoesToKeymailWhetherPermittedOrNot: in both modes,
196// whether an address goes to Keymail depends on its domain alone. A
197// member and a stranger at a Keymail domain get the same first answer,
198// the continuation page, and neither is mailed. Before, gateBegin set
199// force=1 on every member's POST, so Keymail was never used.
200func TestKeymailAddressGoesToKeymailWhetherPermittedOrNot(t *testing.T) {
201 for _, home := range []bool{false, true} {
202 t.Run(fmt.Sprintf("home=%v", home), func(t *testing.T) {
203 f := newKeymailFixture(t, home)
204 member := f.post(url.Values{"address": {keymailMember}})
205 stranger := f.post(url.Values{"address": {keymailStranger}})
206 mu, mp := continuation(t, f, "member Keymail address", member)
207 su, sp := continuation(t, f, "stranger Keymail address", stranger)
208 mask := func(rec *httptest.ResponseRecorder, u *url.URL) string {
209 return strings.ReplaceAll(rec.Body.String(), html.EscapeString(u.String()), "AUTHORIZE")
210 }
211 if a, b := mask(mp, mu), mask(sp, su); a != b {
212 t.Errorf("the two Keymail answers differ beyond the authorize URL:\n%s\n----\n%s", a, b)
213 }
214 if got := f.mail.sent(); len(got) != 0 {
215 t.Errorf("a Keymail address was mailed: %v", got)
216 }
217 if n := f.km.Lookups(); n != 2 {
218 t.Errorf("Keymail saw %d lookups, want 2", n)
219 }
220 })
221 }
222}
223
224// TestNonPermittedPlainAddressIsAnsweredSentAndNotMailed: an address
225// with no Keymail gets ?sent=1, member or not; only the member is
226// mailed.
227func TestNonPermittedPlainAddressIsAnsweredSentAndNotMailed(t *testing.T) {
228 f := newKeymailFixture(t, false)
229 for _, address := range []string{"someone@else.test", plainMember} {
230 rec := f.post(url.Values{"address": {address}})
231 if rec.Code != http.StatusSeeOther || !sentAnswer(rec.Header().Get("Location")) {
232 t.Fatalf("POST /signin %q: %d %q, want 303 /signin?sent=1", address, rec.Code, rec.Header().Get("Location"))
233 }
234 }
235 if got := f.mail.sent(); len(got) != 1 || got[0] != plainMember {
236 t.Fatalf("mail = %v, want one, to %s", got, plainMember)
237 }
238}
239
240// TestKeymailFailureFallsBackToAnEmailLink: the page rastrillo lands a
241// failed Keymail exchange on (?force=1&err=keymail) carries force, so
242// the retry mails a link instead of returning to Keymail; the ordinary
243// form carries none.
244func TestKeymailFailureFallsBackToAnEmailLink(t *testing.T) {
245 f := newKeymailFixture(t, false)
246 forced := `name="force" value="1"`
247 if strings.Contains(f.get("/signin").Body.String(), forced) {
248 t.Fatal("the ordinary form forces an email link")
249 }
250 if !strings.Contains(f.get("/signin?force=1&err=keymail").Body.String(), forced) {
251 t.Fatal("the err=keymail form does not carry force; a failed Keymail sign-in would loop back to Keymail")
252 }
253 rec := f.post(url.Values{"address": {keymailMember}, "force": {"1"}})
254 if rec.Code != http.StatusSeeOther || !sentAnswer(rec.Header().Get("Location")) {
255 t.Fatalf("forced POST: %d %q", rec.Code, rec.Header().Get("Location"))
256 }
257 if got := f.mail.sent(); len(got) != 1 || got[0] != keymailMember {
258 t.Fatalf("mail = %v, want one link to %s", got, keymailMember)
259 }
260 if f.km.Lookups() != 0 {
261 t.Error("a forced sign-in classified the address")
262 }
263}
264
265// TestKeymailRefusalIsTheDoor: a stranger Keymail verified is refused
266// after verification on the door, with the form for a different
267// address, not in rastrillo's bare text; a member is signed in. Both
268// modes.
269func TestKeymailRefusalIsTheDoor(t *testing.T) {
270 for _, home := range []bool{false, true} {
271 t.Run(fmt.Sprintf("home=%v", home), func(t *testing.T) {
272 f := newKeymailFixture(t, home)
273 form := "/signin"
274 if home {
275 form = "/signin/local"
276 }
277 roundTrip := func(address string) *httptest.ResponseRecorder {
278 begin := f.post(url.Values{"address": {address}})
279 u, page := continuation(t, f, address, begin)
280 return f.get("/auth/callback?"+url.Values{"state": {u.Query().Get("state")}, "code": {f.km.Approve(address)}}.Encode(), append(begin.Result().Cookies(), page.Result().Cookies()...)...)
281 }
282 cb := roundTrip(keymailMember)
283 if cb.Code != http.StatusSeeOther || strings.Contains(cb.Header().Get("Location"), "err=") {
284 t.Fatalf("member callback: %d %q", cb.Code, cb.Header().Get("Location"))
285 }
286 // The member's session, carried through the landing redirects
287 // (/auth/local/complete with Home, then /continue), opens the
288 // meeting list: the continuation signed them in for real.
289 jar := map[string]*http.Cookie{}
290 keep := func(w *httptest.ResponseRecorder) {
291 for _, c := range w.Result().Cookies() {
292 if c.MaxAge < 0 {
293 delete(jar, c.Name)
294 } else {
295 jar[c.Name] = c
296 }
297 }
298 }
299 keep(cb)
300 next := cb.Header().Get("Location")
301 var landed *httptest.ResponseRecorder
302 for range 4 {
303 cookies := make([]*http.Cookie, 0, len(jar))
304 for _, c := range jar {
305 cookies = append(cookies, c)
306 }
307 landed = f.get(next, cookies...)
308 keep(landed)
309 if landed.Code != http.StatusSeeOther {
310 break
311 }
312 next = landed.Header().Get("Location")
313 }
314 if landed.Code != http.StatusOK || !strings.Contains(landed.Body.String(), "Meetings") {
315 t.Fatalf("member's Keymail session landed on %s with %d, want the meeting list", next, landed.Code)
316 }
317 cb = roundTrip(keymailStranger)
318 if cb.Code != http.StatusForbidden || cb.Header().Get("Location") != "" {
319 t.Fatalf("stranger callback: %d %q, want 403 and the door itself (bare text is the bug)\n%s", cb.Code, cb.Header().Get("Location"), cb.Body.String())
320 }
321 door := cb.Body.String()
322 for _, want := range []string{"estilo-door", `name="address"`, signinRefusal} {
323 if !strings.Contains(door, want) {
324 t.Errorf("refusal door lacks %q:\n%s", want, door)
325 }
326 }
327 // Nobody may summon the sentence by typing a URL (Astra, round 3).
328 if spoof := f.get(form + "?err=refused").Body.String(); strings.Contains(spoof, "can’t sign in to Calls") {
329 t.Fatalf("anybody can show the refusal by visiting %s?err=refused", form)
330 }
331 })
332 }
333}
334