Skip to content
pi-c Documentation
Login

Documentation

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <time.h>
#include <unistd.h>

#include "bearssl.h"
#include "cred.h"
#include "platform.h"
#include "userdb.h"

/* PBKDF2-HMAC-SHA256 for a passphrase: OWASP's 2023 floor for this KDF.
 * Nothing memory-hard is vendored; the count is stored per store, so it can
 * rise later without breaking an old one. */
#define KDF_NAME "pbkdf2-sha256"
#define KDF_ITERATIONS 600000u
#define SALT_BYTES 16
#define VERIFIER_TEXT "pic credential store"
/* AADs: the verifier's and a provider key's live in separate namespaces
 * (a provider is bound as "key:NAME"), so no provider name can make one
 * pass for the other. */
#define VERIFIER_AAD "verifier:picu_credential_key"
#define KEY_AAD "key:"
#define SECRET_CAP 512

static unsigned char master[PIC_CRED_KEY];
static int unlocked;
static unsigned char handed[PIC_CRED_KEY]; /* a key a parent handed over, not yet checked */
static int have_handed;
static int wipe_registered;

void pic_cred_wipe(void *p, size_t n) {
    volatile unsigned char *v = p;
    while (n--) {
        *v++ = 0;
    }
}

static void wipe_all(void) {
    pic_cred_wipe(master, sizeof master);
    pic_cred_wipe(handed, sizeof handed);
    unlocked = have_handed = 0;
}

void pic_cred_lock(void) { wipe_all(); }

/* Host only: once a master key or a plaintext key is in memory, no core
 * dump may carry it. */
static void no_core(void) {
    struct rlimit rl = {0, 0};
    (void)setrlimit(RLIMIT_CORE, &rl);
}

/* The AAD a provider's key is sealed under. */
static void key_aad(const char *provider, char *out, size_t cap) { (void)snprintf(out, cap, KEY_AAD "%s", provider); }

static void remember(const unsigned char key[PIC_CRED_KEY]) {
    no_core();
    memcpy(master, key, PIC_CRED_KEY);
    unlocked = 1;
    if (!wipe_registered) {
        wipe_registered = 1;
        (void)atexit(wipe_all);
    }
}

/* ---- primitives ---------------------------------------------------------- */

/* The one source of nonces and salts: the platform's entropy (the OS RNG on
 * a host), at most 256 bytes a call. */
static int random_bytes(void *buf, size_t n) { return pic_platform_get()->entropy(buf, n); }

int pic_cred_seal(const unsigned char key[PIC_CRED_KEY], const char *aad, const void *pt, size_t n, unsigned char *out) {
    unsigned char *nonce = out, *body = out + PIC_CRED_NONCE, *tag = out + PIC_CRED_NONCE + n;
    if (random_bytes(nonce, PIC_CRED_NONCE) != 0) {
        return -1;
    }
    memcpy(body, pt, n);
    br_poly1305_ctmul_run(key, nonce, body, n, aad, strlen(aad), tag, br_chacha20_ct_run, 1);
    return 0;
}

int pic_cred_open(const unsigned char key[PIC_CRED_KEY], const char *aad, const unsigned char *in, size_t n, void *pt) {
    unsigned char tag[PIC_CRED_TAG], diff = 0;
    size_t len;
    if (n < PIC_CRED_OVERHEAD) {
        return -1;
    }
    len = n - PIC_CRED_OVERHEAD;
    memcpy(pt, in + PIC_CRED_NONCE, len);
    br_poly1305_ctmul_run(key, in, pt, len, aad, strlen(aad), tag, br_chacha20_ct_run, 0);
    for (size_t i = 0; i < PIC_CRED_TAG; i++) {
        diff |= (unsigned char)(tag[i] ^ in[PIC_CRED_NONCE + len + i]);
    }
    if (diff != 0) {
        pic_cred_wipe(pt, len);
        return -1;
    }
    return 0;
}

void pic_cred_kdf(const void *pass, size_t n, const unsigned char *salt, size_t saltn, uint32_t iterations,
                  unsigned char out[PIC_CRED_KEY]) {
    br_hmac_key_context kc;
    br_hmac_context hc;
    unsigned char u[PIC_CRED_KEY], one[4] = {0, 0, 0, 1};
    br_hmac_key_init(&kc, &br_sha256_vtable, pass, n);
    br_hmac_init(&hc, &kc, 0);
    br_hmac_update(&hc, salt, saltn);
    br_hmac_update(&hc, one, 4);
    br_hmac_out(&hc, u);
    memcpy(out, u, PIC_CRED_KEY);
    for (uint32_t i = 1; i < iterations; i++) {
        br_hmac_init(&hc, &kc, 0);
        br_hmac_update(&hc, u, sizeof u);
        br_hmac_out(&hc, u);
        for (size_t k = 0; k < PIC_CRED_KEY; k++) {
            out[k] ^= u[k];
        }
    }
    pic_cred_wipe(u, sizeof u);
    pic_cred_wipe(&kc, sizeof kc);
    pic_cred_wipe(&hc, sizeof hc);
}

/* ---- the master key ------------------------------------------------------ */

static long long cred_now_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }

/* Where the passphrase comes from when no one types it: --passphrase-fd, or
 * a command (PIC_PASSPHRASE_COMMAND, else the setting passphraseCommand). */
static int pass_fd = -1;
static char pass_cmd[1024];
static char store_source[32]; /* the unlocked store's key source */
static int typed;              /* this process unlocked it with a passphrase typed at a prompt */
static int offered;
static void (*offer_fn)(void);

void pic_cred_passphrase_fd(int fd) { pass_fd = fd; }

static const char *pass_command(void) {
    const char *env = getenv("PIC_PASSPHRASE_COMMAND");
    char *set;
    if (env && *env) {
        return env;
    }
    if ((set = pic_setting("passphraseCommand")) && *set) {
        (void)snprintf(pass_cmd, sizeof pass_cmd, "%s", set);
        free(set);
        return pass_cmd;
    }
    free(set);
    return NULL;
}

/* The secret from the platform's SOURCE, as a 32-byte key: stretched when it
 * is a passphrase. *HOW (may be NULL) says how it came. 0, or -1 with err. */
static int source_key(const char *source, int fresh, const unsigned char *salt, size_t saltn, uint32_t iterations,
                      unsigned char key[PIC_CRED_KEY], int *how, char *err, size_t errcap) {
    const pic_platform *p = pic_platform_get();
    unsigned char secret[SECRET_CAP];
    char id[1024] = "";
    pic_secret_ask ask;
    size_t len = 0;
    int got = PIC_SECRET_PASSPHRASE, rc = -1;
    char why[200] = "";
    if (!p->secret_key) {
        (void)snprintf(err, errcap, "this build has no source for the credential store's key");
        return -1;
    }
    (void)pic_userdb_path(id, sizeof id);
    ask.source = source;
    ask.id = id;
    ask.fresh = fresh;
    ask.fd = pass_fd;
    ask.command = strcmp(source, "passphrase") == 0 && pass_fd < 0 ? pass_command() : NULL;
    if (p->secret_key(&ask, secret, sizeof secret, &len, &got, why, sizeof why) != 0) {
        (void)snprintf(err, errcap, "cannot unlock the credential store: %s", why[0] ? why : "no key");
    } else if (got != PIC_SECRET_KEY) {
        pic_cred_kdf(secret, len, salt, saltn, iterations, key);
        rc = 0;
    } else if (len == PIC_CRED_KEY) {
        memcpy(key, secret, PIC_CRED_KEY);
        rc = 0;
    } else {
        (void)snprintf(err, errcap, "the credential store's key source gave a key of the wrong size");
    }
    if (how) {
        *how = got;
    }
    pic_cred_wipe(secret, sizeof secret);
    return rc;
}

/* A new master key for the source WANT (NULL: the platform's choice for a
 * new store, or a passphrase when one is given without a terminal): the key,
 * the source's name, and the salt and iterations a passphrase is stretched
 * with (iterations 0: a raw key, no salt). kept: the platform keeps it, and
 * must drop it if the store does not take it. 0; 1 when QUIET and it would
 * take a typed passphrase; -1 with err. */
typedef struct {
    unsigned char key[PIC_CRED_KEY], salt[SALT_BYTES];
    char source[32];
    uint32_t iterations;
    int kept, how;
} new_master;

static int make_key(const char *want, int quiet, new_master *nm, char *err, size_t errcap) {
    const pic_platform *p = pic_platform_get();
    char id[1024] = "";
    int r = 1;
    memset(nm, 0, sizeof *nm);
    nm->how = PIC_SECRET_KEY;
    (void)pic_userdb_path(id, sizeof id);
    if ((want && strcmp(want, "passphrase") == 0) || (!want && (pass_fd >= 0 || pass_command()))) {
        (void)snprintf(nm->source, sizeof nm->source, "passphrase");
    } else if (!p->secret_keep) {
        (void)snprintf(nm->source, sizeof nm->source, "passphrase");
    } else {
        if (random_bytes(nm->key, sizeof nm->key) != 0) {
            (void)snprintf(err, errcap, "no entropy for the credential store's key");
            return -1;
        }
        r = p->secret_keep(want, id, nm->key, sizeof nm->key, nm->source, sizeof nm->source, err, errcap);
        if (r < 0) {
            pic_cred_wipe(nm, sizeof *nm);
            return -1;
        }
        nm->kept = r == 0;
    }
    if (r == 1) { /* fetched from the source the platform named */
        int pass = strcmp(nm->source, "passphrase") == 0;
        if (pass && quiet && pass_fd < 0 && !pass_command()) {
            return 1;
        }
        if (pass && random_bytes(nm->salt, sizeof nm->salt) != 0) {
            (void)snprintf(err, errcap, "no entropy for the credential store's salt");
            return -1;
        }
        nm->iterations = pass ? KDF_ITERATIONS : 0;
        if (source_key(nm->source, 1, nm->salt, sizeof nm->salt, nm->iterations, nm->key, &nm->how, err, errcap) != 0) {
            pic_cred_wipe(nm, sizeof *nm);
            return -1;
        }
    }
    return 0;
}

