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 "encoding/base64"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "net/http/httptest"
9 "strings"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/home/internal/home/sealtest"
14 "amadan.net/rastrillo/rastrillo/webauthn/authtest"
15)
16
17func idJSON(t *testing.T, app *testApp, path string, body any, cookies ...*http.Cookie) *httptest.ResponseRecorder {
18 t.Helper()
19 b, err := json.Marshal(body)
20 if err != nil {
21 t.Fatal(err)
22 }
23 req := httptest.NewRequest("POST", app.origins.Credential+path, strings.NewReader(string(b)))
24 req.Header.Set("Origin", app.origins.Credential)
25 req.Header.Set("Content-Type", "application/json")
26 for _, c := range cookies {
27 if c != nil {
28 req.AddCookie(c)
29 }
30 }
31 w := httptest.NewRecorder()
32 app.Router().ServeHTTP(w, req)
33 return w
34}
35func assertionBody(a *authtest.Authenticator, challenge []byte, opts authtest.Options) map[string]string {
36 cd, ad, sig, _ := a.Get(challenge, opts)
37 return map[string]string{"id": base64.RawURLEncoding.EncodeToString(a.CredID), "clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "authenticatorData": base64.RawURLEncoding.EncodeToString(ad), "signature": base64.RawURLEncoding.EncodeToString(sig)}
38}
39func TestIDDirectPasskey(t *testing.T) {
40 app := newTestApp(t)
41 session := signInFully(t, app, sealtest.CanaryAddress)
42 key := enrol(t, app, session)
43 begin := idJSON(t, app, "/passkey/direct/begin", nil)
44 challenge := challengeFrom(t, begin)
45 cookie := namedCookie(t, begin, "__Host-oficina-ceremony")
46 zero := uint32(0)
47 body := assertionBody(key, challenge, authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero})
48 wrong := idJSON(t, app, "/passkey/direct/finish", body)
49 if sessionCookie(wrong) != nil || wrong.Code == 200 {
50 t.Fatal("unbound browser signed in")
51 }
52 done := idJSON(t, app, "/passkey/direct/finish", body, cookie)
53 if done.Code != 200 || sessionCookie(done) == nil {
54 t.Fatal("direct sign-in failed", done.Code)
55 }
56 if subjectOf(t, app, sessionCookie(done)) != subjectOf(t, app, session) {
57 t.Fatal("wrong person")
58 }
59 replay := idJSON(t, app, "/passkey/direct/finish", body, cookie)
60 if sessionCookie(replay) != nil || replay.Code == 200 {
61 t.Fatal("replay signed in")
62 }
63 sealtest.AssertNoPlaintext(t, app.dbPath)
64}
65func TestIDPasskeyRejectsBadProofs(t *testing.T) {
66 for _, kind := range []string{"origin", "rp", "uv", "signature", "unknown"} {
67 t.Run(kind, func(t *testing.T) {
68 app := newTestApp(t)
69 s := signInFully(t, app, sealtest.CanaryAddress)
70 key := enrol(t, app, s)
71 begin := idJSON(t, app, "/passkey/direct/begin", nil)
72 challenge := challengeFrom(t, begin)
73 c := namedCookie(t, begin, "__Host-oficina-ceremony")
74 opts := authtest.Options{RPID: credentialHost, Origin: Origin}
75 switch kind {
76 case "origin":
77 opts.Origin = "https://evil.invalid"
78 case "rp":
79 opts.RPID = "oficina.works"
80 case "uv":
81 opts.Flags = authtest.FlagUserPresent
82 case "signature":
83 opts.CorruptSig = true
84 case "unknown":
85 key, _ = authtest.New()
86
87 }
88 r := idJSON(t, app, "/passkey/direct/finish", assertionBody(key, challenge, opts), c)
89 if r.Code == 200 || sessionCookie(r) != nil {
90 t.Fatal("bad proof signed in", kind)
91 }
92 })
93 }
94}
95func TestIDEnrollmentCannotTransferCredential(t *testing.T) {
96 app := newTestApp(t)
97 first := signInFully(t, app, sealtest.CanaryAddress)
98 key := enrol(t, app, first)
99 second := signInFully(t, app, "other@example.invalid")
100 challenge := challengeFrom(t, idJSON(t, app, "/passkey/register/begin", nil, second))
101 cd, att := key.Create(challenge, authtest.Options{RPID: credentialHost, Origin: Origin})
102 got := idJSON(t, app, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, second)
103 if got.Code == 200 {
104 t.Fatal("credential transferred to another person")
105 }
106}
107
108func TestIDGateOffersBoundLegacyCredentials(t *testing.T) {
109 a := newTestApp(t)
110 s := signInFully(t, a, sealtest.CanaryAddress)
111 key := enrol(t, a, s)
112 if _, err := a.db.Writer().Exec("DELETE FROM home_id_discoverable"); err != nil {
113 t.Fatal(err)
114 }
115 gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
116 begin := idJSON(t, a, "/passkey/signin/begin", nil, gated.Result().Cookies()...)
117 var body struct {
118 Credentials []string `json:"credentials"`
119 }
120 json.Unmarshal(begin.Body.Bytes(), &body)
121 if len(body.Credentials) != 1 || body.Credentials[0] != base64.RawURLEncoding.EncodeToString(key.CredID) {
122 t.Fatal("legacy gate omitted bound credential IDs")
123 }
124 r := idJSON(t, a, "/passkey/signin/finish", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}), gated.Result().Cookies()...)
125 if r.Code != 200 {
126 t.Fatal("legacy gated signin failed", r.Code)
127 }
128}
129
130func TestIDCeremonyRejectsAmbiguousJSON(t *testing.T) {
131 for _, kind := range []string{"trailing", "duplicate"} {
132 t.Run(kind, func(t *testing.T) {
133 a := newTestApp(t)
134 s := signInFully(t, a, sealtest.CanaryAddress)
135 key := enrol(t, a, s)
136 begin := idJSON(t, a, "/passkey/direct/begin", nil)
137 cookie := namedCookie(t, begin, ceremonyCookie)
138 body := assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin})
139 b, _ := json.Marshal(body)
140 if kind == "trailing" {
141 b = append(b, []byte(` {}`)...)
142 } else {
143 b = append([]byte(`{"id":"ignored",`), b[1:]...)
144 }
145 req := httptest.NewRequest("POST", Origin+"/passkey/direct/finish", strings.NewReader(string(b)))
146 req.Header.Set("Origin", Origin)
147 req.AddCookie(cookie)
148 w := httptest.NewRecorder()
149 a.Router().ServeHTTP(w, req)
150 if w.Code == 200 || sessionCookie(w) != nil {
151 t.Fatal("ambiguous ceremony JSON accepted")
152 }
153 })
154 }
155}
156func TestIDEnrollmentBound(t *testing.T) {
157 a := newTestApp(t)
158 s := signInFully(t, a, sealtest.CanaryAddress)
159 key := enrol(t, a, s)
160 subject := subjectOf(t, a, s)
161 for i := 0; i < 99; i++ {
162 if _, err := a.db.Writer().Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,0,'2026-11-13')", fmt.Sprintf("%064x", i), subject, key.COSEKey()); err != nil {
163 t.Fatal(err)
164 }
165 }
166 begin := idJSON(t, a, "/passkey/register/begin", nil, s)
167 next, _ := authtest.New()
168 cd, att := next.Create(challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin})
169 r := idJSON(t, a, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, s)
170 if r.Code == 200 {
171 t.Fatal("enrollment exceeded the gated allowlist bound")
172 }
173}
174
175func TestIDEnrollmentRejectsFutureAndPassiveAuthentication(t *testing.T) {
176 for _, kind := range []string{"future", "passive"} {
177 t.Run(kind, func(t *testing.T) {
178 a := newTestApp(t)
179 s := signInFully(t, a, sealtest.CanaryAddress)
180 query := "UPDATE sessions SET auth_time=?"
181 value := time.Now().Add(time.Hour).UTC().Format(time.RFC3339)
182 if kind == "passive" {
183 query = "UPDATE sessions SET auth_time=?,method='keymail'"
184 value = ""
185 }
186 if _, err := a.db.Writer().Exec(query, value); err != nil {
187 t.Fatal(err)
188 }
189 if r := idJSON(t, a, "/passkey/register/begin", nil, s); r.Code == 200 {
190 t.Fatal("enrollment accepted non-fresh authentication", kind)
191 }
192 })
193 }
194}
195
196func TestIDGateBindsCredentialOwner(t *testing.T) {
197 a := newTestApp(t)
198 first := signInFully(t, a, sealtest.CanaryAddress)
199 enrol(t, a, first)
200 second := signInFully(t, a, "other@example.invalid")
201 key := enrol(t, a, second)
202 gated := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
203 begin := idJSON(t, a, "/passkey/signin/begin", nil, gated.Result().Cookies()...)
204 r := idJSON(t, a, "/passkey/signin/finish", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin}), gated.Result().Cookies()...)
205 if r.Code == 200 || sessionCookie(r) != nil {
206 t.Fatal("another person's passkey completed gate")
207 }
208}
209func TestIDChallengeBrowserCookiesAndExpiry(t *testing.T) {
210 for _, kind := range []string{"duplicate", "other-browser", "ttl", "clock", "capacity"} {
211 t.Run(kind, func(t *testing.T) {
212 a := newTestApp(t)
213 s := signInFully(t, a, sealtest.CanaryAddress)
214 key := enrol(t, a, s)
215 b := idJSON(t, a, "/passkey/direct/begin", nil)
216 c := namedCookie(t, b, ceremonyCookie)
217 if c.MaxAge != 300 || !c.Secure || !c.HttpOnly || c.Domain != "" || c.Path != "/" || c.SameSite != http.SameSiteLaxMode {
218 t.Fatal("challenge cookie isolation or TTL")
219 }
220 body := assertionBody(key, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin})
221 cookies := []*http.Cookie{c}
222 switch kind {
223 case "duplicate":
224 cookies = append(cookies, c)
225 case "other-browser":
226 other := idJSON(t, a, "/passkey/direct/begin", nil)
227 cookies = []*http.Cookie{namedCookie(t, other, ceremonyCookie)}
228 case "ttl":
229 raw, _ := base64.RawURLEncoding.DecodeString(c.Value)
230 plain, err := a.secrets.Sealer.Open("id.direct", raw)
231 var proof directChallenge
232 if err != nil || json.Unmarshal(plain, &proof) != nil || proof.Expires > time.Now().Unix()+300 || proof.Expires < time.Now().Unix()+295 {
233 t.Fatal("challenge lifetime")
234 }
235 return
236 case "clock":
237 a.db.Writer().Exec("UPDATE home_id_clock SET high_water=?", time.Now().Unix()+100)
238 case "capacity":
239 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_ceremonies SELECT printf('%064x',x),'other','','direct',? FROM n", time.Now().Unix()+300); err != nil {
240 t.Fatal(err)
241 }
242 if r := idJSON(t, a, "/passkey/register/begin", nil, s); r.Code == 200 {
243 t.Fatal("challenge bound bypassed")
244 }
245 return
246 }
247 if r := idJSON(t, a, "/passkey/direct/finish", body, cookies...); r.Code == 200 || sessionCookie(r) != nil {
248 t.Fatal("challenge accepted", kind)
249 }
250 })
251 }
252}
253
254func TestIDRegistrationChallengeSubjectAndLiveSession(t *testing.T) {
255 for _, kind := range []string{"subject", "expired-session"} {
256 t.Run(kind, func(t *testing.T) {
257 a := newTestApp(t)
258 s := signInFully(t, a, sealtest.CanaryAddress)
259 b := idJSON(t, a, "/passkey/register/begin", nil, s)
260 k, _ := authtest.New()
261 cd, att := k.Create(challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin})
262 if kind == "subject" {
263 a.db.Writer().Exec("UPDATE home_id_ceremonies SET subject='other'")
264 } else {
265 a.db.Writer().Exec("UPDATE sessions SET expires_at='2000-01-01T00:00:00Z'")
266 }
267 r := idJSON(t, a, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, s)
268 if r.Code == 200 {
269 t.Fatal("registration lost live subject/session binding")
270 }
271 })
272 }
273}
274func TestIDLegacyCredentialCannotSignInDirectly(t *testing.T) {
275 a := newTestApp(t)
276 s := signInFully(t, a, sealtest.CanaryAddress)
277 k := enrol(t, a, s)
278 a.db.Writer().Exec("DELETE FROM home_id_discoverable")
279 b := idJSON(t, a, "/passkey/direct/begin", nil)
280 r := idJSON(t, a, "/passkey/direct/finish", assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin}), namedCookie(t, b, ceremonyCookie))
281 if r.Code == 200 {
282 t.Fatal("legacy credential bypassed mailbox gate")
283 }
284}
285
286func TestIDGatedChallengeGuards(t *testing.T) {
287 for _, kind := range []string{"purpose", "expiry", "browser", "single-use", "ttl"} {
288 t.Run(kind, func(t *testing.T) {
289 a := newTestApp(t)
290 s := signInFully(t, a, sealtest.CanaryAddress)
291 k := enrol(t, a, s)
292 g := redeemAfterSignIn(t, a, sealtest.CanaryAddress)
293 cookies := g.Result().Cookies()
294 b := idJSON(t, a, "/passkey/signin/begin", nil, cookies...)
295 body := assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: Origin})
296 switch kind {
297 case "purpose":
298 a.db.Writer().Exec("UPDATE home_id_ceremonies SET purpose='register'")
299 case "expiry":
300 a.db.Writer().Exec("UPDATE home_id_ceremonies SET expires_at=0")
301 case "browser":
302 a.db.Writer().Exec("UPDATE home_id_ceremonies SET browser_hash='other'")
303 case "ttl":
304 var expiry int64
305 a.db.Writer().QueryRow("SELECT expires_at FROM home_id_ceremonies").Scan(&expiry)
306 if expiry > time.Now().Unix()+300 || expiry < time.Now().Unix()+295 {
307 t.Fatal("gated challenge TTL")
308 }
309 return
310 case "single-use":
311 // A valid signed response with a bad origin consumes the gated proof too.
312 bad := assertionBody(k, challengeFrom(t, b), authtest.Options{RPID: credentialHost, Origin: "https://evil.invalid"})
313 idJSON(t, a, "/passkey/signin/finish", bad, cookies...)
314 }
315 r := idJSON(t, a, "/passkey/signin/finish", body, cookies...)
316 if r.Code == 200 {
317 t.Fatal("gated guard failed", kind)
318 }
319 })
320 }
321}
322
323// TestIDRegistrationRefusesWithoutUserVerification: since v0.27.1
324// rastrillo's webauthn.Config.Register no longer requires user
325// verification, so Home refuses a UV-less attestation itself, on
326// registration as on replacement (TestIDReplacementProofBinding/bad-uv).
327// The same ceremony with UV set is the control: it must succeed, so
328// the refusal is about the flag and nothing else.
329func TestIDRegistrationRefusesWithoutUserVerification(t *testing.T) {
330 for _, uv := range []bool{false, true} {
331 a := newTestApp(t)
332 s := signInFully(t, a, sealtest.CanaryAddress)
333 b := idJSON(t, a, "/passkey/register/begin", nil, s)
334 k, _ := authtest.New()
335 opts := authtest.Options{RPID: credentialHost, Origin: Origin}
336 if !uv {
337 opts.Flags = authtest.FlagUserPresent | authtest.FlagAttestedData
338 }
339 cd, att := k.Create(challengeFrom(t, b), opts)
340 r := idJSON(t, a, "/passkey/register/finish", map[string]string{"clientDataJSON": base64.RawURLEncoding.EncodeToString(cd), "attestationObject": base64.RawURLEncoding.EncodeToString(att)}, s)
341 var n int
342 if err := a.db.Reader().QueryRow("SELECT count(*) FROM passkey_credentials").Scan(&n); err != nil {
343 t.Fatal(err)
344 }
345 if uv && (r.Code != 200 || n != 1) {
346 t.Fatalf("control: registration with UV got %d and %d credentials", r.Code, n)
347 }
348 if !uv && (r.Code == 200 || n != 0) {
349 t.Fatalf("registration without user verification accepted: %d, %d credentials", r.Code, n)
350 }
351 }
352}
353