Skip to content
pi-c Documentation
Login

Documentation

/* The credential store's primitives and its rows: seal/open round trip,
 * tamper and wrong-AAD detection, nonce uniqueness, PBKDF2 against RFC 7914's
 * vector, and the store end to end under a test secret_key source (the seam a
 * no-OS build fills). HOME must be a private directory. */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/resource.h>

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

static const char *passphrase = "correct horse";
static int asked;

static int test_secret(const pic_secret_ask *ask, unsigned char *buf, size_t cap, size_t *len, int *how, char *err,
                       size_t errcap) {
    size_t n = strlen(passphrase);
    (void)err;
    (void)errcap;
    assert(strcmp(ask->source, "passphrase") == 0);
    asked++;
    assert(n <= cap);
    memcpy(buf, passphrase, n);
    *len = n;
    *how = PIC_SECRET_PASSPHRASE;
    return 0;
}

static void test_round_trip(void) {
    unsigned char key[PIC_CRED_KEY], box[64 + PIC_CRED_OVERHEAD];
    char out[64];
    const char *pt = "sk-test-round-trip";
    size_t n = strlen(pt) + 1;
    for (int i = 0; i < PIC_CRED_KEY; i++) {
        key[i] = (unsigned char)i;
    }
    assert(pic_cred_seal(key, "anthropic", pt, n, box) == 0);
    assert(memmem(box, n + PIC_CRED_OVERHEAD, "sk-test", 7) == NULL); /* no plaintext in the box */
    assert(pic_cred_open(key, "anthropic", box, n + PIC_CRED_OVERHEAD, out) == 0);
    assert(strcmp(out, pt) == 0);
    puts("ok seal/open round trip");
}

static void test_tamper(void) {
    unsigned char key[PIC_CRED_KEY] = {7}, box[32 + PIC_CRED_OVERHEAD], other[PIC_CRED_KEY] = {8};
    char out[32];
    const char *pt = "sk-test-tamper";
    size_t n = strlen(pt) + 1, total = n + PIC_CRED_OVERHEAD;
    assert(pic_cred_seal(key, "openai", pt, n, box) == 0);
    for (size_t i = 0; i < total; i++) { /* every byte: nonce, ciphertext and tag */
        box[i] ^= 0x01;
        memset(out, 'x', sizeof out);
        assert(pic_cred_open(key, "openai", box, total, out) == -1);
        for (size_t k = 0; k < n; k++) {
            assert(out[k] == 0); /* wiped, never a garbage key */
        }
        box[i] ^= 0x01;
    }
    assert(pic_cred_open(key, "anthropic", box, total, out) == -1); /* wrong AAD: another provider's row */
    assert(pic_cred_open(key, "openai2", box, total, out) == -1);
    assert(pic_cred_open(other, "openai", box, total, out) == -1); /* wrong key */
    assert(pic_cred_open(key, "openai", box, PIC_CRED_OVERHEAD - 1, out) == -1); /* too short */
    assert(pic_cred_open(key, "openai", box, total, out) == 0 && strcmp(out, pt) == 0);
    puts("ok tamper and wrong AAD are refused");
}

static void test_nonces(void) {
    enum { N = 512 };
    static unsigned char boxes[N][4 + PIC_CRED_OVERHEAD];
    unsigned char key[PIC_CRED_KEY] = {1};
    for (int i = 0; i < N; i++) {
        assert(pic_cred_seal(key, "p", "same", 4, boxes[i]) == 0);
        for (int j = 0; j < i; j++) {
            assert(memcmp(boxes[i], boxes[j], PIC_CRED_NONCE) != 0);
            assert(memcmp(boxes[i] + PIC_CRED_NONCE, boxes[j] + PIC_CRED_NONCE, 4) != 0);
        }
    }
    puts("ok nonces are unique per seal");
}

static void test_kdf(void) {
    /* RFC 7914 section 11: PBKDF2-HMAC-SHA256("passwd", "salt", c=1, dkLen=64), first 32 bytes. */
    static const unsigned char want[32] = {0x55, 0xac, 0x04, 0x6e, 0x56, 0xe3, 0x08, 0x9f, 0xec, 0x16, 0x91,
                                           0xc2, 0x25, 0x44, 0xb6, 0x05, 0xf9, 0x41, 0x85, 0x21, 0x6d, 0xde,
                                           0x04, 0x65, 0xe6, 0x8b, 0x9d, 0x57, 0xc2, 0x0d, 0xac, 0xbc};
    /* RFC 7914: ("Password", "NaCl", c=80000), first 32 bytes. */
    static const unsigned char want2[32] = {0x4d, 0xdc, 0xd8, 0xf6, 0x0b, 0x98, 0xbe, 0x21, 0x83, 0x0c, 0xee,
                                            0x5e, 0xf2, 0x27, 0x01, 0xf9, 0x64, 0x1a, 0x44, 0x18, 0xd0, 0x4c,
                                            0x04, 0x14, 0xae, 0xff, 0x08, 0x87, 0x6b, 0x34, 0xab, 0x56};
    unsigned char out[32];
    pic_cred_kdf("passwd", 6, (const unsigned char *)"salt", 4, 1, out);
    assert(memcmp(out, want, 32) == 0);
    pic_cred_kdf("Password", 8, (const unsigned char *)"NaCl", 4, 80000, out);
    assert(memcmp(out, want2, 32) == 0);
    puts("ok PBKDF2-HMAC-SHA256 matches RFC 7914");
}

