feat(auth): passkeys, as a way in and as a second factor
A password and a TOTP code are both shared secrets: the server keeps something that can be stolen from it, and the person keeps something that can be talked out of them. A passkey is neither. The private half never leaves the device, and the signature is bound to the origin that asked for it — so a convincing copy of the sign-in page at another address gets a signature it cannot use. Logging in asks for no email. The device knows which account its key belongs to, which is not only convenience: it means the sign-in page cannot be used to find out who has an account here. A key that verified its owner is both factors at once and completes the login; one that only proved possession still meets the TOTP step, exactly as a password does. The relying party id is derived from VERDANDE_BASE_URL rather than configured separately — a second setting that has to agree with the first is one that will one day disagree, and the failure is a login nobody can complete. An IP address is refused up front: no browser accepts one, and without the check the server issues a challenge happily and the browser throws SecurityError long afterwards. The list endpoint reports whether this deployment can offer them at all, so the interface never shows a button that cannot work. A challenge is stored server-side, answerable exactly once, and taken rather than read — two requests racing the same one would both succeed, which is the shape of a replay. A sign count that has gone backwards means the credential was cloned and is refused rather than logged. The Go tests cover who may reach these endpoints and that challenges are spent. The ceremony itself needs an authenticator, so the smoke test drives Chromium's virtual one over CDP — the only thing that can tell whether the base64url conversions are right, since one wrong byte produces a signature that will not verify and reads as a broken key rather than a broken encoder. That test runs at localhost in its own context while the suite stays on the loopback address, because WebAuthn refuses an IP and resolving localhost is slow enough here to cost the suite minutes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
982c3aab18
commit
fe52818ab6
@@ -0,0 +1,73 @@
|
||||
-- Passkeys: a key on a device instead of a secret in a head.
|
||||
--
|
||||
-- The account already has two ways in — a password, and a TOTP code on top of it.
|
||||
-- Both are shared secrets: the server keeps something that can be stolen from it,
|
||||
-- and the person keeps something that can be phished out of them. A passkey is
|
||||
-- neither. The private half never leaves the device, the public half is all this
|
||||
-- table holds, and the signature is bound to the origin — so a convincing copy of
|
||||
-- the sign-in page at a different address gets nothing.
|
||||
--
|
||||
-- One row per credential rather than per account, because a person has more than
|
||||
-- one device and losing a laptop should not mean losing the way in. The name is
|
||||
-- theirs to write: "min bærbare" is what makes a list of keys reviewable, and a
|
||||
-- list nobody can read is a list nobody revokes from.
|
||||
--
|
||||
-- `sign_count` is the authenticator's own counter. It is stored to be compared:
|
||||
-- a counter that goes backwards means the credential has been cloned, which is
|
||||
-- the one thing this design cannot otherwise detect. Not every authenticator keeps
|
||||
-- one — the spec allows zero — so zero means "not offered" rather than "suspicious".
|
||||
CREATE TABLE passkeys (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
-- The credential id the authenticator generated, raw bytes, base64url as
|
||||
-- stored. Unique across the instance: it is what a login is looked up by,
|
||||
-- before anybody has said who they are.
|
||||
credential_id TEXT NOT NULL,
|
||||
public_key BLOB NOT NULL,
|
||||
-- The AAGUID identifies the authenticator model, which is what lets a list say
|
||||
-- "iCloud Keychain" beside a key somebody named three months ago and forgot.
|
||||
aaguid TEXT NOT NULL DEFAULT '',
|
||||
sign_count INTEGER NOT NULL DEFAULT 0,
|
||||
-- Whether the credential lives on the device itself (a resident key). Only
|
||||
-- those can start a login with no email typed first, so the interface has to
|
||||
-- know which it has before it offers that.
|
||||
discoverable INTEGER NOT NULL DEFAULT 0,
|
||||
-- Whether the authenticator verified the person — a PIN, a fingerprint, a
|
||||
-- face. A key that only proves possession is a first factor; one that verified
|
||||
-- its owner is both, and that is what decides whether a password is still
|
||||
-- asked for.
|
||||
user_verified INTEGER NOT NULL DEFAULT 0,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
last_used_at INTEGER
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX idx_passkeys_credential ON passkeys (credential_id);
|
||||
CREATE INDEX idx_passkeys_user ON passkeys (user_id);
|
||||
|
||||
-- The challenge a registration or a login is answered against.
|
||||
--
|
||||
-- Kept server-side rather than in a cookie: the whole point of the challenge is
|
||||
-- that the server chose it and remembers choosing it. One row per attempt, deleted
|
||||
-- when it is answered, and swept when it expires — a challenge that outlives its
|
||||
-- ceremony is a replay waiting to be tried.
|
||||
--
|
||||
-- user_id is null for a login that has not said who it is yet, which is the case
|
||||
-- a discoverable credential exists for.
|
||||
CREATE TABLE webauthn_challenges (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT REFERENCES users (id) ON DELETE CASCADE,
|
||||
challenge TEXT NOT NULL,
|
||||
-- 'register' or 'login'. A challenge issued for one must not be answerable by
|
||||
-- the other: registering is done by somebody already signed in, and logging in
|
||||
-- is not.
|
||||
purpose TEXT NOT NULL,
|
||||
-- The library's own session state, which carries the allowed credentials and
|
||||
-- the verification requirement it will check the answer against.
|
||||
session BLOB NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
CHECK (purpose IN ('register', 'login'))
|
||||
);
|
||||
|
||||
CREATE INDEX idx_webauthn_challenges_expiry ON webauthn_challenges (expires_at);
|
||||
@@ -0,0 +1,206 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A Passkey is one credential on one device.
|
||||
//
|
||||
// One row per credential rather than per account: a person has a laptop and a
|
||||
// phone, and losing one must not mean losing the way in. The name is theirs to
|
||||
// write — "min bærbare" is what makes the list reviewable, and a list nobody can
|
||||
// read is a list nobody revokes from.
|
||||
type Passkey struct {
|
||||
ID string
|
||||
UserID string
|
||||
CredentialID string
|
||||
PublicKey []byte
|
||||
AAGUID string
|
||||
SignCount uint32
|
||||
Discoverable bool
|
||||
UserVerified bool
|
||||
Name string
|
||||
CreatedAt time.Time
|
||||
LastUsedAt time.Time
|
||||
}
|
||||
|
||||
func (db *DB) CreatePasskey(ctx context.Context, p *Passkey) error {
|
||||
if p.ID == "" {
|
||||
p.ID = NewID()
|
||||
}
|
||||
p.CreatedAt = time.Now().UTC()
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO passkeys (id, user_id, credential_id, public_key, aaguid, sign_count,
|
||||
discoverable, user_verified, name, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
p.ID, p.UserID, p.CredentialID, p.PublicKey, p.AAGUID, p.SignCount,
|
||||
boolToInt(p.Discoverable), boolToInt(p.UserVerified), p.Name, p.CreatedAt.Unix())
|
||||
return err
|
||||
}
|
||||
|
||||
func (db *DB) ListPasskeys(ctx context.Context, userID string) ([]Passkey, error) {
|
||||
rows, err := db.QueryContext(ctx, `
|
||||
SELECT id, user_id, credential_id, public_key, aaguid, sign_count,
|
||||
discoverable, user_verified, name, created_at, COALESCE(last_used_at, 0)
|
||||
FROM passkeys WHERE user_id = ? ORDER BY created_at`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanPasskeys(rows)
|
||||
}
|
||||
|
||||
// PasskeyByCredentialID is how a login finds the account, before anybody has said
|
||||
// who they are. The credential id is unique across the instance, which is what
|
||||
// makes that possible.
|
||||
func (db *DB) PasskeyByCredentialID(ctx context.Context, credentialID string) (*Passkey, error) {
|
||||
rows, err := db.QueryContext(ctx, `
|
||||
SELECT id, user_id, credential_id, public_key, aaguid, sign_count,
|
||||
discoverable, user_verified, name, created_at, COALESCE(last_used_at, 0)
|
||||
FROM passkeys WHERE credential_id = ?`, credentialID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list, err := scanPasskeys(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return &list[0], nil
|
||||
}
|
||||
|
||||
// TouchPasskey records a use and the authenticator's counter.
|
||||
//
|
||||
// The counter is stored to be compared. One that goes backwards means the
|
||||
// credential has been cloned, which is the single thing this design cannot
|
||||
// otherwise detect — and not every authenticator keeps one, so zero means "not
|
||||
// offered" rather than "suspicious".
|
||||
func (db *DB) TouchPasskey(ctx context.Context, id string, signCount uint32) error {
|
||||
_, err := db.ExecContext(ctx,
|
||||
`UPDATE passkeys SET sign_count = ?, last_used_at = ? WHERE id = ?`,
|
||||
signCount, time.Now().Unix(), id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (db *DB) RenamePasskey(ctx context.Context, id, userID, name string) error {
|
||||
res, err := db.ExecContext(ctx,
|
||||
`UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?`, name, id, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeletePasskey removes one key. Scoped in the SQL rather than checked first: an
|
||||
// id read in one step and deleted in the next is a window, and the reason somebody
|
||||
// is on this screen at all is usually that they think a device is gone.
|
||||
func (db *DB) DeletePasskey(ctx context.Context, id, userID string) error {
|
||||
res, err := db.ExecContext(ctx,
|
||||
`DELETE FROM passkeys WHERE id = ? AND user_id = ?`, id, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountPasskeys is what stops somebody removing their last way in when it is the
|
||||
// only one they have.
|
||||
func (db *DB) CountPasskeys(ctx context.Context, userID string) (int, error) {
|
||||
var n int
|
||||
err := db.QueryRowContext(ctx,
|
||||
`SELECT count(*) FROM passkeys WHERE user_id = ?`, userID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func scanPasskeys(rows *sql.Rows) ([]Passkey, error) {
|
||||
out := []Passkey{}
|
||||
for rows.Next() {
|
||||
var p Passkey
|
||||
var discoverable, verified int
|
||||
var created, used int64
|
||||
if err := rows.Scan(&p.ID, &p.UserID, &p.CredentialID, &p.PublicKey, &p.AAGUID,
|
||||
&p.SignCount, &discoverable, &verified, &p.Name, &created, &used); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Discoverable = discoverable == 1
|
||||
p.UserVerified = verified == 1
|
||||
p.CreatedAt = time.Unix(created, 0).UTC()
|
||||
if used > 0 {
|
||||
p.LastUsedAt = time.Unix(used, 0).UTC()
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// --- challenges -------------------------------------------------------------------
|
||||
|
||||
// StoreChallenge keeps the server's side of one ceremony.
|
||||
//
|
||||
// Server-side rather than in a cookie: the whole point of a challenge is that the
|
||||
// server chose it and remembers choosing it. It is deleted when answered and swept
|
||||
// when it expires — a challenge that outlives its ceremony is a replay waiting to
|
||||
// be tried.
|
||||
func (db *DB) StoreChallenge(ctx context.Context, userID, challenge, purpose string, session []byte, ttl time.Duration) (string, error) {
|
||||
id := NewID()
|
||||
now := time.Now()
|
||||
_, err := db.ExecContext(ctx, `
|
||||
INSERT INTO webauthn_challenges (id, user_id, challenge, purpose, session, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
id, nullString(userID), challenge, purpose, session, now.Unix(), now.Add(ttl).Unix())
|
||||
return id, err
|
||||
}
|
||||
|
||||
// TakeChallenge reads a challenge and removes it in the same transaction.
|
||||
//
|
||||
// Taken rather than read, because a challenge is answerable exactly once. Two
|
||||
// requests racing the same one would otherwise both succeed, which is the whole
|
||||
// shape of a replay.
|
||||
func (db *DB) TakeChallenge(ctx context.Context, id, purpose string) (userID string, session []byte, err error) {
|
||||
err = db.Tx(ctx, func(tx *sql.Tx) error {
|
||||
var owner sql.NullString
|
||||
var expires int64
|
||||
row := tx.QueryRowContext(ctx,
|
||||
`SELECT user_id, session, expires_at FROM webauthn_challenges WHERE id = ? AND purpose = ?`,
|
||||
id, purpose)
|
||||
if err := row.Scan(&owner, &session, &expires); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM webauthn_challenges WHERE id = ?`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if time.Now().Unix() > expires {
|
||||
return ErrNotFound
|
||||
}
|
||||
userID = owner.String
|
||||
return nil
|
||||
})
|
||||
return userID, session, err
|
||||
}
|
||||
|
||||
// PurgeChallenges is run by the nightly sweep. An answered challenge deletes
|
||||
// itself; an abandoned one is what this is for.
|
||||
func (db *DB) PurgeChallenges(ctx context.Context) (int64, error) {
|
||||
res, err := db.ExecContext(ctx,
|
||||
`DELETE FROM webauthn_challenges WHERE expires_at < ?`, time.Now().Unix())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
Reference in New Issue
Block a user