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 "database/sql"
5 "encoding/base64"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "net/http"
10
11 "amadan.net/rastrillo/rastrillo/webauthn"
12)
13
14// Native passkey sign-in (§5). The app runs the platform ceremony against
15// RP id.oficina.works; Home verifies it exactly as the web door does — the
16// same RP, origin, user-verification and person-binding checks — and mints a
17// grant instead of a cookie.
18const nativeCeremonyPurpose = "native"
19
20// nativeCeremonyShare is the most of home_id_ceremonies' 10,000 rows native
21// challenges may hold.
22const nativeCeremonyShare = 5000
23
24// nativePasskeyBegin is POST passkey/begin {device_key, platform, pending?}.
25// Without pending it is a discoverable sign-in that needs no email; with one
26// it finishes a code sign-in on an enrolled account, and device_key must be
27// the key that start was made with. The challenge is single-use, lives five
28// minutes, is bound to the device key and counts within home_id_ceremonies.
29func (a *App) nativePasskeyBegin(w http.ResponseWriter, r *http.Request) {
30 body, ok := nativeIntake(w, r)
31 if !ok {
32 return
33 }
34 var in struct {
35 DeviceKey string `json:"device_key,omitzero"`
36 Platform string `json:"platform,omitzero"`
37 Pending string `json:"pending,omitzero"`
38 }
39 if !decodeNative(body, &in) || in.DeviceKey == "" || !nativePlatforms[in.Platform] {
40 nativeFail(w, http.StatusBadRequest, "request")
41 return
42 }
43 tx, now, err := a.idTransaction(r.Context())
44 if err != nil {
45 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
46 return
47 }
48 defer tx.Rollback()
49 if sweepCodes(tx, now) != nil {
50 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
51 return
52 }
53 subject, key, platform, pendingHash := "", in.DeviceKey, in.Platform, ""
54 if in.Pending != "" {
55 if _, ok := decodeB64(in.Pending, 32); !ok {
56 nativeFail(w, http.StatusBadRequest, "pending")
57 return
58 }
59 pendingHash = nativeHash(in.Pending)
60 if tx.QueryRow("SELECT person_ref,device_key,platform FROM home_id_native_pending WHERE pending_hash=? AND expires_at>?", pendingHash, now).Scan(&subject, &key, &platform) != nil {
61 nativeFail(w, http.StatusGone, "expired")
62 return
63 }
64 // The pending is bound to its start's key; the proof below is
65 // checked against that key, never the one in the body.
66 if key != in.DeviceKey {
67 nativeUnauthorized(w, nativeProofRejected)
68 return
69 }
70 }
71 if !a.nativePreGrant(r, body, key, now) {
72 nativeUnauthorized(w, nativeProofRejected)
73 return
74 }
75 if ip := nativeIPBucket(r); ip != "" {
76 bs := []nativeBucket{
77 {a.bucketKey(passkeyBeginsPerIP, a.nativeMAC("native-ip", ip)), passkeyBeginsPerIP, errNativeLimited},
78 {a.bucketKey(passkeyBeginsPerNet, a.nativeMAC("native-ip", nativeNetBucket(r))), passkeyBeginsPerNet, errNativeLimited},
79 }
80 if err = checkThenSpend(tx, bs, now); err != nil {
81 nativeLimitFail(w, err)
82 return
83 }
84 }
85 // One live challenge per device key: a new begin replaces the last, so
86 // a key cannot hold more than one row.
87 binding := nativeHash("native\x00" + key)
88 for _, q := range []struct {
89 sql string
90 args []any
91 }{
92 {"DELETE FROM home_id_ceremonies WHERE expires_at<=? OR (browser_hash=? AND purpose=?)", []any{now, binding, nativeCeremonyPurpose}},
93 {"DELETE FROM home_id_native_ceremonies WHERE expires_at<=? OR device_key=?", []any{now, key}},
94 } {
95 if _, err = tx.Exec(q.sql, q.args...); err != nil {
96 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
97 return
98 }
99 }
100 // The ceremonies table is shared with the web door. Native challenges
101 // may take at most half of it, so a native flood cannot lock the web's
102 // passkey sign-in out.
103 var n, native int
104 if tx.QueryRow("SELECT count(*), count(CASE WHEN purpose=? THEN 1 END) FROM home_id_ceremonies", nativeCeremonyPurpose).Scan(&n, &native) != nil || n >= 10000 || native >= nativeCeremonyShare {
105 nativeFail(w, http.StatusServiceUnavailable, "full")
106 return
107 }
108 challenge, err := webauthn.NewChallenge()
109 if err != nil {
110 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
111 return
112 }
113 id := hex.EncodeToString(challenge)
114 if _, err = tx.Exec("INSERT INTO home_id_ceremonies VALUES (?,?,?,?,?)", id, binding, subject, nativeCeremonyPurpose, now+300); err != nil {
115 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
116 return
117 }
118 if _, err = tx.Exec("INSERT INTO home_id_native_ceremonies VALUES (?,?,?,?,?)", id, key, platform, pendingHash, now+300); err != nil {
119 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
120 return
121 }
122 credentials := []string{}
123 if subject != "" {
124 rows, err := tx.Query("SELECT id FROM passkey_credentials WHERE subject=? ORDER BY id LIMIT 100", subject)
125 if err != nil {
126 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
127 return
128 }
129 for rows.Next() {
130 var hexID string
131 if rows.Scan(&hexID) != nil {
132 rows.Close()
133 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
134 return
135 }
136 raw, err := hex.DecodeString(hexID)
137 if err != nil {
138 rows.Close()
139 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
140 return
141 }
142 credentials = append(credentials, base64.RawURLEncoding.EncodeToString(raw))
143 }
144 err = rows.Err()
145 rows.Close()
146 if err != nil {
147 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
148 return
149 }
150 }
151 if tx.Commit() != nil {
152 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
153 return
154 }
155 nativeReply(w, http.StatusOK, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge), "rp_id": a.credentialHost, "credentials": credentials})
156}
157
158// nativePasskeyFinish is POST passkey/finish {id, clientDataJSON,
159// authenticatorData, signature, device_key, platform?, userHandle?}: the web
160// door's finish fields plus the device key. device_key must be the key the
161// challenge was bound to at begin, and the proof is checked against that
162// bound key. platform was fixed at begin and userHandle decides nothing
163// (the credential id names the owner, as on the web); both are accepted
164// and ignored. It returns {grant, identity_id, auth_time}.
165func (a *App) nativePasskeyFinish(w http.ResponseWriter, r *http.Request) {
166 body, ok := nativeIntake(w, r)
167 if !ok {
168 return
169 }
170 var in struct {
171 idCeremony
172 DeviceKey string `json:"device_key"`
173 Platform string `json:"platform,omitzero"`
174 UserHandle string `json:"userHandle,omitzero"`
175 }
176 if !decodeNative(body, &in) || in.Attestation != "" || in.DeviceKey == "" || len(in.UserHandle) > 128 || (in.Platform != "" && !nativePlatforms[in.Platform]) {
177 nativeFail(w, http.StatusBadRequest, "request")
178 return
179 }
180 cd, err := base64.RawURLEncoding.Strict().DecodeString(in.ClientData)
181 if err != nil {
182 nativeFail(w, http.StatusBadRequest, "request")
183 return
184 }
185 var c struct {
186 Challenge string `json:"challenge"`
187 }
188 if json.Unmarshal(cd, &c) != nil {
189 nativeFail(w, http.StatusBadRequest, "request")
190 return
191 }
192 challenge, err := base64.RawURLEncoding.Strict().DecodeString(c.Challenge)
193 if err != nil || len(challenge) != 32 {
194 nativeFail(w, http.StatusBadRequest, "request")
195 return
196 }
197 id := hex.EncodeToString(challenge)
198 tx, now, err := a.idTransaction(r.Context())
199 if err != nil {
200 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
201 return
202 }
203 defer tx.Rollback()
204 var key, platform, pendingHash string
205 if tx.QueryRow("SELECT device_key,platform,pending FROM home_id_native_ceremonies WHERE challenge=? AND expires_at>?", id, now).Scan(&key, &platform, &pendingHash) != nil {
206 nativeFail(w, http.StatusBadRequest, "passkey")
207 return
208 }
209 if key != in.DeviceKey || !a.nativePreGrant(r, body, key, now) {
210 nativeUnauthorized(w, nativeProofRejected)
211 return
212 }
213 // Consume the challenge first and keep it consumed whatever follows: a
214 // challenge that survived a failed verification could be tried again.
215 var subject string
216 if tx.QueryRow("DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND purpose=? AND expires_at>? RETURNING subject", id, nativeHash("native\x00"+key), nativeCeremonyPurpose, now).Scan(&subject) != nil {
217 nativeFail(w, http.StatusBadRequest, "passkey")
218 return
219 }
220 if _, err = tx.Exec("DELETE FROM home_id_native_ceremonies WHERE challenge=?", id); err != nil {
221 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
222 return
223 }
224 refuse := func() {
225 if tx.Commit() != nil {
226 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
227 return
228 }
229 nativeFail(w, http.StatusBadRequest, "passkey")
230 }
231 credID, e1 := base64.RawURLEncoding.Strict().DecodeString(in.ID)
232 ad, e2 := base64.RawURLEncoding.Strict().DecodeString(in.AuthData)
233 sig, e3 := base64.RawURLEncoding.Strict().DecodeString(in.Signature)
234 if e1 != nil || e2 != nil || e3 != nil {
235 refuse()
236 return
237 }
238 // A discoverable sign-in accepts only discoverable credentials, as the
239 // web's direct sign-in does; a pending one accepts only that person's.
240 query := "SELECT subject,public_key,sign_count FROM passkey_credentials WHERE id=?"
241 if subject == "" {
242 query += " AND id IN (SELECT credential_id FROM home_id_discoverable)"
243 }
244 var owner string
245 cred := webauthn.Credential{ID: credID}
246 if err = tx.QueryRow(query, hex.EncodeToString(credID)).Scan(&owner, &cred.PublicKey, &cred.SignCount); err != nil || (subject != "" && owner != subject) {
247 refuse()
248 return
249 }
250 next, err := a.idWebAuthn().Verify(cred, challenge, cd, ad, sig)
251 if err != nil {
252 refuse()
253 return
254 }
255 if _, err = tx.Exec("UPDATE passkey_credentials SET sign_count=? WHERE id=?", next, hex.EncodeToString(credID)); err != nil {
256 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
257 return
258 }
259 method := "passkey"
260 if pendingHash != "" {
261 var person, first string
262 err = tx.QueryRow("DELETE FROM home_id_native_pending WHERE pending_hash=? AND device_key=? AND expires_at>? RETURNING person_ref,method", pendingHash, key, now).Scan(&person, &first)
263 if errors.Is(err, sql.ErrNoRows) || (err == nil && person != owner) {
264 refuse()
265 return
266 }
267 if err != nil {
268 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
269 return
270 }
271 method = first + "+passkey"
272 }
273 reply, err := a.mintGrant(tx, owner, key, platform, method, now, now)
274 if err != nil || tx.Commit() != nil {
275 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
276 return
277 }
278 nativeReply(w, http.StatusOK, reply)
279}
280
281// The association file (§5). Static, application/json, no redirect, no
282// applinks and no account-authored text: it lists each App ID allowed to use
283// passkeys for id.oficina.works. Mac and iPhone share bundle IDs, so there
284// are seven.
285const aasaPath = "/.well-known/apple-app-site-association"
286
287var nativeAppIDs = []string{
288 "9U4A84C4WK.works.oficina.calls",
289 "9U4A84C4WK.works.oficina.docs",
290 "9U4A84C4WK.works.oficina.sheets",
291 "9U4A84C4WK.works.oficina.calendar",
292 "9U4A84C4WK.works.oficina.memoria",
293 "9U4A84C4WK.works.oficina.equipo",
294 "9U4A84C4WK.works.oficina.base",
295}
296
297var aasaBody = func() []byte {
298 b, err := json.Marshal(map[string]any{"webcredentials": map[string]any{"apps": nativeAppIDs}})
299 if err != nil {
300 panic(err)
301 }
302 return b
303}()
304
305func (a *App) serveAASA(w http.ResponseWriter, r *http.Request) {
306 w.Header().Set("Content-Type", "application/json")
307 w.Header().Set("Cache-Control", "public, max-age=3600")
308 w.Header().Set("X-Content-Type-Options", "nosniff")
309 _, _ = w.Write(aasaBody)
310}
311