| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/hmac" |
| 6 | "crypto/rand" |
| 7 | "database/sql" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "math/big" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/keymaildev/signin" |
| 17 | ) |
| 18 | |
| 19 | // The email code (§4), for a person with no passkey yet. |
| 20 | const ( |
| 21 | nativeCodeLife = 600 // a code lives ten minutes |
| 22 | nativeCodeTries = 5 // and dies after five wrong tries |
| 23 | nativeCodeSends = 3 // a start gets at most three sends |
| 24 | nativeResendAfter = 30 // thirty seconds apart |
| 25 | nativePendingLife = 300 // a passkey-required pending lives five minutes |
| 26 | nativeLivePerIP = 20 |
| 27 | nativeBucketCap = 500000 |
| 28 | nativeWindow = 900 |
| 29 | nativeCodeSealScope = "native.code" |
| 30 | ) |
| 31 | |
| 32 | // nativeLiveStarts is the live-start table's size (§4). A variable only so a |
| 33 | // test can fill it without 10,000 inserts. |
| 34 | var nativeLiveStarts = 10000 |
| 35 | |
| 36 | // The §4 limits, each its own persistent fixed-window counter. The prefix |
| 37 | // names the bucket; the rest of the key is blinded. |
| 38 | type nativeLimit struct { |
| 39 | prefix string |
| 40 | limit int |
| 41 | window int64 |
| 42 | } |
| 43 | |
| 44 | var ( |
| 45 | startsPerAddress = nativeLimit{"start-addr-15m", 5, nativeWindow} |
| 46 | startsPerAddressDay = nativeLimit{"start-addr-day", 20, day} |
| 47 | startsPerIP = nativeLimit{"start-ip-15m", 20, nativeWindow} |
| 48 | startsPerIPDay = nativeLimit{"start-ip-day", 200, day} |
| 49 | startsPerAddressKey = nativeLimit{"start-key-15m", 5, nativeWindow} |
| 50 | wrongPerAddressKey = nativeLimit{"wrong-key-15m", 5, nativeWindow} |
| 51 | wrongNewKeysPerDay = nativeLimit{"wrong-new-day", 20, day} |
| 52 | passkeyBeginsPerIP = nativeLimit{"passkey-ip-15m", 60, nativeWindow} |
| 53 | // Per network (IPv4 /24, IPv6 /48): rotating through a /64 allocation's |
| 54 | // addresses, or a /48's /64s, does not buy a fresh allowance each time. |
| 55 | startsPerNetDay = nativeLimit{"start-net-day", 1000, day} |
| 56 | passkeyBeginsPerNet = nativeLimit{"passkey-net-15m", 300, nativeWindow} |
| 57 | errNativeLimited = errors.New("home: native limit reached") |
| 58 | // errNativeDailyLimit is only the per-address daily wrong-code cap for |
| 59 | // new devices (§4, cost B): the client answers it with the spec's "use a |
| 60 | // passkey or a device you've signed in on before" copy. Every other limit |
| 61 | // is errNativeLimited. |
| 62 | errNativeDailyLimit = errors.New("home: native daily wrong-code limit reached") |
| 63 | ) |
| 64 | |
| 65 | const codeMailSubject = "Your Oficina ID code" |
| 66 | |
| 67 | // codeMailBody has no link: a link would sign in a browser (§4). |
| 68 | func codeMailBody(code string) string { |
| 69 | return "Your Oficina ID code is " + code + "\n\n" + |
| 70 | "It expires in 10 minutes and works once.\n\n" + |
| 71 | "If you didn't ask for it, ignore this email. Nobody can sign in without the code." |
| 72 | } |
| 73 | |
| 74 | // bucketKey is 128 bits of a keyed MAC: ample to keep buckets apart, and |
| 75 | // half the bytes per row of the full MAC. |
| 76 | func (a *App) bucketKey(l nativeLimit, parts ...string) string { |
| 77 | return l.prefix + ":" + a.nativeMAC("native-bucket", append([]string{l.prefix}, parts...)...)[:32] |
| 78 | } |
| 79 | |
| 80 | // bucketFull reports whether a bucket has reached its limit in its window. |
| 81 | func bucketFull(tx *sql.Tx, key string, l nativeLimit, now int64) (bool, error) { |
| 82 | var n int |
| 83 | err := tx.QueryRow("SELECT count FROM home_id_native_buckets WHERE bucket=? AND expires_at>?", key, now).Scan(&n) |
| 84 | if errors.Is(err, sql.ErrNoRows) { |
| 85 | return false, nil |
| 86 | } |
| 87 | if err != nil { |
| 88 | return false, errIDProof |
| 89 | } |
| 90 | return n >= l.limit, nil |
| 91 | } |
| 92 | |
| 93 | // bucketSpend counts one against a bucket, opening a new window when the |
| 94 | // last one has closed. |
| 95 | func bucketSpend(tx *sql.Tx, key string, l nativeLimit, now int64) error { |
| 96 | _, err := tx.Exec(`INSERT INTO home_id_native_buckets(bucket,count,expires_at) VALUES(?,1,?) |
| 97 | ON CONFLICT(bucket) DO UPDATE SET |
| 98 | count = CASE WHEN expires_at<=? THEN 1 ELSE count+1 END, |
| 99 | expires_at = CASE WHEN expires_at<=? THEN ? ELSE expires_at END`, key, now+l.window, now, now, now+l.window) |
| 100 | if err != nil { |
| 101 | return errIDProof |
| 102 | } |
| 103 | return nil |
| 104 | } |
| 105 | |
| 106 | type nativeBucket struct { |
| 107 | key string |
| 108 | limit nativeLimit |
| 109 | err error |
| 110 | } |
| 111 | |
| 112 | // checkThenSpend refuses if any bucket is full, and otherwise spends one |
| 113 | // from each, in the caller's transaction: parallel requests serialise on the |
| 114 | // writer, so none can see a count another has not yet written. |
| 115 | func checkThenSpend(tx *sql.Tx, buckets []nativeBucket, now int64) error { |
| 116 | for _, b := range buckets { |
| 117 | full, err := bucketFull(tx, b.key, b.limit, now) |
| 118 | if err != nil { |
| 119 | return err |
| 120 | } |
| 121 | if full { |
| 122 | return b.err |
| 123 | } |
| 124 | } |
| 125 | var n int |
| 126 | if tx.QueryRow("SELECT count(*) FROM home_id_native_buckets").Scan(&n) != nil { |
| 127 | return errIDProof |
| 128 | } |
| 129 | if n+len(buckets) > nativeBucketCap { |
| 130 | return errIDProof |
| 131 | } |
| 132 | for _, b := range buckets { |
| 133 | if err := bucketSpend(tx, b.key, b.limit, now); err != nil { |
| 134 | return err |
| 135 | } |
| 136 | } |
| 137 | return nil |
| 138 | } |
| 139 | |
| 140 | // nativeIPBucket is §4's ip_bucket: the IPv4 /32 or the IPv6 /64, from the |
| 141 | // same edge-written address signin's limiter uses. "" when no IP is known, |
| 142 | // which skips the per-IP limits rather than pooling everyone into one. |
| 143 | func nativeIPBucket(r *http.Request) string { |
| 144 | ip := net.ParseIP(clientIP(r)) |
| 145 | if ip == nil { |
| 146 | return "" |
| 147 | } |
| 148 | if v4 := ip.To4(); v4 != nil { |
| 149 | return v4.String() |
| 150 | } |
| 151 | return ip.Mask(net.CIDRMask(64, 128)).String() + "/64" |
| 152 | } |
| 153 | |
| 154 | // nativeNetBucket is the wider network an address sits in: the IPv4 /24 or |
| 155 | // the IPv6 /48. "" when no IP is known. |
| 156 | func nativeNetBucket(r *http.Request) string { |
| 157 | ip := net.ParseIP(clientIP(r)) |
| 158 | if ip == nil { |
| 159 | return "" |
| 160 | } |
| 161 | if v4 := ip.To4(); v4 != nil { |
| 162 | return v4.Mask(net.CIDRMask(24, 32)).String() + "/24" |
| 163 | } |
| 164 | return ip.Mask(net.CIDRMask(48, 128)).String() + "/48" |
| 165 | } |
| 166 | |
| 167 | func newNativeCode() (string, error) { |
| 168 | n, err := rand.Int(rand.Reader, big.NewInt(1000000)) |
| 169 | if err != nil { |
| 170 | return "", err |
| 171 | } |
| 172 | return fmt.Sprintf("%06d", n.Int64()), nil |
| 173 | } |
| 174 | |
| 175 | // codeMAC binds a code to its start, so a code is worth nothing elsewhere. |
| 176 | func (a *App) codeMAC(startHash, code string) string { |
| 177 | return a.nativeMAC("native-code", startHash, code) |
| 178 | } |
| 179 | |
| 180 | func validCode(s string) bool { |
| 181 | if len(s) != 6 { |
| 182 | return false |
| 183 | } |
| 184 | for i := 0; i < 6; i++ { |
| 185 | if s[i] < '0' || s[i] > '9' { |
| 186 | return false |
| 187 | } |
| 188 | } |
| 189 | return true |
| 190 | } |
| 191 | |
| 192 | // nativeAddress is the address as /signin normalises it, and its native |
| 193 | // blind: a Home-keyed HMAC distinct from the people table's index. |
| 194 | func (a *App) nativeAddress(raw string) (address, blind string, err error) { |
| 195 | local, domain, err := signin.SplitAddress(raw) |
| 196 | if err != nil || len(raw) > 320 { |
| 197 | return "", "", signin.ErrBadAddress |
| 198 | } |
| 199 | address = local + "@" + domain |
| 200 | return address, a.nativeMAC("native-address", strings.ToLower(address)), nil |
| 201 | } |
| 202 | |
| 203 | // personFor finds, never mints, the person behind an address. |
| 204 | func (a *App) personFor(tx *sql.Tx, address string) (string, error) { |
| 205 | var person string |
| 206 | err := tx.QueryRow("SELECT person_ref FROM people WHERE blind_index=?", blindIndex(a.secrets.Pepper, address)).Scan(&person) |
| 207 | if errors.Is(err, sql.ErrNoRows) { |
| 208 | return "", nil |
| 209 | } |
| 210 | if err != nil { |
| 211 | return "", errIDProof |
| 212 | } |
| 213 | return person, nil |
| 214 | } |
| 215 | |
| 216 | // spendWebBudget spends the address's share of the web door's email budget, |
| 217 | // so an address has one allowance across both doors (§4). |
| 218 | func (a *App) spendWebBudget(ctx context.Context, address string) bool { |
| 219 | budget := a.flow.AddressBudget |
| 220 | if budget == 0 { |
| 221 | budget = 5 |
| 222 | } |
| 223 | ok, err := a.flow.Limiter.Allow(ctx, "addr:"+strings.ToLower(address), time.Now(), budget) |
| 224 | return err == nil && ok |
| 225 | } |
| 226 | |
| 227 | // sweepNativeAtBoot drops expired starts, pendings and buckets at boot, as |
| 228 | // the link store does, so a sealed address never outlives its code because |
| 229 | // nobody started another one before a restart. |
| 230 | func (a *App) sweepNativeAtBoot(ctx context.Context) error { |
| 231 | tx, err := a.db.Writer().BeginTx(ctx, nil) |
| 232 | if err != nil { |
| 233 | return err |
| 234 | } |
| 235 | defer tx.Rollback() |
| 236 | if err = sweepCodes(tx, time.Now().Unix()); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | return tx.Commit() |
| 240 | } |
| 241 | |
| 242 | func sweepCodes(tx *sql.Tx, now int64) error { |
| 243 | for _, q := range []string{ |
| 244 | "DELETE FROM home_id_native_starts WHERE expires_at<=?", |
| 245 | "DELETE FROM home_id_native_pending WHERE expires_at<=?", |
| 246 | "DELETE FROM home_id_native_buckets WHERE expires_at<=?", |
| 247 | } { |
| 248 | if _, err := tx.Exec(q, now); err != nil { |
| 249 | return errIDProof |
| 250 | } |
| 251 | } |
| 252 | return nil |
| 253 | } |
| 254 | |
| 255 | func nativeLimitFail(w http.ResponseWriter, err error) { |
| 256 | switch { |
| 257 | case errors.Is(err, errNativeDailyLimit): |
| 258 | nativeFail(w, http.StatusTooManyRequests, "daily_limit") |
| 259 | case errors.Is(err, errNativeLimited): |
| 260 | nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| 261 | default: |
| 262 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | // nativeCodeStart is POST code/start {email, device_key, platform}. The |
| 267 | // answer is the same for an address Home knows and one it has never seen. |
| 268 | func (a *App) nativeCodeStart(w http.ResponseWriter, r *http.Request) { |
| 269 | body, ok := nativeIntake(w, r) |
| 270 | if !ok { |
| 271 | return |
| 272 | } |
| 273 | var in struct { |
| 274 | Email string `json:"email"` |
| 275 | DeviceKey string `json:"device_key"` |
| 276 | Platform string `json:"platform"` |
| 277 | } |
| 278 | if !decodeNative(body, &in) || !nativePlatforms[in.Platform] { |
| 279 | nativeFail(w, http.StatusBadRequest, "request") |
| 280 | return |
| 281 | } |
| 282 | if !a.nativePreGrant(r, body, in.DeviceKey, time.Now().Unix()) { |
| 283 | nativeUnauthorized(w, nativeProofRejected) |
| 284 | return |
| 285 | } |
| 286 | address, blind, err := a.nativeAddress(in.Email) |
| 287 | if err != nil { |
| 288 | nativeFail(w, http.StatusBadRequest, "email") |
| 289 | return |
| 290 | } |
| 291 | ip := nativeIPBucket(r) |
| 292 | ipBlind := "" |
| 293 | if ip != "" { |
| 294 | ipBlind = a.nativeMAC("native-ip", ip) |
| 295 | } |
| 296 | |
| 297 | tx, now, err := a.idTransaction(r.Context()) |
| 298 | if err != nil { |
| 299 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 300 | return |
| 301 | } |
| 302 | defer tx.Rollback() |
| 303 | if sweepCodes(tx, now) != nil { |
| 304 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 305 | return |
| 306 | } |
| 307 | // A second start for the same (address, key) replaces the first: one |
| 308 | // code is live per pair, and the old one stops counting as live. |
| 309 | if _, err = tx.Exec("DELETE FROM home_id_native_starts WHERE blind_index=? AND device_key=?", blind, in.DeviceKey); err != nil { |
| 310 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 311 | return |
| 312 | } |
| 313 | var live, liveIP int |
| 314 | if tx.QueryRow("SELECT count(*) FROM home_id_native_starts").Scan(&live) != nil { |
| 315 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 316 | return |
| 317 | } |
| 318 | if live >= nativeLiveStarts { |
| 319 | // Full: new starts wait, existing ones still verify, and the web's |
| 320 | // link sign-in is untouched (§4). |
| 321 | nativeFail(w, http.StatusServiceUnavailable, "full") |
| 322 | return |
| 323 | } |
| 324 | if ipBlind != "" { |
| 325 | if tx.QueryRow("SELECT count(*) FROM home_id_native_starts WHERE ip_bucket=?", ipBlind).Scan(&liveIP) != nil { |
| 326 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 327 | return |
| 328 | } |
| 329 | if liveIP >= nativeLivePerIP { |
| 330 | nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| 331 | return |
| 332 | } |
| 333 | } |
| 334 | person, err := a.personFor(tx, address) |
| 335 | if err != nil { |
| 336 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 337 | return |
| 338 | } |
| 339 | returning, err := returningKey(tx, person, in.DeviceKey) |
| 340 | if err != nil { |
| 341 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 342 | return |
| 343 | } |
| 344 | buckets := []nativeBucket{{a.bucketKey(startsPerAddressKey, blind, in.DeviceKey), startsPerAddressKey, errNativeLimited}} |
| 345 | if ipBlind != "" { |
| 346 | buckets = append(buckets, |
| 347 | nativeBucket{a.bucketKey(startsPerIP, ipBlind), startsPerIP, errNativeLimited}, |
| 348 | nativeBucket{a.bucketKey(startsPerIPDay, ipBlind), startsPerIPDay, errNativeLimited}, |
| 349 | nativeBucket{a.bucketKey(startsPerNetDay, a.nativeMAC("native-ip", nativeNetBucket(r))), startsPerNetDay, errNativeLimited}) |
| 350 | } |
| 351 | if !returning { |
| 352 | // A new device's start is pointless once the address's new-device |
| 353 | // guesses are spent for the day, so it is refused before any mail. |
| 354 | full, err := bucketFull(tx, a.bucketKey(wrongNewKeysPerDay, blind), wrongNewKeysPerDay, now) |
| 355 | if err != nil { |
| 356 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 357 | return |
| 358 | } |
| 359 | if full { |
| 360 | nativeLimitFail(w, errNativeDailyLimit) |
| 361 | return |
| 362 | } |
| 363 | buckets = append(buckets, |
| 364 | nativeBucket{a.bucketKey(startsPerAddress, blind), startsPerAddress, errNativeLimited}, |
| 365 | nativeBucket{a.bucketKey(startsPerAddressDay, blind), startsPerAddressDay, errNativeLimited}) |
| 366 | } |
| 367 | if err = checkThenSpend(tx, buckets, now); err != nil { |
| 368 | nativeLimitFail(w, err) |
| 369 | return |
| 370 | } |
| 371 | start, err := nativeToken() |
| 372 | if err != nil { |
| 373 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 374 | return |
| 375 | } |
| 376 | code, err := newNativeCode() |
| 377 | if err != nil { |
| 378 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 379 | return |
| 380 | } |
| 381 | startHash := nativeHash(start) |
| 382 | sealed, err := a.secrets.Sealer.Seal(nativeCodeSealScope, []byte(address)) |
| 383 | if err != nil { |
| 384 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 385 | return |
| 386 | } |
| 387 | if _, err = tx.Exec("INSERT INTO home_id_native_starts(start_hash,sealed_address,blind_index,device_key,platform,ip_bucket,code_mac,sends,last_send,attempts,expires_at) VALUES(?,?,?,?,?,?,?,1,?,0,?)", |
| 388 | startHash, sealed, blind, in.DeviceKey, in.Platform, ipBlind, a.codeMAC(startHash, code), now, now+nativeCodeLife); err != nil { |
| 389 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 390 | return |
| 391 | } |
| 392 | // Last before commit: the in-memory web budget cannot roll back, so it is |
| 393 | // spent only once every persistent check has passed. |
| 394 | if !a.spendWebBudget(r.Context(), address) { |
| 395 | nativeLimitFail(w, errNativeLimited) |
| 396 | return |
| 397 | } |
| 398 | if tx.Commit() != nil { |
| 399 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 400 | return |
| 401 | } |
| 402 | if !a.sendCode(r.Context(), address, code) { |
| 403 | a.dropStart(r.Context(), startHash) |
| 404 | nativeFail(w, http.StatusServiceUnavailable, "mail") |
| 405 | return |
| 406 | } |
| 407 | nativeReply(w, http.StatusAccepted, map[string]any{"start": start, "resend_after": nativeResendAfter}) |
| 408 | } |
| 409 | |
| 410 | // sendCode mails the code. Neither the code nor the address reaches a log. |
| 411 | func (a *App) sendCode(ctx context.Context, address, code string) bool { |
| 412 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 413 | defer cancel() |
| 414 | if a.secrets.Mailer.Send(ctx, address, codeMailSubject, codeMailBody(code)) != nil { |
| 415 | a.logger.Warn("native code delivery failed") |
| 416 | return false |
| 417 | } |
| 418 | return true |
| 419 | } |
| 420 | |
| 421 | // dropStart removes a start whose mail failed. Best effort: the row is |
| 422 | // sealed and expires in ten minutes regardless. |
| 423 | func (a *App) dropStart(ctx context.Context, startHash string) { |
| 424 | if _, err := a.db.Writer().ExecContext(ctx, "DELETE FROM home_id_native_starts WHERE start_hash=?", startHash); err != nil { |
| 425 | a.logger.Warn("dropping an undelivered native start failed") |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | type nativeStart struct { |
| 430 | hash, deviceKey, platform, blind, codeMAC string |
| 431 | sealed []byte |
| 432 | sends, attempts int |
| 433 | lastSend int64 |
| 434 | } |
| 435 | |
| 436 | func loadStart(tx *sql.Tx, start string, now int64) (nativeStart, bool) { |
| 437 | s := nativeStart{hash: nativeHash(start)} |
| 438 | if _, ok := decodeB64(start, 32); !ok { |
| 439 | return s, false |
| 440 | } |
| 441 | err := tx.QueryRow("SELECT device_key,platform,blind_index,code_mac,sealed_address,sends,attempts,last_send FROM home_id_native_starts WHERE start_hash=? AND expires_at>?", s.hash, now). |
| 442 | Scan(&s.deviceKey, &s.platform, &s.blind, &s.codeMAC, &s.sealed, &s.sends, &s.attempts, &s.lastSend) |
| 443 | return s, err == nil |
| 444 | } |
| 445 | |
| 446 | // nativeCodeResend is POST code/resend {start}: a new code for the same |
| 447 | // start, at most three sends, thirty seconds apart. |
| 448 | func (a *App) nativeCodeResend(w http.ResponseWriter, r *http.Request) { |
| 449 | body, ok := nativeIntake(w, r) |
| 450 | if !ok { |
| 451 | return |
| 452 | } |
| 453 | var in struct { |
| 454 | Start string `json:"start"` |
| 455 | } |
| 456 | if !decodeNative(body, &in) { |
| 457 | nativeFail(w, http.StatusBadRequest, "request") |
| 458 | return |
| 459 | } |
| 460 | tx, now, err := a.idTransaction(r.Context()) |
| 461 | if err != nil { |
| 462 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 463 | return |
| 464 | } |
| 465 | defer tx.Rollback() |
| 466 | if sweepCodes(tx, now) != nil { |
| 467 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 468 | return |
| 469 | } |
| 470 | s, found := loadStart(tx, in.Start, now) |
| 471 | if !found { |
| 472 | // Unknown, expired, used or dead after five wrong tries: one answer, |
| 473 | // and the app starts again. |
| 474 | nativeFail(w, http.StatusGone, "expired") |
| 475 | return |
| 476 | } |
| 477 | if !a.nativePreGrant(r, body, s.deviceKey, now) { |
| 478 | nativeUnauthorized(w, nativeProofRejected) |
| 479 | return |
| 480 | } |
| 481 | if s.sends >= nativeCodeSends { |
| 482 | nativeFail(w, http.StatusTooManyRequests, "rate_limited") |
| 483 | return |
| 484 | } |
| 485 | if wait := s.lastSend + nativeResendAfter - now; wait > 0 { |
| 486 | nativeReply(w, http.StatusTooManyRequests, map[string]any{"error": "rate_limited", "resend_after": wait}) |
| 487 | return |
| 488 | } |
| 489 | plain, err := a.secrets.Sealer.Open(nativeCodeSealScope, s.sealed) |
| 490 | if err != nil { |
| 491 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 492 | return |
| 493 | } |
| 494 | address := string(plain) |
| 495 | code, err := newNativeCode() |
| 496 | if err != nil { |
| 497 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 498 | return |
| 499 | } |
| 500 | // A new code replaces the old one, with its own five tries; the |
| 501 | // persistent wrong-code buckets still bound guessing across codes. |
| 502 | if _, err = tx.Exec("UPDATE home_id_native_starts SET code_mac=?,sends=sends+1,last_send=?,attempts=0,expires_at=? WHERE start_hash=?", a.codeMAC(s.hash, code), now, now+nativeCodeLife, s.hash); err != nil { |
| 503 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 504 | return |
| 505 | } |
| 506 | if !a.spendWebBudget(r.Context(), address) { |
| 507 | nativeLimitFail(w, errNativeLimited) |
| 508 | return |
| 509 | } |
| 510 | if tx.Commit() != nil { |
| 511 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 512 | return |
| 513 | } |
| 514 | if !a.sendCode(r.Context(), address, code) { |
| 515 | nativeFail(w, http.StatusServiceUnavailable, "mail") |
| 516 | return |
| 517 | } |
| 518 | nativeReply(w, http.StatusAccepted, map[string]any{"start": in.Start, "resend_after": nativeResendAfter}) |
| 519 | } |
| 520 | |
| 521 | // nativeCodeVerify is POST code/verify {start, code}. A right code finds or |
| 522 | // mints the person and runs idGate's check: no passkey mints a grant; a |
| 523 | // passkey returns a pending that must be finished with one. |
| 524 | func (a *App) nativeCodeVerify(w http.ResponseWriter, r *http.Request) { |
| 525 | body, ok := nativeIntake(w, r) |
| 526 | if !ok { |
| 527 | return |
| 528 | } |
| 529 | var in struct { |
| 530 | Start string `json:"start"` |
| 531 | Code string `json:"code"` |
| 532 | } |
| 533 | if !decodeNative(body, &in) || !validCode(in.Code) { |
| 534 | nativeFail(w, http.StatusBadRequest, "request") |
| 535 | return |
| 536 | } |
| 537 | tx, now, err := a.idTransaction(r.Context()) |
| 538 | if err != nil { |
| 539 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 540 | return |
| 541 | } |
| 542 | defer tx.Rollback() |
| 543 | if sweepCodes(tx, now) != nil { |
| 544 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 545 | return |
| 546 | } |
| 547 | s, found := loadStart(tx, in.Start, now) |
| 548 | if !found { |
| 549 | nativeFail(w, http.StatusGone, "expired") |
| 550 | return |
| 551 | } |
| 552 | if !a.nativePreGrant(r, body, s.deviceKey, now) { |
| 553 | nativeUnauthorized(w, nativeProofRejected) |
| 554 | return |
| 555 | } |
| 556 | plain, err := a.secrets.Sealer.Open(nativeCodeSealScope, s.sealed) |
| 557 | if err != nil { |
| 558 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 559 | return |
| 560 | } |
| 561 | address := string(plain) |
| 562 | person, err := a.personFor(tx, address) |
| 563 | if err != nil { |
| 564 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 565 | return |
| 566 | } |
| 567 | returning, err := returningKey(tx, person, s.deviceKey) |
| 568 | if err != nil { |
| 569 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 570 | return |
| 571 | } |
| 572 | wrongKey := nativeBucket{a.bucketKey(wrongPerAddressKey, s.blind, s.deviceKey), wrongPerAddressKey, errNativeLimited} |
| 573 | wrongNew := nativeBucket{a.bucketKey(wrongNewKeysPerDay, s.blind), wrongNewKeysPerDay, errNativeDailyLimit} |
| 574 | guard := []nativeBucket{wrongKey} |
| 575 | if !returning { |
| 576 | guard = append(guard, wrongNew) |
| 577 | } |
| 578 | for _, b := range guard { |
| 579 | full, err := bucketFull(tx, b.key, b.limit, now) |
| 580 | if err != nil { |
| 581 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 582 | return |
| 583 | } |
| 584 | if full { |
| 585 | nativeLimitFail(w, b.err) |
| 586 | return |
| 587 | } |
| 588 | } |
| 589 | if !hmac.Equal([]byte(a.codeMAC(s.hash, in.Code)), []byte(s.codeMAC)) { |
| 590 | for _, b := range guard { |
| 591 | if bucketSpend(tx, b.key, b.limit, now) != nil { |
| 592 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 593 | return |
| 594 | } |
| 595 | } |
| 596 | q := "UPDATE home_id_native_starts SET attempts=attempts+1 WHERE start_hash=?" |
| 597 | if s.attempts+1 >= nativeCodeTries { |
| 598 | q = "DELETE FROM home_id_native_starts WHERE start_hash=?" |
| 599 | } |
| 600 | if _, err = tx.Exec(q, s.hash); err != nil || tx.Commit() != nil { |
| 601 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 602 | return |
| 603 | } |
| 604 | nativeFail(w, http.StatusBadRequest, "code") |
| 605 | return |
| 606 | } |
| 607 | // Right: the start is used once, and its sealed address goes with it. |
| 608 | if _, err = tx.Exec("DELETE FROM home_id_native_starts WHERE start_hash=?", s.hash); err != nil { |
| 609 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 610 | return |
| 611 | } |
| 612 | if person == "" { |
| 613 | if person, err = findOrMintPersonOn(r.Context(), tx, a.secrets.Pepper, address, time.Unix(now, 0)); err != nil { |
| 614 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 615 | return |
| 616 | } |
| 617 | } |
| 618 | var passkeys int |
| 619 | if tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", person).Scan(&passkeys) != nil { |
| 620 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 621 | return |
| 622 | } |
| 623 | var reply map[string]any |
| 624 | if passkeys == 0 { |
| 625 | reply, err = a.mintGrant(tx, person, s.deviceKey, s.platform, "email", now, now) |
| 626 | } else { |
| 627 | reply, err = a.nativePending(tx, person, s, now) |
| 628 | } |
| 629 | if err != nil || tx.Commit() != nil { |
| 630 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 631 | return |
| 632 | } |
| 633 | nativeReply(w, http.StatusOK, reply) |
| 634 | } |
| 635 | |
| 636 | // nativePending is a code verified for an enrolled account: no grant, only a |
| 637 | // five-minute handle bound to the start and its key, finished by a passkey. |
| 638 | func (a *App) nativePending(tx *sql.Tx, person string, s nativeStart, now int64) (map[string]any, error) { |
| 639 | var n int |
| 640 | if tx.QueryRow("SELECT count(*) FROM home_id_native_pending").Scan(&n) != nil || n >= nativeLiveStarts { |
| 641 | return nil, errIDProof |
| 642 | } |
| 643 | pending, err := nativeToken() |
| 644 | if err != nil { |
| 645 | return nil, errIDProof |
| 646 | } |
| 647 | if _, err = tx.Exec("INSERT INTO home_id_native_pending VALUES(?,?,?,?,?,?,?)", nativeHash(pending), person, s.hash, s.deviceKey, s.platform, "email", now+nativePendingLife); err != nil { |
| 648 | return nil, errIDProof |
| 649 | } |
| 650 | return map[string]any{"factor": []string{"passkey"}, "pending": pending}, nil |
| 651 | } |
| 652 | |