oficina / fichas Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fichastest
2
3import (
4 "context"
5 "io"
6 "log/slog"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "path/filepath"
11 "regexp"
12 "strings"
13 "sync"
14 "testing"
15
16 fichas "amadan.net/oficina/fichas/internal/fichas"
17 "amadan.net/rastrillo/rastrillo/db"
18)
19
20// capturingMailer records what the app sends instead of sending it.
21type capturingMailer struct {
22 mu sync.Mutex
23 sent []string
24}
25
26func (m *capturingMailer) Send(_ context.Context, to, subject, body string) error {
27 m.mu.Lock()
28 defer m.mu.Unlock()
29 m.sent = append(m.sent, to+"\n"+subject+"\n"+body)
30 return nil
31}
32
33func (m *capturingMailer) last(t *testing.T) string {
34 t.Helper()
35 m.mu.Lock()
36 defer m.mu.Unlock()
37 if len(m.sent) == 0 {
38 t.Fatal("no email was sent")
39 }
40 return m.sent[len(m.sent)-1]
41}
42
43// wiredApp is the app exactly as main.go builds it — App, then NewAuth,
44// then UseAuth — with a capturing mailer in place of SMTP and NO test
45// identity or bypass. Everything that reached production went through
46// this sequence, and until this test nothing in the suite did.
47func wiredApp(t *testing.T) (http.Handler, *capturingMailer, *db.DB) {
48 t.Helper()
49 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
50 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
51 if err != nil {
52 t.Fatalf("db.Open: %v", err)
53 }
54 t.Cleanup(func() { d.Close() })
55
56 cfg := testConfig(t)
57 mux, app, err := fichas.App(d, cfg, logger)
58 if err != nil {
59 t.Fatalf("App: %v", err)
60 }
61 mailer := &capturingMailer{}
62 au, err := fichas.NewAuth(d.Writer(), fichas.AuthEnv{
63 Origin: cfg.Origin,
64 InstanceKey: cfg.InstanceKey,
65 Mailer: mailer,
66 }, logger, app)
67 if err != nil {
68 t.Fatalf("NewAuth: %v", err)
69 }
70 app.UseAuth(au)
71 return mux, mailer, d
72}
73
74// TestBootSchema: the tables sign-in depends on exist after a boot.
75//
76// BootSchema was migrate.Merge(Schema) for eight days in production: an
77// edit meant to add sessions and auth matched a different spelling of the
78// line and changed nothing. Every boot log said skipped=2 and nobody read
79// it as "two, not six".
80func TestBootSchema(t *testing.T) {
81 _, _, d := wiredApp(t)
82 for _, table := range []string{"auth_links", "sessions", "cards", "events"} {
83 var n int64
84 if err := d.G.Raw("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?", table).Scan(&n).Error; err != nil {
85 t.Fatalf("sqlite_master: %v", err)
86 }
87 if n != 1 {
88 t.Errorf("table %s does not exist after boot", table)
89 }
90 }
91}
92
93var linkToken = regexp.MustCompile(`/auth/verify\?token=([A-Za-z0-9_\-%.~]+)`)
94
95// TestASignInCompletesEndToEnd walks the email path the way a person does:
96// submit an address, receive a link, follow it, arrive signed in.
97//
98// No earlier test did this. They either bypassed auth or stopped at the
99// guard in front of it, so nothing exercised the path that touches the
100// database — and the deployed app could not complete a single sign-in.
101func TestASignInCompletesEndToEnd(t *testing.T) {
102 h, mailer, _ := wiredApp(t)
103
104 // force=1 takes the plain-email path, which skips the classifier and
105 // so makes no network request: this test must not dial anything.
106 rec := post(t, h, "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}})
107 if rec.Code != http.StatusSeeOther {
108 t.Fatalf("POST /auth/begin: status %d\n%s", rec.Code, rec.Body.String())
109 }
110 if loc := rec.Header().Get("Location"); !strings.HasPrefix(loc, "/signin?sent=1&attempt=") {
111 t.Fatalf("POST /auth/begin redirected to %q, want the door's Sent", loc)
112 }
113
114 mail := mailer.last(t)
115 if !strings.HasPrefix(mail, TestOwner+"\n") {
116 t.Fatalf("the link went to the wrong address:\n%s", mail)
117 }
118 // The subject is the door's: "Sign in to Fichas", the app capitalised.
119 if !strings.HasPrefix(mail, TestOwner+"\nSign in to Fichas\n") {
120 t.Errorf("the email's subject is not the door's \"Sign in to Fichas\":\n%s", mail)
121 }
122 m := linkToken.FindStringSubmatch(mail)
123 if m == nil {
124 t.Fatalf("the email carries no sign-in link:\n%s", mail)
125 }
126 // The link must point at the configured origin, or it goes nowhere.
127 if !strings.Contains(mail, testOrigin+"/auth/verify?token=") {
128 t.Errorf("the link does not use FICHAS_ORIGIN:\n%s", mail)
129 }
130
131 // The link opens the door with one Sign in button and spends nothing:
132 // a mail scanner's GET must not sign anybody in.
133 confirm := get(t, h, "/auth/verify?token="+m[1])
134 if confirm.Code != http.StatusOK {
135 t.Fatalf("GET /auth/verify: status %d, want the confirm page\n%s", confirm.Code, confirm.Body.String())
136 }
137 if len(confirm.Result().Cookies()) != 0 {
138 t.Fatal("GET /auth/verify set a cookie: the link's GET must spend nothing")
139 }
140 page := confirm.Body.String()
141 for _, want := range []string{"estilo-door", "<div estilo-signin-screen>", `method="post" action="/auth/verify"`, `name="token" value="` + m[1] + `"`, ">Sign in</button>"} {
142 if !strings.Contains(page, want) {
143 t.Fatalf("the confirm page is not the door with a Sign in button (missing %q):\n%s", want, page)
144 }
145 }
146
147 verify := post(t, h, "/auth/verify", url.Values{"token": {m[1]}})
148 if verify.Code != http.StatusSeeOther {
149 t.Fatalf("GET /auth/verify: status %d\n%s", verify.Code, verify.Body.String())
150 }
151 if loc := verify.Header().Get("Location"); strings.Contains(loc, "err=") {
152 t.Fatalf("verify failed: redirected to %q", loc)
153 }
154 cookies := verify.Result().Cookies()
155 if len(cookies) == 0 {
156 t.Fatal("verify set no session cookie")
157 }
158
159 req := httptest.NewRequest(http.MethodGet, "/", nil)
160 for _, c := range cookies {
161 req.AddCookie(c)
162 }
163 home := httptest.NewRecorder()
164 h.ServeHTTP(home, req)
165 if home.Code != http.StatusOK {
166 t.Fatalf("GET / with the new session: status %d, want 200 (Location %q)",
167 home.Code, home.Header().Get("Location"))
168 }
169 if !strings.Contains(home.Body.String(), "Customers") {
170 t.Error("signed in, but the index did not render")
171 }
172
173 // A link is single-use.
174 again := post(t, h, "/auth/verify", url.Values{"token": {m[1]}})
175 if loc := again.Header().Get("Location"); !strings.Contains(loc, "err=expired") {
176 t.Errorf("a used link was accepted a second time (redirected to %q)", loc)
177 }
178}
179
180// A stranger must get the same outcome and no email — the anti-oracle
181// property — and the wiring must not change that.
182func TestAStrangerIsSentNothing(t *testing.T) {
183 h, mailer, _ := wiredApp(t)
184 rec := post(t, h, "/auth/begin", url.Values{"address": {"nobody@example.com"}, "force": {"1"}})
185 if loc := rec.Header().Get("Location"); !strings.HasPrefix(loc, "/signin?sent=1&attempt=") {
186 t.Fatalf("a stranger was redirected to %q", loc)
187 }
188 mailer.mu.Lock()
189 defer mailer.mu.Unlock()
190 if len(mailer.sent) != 0 {
191 t.Fatalf("a stranger was sent %d email(s)", len(mailer.sent))
192 }
193}
194
195// Every error code renders something a person can act on, in
196// rastrillo's approved words, and the email fallback survives a failed
197// keymail round trip.
198func TestSigninErrorsArePlainLanguage(t *testing.T) {
199 h, _, _ := wiredApp(t)
200 for code, want := range map[string]string{
201 "rate": "Too many tries. Try again in a few minutes.",
202 "expired": "That link has expired or was already used. Send a new one.",
203 "keymail": "We couldn&#39;t confirm it&#39;s you. Try again, or email yourself a sign-in link.", // rastrillo v0.45.0: never names Keymail
204 "address": "That doesn&#39;t look like an email address.",
205 "1": "Something went wrong. Try again.",
206 } {
207 body := get(t, h, "/signin?err="+code).Body.String()
208 if !strings.Contains(body, want) {
209 t.Errorf("?err=%s does not say %q", code, want)
210 }
211 }
212 if !strings.Contains(get(t, h, "/signin?force=1&err=keymail").Body.String(), `name="force" value="1"`) {
213 t.Error("after a keymail failure the form does not fall back to email")
214 }
215}
216
217// The door's field is named address, and the POST it makes still signs a
218// person in: an owner's address= gets the sent page and a link; the
219// submission is exactly what the door's form sends, force included after
220// a keymail failure.
221func TestTheDoorsFormStillSignsIn(t *testing.T) {
222 h, mailer, _ := wiredApp(t)
223 form := get(t, h, "/signin?force=1&err=keymail").Body.String()
224 for _, want := range []string{`name="address"`, `name="force" value="1"`, `action="/auth/begin"`} {
225 if !strings.Contains(form, want) {
226 t.Fatalf("the door's form lacks %q:\n%s", want, form)
227 }
228 }
229 rec := post(t, h, "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}})
230 if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/signin?sent=1&attempt=") {
231 t.Fatalf("POST address=: status %d, Location %q", rec.Code, rec.Header().Get("Location"))
232 }
233 if mail := mailer.last(t); !linkToken.MatchString(mail) {
234 t.Fatalf("no sign-in link was sent:\n%s", mail)
235 }
236}
237