static int list_names(void *ctx, const char *name, const char *kind, long long created_ms, long long used_ms) {
    char *buf = ctx;
    (void)used_ms;
    assert(strcmp(kind, "api_key") == 0);
    assert(created_ms > 0);
    strcat(buf, name);
    strcat(buf, ",");
    return 0;
}

static void test_store(void) {
    pic_platform p = *pic_platform_host();
    char key[256], err[256] = "", names[256] = "";
    sqlite3 *db;
    p.secret_key = test_secret;
    p.secret_keep = NULL; /* a platform that keeps no key: a passphrase store */
    pic_platform_set(&p);
    unsetenv("PIC_TEST_ENV_KEY");

    assert(pic_cred_stored("anthropic") == 0);
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == -1);
    assert(strstr(err, "pic login anthropic") && strstr(err, "PIC_TEST_ENV_KEY is not set"));
    assert(pic_cred_get("anthropic", "", "", key, sizeof key, err, sizeof err) == 1); /* nothing configured */
    assert(asked == 0);                                                               /* nothing asked */

    assert(pic_cred_login("anthropic", "sk-store-sentinel-1", err, sizeof err) == 0);
    assert(asked == 1 && pic_cred_stored("anthropic") == 1);
    assert(pic_cred_login("anthropic", "bad key", err, sizeof err) == -1 && strstr(err, "header"));
    {
        /* One limit for login and use: a key a request could not send is refused at login. */
        char big[PIC_CRED_KEY_CAP + 1];
        memset(big, 'k', sizeof big - 1);
        big[sizeof big - 1] = '\0';
        assert(pic_cred_login("anthropic", big, err, sizeof err) == -1 && strstr(err, "longer than"));
        big[PIC_CRED_KEY_CAP - 1] = '\0'; /* the longest that fits */
        assert(pic_cred_check("the key", big, err, sizeof err) == 0);
    }
    {
        /* A master key in memory: no core dump can carry it. */
        struct rlimit rl;
        assert(getrlimit(RLIMIT_CORE, &rl) == 0 && rl.rlim_cur == 0);
    }
    db = pic_userdb(err, sizeof err);
    assert(db);
    {
        sqlite3_stmt *q = NULL;
        int rows = 0;
        assert(sqlite3_prepare_v2(db, "SELECT sealed FROM picu_credential WHERE name = 'anthropic'", -1, &q, NULL) ==
               SQLITE_OK);
        while (sqlite3_step(q) == SQLITE_ROW) {
            const void *b = sqlite3_column_blob(q, 0);
            assert(memmem(b, (size_t)sqlite3_column_bytes(q, 0), "sentinel", 8) == NULL);
            rows++;
        }
        sqlite3_finalize(q);
        assert(rows == 1);
    }

    /* Cached: no second prompt in this process. */
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0);
    assert(strcmp(key, "sk-store-sentinel-1") == 0 && asked == 1);
    /* Pi's order: the store wins over the environment and over a literal; with nothing stored a
     * literal wins over the environment, which is used when it is all there is. */
    setenv("PIC_TEST_ENV_KEY", "sk-from-env", 1);
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0);
    assert(strcmp(key, "sk-store-sentinel-1") == 0);
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "sk-literal", key, sizeof key, err, sizeof err) == 0);
    assert(strcmp(key, "sk-store-sentinel-1") == 0);
    assert(pic_cred_source_of("anthropic", "PIC_TEST_ENV_KEY", "") == PIC_CRED_STORED_KEY);
    assert(pic_cred_get("openai", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0);
    assert(strcmp(key, "sk-from-env") == 0);
    assert(pic_cred_source_of("openai", "PIC_TEST_ENV_KEY", "") == PIC_CRED_ENV);
    assert(pic_cred_get("openai", "PIC_TEST_ENV_KEY", "sk-literal", key, sizeof key, err, sizeof err) == 0);
    assert(strcmp(key, "sk-literal") == 0);
    assert(pic_cred_source_of("openai", "", "sk-literal") == PIC_CRED_LITERAL);
    unsetenv("PIC_TEST_ENV_KEY");

    /* A fresh process (lock): the right passphrase opens it, a wrong one is refused cleanly. */
    pic_cred_lock();
    passphrase = "wrong horse";
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == -1);
    assert(strstr(err, "wrong passphrase") && !strstr(err, "sentinel"));
    assert(pic_cred_needs_unlock("anthropic", "PIC_TEST_ENV_KEY", "") == 1);
    assert(pic_cred_needs_unlock("openai", "PIC_TEST_ENV_KEY", "") == 0); /* nothing stored for it */
    assert(pic_cred_needs_unlock("anthropic", "PIC_TEST_ENV_KEY", "sk-literal") == 1); /* the store is read first */
    passphrase = "correct horse";
    assert(pic_cred_unlock(err, sizeof err) == 0);
    assert(pic_cred_needs_unlock("anthropic", "PIC_TEST_ENV_KEY", "") == 0);
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0);
    assert(strcmp(key, "sk-store-sentinel-1") == 0);

    /* A row moved to another name does not open: the name is bound. */
    assert(sqlite3_exec(db, "INSERT INTO picu_credential(name, kind, sealed, created_ms) SELECT 'openai', kind, sealed,"
                            " created_ms FROM picu_credential WHERE name = 'anthropic'",
                        NULL, NULL, NULL) == SQLITE_OK);
    assert(pic_cred_get("openai", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == -1);
    assert(strstr(err, "openai") && !strstr(err, "sentinel"));
    assert(pic_cred_logout("openai") == 1);

    /* Handoff: a pipe holding the key, adopted as a child would. */
    {
        int fd = pic_cred_handoff();
        char num[16];
        assert(fd >= 0);
        (void)snprintf(num, sizeof num, "%d", fd);
        pic_cred_lock();
        setenv("PIC_KEY_FD", num, 1);
        pic_cred_adopt();
        assert(getenv("PIC_KEY_FD") == NULL);
        assert(fcntl(fd, F_GETFD) == -1); /* closed: nothing the child starts inherits it */
        asked = 0;
        assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0);
        assert(strcmp(key, "sk-store-sentinel-1") == 0 && asked == 0);
    }

    assert(pic_cred_login("openai", "sk-second", err, sizeof err) == 0);
    assert(pic_cred_each(list_names, names) == 0 && strcmp(names, "anthropic,openai,") == 0);
    {
        /* The verifier's AAD and a provider's are apart: a provider named like
         * the verifier's AAD cannot pass for it, and the verifier's box does
         * not open as a key. */
        sqlite3_stmt *q = NULL;
        unsigned char box[64];
        char out[64];
        int n = 0;
        assert(sqlite3_prepare_v2(db, "SELECT verifier FROM picu_credential_key", -1, &q, NULL) == SQLITE_OK);
        assert(sqlite3_step(q) == SQLITE_ROW);
        n = sqlite3_column_bytes(q, 0);
        assert(n > 0 && (size_t)n <= sizeof box);
        memcpy(box, sqlite3_column_blob(q, 0), (size_t)n);
        sqlite3_finalize(q);
        assert(sqlite3_exec(db, "DELETE FROM picu_credential WHERE name = 'picu_credential_key'", NULL, NULL, NULL) ==
               SQLITE_OK);
        q = NULL;
        assert(sqlite3_prepare_v2(db, "INSERT INTO picu_credential(name, kind, sealed, created_ms) VALUES"
                                      " ('picu_credential_key', 'api_key', ?1, 1)",
                                  -1, &q, NULL) == SQLITE_OK);
        sqlite3_bind_blob(q, 1, box, n, SQLITE_STATIC);
        assert(sqlite3_step(q) == SQLITE_DONE);
        sqlite3_finalize(q);
        assert(pic_cred_get("picu_credential_key", "", "", out, sizeof out, err, sizeof err) == -1);
        assert(strstr(err, "does not open"));
        assert(pic_cred_logout("picu_credential_key") == 1);
    }
    /* Keys stored but the master key's record gone: a clear error, not a bare failure. */
    pic_cred_lock();
    assert(sqlite3_exec(db, "CREATE TABLE saved_key AS SELECT * FROM picu_credential_key;"
                            " DELETE FROM picu_credential_key",
                        NULL, NULL, NULL) == SQLITE_OK);
    err[0] = '\0';
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == -1);
    assert(strstr(err, "picu_credential_key") && strstr(err, "pic login anthropic"));
    assert(sqlite3_exec(db, "INSERT INTO picu_credential_key SELECT * FROM saved_key; DROP TABLE saved_key", NULL, NULL,
                        NULL) == SQLITE_OK);
    assert(pic_cred_unlock(err, sizeof err) == 0);
    assert(pic_cred_logout("anthropic") == 1 && pic_cred_logout("anthropic") == 0);
    assert(pic_cred_stored("anthropic") == 0);
    pic_cred_wipe(key, sizeof key);
    pic_platform_set(NULL);
    puts("ok the store: login, lookup order, wrong passphrase, binding, handoff, logout");
}

