oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "context"
5 "html"
6 "net/http"
7 "net/http/httptest"
8 "net/url"
9 "path/filepath"
10 "regexp"
11 "strings"
12 "sync"
13 "testing"
14
15 rdb "amadan.net/rastrillo/rastrillo/db"
16 "amadan.net/rastrillo/rastrillo/migrate"
17
18 "amadan.net/oficina/sheets/internal/sheets/seal"
19)
20
21// recorder is a mail.Sender that delivers nothing and remembers who it
22// was asked to write to.
23type recorder struct {
24 mu sync.Mutex
25 sent []string
26 bodies []string
27 // waits are the sign-in mail queues in front of this recorder:
28 // links go out after the response (mailqueue.go), so every read
29 // waits for them first.
30 waits []func()
31}
32
33func (m *recorder) attachQueue(wait func()) {
34 m.mu.Lock()
35 m.waits = append(m.waits, wait)
36 m.mu.Unlock()
37}
38
39func (m *recorder) flush() {
40 m.mu.Lock()
41 waits := append([]func(){}, m.waits...)
42 m.mu.Unlock()
43 for _, w := range waits {
44 w()
45 }
46}
47
48func (m *recorder) Send(_ context.Context, to, _, body string) error {
49 m.mu.Lock()
50 defer m.mu.Unlock()
51 m.sent = append(m.sent, to)
52 m.bodies = append(m.bodies, body)
53 return nil
54}
55
56// lastLink pulls the verify URL out of the most recent email.
57func (m *recorder) lastLink(t *testing.T) string {
58 t.Helper()
59 m.flush()
60 m.mu.Lock()
61 defer m.mu.Unlock()
62 if len(m.bodies) == 0 {
63 t.Fatal("no mail was sent")
64 }
65 link := regexp.MustCompile(`https?://\S*/auth/verify\?\S+`).
66 FindString(m.bodies[len(m.bodies)-1])
67 if link == "" {
68 t.Fatalf("no verify link in mail body: %q", m.bodies[len(m.bodies)-1])
69 }
70 return strings.TrimRight(link, ".,)\"'>")
71}
72
73func (m *recorder) addresses() []string {
74 m.flush()
75 m.mu.Lock()
76 defer m.mu.Unlock()
77 return append([]string(nil), m.sent...)
78}
79
80const testOrigin = "https://sheets.example.com"
81
82// appWithRecorder builds a signed-in-capable app whose CSRF check is
83// off, because Config.Origin is empty. Most tests want that: they post
84// forms without faking a browser's Sec-Fetch-Site header on every
85// request. appWithOrigin is the protected shape, and
86// TestCSRFRefusesACrossOriginPost is what exercises it.
87func appWithRecorder(t *testing.T) (*App, *recorder) {
88 t.Helper()
89 return appWithOrigin(t, "")
90}
91
92func appWithOrigin(t *testing.T, origin string) (*App, *recorder) {
93 t.Helper()
94 return appWithOwners(t, origin, signedInAddress)
95}
96
97// appWithOwners is appWithOrigin with the SHEETS_OWNERS list spelled out.
98func appWithOwners(t *testing.T, origin string, owners ...string) (*App, *recorder) {
99 t.Helper()
100 return appWithSchema(t, origin, BootSchema, owners...)
101}
102
103// appWithSchema is appWithOwners over a chosen boot schema: team mode's
104// fixture applies TeamBootSchema, as main does when SHEETS_TEAM_* is set.
105func appWithSchema(t *testing.T, origin string, schema *migrate.Set, owners ...string) (*App, *recorder) {
106 t.Helper()
107 d, err := rdb.Open(filepath.Join(t.TempDir(), "test.db"), quietLogger())
108 if err != nil {
109 t.Fatalf("open db: %v", err)
110 }
111 t.Cleanup(func() { d.Close() })
112 if _, err := migrate.Apply(context.Background(), d, schema); err != nil {
113 t.Fatalf("migrate: %v", err)
114 }
115 rec := &recorder{}
116 sealer, err := seal.New(make([]byte, dekBytes))
117 if err != nil {
118 t.Fatalf("seal.New: %v", err)
119 }
120 // The app is built first and auth attached second, the same order
121 // main uses and for the same reason: auth's admission gate reads
122 // this app's grants table so a shared-with guest can sign in.
123 app := New(Config{
124 DB: d.G, Sealer: sealer, Origin: origin, Admit: Admits(owners),
125 })
126 a, err := NewAuth(d.Writer(), AuthEnv{
127 Origin: testOrigin,
128 InstanceKey: "test-instance-key",
129 Owners: owners,
130 Mailer: rec,
131 }, quietLogger(), app)
132 if err != nil {
133 t.Fatalf("NewAuth: %v", err)
134 }
135 t.Cleanup(func() { CloseSigninMail(a) })
136 app.UseAuth(a)
137 rememberMailer(app, rec)
138 return app, rec
139}
140
141func postSignin(t *testing.T, app *App, address string) *httptest.ResponseRecorder {
142 t.Helper()
143 req := httptest.NewRequest(http.MethodPost, "/signin",
144 strings.NewReader("address="+address))
145 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
146 req.Header.Set("Origin", testOrigin)
147 w := httptest.NewRecorder()
148 app.Router().ServeHTTP(w, req)
149 return w
150}
151
152// confirmForm is the confirm door's one form, as a browser would read it.
153var confirmForm = regexp.MustCompile(`<form[^>]*method="post" action="([^"]+)">\s*<input type="hidden" name="token" value="([^"]+)">`)
154
155// openLink is opening an emailed link: a GET that must spend nothing and
156// answer with the confirm door. It returns the door's form action and the
157// token it carries, read off the page rather than the link, so a door
158// that dropped or mangled the token fails here.
159func openLink(t *testing.T, h http.Handler, link string, cookies ...*http.Cookie) (action, token string) {
160 t.Helper()
161 u, err := url.Parse(link)
162 if err != nil {
163 t.Fatalf("parse emailed link %q: %v", link, err)
164 }
165 r := httptest.NewRequest(http.MethodGet, u.RequestURI(), nil)
166 for _, c := range cookies {
167 r.AddCookie(c)
168 }
169 rec := httptest.NewRecorder()
170 h.ServeHTTP(rec, r)
171 if rec.Code != http.StatusOK || len(rec.Result().Cookies()) != 0 {
172 t.Fatalf("GET %s = %d with %d cookies, want 200 and the confirm door, minting nothing", u.Path, rec.Code, len(rec.Result().Cookies()))
173 }
174 m := confirmForm.FindStringSubmatch(rec.Body.String())
175 if m == nil {
176 t.Fatalf("GET %s: no confirm form on the page:\n%s", u.Path, rec.Body.String())
177 }
178 return html.UnescapeString(m[1]), html.UnescapeString(m[2])
179}
180
181// postLink is pressing the confirm door's Sign in button: the token,
182// POSTed back to the door's action with a browser's same-origin
183// evidence. This is the request that spends the link.
184func postLink(t *testing.T, h http.Handler, action, token string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
185 t.Helper()
186 r := httptest.NewRequest(http.MethodPost, action, strings.NewReader(url.Values{"token": {token}}.Encode()))
187 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
188 r.Header.Set("Origin", testOrigin)
189 r.Header.Set("Sec-Fetch-Site", "same-origin")
190 for _, c := range cookies {
191 r.AddCookie(c)
192 }
193 rec := httptest.NewRecorder()
194 h.ServeHTTP(rec, r)
195 return rec
196}
197
198// followLink is both: open the emailed link, then press Sign in.
199func followLink(t *testing.T, h http.Handler, link string) *httptest.ResponseRecorder {
200 t.Helper()
201 action, token := openLink(t, h, link)
202 return postLink(t, h, action, token)
203}
204
205// TestBeginDoesNotEmailStrangers is the defect this handler exists for.
206// auth checks Authorize at redemption, so without the gate a stranger
207// still cannot get a session — but the instance cheerfully emails them a
208// live link, which is abuse of our sending identity, not access control.
209func TestBeginDoesNotEmailStrangers(t *testing.T) {
210 app, mail := appWithRecorder(t)
211 w := postSignin(t, app, "stranger@example.com")
212 if got := mail.addresses(); len(got) != 0 {
213 t.Errorf("emailed a stranger: %v", got)
214 }
215 if w.Code != http.StatusSeeOther {
216 t.Errorf("status = %d, want 303", w.Code)
217 }
218}
219
220// TestBeginStillEmailsMembers is the other half: the gate must not have
221// broken the thing it guards. Without this, refusing everyone would pass
222// the test above.
223func TestBeginStillEmailsMembers(t *testing.T) {
224 app, mail := appWithRecorder(t)
225 postSignin(t, app, "paul@example.com")
226 got := mail.addresses()
227 if len(got) != 1 || got[0] != "paul@example.com" {
228 t.Fatalf("member mail = %v, want one to paul@example.com", got)
229 }
230}
231
232// TestBeginIsNotAMembershipOracle: the refusal has to be invisible, or
233// the endpoint becomes a way to enumerate the team. Member and stranger
234// must be indistinguishable from outside — same status, same location,
235// body and cookies, but for the random attempt each answer names.
236func TestBeginIsNotAMembershipOracle(t *testing.T) {
237 app, _ := appWithRecorder(t)
238 member := postSignin(t, app, "paul@example.com")
239 stranger := postSignin(t, app, "stranger@example.com")
240
241 if member.Code != stranger.Code {
242 t.Errorf("status differs: member %d, stranger %d", member.Code, stranger.Code)
243 }
244 // Each answer names its own attempt (rastrillo binds the Sent page to
245 // this browser's attempt cookie), a random id either way.
246 if m, s := member.Header().Get("Location"), stranger.Header().Get("Location"); !sentAnswer(m) || !sentAnswer(s) {
247 t.Errorf("Location differs: member %q, stranger %q", m, s)
248 }
249 attempt := regexp.MustCompile(`attempt=[A-Za-z0-9_-]+`)
250 if m, s := attempt.ReplaceAllString(member.Body.String(), "attempt=X"), attempt.ReplaceAllString(stranger.Body.String(), "attempt=X"); m != s {
251 t.Error("body differs between member and stranger")
252 }
253 if len(member.Result().Cookies()) != len(stranger.Result().Cookies()) {
254 t.Error("cookies differ between member and stranger")
255 }
256}
257
258// TestBeginGateIsCaseInsensitive: the allowlist is compared lowercased,
259// so a member typing their address with different capitalisation must
260// still receive a link rather than being silently dropped.
261func TestBeginGateIsCaseInsensitive(t *testing.T) {
262 app, mail := appWithRecorder(t)
263 postSignin(t, app, "PAUL@example.com")
264 if got := mail.addresses(); len(got) != 1 {
265 t.Errorf("mail for capitalised member address = %v, want one", got)
266 }
267}
268