oficina / calendar Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calendartest
2
3import (
4 "io"
5 "log/slog"
6 "net/http"
7 "net/url"
8 "path/filepath"
9 "regexp"
10 "strings"
11 "testing"
12
13 calendar "amadan.net/oficina/calendar/internal/calendar"
14)
15
16// Everything behind the session group is behind it. A test per route
17// would rot the moment somebody adds one, so this walks the list and
18// the list is the thing to extend.
19func TestSignInRequiredForEverything(t *testing.T) {
20 h := newApp(t).Handler()
21 for _, target := range []string{"/"} {
22 rec := get(t, h, target)
23 if rec.Code != http.StatusSeeOther && rec.Code != http.StatusFound {
24 t.Errorf("GET %s signed out: status %d, want a redirect to sign-in", target, rec.Code)
25 continue
26 }
27 if loc := rec.Header().Get("Location"); !strings.HasPrefix(loc, "/signin") {
28 t.Errorf("GET %s signed out: Location = %q, want /signin", target, loc)
29 }
30 }
31}
32
33func TestSignInMintsASession(t *testing.T) {
34 app, session := signedIn(t, "someone@example.com")
35 if session == nil || session.Value == "" {
36 t.Fatal("sign-in minted no session cookie")
37 }
38 if rec := follow(t, app.Handler(), session, "/"); rec.Code != http.StatusOK {
39 t.Fatalf("GET / signed in: status %d, want 200", rec.Code)
40 }
41}
42
43// The defect this pins is an open relay on our own mail-sending
44// identity: rastrillo/auth checks Config.Authorize at the CALLBACK,
45// after Begin has already emailed the link. Gating only Authorize
46// would let anyone POST any address and have this instance mail it a
47// working sign-in link.
48func TestSignInMailsNothingForANonPermittedAddress(t *testing.T) {
49 app := newAppWithAllowlist(t, "allowed@example.com")
50 h := app.Handler()
51
52 post(t, h, "/signin", url.Values{"address": {"stranger@example.com"}})
53 if body, _ := app.LastMailForTest(); body != "" {
54 t.Fatalf("a non-permitted address was mailed a sign-in link:\n%s", body)
55 }
56
57 post(t, h, "/signin", url.Values{"address": {"allowed@example.com"}})
58 body, err := app.LastMailForTest()
59 if err != nil {
60 t.Fatalf("LastMailForTest: %v", err)
61 }
62 if body == "" {
63 t.Fatal("a permitted address was mailed nothing")
64 }
65}
66
67// Any observable difference between the two responses turns this
68// endpoint into a membership oracle: an attacker could learn which
69// addresses this instance admits by watching how it answers each one.
70// Byte-for-byte, not merely "both are 303", once the attempt id is masked:
71// since rastrillo v0.38 Sent carries this browser's attempt (attempt=…),
72// fresh random bytes on every post that say nothing about the address.
73func TestSignInAnswersIdenticallyForPermittedAndNot(t *testing.T) {
74 h := newAppWithAllowlist(t, "allowed@example.com").Handler()
75
76 yes := post(t, h, "/signin", url.Values{"address": {"allowed@example.com"}})
77 no := post(t, h, "/signin", url.Values{"address": {"stranger@example.com"}})
78
79 attempt := regexp.MustCompile(`attempt=[A-Za-z0-9_-]+`)
80 mask := func(s string) string { return attempt.ReplaceAllString(s, "attempt=ATTEMPT") }
81 if yes.Code != no.Code {
82 t.Errorf("status differs: permitted %d, non-permitted %d", yes.Code, no.Code)
83 }
84 if mask(yes.Header().Get("Location")) != mask(no.Header().Get("Location")) || !strings.Contains(yes.Header().Get("Location"), "sent=1") {
85 t.Errorf("Location differs: permitted %q, non-permitted %q",
86 yes.Header().Get("Location"), no.Header().Get("Location"))
87 }
88 if len(yes.Result().Cookies()) != len(no.Result().Cookies()) {
89 t.Errorf("cookies differ: permitted %v, non-permitted %v", yes.Result().Cookies(), no.Result().Cookies())
90 }
91 if mask(yes.Body.String()) != mask(no.Body.String()) {
92 t.Errorf("body differs:\npermitted: %q\nnon-permitted: %q",
93 yes.Body.String(), no.Body.String())
94 }
95}
96
97// A link minted for an address that is no longer permitted must not
98// mint a session — the second of the two wirings, defending admission
99// itself rather than delivery. The refusal is the door, with the
100// refusal on it, in auth's 403 (auth.Config.Refused, App.refused):
101// not rastrillo's bare text, and not a redirect to a query anybody could
102// type.
103func TestASessionIsRefusedForANonPermittedAddress(t *testing.T) {
104 dir := t.TempDir()
105 app := newAppWithAllowlistAt(t, dir, "allowed@example.com")
106 h := app.Handler()
107
108 post(t, h, "/signin", url.Values{"address": {"allowed@example.com"}})
109 body, err := app.LastMailForTest()
110 if err != nil || body == "" {
111 t.Fatalf("no link was mailed: %v", err)
112 }
113 link := magicLink(t, body)
114 app.Close()
115
116 // The same database, reopened with a different allowlist: "the
117 // allowlist changed between the link being mailed and clicked".
118 other := newAppWithAllowlistAt(t, dir, "somebody-else@example.com")
119 action, token := openLink(t, other.Handler(), link)
120 rec := postLink(t, other.Handler(), action, token)
121 if rec.Code != http.StatusForbidden || rec.Header().Get("Location") != "" {
122 t.Fatalf("refused redemption = %d %q, want 403 and the door itself\n%s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
123 }
124 for _, c := range rec.Result().Cookies() {
125 if c.Value != "" && c.MaxAge >= 0 && strings.Contains(c.Name, "session") {
126 t.Fatalf("a refused sign-in set a session cookie %q", c.Name)
127 }
128 }
129 page := rec.Body.String()
130 for _, want := range []string{"estilo-door", `name="address"`, `action="/signin"`, "That email can’t sign in to Calendar. Use a different email, or ask whoever runs this team to add it."} {
131 if !strings.Contains(page, want) {
132 t.Errorf("refusal door lacks %q:\n%s", want, page)
133 }
134 }
135 if rec.Header().Get("Cache-Control") != "no-store" {
136 t.Errorf("refusal door Cache-Control = %q, want no-store", rec.Header().Get("Cache-Control"))
137 }
138}
139
140// newAppWithAllowlist builds an app admitting only the given addresses.
141// Env stays "development" so mail is still recorded rather than sent;
142// the allowlist is what is under test, not the environment gate.
143func newAppWithAllowlist(t *testing.T, addresses ...string) *calendar.App {
144 t.Helper()
145 return newAppWithAllowlistAt(t, t.TempDir(), addresses...)
146}
147
148// newAppWithAllowlistAt is newAppWithAllowlist over the database in dir,
149// so a second app can reopen the first one's.
150func newAppWithAllowlistAt(t *testing.T, dir string, addresses ...string) *calendar.App {
151 t.Helper()
152 app, err := calendar.New(calendar.Config{
153 DBPath: filepath.Join(dir, "calendar.db"),
154 Env: "development",
155 Origin: testOrigin,
156 AllowedAddresses: strings.Join(addresses, ","),
157 Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
158 })
159 if err != nil {
160 t.Fatalf("calendar.New: %v", err)
161 }
162 t.Cleanup(func() { app.Close() })
163 return app
164}
165
166// magicLink pulls the request target out of a mailed sign-in link.
167func magicLink(t *testing.T, body string) string {
168 t.Helper()
169 i := strings.Index(body, "/auth/verify?token=")
170 if i < 0 {
171 t.Fatalf("no sign-in link in mail body:\n%s", body)
172 }
173 rest := body[i:]
174 if j := strings.IndexAny(rest, " \r\n\t"); j >= 0 {
175 rest = rest[:j]
176 }
177 if _, err := url.Parse(rest); err != nil {
178 t.Fatalf("unparseable sign-in link %q: %v", rest, err)
179 }
180 return rest
181}
182