static int list_entry(void *ctx, const pic_cred_entry *e) {
    char *out = ctx;
    size_t n = strlen(out);
    (void)snprintf(out + n, 512 - n, "%s=%s/%s%s,", e->label, e->kind, e->name, e->active ? "*" : "");
    return 0;
}

/* A provider's message that quotes the key, whole or in part (its first
 * eight or last four characters), anywhere: the quoting token becomes [key]. */
static void test_scrub(void) {
    const char *key = "sk-abcdefghijklmnopqrstuvwxyz1234";
    static const char *const cases[][2] = {
        {"Incorrect API key provided: sk-ab***1234.", "Incorrect API key provided: [key]."},
        {"Incorrect API key provided: sk-abcde*********1234.", "Incorrect API key provided: [key]."},
        {"key `sk-abcdefghijklmnopqrstuvwxyz1234` bad", "key `[key]` bad"},
        {"key=sk-abcdefghijklmnopqrstuvwxyz1234}", "key=[key]}"},
        {"[sk-abcdefghijklmnopqrstuvwxyz1234] <sk-abcdefghijklmnopqrstuvwxyz1234>", "[[key]] <[key]>"},
        {"{\"k\":\"xsk-abcdefghijklmnopqrstuvwxyz1234x\"}", "{\"k\":\"[key]\"}"},
        {"invalid x-api-key", "invalid x-api-key"},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        char msg[200];
        (void)snprintf(msg, sizeof msg, "%s", cases[i][0]);
        pic_cred_scrub(msg, key);
        if (strcmp(msg, cases[i][1]) != 0) {
            fprintf(stderr, "scrub %zu: got %s want %s\n", i, msg, cases[i][1]);
            assert(0);
        }
    }
    puts("ok a quoted key, whole or in part, is scrubbed from a message");
}

