oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1// Package consumer is the side of Base's sign-in handoff that every app Base
2// installs shares. It accepts Base's identity assertion and starts the app's
3// own session.
4//
5// The exchange has three steps, all on the app's own origin:
6//
7// 1. GET /auth/start sets a pending cookie holding a random secret, records
8// a fresh nonce against that secret, and sends the browser to Base's
9// /authorize with the nonce.
10// 2. Base answers with a form that posts the signed assertion to
11// POST /auth/assertion. That request comes from Base's page, so it may
12// carry no cookies of ours. It must carry Base's exact Origin. The
13// assertion is verified, held in an inbox under a second random cookie,
14// and the browser is sent on with a same-origin 303.
15// 3. GET /auth/finish arrives with both cookies. The assertion's nonce must
16// match the one recorded for this browser's pending request, and in one
17// transaction the pending request and inbox entry are consumed and the
18// assertion's ID is recorded so it can never be used again. Only then is
19// the session started.
20//
21// POST /auth/signout ends the app's own session, and nothing else, and
22// lands on GET /auth/signed-out.
23//
24// An assertion says who the person is. It grants nothing: each app decides
25// what that person may do.
26package consumer
27
28import (
29 "context"
30 "crypto/rand"
31 "crypto/sha256"
32 "crypto/subtle"
33 "database/sql"
34 "embed"
35 "encoding/base64"
36 "encoding/hex"
37 "encoding/json"
38 "errors"
39 "fmt"
40 "io"
41 "io/fs"
42 "log/slog"
43 "math"
44 "mime"
45 "net/http"
46 "net/url"
47 "strings"
48 "time"
49 "unicode/utf8"
50
51 "github.com/go-chi/chi/v5"
52
53 "amadan.net/rastrillo/rastrillo/assertion"
54 "amadan.net/rastrillo/rastrillo/migrate"
55 "amadan.net/rastrillo/rastrillo/sessions"
56
57 "amadan.net/oficina/base/internal/look"
58)
59
60// The handoff's routes.
61const (
62 StartPath = "/auth/start"
63 AssertionPath = "/auth/assertion"
64 FinishPath = "/auth/finish"
65 // SignOutPath ends the app's own session (POST, same origin).
66 SignOutPath = "/auth/signout"
67 // SignedOutPath is the page sign-out lands on.
68 SignedOutPath = "/auth/signed-out"
69)
70
71const (
72 pendingCookie = "__Host-base-pending"
73 inboxCookie = "__Host-base-inbox"
74
75 // A sign-in can take several minutes when Base must email a link.
76 pendingLifetime = int64(600)
77 // The inbox never needs to outlive the assertion it holds.
78 inboxLifetime = int64(120)
79 // How far the clock may step back. Replay rows are kept this long past
80 // their expiry, so a clock moved back cannot make a used assertion valid.
81 clockTolerance = int64(30)
82 // Bounds what unauthenticated requests can make the tables hold.
83 rowLimit = 10000
84
85 // sessionMethod marks sessions this package started.
86 sessionMethod = "base"
87)
88
89var (
90 errRefused = errors.New("consumer: refused")
91 errStorage = errors.New("consumer: storage")
92 errClock = errors.New("consumer: clock")
93 errFull = errors.New("consumer: capacity")
94)
95
96//go:embed migrations/*.sql
97var migrationFS embed.FS
98
99//go:embed templates/*.html
100var templateFS embed.FS
101
102// Schema is the handoff's tables. Apply it with sessions.Schema before Mount.
103var Schema = migrate.MustFromFS(migrationFS, "consumer")
104
105// Config is what an installed app knows about the Base that installed it.
106type Config struct {
107 Origin string // BASE_APP_ORIGIN: this app's own origin, the assertions' audience
108 Issuer string // BASE_APP_ISSUER: Base's origin
109 ConsumerID string // BASE_APP_CONSUMER_ID: this app's id in Base's catalogue
110 Verifier *assertion.Verifier
111 // Logger receives the handoff's refusals and failures. Nil means
112 // slog.Default(). Load leaves it nil; set it before Mount.
113 Logger *slog.Logger
114
115 now func() time.Time // tests only; time.Now when nil
116}
117
118// Load reads the four BASE_APP_* variables Base writes at install time and
119// builds the verifier. getenv is os.Getenv in production. BASE_APP_KEYS is
120// the base64 of a JSON object mapping each key id to the base64 of its
121// 65-byte P-256 public key.
122func Load(getenv func(string) string) (Config, error) {
123 get := func(k string) string { return strings.TrimSpace(getenv(k)) }
124 cfg := Config{Origin: get("BASE_APP_ORIGIN"), Issuer: get("BASE_APP_ISSUER"), ConsumerID: get("BASE_APP_CONSUMER_ID")}
125 raw := get("BASE_APP_KEYS")
126 for _, v := range []struct{ name, value string }{
127 {"BASE_APP_ORIGIN", cfg.Origin}, {"BASE_APP_ISSUER", cfg.Issuer},
128 {"BASE_APP_CONSUMER_ID", cfg.ConsumerID}, {"BASE_APP_KEYS", raw},
129 } {
130 if v.value == "" {
131 return Config{}, fmt.Errorf("%s is required; Base sets it when it installs the app", v.name)
132 }
133 }
134 if !consumerID(cfg.ConsumerID) {
135 return Config{}, errors.New("BASE_APP_CONSUMER_ID must be 1 to 64 characters of a-z, A-Z, 0-9, _ and -")
136 }
137 doc, err := base64.StdEncoding.DecodeString(raw)
138 if err != nil {
139 return Config{}, errors.New("BASE_APP_KEYS is not base64")
140 }
141 var encoded map[string]string
142 if err := json.Unmarshal(doc, &encoded); err != nil {
143 return Config{}, errors.New("BASE_APP_KEYS is not a JSON object of key ids to keys")
144 }
145 keys := make(map[string][]byte, len(encoded))
146 for kid, b64 := range encoded {
147 pub, err := base64.StdEncoding.DecodeString(b64)
148 if err != nil || len(pub) != 65 {
149 return Config{}, errors.New("BASE_APP_KEYS holds a key that is not the base64 of a 65-byte public key")
150 }
151 keys[kid] = pub
152 }
153 if cfg.Verifier, err = assertion.NewVerifier(cfg.Issuer, cfg.Origin, keys); err != nil {
154 return Config{}, errors.New("BASE_APP_ORIGIN and BASE_APP_ISSUER must be different https origins (hostnames, no path), and BASE_APP_KEYS 1 to 8 valid keys")
155 }
156 return cfg, nil
157}
158
159func consumerID(s string) bool {
160 if len(s) == 0 || len(s) > 64 {
161 return false
162 }
163 for _, b := range []byte(s) {
164 if !(b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || b == '_' || b == '-') {
165 return false
166 }
167 }
168 return true
169}
170
171type handoff struct {
172 db *sql.DB
173 cfg Config
174 sess *sessions.Sessions
175 host string
176 logger *slog.Logger
177 pages *look.Renderer
178}
179
180// Mount adds the handoff to r: a middleware that puts the signed-in person
181// on every request, and the three routes. Call it before adding any route to
182// r (chi requires middleware first). db is the writer handle with Schema
183// applied; sess must be built for cfg.Origin on the same database.
184//
185// POST /auth/signout ends the app's session and sends the browser to
186// GET /auth/signed-out, a page that says so, with a link to sign in again
187// and one back to Base's Home. It relies on the app's CSRF guard, which it
188// does not exempt. It signs out of this app only: Base, and other apps,
189// keep theirs.
190//
191// POST /auth/assertion arrives from Base's page, so the app's CSRF guard must
192// exempt it, as csrf.Protect(origin, csrf.Exempt(consumer.AssertionPath))
193// does. That handler makes its own, stricter check: Origin must be exactly
194// Base's.
195//
196// Mount panics on a missing database, session store or verifier.
197func Mount(r chi.Router, db *sql.DB, cfg Config, sess *sessions.Sessions) {
198 if db == nil || sess == nil || cfg.Verifier == nil {
199 panic("consumer.Mount: needs a database, a session store and a Config from Load")
200 }
201 if cfg.now == nil {
202 cfg.now = time.Now
203 }
204 logger := cfg.Logger
205 if logger == nil {
206 logger = slog.Default()
207 }
208 sub, err := fs.Sub(templateFS, "templates")
209 if err != nil {
210 panic("consumer.Mount: " + err.Error())
211 }
212 pages, err := look.NewRenderer(sub, nil)
213 if err != nil {
214 panic("consumer.Mount: " + err.Error())
215 }
216 h := &handoff{db: db, cfg: cfg, sess: sess, host: strings.TrimPrefix(cfg.Origin, "https://"), logger: logger, pages: pages}
217 r.Use(h.identify)
218 r.Get(StartPath, h.start)
219 r.Post(AssertionPath, h.assertion)
220 r.Get(FinishPath, h.finish)
221 r.Post(SignOutPath, h.signOut)
222 r.Get(SignedOutPath, h.signedOut)
223}
224
225type ctxKey struct{}
226
227// who is the signed-in person, as the request context carries them.
228type who struct {
229 sub, name, base string
230 broken bool // the lookup failed; Require answers 503
231}
232
233// identify resolves the request's session and the person behind it.
234func (h *handoff) identify(next http.Handler) http.Handler {
235 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
236 s, ok := h.sess.FromContext(r.Context(), r)
237 if !ok || s.Method != sessionMethod {
238 next.ServeHTTP(w, r)
239 return
240 }
241 r = sessions.WithSession(r, s)
242 p, found, err := h.person(r.Context(), s.Subject)
243 switch {
244 case err != nil:
245 h.logger.Error("consumer: person lookup", "err", err)
246 r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, who{broken: true}))
247 case found:
248 r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, p))
249 }
250 next.ServeHTTP(w, r)
251 })
252}
253
254func (h *handoff) person(ctx context.Context, sub string) (who, bool, error) {
255 var p who
256 var email string
257 err := h.db.QueryRowContext(ctx, `SELECT subject, name, email, base FROM base_consumer_people WHERE subject = ?`, sub).
258 Scan(&p.sub, &p.name, &email, &p.base)
259 if errors.Is(err, sql.ErrNoRows) {
260 return who{}, false, nil
261 }
262 if err != nil {
263 return who{}, false, err
264 }
265 if p.name == "" {
266 p.name = email
267 }
268 return p, true, nil
269}
270
271// Require lets through only a request with a signed-in person. A signed-out
272// page request goes to /auth/start with the page as return_to; anything
273// else gets 403. Signed-in responses are marked no-store. Use it on routes
274// of a router Mount was called on.
275func Require(next http.Handler) http.Handler {
276 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
277 w.Header().Set("Cache-Control", "no-store")
278 p, ok := r.Context().Value(ctxKey{}).(who)
279 switch {
280 case ok && p.broken:
281 http.Error(w, "unavailable", http.StatusServiceUnavailable)
282 case ok:
283 next.ServeHTTP(w, r)
284 case r.Method == http.MethodGet || r.Method == http.MethodHead:
285 to := r.URL.RequestURI()
286 if !safePath(to) {
287 to = "/"
288 }
289 http.Redirect(w, r, StartPath+"?return_to="+url.QueryEscape(to), http.StatusSeeOther)
290 default:
291 http.Error(w, "signed out", http.StatusForbidden)
292 }
293 })
294}
295
296// Person is the signed-in person on a request that passed Require: Base's
297// member id, their name (their email when Base has no name for them) and
298// the Base's name. The name and Base name are for display only.
299func Person(r *http.Request) (sub, name, base string, ok bool) {
300 p, ok := r.Context().Value(ctxKey{}).(who)
301 if !ok || p.broken {
302 return "", "", "", false
303 }
304 return p.sub, p.name, p.base, true
305}
306
307// guard refuses a request for another host: the cookies set here belong to
308// this origin only.
309func (h *handoff) guard(w http.ResponseWriter, r *http.Request) bool {
310 w.Header().Set("Cache-Control", "no-store")
311 if r.Host != h.host {
312 http.NotFound(w, r)
313 return false
314 }
315 return true
316}
317
318func (h *handoff) fail(w http.ResponseWriter, err error) {
319 status := http.StatusBadRequest
320 if errors.Is(err, errStorage) || errors.Is(err, errClock) || errors.Is(err, errFull) {
321 status = http.StatusServiceUnavailable
322 h.logger.Error("consumer: sign-in failed", "err", err)
323 }
324 http.Error(w, "Unable to sign in. Start again.", status)
325}
326
327// cookie returns the named cookie's value when the request carries exactly
328// one of that name and it has a handle's shape.
329func cookie(r *http.Request, name string) (string, bool) {
330 value, count := "", 0
331 for _, c := range r.Cookies() {
332 if c.Name == name {
333 count++
334 value = c.Value
335 }
336 }
337 return value, count == 1 && validHandle(value)
338}
339
340// setCookie writes a __Host- cookie: Secure, Path=/ and no Domain, as the
341// prefix requires. Lax, so the top-level GET to /auth/finish carries it.
342func setCookie(w http.ResponseWriter, name, value string, seconds int) {
343 http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds,
344 Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
345}
346
347// start begins a sign-in for this browser and sends it to Base.
348func (h *handoff) start(w http.ResponseWriter, r *http.Request) {
349 if !h.guard(w, r) {
350 return
351 }
352 q, err := url.ParseQuery(r.URL.RawQuery)
353 if err != nil || len(q) > 1 {
354 h.fail(w, errRefused)
355 return
356 }
357 to := "/"
358 if len(q) == 1 {
359 v, ok := q["return_to"]
360 if !ok || len(v) != 1 {
361 h.fail(w, errRefused)
362 return
363 }
364 to = v[0]
365 }
366 if !safePath(to) {
367 h.fail(w, errRefused)
368 return
369 }
370 previous, _ := cookie(r, pendingCookie)
371 secret, nonce, err := h.beginPending(r.Context(), to, previous, h.cfg.now())
372 if err != nil {
373 h.fail(w, err)
374 return
375 }
376 setCookie(w, pendingCookie, secret, int(pendingLifetime))
377 target := h.cfg.Issuer + "/authorize?" + url.Values{"consumer": {h.cfg.ConsumerID}, "nonce": {nonce}}.Encode()
378 http.Redirect(w, r, target, http.StatusSeeOther)
379}
380
381// assertion receives Base's form post. It needs no cookie and must not rely
382// on one: the post comes from Base's page.
383func (h *handoff) assertion(w http.ResponseWriter, r *http.Request) {
384 if !h.guard(w, r) {
385 return
386 }
387 // Exactly Base's origin. A missing Origin or "null" is refused.
388 if o := r.Header.Values("Origin"); len(o) != 1 || o[0] != h.cfg.Issuer {
389 http.Error(w, "Unable to sign in. Start again.", http.StatusForbidden)
390 return
391 }
392 if r.URL.RawQuery != "" {
393 h.fail(w, errRefused)
394 return
395 }
396 if media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || media != "application/x-www-form-urlencoded" {
397 h.fail(w, errRefused)
398 return
399 }
400 // A token is at most 8192 bytes; form encoding leaves it as is (it is
401 // base64url and one dot), so 12 KiB bounds the body before any parsing.
402 body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024))
403 if err != nil {
404 h.fail(w, errRefused)
405 return
406 }
407 form, err := url.ParseQuery(string(body))
408 if err != nil || len(form) != 1 || len(form["assertion"]) != 1 {
409 h.fail(w, errRefused)
410 return
411 }
412 handle, err := h.receive(r.Context(), form["assertion"][0], h.cfg.now())
413 if err != nil {
414 h.fail(w, err)
415 return
416 }
417 setCookie(w, inboxCookie, handle, int(inboxLifetime))
418 // Same origin, relative: Base's CSP lets its form post only here, and a
419 // redirect anywhere else would be refused.
420 http.Redirect(w, r, FinishPath, http.StatusSeeOther)
421}
422
423// finish binds the held assertion to this browser's pending request and, once
424// its use is recorded, starts the session.
425func (h *handoff) finish(w http.ResponseWriter, r *http.Request) {
426 if !h.guard(w, r) {
427 return
428 }
429 secret, okSecret := cookie(r, pendingCookie)
430 handle, okHandle := cookie(r, inboxCookie)
431 // Both are single-use whatever happens next.
432 setCookie(w, pendingCookie, "", -1)
433 setCookie(w, inboxCookie, "", -1)
434 if r.URL.RawQuery != "" || !okSecret || !okHandle {
435 h.fail(w, errRefused)
436 return
437 }
438 // Read before the transaction: the writer pool has one connection.
439 existing := ""
440 if s, ok := sessions.Current(r); ok {
441 existing = s.Subject
442 }
443 claims, to, err := h.consume(r.Context(), secret, handle, existing, h.cfg.now())
444 if err != nil {
445 h.fail(w, err)
446 return
447 }
448 s := sessions.Session{Subject: claims.Subject, Method: sessionMethod, AuthTime: time.Unix(claims.AuthTime, 0)}
449 if err := h.sess.SignIn(w, r, s); err != nil {
450 h.fail(w, storage("start session", err))
451 return
452 }
453 h.logger.Info("signed in through Base", "subject", claims.Subject, "jti", claims.ID)
454 http.Redirect(w, r, to, http.StatusSeeOther)
455}
456
457// signOut ends this browser's session here. Signing in again starts a fresh
458// handoff, so whoever Base vouches for then is who the app sees.
459func (h *handoff) signOut(w http.ResponseWriter, r *http.Request) {
460 if !h.guard(w, r) {
461 return
462 }
463 h.sess.SignOut(w, r)
464 // Not straight to "/": signed out, that redirects on to Base, and the
465 // app's CSP form-action 'self' covers this form's whole redirect chain,
466 // so the browser would refuse the hop and leave the old page showing.
467 // The signed-out page's links are plain navigations.
468 http.Redirect(w, r, SignedOutPath, http.StatusSeeOther)
469}
470
471// signedOut says the person has left this app, and offers the way back in.
472func (h *handoff) signedOut(w http.ResponseWriter, r *http.Request) {
473 if !h.guard(w, r) {
474 return
475 }
476 if err := h.pages.Page(w, "signedout", struct{ Home string }{h.cfg.Issuer + "/"}); err != nil {
477 h.logger.Error("consumer: render signed-out page", "err", err)
478 http.Error(w, "something went wrong", http.StatusInternalServerError)
479 }
480}
481
482func digest(s string) string { sum := sha256.Sum256([]byte(s)); return hex.EncodeToString(sum[:]) }
483
484func jtiHash(c assertion.Claims) string { return digest(c.Issuer + "\x00" + c.ID) }
485
486func randomHandle() (string, error) {
487 var b [32]byte
488 if _, err := rand.Read(b[:]); err != nil {
489 return "", storage("random handle", err)
490 }
491 return base64.RawURLEncoding.EncodeToString(b[:]), nil
492}
493
494func validHandle(s string) bool {
495 if len(s) != 43 {
496 return false
497 }
498 b, err := base64.RawURLEncoding.Strict().DecodeString(s)
499 return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == s
500}
501
502// safePath accepts only a local path on this origin, outside the sign-in
503// routes: one leading slash, no scheme or host, no backslash, control
504// character, space, fragment or dot segment.
505func safePath(s string) bool {
506 if len(s) == 0 || len(s) > 2048 || !utf8.ValidString(s) || !strings.HasPrefix(s, "/") || strings.HasPrefix(s, "//") || strings.Contains(s, "#") {
507 return false
508 }
509 for _, b := range []byte(s) {
510 if b <= ' ' || b == 127 || b == '\\' {
511 return false
512 }
513 }
514 u, err := url.ParseRequestURI(s)
515 if err != nil || u.IsAbs() || u.Host != "" || u.Opaque != "" {
516 return false
517 }
518 p := u.Path
519 if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") || strings.ContainsAny(p, "\\\x00\r\n\t") {
520 return false
521 }
522 for _, part := range strings.Split(p, "/") {
523 if part == "." || part == ".." {
524 return false
525 }
526 }
527 return p != "/auth" && !strings.HasPrefix(p, "/auth/")
528}
529
530// begin opens a transaction, moves the clock fence forward, and prunes what
531// has expired. It refuses a clock more than clockTolerance behind the fence.
532func (h *handoff) begin(ctx context.Context, now time.Time) (*sql.Tx, int64, error) {
533 n := now.Unix()
534 if n <= 0 || n > math.MaxInt64-pendingLifetime {
535 return nil, 0, errClock
536 }
537 tx, err := h.db.BeginTx(ctx, nil)
538 if err != nil {
539 return nil, 0, storage("begin transaction", err)
540 }
541 res, err := tx.ExecContext(ctx, `UPDATE base_consumer_clock SET observed = MAX(observed, ?) WHERE id = 1 AND observed <= ?`, n, n+clockTolerance)
542 if err != nil {
543 tx.Rollback()
544 return nil, 0, storage("advance clock", err)
545 }
546 if rows, err := res.RowsAffected(); err != nil || rows != 1 {
547 tx.Rollback()
548 return nil, 0, errClock
549 }
550 var fence int64
551 if err := tx.QueryRowContext(ctx, `SELECT observed FROM base_consumer_clock WHERE id = 1`).Scan(&fence); err != nil {
552 tx.Rollback()
553 return nil, 0, storage("read clock", err)
554 }
555 for _, q := range []struct {
556 sql string
557 at int64
558 }{
559 {`DELETE FROM base_consumer_pending WHERE expires_at <= ?`, n},
560 {`DELETE FROM base_consumer_inbox WHERE expires_at <= ?`, n},
561 {`DELETE FROM base_consumer_replay WHERE expires_at < ?`, fence - clockTolerance},
562 } {
563 if _, err := tx.ExecContext(ctx, q.sql, q.at); err != nil {
564 tx.Rollback()
565 return nil, 0, storage("prune expired rows", err)
566 }
567 }
568 return tx, n, nil
569}
570
571// beginPending records a new pending request, replacing this browser's
572// previous one. Only hashes of the secret and nonce are stored.
573func (h *handoff) beginPending(ctx context.Context, to, previous string, now time.Time) (secret, nonce string, err error) {
574 if secret, err = randomHandle(); err != nil {
575 return "", "", err
576 }
577 if nonce, err = assertion.RandomID(); err != nil {
578 return "", "", storage("random nonce", err)
579 }
580 tx, n, err := h.begin(ctx, now)
581 if err != nil {
582 return "", "", err
583 }
584 defer tx.Rollback()
585 if validHandle(previous) {
586 if _, err := tx.ExecContext(ctx, `DELETE FROM base_consumer_pending WHERE secret_hash = ?`, digest(previous)); err != nil {
587 return "", "", storage("delete previous pending", err)
588 }
589 }
590 var count int
591 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM base_consumer_pending`).Scan(&count); err != nil {
592 return "", "", storage("count pending", err)
593 }
594 if count >= rowLimit {
595 // Evicting the oldest only loses someone's navigation, never a proof.
596 if _, err := tx.ExecContext(ctx, `DELETE FROM base_consumer_pending WHERE secret_hash IN
597 (SELECT secret_hash FROM base_consumer_pending ORDER BY created_at, secret_hash LIMIT ?)`, count-rowLimit+1); err != nil {
598 return "", "", storage("evict pending", err)
599 }
600 }
601 if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_pending (secret_hash, nonce_hash, return_to, created_at, expires_at)
602 VALUES (?, ?, ?, ?, ?)`, digest(secret), digest(nonce), to, n, n+pendingLifetime); err != nil {
603 return "", "", storage("insert pending", err)
604 }
605 if err := tx.Commit(); err != nil {
606 return "", "", storage("commit pending", err)
607 }
608 return secret, nonce, nil
609}
610
611// receive verifies token and holds it in the inbox under a new handle. An
612// assertion already used, or already waiting, is refused.
613func (h *handoff) receive(ctx context.Context, token string, now time.Time) (string, error) {
614 claims, err := h.cfg.Verifier.Verify(token, now)
615 if err != nil {
616 h.logger.Info("consumer: assertion refused", "err", err)
617 return "", errRefused
618 }
619 handle, err := randomHandle()
620 if err != nil {
621 return "", err
622 }
623 jti := jtiHash(claims)
624 tx, n, err := h.begin(ctx, now)
625 if err != nil {
626 return "", err
627 }
628 defer tx.Rollback()
629 var used int
630 if err := tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM base_consumer_replay WHERE jti_hash = ?)
631 + (SELECT COUNT(*) FROM base_consumer_inbox WHERE jti_hash = ?)`, jti, jti).Scan(&used); err != nil {
632 return "", storage("check replay", err)
633 }
634 if used != 0 {
635 h.logger.Warn("consumer: assertion replayed", "jti", claims.ID)
636 return "", errRefused
637 }
638 var count int
639 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM base_consumer_inbox`).Scan(&count); err != nil {
640 return "", storage("count inbox", err)
641 }
642 if count >= rowLimit {
643 return "", errFull
644 }
645 expires := min(claims.ExpiresAt, n+inboxLifetime)
646 if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_inbox (handle_hash, jti_hash, token, created_at, expires_at)
647 VALUES (?, ?, ?, ?, ?)`, digest(handle), jti, token, n, expires); err != nil {
648 return "", storage("insert inbox", err)
649 }
650 if err := tx.Commit(); err != nil {
651 return "", storage("commit inbox", err)
652 }
653 return handle, nil
654}
655
656// consume checks the held assertion against the pending request and, in one
657// transaction, records its ID, deletes both rows and stores the person's
658// display fields. existing is the subject of a live session already on this
659// browser; an assertion for anyone else is refused rather than swapped in.
660func (h *handoff) consume(ctx context.Context, secret, handle, existing string, now time.Time) (assertion.Claims, string, error) {
661 var zero assertion.Claims
662 tx, n, err := h.begin(ctx, now)
663 if err != nil {
664 return zero, "", err
665 }
666 defer tx.Rollback()
667 secretHash, handleHash := digest(secret), digest(handle)
668 var nonceHash, to, token string
669 if err := tx.QueryRowContext(ctx, `SELECT nonce_hash, return_to FROM base_consumer_pending WHERE secret_hash = ? AND expires_at > ?`,
670 secretHash, n).Scan(&nonceHash, &to); err != nil {
671 return zero, "", readError(err)
672 }
673 if err := tx.QueryRowContext(ctx, `SELECT token FROM base_consumer_inbox WHERE handle_hash = ? AND expires_at > ?`,
674 handleHash, n).Scan(&token); err != nil {
675 return zero, "", readError(err)
676 }
677 claims, err := h.cfg.Verifier.Verify(token, now)
678 if err != nil {
679 return zero, "", errRefused
680 }
681 if subtle.ConstantTimeCompare([]byte(nonceHash), []byte(digest(claims.Nonce))) != 1 {
682 h.logger.Warn("consumer: assertion for another pending request", "jti", claims.ID)
683 return zero, "", errRefused
684 }
685 if existing != "" && existing != claims.Subject {
686 return zero, "", errRefused
687 }
688 if !safePath(to) {
689 return zero, "", errRefused
690 }
691 res, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_replay (jti_hash, expires_at) VALUES (?, ?) ON CONFLICT DO NOTHING`,
692 jtiHash(claims), claims.ExpiresAt)
693 if err != nil {
694 return zero, "", storage("record replay", err)
695 }
696 if rows, err := res.RowsAffected(); err != nil {
697 return zero, "", storage("record replay", err)
698 } else if rows != 1 {
699 return zero, "", errRefused
700 }
701 for _, q := range []struct{ sql, key string }{
702 {`DELETE FROM base_consumer_pending WHERE secret_hash = ?`, secretHash},
703 {`DELETE FROM base_consumer_inbox WHERE handle_hash = ?`, handleHash},
704 } {
705 res, err := tx.ExecContext(ctx, q.sql, q.key)
706 if err != nil {
707 return zero, "", storage("delete consumed row", err)
708 }
709 if rows, err := res.RowsAffected(); err != nil {
710 return zero, "", storage("delete consumed row", err)
711 } else if rows != 1 {
712 return zero, "", fmt.Errorf("%w: delete consumed row: %d rows affected", errStorage, rows)
713 }
714 }
715 // Display only: Ext grants nothing, and a malformed one shows blanks.
716 var ext struct {
717 Name string `json:"name"`
718 Email string `json:"email"`
719 Base string `json:"base"`
720 }
721 _ = json.Unmarshal(claims.Ext, &ext)
722 if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_people (subject, name, email, base, updated_at) VALUES (?, ?, ?, ?, ?)
723 ON CONFLICT (subject) DO UPDATE SET name = excluded.name, email = excluded.email, base = excluded.base, updated_at = excluded.updated_at`,
724 claims.Subject, ext.Name, ext.Email, ext.Base, n); err != nil {
725 return zero, "", storage("store person", err)
726 }
727 if err := tx.Commit(); err != nil {
728 return zero, "", storage("commit finish", err)
729 }
730 return claims, to, nil
731}
732
733// storage classifies a database or randomness failure, keeping the
734// operation and the cause for the log. Callers match it with errors.Is.
735func storage(op string, err error) error {
736 return fmt.Errorf("%w: %s: %w", errStorage, op, err)
737}
738
739func readError(err error) error {
740 if errors.Is(err, sql.ErrNoRows) {
741 return errRefused
742 }
743 return storage("read exchange", err)
744}
745