Skip to content
pi-c Documentation
Login

Documentation

#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); }

/* The secret from the platform's source, as a 32-byte key: stretched when it
 * is a passphrase. 0, or -1 with err. */
static int source_key(int fresh, const unsigned char *salt, size_t saltn, uint32_t iterations,
                      unsigned char key[PIC_CRED_KEY], char *err, size_t errcap) {
    const pic_platform *p = pic_platform_get();
    unsigned char secret[SECRET_CAP];
    size_t len = 0;
    int stretch = 1, 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;
    }
    if (p->secret_key(fresh, secret, sizeof secret, &len, &stretch, why, sizeof why) != 0) {
        (void)snprintf(err, errcap, "cannot unlock the credential store: %s", why[0] ? why : "no key");
    } else if (stretch) {
        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");
    }
    pic_cred_wipe(secret, sizeof secret);
    return rc;
}

/* Makes the store's master key: a salt, the key from the source (asked
 * twice), and the verifier. 0, or -1 with err. */
static int create(sqlite3 *db, char *err, size_t errcap) {
    unsigned char salt[SALT_BYTES], key[PIC_CRED_KEY], verifier[sizeof VERIFIER_TEXT - 1 + PIC_CRED_OVERHEAD];
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (random_bytes(salt, sizeof salt) != 0) {
        (void)snprintf(err, errcap, "no entropy for the credential store's salt");
        return -1;
    }
    if (source_key(1, salt, sizeof salt, KDF_ITERATIONS, key, err, errcap) != 0) {
        return -1;
    }
    if (pic_cred_seal(key, VERIFIER_AAD, VERIFIER_TEXT, sizeof VERIFIER_TEXT - 1, verifier) != 0) {
        (void)snprintf(err, errcap, "no entropy for a nonce");
    } else if (sqlite3_prepare_v2(db,
                                  "INSERT INTO picu_credential_key(id, source, kdf, iterations, salt, verifier, created_ms)"
                                  " VALUES(1, 'passphrase', ?1, ?2, ?3, ?4, ?5)",
                                  -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
    } else {
        sqlite3_bind_text(q, 1, KDF_NAME, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, KDF_ITERATIONS);
        sqlite3_bind_blob(q, 3, salt, sizeof salt, SQLITE_STATIC);
        sqlite3_bind_blob(q, 4, verifier, sizeof verifier, SQLITE_STATIC);
        sqlite3_bind_int64(q, 5, cred_now_ms());
        if (sqlite3_step(q) == SQLITE_DONE) {
            remember(key);
            rc = 0;
        } else {
            (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db));
        }
    }
    sqlite3_finalize(q);
    pic_cred_wipe(key, sizeof key);
    return rc;
}

/* 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 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) {
            return create(db, err, errcap);
        }
        (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 if (strcmp((const char *)sqlite3_column_text(q, 0), KDF_NAME) != 0 || sqlite3_column_int64(q, 1) < 1 ||
               sqlite3_column_int64(q, 1) > 100000000) {
        (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, 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(0, salt, (size_t)sqlite3_column_bytes(q, 2), (uint32_t)sqlite3_column_int64(q, 1), key,
                             err, errcap);
        }
        if (got == 0) {
            if (pic_cred_open(key, VERIFIER_AAD, verifier, sizeof check + PIC_CRED_OVERHEAD, check) == 0) {
                remember(key);
                rc = 0;
            } else {
                (void)snprintf(err, errcap, from_parent ? "the key handed over by the parent pic does not open the credential store"
                                                        : "wrong passphrase for the credential store");
            }
        }
    }
    sqlite3_finalize(q);
    pic_cred_wipe(key, sizeof key);
    pic_cred_wipe(check, sizeof check);
    return rc;
}

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 + 128];
    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) {
    if (!provider || !*provider) {
        (void)snprintf(err, errcap, "no provider named");
        return -1;
    }
    if (pic_cred_check("the key", key, err, errcap) != 0 || unlock(1, err, errcap) != 0) {
        return -1;
    }
    return put_row(provider, "api_key", key, strlen(key), 1, err, errcap);
}

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);
    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 + 128];
    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;
}

/* Pi's order: a stored credential owns the provider; the models file's literal, then the
 * variable, are consulted only when nothing is stored. */
pic_cred_source pic_cred_source_of(const char *provider, const char *env, const char *literal) {
    const char *v = env && *env ? getenv(env) : NULL, *kind;
    kind = provider && *provider ? stored_kind(provider) : NULL;
    if (kind) {
        return strcmp(kind, "oauth") == 0 ? PIC_CRED_STORED_OAUTH : PIC_CRED_STORED_KEY;
    }
    if (literal && *literal) {
        return PIC_CRED_LITERAL;
    }
    return v && *v ? PIC_CRED_ENV : PIC_CRED_NONE;
}

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] = "";
    switch (pic_cred_source_of(provider, env, literal)) {
    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 (in use%s)",
                       pic_cred_source_of(provider, env, literal) == PIC_CRED_STORED_OAUTH ? "stored sign-in" : "stored key",
                       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, "none");
    }
}

int pic_cred_get(const char *provider, const char *env, const char *literal, char *buf, size_t cap, char *err,
                 size_t errcap) {
    const char *value = literal && *literal ? literal : NULL;
    const char *what = value ? "the models file's apiKey" : env;
    size_t n;
    if (provider && *provider && stored_kind(provider)) {
        char why[256] = "";
        int got = stored_key(provider, buf, cap, why, sizeof why);
        if (got == 0) {
            return 0;
        }
        if (got < 0) {
            (void)snprintf(err, errcap, "%s", why); /* a stored credential owns the provider: no fall back to the variable */
            return -1;
        }
    }
    if (!value && env && *env) {
        value = getenv(env);
        value = value && *value ? value : NULL;
    }
    if (!value) {
        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;
    }
    n = strlen(value);
    if (n >= cap) {
        (void)snprintf(err, errcap, "%s is longer than %zu bytes", what, cap - 1);
        return -1;
    }
    if (pic_cred_check(what, value, err, errcap) != 0) {
        return -1;
    }
    memcpy(buf, value, n + 1);
    return 0;
}

int pic_cred_needs_unlock(const char *provider, const char *env, const char *literal) {
    (void)env;
    (void)literal;
    if (unlocked || !provider || !*provider) {
        return 0;
    }
    return pic_cred_stored(provider); /* a stored credential is read first, whatever else is set */
}

/* ---- 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);
    }
}