/* Named keys, the active one, its use for one run, and remembered health:
 * extra keys are rows named provider:label beside the provider's own (its
 * default), sealed under their own names; the active label is a setting; an
 * environment key's health is kept under its variable and a salted hash of
 * its value, so a changed value starts fresh, and no key text is stored. */
static void test_named(void) {
    pic_platform p = *pic_platform_host();
    char key[256], err[256] = "", list[512] = "", env1[160], env2[160];
    pic_cred_used used;
    pic_key_health h;
    p.secret_key = test_secret;
    p.secret_keep = NULL; /* a platform that keeps no key: a passphrase store */
    pic_platform_set(&p);
    unsetenv("PIC_TEST_NAMED_KEY");
    passphrase = "correct horse";

    assert(pic_cred_label_check("second", err, sizeof err) == 0);
    assert(pic_cred_label_check("Bad Label", err, sizeof err) == -1 && strstr(err, "label"));
    assert(pic_cred_label_check("env", err, sizeof err) == -1); /* names the variable */
    assert(pic_cred_login_as("fa:ke", NULL, "sk-x", err, sizeof err) == -1);
    {
        char longp[100];
        memset(longp, 'p', sizeof longp - 1);
        longp[sizeof longp - 1] = '\0';
        assert(pic_cred_login_as(longp, "second", "sk-xxxxxxxx", err, sizeof err) == -1 && strstr(err, "too long"));
    }
    assert(pic_cred_login_as("fake", "second", "sk-named-second", err, sizeof err) == 0);
    /* Only a named key: it is used, as the provider's only stored key, before the variable. */
    setenv("PIC_TEST_NAMED_KEY", "sk-named-env-1", 1);
    assert(pic_cred_get_as("fake", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == 0);
    assert(strcmp(key, "sk-named-second") == 0 && strcmp(used.name, "fake:second") == 0 && strcmp(used.label, "second") == 0);
    assert(pic_cred_login("fake", "sk-named-default", err, sizeof err) == 0);
    /* The provider's own row is its default and wins once it exists. */
    assert(pic_cred_get_as("fake", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == 0);
    assert(strcmp(key, "sk-named-default") == 0 && strcmp(used.name, "fake") == 0 && strcmp(used.label, "default") == 0);
    list[0] = '\0';
    assert(pic_cred_entries("fake", "PIC_TEST_NAMED_KEY", "", list_entry, list) == 0);
    assert(strncmp(list, "default=api_key/fake*,second=api_key/fake:second,env=env/env:PIC_TEST_NAMED_KEY:", 80) == 0);
    /* auth use: the label is a setting; a label nobody stored is refused. */
    assert(pic_cred_use("fake", "third", "PIC_TEST_NAMED_KEY", "", err, sizeof err) == -1 && strstr(err, "third"));
    assert(pic_cred_use("fake", "second", "PIC_TEST_NAMED_KEY", "", err, sizeof err) == 0);
    {
        char *v = pic_setting("activeKey:fake");
        assert(v && strcmp(v, "second") == 0);
        free(v);
    }
    assert(pic_cred_get_as("fake", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == 0);
    assert(strcmp(key, "sk-named-second") == 0 && strcmp(used.name, "fake:second") == 0);
    assert(pic_cred_source_of("fake", "PIC_TEST_NAMED_KEY", "") == PIC_CRED_STORED_KEY);
    /* The variable can be chosen by name, though stored keys exist. */
    assert(pic_cred_use("fake", "env", "PIC_TEST_NAMED_KEY", "", err, sizeof err) == 0);
    assert(pic_cred_source_of("fake", "PIC_TEST_NAMED_KEY", "") == PIC_CRED_ENV);
    assert(pic_cred_get_as("fake", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == 0);
    assert(strcmp(key, "sk-named-env-1") == 0 && strncmp(used.name, "env:PIC_TEST_NAMED_KEY:", 23) == 0);
    assert(strlen(used.name) == 23 + 12 && !strstr(used.name, "sk-named"));
    (void)snprintf(env1, sizeof env1, "%s", used.name);
    /* --key for one run beats the setting, and only for its provider. */
    pic_cred_override("fake", "default");
    assert(pic_cred_get_as("fake", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == 0);
    assert(strcmp(key, "sk-named-default") == 0);
    assert(pic_cred_get_as("other", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == 0);
    assert(strcmp(key, "sk-named-env-1") == 0);
    assert(pic_cred_has("fake", "default", "PIC_TEST_NAMED_KEY", "") == 1);
    assert(pic_cred_has("fake", "nosuch", "PIC_TEST_NAMED_KEY", "") == 0);
    pic_cred_override("fake", "nosuch");
    assert(pic_cred_get_as("fake", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == -1);
    assert(strstr(err, "nosuch") && strstr(err, "pic auth status"));
    pic_cred_override(NULL, NULL);
    /* Every per-provider slot full: the next provider is refused, not dropped silently. */
    for (int i = 0; i < 16; i++) {
        char pn[16];
        (void)snprintf(pn, sizeof pn, "prov%d", i);
        assert(pic_cred_override(pn, "default") == 0);
    }
    assert(pic_cred_override("prov16", "default") == -1);
    assert(pic_cred_override("prov3", "other") == 0); /* an existing provider still changes */
    assert(pic_cred_override("prov3", NULL) == 0);    /* and clearing frees a slot */
    assert(pic_cred_override("prov16", "default") == 0);
    pic_cred_override(NULL, NULL);

    /* Health: kept per credential name, never with key text. */
    assert(pic_cred_health_of("fake:second", &h) == 0 && h.state == PIC_KEY_UNKNOWN);
    memset(&h, 0, sizeof h);
    h.state = PIC_KEY_CREDIT;
    h.status = 402;
    (void)snprintf(h.reason, sizeof h.reason, "credit balance is too low");
    assert(pic_cred_health_note("fake:second", &h) == 0);
    memset(&h, 0, sizeof h);
    assert(pic_cred_health_of("fake:second", &h) == 1 && h.state == PIC_KEY_CREDIT && h.status == 402);
    assert(strcmp(h.reason, "credit balance is too low") == 0 && h.checked_ms > 0);
    assert(strcmp(pic_key_state_name(PIC_KEY_CREDIT), "credit") == 0);
    /* A transient failure says nothing about the key: the state stands. */
    memset(&h, 0, sizeof h);
    h.state = PIC_KEY_TRANSIENT;
    h.status = 529;
    assert(pic_cred_health_note("fake:second", &h) == 0);
    assert(pic_cred_health_of("fake:second", &h) == 1 && h.state == PIC_KEY_CREDIT);
    /* An environment key's state is under its variable and the value's salted hash: a new value starts fresh. */
    memset(&h, 0, sizeof h);
    h.state = PIC_KEY_INVALID;
    h.status = 401;
    assert(pic_cred_health_note(env1, &h) == 0);
    setenv("PIC_TEST_NAMED_KEY", "sk-named-env-2", 1);
    assert(pic_cred_get_as("fake", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == 0);
    (void)snprintf(env2, sizeof env2, "%s", used.name);
    assert(strcmp(env1, env2) != 0 && pic_cred_health_of(env2, &h) == 0);
    memset(&h, 0, sizeof h);
    h.state = PIC_KEY_OK;
    assert(pic_cred_health_note(env2, &h) == 0);
    assert(pic_cred_health_of(env1, &h) == 0); /* the old value's row went with it */
    {
        sqlite3 *db = pic_userdb(err, sizeof err);
        sqlite3_stmt *q = NULL;
        assert(sqlite3_prepare_v2(db, "SELECT count(*) FROM picu_credential_health WHERE name LIKE '%sk-named%'"
                                      " OR reason LIKE '%sk-named%'", -1, &q, NULL) == SQLITE_OK);
        assert(sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0) == 0);
        sqlite3_finalize(q);
    }
    /* The models file's key is kept the same way: a new value drops the old one's state. */
    {
        char f1[160], f2[160];
        assert(pic_cred_get_as("lit", "", "sk-lit-value-1", key, sizeof key, &used, err, sizeof err) == 0);
        (void)snprintf(f1, sizeof f1, "%s", used.name);
        assert(strncmp(f1, "file:lit:", 9) == 0);
        memset(&h, 0, sizeof h);
        h.state = PIC_KEY_CREDIT;
        assert(pic_cred_health_note(f1, &h) == 0);
        assert(pic_cred_get_as("lit", "", "sk-lit-value-2", key, sizeof key, &used, err, sizeof err) == 0);
        (void)snprintf(f2, sizeof f2, "%s", used.name);
        memset(&h, 0, sizeof h);
        h.state = PIC_KEY_OK;
        assert(pic_cred_health_note(f2, &h) == 0);
        assert(pic_cred_health_of(f1, &h) == 0);
    }
    /* Logout of the active named key: its row, its health and the choice go. */
    assert(pic_cred_use("fake", "second", "PIC_TEST_NAMED_KEY", "", err, sizeof err) == 0);
    assert(pic_cred_logout("fake:second") == 1);
    assert(pic_cred_health_of("fake:second", &h) == 0);
    {
        char *v = pic_setting("activeKey:fake");
        assert(v == NULL);
    }
    assert(pic_cred_get_as("fake", "PIC_TEST_NAMED_KEY", "", key, sizeof key, &used, err, sizeof err) == 0);
    assert(strcmp(key, "sk-named-default") == 0);
    assert(pic_cred_logout("fake") == 1);
    unsetenv("PIC_TEST_NAMED_KEY");
    pic_cred_wipe(key, sizeof key);
    pic_platform_set(NULL);
    puts("ok named keys: default and labels, use, one-run override, health, the environment hash, logout");
}

/* A platform that keeps a raw key (a keychain, a no-OS build's vault): in
 * memory here, refusing while vault_locked. */
static unsigned char vault[PIC_CRED_KEY];
static int vault_has, vault_locked, vault_drops, typed_pass;

static int vault_key(const pic_secret_ask *ask, unsigned char *buf, size_t cap, size_t *len, int *how, char *err,
                     size_t errcap) {
    if (strcmp(ask->source, "passphrase") == 0) {
        int rc = test_secret(ask, buf, cap, len, how, err, errcap);
        *how = typed_pass ? PIC_SECRET_TYPED : PIC_SECRET_PASSPHRASE;
        return rc;
    }
    assert(strcmp(ask->source, "vault") == 0);
    assert(strstr(ask->id, "pic.sqlite"));
    if (vault_locked || !vault_has) {
        (void)snprintf(err, errcap, "the vault is locked");
        return -1;
    }
    memcpy(buf, vault, PIC_CRED_KEY);
    *len = PIC_CRED_KEY;
    *how = PIC_SECRET_KEY;
    return 0;
}

static int vault_keep(const char *want, const char *id, const unsigned char *key, size_t n, char *source, size_t scap,
                      char *err, size_t errcap) {
    (void)id;
    if (want && strcmp(want, "passphrase") == 0) {
        (void)snprintf(source, scap, "passphrase");
        return 1;
    }
    if (want && *want && strcmp(want, "vault") != 0) {
        (void)snprintf(err, errcap, "no source %s", want);
        return -1;
    }
    if (vault_locked) {
        (void)snprintf(err, errcap, "the vault is locked");
        return -1;
    }
    assert(n == PIC_CRED_KEY);
    memcpy(vault, key, n);
    vault_has = 1;
    (void)snprintf(source, scap, "vault");
    return 0;
}

static void vault_drop(const char *source, const char *id) {
    (void)id;
    assert(strcmp(source, "vault") == 0);
    vault_has = 0;
    vault_drops++;
}

static void record(char *source, size_t cap, char *kdf, size_t kcap) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    assert(sqlite3_prepare_v2(db, "SELECT source, kdf FROM picu_credential_key WHERE id = 1", -1, &q, NULL) == SQLITE_OK);
    assert(sqlite3_step(q) == SQLITE_ROW);
    (void)snprintf(source, cap, "%s", (const char *)sqlite3_column_text(q, 0));
    (void)snprintf(kdf, kcap, "%s", (const char *)sqlite3_column_text(q, 1));
    sqlite3_finalize(q);
}

/* A sealed remote-control row, as remote.c writes one, opens after a rekey too. */
static void remote_row_put(void) {
    unsigned char box[16 + PIC_CRED_OVERHEAD], dev[16 + PIC_CRED_OVERHEAD], id[16];
    char err[200];
    sqlite3_stmt *q = NULL;
    sqlite3 *db = pic_userdb(NULL, 0);
    memset(id, 0xab, sizeof id);
    assert(pic_cred_box("remote-key:static", "remote-secret-16", 16, box, err, sizeof err) == 0);
    assert(sqlite3_prepare_v2(db, "INSERT INTO picu_remote_key(name, sealed, created_ms) VALUES('static', ?1, 1)", -1, &q,
                              NULL) == SQLITE_OK);
    sqlite3_bind_blob(q, 1, box, sizeof box, SQLITE_STATIC);
    assert(sqlite3_step(q) == SQLITE_DONE);
    sqlite3_finalize(q);
    assert(pic_cred_box("remote-device:abababababababababababababababab", "device-json-16b!", 16, dev, err, sizeof err) == 0);
    assert(sqlite3_prepare_v2(db, "INSERT INTO picu_remote_device(id, sealed, paired_ms) VALUES(?1, ?2, 1)", -1, &q, NULL) ==
           SQLITE_OK);
    sqlite3_bind_blob(q, 1, id, sizeof id, SQLITE_STATIC);
    sqlite3_bind_blob(q, 2, dev, sizeof dev, SQLITE_STATIC);
    assert(sqlite3_step(q) == SQLITE_DONE);
    sqlite3_finalize(q);
}

static void remote_rows_open(void) {
    unsigned char pt[16];
    char err[200];
    sqlite3_stmt *q = NULL;
    sqlite3 *db = pic_userdb(NULL, 0);
    assert(sqlite3_prepare_v2(db, "SELECT sealed FROM picu_remote_key WHERE name = 'static'", -1, &q, NULL) == SQLITE_OK);
    assert(sqlite3_step(q) == SQLITE_ROW);
    assert(pic_cred_unbox("remote-key:static", sqlite3_column_blob(q, 0), (size_t)sqlite3_column_bytes(q, 0), pt, err,
                          sizeof err) == 0);
    assert(memcmp(pt, "remote-secret-16", 16) == 0);
    sqlite3_finalize(q);
    assert(sqlite3_prepare_v2(db, "SELECT sealed FROM picu_remote_device", -1, &q, NULL) == SQLITE_OK);
    assert(sqlite3_step(q) == SQLITE_ROW);
    assert(pic_cred_unbox("remote-device:abababababababababababababababab", sqlite3_column_blob(q, 0),
                          (size_t)sqlite3_column_bytes(q, 0), pt, err, sizeof err) == 0);
    assert(memcmp(pt, "device-json-16b!", 16) == 0);
    sqlite3_finalize(q);
}

/* Where the master key comes from: a new store's key kept by the platform
 * (no passphrase asked, kdf none), a refusing source, pic_cred_quiet, a
 * rekey each way with every sealed row still opening and the old source
 * dropped, and the offer to stop asking for a typed passphrase. */
static void test_sources(void) {
    pic_platform p = *pic_platform_host();
    char key[256], err[256] = "", source[32], kdf[32];
    int skipped = -1;
    sqlite3 *db = pic_userdb(NULL, 0);
    p.secret_key = vault_key;
    p.secret_keep = vault_keep;
    p.secret_drop = vault_drop;
    pic_platform_set(&p);
    passphrase = "correct horse";
    pic_cred_lock();
    assert(sqlite3_exec(db, "DELETE FROM picu_credential_key; DELETE FROM picu_credential; DELETE FROM picu_setting",
                        NULL, NULL, NULL) == SQLITE_OK);

    /* A refusing source: no store is made, and nothing is half-written. */
    vault_locked = 1;
    asked = 0;
    assert(pic_cred_login("anthropic", "sk-ant-vault-0001", err, sizeof err) == -1 && strstr(err, "vault is locked"));
    assert(pic_cred_state() == PIC_CRED_NEW && asked == 0);
    assert(pic_cred_quiet(err, sizeof err) == -1);
    vault_locked = 0;

    /* New: the platform keeps a random key; nothing is asked. */
    assert(pic_cred_quiet(err, sizeof err) == 0 && asked == 0 && vault_has);
    record(source, sizeof source, kdf, sizeof kdf);
    assert(strcmp(source, "vault") == 0 && strcmp(kdf, "none") == 0);
    assert(strcmp(pic_cred_source_name(), "vault") == 0);
    assert(pic_cred_login("anthropic", "sk-ant-vault-0001", err, sizeof err) == 0);
    remote_row_put();
    pic_cred_lock();
    assert(pic_cred_state() == PIC_CRED_LOCKED);
    assert(pic_cred_quiet(err, sizeof err) == 0 && asked == 0);
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0);
    assert(strcmp(key, "sk-ant-vault-0001") == 0);
    pic_cred_lock();
    vault_locked = 1;
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == -1 &&
           strstr(err, "vault is locked"));
    vault_locked = 0;
    assert(pic_cred_rekey("vault", source, sizeof source, &skipped, err, sizeof err) == 2);
    puts("ok a key the platform keeps: no passphrase, a locked source refused");

    /* To a passphrase: every row reseals, the vault's key is dropped. */
    vault_drops = 0;
    assert(pic_cred_rekey("passphrase", source, sizeof source, &skipped, err, sizeof err) == 0);
    assert(strcmp(source, "passphrase") == 0 && skipped == 0 && vault_drops == 1 && !vault_has && asked == 1);
    record(source, sizeof source, kdf, sizeof kdf);
    assert(strcmp(source, "passphrase") == 0 && strcmp(kdf, "pbkdf2-sha256") == 0);
    pic_cred_lock();
    assert(pic_cred_quiet(err, sizeof err) == 1 && asked == 1); /* a passphrase store asks nothing quietly */
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0 && asked == 2);
    assert(strcmp(key, "sk-ant-vault-0001") == 0);
    remote_rows_open();
    passphrase = "wrong horse";
    pic_cred_lock();
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == -1);
    passphrase = "correct horse";
    puts("ok rekey to a passphrase: credentials and remote rows still open");

    /* The offer: due after a typed unlock, gone once declined. */
    pic_cred_lock();
    typed_pass = 1;
    assert(pic_cred_unlock(err, sizeof err) == 0 && pic_cred_offer_due() == 1);
    pic_cred_offer_answer(0);
    assert(pic_cred_offer_due() == 0);
    pic_cred_lock();
    assert(pic_cred_unlock(err, sizeof err) == 0 && pic_cred_offer_due() == 0);
    typed_pass = 0;
    puts("ok the offer to stop asking is made once, and a no is remembered");

    /* Back to the platform's own choice (NULL: the offer's yes), rows again; a wrong passphrase
     * cannot start one. cred.c names no source of the platform's. */
    pic_cred_lock();
    passphrase = "wrong horse";
    assert(pic_cred_rekey(NULL, source, sizeof source, &skipped, err, sizeof err) == -1 && !vault_has);
    passphrase = "correct horse";
    assert(pic_cred_rekey(NULL, source, sizeof source, &skipped, err, sizeof err) == 0 && vault_has);
    assert(strcmp(source, "vault") == 0 && skipped == 0);
    pic_cred_lock();
    asked = 0;
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0 && asked == 0);
    assert(strcmp(key, "sk-ant-vault-0001") == 0);
    remote_rows_open();
    /* A refused target leaves the store as it was. */
    vault_locked = 1;
    assert(pic_cred_rekey("elsewhere", source, sizeof source, &skipped, err, sizeof err) == -1);
    vault_locked = 0;
    pic_cred_lock();
    assert(pic_cred_get("anthropic", "PIC_TEST_ENV_KEY", "", key, sizeof key, err, sizeof err) == 0);
    /* Another pic moved the key after this one unlocked: this rekey stops, changing nothing. */
    {
        sqlite3_stmt *q = NULL;
        unsigned char other[PIC_CRED_KEY] = {9}, ver[20 + PIC_CRED_OVERHEAD];
        assert(pic_cred_unlock(err, sizeof err) == 0);
        assert(pic_cred_seal(other, "verifier:picu_credential_key", "pic credential store", 20, ver) == 0);
        assert(sqlite3_prepare_v2(db, "UPDATE picu_credential_key SET verifier = ?1", -1, &q, NULL) == SQLITE_OK);
        sqlite3_bind_blob(q, 1, ver, sizeof ver, SQLITE_STATIC);
        assert(sqlite3_step(q) == SQLITE_DONE);
        sqlite3_finalize(q);
        vault_drops = 0;
        assert(pic_cred_rekey("passphrase", source, sizeof source, &skipped, err, sizeof err) == -1 &&
               strstr(err, "another pic moved"));
        assert(vault_has && vault_drops == 0);
        record(source, sizeof source, kdf, sizeof kdf);
        assert(strcmp(source, "vault") == 0);
    }
    puts("ok rekey back to the platform's source; a refused one, or one another pic overtook, changes nothing");

    assert(sqlite3_exec(db, "DELETE FROM picu_remote_key; DELETE FROM picu_remote_device", NULL, NULL, NULL) == SQLITE_OK);
    pic_cred_lock();
    pic_platform_set(NULL);
}


static int count_rows(const char *sql) {
    sqlite3_stmt *q = NULL;
    int n = -1;
    if (sqlite3_prepare_v2(pic_userdb(NULL, 0), sql, -1, &q, NULL) == SQLITE_OK && sqlite3_step(q) == SQLITE_ROW) {
        n = sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    return n;
}

/* A forgotten passphrase: reset forgets the master key and every sealed row, remote control's
 * included, and keeps the rest; the next login makes a new store. The passphrase given over
 * RPC (unlock_with) opens a store, refuses a wrong one, and makes a new store. */
static void test_reset(void) {
    pic_platform p = *pic_platform_host();
    char err[256] = "", *v;
    int created = -1;
    unsigned char sealed[8 + PIC_CRED_OVERHEAD];
    sqlite3_stmt *q = NULL;
    p.secret_key = test_secret;
    p.secret_keep = NULL; /* a passphrase store */
    pic_platform_set(&p);
    pic_cred_lock();
    assert(pic_cred_reset(err, sizeof err) == 0); /* the earlier cases' store, gone */
    passphrase = "the old one";
    assert(pic_cred_login("acme", "sk-reset-sentinel-1", err, sizeof err) == 0);
    assert(pic_cred_box("remote-key:static", "12345678", 8, sealed, err, sizeof err) == 0);
    assert(sqlite3_prepare_v2(pic_userdb(NULL, 0), "INSERT INTO picu_remote_key(name, sealed, created_ms) VALUES('static', ?1, 1);"
                              , -1, &q, NULL) == SQLITE_OK);
    sqlite3_bind_blob(q, 1, sealed, sizeof sealed, SQLITE_STATIC);
    assert(sqlite3_step(q) == SQLITE_DONE);
    sqlite3_finalize(q);
    assert(sqlite3_exec(pic_userdb(NULL, 0), "INSERT INTO picu_remote_device(id, sealed, paired_ms) VALUES(x'01', x'00', 1)",
                        NULL, NULL, NULL) == SQLITE_OK);
    assert(pic_setting_set("activeKey:acme", "default") == 0 && pic_setting_set("activeKey:other", "env") == 0);
    assert(pic_setting_set("defaultModel", "acme/m") == 0 && pic_trust_set("/tmp/reset-ws", 1) == 0);

    assert(pic_cred_reset(err, sizeof err) == 0);
    assert(pic_cred_state() == PIC_CRED_NEW && !pic_cred_stored("acme"));
    assert(count_rows("SELECT count(*) FROM picu_credential_key") == 0);
    assert(count_rows("SELECT count(*) FROM picu_remote_key") == 0);
    assert(count_rows("SELECT count(*) FROM picu_remote_device") == 0);
    assert((v = pic_setting("activeKey:acme")) == NULL);
    assert((v = pic_setting("activeKey:other")) && strcmp(v, "env") == 0);
    free(v);
    assert((v = pic_setting("defaultModel")) && strcmp(v, "acme/m") == 0);
    free(v);
    assert(pic_trust_get("/tmp/reset-ws") == 1);

    /* The next login makes a new store under a new passphrase. */
    passphrase = "the new one";
    assert(pic_cred_login("acme", "sk-reset-sentinel-2", err, sizeof err) == 0);
    pic_cred_lock();
    assert(pic_cred_unlock_with("the old one", 11, &created, err, sizeof err) == -1 && strstr(err, "wrong passphrase"));
    assert(pic_cred_unlock_with("the new one", 11, &created, err, sizeof err) == 0 && created == 0);
    assert(pic_cred_reset(err, sizeof err) == 0);
    assert(pic_cred_unlock_with("made over rpc", 13, &created, err, sizeof err) == 0 && created == 1);
    assert(pic_cred_state() == PIC_CRED_OPEN);
    assert(pic_cred_reset(err, sizeof err) == 0);
    passphrase = "correct horse";
    pic_platform_set(NULL);
    puts("ok reset: the master key and every sealed row forgotten, settings and trust kept; unlock with a given passphrase");
}

int main(void) {
    test_round_trip();
    test_tamper();
    test_nonces();
    test_kdf();
    test_store();
    test_named();
    test_scrub();
    test_sources();
    test_reset();
    pic_userdb_close();
    return 0;
}