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 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "log/slog"
9 "net/http"
10 "net/url"
11 "sort"
12 "strings"
13 "sync"
14 "testing"
15
16 "amadan.net/oficina/home/internal/home/sealtest"
17)
18
19// §13 Codes: a full code sign-in, and the mail that carries the code.
20func TestNativeCodeSignIn(t *testing.T) {
21 t.Parallel()
22 app := newNativeApp(t)
23 d := newDevice(t)
24 start := d.start(t, app, sealtest.CanaryAddress)
25 mail, _ := app.mailer.last()
26 if mail.To != sealtest.CanaryAddress || mail.Subject != "Your Oficina ID code" || !strings.HasPrefix(mail.Body, "Your Oficina ID code is ") {
27 t.Fatalf("mail: %+v", mail)
28 }
29 if strings.Contains(mail.Body, "http") || strings.Contains(mail.Body, "oficina.works") {
30 t.Fatal("the code mail carries a link")
31 }
32 // No address at rest while the code is live: sealed, never readable.
33 sealtest.AssertNoPlaintext(t, app.dbPath)
34 w := d.verify(t, app, start, lastCode(t, app))
35 out := decodeReply(t, w)
36 if w.Code != 200 || len(out["grant"].(string)) != 43 || out["identity_id"] == "" || out["auth_time"] == nil {
37 t.Fatal("verify", w.Code, w.Body.String())
38 }
39 if n := count(t, app, "SELECT count(*) FROM home_id_native_starts"); n != 0 {
40 t.Fatal("a used start survived verify", n)
41 }
42 var method, platform string
43 if err := app.db.Writer().QueryRow("SELECT method,platform FROM home_id_grants").Scan(&method, &platform); err != nil || method != "email" || platform != "macos" {
44 t.Fatal("grant row", method, platform, err)
45 }
46 // The same person as the web door finds for that address.
47 session := signInFully(t, app, sealtest.CanaryAddress)
48 if out["identity_id"] != app.identityID(subjectOf(t, app, session)) {
49 t.Fatal("native code found a different person than /signin")
50 }
51 sealtest.AssertNoPlaintext(t, app.dbPath)
52}
53
54// §13 Codes: identical answers for known and unknown addresses.
55func TestNativeCodeStartIdenticalForKnownAndUnknown(t *testing.T) {
56 t.Parallel()
57 app := newNativeApp(t)
58 signInFully(t, app, "known@example.invalid")
59 shape := func(email string) (int, []string, []string) {
60 d := newDevice(t)
61 w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": d.public(), "platform": "ios"}, "")
62 var keys, headers []string
63 for k := range decodeReply(t, w) {
64 keys = append(keys, k)
65 }
66 for k := range w.Header() {
67 headers = append(headers, k)
68 }
69 sort.Strings(keys)
70 sort.Strings(headers)
71 return w.Code, keys, headers
72 }
73 c1, k1, h1 := shape("known@example.invalid")
74 c2, k2, h2 := shape("never-seen@example.invalid")
75 if c1 != 202 || c1 != c2 || fmt.Sprint(k1) != fmt.Sprint(k2) || fmt.Sprint(h1) != fmt.Sprint(h2) {
76 t.Fatal("known and unknown addresses differ", c1, c2, k1, k2, h1, h2)
77 }
78}
79
80// §13 Codes: entropy, expiry and single use.
81func TestNativeCodeEntropyExpiryAndSingleUse(t *testing.T) {
82 t.Parallel()
83 seen := map[string]bool{}
84 for range 200 {
85 c, err := newNativeCode()
86 if err != nil || !validCode(c) {
87 t.Fatal("bad code", c, err)
88 }
89 seen[c] = true
90 }
91 if len(seen) < 190 {
92 t.Fatal("codes repeat far too often", len(seen))
93 }
94 app := newNativeApp(t)
95 d := newDevice(t)
96 start := d.start(t, app, "a@example.invalid")
97 code := lastCode(t, app)
98 var mac string
99 app.db.Writer().QueryRow("SELECT code_mac FROM home_id_native_starts").Scan(&mac)
100 if strings.Contains(mac, code) {
101 t.Fatal("the code is at rest")
102 }
103 if w := d.verify(t, app, start, code); w.Code != 200 {
104 t.Fatal("first use", w.Code)
105 }
106 if w := d.verify(t, app, start, code); w.Code == 200 {
107 t.Fatal("a code worked twice")
108 }
109 // Expiry.
110 start = d.start(t, app, "a@example.invalid")
111 code = lastCode(t, app)
112 if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1"); err != nil {
113 t.Fatal(err)
114 }
115 if w := d.verify(t, app, start, code); w.Code == 200 {
116 t.Fatal("an expired code worked")
117 }
118 // A code is bound to its start.
119 other := newDevice(t)
120 d.start(t, app, "b@example.invalid")
121 c1 := lastCode(t, app)
122 s2 := other.start(t, app, "b@example.invalid")
123 if c2 := lastCode(t, app); c1 != c2 {
124 if w := other.verify(t, app, s2, c1); w.Code == 200 {
125 t.Fatal("one start's code opened another")
126 }
127 }
128}
129
130// §13 Codes: a code dies after five wrong tries.
131func TestNativeCodeDiesAfterFiveWrong(t *testing.T) {
132 t.Parallel()
133 app := newNativeApp(t)
134 d := newDevice(t)
135 start := d.start(t, app, "a@example.invalid")
136 code := lastCode(t, app)
137 wrong := "000000"
138 if code == wrong {
139 wrong = "111111"
140 }
141 for i := range 5 {
142 if w := d.verify(t, app, start, wrong); w.Code != 400 || decodeReply(t, w)["error"] != "code" {
143 t.Fatal("wrong try", i, w.Code, w.Body.String())
144 }
145 }
146 if w := d.verify(t, app, start, code); w.Code == 200 {
147 t.Fatal("the right code worked after five wrong tries")
148 }
149}
150
151// §13 Codes: persistent buckets survive a restart, and the per-(address,
152// key) wrong-code cap holds.
153func TestNativeCodeBucketsSurviveRestart(t *testing.T) {
154 t.Parallel()
155 app := newNativeApp(t)
156 for range 5 {
157 newDevice(t).start(t, app, "a@example.invalid")
158 }
159 // A restart forgets the web's in-memory budget; the native start cap
160 // is on disk and still refuses.
161 app = app.restart(t)
162 d := newDevice(t)
163 w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "a@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
164 if w.Code != 429 {
165 t.Fatal("per-address start cap forgot itself across a restart", w.Code)
166 }
167
168 // Wrong codes per (address, key): five per fifteen minutes, counted
169 // across codes (a resend gives a code fresh tries, never the address)
170 // and across a restart.
171 app = newNativeApp(t)
172 d = newDevice(t)
173 start := d.start(t, app, "b@example.invalid")
174 wrong := func() {
175 t.Helper()
176 if w := d.verify(t, app, start, "999999"); w.Code != 400 && lastCode(t, app) != "999999" {
177 t.Fatal("wrong code", w.Code)
178 }
179 }
180 for range 4 {
181 wrong()
182 }
183 if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil {
184 t.Fatal(err)
185 }
186 if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 202 {
187 t.Fatal("resend", w.Code)
188 }
189 app = app.restart(t)
190 wrong()
191 if w := d.verify(t, app, start, lastCode(t, app)); w.Code != 429 {
192 t.Fatal("a sixth guess in the window was judged", w.Code)
193 }
194}
195
196// §13 Codes: parallel starts cannot overspend a bucket.
197func TestNativeCodeParallelStartsHoldTheCap(t *testing.T) {
198 t.Parallel()
199 app := newNativeApp(t)
200 var wg sync.WaitGroup
201 var mu sync.Mutex
202 codes := map[int]int{}
203 devices := make([]*device, 12)
204 for i := range devices {
205 devices[i] = newDevice(t)
206 }
207 for _, d := range devices {
208 wg.Add(1)
209 go func() {
210 defer wg.Done()
211 w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "p@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
212 mu.Lock()
213 codes[w.Code]++
214 mu.Unlock()
215 }()
216 }
217 wg.Wait()
218 if codes[202] != 5 || codes[429] != 7 {
219 t.Fatal("parallel starts overspent the address", codes)
220 }
221}
222
223// §13 Codes: the daily cap, the returning-key exemption, and its exclusions.
224func TestNativeCodeDailyCapAndReturningKeys(t *testing.T) {
225 t.Parallel()
226 for _, tc := range []struct {
227 reason string
228 returning bool
229 }{
230 // End to end for one of each kind; TestNativeReturningKeyRule and
231 // the end_reason CHECK cover the rest without a sign-in apiece.
232 {"", true}, {"expiry", true}, {"all_devices", false},
233 } {
234 t.Run("ended="+tc.reason, func(t *testing.T) {
235 app := newNativeApp(t)
236 const email = "victim@example.invalid"
237 mine := newDevice(t)
238 grant, _ := mine.signInByCode(t, app, email)
239 if tc.reason != "" {
240 if _, err := app.db.Writer().Exec("UPDATE home_id_grants SET ended_at=1,end_reason=? WHERE grant_hash=?", tc.reason, nativeHash(grant)); err != nil {
241 t.Fatal(err)
242 }
243 }
244 // An attacker spends the address's new-device guesses: four
245 // starts, five wrong codes each.
246 for range 4 {
247 a := newDevice(t)
248 start := a.start(t, app, email)
249 code := lastCode(t, app)
250 wrong := "000000"
251 if code == wrong {
252 wrong = "000001"
253 }
254 for range 5 {
255 a.verify(t, app, start, wrong)
256 }
257 }
258 stranger := newDevice(t)
259 w := stranger.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": stranger.public(), "platform": "macos"}, "")
260 if w.Code != 429 || decodeReply(t, w)["error"] != "daily_limit" {
261 t.Fatal("a new device started past the daily cap", w.Code, w.Body.String())
262 }
263 app = app.restart(t) // a fresh web budget: only the native caps speak
264 w = mine.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": mine.public(), "platform": "macos"}, "")
265 if tc.returning {
266 if w.Code != 202 {
267 t.Fatal("a returning device was blocked", w.Code, w.Body.String())
268 }
269 start := decodeReply(t, w)["start"].(string)
270 if v := mine.verify(t, app, start, lastCode(t, app)); v.Code != 200 {
271 t.Fatal("a returning device could not verify", v.Code, v.Body.String())
272 }
273 } else if w.Code != 429 || decodeReply(t, w)["error"] != "daily_limit" {
274 t.Fatal("a cut-off device was treated as returning", w.Code, w.Body.String())
275 }
276 })
277 }
278}
279
280// The 429 markers: daily_limit is only the daily wrong-code cap for new
281// devices, at start and at verify; every other limit is rate_limited.
282func TestNativeCode429Markers(t *testing.T) {
283 t.Parallel()
284 app := newNativeApp(t)
285 const email = "marker@example.invalid"
286 waiting := newDevice(t)
287 held := waiting.start(t, app, email) // a new device holding a live code
288 for range 3 {
289 a := newDevice(t)
290 start := a.start(t, app, email)
291 for range 5 {
292 a.verify(t, app, start, "000000")
293 }
294 }
295 // 15 wrong so far; five more from the waiting device fill the cap.
296 for i := range 5 {
297 if w := waiting.verify(t, app, held, "000000"); w.Code != 400 && lastCode(t, app) != "000000" {
298 t.Fatal("wrong", i, w.Code)
299 }
300 }
301 late := newDevice(t)
302 w := late.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": late.public(), "platform": "macos"}, "")
303 if w.Code != 429 || decodeReply(t, w)["error"] != "daily_limit" {
304 t.Fatal("start past the daily cap", w.Code, w.Body.String())
305 }
306 // A verify past the cap, from a new device with a live start.
307 app = app.restart(t)
308 if _, err := app.db.Writer().Exec("DELETE FROM home_id_native_buckets WHERE bucket LIKE 'start-%'"); err != nil {
309 t.Fatal(err)
310 }
311 other := newDevice(t)
312 if _, err := app.db.Writer().Exec("UPDATE home_id_native_buckets SET count=count-1 WHERE bucket LIKE 'wrong-new-day:%'"); err != nil {
313 t.Fatal(err)
314 }
315 start := other.start(t, app, email)
316 if _, err := app.db.Writer().Exec("UPDATE home_id_native_buckets SET count=count+1 WHERE bucket LIKE 'wrong-new-day:%'"); err != nil {
317 t.Fatal(err)
318 }
319 if w := other.verify(t, app, start, lastCode(t, app)); w.Code != 429 || decodeReply(t, w)["error"] != "daily_limit" {
320 t.Fatal("verify past the daily cap", w.Code, w.Body.String())
321 }
322 // Any other limit: the per-address start window.
323 app = newNativeApp(t)
324 for range 5 {
325 newDevice(t).start(t, app, "window@example.invalid")
326 }
327 app = app.restart(t)
328 d := newDevice(t)
329 if w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "window@example.invalid", "device_key": d.public(), "platform": "macos"}, ""); w.Code != 429 || decodeReply(t, w)["error"] != "rate_limited" {
330 t.Fatal("window limit marker", w.Code, w.Body.String())
331 }
332}
333
334// §13 Codes: an exempt key keeps its own limit.
335func TestNativeCodeExemptKeyKeepsItsOwnLimit(t *testing.T) {
336 t.Parallel()
337 app := newNativeApp(t)
338 d := newDevice(t)
339 d.signInByCode(t, app, "e@example.invalid")
340 for range 4 {
341 d.start(t, app, "e@example.invalid")
342 }
343 app = app.restart(t)
344 w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "e@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
345 if w.Code != 429 {
346 t.Fatal("a returning key started six times in fifteen minutes", w.Code)
347 }
348}
349
350// §13 Codes: one email allowance shared with the web, both ways.
351func TestNativeCodeSharesTheWebEmailBudget(t *testing.T) {
352 t.Parallel()
353 app := newNativeApp(t)
354 for range 5 {
355 signIn(t, app, "shared@example.invalid")
356 }
357 d := newDevice(t)
358 w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "shared@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
359 if w.Code != 429 {
360 t.Fatal("native start ignored the web's spent budget", w.Code)
361 }
362 app = newNativeApp(t)
363 for range 5 {
364 newDevice(t).start(t, app, "shared@example.invalid")
365 }
366 if rec := signIn(t, app, "shared@example.invalid"); rec.Code != http.StatusTooManyRequests {
367 t.Fatal("the web ignored native starts", rec.Code)
368 }
369}
370
371// §13 Codes: per-IP-bucket live starts, IPv6 by /64, and 503 when full.
372func TestNativeCodeLiveStartLimits(t *testing.T) {
373 app := newNativeApp(t)
374 for i := range 20 {
375 newDevice(t).start(t, app, fmt.Sprintf("ip%d@example.invalid", i))
376 }
377 if _, err := app.db.Writer().Exec("DELETE FROM home_id_native_buckets"); err != nil {
378 t.Fatal(err)
379 }
380 d := newDevice(t)
381 w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "ip-last@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
382 if w.Code != 429 {
383 t.Fatal("a 21st live start from one IP bucket", w.Code)
384 }
385 if w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "ip-last@example.invalid", "device_key": d.public(), "platform": "macos"}, "", proofOpts{ip: "198.51.100.7:1"}); w.Code != 202 {
386 t.Fatal("another IP was refused", w.Code)
387 }
388 a := httpRequestFrom("[2001:db8:1:2:aaaa::1]:1")
389 b := httpRequestFrom("[2001:db8:1:2:bbbb::9]:1")
390 c := httpRequestFrom("[2001:db8:1:3::1]:1")
391 if nativeIPBucket(a) != nativeIPBucket(b) || nativeIPBucket(a) == nativeIPBucket(c) || nativeIPBucket(httpRequestFrom("192.0.2.1:1")) != "192.0.2.1" {
392 t.Fatal("IP buckets", nativeIPBucket(a), nativeIPBucket(b), nativeIPBucket(c))
393 }
394
395 // Full: new starts get 503, an existing start still verifies.
396 app = newNativeApp(t)
397 keep := newDevice(t)
398 start := keep.start(t, app, "keep@example.invalid")
399 code := lastCode(t, app)
400 if nativeLiveStarts != 10000 {
401 t.Fatal("the live-start table's size moved", nativeLiveStarts)
402 }
403 prev := nativeLiveStarts
404 nativeLiveStarts = 100
405 t.Cleanup(func() { nativeLiveStarts = prev })
406 tx, err := app.db.Writer().Begin()
407 if err != nil {
408 t.Fatal(err)
409 }
410 for i := range nativeLiveStarts - 1 {
411 if _, err := tx.Exec("INSERT INTO home_id_native_starts VALUES(?,x'00',?,?,?,'',?,1,0,0,?)", fmt.Sprint("fill", i), fmt.Sprint("b", i), "k", "macos", "m", int64(1<<40)); err != nil {
412 t.Fatal(err)
413 }
414 }
415 if err := tx.Commit(); err != nil {
416 t.Fatal(err)
417 }
418 d = newDevice(t)
419 w = d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "late@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
420 if w.Code != 503 || decodeReply(t, w)["error"] != "full" {
421 t.Fatal("a full table took a start", w.Code, w.Body.String())
422 }
423 if v := keep.verify(t, app, start, code); v.Code != 200 {
424 t.Fatal("a full table refused an existing start", v.Code)
425 }
426 // The web's link sign-in is unaffected.
427 if rec := signIn(t, app, "web@example.invalid"); rec.Code != http.StatusSeeOther {
428 t.Fatal("a full native table blocked the web", rec.Code)
429 }
430}
431
432func httpRequestFrom(addr string) *http.Request {
433 r, _ := http.NewRequest("POST", Origin, nil)
434 r.RemoteAddr = addr
435 return r
436}
437
438// §13 Codes: no grant from a code alone on an enrolled account.
439func TestNativeCodeOnEnrolledAccountNeedsPasskey(t *testing.T) {
440 t.Parallel()
441 app := newNativeApp(t)
442 session := signInFully(t, app, sealtest.CanaryAddress)
443 enrol(t, app, session)
444 d := newDevice(t)
445 start := d.start(t, app, sealtest.CanaryAddress)
446 w := d.verify(t, app, start, lastCode(t, app))
447 out := decodeReply(t, w)
448 if w.Code != 200 || out["grant"] != nil || out["pending"] == nil || fmt.Sprint(out["factor"]) != "[passkey]" {
449 t.Fatal("a code alone opened an enrolled account", w.Code, w.Body.String())
450 }
451 if n := count(t, app, "SELECT count(*) FROM home_id_grants"); n != 0 {
452 t.Fatal("a grant row exists", n)
453 }
454}
455
456// §13 Codes: no address and no code in any log line, the failure paths
457// included.
458func TestNativeCodeNothingInLogs(t *testing.T) {
459 t.Parallel()
460 app := newNativeApp(t)
461 var buf bytes.Buffer
462 app.logger = slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
463 d := newDevice(t)
464 start := d.start(t, app, sealtest.CanaryAddress)
465 code := lastCode(t, app)
466 d.verify(t, app, start, "123456")
467 d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, "")
468 d.verify(t, app, start, code)
469 app.secrets.Mailer = failingMailer{}
470 app.flow.Mailer = failingMailer{}
471 e := newDevice(t)
472 w := e.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "other-" + sealtest.CanaryAddress, "device_key": e.public(), "platform": "macos"}, "")
473 if w.Code != 503 {
474 t.Fatal("failed mail answered", w.Code)
475 }
476 for _, needle := range []string{sealtest.CanaryAddress, url.QueryEscape(sealtest.CanaryAddress), code, start} {
477 if strings.Contains(buf.String(), needle) || strings.Contains(w.Body.String(), needle) {
478 t.Fatalf("%q reached a log line or an error", needle)
479 }
480 }
481 if !strings.Contains(buf.String(), "native code delivery failed") {
482 t.Fatal("the failure path did not run")
483 }
484 sealtest.AssertNoPlaintext(t, app.dbPath)
485}
486
487type failingMailer struct{}
488
489func (failingMailer) Send(context.Context, string, string, string) error {
490 return errors.New("smtp down")
491}
492
493// Resend replaces the code, three sends at most, thirty seconds apart.
494func TestNativeCodeResend(t *testing.T) {
495 t.Parallel()
496 app := newNativeApp(t)
497 d := newDevice(t)
498 start := d.start(t, app, "r@example.invalid")
499 first := lastCode(t, app)
500 if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 429 {
501 t.Fatal("resend inside thirty seconds", w.Code)
502 }
503 for i := range 2 {
504 if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil {
505 t.Fatal(err)
506 }
507 if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 202 {
508 t.Fatal("resend", i, w.Code, w.Body.String())
509 }
510 }
511 if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil {
512 t.Fatal(err)
513 }
514 if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 429 {
515 t.Fatal("a fourth send", w.Code)
516 }
517 latest := lastCode(t, app)
518 if latest != first {
519 if w := d.verify(t, app, start, first); w.Code == 200 {
520 t.Fatal("a replaced code still worked")
521 }
522 }
523 if w := d.verify(t, app, start, latest); w.Code != 200 {
524 t.Fatal("the latest code failed", w.Code)
525 }
526 // A resend must be signed by the start's own key.
527 start = d.start(t, app, "s@example.invalid")
528 if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil {
529 t.Fatal(err)
530 }
531 if w := newDevice(t).call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 401 {
532 t.Fatal("another key resent", w.Code)
533 }
534 if w := newDevice(t).verify(t, app, start, lastCode(t, app)); w.Code != 401 {
535 t.Fatal("another key verified", w.Code)
536 }
537}
538