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(int fresh, unsigned char *buf, size_t cap, size_t *len, int *stretch, char *err, size_t errcap) {
    size_t n = strlen(passphrase);
    (void)fresh;
    (void)err;
    (void)errcap;
    asked++;
    assert(n <= cap);
    memcpy(buf, passphrase, n);
    *len = n;
    *stretch = 1;
    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;
    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;
}

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

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

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