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 "fmt"
5 "html"
6 "net/http"
7 "net/http/httptest"
8 "net/url"
9 "os"
10 "os/exec"
11 "regexp"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/sheets/internal/sheets/keymailtest"
17)
18
19// TestMain keeps Keymail classification inside the process: every DNS
20// query is answered NXDOMAIN and only the Keymail fixtures a test
21// registers answer HTTPS (keymailtest). Before it, every POST /signin
22// in this suite classified its address against the real network.
23func TestMain(m *testing.M) {
24 if os.Getenv(asDeployedEnv) == "1" {
25 // TestAuthIsBuiltAsDeployed's child: no fixtures, no list.
26 os.Exit(m.Run())
27 }
28 keymailTestServers = []string{keymailHost}
29 restore, err := keymailtest.Install()
30 if err != nil {
31 fmt.Fprintln(os.Stderr, "keymailtest.Install:", err)
32 os.Exit(1)
33 }
34 code := m.Run()
35 // No test may leave a sign-in mail worker running: every plugin a
36 // test builds is closed in its cleanup (CloseSigninMail).
37 if code == 0 {
38 deadline := time.Now().Add(5 * time.Second)
39 for mailWorkers() > 0 && time.Now().Before(deadline) {
40 time.Sleep(10 * time.Millisecond)
41 }
42 if n := mailWorkers(); n > 0 {
43 fmt.Fprintf(os.Stderr, "FAIL: %d sign-in mail queue goroutines still running after the tests\n", n)
44 code = 1
45 }
46 }
47 restore()
48 os.Exit(code)
49}
50
51const (
52 keymailHost = "keymail.sheets.test"
53 keymailMember = "paul@" + keymailHost
54 keymailStranger = "stranger@" + keymailHost
55)
56
57// keymailApp is a standalone app whose owners include keymailMember,
58// beside a Keymail deployment holding keymailMember and keymailStranger.
59func keymailApp(t *testing.T) (*App, *recorder, *keymailtest.Server) {
60 t.Helper()
61 km := keymailtest.Serve(t, keymailHost, keymailMember, keymailStranger)
62 app, rec := appWithOwners(t, testOrigin, signedInAddress, keymailMember)
63 return app, rec, km
64}
65
66func keymailPost(t *testing.T, h http.Handler, form url.Values, cookies ...*http.Cookie) *httptest.ResponseRecorder {
67 t.Helper()
68 r := httptest.NewRequest(http.MethodPost, testOrigin+"/signin", strings.NewReader(form.Encode()))
69 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
70 r.Header.Set("Origin", testOrigin)
71 r.Header.Set("Sec-Fetch-Site", "same-origin")
72 for _, c := range cookies {
73 r.AddCookie(c)
74 }
75 w := httptest.NewRecorder()
76 h.ServeHTTP(w, r)
77 return w
78}
79
80func keymailGet(t *testing.T, h http.Handler, path string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
81 t.Helper()
82 r := httptest.NewRequest(http.MethodGet, testOrigin+path, nil)
83 for _, c := range cookies {
84 r.AddCookie(c)
85 }
86 w := httptest.NewRecorder()
87 h.ServeHTTP(w, r)
88 return w
89}
90
91var authorizeHref = regexp.MustCompile(`href="(https://` + regexp.QuoteMeta(keymailHost) + `/oauth/authorize\?[^"]+)"`)
92
93// continueOnTheDoor matches Begin's answer for a Keymail address with
94// SigninScreen on: a redirect that stays on this origin, to the door's
95// Keymail continuation.
96var continueOnTheDoor = regexp.MustCompile(`^/signin\?continue=[A-Za-z0-9_-]+(&return_to=[^&]+)?$`)
97
98// continuation asserts begin is Begin's answer for a Keymail address —
99// a 303 to the door's continuation on this origin, never a redirect off
100// it from the form POST (Safari applies form-action to that redirect) —
101// follows it with begin's cookies, asserts the door is a 200 document with
102// a meta refresh, and returns that page and the authorize URL it carries.
103func continuation(t *testing.T, h http.Handler, label string, begin *httptest.ResponseRecorder, cookies ...*http.Cookie) (*httptest.ResponseRecorder, *url.URL) {
104 t.Helper()
105 loc := begin.Header().Get("Location")
106 if begin.Code != http.StatusSeeOther || !continueOnTheDoor.MatchString(loc) {
107 t.Fatalf("%s: %d %q, want 303 to the door's continuation — the hop to Keymail must not leave this origin from the form POST", label, begin.Code, loc)
108 }
109 rec := keymailGet(t, h, loc, append(cookies, begin.Result().Cookies()...)...)
110 if rec.Code != http.StatusOK || rec.Header().Get("Location") != "" {
111 t.Fatalf("%s: GET %s = %d %q, want 200 and the continuation", label, loc, rec.Code, rec.Header().Get("Location"))
112 }
113 body := rec.Body.String()
114 m := authorizeHref.FindStringSubmatch(body)
115 if m == nil || !strings.Contains(body, `http-equiv="refresh"`) || !strings.Contains(body, "<div estilo-signin-screen>") {
116 t.Fatalf("%s: no Keymail continuation on the door:\n%s", label, body)
117 }
118 u, err := url.Parse(html.UnescapeString(m[1]))
119 if err != nil {
120 t.Fatal(err)
121 }
122 return rec, u
123}
124
125// sentAnswer reports whether loc is Begin's Sent answer: the door's Sent
126// state, with the attempt rastrillo binds the address to and nothing else.
127var sentAnswer = regexp.MustCompile(`^/signin\?sent=1&attempt=[A-Za-z0-9_-]+$`).MatchString
128
129// TestKeymailAddressGoesToKeymailWhetherAdmittedOrNot: whether an
130// address goes to Keymail depends on its domain alone. An admitted and
131// a non-admitted Keymail address get the same first answer — the
132// continuation page — so the answer says nothing about who is on the
133// team. Before, the admission gate answered the stranger ?sent=1 and
134// sent the member to Keymail with a 303 out of the form POST, which
135// Safari refused under form-action 'self'.
136func TestKeymailAddressGoesToKeymailWhetherAdmittedOrNot(t *testing.T) {
137 app, mail, km := keymailApp(t)
138 h := app.Router()
139 member, mu := continuation(t, h, "admitted Keymail address", keymailPost(t, h, url.Values{"address": {keymailMember}}))
140 stranger, su := continuation(t, h, "non-admitted Keymail address", keymailPost(t, h, url.Values{"address": {keymailStranger}}))
141 mask := func(rec *httptest.ResponseRecorder, u *url.URL) string {
142 return strings.ReplaceAll(rec.Body.String(), html.EscapeString(u.String()), "AUTHORIZE")
143 }
144 if a, b := mask(member, mu), mask(stranger, su); a != b {
145 t.Errorf("the two Keymail answers differ beyond the authorize URL:\nadmitted:\n%s\nnot admitted:\n%s", a, b)
146 }
147 if got := mail.addresses(); len(got) != 0 {
148 t.Errorf("a Keymail address was mailed: %v", got)
149 }
150 if n := km.Lookups(); n != 2 {
151 t.Errorf("Keymail saw %d lookups, want 2: both addresses classified", n)
152 }
153}
154
155// TestHomeLocalKeymailIsTheSameAnswer is the same in Home mode, where the
156// local form posts to /signin under LocalGuard.
157func TestHomeLocalKeymailIsTheSameAnswer(t *testing.T) {
158 km := keymailtest.Serve(t, keymailHost, keymailMember, keymailStranger)
159 f := newHomeFixture(t)
160 member := f.request(t, http.MethodPost, "/signin", url.Values{"address": {signedInAddress}}, false)
161 if member.Code != http.StatusSeeOther || !sentAnswer(member.Header().Get("Location")) {
162 t.Fatalf("Home-local plain member: %d %q", member.Code, member.Header().Get("Location"))
163 }
164 stranger := f.request(t, http.MethodPost, "/signin", url.Values{"address": {keymailStranger}}, false)
165 continuation(t, f.app.Router(), "Home-local non-admitted Keymail address", stranger, f.cookies()...)
166 if n := km.Lookups(); n != 1 {
167 t.Errorf("Keymail saw %d lookups, want 1", n)
168 }
169}
170
171// TestNonAdmittedPlainAddressIsAnsweredSentAndNotMailed: an address
172// with no Keymail still gets ?sent=1, admitted or not, and only the
173// admitted one is mailed.
174func TestNonAdmittedPlainAddressIsAnsweredSentAndNotMailed(t *testing.T) {
175 app, mail, _ := keymailApp(t)
176 h := app.Router()
177 for _, address := range []string{"stranger@example.com", signedInAddress} {
178 rec := keymailPost(t, h, url.Values{"address": {address}})
179 if rec.Code != http.StatusSeeOther || !sentAnswer(rec.Header().Get("Location")) {
180 t.Fatalf("POST /signin %q: %d %q, want 303 /signin?sent=1&attempt=…", address, rec.Code, rec.Header().Get("Location"))
181 }
182 }
183 if got := mail.addresses(); len(got) != 1 || got[0] != signedInAddress {
184 t.Fatalf("mail = %v, want one, to %s", got, signedInAddress)
185 }
186}
187
188// TestKeymailFailureFallsBackToAnEmailLink: the form rastrillo lands a
189// failed Keymail exchange on carries force, and a forced POST mails a
190// link without classifying.
191func TestKeymailFailureFallsBackToAnEmailLink(t *testing.T) {
192 app, mail, km := keymailApp(t)
193 h := app.Router()
194 if body := keymailGet(t, h, "/signin?force=1&err=keymail").Body.String(); !strings.Contains(body, `name="force"`) {
195 t.Fatal("the err=keymail page does not carry force")
196 }
197 rec := keymailPost(t, h, url.Values{"address": {keymailMember}, "force": {"1"}})
198 if rec.Code != http.StatusSeeOther || !sentAnswer(rec.Header().Get("Location")) {
199 t.Fatalf("forced POST: %d %q", rec.Code, rec.Header().Get("Location"))
200 }
201 if got := mail.addresses(); len(got) != 1 || got[0] != keymailMember {
202 t.Fatalf("mail = %v, want one link to %s", got, keymailMember)
203 }
204 if km.Lookups() != 0 {
205 t.Error("a forced sign-in classified the address")
206 }
207}
208
209// TestKeymailRefusalIsTheDoor: a non-admitted address Keymail verified
210// is refused after verification with the sign-in door, rendered in the
211// refusal's own 403 by auth's Refused hook (App.refused) — not
212// rastrillo's bare text, and not a redirect to a query anybody could
213// type. No session is minted. An admitted one is signed in, through the
214// continuation page, and its session opens the list.
215func TestKeymailRefusalIsTheDoor(t *testing.T) {
216 app, _, km := keymailApp(t)
217 h := app.Router()
218 roundTrip := func(address string) *httptest.ResponseRecorder {
219 begin := keymailPost(t, h, url.Values{"address": {address}})
220 door, u := continuation(t, h, address, begin)
221 jar := map[string]*http.Cookie{}
222 for _, c := range append(begin.Result().Cookies(), door.Result().Cookies()...) {
223 if c.MaxAge < 0 {
224 delete(jar, c.Name)
225 } else {
226 jar[c.Name] = c
227 }
228 }
229 var cookies []*http.Cookie
230 for _, c := range jar {
231 cookies = append(cookies, c)
232 }
233 return keymailGet(t, h, "/auth/callback?"+url.Values{"state": {u.Query().Get("state")}, "code": {km.Approve(address)}}.Encode(), cookies...)
234 }
235 cb := roundTrip(keymailMember)
236 if cb.Code != http.StatusSeeOther || cb.Header().Get("Location") != "/sheets" {
237 t.Fatalf("admitted callback: %d %q, want 303 /sheets", cb.Code, cb.Header().Get("Location"))
238 }
239 if list := page(t, app, cb.Result().Cookies(), "/sheets"); list.Code != http.StatusOK || !strings.Contains(list.Body.String(), keymailMember) {
240 t.Fatalf("GET /sheets with the Keymail session = %d, or it does not name %s", list.Code, keymailMember)
241 }
242 cb = roundTrip(keymailStranger)
243 if cb.Code != http.StatusForbidden || cb.Header().Get("Location") != "" {
244 t.Fatalf("non-admitted 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())
245 }
246 for _, c := range cb.Result().Cookies() {
247 if strings.Contains(c.Name, "session") && c.MaxAge >= 0 && c.Value != "" {
248 t.Fatalf("a refused sign-in set a session cookie %q", c.Name)
249 }
250 }
251 door := cb.Body.String()
252 for _, want := range []string{"estilo-door", `id="rst-signin-app-problem"`, `name="address"`, signinRefusal} {
253 if !strings.Contains(door, want) {
254 t.Errorf("refusal door lacks %q:\n%s", want, door)
255 }
256 }
257 // The sentence means "you proved this address and it is not
258 // admitted"; nobody may summon it by typing a URL (Astra, round 3).
259 if spoof := keymailGet(t, h, "/signin?err=refused").Body.String(); strings.Contains(spoof, "can’t sign in to Sheets") {
260 t.Fatal("anybody can show the refusal by visiting /signin?err=refused")
261 }
262}
263
264const asDeployedEnv = "SHEETS_TEST_AUTH_AS_DEPLOYED"
265
266// TestAuthIsBuiltAsDeployed: every other test here lists its Keymail
267// fixture's host (keymailTestServers), so auth takes its listed-servers
268// path. A deployment lists none, and from rastrillo v0.45.0 that path
269// builds a public-address-only client from http.DefaultTransport. This
270// builds the app that way, in a child process with neither the list nor
271// keymailtest's transport, and opens the door.
272func TestAuthIsBuiltAsDeployed(t *testing.T) {
273 if os.Getenv(asDeployedEnv) != "1" {
274 cmd := exec.Command(os.Args[0], "-test.run=^TestAuthIsBuiltAsDeployed$", "-test.count=1")
275 cmd.Env = append(os.Environ(), asDeployedEnv+"=1")
276 if out, err := cmd.CombinedOutput(); err != nil {
277 t.Fatalf("built as deployed: %v\n%s", err, out)
278 }
279 return
280 }
281 if keymailTestServers != nil {
282 t.Fatal("the child lists Keymail servers; it is meant to be built as deployed")
283 }
284 app, _ := appWithRecorder(t)
285 rec := do(t, app, httptest.NewRequest(http.MethodGet, "/signin", nil))
286 if rec.Code != http.StatusOK {
287 t.Fatalf("GET /signin: %d", rec.Code)
288 }
289}
290