oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "crypto/rand"
5 "encoding/base64"
6 "encoding/json"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "strings"
11 "testing"
12 "time"
13
14 "amadan.net/rastrillo/rastrillo/sessions"
15 "amadan.net/rastrillo/rastrillo/webauthn/authtest"
16)
17
18// signInFully takes a person all the way to a full session and returns
19// the session cookie.
20func signInFully(t *testing.T, app *testApp, addr string) *http.Cookie {
21 t.Helper()
22 signIn(t, app, addr)
23 rec := redeem(t, app, capturedLink(t, app))
24 c := sessionCookie(rec)
25 if c == nil {
26 t.Fatalf("no session cookie after redeeming (status %d)", rec.Code)
27 }
28 return c
29}
30
31// postJSON drives one of the ceremony endpoints.
32func postJSON(t *testing.T, app *testApp, path string, cookie *http.Cookie, body any) *httptest.ResponseRecorder {
33 t.Helper()
34 var payload string
35 if body != nil {
36 b, err := json.Marshal(body)
37 if err != nil {
38 t.Fatal(err)
39 }
40 payload = string(b)
41 } else {
42 payload = "{}"
43 }
44 req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(payload))
45 req.Host = app.credentialHost
46 req.Header.Set("Content-Type", "application/json")
47 req.Header.Set("Origin", app.origins.Credential)
48 if cookie != nil {
49 req.AddCookie(cookie)
50 }
51 w := httptest.NewRecorder()
52 app.Router().ServeHTTP(w, req)
53 return w
54}
55
56func challengeFrom(t *testing.T, rec *httptest.ResponseRecorder) []byte {
57 t.Helper()
58 if rec.Code != http.StatusOK {
59 t.Fatalf("begin: status %d, body %s", rec.Code, rec.Body.String())
60 }
61 var body struct {
62 Challenge string `json:"challenge"`
63 }
64 if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
65 t.Fatalf("decode challenge: %v (body %s)", err, rec.Body.String())
66 }
67 raw, err := base64.RawURLEncoding.DecodeString(body.Challenge)
68 if err != nil {
69 t.Fatalf("challenge is not base64url: %v", err)
70 }
71 return raw
72}
73
74// enrol runs the real registration ceremony against a software
75// authenticator — rastrillo's own, rather than a hand-rolled credential.
76func enrol(t *testing.T, app *testApp, cookie *http.Cookie) *authtest.Authenticator {
77 t.Helper()
78 a, err := authtest.New()
79 if err != nil {
80 t.Fatal(err)
81 }
82 challenge := challengeFrom(t, postJSON(t, app, "/passkey/register/begin", cookie, nil))
83 clientData, attestation := a.Create(challenge, authtest.Options{RPID: app.credentialHost, Origin: app.origins.Credential})
84 rec := postJSON(t, app, "/passkey/register/finish", cookie, map[string]string{
85 "clientDataJSON": base64.RawURLEncoding.EncodeToString(clientData),
86 "attestationObject": base64.RawURLEncoding.EncodeToString(attestation),
87 })
88 if rec.Code != http.StatusOK {
89 t.Fatalf("RegisterFinish: status %d, body %s", rec.Code, rec.Body.String())
90 }
91 return a
92}
93
94// TestEnrolledPersonCannotSignInWithOneFactor is what the whole task is
95// for. A magic link alone must not open an enrolled account.
96func TestEnrolledPersonCannotSignInWithOneFactor(t *testing.T) {
97 app := newTestApp(t)
98 const addr = "person@example.invalid"
99
100 cookie := signInFully(t, app, addr)
101 enrol(t, app, cookie)
102
103 // A fresh sign-in, first factor only.
104 signIn(t, app, addr)
105 rec := redeem(t, app, capturedLink(t, app))
106
107 if got := rec.Header().Get("Location"); got != confirmPath {
108 t.Errorf("redemption went to %q, want %q — the Gate did not take over", got, confirmPath)
109 }
110 if c := sessionCookie(rec); c != nil {
111 t.Fatal("one factor minted a full session for an enrolled person")
112 }
113}
114
115// The control: an account with no passkey is unaffected.
116func TestUnenrolledPersonSignsInWithOneFactor(t *testing.T) {
117 app := newTestApp(t)
118 rec := redeemAfterSignIn(t, app, "nobody@example.invalid")
119 if got := rec.Header().Get("Location"); got != "/" {
120 t.Errorf("redemption went to %q, want / — the Gate should pass an unenrolled account through", got)
121 }
122 if sessionCookie(rec) == nil {
123 t.Error("an unenrolled person got no session")
124 }
125}
126
127func redeemAfterSignIn(t *testing.T, app *testApp, addr string) *httptest.ResponseRecorder {
128 t.Helper()
129 signIn(t, app, addr)
130 return redeem(t, app, capturedLink(t, app))
131}
132
133// This source tripwire names the two app-owned session boundaries. Behavioural
134// tests prove the credential Gate and the directory assertion exchange; aliases
135// can evade a source search, so the search alone is not a security proof.
136func TestSessionIssuanceStaysAtCredentialAndDirectoryBoundaries(t *testing.T) {
137 got := grepPackage(t, "a.sessions.SignIn(")
138 if len(got) != 1 || got[0] != "directory.go" {
139 t.Fatalf("unexpected app session boundaries: %v", got)
140 }
141 gate := grepPackage(t, "a.idGate(")
142 if len(gate) != 1 || gate[0] != "signin.go" {
143 t.Fatalf("credential gate moved: %v", gate)
144 }
145}
146
147// A recovery code signs somebody in with no script at all — a plain
148// form POST, which is the point: recovery is exactly the moment
149// WebAuthn is not working.
150func TestRecoveryCodeCompletesSignInWithoutScript(t *testing.T) {
151 app := newTestApp(t)
152 const addr = "person@example.invalid"
153
154 cookie := signInFully(t, app, addr)
155 enrol(t, app, cookie)
156
157 codes, err := app.regenerateRecoveryCodes(subjectOf(t, app, cookie))
158 if err != nil {
159 t.Fatal(err)
160 }
161 if len(codes) != 10 {
162 t.Fatalf("got %d recovery codes, want 10 (§5.2 says ten)", len(codes))
163 }
164
165 // First factor again, which now stops at the Gate and leaves the
166 // pending half-session cookie behind.
167 signIn(t, app, addr)
168 gated := redeem(t, app, capturedLink(t, app))
169
170 form := url.Values{"code": {codes[0]}}
171 req := httptest.NewRequest(http.MethodPost, "/passkey/signin/recovery", strings.NewReader(form.Encode()))
172 req.Host = app.credentialHost
173 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
174 req.Header.Set("Origin", app.origins.Credential)
175 for _, c := range (&http.Response{Header: gated.Header()}).Cookies() {
176 req.AddCookie(c)
177 }
178 w := httptest.NewRecorder()
179 app.Router().ServeHTTP(w, req)
180
181 if sessionCookie(w) == nil {
182 t.Fatalf("a recovery code did not sign anybody in (status %d, location %q)",
183 w.Code, w.Header().Get("Location"))
184 }
185
186 // And it is single-use.
187 var n int
188 if err := app.db.Writer().QueryRow("SELECT count(*) FROM passkey_recovery_codes").Scan(&n); err != nil {
189 t.Fatal(err)
190 }
191 if n != 9 {
192 t.Errorf("%d codes left after redeeming one of ten, want 9", n)
193 }
194}
195
196func subjectOf(t *testing.T, app *testApp, cookie *http.Cookie) string {
197 t.Helper()
198 req := httptest.NewRequest(http.MethodGet, "/", nil)
199 req.Host = app.credentialHost
200 req.AddCookie(cookie)
201 sess, ok := app.sessions.From(req)
202 if !ok {
203 t.Fatal("the session cookie does not resolve")
204 }
205 return sess.Subject
206}
207
208// regenerateRecoveryCodes mints subject a fresh set of recovery codes
209// the way rastrillo's passkey.RegenerateRecoveryCodes did through v0.27.0
210// (copied from v0.26.1's passkey/recovery.go): ten codes of 50 bits,
211// xxxxx-xxxxx, hashed normalized into passkey_recovery_codes, replacing
212// any previous set. That method moved to rastrillo/secondfactor at
213// v0.27.1, which Home does not wire. Kept as a verbatim fixture because
214// these are the codes people already hold — TestIDLegacyRecoveryCodesStillRedeem
215// proves Home still redeems them — and every test that used the method
216// keeps exercising exactly the codes it was written against.
217func (a *App) regenerateRecoveryCodes(subject string) ([]string, error) {
218 const alphabet = "abcdefghijklmnopqrstuvwxyz234567"
219 tx, err := a.db.Writer().Begin()
220 if err != nil {
221 return nil, err
222 }
223 defer tx.Rollback()
224 if _, err := tx.Exec(`DELETE FROM passkey_recovery_codes WHERE subject = ?`, subject); err != nil {
225 return nil, err
226 }
227 now := time.Now().UTC().Format(time.RFC3339)
228 codes := make([]string, 0, 10)
229 for range 10 {
230 b := make([]byte, 10)
231 if _, err := rand.Read(b); err != nil {
232 return nil, err
233 }
234 for i := range b {
235 b[i] = alphabet[int(b[i])%len(alphabet)]
236 }
237 code := string(b[:5]) + "-" + string(b[5:])
238 normalized := strings.ReplaceAll(strings.ReplaceAll(strings.ToLower(code), "-", ""), " ", "")
239 if _, err := tx.Exec(`INSERT INTO passkey_recovery_codes (code_hash, subject, created_at) VALUES (?, ?, ?)`,
240 sessions.HashToken(normalized), subject, now); err != nil {
241 return nil, err
242 }
243 codes = append(codes, code)
244 }
245 return codes, tx.Commit()
246}
247
248// Both script files must stay on stable, unfingerprinted paths, because
249// the scriptless sweep's allowlist names them.
250func TestScriptAssetsAreServedOnNamedPaths(t *testing.T) {
251 app := newTestApp(t)
252 for _, path := range []string{"/static/webauthn.mjs", "/static/passkey.js"} {
253 req := httptest.NewRequest(http.MethodGet, path, nil)
254 req.Host = app.credentialHost
255 w := httptest.NewRecorder()
256 app.Router().ServeHTTP(w, req)
257 if w.Code != http.StatusOK {
258 t.Errorf("GET %s = %d, want 200", path, w.Code)
259 }
260 if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/javascript") {
261 t.Errorf("GET %s Content-Type = %q; a wrong MIME type blocks a module silently", path, ct)
262 }
263 if w.Body.Len() == 0 {
264 t.Errorf("GET %s served an empty body", path)
265 }
266 }
267}
268
269// The codes page shows ten codes once, so a merely valid session is not
270// enough — it wants a recent one. Without this, a stolen session cookie
271// of any age reads somebody's whole recovery set.
272func TestRecoveryCodesPageNeedsAFreshSession(t *testing.T) {
273 app := newTestApp(t)
274 cookie := signInFully(t, app, "person@example.invalid")
275
276 get := func() int {
277 req := httptest.NewRequest(http.MethodGet, "/passkey/codes", nil)
278 req.Host = app.credentialHost
279 req.AddCookie(cookie)
280 w := httptest.NewRecorder()
281 app.Router().ServeHTTP(w, req)
282 return w.Code
283 }
284
285 if code := get(); code != http.StatusOK {
286 t.Fatalf("a fresh session got %d from /passkey/codes, want 200", code)
287 }
288
289 // Age the session past the freshness window. Both columns, because
290 // sessions.Fresh falls back to At when AuthTime is zero — checking
291 // only one would leave this passing on a session that is still
292 // fresh by the other.
293 old := time.Now().Add(-24 * time.Hour).UTC().Format(time.RFC3339)
294 if _, err := app.db.Writer().Exec(
295 `UPDATE sessions SET auth_time = ?, created_at = ?`, old, old); err != nil {
296 t.Fatal(err)
297 }
298
299 if code := get(); code == http.StatusOK {
300 t.Error("a day-old session still reads the recovery codes page")
301 }
302}
303
304// A recovery code produces a session that satisfies RequireFresh,
305// because passkey.SignInRecovery mints one with AuthTime: time.Now().
306//
307// This test does not object to that — replacing the code set right after
308// spending one is the sensible behaviour. It pins the fact, because §5.2
309// says recovery is "sign-in only — step-up still demands a real
310// assertion" and RequireFresh does not distinguish the two. §14's owner
311// write is specified to sit behind step-up; built on RequireFresh it
312// would take a recovery code instead, and nothing else in the tree would
313// notice.
314func TestRecoveryCodeProducesAFreshSession(t *testing.T) {
315 app := newTestApp(t)
316 const addr = "person@example.invalid"
317
318 cookie := signInFully(t, app, addr)
319 enrol(t, app, cookie)
320 codes, err := app.regenerateRecoveryCodes(subjectOf(t, app, cookie))
321 if err != nil {
322 t.Fatal(err)
323 }
324
325 signIn(t, app, addr)
326 gated := redeem(t, app, capturedLink(t, app))
327
328 form := url.Values{"code": {codes[0]}}
329 req := httptest.NewRequest(http.MethodPost, "/passkey/signin/recovery", strings.NewReader(form.Encode()))
330 req.Host = app.credentialHost
331 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
332 req.Header.Set("Origin", app.origins.Credential)
333 for _, c := range (&http.Response{Header: gated.Header()}).Cookies() {
334 req.AddCookie(c)
335 }
336 w := httptest.NewRecorder()
337 app.Router().ServeHTTP(w, req)
338
339 recovered := sessionCookie(w)
340 if recovered == nil {
341 t.Fatalf("the recovery code did not sign anybody in (status %d)", w.Code)
342 }
343
344 // The RequireFresh-guarded page opens to it.
345 page := httptest.NewRequest(http.MethodGet, "/passkey/codes", nil)
346 page.Host = credentialHost
347 page.AddCookie(recovered)
348 pw := httptest.NewRecorder()
349 app.Router().ServeHTTP(pw, page)
350 if pw.Code != http.StatusOK {
351 t.Errorf("a recovery-code session got %d from the RequireFresh page; if this has "+
352 "changed, the note on codesFreshness needs revisiting", pw.Code)
353 }
354}
355
356// A stolen long-lived session cookie must not be able to enrol its own
357// passkey. With no operator reset (§5.2), enrolment by an attacker turns
358// a compromise that would have expired with the cookie into a permanent
359// lockout: the owner's next magic link lands on the Gate and stops, and
360// they have no recovery codes because they never enrolled.
361func TestEnrolmentNeedsAFreshSession(t *testing.T) {
362 app := newTestApp(t)
363 cookie := signInFully(t, app, "person@example.invalid")
364
365 // Fresh, straight after signing in: the normal path still works.
366 if rec := postJSON(t, app, "/passkey/register/begin", cookie, nil); rec.Code != http.StatusOK {
367 t.Fatalf("a fresh session got %d from register/begin, want 200", rec.Code)
368 }
369
370 // Aged past the window. Both columns, because sessions.Fresh falls
371 // back to At when AuthTime is zero.
372 old := time.Now().Add(-24 * time.Hour).UTC().Format(time.RFC3339)
373 if _, err := app.db.Writer().Exec(
374 `UPDATE sessions SET auth_time = ?, created_at = ?`, old, old); err != nil {
375 t.Fatal(err)
376 }
377
378 if rec := postJSON(t, app, "/passkey/register/begin", cookie, nil); rec.Code == http.StatusOK {
379 t.Error("a day-old session began a passkey enrolment")
380 }
381 if rec := postJSON(t, app, "/passkey/register/finish", cookie,
382 map[string]string{"clientDataJSON": "x", "attestationObject": "y"}); rec.Code == http.StatusOK {
383 t.Error("a day-old session finished a passkey enrolment")
384 }
385
386 // The page itself redirects to re-authenticate rather than 404ing or
387 // 403ing: a detour, not a dead end.
388 req := httptest.NewRequest(http.MethodGet, "/passkey/enrol", nil)
389 req.Host = app.credentialHost
390 req.AddCookie(cookie)
391 w := httptest.NewRecorder()
392 app.Router().ServeHTTP(w, req)
393 if w.Code != http.StatusSeeOther && w.Code != http.StatusFound {
394 t.Errorf("GET /passkey/enrol with a stale session = %d, want a redirect to re-auth", w.Code)
395 }
396}
397
398// The codes window must be at least as wide as the enrolment window.
399//
400// passkey.js sends the browser to /passkey/codes the moment registration
401// finishes. If a session can enrol but cannot then read its codes, the
402// person is bounced to re-authenticate holding a passkey and zero
403// recovery codes. That was real: enrolFreshness was 10 minutes and
404// codesFreshness 5, so a 7-minute-old session enrolled and was then
405// refused.
406func TestFreshnessWindowsDoNotStrandAnEnroller(t *testing.T) {
407 if codesFreshness < enrolFreshness {
408 t.Fatalf("codesFreshness (%s) is shorter than enrolFreshness (%s): a session can "+
409 "enrol a passkey and then be refused its recovery codes",
410 codesFreshness, enrolFreshness)
411 }
412}
413
414// And the same thing end to end, at a session age that used to fall in
415// the gap: enrol, then read the codes page, without re-authenticating.
416func TestEnrolThenReadCodesWithoutReauthenticating(t *testing.T) {
417 app := newTestApp(t)
418 cookie := signInFully(t, app, "person@example.invalid")
419
420 // Seven minutes old: inside the old enrol window, outside the old
421 // codes window.
422 aged := time.Now().Add(-7 * time.Minute).UTC().Format(time.RFC3339)
423 if _, err := app.db.Writer().Exec(
424 `UPDATE sessions SET auth_time = ?, created_at = ?`, aged, aged); err != nil {
425 t.Fatal(err)
426 }
427
428 enrol(t, app, cookie)
429
430 req := httptest.NewRequest(http.MethodGet, "/passkey/codes", nil)
431 req.Host = app.credentialHost
432 req.AddCookie(cookie)
433 w := httptest.NewRecorder()
434 app.Router().ServeHTTP(w, req)
435 if w.Code != http.StatusOK {
436 t.Errorf("a session that just enrolled got %d from /passkey/codes; it is holding "+
437 "a passkey and no recovery codes", w.Code)
438 }
439}
440