static void drop_key(const char *source) {
    const pic_platform *p = pic_platform_get();
    char id[1024] = "";
    if (p->secret_drop && strcmp(source, "passphrase") != 0 && pic_userdb_path(id, sizeof id) == 0) {
        p->secret_drop(source, id);
    }
}

/* Writes NM's record into picu_credential_key (INSERT: the store's first). 0, or -1 with err. */
static int write_record(sqlite3 *db, const new_master *nm, int insert, char *err, size_t errcap) {
    unsigned char verifier[sizeof VERIFIER_TEXT - 1 + PIC_CRED_OVERHEAD];
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (pic_cred_seal(nm->key, VERIFIER_AAD, VERIFIER_TEXT, sizeof VERIFIER_TEXT - 1, verifier) != 0) {
        (void)snprintf(err, errcap, "no entropy for a nonce");
        return -1;
    }
    if (sqlite3_prepare_v2(db,
                           insert ? "INSERT INTO picu_credential_key(id, source, kdf, iterations, salt, verifier, created_ms)"
                                    " VALUES(1, ?6, ?1, ?2, ?3, ?4, ?5)"
                                  : "UPDATE picu_credential_key SET source = ?6, kdf = ?1, iterations = ?2, salt = ?3,"
                                    " verifier = ?4 WHERE id = 1",
                           -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        return -1;
    }
    sqlite3_bind_text(q, 1, nm->iterations ? KDF_NAME : "none", -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 2, nm->iterations);
    sqlite3_bind_blob(q, 3, nm->salt, nm->iterations ? (int)sizeof nm->salt : 0, SQLITE_STATIC);
    sqlite3_bind_blob(q, 4, verifier, sizeof verifier, SQLITE_STATIC);
    sqlite3_bind_int64(q, 5, cred_now_ms());
    sqlite3_bind_text(q, 6, nm->source, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_DONE && sqlite3_changes(db) == 1) {
        rc = 0;
    } else {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
    }
    sqlite3_finalize(q);
    return rc;
}

/* Whether the store has its record: 1, 0, or -1. */
static int has_record(sqlite3 *db) {
    sqlite3_stmt *q = NULL;
    int rc = -1, step;
    if (sqlite3_prepare_v2(db, "SELECT 1 FROM picu_credential_key WHERE id = 1", -1, &q, NULL) == SQLITE_OK) {
        step = sqlite3_step(q);
        rc = step == SQLITE_ROW ? 1 : step == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    return rc;
}

/* Makes the store's master key in WANT (NULL: the platform's choice) and
 * records it. A key kept outside the database is made under the database's
 * write lock, so two processes making a store at once cannot keep one key
 * and record another; a chosen passphrase is asked outside it. 0; 1 when
 * QUIET and it would take a typed passphrase; 2 when another process made
 * the store meanwhile; -1 with err. */
static int create(sqlite3 *db, const char *want, int quiet, char *err, size_t errcap) {
    new_master nm;
    int r, locked = !(want && strcmp(want, "passphrase") == 0);
    if (locked && sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        return -1;
    }
    r = locked ? has_record(db) : 0;
    if (r != 0) {
        (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        if (r < 0) {
            (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        }
        return r > 0 ? 2 : -1;
    }
    r = make_key(want, quiet, &nm, err, errcap);
    if (r != 0) {
        if (locked) {
            (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        }
        return r;
    }
    if (write_record(db, &nm, 1, err, errcap) != 0 ||
        (locked && sqlite3_exec(db, "COMMIT", NULL, NULL, NULL) != SQLITE_OK)) {
        if (!err[0]) {
            (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        }
        if (locked) {
            (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        }
        if (nm.kept) {
            drop_key(nm.source);
        }
        pic_cred_wipe(&nm, sizeof nm);
        return -1;
    }
    remember(nm.key);
    (void)snprintf(store_source, sizeof store_source, "%s", nm.source);
    typed = 0; /* a passphrase just chosen is not one to offer to stop asking for */
    pic_cred_wipe(&nm, sizeof nm);
    return 0;
}

void pic_cred_offer_register(void (*fn)(void)) { offer_fn = fn; }

int pic_cred_offer_due(void) {
    char *v;
    int due;
    if (!unlocked || !typed || offered || strcmp(store_source, "passphrase") != 0) {
        return 0;
    }
    v = pic_setting("cred.offer");
    due = !(v && strcmp(v, "declined") == 0);
    free(v);
    return due;
}

void pic_cred_offer_answer(int yes) {
    offered = 1;
    if (!yes) {
        (void)pic_setting_set("cred.offer", "declined");
    }
}

const char *pic_cred_source_name(void) { return unlocked ? store_source : ""; }

/* Unlocks the store: 0; 1 when it has no master key yet (CREATE 0); -1 with
 * err. */
static int unlock(int create_if_new, char *err, size_t errcap) {
    sqlite3 *db = pic_userdb(err, errcap);
    sqlite3_stmt *q = NULL;
    unsigned char key[PIC_CRED_KEY], check[sizeof VERIFIER_TEXT - 1];
    int rc = -1, step;
    if (unlocked) {
        return 0;
    }
    if (!db) {
        return -1;
    }
    if (sqlite3_prepare_v2(db, "SELECT kdf, iterations, salt, verifier, source FROM picu_credential_key WHERE id = 1", -1,
                           &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        return -1;
    }
    step = sqlite3_step(q);
    if (step == SQLITE_DONE) {
        sqlite3_finalize(q);
        if (create_if_new) {
            int r = create(db, NULL, 0, err, errcap);
            return r == 2 ? unlock(0, err, errcap) : r; /* another pic made it first: open that one */
        }
        (void)snprintf(err, errcap, "the credential store has no master key record (picu_credential_key)");
        return 1;
    }
    if (step != SQLITE_ROW) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
    } else {
        const char *kdf = (const char *)sqlite3_column_text(q, 0), *source = (const char *)sqlite3_column_text(q, 4);
        long long iterations = sqlite3_column_int64(q, 1);
        int pass = source && strcmp(source, "passphrase") == 0;
        if (!kdf || !source || strlen(source) >= sizeof store_source ||
            (pass ? strcmp(kdf, KDF_NAME) != 0 || iterations < 1 || iterations > 100000000
                  : strcmp(kdf, "none") != 0 || iterations != 0)) {
            (void)snprintf(err, errcap, "the credential store uses a key derivation this pic does not know");
        } else if ((size_t)sqlite3_column_bytes(q, 3) != sizeof check + PIC_CRED_OVERHEAD) {
            (void)snprintf(err, errcap, "the credential store's verifier is damaged");
        } else {
            const unsigned char *salt = sqlite3_column_blob(q, 2), *verifier = sqlite3_column_blob(q, 3);
            int got, how = PIC_SECRET_KEY, from_parent = have_handed;
            if (have_handed) {
                memcpy(key, handed, sizeof key);
                pic_cred_wipe(handed, sizeof handed);
                have_handed = 0;
                got = 0;
            } else {
                got = source_key(source, 0, salt, (size_t)sqlite3_column_bytes(q, 2), (uint32_t)iterations, key, &how, err,
                                 errcap);
            }
            if (got == 0) {
                if (pic_cred_open(key, VERIFIER_AAD, verifier, sizeof check + PIC_CRED_OVERHEAD, check) == 0) {
                    remember(key);
                    (void)snprintf(store_source, sizeof store_source, "%s", source);
                    typed = how == PIC_SECRET_TYPED;
                    rc = 0;
                } else if (from_parent) {
                    (void)snprintf(err, errcap, "the key handed over by the parent pic does not open the credential store");
                } else if (pass) {
                    (void)snprintf(err, errcap, "wrong passphrase for the credential store");
                } else {
                    (void)snprintf(err, errcap, "the key in the %s source does not open the credential store", source);
                }
            }
        }
    }
    sqlite3_finalize(q);
    pic_cred_wipe(key, sizeof key);
    pic_cred_wipe(check, sizeof check);
    if (rc == 0 && offer_fn && pic_cred_offer_due()) {
        offered = 1;
        offer_fn();
    }
    return rc;
}

/* The store's recorded key source into out ("" when it has none): 0, or -1. */
static int recorded_source(char *out, size_t cap) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    out[0] = '\0';
    if (db && sqlite3_prepare_v2(db, "SELECT source FROM picu_credential_key WHERE id = 1", -1, &q, NULL) == SQLITE_OK) {
        int step = sqlite3_step(q);
        if (step == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            (void)snprintf(out, cap, "%s", (const char *)sqlite3_column_text(q, 0));
        }
        rc = step == SQLITE_ROW || step == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    return rc;
}

int pic_cred_quiet(char *err, size_t errcap) {
    char source[32];
    if (unlocked) {
        return 0;
    }
    if (pass_fd >= 0 || pass_command()) { /* a passphrase that needs no one to type it */
        return pic_cred_prepare(err, errcap);
    }
    if (recorded_source(source, sizeof source) != 0) {
        (void)snprintf(err, errcap, "the credential store cannot be read");
        return -1;
    }
    if (!source[0]) { /* new: the platform's choice, unless that is a passphrase */
        sqlite3 *db = pic_userdb(err, errcap);
        int r = db ? create(db, NULL, 1, err, errcap) : -1;
        return r == 2 ? pic_cred_quiet(err, errcap) : r; /* another pic made it first */
    }
    if (strcmp(source, "passphrase") == 0 && !have_handed) {
        return 1;
    }
    return unlock(0, err, errcap) == 0 ? 0 : -1;
}

/* ---- moving the key: pic auth rekey --------------------------------------- */

/* A sealed row to move: its table, the key column's value and the AAD it is bound to. */
typedef struct {
    int table;
    unsigned char *id;
    int idn;
    char aad[sizeof KEY_AAD + PIC_CRED_NAME_CAP + 64];
    unsigned char *sealed;
    int n;
} sealed_row;

static const struct {
    const char *select, *update, *prefix;
    int hex; /* the AAD names the key column in hex (a blob id) */
} sealed_tables[] = {
    {"SELECT name, sealed FROM picu_credential", "UPDATE picu_credential SET sealed = ?2 WHERE name = ?1", KEY_AAD, 0},
    {"SELECT name, sealed FROM picu_remote_key", "UPDATE picu_remote_key SET sealed = ?2 WHERE name = ?1", "remote-key:", 0},
    {"SELECT id, sealed FROM picu_remote_device", "UPDATE picu_remote_device SET sealed = ?2 WHERE id = ?1", "remote-device:", 1},
};

static void rows_free(sealed_row *rows, size_t n) {
    for (size_t i = 0; i < n; i++) {
        free(rows[i].id);
        free(rows[i].sealed);
    }
    free(rows);
}

/* Every sealed row, read before any is rewritten. 0, or -1. */
static int rows_load(sqlite3 *db, sealed_row **out, size_t *count) {
    sealed_row *rows = NULL;
    size_t n = 0, cap = 0;
    for (int t = 0; t < (int)(sizeof sealed_tables / sizeof sealed_tables[0]); t++) {
        sqlite3_stmt *q = NULL;
        int step;
        if (sqlite3_prepare_v2(db, sealed_tables[t].select, -1, &q, NULL) != SQLITE_OK) {
            rows_free(rows, n);
            return -1;
        }
        while ((step = sqlite3_step(q)) == SQLITE_ROW) {
            sealed_row *r;
            int idn = sqlite3_column_bytes(q, 0), sn = sqlite3_column_bytes(q, 1);
            if (n == cap) {
                sealed_row *more = realloc(rows, (cap = cap ? cap * 2 : 16) * sizeof *rows);
                if (!more) {
                    break;
                }
                rows = more;
            }
            r = &rows[n];
            memset(r, 0, sizeof *r);
            r->table = t;
            r->idn = idn;
            r->n = sn;
            r->id = malloc((size_t)idn + 1);
            r->sealed = malloc(sn ? (size_t)sn : 1);
            if (!r->id || !r->sealed) {
                free(r->id);
                free(r->sealed);
                break;
            }
            n++;
            memcpy(r->id, sqlite3_column_blob(q, 0), (size_t)idn);
            r->id[idn] = '\0';
            memcpy(r->sealed, sqlite3_column_blob(q, 1), (size_t)sn);
            if (sealed_tables[t].hex) {
                int k = snprintf(r->aad, sizeof r->aad, "%s", sealed_tables[t].prefix);
                for (int i = 0; i < idn && k + 3 < (int)sizeof r->aad; i++) {
                    k += snprintf(r->aad + k, sizeof r->aad - (size_t)k, "%02x", r->id[i]);
                }
            } else {
                (void)snprintf(r->aad, sizeof r->aad, "%s%s", sealed_tables[t].prefix, (const char *)r->id);
            }
        }
        sqlite3_finalize(q);
        if (step != SQLITE_DONE) {
            rows_free(rows, n);
            return -1;
        }
    }
    *out = rows;
    *count = n;
    return 0;
}

/* Reseals every row from the master key to KEY. *SKIPPED counts rows that
 * did not open under the master key either (left as they are). 0, or -1. */
static int reseal(sqlite3 *db, const unsigned char key[PIC_CRED_KEY], int *skipped, char *err, size_t errcap) {
    sealed_row *rows = NULL;
    size_t n = 0;
    int rc = 0;
    if (rows_load(db, &rows, &n) != 0) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        return -1;
    }
    no_core();
    for (size_t i = 0; i < n && rc == 0; i++) {
        sealed_row *r = &rows[i];
        size_t len = r->n >= PIC_CRED_OVERHEAD ? (size_t)r->n - PIC_CRED_OVERHEAD : 0;
        unsigned char *plain = malloc(len ? len : 1), *box = malloc((size_t)r->n ? (size_t)r->n : 1);
        sqlite3_stmt *q = NULL;
        if (!plain || !box) {
            (void)snprintf(err, errcap, "out of memory");
            rc = -1;
        } else if (r->n < PIC_CRED_OVERHEAD || pic_cred_open(master, r->aad, r->sealed, (size_t)r->n, plain) != 0) {
            ++*skipped;
        } else if (pic_cred_seal(key, r->aad, plain, len, box) != 0) {
            (void)snprintf(err, errcap, "no entropy for a nonce");
            rc = -1;
        } else if (sqlite3_prepare_v2(db, sealed_tables[r->table].update, -1, &q, NULL) != SQLITE_OK) {
            (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
            rc = -1;
        } else {
            if (sealed_tables[r->table].hex) {
                sqlite3_bind_blob(q, 1, r->id, r->idn, SQLITE_STATIC);
            } else {
                sqlite3_bind_text(q, 1, (const char *)r->id, r->idn, SQLITE_STATIC);
            }
            sqlite3_bind_blob(q, 2, box, r->n, SQLITE_STATIC);
            if (sqlite3_step(q) != SQLITE_DONE) {
                (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
                rc = -1;
            }
        }
        sqlite3_finalize(q);
        if (plain) {
            pic_cred_wipe(plain, len);
        }
        free(plain);
        free(box);
    }
    rows_free(rows, n);
    return rc;
}

/* Inside the rekey's transaction: the record's verifier still opens under the
 * key this process holds (no other pic moved the key since it unlocked). 0, or -1 with err. */
static int still_ours(sqlite3 *db, char *err, size_t errcap) {
    sqlite3_stmt *q = NULL;
    unsigned char check[sizeof VERIFIER_TEXT - 1];
    int rc = -1;
    if (sqlite3_prepare_v2(db, "SELECT verifier FROM picu_credential_key WHERE id = 1", -1, &q, NULL) == SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW && (size_t)sqlite3_column_bytes(q, 0) == sizeof check + PIC_CRED_OVERHEAD &&
        pic_cred_open(master, VERIFIER_AAD, sqlite3_column_blob(q, 0), sizeof check + PIC_CRED_OVERHEAD, check) == 0) {
        rc = 0;
    } else {
        (void)snprintf(err, errcap, "another pic moved the credential store's key just now: run this again");
    }
    sqlite3_finalize(q);
    pic_cred_wipe(check, sizeof check);
    return rc;
}

int pic_cred_rekey(const char *target, char *source, size_t scap, int *skipped, char *err, size_t errcap) {
    sqlite3 *db = pic_userdb(err, errcap);
    new_master nm;
    char old[sizeof store_source];
    int rc, made = 0, pass;
    *skipped = 0;
    if (!db) {
        return -1;
    }
    if (!unlocked) {
        rc = unlock(0, err, errcap);
        if (rc == 1) { /* a new store is made in the source asked for */
            char why[200] = "";
            int r = create(db, target ? target : "keychain", 0, target ? err : why, target ? errcap : sizeof why);
            if (r == -1 && !target) {
                r = create(db, "file", 0, err, errcap);
            }
            if (r == 2) {
                (void)snprintf(err, errcap, "another pic made the credential store just now: run this again");
            }
            if (r != 0) {
                return -1;
            }
            (void)snprintf(source, scap, "%s", store_source);
            return 0;
        }
        if (rc != 0) {
            return -1;
        }
    }
    if (target && strcmp(target, store_source) == 0 && strcmp(target, "passphrase") != 0) {
        (void)snprintf(source, scap, "%s", store_source);
        return 2;
    }
    /* A passphrase is asked before the write lock is taken; a key kept outside the database is
     * made under it, so two rekeys at once cannot leave the keychain holding the loser's key. */
    pass = target && strcmp(target, "passphrase") == 0;
    if (pass && make_key(target, 0, &nm, err, errcap) != 0) {
        return -1;
    }
    (void)snprintf(old, sizeof old, "%s", store_source);
    if (sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        if (pass) {
            pic_cred_wipe(&nm, sizeof nm);
        }
        return -1;
    }
    rc = still_ours(db, err, errcap);
    if (rc == 0 && !pass) {
        char why[200] = "";
        made = target ? make_key(target, 0, &nm, err, errcap) == 0
                      : make_key("keychain", 0, &nm, why, sizeof why) == 0 || make_key("file", 0, &nm, err, errcap) == 0;
        rc = made ? 0 : -1;
        if (!made) {
            (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
            return -1;
        }
    } else if (rc != 0) {
        (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        if (pass) {
            pic_cred_wipe(&nm, sizeof nm);
        }
        return -1;
    }
    if (reseal(db, nm.key, skipped, err, errcap) != 0 || write_record(db, &nm, 0, err, errcap) != 0 ||
        sqlite3_exec(db, "COMMIT", NULL, NULL, NULL) != SQLITE_OK) {
        if (!err[0]) {
            (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        }
        (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        rc = -1;
    }
    if (rc != 0) {
        if (nm.kept && strcmp(nm.source, old) != 0) {
            drop_key(nm.source);
        }
        pic_cred_wipe(&nm, sizeof nm);
        return -1;
    }
    remember(nm.key);
    (void)snprintf(store_source, sizeof store_source, "%s", nm.source);
    typed = 0;
    if (strcmp(old, nm.source) != 0) {
        drop_key(old);
    }
    (void)snprintf(source, scap, "%s", nm.source);
    pic_cred_wipe(&nm, sizeof nm);
    return 0;
}

int pic_cred_state(void) {
    sqlite3 *db;
    sqlite3_stmt *q = NULL;
    int has = 0;
    if (unlocked) {
        return PIC_CRED_OPEN;
    }
    if ((db = pic_userdb(NULL, 0)) &&
        sqlite3_prepare_v2(db, "SELECT 1 FROM picu_credential_key WHERE id = 1", -1, &q, NULL) == SQLITE_OK) {
        has = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return has ? PIC_CRED_LOCKED : PIC_CRED_NEW;
}

int pic_cred_prepare(char *err, size_t errcap) { return unlock(1, err, errcap); }

int pic_cred_unlock(char *err, size_t errcap) {
    int rc = unlock(0, err, errcap);
    if (rc == 1) {
        (void)snprintf(err, errcap, "no key is stored yet: run `pic login PROVIDER`");
        return -1;
    }
    return rc;
}

int pic_cred_box(const char *aad, const void *pt, size_t n, unsigned char *out, char *err, size_t errcap) {
    if (!unlocked) {
        (void)snprintf(err, errcap, "the credential store is locked");
        return -1;
    }
    if (pic_cred_seal(master, aad, pt, n, out) != 0) {
        (void)snprintf(err, errcap, "no entropy for a nonce");
        return -1;
    }
    return 0;
}

int pic_cred_unbox(const char *aad, const unsigned char *in, size_t n, void *pt, char *err, size_t errcap) {
    if (!unlocked) {
        (void)snprintf(err, errcap, "the credential store is locked");
        return -1;
    }
    if (n < PIC_CRED_OVERHEAD || pic_cred_open(master, aad, in, n, pt) != 0) {
        (void)snprintf(err, errcap, "a sealed row does not open under the store's key");
        return -1;
    }
    return 0;
}

/* ---- rows ---------------------------------------------------------------- */

/* VALUE is 1 to CAP - 1 bytes, each one that can go in a header. 0, or -1
 * with err (never the value). */
static int header_safe(const char *what, const char *key, size_t cap, char *err, size_t errcap) {
    size_t n = strlen(key);
    if (n == 0) {
        (void)snprintf(err, errcap, "%s is empty", what);
        return -1;
    }
    if (n >= cap) {
        (void)snprintf(err, errcap, "%s is longer than %zu bytes", what, cap - 1);
        return -1;
    }
    for (size_t i = 0; i < n; i++) {
        if ((unsigned char)key[i] < 0x21 || (unsigned char)key[i] > 0x7e) {
            (void)snprintf(err, errcap, "%s has a character that cannot go in a header", what);
            return -1;
        }
    }
    return 0;
}

int pic_cred_check(const char *what, const char *key, char *err, size_t errcap) {
    return header_safe(what, key, PIC_CRED_KEY_CAP, err, errcap);
}

/* The kind of PROVIDER's stored row ("api_key" or "oauth"), or NULL. */
static const char *stored_kind(const char *provider) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    const char *kind = NULL;
    if (db && sqlite3_prepare_v2(db, "SELECT kind FROM picu_credential WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            kind = strcmp((const char *)sqlite3_column_text(q, 0), "oauth") == 0 ? "oauth" : "api_key";
        }
    }
    sqlite3_finalize(q);
    return kind;
}

int pic_cred_stored(const char *provider) { return stored_kind(provider) != NULL; }

/* Seals N bytes of PLAIN for PROVIDER into its row as KIND: a new row
 * (FRESH: created now, never used), or the sealed value alone replaced (a
 * refresh keeps the row's dates). The store must be unlocked. 0, or -1. */
static int put_row(const char *provider, const char *kind, const char *plain, size_t n, int fresh, char *err,
                   size_t errcap) {
    sqlite3 *db = pic_userdb(err, errcap);
    sqlite3_stmt *q = NULL;
    char aad[sizeof KEY_AAD + PIC_CRED_NAME_CAP];
    unsigned char *box;
    int rc = -1;
    if (!db) {
        return -1;
    }
    if (!(box = malloc(n + PIC_CRED_OVERHEAD))) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    no_core();
    key_aad(provider, aad, sizeof aad);
    if (pic_cred_seal(master, aad, plain, n, box) != 0) {
        (void)snprintf(err, errcap, "no entropy for a nonce");
    } else if (sqlite3_prepare_v2(db,
                                  fresh ? "INSERT INTO picu_credential(name, kind, sealed, created_ms) VALUES(?1, ?4, ?2, ?3)"
                                          " ON CONFLICT(name) DO UPDATE SET kind = excluded.kind, sealed = excluded.sealed,"
                                          " created_ms = excluded.created_ms, used_ms = NULL"
                                        : "UPDATE picu_credential SET sealed = ?2, used_ms = ?3 WHERE name = ?1 AND kind = ?4",
                                  -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
    } else {
        sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC);
        sqlite3_bind_blob(q, 2, box, (int)(n + PIC_CRED_OVERHEAD), SQLITE_STATIC);
        sqlite3_bind_int64(q, 3, cred_now_ms());
        sqlite3_bind_text(q, 4, kind, -1, SQLITE_STATIC);
        if (sqlite3_step(q) != SQLITE_DONE) {
            (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        } else if (!fresh && sqlite3_changes(db) != 1) {
            (void)snprintf(err, errcap, "the sign-in for %s was removed while it was refreshed", provider);
        } else {
            rc = 0;
        }
    }
    sqlite3_finalize(q);
    free(box);
    return rc;
}

int pic_cred_login(const char *provider, const char *key, char *err, size_t errcap) {
    return pic_cred_login_as(provider, NULL, key, err, errcap);
}

/* The provider and label of row NAME ("p" or "p:label"). */
static void cred_row_parts(const char *name, char *provider, size_t pcap, char *label, size_t lcap) {
    const char *colon = strchr(name, ':');
    (void)snprintf(provider, pcap, "%.*s", colon ? (int)(colon - name) : (int)strlen(name), name);
    (void)snprintf(label, lcap, "%s", colon ? colon + 1 : "default");
}

static void cred_health_forget(const char *name) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (db && sqlite3_prepare_v2(db, "DELETE FROM picu_credential_health WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        (void)sqlite3_step(q);
    }
    sqlite3_finalize(q);
}

int pic_cred_logout(const char *provider) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (db && sqlite3_prepare_v2(db, "DELETE FROM picu_credential WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC);
        rc = sqlite3_step(q) == SQLITE_DONE ? sqlite3_changes(db) > 0 : -1;
    }
    sqlite3_finalize(q);
    if (rc == 1) { /* its health and, when it was the active one, the choice go with it */
        char prov[128], label[PIC_CRED_LABEL_CAP], setting[160], *v;
        cred_row_parts(provider, prov, sizeof prov, label, sizeof label);
        cred_health_forget(provider);
        (void)snprintf(setting, sizeof setting, "activeKey:%s", prov);
        if ((v = pic_setting(setting)) && strcmp(v, label) == 0) {
            (void)pic_setting_set(setting, NULL);
        }
        free(v);
    }
    return rc;
}

int pic_cred_each(int (*fn)(void *ctx, const char *name, const char *kind, long long created_ms, long long used_ms),
                  void *ctx) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!db || sqlite3_prepare_v2(db, "SELECT name, kind, created_ms, coalesce(used_ms, 0) FROM picu_credential"
                                      " ORDER BY created_ms, name",
                                  -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    while (sqlite3_step(q) == SQLITE_ROW &&
           !fn(ctx, (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1),
               sqlite3_column_int64(q, 2), sqlite3_column_int64(q, 3))) {
    }
    sqlite3_finalize(q);
    return 0;
}

/* PROVIDER's row, unlocked and opened: 0 with *kind and *plain (malloc'd,
 * NUL-terminated, *n bytes; the caller wipes and frees it); 1 when none is
 * stored; -1 with err. */
static int open_row(const char *provider, const char **kind, char **plain, size_t *n, char *err, size_t errcap) {
    sqlite3 *db;
    sqlite3_stmt *q = NULL;
    char aad[sizeof KEY_AAD + PIC_CRED_NAME_CAP];
    int rc = -1, locked;
    *plain = NULL;
    if (!(*kind = stored_kind(provider))) {
        return 1;
    }
    if ((locked = unlock(0, err, errcap)) != 0 || !(db = pic_userdb(err, errcap))) {
        if (locked == 1) { /* rows, but nothing to open them with */
            (void)snprintf(err, errcap,
                           "the credential store has a key for %s but no master key record (picu_credential_key), so it"
                           " cannot be opened: run `pic logout %s`, then `pic login %s`",
                           provider, provider, provider);
        }
        return -1;
    }
    if (sqlite3_prepare_v2(db, "SELECT sealed, kind FROM picu_credential WHERE name = ?1", -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        return -1;
    }
    sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC);
    if (sqlite3_step(q) != SQLITE_ROW) {
        rc = 1;
    } else {
        size_t len = (size_t)sqlite3_column_bytes(q, 0);
        *kind = strcmp((const char *)sqlite3_column_text(q, 1), "oauth") == 0 ? "oauth" : "api_key";
        if (len < PIC_CRED_OVERHEAD || len - PIC_CRED_OVERHEAD > PIC_CRED_OAUTH_CAP ||
            !(*plain = malloc(len - PIC_CRED_OVERHEAD + 1))) {
            (void)snprintf(err, errcap, "the stored key for %s is damaged: run `pic login %s` again", provider, provider);
        } else if ((key_aad(provider, aad, sizeof aad), no_core(),
                    pic_cred_open(master, aad, sqlite3_column_blob(q, 0), len, *plain)) != 0) {
            (void)snprintf(err, errcap, "the stored key for %s does not open: run `pic login %s` again", provider,
                           provider);
        } else {
            *n = len - PIC_CRED_OVERHEAD;
            (*plain)[*n] = '\0';
            rc = 0;
        }
        if (rc != 0) {
            free(*plain);
            *plain = NULL;
        }
    }
    sqlite3_finalize(q);
    return rc;
}

static void free_plain(char *plain, size_t n) {
    if (plain) {
        pic_cred_wipe(plain, n);
        free(plain);
    }
}

static void mark_used(const char *provider) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (db && sqlite3_prepare_v2(db, "UPDATE picu_credential SET used_ms = ?2 WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, cred_now_ms());
        (void)sqlite3_step(q);
    }
    sqlite3_finalize(q);
}

/* ---- subscription sign-in --------------------------------------------------- */

/* A token is refreshed when it expires within this long. */
#define OAUTH_MARGIN_MS 60000
/* How long a process waits for another's refresh to finish. */
#define REFRESH_WAIT_MS 60000

static const pic_cred_oauth_ops *oauth_ops;

void pic_cred_oauth_register(const pic_cred_oauth_ops *ops) { oauth_ops = ops; }

const char *pic_cred_oauth_origin(const char *provider) {
    return oauth_ops && oauth_ops->origin && provider ? oauth_ops->origin(provider) : NULL;
}

const char *pic_cred_oauth_label(const char *provider) {
    return oauth_ops && oauth_ops->label && provider ? oauth_ops->label(provider) : NULL;
}

/* A subscription credential's access token (into access) and expiry; the
 * refresh token must be there too. 0, or -1 when the JSON lacks them. */
static int oauth_fields(const char *json, char *access, size_t cap, long long *expires) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (db && sqlite3_prepare_v2(db,
                                 "SELECT json_extract(?1, '$.access'), json_extract(?1, '$.expires') WHERE json_valid(?1)"
                                 " AND json_type(?1, '$.access') = 'text' AND json_type(?1, '$.refresh') = 'text'"
                                 " AND json_type(?1, '$.expires') IN ('integer', 'real')",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && (size_t)sqlite3_column_bytes(q, 0) < cap) {
            memcpy(access, sqlite3_column_text(q, 0), (size_t)sqlite3_column_bytes(q, 0) + 1);
            *expires = sqlite3_column_int64(q, 1);
            rc = 0;
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* The lock one refresh holds (beside ~/.pic/pic.sqlite), waited for: a
 * handle, or -1 with err. */
static int refresh_lock(char *err, size_t errcap) {
    char path[4096];
    const pic_platform *p = pic_platform_get();
    uint64_t end = p->mono_ns() + (uint64_t)REFRESH_WAIT_MS * 1000000u;
    size_t n;
    if (pic_userdb_path(path, sizeof path) != 0 || (n = strlen(path)) < 7 || n + 16 > sizeof path) {
        (void)snprintf(err, errcap, "no home directory for ~/.pic");
        return -1;
    }
    (void)snprintf(path + n - strlen("pic.sqlite"), sizeof path - n, "credential.lock");
    for (;;) {
        int h = p->lock(path, 0);
        if (h >= 0) {
            return h;
        }
        if (h == -1 || p->mono_ns() >= end) {
            (void)snprintf(err, errcap, h == -1 ? "cannot open %s" : "another pic is still refreshing a sign-in (%s)", path);
            return -1;
        }
        {
            struct timespec ts = {0, 20 * 1000000L};
            (void)nanosleep(&ts, NULL);
        }
    }
}

/* PROVIDER's access token into buf, refreshed under the lock when the stored
 * one is STALE (or, STALE NULL, expires within the margin), unless another
 * process already replaced it. 0, or -1 with err. */
static int refresh_locked(const char *provider, const char *stale, char *buf, size_t cap, char *err, size_t errcap) {
    char *plain = NULL, *fresh = NULL, why[256] = "";
    const char *kind;
    size_t n = 0;
    long long expires = 0;
    int lock = refresh_lock(err, errcap), rc = -1, got;
    if (lock < 0) {
        return -1;
    }
    got = open_row(provider, &kind, &plain, &n, err, errcap);
    if (got == 1 || (got == 0 && strcmp(kind, "oauth") != 0)) {
        (void)snprintf(err, errcap, "no subscription sign-in is stored for %s: run `pic auth login %s`", provider, provider);
    } else if (got == 0 && oauth_fields(plain, buf, cap, &expires) != 0) {
        (void)snprintf(err, errcap, "the stored sign-in for %s is damaged: run `pic auth login %s`", provider, provider);
    } else if (got == 0 && (stale ? strcmp(buf, stale) != 0 : expires - cred_now_ms() > OAUTH_MARGIN_MS)) {
        rc = 0; /* another process refreshed it while this one waited */
    } else if (got == 0 && (!oauth_ops || !oauth_ops->refresh)) {
        (void)snprintf(err, errcap, "this pic cannot refresh the sign-in for %s", provider);
    } else if (got == 0 && oauth_ops->refresh(provider, plain, &fresh, why, sizeof why) != 0) {
        (void)snprintf(err, errcap, "the sign-in for %s could not be refreshed (%s): run `pic auth login %s`", provider, why,
                       provider);
    } else if (got == 0 && (strlen(fresh) > PIC_CRED_OAUTH_CAP || oauth_fields(fresh, buf, cap, &expires) != 0)) {
        (void)snprintf(err, errcap, "the refreshed sign-in for %s is not usable", provider);
    } else if (got == 0) {
        /* The provider may have rotated the refresh token already: losing this write loses the sign-in,
         * so a failed write (a busy database, say) is tried once more. */
        if ((rc = put_row(provider, "oauth", fresh, strlen(fresh), 0, err, errcap)) != 0) {
            struct timespec ts = {0, 200 * 1000000L};
            (void)nanosleep(&ts, NULL);
            rc = put_row(provider, "oauth", fresh, strlen(fresh), 0, err, errcap);
        }
    }
    if (rc == 0 && header_safe("the access token", buf, PIC_CRED_TOKEN_CAP, err, errcap) != 0) {
        rc = -1;
    }
    if (rc != 0) {
        pic_cred_wipe(buf, cap);
    }
    free_plain(plain, n);
    free_plain(fresh, fresh ? strlen(fresh) : 0);
    pic_platform_get()->unlock(lock);
    return rc;
}

int pic_cred_refresh(const char *provider, const char *stale, char *buf, size_t cap, char *err, size_t errcap) {
    int rc = refresh_locked(provider, stale, buf, cap, err, errcap);
    if (rc == 0) {
        mark_used(provider);
    }
    return rc;
}

int pic_cred_oauth_login(const char *provider, int flags, char *err, size_t errcap) {
    const char *kind = NULL;
    char *secret = NULL, access[PIC_CRED_TOKEN_CAP];
    long long expires;
    int rc = -1, lock;
    if (!pic_cred_oauth_label(provider) || !oauth_ops->login) {
        (void)snprintf(err, errcap, "%s has no subscription sign-in", provider ? provider : "this provider");
        return -1;
    }
    /* The passphrase first: a wrong one should not cost a sign-in. */
    if (unlock(1, err, errcap) != 0 || oauth_ops->login(provider, flags, &kind, &secret, err, errcap) != 0) {
        return -1;
    }
    if (strcmp(kind, "api_key") == 0) {
        rc = pic_cred_check("the key", secret, err, errcap) == 0 ? put_row(provider, "api_key", secret, strlen(secret), 1, err, errcap) : -1;
    } else if (strlen(secret) > PIC_CRED_OAUTH_CAP || oauth_fields(secret, access, sizeof access, &expires) != 0) {
        (void)snprintf(err, errcap, "the sign-in for %s returned no usable tokens", provider);
    } else if ((lock = refresh_lock(err, errcap)) >= 0) {
        rc = put_row(provider, "oauth", secret, strlen(secret), 1, err, errcap);
        pic_platform_get()->unlock(lock);
    }
    pic_cred_wipe(access, sizeof access);
    free_plain(secret, strlen(secret));
    return rc;
}

/* PROVIDER's stored credential as a key into buf: an API key as it is, a
 * sign-in's access token (refreshed first near its expiry). 0; 1 none
 * stored; -1 with err. */
static int stored_key(const char *provider, char *buf, size_t cap, char *err, size_t errcap) {
    char *plain = NULL;
    const char *kind;
    size_t n = 0;
    long long expires = 0;
    int rc = open_row(provider, &kind, &plain, &n, err, errcap);
    if (rc != 0) {
        return rc;
    }
    if (strcmp(kind, "oauth") == 0) {
        if (oauth_fields(plain, buf, cap, &expires) != 0) {
            (void)snprintf(err, errcap, "the stored sign-in for %s is damaged: run `pic auth login %s`", provider, provider);
            rc = -1;
        } else if (expires - cred_now_ms() <= OAUTH_MARGIN_MS) {
            rc = refresh_locked(provider, NULL, buf, cap, err, errcap);
        } else {
            rc = header_safe("the access token", buf, PIC_CRED_TOKEN_CAP, err, errcap) == 0 ? 0 : -1;
        }
    } else if (n >= cap) {
        (void)snprintf(err, errcap, "the stored key for %s is damaged: run `pic login %s` again", provider, provider);
        rc = -1;
    } else {
        memcpy(buf, plain, n + 1);
        rc = pic_cred_check("the stored key", buf, err, errcap) == 0 ? 0 : -1;
    }
    free_plain(plain, n);
    if (rc != 0) {
        pic_cred_wipe(buf, cap);
    } else {
        mark_used(provider);
    }
    return rc;
}

/* ---- named keys and which one a request uses ------------------------------ */

/* The labels chosen for this process only (--key, RPC's set_credential), per provider. */
#define CRED_OVERRIDES 16
static struct {
    char provider[PIC_CRED_PROVIDER_CAP], label[PIC_CRED_LABEL_CAP];
} cred_overrides[CRED_OVERRIDES];

int pic_cred_override(const char *provider, const char *label) {
    int free_slot = -1;
    if (!provider) {
        memset(cred_overrides, 0, sizeof cred_overrides);
        return 0;
    }
    for (int i = 0; i < CRED_OVERRIDES; i++) {
        if (strcmp(cred_overrides[i].provider, provider) == 0) {
            free_slot = i;
            break;
        }
        if (free_slot < 0 && !cred_overrides[i].provider[0]) {
            free_slot = i;
        }
    }
    if (strlen(provider) >= PIC_CRED_PROVIDER_CAP || (label && strlen(label) >= PIC_CRED_LABEL_CAP)) {
        return -1;
    }
    if (free_slot < 0) {
        return label ? -1 : 0; /* every slot is taken by other providers: nothing to set, nothing to clear */
    }
    if (!label) {
        cred_overrides[free_slot].provider[0] = cred_overrides[free_slot].label[0] = '\0';
    } else {
        (void)snprintf(cred_overrides[free_slot].provider, sizeof cred_overrides[free_slot].provider, "%s", provider);
        (void)snprintf(cred_overrides[free_slot].label, sizeof cred_overrides[free_slot].label, "%s", label);
    }
    return 0;
}

/* PROVIDER's label for this process, or NULL. */
static const char *cred_override_of(const char *provider) {
    for (int i = 0; i < CRED_OVERRIDES; i++) {
        if (cred_overrides[i].provider[0] && strcmp(cred_overrides[i].provider, provider) == 0) {
            return cred_overrides[i].label;
        }
    }
    return NULL;
}

int pic_cred_label_check(const char *label, char *err, size_t errcap) {
    size_t n = label ? strlen(label) : 0;
    int ok = n >= 1 && n <= 32 && strcmp(label, "env") != 0 && strcmp(label, "file") != 0;
    for (size_t i = 0; ok && i < n; i++) {
        char c = label[i];
        ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_';
    }
    if (!ok) {
        (void)snprintf(err, errcap, "a key's label is 1-32 of a-z, 0-9, - and _, and not env or file (got \"%.40s\")",
                       label ? label : "");
        return -1;
    }
    return 0;
}

/* The row of PROVIDER's key LABEL: PROVIDER itself for "default". */
static int cred_row_name(const char *provider, const char *label, char *out, size_t cap) {
    int n = !label || !*label || strcmp(label, "default") == 0 ? snprintf(out, cap, "%s", provider)
                                                              : snprintf(out, cap, "%s:%s", provider, label);
    if (n < 0 || (size_t)n >= cap) { /* never a truncated name: it would be another row */
        out[0] = '\0';
        return -1;
    }
    return 0;
}

int pic_cred_login_as(const char *provider, const char *label, const char *key, char *err, size_t errcap) {
    char name[PIC_CRED_NAME_CAP];
    if (!provider || !*provider || strchr(provider, ':')) {
        (void)snprintf(err, errcap, "no provider named, or a provider name with a ':'");
        return -1;
    }
    if (strlen(provider) >= PIC_CRED_PROVIDER_CAP) {
        (void)snprintf(err, errcap, "the provider name is too long (at most %d bytes)", PIC_CRED_PROVIDER_CAP - 1);
        return -1;
    }
    if (label && *label && strcmp(label, "default") != 0 && pic_cred_label_check(label, err, errcap) != 0) {
        return -1;
    }
    if (pic_cred_check("the key", key, err, errcap) != 0 || unlock(1, err, errcap) != 0) {
        return -1;
    }
    if (cred_row_name(provider, label, name, sizeof name) != 0) {
        (void)snprintf(err, errcap, "the key's name is too long");
        return -1;
    }
    return put_row(name, "api_key", key, strlen(key), 1, err, errcap);
}

/* This installation's salt for hashing a variable's value (picu_meta), made
 * on first use: 0 with 16 bytes in salt, or -1. */
static unsigned char cred_salt_bytes[16];
static int cred_salt_known;

/* The salt's hex in picu_meta into salt: 0, or -1 when it is missing or damaged. */
static int cred_salt_read(sqlite3 *db, unsigned char salt[16]) {
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (sqlite3_prepare_v2(db, "SELECT value FROM picu_meta WHERE key = 'credential_salt'", -1, &q, NULL) == SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW && sqlite3_column_bytes(q, 0) == 32) {
        const char *v = (const char *)sqlite3_column_text(q, 0);
        rc = 0;
        for (int i = 0; i < 16; i++) {
            unsigned int b;
            if (sscanf(v + 2 * i, "%2x", &b) != 1) {
                rc = -1;
                break;
            }
            salt[i] = (unsigned char)b;
        }
    }
    sqlite3_finalize(q);
    return rc;
}

static int cred_salt(unsigned char salt[16]) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    unsigned char fresh[16];
    char hex[33];
    if (cred_salt_known) {
        memcpy(salt, cred_salt_bytes, 16);
        return 0;
    }
    if (!db) {
        return -1;
    }
    if (cred_salt_read(db, salt) != 0) { /* the first time: made, unless another process just did */
        if (random_bytes(fresh, sizeof fresh) != 0) {
            return -1;
        }
        for (int i = 0; i < 16; i++) {
            (void)snprintf(hex + 2 * i, 3, "%02x", fresh[i]);
        }
        if (sqlite3_prepare_v2(db, "INSERT OR IGNORE INTO picu_meta(key, value) VALUES('credential_salt', ?1)", -1, &q,
                               NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, hex, -1, SQLITE_STATIC);
            (void)sqlite3_step(q);
        }
        sqlite3_finalize(q);
        if (cred_salt_read(db, salt) != 0) {
            return -1;
        }
    }
    memcpy(cred_salt_bytes, salt, 16);
    cred_salt_known = 1;
    return 0;
}

/* The name a value from outside the store is kept under: PREFIX:WHAT: and
 * twelve hex digits of HMAC-SHA256 over it under the install's salt, so a
 * changed value is a new name and the name says nothing of the value. */
static void cred_outside_name(const char *prefix, const char *what, const char *value, char *out, size_t cap) {
    unsigned char salt[16], mac[32];
    br_hmac_key_context kc;
    br_hmac_context hc;
    char hex[13];
    int n;
    out[0] = '\0';
    if (cred_salt(salt) != 0) { /* no salt, no name: no health is kept for it */
        return;
    }
    br_hmac_key_init(&kc, &br_sha256_vtable, salt, sizeof salt);
    br_hmac_init(&hc, &kc, 0);
    br_hmac_update(&hc, value, strlen(value));
    br_hmac_out(&hc, mac);
    for (int i = 0; i < 6; i++) {
        (void)snprintf(hex + 2 * i, 3, "%02x", mac[i]);
    }
    n = snprintf(out, cap, "%s:%s:%s", prefix, what, hex);
    if (n < 0 || (size_t)n >= cap) {
        out[0] = '\0';
    }
    pic_cred_wipe(&kc, sizeof kc);
    pic_cred_wipe(&hc, sizeof hc);
    pic_cred_wipe(mac, sizeof mac);
}

/* The oldest named row of PROVIDER, into name: 1, or 0 when it has none. */
static int cred_oldest_named(const char *provider, char *name, size_t cap) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int found = 0;
    if (db && sqlite3_prepare_v2(db, "SELECT name FROM picu_credential WHERE substr(name, 1, length(?1) + 1) = ?1 || ':'"
                                     " ORDER BY created_ms, name LIMIT 1",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            (void)snprintf(name, cap, "%s", (const char *)sqlite3_column_text(q, 0));
            found = 1;
        }
    }
    sqlite3_finalize(q);
    return found;
}

/* Which credential a request for PROVIDER uses, opening nothing. */
typedef struct {
    pic_cred_source source;
    char row[PIC_CRED_NAME_CAP];   /* a stored one's row */
    char label[PIC_CRED_LABEL_CAP];
    const char *value;             /* the literal's or the variable's value */
    char missing[200];             /* a chosen label PROVIDER does not have: why */
} cred_choice;

static void cred_choose(const char *provider, const char *env, const char *literal, cred_choice *c) {
    const char *v = env && *env ? getenv(env) : NULL, *kind;
    char setting[160], *chosen = NULL;
    const char *label = NULL;
    memset(c, 0, sizeof *c);
    v = v && *v ? v : NULL;
    if (!provider || !*provider) {
        provider = "";
    } else if (cred_override_of(provider)) {
        label = cred_override_of(provider);
    } else {
        (void)snprintf(setting, sizeof setting, "activeKey:%s", provider);
        label = chosen = pic_setting(setting);
    }
    if (label && *label) {
        (void)snprintf(c->label, sizeof c->label, "%s", label);
        if (strcmp(label, "env") == 0) {
            if (v) {
                c->source = PIC_CRED_ENV;
                c->value = v;
            } else {
                (void)snprintf(c->missing, sizeof c->missing, "the key \"env\" is chosen for %s but %s is not set", provider,
                               env && *env ? env : "its variable");
            }
        } else if (strcmp(label, "file") == 0) {
            if (literal && *literal) {
                c->source = PIC_CRED_LITERAL;
                c->value = literal;
            } else {
                (void)snprintf(c->missing, sizeof c->missing, "the key \"file\" is chosen for %s but the models file gives none",
                               provider);
            }
        } else {
            if (cred_row_name(provider, label, c->row, sizeof c->row) == 0 && (kind = stored_kind(c->row))) {
                c->source = strcmp(kind, "oauth") == 0 ? PIC_CRED_STORED_OAUTH : PIC_CRED_STORED_KEY;
            } else {
                (void)snprintf(c->missing, sizeof c->missing,
                               "%s has no key named \"%.40s\": pic auth status lists its keys", provider, label);
                c->row[0] = '\0';
            }
        }
        free(chosen);
        return;
    }
    free(chosen);
    if (*provider && (kind = stored_kind(provider))) {
        (void)snprintf(c->row, sizeof c->row, "%s", provider);
        (void)snprintf(c->label, sizeof c->label, "default");
        c->source = strcmp(kind, "oauth") == 0 ? PIC_CRED_STORED_OAUTH : PIC_CRED_STORED_KEY;
    } else if (*provider && cred_oldest_named(provider, c->row, sizeof c->row)) {
        (void)snprintf(c->label, sizeof c->label, "%s", strchr(c->row, ':') + 1);
        c->source = strcmp(stored_kind(c->row), "oauth") == 0 ? PIC_CRED_STORED_OAUTH : PIC_CRED_STORED_KEY;
    } else if (literal && *literal) {
        (void)snprintf(c->label, sizeof c->label, "file");
        c->source = PIC_CRED_LITERAL;
        c->value = literal;
    } else if (v) {
        (void)snprintf(c->label, sizeof c->label, "env");
        c->source = PIC_CRED_ENV;
        c->value = v;
    }
}

/* The health name of choice C. */
static void cred_choice_name(const cred_choice *c, const char *provider, const char *env, char *out, size_t cap) {
    if (c->source == PIC_CRED_ENV) {
        cred_outside_name("env", env, c->value, out, cap);
    } else if (c->source == PIC_CRED_LITERAL) {
        cred_outside_name("file", provider, c->value, out, cap);
    } else {
        (void)snprintf(out, cap, "%s", c->row);
    }
}

int pic_cred_active(const char *provider, const char *env, const char *literal, pic_cred_used *out) {
    cred_choice c;
    cred_choose(provider, env, literal, &c);
    memset(out, 0, sizeof *out);
    if (c.source == PIC_CRED_NONE) {
        return -1;
    }
    cred_choice_name(&c, provider, env, out->name, sizeof out->name);
    (void)snprintf(out->label, sizeof out->label, "%s", c.label);
    return 0;
}

pic_cred_source pic_cred_source_of(const char *provider, const char *env, const char *literal) {
    cred_choice c;
    cred_choose(provider, env, literal, &c);
    return c.source;
}

void pic_cred_describe(const char *provider, const char *env, const char *literal, char *out, size_t cap) {
    const char *v = env && *env ? getenv(env) : NULL;
    int env_set = v && *v, lit = literal && *literal;
    char also[160] = "";
    cred_choice c;
    cred_choose(provider, env, literal, &c);
    switch (c.source) {
    case PIC_CRED_STORED_OAUTH:
    case PIC_CRED_STORED_KEY:
        if (lit || env_set) {
            (void)snprintf(also, sizeof also, "; %s also set", env_set ? env : "the models file's apiKey");
        }
        (void)snprintf(out, cap, "%s%s%s (in use%s)", c.source == PIC_CRED_STORED_OAUTH ? "stored sign-in" : "stored key",
                       strcmp(c.label, "default") != 0 ? " " : "", strcmp(c.label, "default") != 0 ? c.label : "", also);
        break;
    case PIC_CRED_LITERAL:
        (void)snprintf(out, cap, "models.json apiKey (in use%s%s%s)", env_set ? "; " : "", env_set ? env : "",
                       env_set ? " also set" : "");
        break;
    case PIC_CRED_ENV:
        (void)snprintf(out, cap, "%s (in use)", env);
        break;
    default:
        (void)snprintf(out, cap, "%s", c.missing[0] ? c.missing : "none");
    }
}

int pic_cred_has(const char *provider, const char *label, const char *env, const char *literal) {
    char row[PIC_CRED_NAME_CAP];
    const char *v = env && *env ? getenv(env) : NULL;
    if (!provider || !*provider || !label || !*label) {
        return 0;
    }
    if (strcmp(label, "env") == 0) {
        return v && *v;
    }
    if (strcmp(label, "file") == 0) {
        return literal && *literal;
    }
    return cred_row_name(provider, label, row, sizeof row) == 0 && stored_kind(row) != NULL;
}

/* PAT's occurrences in MSG, each with the run of key-like characters around
 * it, become [key]. */
static void cred_scrub_one(char *msg, const char *pat, size_t pn) {
    char *p = msg;
    while ((p = strstr(p, pat))) {
        char *a = p, *b = p + pn;
        while (a > msg && (isalnum((unsigned char)a[-1]) || a[-1] == '-' || a[-1] == '_' || a[-1] == '*')) {
            a--;
        }
        while (isalnum((unsigned char)*b) || *b == '-' || *b == '_' || *b == '*') {
            b++;
        }
        memmove(a + 5, b, strlen(b) + 1);
        memcpy(a, "[key]", 5);
        p = a + 5;
    }
}

void pic_cred_scrub(char *msg, const char *key) {
    char part[16];
    size_t kn = key ? strlen(key) : 0;
    if (kn < 8) {
        return;
    }
    cred_scrub_one(msg, key, kn);
    if (kn >= 12) {
        (void)snprintf(part, sizeof part, "%.8s", key);
        cred_scrub_one(msg, part, 8);
        (void)snprintf(part, sizeof part, "%s", key + kn - 4);
        cred_scrub_one(msg, part, 4);
    }
}

int pic_cred_use(const char *provider, const char *label, const char *env, const char *literal, char *err, size_t errcap) {
    char setting[160], row[PIC_CRED_NAME_CAP];
    const char *v = env && *env ? getenv(env) : NULL;
    int has;
    if (!provider || !*provider || !label || !*label) {
        (void)snprintf(err, errcap, "name a provider and one of its keys");
        return -1;
    }
    if (strcmp(label, "env") == 0) {
        has = v && *v;
    } else if (strcmp(label, "file") == 0) {
        has = literal && *literal;
    } else {
        has = cred_row_name(provider, label, row, sizeof row) == 0 && stored_kind(row) != NULL;
    }
    if (!has) {
        (void)snprintf(err, errcap, "%s has no key named \"%.40s\": pic auth status lists its keys", provider, label);
        return -1;
    }
    (void)snprintf(setting, sizeof setting, "activeKey:%s", provider);
    if (pic_setting_set(setting, label) != 0) {
        (void)snprintf(err, errcap, "cannot write ~/.pic/pic.sqlite");
        return -1;
    }
    return 0;
}

int pic_cred_entries(const char *provider, const char *env, const char *literal,
                     int (*fn)(void *ctx, const pic_cred_entry *e), void *ctx) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    const char *v = env && *env ? getenv(env) : NULL;
    cred_choice c;
    char name[PIC_CRED_NAME_CAP];
    int stop = 0;
    pic_cred_entry e;
    if (!db || !provider || sqlite3_prepare_v2(db, "SELECT name, kind, created_ms, coalesce(used_ms, 0) FROM picu_credential"
                                                   " WHERE name = ?1 OR substr(name, 1, length(?1) + 1) = ?1 || ':'"
                                                   " ORDER BY name != ?1, created_ms, name",
                                               -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    cred_choose(provider, env, literal, &c);
    sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC);
    while (!stop && sqlite3_step(q) == SQLITE_ROW) {
        const char *row = (const char *)sqlite3_column_text(q, 0), *colon = strchr(row, ':');
        memset(&e, 0, sizeof e);
        e.provider = provider;
        e.name = row;
        e.label = colon ? colon + 1 : "default";
        e.kind = strcmp((const char *)sqlite3_column_text(q, 1), "oauth") == 0 ? "oauth" : "api_key";
        e.active = (c.source == PIC_CRED_STORED_KEY || c.source == PIC_CRED_STORED_OAUTH) && strcmp(c.row, row) == 0;
        e.created_ms = sqlite3_column_int64(q, 2);
        e.used_ms = sqlite3_column_int64(q, 3);
        stop = fn(ctx, &e);
    }
    sqlite3_finalize(q);
    if (!stop && v && *v) {
        cred_outside_name("env", env, v, name, sizeof name);
        memset(&e, 0, sizeof e);
        e.provider = provider;
        e.name = name;
        e.label = "env";
        e.kind = "env";
        e.env = env;
        e.active = c.source == PIC_CRED_ENV;
        stop = fn(ctx, &e);
    }
    if (!stop && literal && *literal) {
        cred_outside_name("file", provider, literal, name, sizeof name);
        memset(&e, 0, sizeof e);
        e.provider = provider;
        e.name = name;
        e.label = "file";
        e.kind = "file";
        e.active = c.source == PIC_CRED_LITERAL;
        (void)fn(ctx, &e);
    }
    return 0;
}

/* ---- what pic remembers of a key ------------------------------------------ */

static const char *const cred_key_states[] = {"unknown", "ok", "invalid", "credit", "limited", "transient", "other"};

const char *pic_key_state_name(pic_key_state s) {
    return (unsigned)s < sizeof cred_key_states / sizeof cred_key_states[0] ? cred_key_states[s] : "unknown";
}

int pic_cred_health_note(const char *name, const pic_key_health *h) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (h->state != PIC_KEY_OK && h->state != PIC_KEY_INVALID && h->state != PIC_KEY_CREDIT && h->state != PIC_KEY_LIMITED) {
        return 0; /* says nothing about the key */
    }
    if (!db || !name || !*name) {
        return -1;
    }
    /* A failure seen again keeps the time it was first seen ("out of credit since"). */
    if (sqlite3_prepare_v2(db,
                           "INSERT INTO picu_credential_health(name, state, reason, status, until_ms, checked_ms, remaining, unit, probed_ms)"
                           " VALUES(?1, ?2, nullif(?3, ''), nullif(?4, 0), nullif(?5, 0), ?6, ?7, nullif(?8, ''), nullif(?9, 0))"
                           " ON CONFLICT(name) DO UPDATE SET reason = excluded.reason, status = excluded.status,"
                           " until_ms = excluded.until_ms, remaining = coalesce(excluded.remaining, remaining),"
                           " unit = CASE WHEN excluded.remaining IS NULL THEN unit ELSE excluded.unit END,"
                           " probed_ms = coalesce(excluded.probed_ms, probed_ms),"
                           " checked_ms = CASE WHEN state = excluded.state AND state != 'ok' THEN checked_ms"
                           "   ELSE excluded.checked_ms END, state = excluded.state",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, pic_key_state_name(h->state), -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 3, h->reason, -1, SQLITE_STATIC);
        sqlite3_bind_int(q, 4, h->status);
        sqlite3_bind_int64(q, 5, h->until_ms);
        sqlite3_bind_int64(q, 6, h->checked_ms ? h->checked_ms : cred_now_ms());
        if (h->has_remaining) {
            sqlite3_bind_double(q, 7, h->remaining);
        }
        sqlite3_bind_text(q, 8, h->currency, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 9, h->probed_ms);
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    q = NULL;
    /* An earlier value of the same variable starts nothing: its state goes. */
    if (rc == 0 && (strncmp(name, "env:", 4) == 0 || strncmp(name, "file:", 5) == 0) && strchr(strchr(name, ':') + 1, ':') &&
        sqlite3_prepare_v2(db, "DELETE FROM picu_credential_health WHERE name != ?1 AND substr(name, 1, ?2) = substr(?1, 1, ?2)",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        sqlite3_bind_int(q, 2, (int)(strrchr(name, ':') - name + 1));
        (void)sqlite3_step(q);
    }
    sqlite3_finalize(q);
    return rc;
}

int pic_cred_health_of(const char *name, pic_key_health *h) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int found = 0;
    memset(h, 0, sizeof *h);
    if (db && name && sqlite3_prepare_v2(db, "SELECT state, coalesce(reason, ''), coalesce(status, 0), coalesce(until_ms, 0),"
                                             " checked_ms, remaining, coalesce(unit, ''), coalesce(probed_ms, 0) FROM picu_credential_health WHERE name = ?1",
                                         -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            const char *state = (const char *)sqlite3_column_text(q, 0);
            for (size_t i = 0; i < sizeof cred_key_states / sizeof cred_key_states[0]; i++) {
                if (strcmp(state, cred_key_states[i]) == 0) {
                    h->state = (pic_key_state)i;
                }
            }
            (void)snprintf(h->reason, sizeof h->reason, "%s", (const char *)sqlite3_column_text(q, 1));
            h->status = sqlite3_column_int(q, 2);
            h->until_ms = sqlite3_column_int64(q, 3);
            h->checked_ms = sqlite3_column_int64(q, 4);
            if (sqlite3_column_type(q, 5) != SQLITE_NULL) {
                h->remaining = sqlite3_column_double(q, 5);
                h->has_remaining = 1;
            }
            (void)snprintf(h->currency, sizeof h->currency, "%s", (const char *)sqlite3_column_text(q, 6));
            h->probed_ms = sqlite3_column_int64(q, 7);
            found = 1;
        }
    }
    sqlite3_finalize(q);
    return found;
}

int pic_cred_health_probed(const char *name, long long now_ms, int status, const char *reason) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (!db || !name || !*name) {
        return -1;
    }
    if (sqlite3_prepare_v2(db,
                           "INSERT INTO picu_credential_health(name, state, reason, status, checked_ms, probed_ms)"
                           " VALUES(?1, 'other', nullif(?2, ''), nullif(?3, 0), ?4, ?4)"
                           " ON CONFLICT(name) DO UPDATE SET probed_ms = excluded.probed_ms",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, reason ? reason : "", -1, SQLITE_STATIC);
        sqlite3_bind_int(q, 3, status);
        sqlite3_bind_int64(q, 4, now_ms);
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    return rc;
}

/* ---- reading a refusal ------------------------------------------------------ */

static const pic_cred_health_ops *cred_failure_ops;

void pic_cred_health_register(const pic_cred_health_ops *ops) { cred_failure_ops = ops; }

void pic_cred_classify(const char *provider, int status, const char *body, const char *message, const char *ratelimit,
                       const char *retry_after, long long now_ms, pic_key_health *h) {
    memset(h, 0, sizeof *h);
    h->status = status;
    h->checked_ms = now_ms;
    if (cred_failure_ops && cred_failure_ops->classify) {
        cred_failure_ops->classify(provider, status, body ? body : "", message ? message : "", ratelimit ? ratelimit : "",
                              retry_after ? retry_after : "", now_ms, h);
        return;
    }
    /* No component: the status alone. A 429 is a limit only when it says to wait a minute or more. */
    (void)snprintf(h->reason, sizeof h->reason, "%.199s", message ? message : "");
    if (status == 401 || status == 403) {
        h->state = PIC_KEY_INVALID;
    } else if (status == 402) {
        h->state = PIC_KEY_CREDIT;
    } else if (status == 429) {
        char *end;
        long secs = retry_after && *retry_after ? strtol(retry_after, &end, 10) : 0;
        h->state = retry_after && *retry_after && *end == '\0' && secs >= 60 ? PIC_KEY_LIMITED : PIC_KEY_TRANSIENT;
        h->until_ms = h->state == PIC_KEY_LIMITED ? now_ms + secs * 1000LL : 0;
    } else if (status == 529 || status >= 500) {
        h->state = PIC_KEY_TRANSIENT;
    } else {
        h->state = PIC_KEY_OTHER;
    }
}

void pic_cred_failure_message(const char *provider, const char *label, const pic_key_health *h, long long now_ms,
                              char *out, size_t cap) {
    if (cred_failure_ops && cred_failure_ops->message) {
        cred_failure_ops->message(provider, label, h, now_ms, out, cap);
        return;
    }
    (void)snprintf(out, cap, "HTTP %d%s%s", h->status, h->reason[0] ? ": " : "", h->reason);
}

/* With nothing registered: plain words, the status, and no choice but to stop or change model. */
void pic_cred_key_headline(const char *provider, const char *label, const pic_key_health *h, long long now_ms, char *out,
                           size_t cap) {
    if (cred_failure_ops && cred_failure_ops->headline) {
        cred_failure_ops->headline(provider, label, h, now_ms, out, cap);
        return;
    }
    (void)snprintf(out, cap, "%s refused the key \"%s\" (%s, HTTP %d).", provider, label, pic_key_state_name(h->state),
                   h->status);
}

const char *pic_cred_key_offers(pic_key_state state, int have_other) {
    return cred_failure_ops && cred_failure_ops->offers ? cred_failure_ops->offers(state, have_other) : "m";
}

void pic_cred_key_phrase(const pic_key_health *h, long long now_ms, char *out, size_t cap) {
    if (cred_failure_ops && cred_failure_ops->phrase) {
        cred_failure_ops->phrase(h, now_ms, out, cap);
        return;
    }
    if (h->status) {
        (void)snprintf(out, cap, "%s (HTTP %d)", pic_key_state_name(h->state), h->status);
    } else {
        (void)snprintf(out, cap, "%s", pic_key_state_name(h->state));
    }
}

void pic_cred_key_alert(const pic_key_health *h, long long now_ms, char *out, size_t cap) {
    if (cred_failure_ops && cred_failure_ops->alert) {
        cred_failure_ops->alert(h, now_ms, out, cap);
        return;
    }
    (void)snprintf(out, cap, "%s", pic_cred_key_bad(h, now_ms) ? "! key" : "");
}

int pic_cred_key_bad(const pic_key_health *h, long long now_ms) {
    if (cred_failure_ops && cred_failure_ops->bad) {
        return cred_failure_ops->bad(h, now_ms);
    }
    return h->state == PIC_KEY_INVALID || h->state == PIC_KEY_CREDIT || (h->state == PIC_KEY_LIMITED && h->until_ms > now_ms);
}

void pic_cred_key_until(long long until_ms, long long now_ms, char *out, size_t cap) {
    if (cred_failure_ops && cred_failure_ops->until) {
        cred_failure_ops->until(until_ms, now_ms, out, cap);
        return;
    }
    (void)snprintf(out, cap, "in %lld min", (until_ms - now_ms + 59999) / 60000);
}

int pic_cred_get_as(const char *provider, const char *env, const char *literal, char *buf, size_t cap, pic_cred_used *used,
                    char *err, size_t errcap) {
    cred_choice c;
    const char *what;
    size_t n;
    cred_choose(provider, env, literal, &c);
    if (used) {
        memset(used, 0, sizeof *used);
    }
    if (c.missing[0]) {
        (void)snprintf(err, errcap, "%s", c.missing);
        return -1;
    }
    if (c.source == PIC_CRED_STORED_KEY || c.source == PIC_CRED_STORED_OAUTH) {
        char why[256] = "";
        int got = stored_key(c.row, buf, cap, why, sizeof why);
        if (got != 0) {
            /* a stored credential owns the provider: no fall back to the variable */
            (void)snprintf(err, errcap, "%s", got < 0 ? why : "the stored key went away while it was read");
            return -1;
        }
    } else if (c.source == PIC_CRED_NONE) {
        if (!env || !*env) {
            return 1; /* nothing configured and nothing stored: a server that needs no key */
        }
        if (pic_cred_oauth_label(provider)) {
            (void)snprintf(err, errcap,
                           "%s is not set and nothing is stored for %s: run `pic auth login %s` (%s), or `pic login %s`"
                           " for an API key",
                           env, provider, provider, pic_cred_oauth_label(provider), provider);
            return -1;
        }
        (void)snprintf(err, errcap, "%s is not set and no key is stored for %s: run `pic login %s`", env,
                       provider && *provider ? provider : "this provider", provider && *provider ? provider : "PROVIDER");
        return -1;
    } else {
        what = c.source == PIC_CRED_LITERAL ? "the models file's apiKey" : env;
        n = strlen(c.value);
        if (n >= cap) {
            (void)snprintf(err, errcap, "%s is longer than %zu bytes", what, cap - 1);
            return -1;
        }
        if (pic_cred_check(what, c.value, err, errcap) != 0) {
            return -1;
        }
        memcpy(buf, c.value, n + 1);
    }
    if (used) {
        cred_choice_name(&c, provider, env, used->name, sizeof used->name);
        (void)snprintf(used->label, sizeof used->label, "%s", c.label);
    }
    return 0;
}

int pic_cred_get(const char *provider, const char *env, const char *literal, char *buf, size_t cap, char *err,
                 size_t errcap) {
    return pic_cred_get_as(provider, env, literal, buf, cap, NULL, err, errcap);
}

int pic_cred_needs_unlock(const char *provider, const char *env, const char *literal) {
    pic_cred_source src;
    if (unlocked || !provider || !*provider) {
        return 0;
    }
    src = pic_cred_source_of(provider, env, literal);
    return src == PIC_CRED_STORED_KEY || src == PIC_CRED_STORED_OAUTH; /* the credential in use is in the store */
}

/* ---- handing the key to a child ------------------------------------------ */

int pic_cred_handoff(void) {
    int fds[2];
    ssize_t w;
    if (!unlocked || pipe(fds) != 0) {
        return -1;
    }
    do {
        w = write(fds[1], master, sizeof master);
    } while (w < 0 && errno == EINTR);
    close(fds[1]);
    if (w != (ssize_t)sizeof master) {
        close(fds[0]);
        return -1;
    }
    (void)fcntl(fds[0], F_SETFD, FD_CLOEXEC);
    return fds[0];
}

void pic_cred_adopt(void) {
    const char *v = getenv("PIC_KEY_FD");
    char *end;
    long fd;
    size_t got = 0;
    if (!v) {
        return;
    }
    fd = strtol(v, &end, 10);
    if (*end || fd < 3 || fd > 65535) {
        fd = -1;
    }
    (void)unsetenv("PIC_KEY_FD"); /* frees v */
    if (fd < 0) {
        return;
    }
    while (got < sizeof handed) {
        ssize_t r = read((int)fd, handed + got, sizeof handed - got);
        if (r < 0 && errno == EINTR) {
            continue;
        }
        if (r <= 0) {
            break;
        }
        got += (size_t)r;
    }
    close((int)fd);
    have_handed = got == sizeof handed;
    if (!have_handed) {
        pic_cred_wipe(handed, sizeof handed);
    }
}