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 "encoding/base64"
6 "encoding/json"
7 "fmt"
8 "log/slog"
9 "net/http/httptest"
10 "net/url"
11 "strings"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/home/internal/home/sealtest"
16 "amadan.net/rastrillo/rastrillo/sessions"
17 "amadan.net/rastrillo/rastrillo/webauthn/authtest"
18)
19
20func fullMailbox(a *testApp) {
21 a.mailboxes.mu.Lock()
22 defer a.mailboxes.mu.Unlock()
23 if a.mailboxes.entries == nil {
24 a.mailboxes.entries = map[string]mailboxProof{}
25 }
26 for i := len(a.mailboxes.entries); i < 1000; i++ {
27 a.mailboxes.entries[fmt.Sprint("filler", i)] = mailboxProof{expires: time.Now().Unix() + 300}
28 }
29}
30func TestIDFullMailboxAllowsGatedSignin(t *testing.T) {
31 a := newTestApp(t)
32 s := signInFully(t, a, sealtest.CanaryAddress)
33 k := enrol(t, a, s)
34 fullMailbox(a)
35 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
36 if g.Code != 303 || g.Header().Get("Location") != confirmPath {
37 t.Fatal("RAM capacity blocked email gate", g.Code)
38 }
39 var at int64
40 if err := a.db.Writer().QueryRow("SELECT mailbox_at FROM passkey_pending").Scan(&at); err != nil || at != 0 {
41 t.Fatal("gate advertised unavailable mailbox proof", at, err)
42 }
43 b := idJSON(t, a, "/passkey/signin/begin", nil, g.Result().Cookies()...)
44 r := idJSON(t, a, "/passkey/signin/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), g.Result().Cookies()...)
45 if r.Code != 200 || sessionCookie(r) == nil {
46 t.Fatal("gated passkey refused", r.Code)
47 }
48}
49func TestIDRecoveryMailboxFailurePreservesCode(t *testing.T) {
50 for _, kind := range []string{"missing", "full"} {
51 t.Run(kind, func(t *testing.T) {
52 a := newTestApp(t)
53 s := signInFully(t, a, sealtest.CanaryAddress)
54 enrol(t, a, s)
55 codes := idCodes(t, a, s)
56 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
57 if kind == "missing" {
58 a.mailboxes.entries = map[string]mailboxProof{}
59 } else {
60 fullMailbox(a)
61 }
62 r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
63 if sessionCookie(r) != nil {
64 t.Fatal("recovered without reserving RAM proof")
65 }
66 var n int
67 a.db.Writer().QueryRow("SELECT count(*) FROM passkey_recovery_codes").Scan(&n)
68 if n != 10 {
69 t.Fatal("RAM failure consumed code", n)
70 }
71 a.db.Writer().QueryRow("SELECT count(*) FROM passkey_pending").Scan(&n)
72 if n != 1 {
73 t.Fatal("RAM failure consumed gate", n)
74 }
75 })
76 }
77}
78func TestIDRecoverySigninNotice(t *testing.T) {
79 a := newTestApp(t)
80 s := signInFully(t, a, sealtest.CanaryAddress)
81 enrol(t, a, s)
82 codes := idCodes(t, a, s)
83 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
84 r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
85 if sessionCookie(r) == nil {
86 t.Fatal("recovery failed")
87 }
88 m, ok := a.mailer.last()
89 if !ok || m.Subject != "A recovery code was used for your Oficina account" || m.To != sealtest.CanaryAddress {
90 t.Fatal("redemption notice missing")
91 }
92 // Delivery must leave the RAM proof available for replacement.
93 if p := exchangeRequest(a.App, "GET", Origin+"/passkey/replace", "", nil, r.Result().Cookies()...); p.Code != 200 {
94 t.Fatal("notice consumed replacement proof")
95 }
96 sealtest.AssertNoPlaintext(t, a.dbPath)
97}
98func TestIDRecoveryCannotLink(t *testing.T) {
99 p := newExchangePair(t)
100 _, intent := p.startFresh(t, nil)
101 s := signInFully(t, p.credential, sealtest.CanaryAddress)
102 if _, err := p.credential.db.Writer().Exec("UPDATE sessions SET method='email+recovery'"); err != nil {
103 t.Fatal(err)
104 }
105 for _, method := range []string{"GET", "POST"} {
106 r := exchangeRequest(p.credential.App, method, Origin+"/authorize/resume", Origin, nil, intent, s)
107 if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin") {
108 t.Fatal("recovery satisfied linking", method, r.Code)
109 }
110 }
111}
112func TestIDDirectFloodLeavesGatedCapacity(t *testing.T) {
113 a := newTestApp(t)
114 s := signInFully(t, a, sealtest.CanaryAddress)
115 enrol(t, a, s)
116 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
117 for i := 0; i < 10001; i++ {
118 r := idJSON(t, a, "/passkey/direct/begin", nil)
119 if r.Code != 200 {
120 t.Fatal("direct begin refused", i)
121 }
122 if i == 0 {
123 var n int
124 a.db.Writer().QueryRow("SELECT (SELECT count(*) FROM home_id_ceremonies)+(SELECT count(*) FROM home_id_direct_used)").Scan(&n)
125 if n != 0 {
126 t.Fatal("anonymous begin stored challenge")
127 }
128 }
129 }
130 var n int
131 if err := a.db.Writer().QueryRow("SELECT (SELECT count(*) FROM home_id_ceremonies)+(SELECT count(*) FROM home_id_direct_used)").Scan(&n); err != nil || n != 0 {
132 t.Fatal("anonymous begins retained state", n, err)
133 }
134 if r := idJSON(t, a, "/passkey/signin/begin", nil, g.Result().Cookies()...); r.Code != 200 {
135 t.Fatal("flood blocked authenticated gate")
136 }
137}
138func TestIDDirectSealedChallenge(t *testing.T) {
139 for _, kind := range []string{"tampered", "expired", "future", "mismatch"} {
140 t.Run(kind, func(t *testing.T) {
141 a := newTestApp(t)
142 s := signInFully(t, a, sealtest.CanaryAddress)
143 k := enrol(t, a, s)
144 b := idJSON(t, a, "/passkey/direct/begin", nil)
145 c := namedCookie(t, b, ceremonyCookie)
146 raw, err := base64.RawURLEncoding.DecodeString(c.Value)
147 if err != nil {
148 t.Fatal(err)
149 }
150 plain, err := a.secrets.Sealer.Open("id.direct", raw)
151 if err != nil {
152 t.Fatal("direct challenge is not sealed")
153 }
154 var proof map[string]any
155 if json.Unmarshal(plain, &proof) != nil {
156 t.Fatal("invalid proof")
157 }
158 switch kind {
159 case "tampered":
160 raw[len(raw)-1] ^= 1
161 default:
162 switch kind {
163 case "expired":
164 proof["expires"] = time.Now().Unix() - 1
165 case "future":
166 proof["expires"] = time.Now().Unix() + 600
167 case "mismatch":
168 proof["challenge"] = strings.Repeat("0", 64)
169 }
170 plain, _ = json.Marshal(proof)
171 raw, err = a.secrets.Sealer.Seal("id.direct", plain)
172 if err != nil {
173 t.Fatal(err)
174 }
175 }
176 c.Value = base64.RawURLEncoding.EncodeToString(raw)
177 r := idJSON(t, a, "/passkey/direct/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), c)
178 if r.Code == 200 {
179 t.Fatal("invalid sealed proof accepted", kind)
180 }
181 })
182 }
183}
184func TestIDRecoveryExclusions(t *testing.T) {
185 a, cookies, _ := replacementFixture(t)
186 if r := idJSON(t, a, "/passkey/register/begin", nil, cookies...); r.Code == 200 {
187 t.Fatal("recovery enrolled directly")
188 }
189 if r := exchangeRequest(a.App, "POST", Origin+"/passkey/codes", Origin, url.Values{}, cookies...); r.Code == 200 {
190 t.Fatal("recovery generated codes")
191 }
192}
193func TestIDReplacementRequiresRecoverySession(t *testing.T) {
194 for _, kind := range []string{"method", "session"} {
195 t.Run(kind, func(t *testing.T) {
196 a, cookies, body := replacementFixture(t)
197 if kind == "method" {
198 a.db.Writer().Exec("UPDATE sessions SET method='email'")
199 } else {
200 var token string
201 for _, c := range cookies {
202 if c.Name == a.sessions.CookieName() {
203 token = c.Value
204 }
205 }
206 // Change only the proof's session binding, keeping person and RAM proof valid.
207 a.db.Writer().Exec("UPDATE home_id_recovery_proofs SET session_hash=?", sessions.HashToken(token+"different"))
208 }
209 r := idJSON(t, a, "/passkey/replace/finish", body, cookies...)
210 if r.Code == 200 {
211 t.Fatal("replacement accepted wrong session authority", kind)
212 }
213 })
214 }
215}
216func TestIDLimitsBeforeValidCode(t *testing.T) {
217 for _, bucket := range []string{"account", "ip"} {
218 t.Run(bucket, func(t *testing.T) {
219 a := newTestApp(t)
220 s := signInFully(t, a, sealtest.CanaryAddress)
221 enrol(t, a, s)
222 codes := idCodes(t, a, s)
223 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
224 key := "account:" + subjectOf(t, a, s)
225 limit := 5
226 if bucket == "ip" {
227 req := httptest.NewRequest("POST", Origin+"/", nil)
228 key = "ip:" + blindIndex(a.secrets.Pepper, clientIP(req))
229 limit = 20
230 }
231 a.db.Writer().Exec("INSERT INTO home_id_attempts VALUES(?,?,?)", key, limit, time.Now().Unix()+900)
232 r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
233 if sessionCookie(r) != nil {
234 t.Fatal("valid code bypassed exhausted budget")
235 }
236 var n int
237 a.db.Writer().QueryRow("SELECT count(*) FROM passkey_recovery_codes").Scan(&n)
238 if n != 10 {
239 t.Fatal("budget refusal consumed valid code", n)
240 }
241 })
242 }
243}
244
245func TestIDRecoverySigninNoticeFailurePrivacy(t *testing.T) {
246 a := newTestApp(t)
247 s := signInFully(t, a, sealtest.CanaryAddress)
248 enrol(t, a, s)
249 codes := idCodes(t, a, s)
250 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
251 var logs bytes.Buffer
252 a.logger = slog.New(slog.NewTextHandler(&logs, nil))
253 a.secrets.Mailer = idFailMailer{}
254 r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
255 if sessionCookie(r) == nil {
256 t.Fatal("notice failure rolled back recovery")
257 }
258 if strings.Contains(logs.String(), sealtest.CanaryAddress) {
259 t.Fatal("notice error leaked address")
260 }
261 sealtest.AssertNoPlaintext(t, a.dbPath)
262}
263func TestIDLegacyRecoveryCodesStillRedeem(t *testing.T) {
264 a := newTestApp(t)
265 s := signInFully(t, a, sealtest.CanaryAddress)
266 enrol(t, a, s)
267 codes, err := a.regenerateRecoveryCodes(subjectOf(t, a, s))
268 if err != nil {
269 t.Fatal(err)
270 }
271 if len(normalizeIDCode(codes[0])) != 10 {
272 t.Fatal("fixture no longer exercises legacy 50-bit format")
273 }
274 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
275 r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
276 if sessionCookie(r) == nil {
277 t.Fatal("legacy code rejected")
278 }
279}
280func TestIDDirectReceiptsBounded(t *testing.T) {
281 for _, kind := range []string{"capacity", "expiry", "invalid-proof", "restart"} {
282 t.Run(kind, func(t *testing.T) {
283 a := newTestApp(t)
284 s := signInFully(t, a, sealtest.CanaryAddress)
285 k := enrol(t, a, s)
286 b := idJSON(t, a, "/passkey/direct/begin", nil)
287 c := namedCookie(t, b, ceremonyCookie)
288 zero := uint32(0)
289 opts := authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}
290 if kind == "capacity" || kind == "expiry" {
291 exp := time.Now().Unix() + 300
292 if kind == "expiry" {
293 exp = 0
294 }
295 if _, err := a.db.Writer().Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10000) INSERT INTO home_id_direct_used SELECT printf('%064x',x),? FROM n", exp); err != nil {
296 t.Fatal(err)
297 }
298 }
299 if kind == "invalid-proof" {
300 opts.CorruptSig = true
301 }
302 body := assertionBody(k, challengeFrom(t, b), opts)
303 r := idJSON(t, a, "/passkey/direct/finish", body, c)
304 switch kind {
305 case "capacity":
306 if r.Code != 200 {
307 t.Fatal("another credential can exhaust direct sign-in")
308 }
309 case "expiry":
310 if r.Code != 200 {
311 t.Fatal("expired receipts not reclaimed")
312 }
313 case "invalid-proof":
314 var n int
315 a.db.Writer().QueryRow("SELECT count(*) FROM home_id_direct_used").Scan(&n)
316 if n != 0 {
317 t.Fatal("invalid proof retained receipt")
318 }
319 case "restart":
320 if r.Code != 200 {
321 t.Fatal("first signin failed")
322 }
323 app, err := New(a.secrets, a.db, a.logger)
324 if err != nil {
325 t.Fatal(err)
326 }
327 a.App = app
328 if replay := idJSON(t, a, "/passkey/direct/finish", body, c); replay.Code == 200 {
329 t.Fatal("restart allowed replay")
330 }
331 }
332 })
333 }
334}
335
336func TestIDRecoveryMailboxTimeDefense(t *testing.T) {
337 for _, at := range []int64{0, time.Now().Unix() - 600, time.Now().Unix() + 600} {
338 a := newTestApp(t)
339 s := signInFully(t, a, sealtest.CanaryAddress)
340 enrol(t, a, s)
341 codes := idCodes(t, a, s)
342 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
343 // Keep the independent RAM proof live while checking persisted freshness.
344 if _, err := a.db.Writer().Exec("UPDATE passkey_pending SET mailbox_at=?", at); err != nil {
345 t.Fatal(err)
346 }
347 r := exchangeRequest(a.App, "POST", Origin+"/passkey/signin/recovery", Origin, url.Values{"code": {codes[0]}}, g.Result().Cookies()...)
348 if sessionCookie(r) != nil {
349 t.Fatal("invalid persisted mailbox time accepted", at)
350 }
351 }
352}
353