// Package consumer is the side of Base's sign-in handoff that every app Base // installs shares. It accepts Base's identity assertion and starts the app's // own session. // // The exchange has three steps, all on the app's own origin: // // 1. GET /auth/start sets a pending cookie holding a random secret, records // a fresh nonce against that secret, and sends the browser to Base's // /authorize with the nonce. // 2. Base answers with a form that posts the signed assertion to // POST /auth/assertion. That request comes from Base's page, so it may // carry no cookies of ours. It must carry Base's exact Origin. The // assertion is verified, held in an inbox under a second random cookie, // and the browser is sent on with a same-origin 303. // 3. GET /auth/finish arrives with both cookies. The assertion's nonce must // match the one recorded for this browser's pending request, and in one // transaction the pending request and inbox entry are consumed and the // assertion's ID is recorded so it can never be used again. Only then is // the session started. // // POST /auth/signout ends the app's own session, and nothing else, and // lands on GET /auth/signed-out. // // An assertion says who the person is. It grants nothing: each app decides // what that person may do. package consumer import ( "context" "crypto/rand" "crypto/sha256" "crypto/subtle" "database/sql" "embed" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "io/fs" "log/slog" "math" "mime" "net/http" "net/url" "strings" "time" "unicode/utf8" "github.com/go-chi/chi/v5" "amadan.net/rastrillo/rastrillo/assertion" "amadan.net/rastrillo/rastrillo/migrate" "amadan.net/rastrillo/rastrillo/sessions" "amadan.net/oficina/base/internal/look" ) // The handoff's routes. const ( StartPath = "/auth/start" AssertionPath = "/auth/assertion" FinishPath = "/auth/finish" // SignOutPath ends the app's own session (POST, same origin). SignOutPath = "/auth/signout" // SignedOutPath is the page sign-out lands on. SignedOutPath = "/auth/signed-out" ) const ( pendingCookie = "__Host-base-pending" inboxCookie = "__Host-base-inbox" // A sign-in can take several minutes when Base must email a link. pendingLifetime = int64(600) // The inbox never needs to outlive the assertion it holds. inboxLifetime = int64(120) // How far the clock may step back. Replay rows are kept this long past // their expiry, so a clock moved back cannot make a used assertion valid. clockTolerance = int64(30) // Bounds what unauthenticated requests can make the tables hold. rowLimit = 10000 // sessionMethod marks sessions this package started. sessionMethod = "base" ) var ( errRefused = errors.New("consumer: refused") errStorage = errors.New("consumer: storage") errClock = errors.New("consumer: clock") errFull = errors.New("consumer: capacity") ) //go:embed migrations/*.sql var migrationFS embed.FS //go:embed templates/*.html var templateFS embed.FS // Schema is the handoff's tables. Apply it with sessions.Schema before Mount. var Schema = migrate.MustFromFS(migrationFS, "consumer") // Config is what an installed app knows about the Base that installed it. type Config struct { Origin string // BASE_APP_ORIGIN: this app's own origin, the assertions' audience Issuer string // BASE_APP_ISSUER: Base's origin ConsumerID string // BASE_APP_CONSUMER_ID: this app's id in Base's catalogue Verifier *assertion.Verifier // Logger receives the handoff's refusals and failures. Nil means // slog.Default(). Load leaves it nil; set it before Mount. Logger *slog.Logger now func() time.Time // tests only; time.Now when nil } // Load reads the four BASE_APP_* variables Base writes at install time and // builds the verifier. getenv is os.Getenv in production. BASE_APP_KEYS is // the base64 of a JSON object mapping each key id to the base64 of its // 65-byte P-256 public key. func Load(getenv func(string) string) (Config, error) { get := func(k string) string { return strings.TrimSpace(getenv(k)) } cfg := Config{Origin: get("BASE_APP_ORIGIN"), Issuer: get("BASE_APP_ISSUER"), ConsumerID: get("BASE_APP_CONSUMER_ID")} raw := get("BASE_APP_KEYS") for _, v := range []struct{ name, value string }{ {"BASE_APP_ORIGIN", cfg.Origin}, {"BASE_APP_ISSUER", cfg.Issuer}, {"BASE_APP_CONSUMER_ID", cfg.ConsumerID}, {"BASE_APP_KEYS", raw}, } { if v.value == "" { return Config{}, fmt.Errorf("%s is required; Base sets it when it installs the app", v.name) } } if !consumerID(cfg.ConsumerID) { return Config{}, errors.New("BASE_APP_CONSUMER_ID must be 1 to 64 characters of a-z, A-Z, 0-9, _ and -") } doc, err := base64.StdEncoding.DecodeString(raw) if err != nil { return Config{}, errors.New("BASE_APP_KEYS is not base64") } var encoded map[string]string if err := json.Unmarshal(doc, &encoded); err != nil { return Config{}, errors.New("BASE_APP_KEYS is not a JSON object of key ids to keys") } keys := make(map[string][]byte, len(encoded)) for kid, b64 := range encoded { pub, err := base64.StdEncoding.DecodeString(b64) if err != nil || len(pub) != 65 { return Config{}, errors.New("BASE_APP_KEYS holds a key that is not the base64 of a 65-byte public key") } keys[kid] = pub } if cfg.Verifier, err = assertion.NewVerifier(cfg.Issuer, cfg.Origin, keys); err != nil { 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") } return cfg, nil } func consumerID(s string) bool { if len(s) == 0 || len(s) > 64 { return false } for _, b := range []byte(s) { if !(b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || b == '_' || b == '-') { return false } } return true } type handoff struct { db *sql.DB cfg Config sess *sessions.Sessions host string logger *slog.Logger pages *look.Renderer } // Mount adds the handoff to r: a middleware that puts the signed-in person // on every request, and the three routes. Call it before adding any route to // r (chi requires middleware first). db is the writer handle with Schema // applied; sess must be built for cfg.Origin on the same database. // // POST /auth/signout ends the app's session and sends the browser to // GET /auth/signed-out, a page that says so, with a link to sign in again // and one back to Base's Home. It relies on the app's CSRF guard, which it // does not exempt. It signs out of this app only: Base, and other apps, // keep theirs. // // POST /auth/assertion arrives from Base's page, so the app's CSRF guard must // exempt it, as csrf.Protect(origin, csrf.Exempt(consumer.AssertionPath)) // does. That handler makes its own, stricter check: Origin must be exactly // Base's. // // Mount panics on a missing database, session store or verifier. func Mount(r chi.Router, db *sql.DB, cfg Config, sess *sessions.Sessions) { if db == nil || sess == nil || cfg.Verifier == nil { panic("consumer.Mount: needs a database, a session store and a Config from Load") } if cfg.now == nil { cfg.now = time.Now } logger := cfg.Logger if logger == nil { logger = slog.Default() } sub, err := fs.Sub(templateFS, "templates") if err != nil { panic("consumer.Mount: " + err.Error()) } pages, err := look.NewRenderer(sub, nil) if err != nil { panic("consumer.Mount: " + err.Error()) } h := &handoff{db: db, cfg: cfg, sess: sess, host: strings.TrimPrefix(cfg.Origin, "https://"), logger: logger, pages: pages} r.Use(h.identify) r.Get(StartPath, h.start) r.Post(AssertionPath, h.assertion) r.Get(FinishPath, h.finish) r.Post(SignOutPath, h.signOut) r.Get(SignedOutPath, h.signedOut) } type ctxKey struct{} // who is the signed-in person, as the request context carries them. type who struct { sub, name, base string broken bool // the lookup failed; Require answers 503 } // identify resolves the request's session and the person behind it. func (h *handoff) identify(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s, ok := h.sess.FromContext(r.Context(), r) if !ok || s.Method != sessionMethod { next.ServeHTTP(w, r) return } r = sessions.WithSession(r, s) p, found, err := h.person(r.Context(), s.Subject) switch { case err != nil: h.logger.Error("consumer: person lookup", "err", err) r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, who{broken: true})) case found: r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)) } next.ServeHTTP(w, r) }) } func (h *handoff) person(ctx context.Context, sub string) (who, bool, error) { var p who var email string err := h.db.QueryRowContext(ctx, `SELECT subject, name, email, base FROM base_consumer_people WHERE subject = ?`, sub). Scan(&p.sub, &p.name, &email, &p.base) if errors.Is(err, sql.ErrNoRows) { return who{}, false, nil } if err != nil { return who{}, false, err } if p.name == "" { p.name = email } return p, true, nil } // Require lets through only a request with a signed-in person. A signed-out // page request goes to /auth/start with the page as return_to; anything // else gets 403. Signed-in responses are marked no-store. Use it on routes // of a router Mount was called on. func Require(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") p, ok := r.Context().Value(ctxKey{}).(who) switch { case ok && p.broken: http.Error(w, "unavailable", http.StatusServiceUnavailable) case ok: next.ServeHTTP(w, r) case r.Method == http.MethodGet || r.Method == http.MethodHead: to := r.URL.RequestURI() if !safePath(to) { to = "/" } http.Redirect(w, r, StartPath+"?return_to="+url.QueryEscape(to), http.StatusSeeOther) default: http.Error(w, "signed out", http.StatusForbidden) } }) } // Person is the signed-in person on a request that passed Require: Base's // member id, their name (their email when Base has no name for them) and // the Base's name. The name and Base name are for display only. func Person(r *http.Request) (sub, name, base string, ok bool) { p, ok := r.Context().Value(ctxKey{}).(who) if !ok || p.broken { return "", "", "", false } return p.sub, p.name, p.base, true } // guard refuses a request for another host: the cookies set here belong to // this origin only. func (h *handoff) guard(w http.ResponseWriter, r *http.Request) bool { w.Header().Set("Cache-Control", "no-store") if r.Host != h.host { http.NotFound(w, r) return false } return true } func (h *handoff) fail(w http.ResponseWriter, err error) { status := http.StatusBadRequest if errors.Is(err, errStorage) || errors.Is(err, errClock) || errors.Is(err, errFull) { status = http.StatusServiceUnavailable h.logger.Error("consumer: sign-in failed", "err", err) } http.Error(w, "Unable to sign in. Start again.", status) } // cookie returns the named cookie's value when the request carries exactly // one of that name and it has a handle's shape. func cookie(r *http.Request, name string) (string, bool) { value, count := "", 0 for _, c := range r.Cookies() { if c.Name == name { count++ value = c.Value } } return value, count == 1 && validHandle(value) } // setCookie writes a __Host- cookie: Secure, Path=/ and no Domain, as the // prefix requires. Lax, so the top-level GET to /auth/finish carries it. func setCookie(w http.ResponseWriter, name, value string, seconds int) { http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) } // start begins a sign-in for this browser and sends it to Base. func (h *handoff) start(w http.ResponseWriter, r *http.Request) { if !h.guard(w, r) { return } q, err := url.ParseQuery(r.URL.RawQuery) if err != nil || len(q) > 1 { h.fail(w, errRefused) return } to := "/" if len(q) == 1 { v, ok := q["return_to"] if !ok || len(v) != 1 { h.fail(w, errRefused) return } to = v[0] } if !safePath(to) { h.fail(w, errRefused) return } previous, _ := cookie(r, pendingCookie) secret, nonce, err := h.beginPending(r.Context(), to, previous, h.cfg.now()) if err != nil { h.fail(w, err) return } setCookie(w, pendingCookie, secret, int(pendingLifetime)) target := h.cfg.Issuer + "/authorize?" + url.Values{"consumer": {h.cfg.ConsumerID}, "nonce": {nonce}}.Encode() http.Redirect(w, r, target, http.StatusSeeOther) } // assertion receives Base's form post. It needs no cookie and must not rely // on one: the post comes from Base's page. func (h *handoff) assertion(w http.ResponseWriter, r *http.Request) { if !h.guard(w, r) { return } // Exactly Base's origin. A missing Origin or "null" is refused. if o := r.Header.Values("Origin"); len(o) != 1 || o[0] != h.cfg.Issuer { http.Error(w, "Unable to sign in. Start again.", http.StatusForbidden) return } if r.URL.RawQuery != "" { h.fail(w, errRefused) return } if media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || media != "application/x-www-form-urlencoded" { h.fail(w, errRefused) return } // A token is at most 8192 bytes; form encoding leaves it as is (it is // base64url and one dot), so 12 KiB bounds the body before any parsing. body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024)) if err != nil { h.fail(w, errRefused) return } form, err := url.ParseQuery(string(body)) if err != nil || len(form) != 1 || len(form["assertion"]) != 1 { h.fail(w, errRefused) return } handle, err := h.receive(r.Context(), form["assertion"][0], h.cfg.now()) if err != nil { h.fail(w, err) return } setCookie(w, inboxCookie, handle, int(inboxLifetime)) // Same origin, relative: Base's CSP lets its form post only here, and a // redirect anywhere else would be refused. http.Redirect(w, r, FinishPath, http.StatusSeeOther) } // finish binds the held assertion to this browser's pending request and, once // its use is recorded, starts the session. func (h *handoff) finish(w http.ResponseWriter, r *http.Request) { if !h.guard(w, r) { return } secret, okSecret := cookie(r, pendingCookie) handle, okHandle := cookie(r, inboxCookie) // Both are single-use whatever happens next. setCookie(w, pendingCookie, "", -1) setCookie(w, inboxCookie, "", -1) if r.URL.RawQuery != "" || !okSecret || !okHandle { h.fail(w, errRefused) return } // Read before the transaction: the writer pool has one connection. existing := "" if s, ok := sessions.Current(r); ok { existing = s.Subject } claims, to, err := h.consume(r.Context(), secret, handle, existing, h.cfg.now()) if err != nil { h.fail(w, err) return } s := sessions.Session{Subject: claims.Subject, Method: sessionMethod, AuthTime: time.Unix(claims.AuthTime, 0)} if err := h.sess.SignIn(w, r, s); err != nil { h.fail(w, storage("start session", err)) return } h.logger.Info("signed in through Base", "subject", claims.Subject, "jti", claims.ID) http.Redirect(w, r, to, http.StatusSeeOther) } // signOut ends this browser's session here. Signing in again starts a fresh // handoff, so whoever Base vouches for then is who the app sees. func (h *handoff) signOut(w http.ResponseWriter, r *http.Request) { if !h.guard(w, r) { return } h.sess.SignOut(w, r) // Not straight to "/": signed out, that redirects on to Base, and the // app's CSP form-action 'self' covers this form's whole redirect chain, // so the browser would refuse the hop and leave the old page showing. // The signed-out page's links are plain navigations. http.Redirect(w, r, SignedOutPath, http.StatusSeeOther) } // signedOut says the person has left this app, and offers the way back in. func (h *handoff) signedOut(w http.ResponseWriter, r *http.Request) { if !h.guard(w, r) { return } if err := h.pages.Page(w, "signedout", struct{ Home string }{h.cfg.Issuer + "/"}); err != nil { h.logger.Error("consumer: render signed-out page", "err", err) http.Error(w, "something went wrong", http.StatusInternalServerError) } } func digest(s string) string { sum := sha256.Sum256([]byte(s)); return hex.EncodeToString(sum[:]) } func jtiHash(c assertion.Claims) string { return digest(c.Issuer + "\x00" + c.ID) } func randomHandle() (string, error) { var b [32]byte if _, err := rand.Read(b[:]); err != nil { return "", storage("random handle", err) } return base64.RawURLEncoding.EncodeToString(b[:]), nil } func validHandle(s string) bool { if len(s) != 43 { return false } b, err := base64.RawURLEncoding.Strict().DecodeString(s) return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == s } // safePath accepts only a local path on this origin, outside the sign-in // routes: one leading slash, no scheme or host, no backslash, control // character, space, fragment or dot segment. func safePath(s string) bool { if len(s) == 0 || len(s) > 2048 || !utf8.ValidString(s) || !strings.HasPrefix(s, "/") || strings.HasPrefix(s, "//") || strings.Contains(s, "#") { return false } for _, b := range []byte(s) { if b <= ' ' || b == 127 || b == '\\' { return false } } u, err := url.ParseRequestURI(s) if err != nil || u.IsAbs() || u.Host != "" || u.Opaque != "" { return false } p := u.Path if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") || strings.ContainsAny(p, "\\\x00\r\n\t") { return false } for _, part := range strings.Split(p, "/") { if part == "." || part == ".." { return false } } return p != "/auth" && !strings.HasPrefix(p, "/auth/") } // begin opens a transaction, moves the clock fence forward, and prunes what // has expired. It refuses a clock more than clockTolerance behind the fence. func (h *handoff) begin(ctx context.Context, now time.Time) (*sql.Tx, int64, error) { n := now.Unix() if n <= 0 || n > math.MaxInt64-pendingLifetime { return nil, 0, errClock } tx, err := h.db.BeginTx(ctx, nil) if err != nil { return nil, 0, storage("begin transaction", err) } res, err := tx.ExecContext(ctx, `UPDATE base_consumer_clock SET observed = MAX(observed, ?) WHERE id = 1 AND observed <= ?`, n, n+clockTolerance) if err != nil { tx.Rollback() return nil, 0, storage("advance clock", err) } if rows, err := res.RowsAffected(); err != nil || rows != 1 { tx.Rollback() return nil, 0, errClock } var fence int64 if err := tx.QueryRowContext(ctx, `SELECT observed FROM base_consumer_clock WHERE id = 1`).Scan(&fence); err != nil { tx.Rollback() return nil, 0, storage("read clock", err) } for _, q := range []struct { sql string at int64 }{ {`DELETE FROM base_consumer_pending WHERE expires_at <= ?`, n}, {`DELETE FROM base_consumer_inbox WHERE expires_at <= ?`, n}, {`DELETE FROM base_consumer_replay WHERE expires_at < ?`, fence - clockTolerance}, } { if _, err := tx.ExecContext(ctx, q.sql, q.at); err != nil { tx.Rollback() return nil, 0, storage("prune expired rows", err) } } return tx, n, nil } // beginPending records a new pending request, replacing this browser's // previous one. Only hashes of the secret and nonce are stored. func (h *handoff) beginPending(ctx context.Context, to, previous string, now time.Time) (secret, nonce string, err error) { if secret, err = randomHandle(); err != nil { return "", "", err } if nonce, err = assertion.RandomID(); err != nil { return "", "", storage("random nonce", err) } tx, n, err := h.begin(ctx, now) if err != nil { return "", "", err } defer tx.Rollback() if validHandle(previous) { if _, err := tx.ExecContext(ctx, `DELETE FROM base_consumer_pending WHERE secret_hash = ?`, digest(previous)); err != nil { return "", "", storage("delete previous pending", err) } } var count int if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM base_consumer_pending`).Scan(&count); err != nil { return "", "", storage("count pending", err) } if count >= rowLimit { // Evicting the oldest only loses someone's navigation, never a proof. if _, err := tx.ExecContext(ctx, `DELETE FROM base_consumer_pending WHERE secret_hash IN (SELECT secret_hash FROM base_consumer_pending ORDER BY created_at, secret_hash LIMIT ?)`, count-rowLimit+1); err != nil { return "", "", storage("evict pending", err) } } if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_pending (secret_hash, nonce_hash, return_to, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`, digest(secret), digest(nonce), to, n, n+pendingLifetime); err != nil { return "", "", storage("insert pending", err) } if err := tx.Commit(); err != nil { return "", "", storage("commit pending", err) } return secret, nonce, nil } // receive verifies token and holds it in the inbox under a new handle. An // assertion already used, or already waiting, is refused. func (h *handoff) receive(ctx context.Context, token string, now time.Time) (string, error) { claims, err := h.cfg.Verifier.Verify(token, now) if err != nil { h.logger.Info("consumer: assertion refused", "err", err) return "", errRefused } handle, err := randomHandle() if err != nil { return "", err } jti := jtiHash(claims) tx, n, err := h.begin(ctx, now) if err != nil { return "", err } defer tx.Rollback() var used int if err := tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM base_consumer_replay WHERE jti_hash = ?) + (SELECT COUNT(*) FROM base_consumer_inbox WHERE jti_hash = ?)`, jti, jti).Scan(&used); err != nil { return "", storage("check replay", err) } if used != 0 { h.logger.Warn("consumer: assertion replayed", "jti", claims.ID) return "", errRefused } var count int if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM base_consumer_inbox`).Scan(&count); err != nil { return "", storage("count inbox", err) } if count >= rowLimit { return "", errFull } expires := min(claims.ExpiresAt, n+inboxLifetime) if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_inbox (handle_hash, jti_hash, token, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`, digest(handle), jti, token, n, expires); err != nil { return "", storage("insert inbox", err) } if err := tx.Commit(); err != nil { return "", storage("commit inbox", err) } return handle, nil } // consume checks the held assertion against the pending request and, in one // transaction, records its ID, deletes both rows and stores the person's // display fields. existing is the subject of a live session already on this // browser; an assertion for anyone else is refused rather than swapped in. func (h *handoff) consume(ctx context.Context, secret, handle, existing string, now time.Time) (assertion.Claims, string, error) { var zero assertion.Claims tx, n, err := h.begin(ctx, now) if err != nil { return zero, "", err } defer tx.Rollback() secretHash, handleHash := digest(secret), digest(handle) var nonceHash, to, token string if err := tx.QueryRowContext(ctx, `SELECT nonce_hash, return_to FROM base_consumer_pending WHERE secret_hash = ? AND expires_at > ?`, secretHash, n).Scan(&nonceHash, &to); err != nil { return zero, "", readError(err) } if err := tx.QueryRowContext(ctx, `SELECT token FROM base_consumer_inbox WHERE handle_hash = ? AND expires_at > ?`, handleHash, n).Scan(&token); err != nil { return zero, "", readError(err) } claims, err := h.cfg.Verifier.Verify(token, now) if err != nil { return zero, "", errRefused } if subtle.ConstantTimeCompare([]byte(nonceHash), []byte(digest(claims.Nonce))) != 1 { h.logger.Warn("consumer: assertion for another pending request", "jti", claims.ID) return zero, "", errRefused } if existing != "" && existing != claims.Subject { return zero, "", errRefused } if !safePath(to) { return zero, "", errRefused } res, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_replay (jti_hash, expires_at) VALUES (?, ?) ON CONFLICT DO NOTHING`, jtiHash(claims), claims.ExpiresAt) if err != nil { return zero, "", storage("record replay", err) } if rows, err := res.RowsAffected(); err != nil { return zero, "", storage("record replay", err) } else if rows != 1 { return zero, "", errRefused } for _, q := range []struct{ sql, key string }{ {`DELETE FROM base_consumer_pending WHERE secret_hash = ?`, secretHash}, {`DELETE FROM base_consumer_inbox WHERE handle_hash = ?`, handleHash}, } { res, err := tx.ExecContext(ctx, q.sql, q.key) if err != nil { return zero, "", storage("delete consumed row", err) } if rows, err := res.RowsAffected(); err != nil { return zero, "", storage("delete consumed row", err) } else if rows != 1 { return zero, "", fmt.Errorf("%w: delete consumed row: %d rows affected", errStorage, rows) } } // Display only: Ext grants nothing, and a malformed one shows blanks. var ext struct { Name string `json:"name"` Email string `json:"email"` Base string `json:"base"` } _ = json.Unmarshal(claims.Ext, &ext) if _, err := tx.ExecContext(ctx, `INSERT INTO base_consumer_people (subject, name, email, base, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (subject) DO UPDATE SET name = excluded.name, email = excluded.email, base = excluded.base, updated_at = excluded.updated_at`, claims.Subject, ext.Name, ext.Email, ext.Base, n); err != nil { return zero, "", storage("store person", err) } if err := tx.Commit(); err != nil { return zero, "", storage("commit finish", err) } return claims, to, nil } // storage classifies a database or randomness failure, keeping the // operation and the cause for the log. Callers match it with errors.Is. func storage(op string, err error) error { return fmt.Errorf("%w: %s: %w", errStorage, op, err) } func readError(err error) error { if errors.Is(err, sql.ErrNoRows) { return errRefused } return storage("read exchange", err) }