| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/base64" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "net/http" |
| 11 | "net/url" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/rastrillo/rastrillo/sessions" |
| 16 | "amadan.net/rastrillo/rastrillo/webauthn" |
| 17 | strictjson "github.com/go-json-experiment/json" |
| 18 | ) |
| 19 | |
| 20 | const ceremonyCookie = "__Host-oficina-ceremony" |
| 21 | const gateCookie = "__Host-rastrillo_passkey_pending" |
| 22 | |
| 23 | var errIDProof = errors.New("home: identity proof refused") |
| 24 | |
| 25 | func idCookie(w http.ResponseWriter, name, value string, seconds int) { |
| 26 | http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| 27 | } |
| 28 | func cookieValue(r *http.Request, name string) string { |
| 29 | value := "" |
| 30 | count := 0 |
| 31 | for _, c := range r.Cookies() { |
| 32 | if c.Name == name { |
| 33 | value = c.Value |
| 34 | count++ |
| 35 | } |
| 36 | } |
| 37 | if count != 1 || len(value) > 4096 { |
| 38 | return "" |
| 39 | } |
| 40 | return value |
| 41 | } |
| 42 | func idJSONReply(w http.ResponseWriter, status int, v any) { |
| 43 | w.Header().Set("Cache-Control", "no-store") |
| 44 | w.Header().Set("Content-Type", "application/json") |
| 45 | w.WriteHeader(status) |
| 46 | _ = json.NewEncoder(w).Encode(v) |
| 47 | } |
| 48 | func idRefuse(w http.ResponseWriter) { |
| 49 | idJSONReply(w, http.StatusBadRequest, map[string]string{"error": "ceremony failed"}) |
| 50 | } |
| 51 | func (a *App) idTransaction(ctx context.Context) (*sql.Tx, int64, error) { |
| 52 | tx, err := a.db.Writer().BeginTx(ctx, nil) |
| 53 | if err != nil { |
| 54 | return nil, 0, errIDProof |
| 55 | } |
| 56 | now := time.Now().Unix() |
| 57 | if _, err = tx.ExecContext(ctx, "UPDATE home_id_clock SET high_water=MAX(high_water,?) WHERE id=1", now); err != nil { |
| 58 | tx.Rollback() |
| 59 | return nil, 0, errIDProof |
| 60 | } |
| 61 | var high int64 |
| 62 | if err = tx.QueryRowContext(ctx, "SELECT high_water FROM home_id_clock WHERE id=1").Scan(&high); err != nil || now < high { |
| 63 | tx.Rollback() |
| 64 | return nil, 0, errIDProof |
| 65 | } |
| 66 | return tx, high, nil |
| 67 | } |
| 68 | |
| 69 | func (a *App) idWebAuthn() webauthn.Config { |
| 70 | return webauthn.Config{RPID: a.credentialHost, Origin: a.origins.Credential, LegacyRPID: a.passkeyCfg.LegacyRPID} |
| 71 | } |
| 72 | |
| 73 | // Read the live session inside the writer transaction, so recovery revocation |
| 74 | // and a simultaneous enrollment or session mint cannot pass one another. |
| 75 | func (a *App) idSession(tx *sql.Tx, r *http.Request, now int64) (sessions.Session, string, error) { |
| 76 | token := cookieValue(r, a.sessions.CookieName()) |
| 77 | if token == "" { |
| 78 | return sessions.Session{}, "", errIDProof |
| 79 | } |
| 80 | hash := sessions.HashToken(token) |
| 81 | var s sessions.Session |
| 82 | var auth, created, expires string |
| 83 | err := tx.QueryRow("SELECT subject,method,auth_time,created_at,expires_at FROM sessions WHERE token_hash=?", hash).Scan(&s.Subject, &s.Method, &auth, &created, &expires) |
| 84 | exp, e := time.Parse(time.RFC3339, expires) |
| 85 | if err != nil || e != nil || exp.Unix() <= now { |
| 86 | return s, "", errIDProof |
| 87 | } |
| 88 | s.AuthTime, _ = time.Parse(time.RFC3339, auth) |
| 89 | s.At, _ = time.Parse(time.RFC3339, created) |
| 90 | return s, hash, nil |
| 91 | } |
| 92 | func idFreshSession(s sessions.Session, age time.Duration, now time.Time) bool { |
| 93 | at := s.AuthTime |
| 94 | if at.IsZero() { |
| 95 | at = s.At |
| 96 | } |
| 97 | return !keymailWithoutGesture(s) && !at.After(now) && sessions.Fresh(s, age, now) |
| 98 | } |
| 99 | |
| 100 | func (a *App) idBinding(tx *sql.Tx, r *http.Request, purpose string, now int64) (subject, binding string, err error) { |
| 101 | switch purpose { |
| 102 | case "replace": |
| 103 | return a.replacementBinding(tx, r, now) |
| 104 | case "direct": |
| 105 | v := cookieValue(r, ceremonyCookie) |
| 106 | if v == "" { |
| 107 | return "", "", errIDProof |
| 108 | } |
| 109 | return "", sessions.HashToken(v), nil |
| 110 | case "signin": |
| 111 | v := cookieValue(r, gateCookie) |
| 112 | if v == "" { |
| 113 | return "", "", errIDProof |
| 114 | } |
| 115 | binding = sessions.HashToken(v) |
| 116 | var exp string |
| 117 | err = tx.QueryRow("SELECT subject,expires_at FROM passkey_pending WHERE token_hash=?", binding).Scan(&subject, &exp) |
| 118 | at, e := time.Parse(time.RFC3339, exp) |
| 119 | if err != nil || e != nil || at.Unix() <= now { |
| 120 | return "", "", errIDProof |
| 121 | } |
| 122 | return subject, binding, nil |
| 123 | default: |
| 124 | s, hash, e := a.idSession(tx, r, now) |
| 125 | if e != nil { |
| 126 | return "", "", e |
| 127 | } |
| 128 | if purpose == "register" && (!idFreshSession(s, enrolFreshness, time.Unix(now, 0)) || strings.Contains(s.Method, "recovery")) { |
| 129 | return "", "", errIDProof |
| 130 | } |
| 131 | return s.Subject, hash, nil |
| 132 | } |
| 133 | } |
| 134 | func (a *App) idBegin(purpose string) http.HandlerFunc { |
| 135 | return func(w http.ResponseWriter, r *http.Request) { |
| 136 | if purpose == "direct" { |
| 137 | a.idDirectBegin(w, r) |
| 138 | return |
| 139 | } |
| 140 | tx, now, err := a.idTransaction(r.Context()) |
| 141 | if err != nil { |
| 142 | idRefuse(w) |
| 143 | return |
| 144 | } |
| 145 | defer tx.Rollback() |
| 146 | subject, binding, err := a.idBinding(tx, r, purpose, now) |
| 147 | if err != nil { |
| 148 | idRefuse(w) |
| 149 | return |
| 150 | } |
| 151 | if _, err = tx.Exec("DELETE FROM home_id_ceremonies WHERE expires_at<=? OR (browser_hash=? AND purpose=?)", now, binding, purpose); err != nil { |
| 152 | idRefuse(w) |
| 153 | return |
| 154 | } |
| 155 | var n int |
| 156 | if err = tx.QueryRow("SELECT count(*) FROM home_id_ceremonies").Scan(&n); err != nil || n >= 10000 { |
| 157 | idRefuse(w) |
| 158 | return |
| 159 | } |
| 160 | challenge, err := webauthn.NewChallenge() |
| 161 | if err != nil { |
| 162 | idRefuse(w) |
| 163 | return |
| 164 | } |
| 165 | if _, err = tx.Exec("INSERT INTO home_id_ceremonies VALUES (?,?,?,?,?)", hex.EncodeToString(challenge), binding, subject, purpose, now+300); err != nil { |
| 166 | idRefuse(w) |
| 167 | return |
| 168 | } |
| 169 | var credentials []string |
| 170 | if purpose == "signin" || purpose == "stepup" { |
| 171 | rows, e := tx.Query("SELECT id FROM passkey_credentials WHERE subject=? ORDER BY id LIMIT 101", subject) |
| 172 | if e != nil { |
| 173 | idRefuse(w) |
| 174 | return |
| 175 | } |
| 176 | for rows.Next() { |
| 177 | var id string |
| 178 | if rows.Scan(&id) != nil { |
| 179 | rows.Close() |
| 180 | idRefuse(w) |
| 181 | return |
| 182 | } |
| 183 | raw, e := hex.DecodeString(id) |
| 184 | if e != nil { |
| 185 | rows.Close() |
| 186 | idRefuse(w) |
| 187 | return |
| 188 | } |
| 189 | credentials = append(credentials, base64.RawURLEncoding.EncodeToString(raw)) |
| 190 | } |
| 191 | e = rows.Err() |
| 192 | rows.Close() |
| 193 | if len(credentials) > 100 { |
| 194 | idRefuse(w) |
| 195 | return |
| 196 | } |
| 197 | if e != nil { |
| 198 | idRefuse(w) |
| 199 | return |
| 200 | } |
| 201 | } |
| 202 | if err = tx.Commit(); err != nil { |
| 203 | idRefuse(w) |
| 204 | return |
| 205 | } |
| 206 | idJSONReply(w, 200, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge), "credentials": credentials}) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | type idCeremony struct { |
| 211 | ID string `json:"id"` |
| 212 | ClientData string `json:"clientDataJSON"` |
| 213 | AuthData string `json:"authenticatorData"` |
| 214 | Signature string `json:"signature"` |
| 215 | Attestation string `json:"attestationObject"` |
| 216 | } |
| 217 | |
| 218 | func decodeIDCeremony(w http.ResponseWriter, r *http.Request) (idCeremony, []byte, []byte, error) { |
| 219 | var body idCeremony |
| 220 | if strictjson.UnmarshalRead(http.MaxBytesReader(w, r.Body, 64<<10), &body, strictjson.RejectUnknownMembers(true)) != nil { |
| 221 | return body, nil, nil, errIDProof |
| 222 | } |
| 223 | cd, err := base64.RawURLEncoding.Strict().DecodeString(body.ClientData) |
| 224 | if err != nil { |
| 225 | return body, nil, nil, errIDProof |
| 226 | } |
| 227 | var c struct { |
| 228 | Challenge string `json:"challenge"` |
| 229 | } |
| 230 | if json.Unmarshal(cd, &c) != nil { |
| 231 | return body, nil, nil, errIDProof |
| 232 | } |
| 233 | challenge, err := base64.RawURLEncoding.Strict().DecodeString(c.Challenge) |
| 234 | if err != nil || len(challenge) != 32 { |
| 235 | return body, nil, nil, errIDProof |
| 236 | } |
| 237 | return body, cd, challenge, nil |
| 238 | } |
| 239 | |
| 240 | // This is the narrow storage adapter to replace when upstream auth can supply |
| 241 | // address-blind storage AND transaction-owned session minting. Keep the proof |
| 242 | // consumption, live credential check and session write on this same writer. |
| 243 | func (a *App) idMint(tx *sql.Tx, r *http.Request, s sessions.Session, now int64) (string, error) { |
| 244 | token, hash, err := sessions.NewToken() |
| 245 | if err != nil { |
| 246 | return "", errIDProof |
| 247 | } |
| 248 | stamp := time.Unix(now, 0).UTC().Format(time.RFC3339) |
| 249 | auth := "" |
| 250 | if !s.AuthTime.IsZero() { |
| 251 | auth = s.AuthTime.UTC().Format(time.RFC3339) |
| 252 | } |
| 253 | if old := cookieValue(r, a.sessions.CookieName()); old != "" { |
| 254 | if _, err = tx.Exec("DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(old)); err != nil { |
| 255 | return "", errIDProof |
| 256 | } |
| 257 | } |
| 258 | _, err = tx.Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, s.Subject, s.Method, auth, stamp, time.Unix(now, 0).Add(30*24*time.Hour).UTC().Format(time.RFC3339)) |
| 259 | if err != nil { |
| 260 | return "", errIDProof |
| 261 | } |
| 262 | return token, nil |
| 263 | } |
| 264 | func (a *App) idFinish(purpose string) http.HandlerFunc { |
| 265 | return func(w http.ResponseWriter, r *http.Request) { |
| 266 | body, cd, challenge, err := decodeIDCeremony(w, r) |
| 267 | if err != nil { |
| 268 | idRefuse(w) |
| 269 | return |
| 270 | } |
| 271 | tx, now, err := a.idTransaction(r.Context()) |
| 272 | if err != nil { |
| 273 | idRefuse(w) |
| 274 | return |
| 275 | } |
| 276 | defer tx.Rollback() |
| 277 | subject, binding, err := a.idBinding(tx, r, purpose, now) |
| 278 | if err != nil { |
| 279 | idRefuse(w) |
| 280 | return |
| 281 | } |
| 282 | var directExpires int64 |
| 283 | if purpose == "direct" { |
| 284 | directExpires, err = a.idDirectProof(r, challenge, now) |
| 285 | if err != nil { |
| 286 | idRefuse(w) |
| 287 | return |
| 288 | } |
| 289 | } else { |
| 290 | var consumed string |
| 291 | err = tx.QueryRow("DELETE FROM home_id_ceremonies WHERE challenge=? AND browser_hash=? AND subject=? AND purpose=? AND expires_at>? RETURNING challenge", hex.EncodeToString(challenge), binding, subject, purpose, now).Scan(&consumed) |
| 292 | if err != nil { |
| 293 | idRefuse(w) |
| 294 | return |
| 295 | } |
| 296 | |
| 297 | } |
| 298 | refuse := func() { _ = tx.Commit(); idRefuse(w) } |
| 299 | if purpose == "register" || purpose == "replace" { |
| 300 | att, e := base64.RawURLEncoding.Strict().DecodeString(body.Attestation) |
| 301 | if e != nil { |
| 302 | refuse() |
| 303 | return |
| 304 | } |
| 305 | cred, e := a.idWebAuthn().Register(challenge, cd, att) |
| 306 | // User verification is required to register, as it is to |
| 307 | // assert (Verify). rastrillo's Register enforced it through |
| 308 | // v0.27.0; since v0.27.1 it records the flag and leaves the |
| 309 | // policy to the app, so Home states its own here. |
| 310 | if e != nil || !cred.UserVerified { |
| 311 | refuse() |
| 312 | return |
| 313 | } |
| 314 | if purpose == "replace" { |
| 315 | if a.replaceCredential(tx, r, subject, cred, now) != nil { |
| 316 | idRefuse(w) |
| 317 | return |
| 318 | } |
| 319 | if tx.Commit() != nil { |
| 320 | idRefuse(w) |
| 321 | return |
| 322 | } |
| 323 | idCookie(w, a.sessions.CookieName(), "", -1) |
| 324 | idCookie(w, recoveryCookie, "", -1) |
| 325 | idCookie(w, noticeCookie, cookieValue(r, recoveryCookie), 300) |
| 326 | a.replacementResult(w, !a.sendReplacementNotice(r.Context(), binding)) |
| 327 | idJSONReply(w, 200, map[string]any{"ok": true, "to": "/passkey/replaced"}) |
| 328 | return |
| 329 | } |
| 330 | var count int |
| 331 | if tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", subject).Scan(&count) != nil || count >= 100 { |
| 332 | idRefuse(w) |
| 333 | return |
| 334 | } |
| 335 | // A first passkey ends every grant that has none (§3). A web |
| 336 | // enrolment has no enrolling grant, so every code-only device |
| 337 | // signs in again, now with the passkey. |
| 338 | if count == 0 && endPasskeylessGrants(tx, subject, "", now) != nil { |
| 339 | idRefuse(w) |
| 340 | return |
| 341 | } |
| 342 | id := hex.EncodeToString(cred.ID) |
| 343 | if _, e = tx.Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,?,?)", id, subject, cred.PublicKey, cred.SignCount, time.Unix(now, 0).UTC().Format(time.RFC3339)); e != nil { |
| 344 | idRefuse(w) |
| 345 | return |
| 346 | } |
| 347 | if _, e = tx.Exec("INSERT INTO home_id_discoverable VALUES(?)", id); e != nil { |
| 348 | idRefuse(w) |
| 349 | return |
| 350 | } |
| 351 | if tx.Commit() != nil { |
| 352 | idRefuse(w) |
| 353 | return |
| 354 | } |
| 355 | idJSONReply(w, 200, map[string]bool{"ok": true}) |
| 356 | return |
| 357 | } |
| 358 | id, e := base64.RawURLEncoding.Strict().DecodeString(body.ID) |
| 359 | if e != nil { |
| 360 | refuse() |
| 361 | return |
| 362 | } |
| 363 | ad, e := base64.RawURLEncoding.Strict().DecodeString(body.AuthData) |
| 364 | if e != nil { |
| 365 | refuse() |
| 366 | return |
| 367 | } |
| 368 | sig, e := base64.RawURLEncoding.Strict().DecodeString(body.Signature) |
| 369 | if e != nil { |
| 370 | refuse() |
| 371 | return |
| 372 | } |
| 373 | var owner string |
| 374 | var cred webauthn.Credential |
| 375 | cred.ID = id |
| 376 | query := "SELECT subject,public_key,sign_count FROM passkey_credentials WHERE id=?" |
| 377 | if purpose == "direct" { |
| 378 | query += " AND id IN (SELECT credential_id FROM home_id_discoverable)" |
| 379 | } |
| 380 | if e = tx.QueryRow(query, hex.EncodeToString(id)).Scan(&owner, &cred.PublicKey, &cred.SignCount); e != nil || (subject != "" && owner != subject) { |
| 381 | refuse() |
| 382 | return |
| 383 | } |
| 384 | next, e := a.idWebAuthn().Verify(cred, challenge, cd, ad, sig) |
| 385 | if e != nil { |
| 386 | refuse() |
| 387 | return |
| 388 | } |
| 389 | if purpose == "direct" && consumeDirect(tx, challenge, directExpires, now) != nil { |
| 390 | idRefuse(w) |
| 391 | return |
| 392 | } |
| 393 | if _, e = tx.Exec("UPDATE passkey_credentials SET sign_count=? WHERE id=?", next, hex.EncodeToString(id)); e != nil { |
| 394 | idRefuse(w) |
| 395 | return |
| 396 | } |
| 397 | method, to := "passkey", readReturn(r) |
| 398 | if purpose == "direct" { |
| 399 | // The door's module puts the page's return_to on the finish |
| 400 | // URL (SigninState.PasskeyFinish). It wins over the return |
| 401 | // cookie, which lasts ten minutes and which another tab can |
| 402 | // replace, so a late autofill pick still lands in the app's |
| 403 | // handoff. credentialReturn keeps it to the closed list. |
| 404 | if q := credentialReturn(r.URL.Query().Get("return_to")); q != "/" { |
| 405 | to = q |
| 406 | } |
| 407 | } |
| 408 | if purpose == "signin" { |
| 409 | if e = tx.QueryRow("DELETE FROM passkey_pending WHERE token_hash=? RETURNING method,return_to", binding).Scan(&method, &to); e != nil { |
| 410 | idRefuse(w) |
| 411 | return |
| 412 | } |
| 413 | method += "+passkey" |
| 414 | } |
| 415 | var codes int |
| 416 | if tx.QueryRow("SELECT count(*) FROM passkey_recovery_codes WHERE subject=?", owner).Scan(&codes) != nil { |
| 417 | idRefuse(w) |
| 418 | return |
| 419 | } |
| 420 | if codes == 0 { |
| 421 | if to != "/" && to != "/passkey/codes" { |
| 422 | to = "/passkey/codes?return_to=" + url.QueryEscape(credentialReturn(to)) |
| 423 | } else { |
| 424 | to = "/passkey/codes" |
| 425 | } |
| 426 | } |
| 427 | token, e := a.idMint(tx, r, sessions.Session{Subject: owner, Method: method, AuthTime: time.Unix(now, 0)}, now) |
| 428 | if e != nil { |
| 429 | idRefuse(w) |
| 430 | return |
| 431 | } |
| 432 | // A passkey sign-in, gated or direct, is what the door offers |
| 433 | // next time; the remembered address survives only for the same |
| 434 | // person (door.go, passkeyRemembrance), read in this transaction |
| 435 | // and written only after it commits. |
| 436 | var remember func(http.ResponseWriter) |
| 437 | if purpose == "signin" || purpose == "direct" { |
| 438 | remember = a.passkeyRemembrance(tx, r, owner) |
| 439 | } |
| 440 | if e = tx.Commit(); e != nil { |
| 441 | idRefuse(w) |
| 442 | return |
| 443 | } |
| 444 | if remember != nil { |
| 445 | remember(w) |
| 446 | } |
| 447 | idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| 448 | idCookie(w, ceremonyCookie, "", -1) |
| 449 | if purpose == "signin" { |
| 450 | idCookie(w, gateCookie, "", -1) |
| 451 | } |
| 452 | writeReturn(w, "/") |
| 453 | idJSONReply(w, 200, map[string]any{"ok": true, "to": to}) |
| 454 | } |
| 455 | } |
| 456 | |