Skip to content
pi-c Documentation
Login

Documentation

/* Exact-capacity tests for the parsers and decoders that fill a caller's buffer. A sanitizer only
 * sees a write that happens, and most tests hand these functions generous stack buffers, where an
 * off-by-one lands in slack nobody watches. Here each output goes to a heap buffer of exactly the
 * size it is documented to need, so a single byte more is an ASan report, and, where the function
 * takes a capacity, to one byte less, which it must refuse (or cut) without touching memory beyond.
 * Built with the dev sanitizers: `make test-capacity`. Each case names the function it covers. */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cred.h"
#include "endpoints.h"
#include "http.h"
#include "image.h"
#include "keyhealth.h"
#include "models.h"
#include "noise.h"
#include "oauth.h"
#include "prompts.h"
#include "provider_http.h"
#include "sqlar.h"
#include "sqlite3.h"
#include "sse.h"
#include "toolreg.h"
#include "tui/atfile.h"
#include "tui/keymap.h"
#include "tui/mjson.h"
#include "tui/panel.h"
#include "tui/term.h"
#include "tui/theme.h"
#include "tui/view.h"
#include "webfetch.h"
#include "webpush.h"

/* provider_http.c waits and tells the journal between tries; nothing here makes a request, so the
 * journal's side (events.c, and the store under it) is not linked. */
void pic_ev_retry_wait(pic_store *s, int attempt, int max_attempts, long delay_ms, const char *error) {
    (void)s, (void)attempt, (void)max_attempts, (void)delay_ms, (void)error;
}

/* A heap buffer of exactly N bytes (never 0), filled so a short write shows. */
static unsigned char *hb(size_t n) {
    unsigned char *p = malloc(n ? n : 1);
    assert(p);
    memset(p, 0xa5, n ? n : 1);
    return p;
}

static void seq(unsigned char *b, size_t n, unsigned char from) {
    for (size_t i = 0; i < n; i++) {
        b[i] = (unsigned char)(from + i);
    }
}

/* ---- noise: the handshakes ---------------------------------------------------------- */

#define PAY1 "twenty bytes of data"
#define PAY2 "reply: seventeen+"

typedef struct {
    pic_noise_keypair pic, phone, pre;
    unsigned char prologue[4], bind[7];
} keys;

static void keys_make(keys *k) {
    unsigned char b[32];
    seq(b, 32, 0x01);
    assert(pic_noise_keypair_make(&k->pic, b) == 0);
    seq(b, 32, 0x21);
    assert(pic_noise_keypair_make(&k->phone, b) == 0);
    seq(b, 32, 0xd1);
    assert(pic_noise_keypair_make(&k->pre, b) == 0);
    memcpy(k->prologue, "pro!", 4);
    memcpy(k->bind, "bind-id", 7);
}

static void pair(const keys *k, pic_noise_hs *I, pic_noise_hs *R) {
    pic_noise_hs_init(I, 1, &k->phone, k->pic.pub, NULL, k->prologue, sizeof k->prologue);
    pic_noise_hs_init(R, 0, &k->pic, NULL, NULL, k->prologue, sizeof k->prologue);
}

/* A message 1 (into M, *MN bytes) with I left after it, and R left after reading it. */
static void through1(const keys *k, pic_noise_hs *I, pic_noise_hs *R, unsigned char *m, size_t *mn) {
    unsigned char pl[64];
    size_t n;
    pair(k, I, R);
    assert(pic_noise_write1(I, PAY1, strlen(PAY1), m, 1024, mn) == 0);
    assert(pic_noise_read1(R, m, *mn, pl, sizeof pl, &n) == 0);
}

static void noise_ik(void) {
    keys k;
    pic_noise_hs I, R;
    unsigned char big[1024], m1[1024], m2[1024], *out;
    size_t m1n, m2n, n, p1 = strlen(PAY1), p2 = strlen(PAY2);
    keys_make(&k);

    /* pic_noise_write1: e, s, tag, the payload and its tag: exactly that, and one byte less refused */
    pair(&k, &I, &R);
    assert(pic_noise_write1(&I, PAY1, p1, big, sizeof big, &m1n) == 0);
    pair(&k, &I, &R);
    out = hb(m1n);
    assert(pic_noise_write1(&I, PAY1, p1, out, m1n, &n) == 0 && n == m1n);
    free(out);
    pair(&k, &I, &R);
    out = hb(m1n - 1);
    assert(pic_noise_write1(&I, PAY1, p1, out, m1n - 1, &n) == -1);
    free(out);
    pair(&k, &I, &R);
    out = hb(0);
    assert(pic_noise_write1(&I, "", 0, out, 0, &n) == -1);
    free(out);

    /* pic_noise_read1: the payload only: exactly its length, and one byte less refused */
    through1(&k, &I, &R, m1, &m1n);
    pair(&k, &I, &R);
    assert(pic_noise_write1(&I, PAY1, p1, m1, sizeof m1, &m1n) == 0);
    out = hb(p1);
    assert(pic_noise_read1(&R, m1, m1n, out, p1, &n) == 0 && n == p1 && memcmp(out, PAY1, p1) == 0);
    free(out);
    pair(&k, &I, &R);
    assert(pic_noise_write1(&I, PAY1, p1, m1, sizeof m1, &m1n) == 0);
    out = hb(p1 - 1);
    assert(pic_noise_read1(&R, m1, m1n, out, p1 - 1, &n) == -1);
    free(out);
    pair(&k, &I, &R);
    assert(pic_noise_write1(&I, "", 0, m1, sizeof m1, &m1n) == 0); /* an empty payload into nothing */
    out = hb(0);
    assert(pic_noise_read1(&R, m1, m1n, out, 0, &n) == 0 && n == 0);
    free(out);

    /* pic_noise_write2 */
    through1(&k, &I, &R, m1, &m1n);
    assert(pic_noise_write2(&R, PAY2, p2, big, sizeof big, &m2n) == 0);
    through1(&k, &I, &R, m1, &m1n);
    out = hb(m2n);
    assert(pic_noise_write2(&R, PAY2, p2, out, m2n, &n) == 0 && n == m2n);
    free(out);
    through1(&k, &I, &R, m1, &m1n);
    out = hb(m2n - 1);
    assert(pic_noise_write2(&R, PAY2, p2, out, m2n - 1, &n) == -1);
    free(out);

    /* pic_noise_read2 */
    through1(&k, &I, &R, m1, &m1n);
    assert(pic_noise_write2(&R, PAY2, p2, m2, sizeof m2, &m2n) == 0);
    out = hb(p2);
    assert(pic_noise_read2(&I, m2, m2n, out, p2, &n) == 0 && n == p2 && memcmp(out, PAY2, p2) == 0);
    free(out);
    through1(&k, &I, &R, m1, &m1n);
    assert(pic_noise_write2(&R, PAY2, p2, m2, sizeof m2, &m2n) == 0);
    out = hb(p2 - 1);
    assert(pic_noise_read2(&I, m2, m2n, out, p2 - 1, &n) == -1);
    free(out);
    puts("ok pic_noise_write1, read1, write2, read2 at their exact capacity");
}

static void noise_prekey(void) {
    keys k;
    pic_noise_hs I, R;
    unsigned char big[1024], m[1024], *out;
    size_t mn, used, n, pn = strlen(PAY1);
    keys_make(&k);
#define PK_PAIR()                                                                                        \
    do {                                                                                                 \
        pic_noise_hs_init_prekey(&I, 1, &k.phone, k.pic.pub, k.prologue, sizeof k.prologue);           \
        pic_noise_hs_init_prekey(&R, 0, &k.pic, NULL, k.prologue, sizeof k.prologue);                  \
    } while (0)
    PK_PAIR();
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, big, sizeof big, &mn) == 0);
    /* pic_noise_write1_prekey */
    PK_PAIR();
    out = hb(mn);
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, out, mn, &n) == 0 && n == mn);
    free(out);
    PK_PAIR();
    out = hb(mn - 1);
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, out, mn - 1, &n) == -1);
    free(out);
    /* pic_noise_read1_begin on a message that is exactly its head, and finish into the payload alone */
    PK_PAIR();
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, m, sizeof m, &mn) == 0);
    {
        unsigned char *exact = hb(mn); /* the message in a buffer of its own length */
        memcpy(exact, m, mn);
        assert(pic_noise_read1_begin(&R, exact, mn, &used) == 0);
        out = hb(pn);
        assert(pic_noise_read1_finish(&R, exact + used, mn - used, &k.pre, k.bind, sizeof k.bind, out, pn, &n) == 0 &&
               n == pn && memcmp(out, PAY1, pn) == 0);
        free(out);
        PK_PAIR();
        assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, m, sizeof m, &mn) == 0);
        memcpy(exact, m, mn);
        assert(pic_noise_read1_begin(&R, exact, mn, &used) == 0);
        out = hb(pn - 1);
        assert(pic_noise_read1_finish(&R, exact + used, mn - used, &k.pre, k.bind, sizeof k.bind, out, pn - 1, &n) == -1);
        free(out);
        free(exact);
    }
    puts("ok pic_noise_write1_prekey, read1_begin, read1_finish at their exact capacity");
}

/* ---- noise: the transport ------------------------------------------------------------- */

static void noise_transport(void) {
    pic_noise_transport s, r;
    unsigned char sid[PIC_NOISE_SID], up[32], down[32], *data, *rec, *out;
    size_t sizes[] = {0, 1, 100, PIC_NOISE_CHUNK - 1, PIC_NOISE_CHUNK}, n;
    int flag, gap;
    seq(sid, sizeof sid, 1);
    seq(up, 32, 40);
    seq(down, 32, 80);
    pic_noise_transport_init(&s, 0, sid, up, down);
    pic_noise_transport_init(&r, 1, sid, up, down);
    data = hb(PIC_NOISE_CHUNK + 1);
    seq(data, PIC_NOISE_CHUNK + 1, 7);
    for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
        /* pic_noise_record: 1 + sid + counter + flag + data + tag, no more */
        size_t want = 1 + PIC_NOISE_SID + 8 + 1 + sizes[i] + PIC_NOISE_TAG;
        rec = hb(want);
        assert(pic_noise_record(&s, 1, data, sizes[i], rec) == want);
        /* pic_noise_open_record: into PIC_NOISE_CHUNK exactly */
        out = hb(PIC_NOISE_CHUNK);
        assert(pic_noise_open_record(&r, rec, want, &flag, out, &n, &gap) == 0 && flag == 1 && n == sizes[i] &&
               memcmp(out, data, n) == 0);
        free(out);
        free(rec);
    }
    /* a longer chunk is cut to PIC_NOISE_CHUNK, still inside the documented record size */
    rec = hb(PIC_NOISE_RECORD_CAP);
    assert(pic_noise_record(&s, 0, data, PIC_NOISE_CHUNK + 1, rec) == PIC_NOISE_RECORD_CAP);
    out = hb(PIC_NOISE_CHUNK);
    assert(pic_noise_open_record(&r, rec, PIC_NOISE_RECORD_CAP, &flag, out, &n, &gap) == 0 && n == PIC_NOISE_CHUNK);
    free(out);
    /* one byte over the largest record is refused, read from a buffer of exactly that length */
    free(rec);
    rec = hb(PIC_NOISE_RECORD_CAP + 1);
    out = hb(PIC_NOISE_CHUNK);
    assert(pic_noise_open_record(&r, rec, PIC_NOISE_RECORD_CAP + 1, &flag, out, &n, &gap) == -1);
    free(out);
    free(rec);
    free(data);
    puts("ok pic_noise_record and pic_noise_open_record at the largest record");
}

static void noise_small(void) {
    unsigned char sid[PIC_NOISE_SID], msg[40], *out, *in, mb[16], pub[PIC_NOISE_PUB], ps[32], tok[32], sig[64];
    unsigned char back[16], pub2[PIC_NOISE_PUB], ps2[32];
    uint64_t exp;
    pic_noise_keypair kp;
    size_t n;
    seq(sid, sizeof sid, 1);
    seq(msg, sizeof msg, 9);
    /* pic_noise_head: 1 + sid + message */
    for (size_t len = 0; len <= sizeof msg; len += 20) {
        out = hb(1 + PIC_NOISE_SID + len);
        assert(pic_noise_head(PIC_NOISE_REC_M1, sid, msg, len, out) == 1 + PIC_NOISE_SID + len);
        free(out);
    }
    /* pic_noise_offer and pic_noise_offer_read: PIC_NOISE_OFFER bytes */
    seq(mb, 16, 1);
    seq(ps, 32, 50);
    seq(tok, 32, 3);
    seq(sig, 32, 3);
    assert(pic_noise_keypair_make(&kp, tok) == 0);
    memcpy(pub, kp.pub, sizeof pub);
    out = hb(PIC_NOISE_OFFER);
    pic_noise_offer(mb, pub, ps, 1800000000u, out);
    in = hb(PIC_NOISE_OFFER);
    memcpy(in, out, PIC_NOISE_OFFER);
    assert(pic_noise_offer_read(in, PIC_NOISE_OFFER, back, pub2, ps2, &exp) == 0 && exp == 1800000000u);
    free(out);
    free(in);
    /* pic_noise_es256: 64 bytes */
    {
        unsigned char *s64 = hb(64);
        assert(pic_noise_es256(tok, "header.claims", s64) == 0);
        free(s64);
    }
    /* pic_noise_webpush: LEN + 103 bytes */
    for (size_t len = 0; len <= 200; len += 100) {
        unsigned char salt[16], auth[16], *pt = hb(len + 1), *body = hb(len + 103);
        pic_noise_keypair as, ua;
        seq(salt, 16, 1);
        seq(auth, 16, 2);
        seq(tok, 32, 11);
        assert(pic_noise_keypair_make(&as, tok) == 0);
        seq(tok, 32, 61);
        assert(pic_noise_keypair_make(&ua, tok) == 0);
        n = pic_noise_webpush(&as, salt, ua.pub, auth, pt, len, body);
        assert(n == len + 103);
        free(pt);
        free(body);
    }
    puts("ok pic_noise_head, offer, offer_read, es256 and webpush at their exact sizes");
}

/* ---- base64 ---------------------------------------------------------------------------- */

static void b64(void) {
    unsigned char raw[64], *dec;
    char *enc, big[256];
    for (size_t n = 0; n <= 50; n++) {
        size_t el;
        long dn;
        seq(raw, n, 0xf0);
        /* pic_b64u_enc: its length and a NUL, no padding */
        el = (n * 4 + 2) / 3;
        enc = (char *)hb(el + 1);
        assert(pic_b64u_enc(raw, n, enc) == el && enc[el] == '\0');
        memcpy(big, enc, el + 1);
        free(enc);
        /* pic_b64u_dec: exactly n bytes, and one byte less refused */
        dec = hb(n);
        assert(pic_b64u_dec(big, el, dec, n) == (long)n && memcmp(dec, raw, n) == 0);
        free(dec);
        if (n) {
            dec = hb(n - 1);
            assert(pic_b64u_dec(big, el, dec, n - 1) == -1);
            free(dec);
        }
        /* pic_base64_encode: 4 * ((n + 2) / 3) + 1 bytes with padding */
        el = 4 * ((n + 2) / 3);
        enc = (char *)hb(el + 1);
        assert(pic_base64_encode(raw, n, enc) == el && enc[el] == '\0');
        memcpy(big, enc, el + 1);
        free(enc);
        /* pic_base64_decode has no capacity argument: it must write only the n bytes it returns,
         * padded or not, though the header promises 3 * (len / 4) + 3 */
        dec = hb(n);
        dn = (long)pic_base64_decode(big, el, dec);
        assert(dn == (long)n && memcmp(dec, raw, n) == 0);
        free(dec);
        dec = hb(n);
        while (el && big[el - 1] == '=') {
            el--;
        }
        dn = (long)pic_base64_decode(big, el, dec);
        assert(dn == (long)n && memcmp(dec, raw, n) == 0);
        free(dec);
    }
    puts("ok pic_b64u_enc, pic_b64u_dec, pic_base64_encode and pic_base64_decode at their exact sizes");
}


/* ---- web push ----------------------------------------------------------------------------- */

static void webpush(void) {
    unsigned char priv[PIC_WEBPUSH_PRIV], auth[PIC_WEBPUSH_AUTH];
    char *out, big[512];
    int n, m;
    seq(priv, sizeof priv, 3);
    seq(auth, sizeof auth, 9);
    /* pic_webpush_origin: its length and a NUL, and one byte less is refused */
    {
        static const char *const urls[] = {"https://push.example.com/send/abc", "https://push.example.com:8443/x",
                                           "http://127.0.0.1:8080/p"};
        for (size_t i = 0; i < sizeof urls / sizeof urls[0]; i++) {
            n = pic_webpush_origin(urls[i], big, sizeof big);
            assert(n > 0);
            out = (char *)hb((size_t)n + 1);
            assert(pic_webpush_origin(urls[i], out, (size_t)n + 1) == n && out[n] == '\0');
            free(out);
            out = (char *)hb((size_t)n);
            assert(pic_webpush_origin(urls[i], out, (size_t)n) == -1);
            free(out);
        }
    }
    /* pic_webpush_authorization: the whole header value; claims of the largest size allowed */
    {
        char aud[513], sub[513];
        memset(aud, 'a', 512);
        aud[512] = '\0';
        memset(sub, 's', 512);
        sub[512] = '\0';
        for (int big_claims = 0; big_claims < 2; big_claims++) {
            const char *a = big_claims ? aud : "https://push.example.com", *b = big_claims ? sub : "mailto:[email protected]";
            char *ref = malloc(4096);
            assert(ref);
            n = pic_webpush_authorization(priv, a, 1800000000, b, ref, 4096);
            assert(n > 0);
            free(ref);
            out = (char *)hb((size_t)n + 1);
            m = pic_webpush_authorization(priv, a, 1800000000, b, out, (size_t)n + 1);
            assert(m == n && out[n] == '\0');
            free(out);
            out = (char *)hb((size_t)n);
            assert(pic_webpush_authorization(priv, a, 1800000000, b, out, (size_t)n) == -1);
            free(out);
        }
    }
    /* pic_webpush_topic: PIC_WEBPUSH_TOPIC bytes, 22 characters and the NUL */
    out = (char *)hb(PIC_WEBPUSH_TOPIC);
    pic_webpush_topic(auth, "session-one", out);
    assert(strlen(out) == PIC_WEBPUSH_TOPIC - 1);
    free(out);
    puts("ok pic_webpush_origin, pic_webpush_authorization and pic_webpush_topic at their exact sizes");
}

/* ---- server-sent events ------------------------------------------------------------------- */

static int sse_count;
static size_t sse_last;

static int sse_on(void *ctx, const char *event, const char *data, size_t n) {
    (void)ctx;
    (void)event;
    assert(strlen(data) == n);
    sse_count++;
    sse_last = n;
    return 0;
}

/* Feeds TEXT from a buffer of exactly its length. */
static int sse_feed_exact(pic_sse *p, const char *text) {
    size_t n = strlen(text);
    char *b = (char *)hb(n);
    int rc;
    memcpy(b, text, n);
    rc = pic_sse_feed(p, b, n);
    free(b);
    return rc;
}

static void sse(void) {
    pic_sse p;
    char line[200], name[80];
    /* data_cap: an event's data, with a newline after each line, fills data_cap bytes exactly */
    assert(pic_sse_init(&p, 128, 16, sse_on, NULL) == 0);
    sse_count = 0;
    assert(sse_feed_exact(&p, "data: 123456789012345\n\n") == 0 && sse_count == 1 && sse_last == 15);
    assert(sse_feed_exact(&p, "data: 1234567890123456\n\n") == -1); /* 16 bytes and its LF: one over */
    pic_sse_free(&p);
    assert(pic_sse_init(&p, 128, 16, sse_on, NULL) == 0);
    assert(sse_feed_exact(&p, "data: 1234567\ndata: 1234567\n\n") == 0 && sse_last == 15); /* 8 + 8 = 16 with the LFs */
    pic_sse_free(&p);
    /* line_cap: a line of exactly that many bytes, and one more */
    assert(pic_sse_init(&p, 32, 64, sse_on, NULL) == 0);
    memset(line, 'x', 32);
    line[32] = '\n';
    line[33] = '\0';
    assert(sse_feed_exact(&p, line) == 0);
    memset(line, 'x', 33);
    line[33] = '\n';
    line[34] = '\0';
    assert(sse_feed_exact(&p, line) == -1);
    pic_sse_free(&p);
    /* the event name and the id fields hold 63 characters and a NUL */
    assert(pic_sse_init(&p, 256, 64, sse_on, NULL) == 0);
    (void)snprintf(name, sizeof name, "event: %.63s\ndata: x\n\n", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
    assert(sse_feed_exact(&p, name) == 0);
    (void)snprintf(name, sizeof name, "event: %.64s\ndata: x\n\n", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
    assert(sse_feed_exact(&p, name) == -1);
    pic_sse_free(&p);
    assert(pic_sse_init(&p, 256, 64, sse_on, NULL) == 0);
    (void)snprintf(name, sizeof name, "id: %.63s\n", "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
    assert(sse_feed_exact(&p, name) == 0 && strlen(p.last_id) == 63);
    (void)snprintf(name, sizeof name, "id: %.64s\n", "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
    assert(sse_feed_exact(&p, name) == 0 && strlen(p.last_id) == 63); /* too long: kept as it was */
    pic_sse_free(&p);
    puts("ok pic_sse_feed at the exact line, data, event and id capacities");
}

/* ---- sqlar ----------------------------------------------------------------------------------- */

static void sqlar(void) {
    sqlite3 *db;
    sqlite3_stmt *q;
    size_t sizes[] = {0, 1, 100, 4096, 70000};
    assert(sqlite3_open(":memory:", &db) == SQLITE_OK);
    assert(pic_sqlar_register(db) == 0);
    for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
        size_t n = sizes[i];
        unsigned char *raw = hb(n), *packed;
        const void *blob;
        int bn;
        memset(raw, 'z', n);
        for (size_t k = 0; k < n; k += 7) {
            raw[k] = (unsigned char)k;
        }
        assert(sqlite3_prepare_v2(db, "SELECT sqlar_compress(?1)", -1, &q, NULL) == SQLITE_OK);
        sqlite3_bind_blob64(q, 1, raw, n, SQLITE_STATIC);
        assert(sqlite3_step(q) == SQLITE_ROW);
        bn = sqlite3_column_bytes(q, 0);
        blob = sqlite3_column_blob(q, 0);
        packed = hb((size_t)bn);
        if (bn) {
            memcpy(packed, blob, (size_t)bn);
        }
        sqlite3_finalize(q);
        /* sqlar_uncompress(Y, SZ): exactly SZ bytes out; a wrong SZ either way is an error, not a
         * write beyond (SZ one short makes inflate stop early, one long leaves bytes unfilled) */
        for (int delta = -1; delta <= 1; delta++) {
            long long sz = (long long)n + delta;
            if (sz < 0 || (bn == (int)n && delta != 0 && sz != bn && 0)) {
                continue;
            }
            assert(sqlite3_prepare_v2(db, "SELECT sqlar_uncompress(?1, ?2)", -1, &q, NULL) == SQLITE_OK);
            sqlite3_bind_blob64(q, 1, packed, (size_t)bn, SQLITE_STATIC);
            sqlite3_bind_int64(q, 2, sz);
            if (delta == 0) {
                assert(sqlite3_step(q) == SQLITE_ROW && sqlite3_column_bytes(q, 0) == (int)n &&
                       (n == 0 || memcmp(sqlite3_column_blob(q, 0), raw, n) == 0));
            } else if (bn != (int)n) { /* compressed: a size that is not its own is corrupt */
                assert(sqlite3_step(q) == SQLITE_ERROR);
            } else {
                (void)sqlite3_step(q); /* stored raw: the data comes back as it is whatever SZ says */
            }
            sqlite3_finalize(q);
        }
        free(packed);
        free(raw);
    }
    sqlite3_close(db);
    puts("ok sqlar_compress and sqlar_uncompress at the exact original size");
}

/* ---- the HTTP response parser ---------------------------------------------------------------- */

static int http_sink(void *ctx, const char *bytes, size_t n) {
    (void)ctx;
    (void)bytes;
    (void)n;
    return 0;
}

/* A response whose HEADER (name) has a value of LEN bytes, in a buffer of exactly its length,
 * fed whole and then one byte at a time. FIELD is a view of one of the fixed fields. */
static void http_field(const char *name, size_t len, size_t fieldcap, char *(*field)(pic_http_resp *)) {
    static pic_http_resp r;
    size_t want = len < fieldcap ? len : fieldcap - 1;
    for (int bytewise = 0; bytewise < 2; bytewise++) {
        char *head = malloc(64 + strlen(name) + len), *b;
        size_t hn, n;
        assert(head);
        hn = (size_t)snprintf(head, 64 + strlen(name), "HTTP/1.1 204 No Content\r\n%s: ", name);
        memset(head + hn, 'v', len);
        memcpy(head + hn + len, "\r\n\r\n", 4);
        n = hn + len + 4;
        b = (char *)hb(n);
        memcpy(b, head, n);
        free(head);
        pic_http_resp_init(&r, http_sink, NULL);
        r.want = "x-want";
        if (bytewise) {
            for (size_t i = 0; i < n; i++) {
                assert(pic_http_feed(&r, b + i, 1) == 0);
            }
        } else {
            assert(pic_http_feed(&r, b, n) == 0);
        }
        free(b);
        assert(strlen(field(&r)) == want);
        assert(r.status == 204);
    }
}

static char *f_retry(pic_http_resp *r) { return r->retry_after; }
static char *f_reqid(pic_http_resp *r) { return r->request_id; }
static char *f_ctype(pic_http_resp *r) { return r->content_type; }
static char *f_etag(pic_http_resp *r) { return r->etag; }
static char *f_lastmod(pic_http_resp *r) { return r->last_modified; }
static char *f_peer(pic_http_resp *r) { return r->peer; }
static char *f_wanted(pic_http_resp *r) { return r->wanted; }

static void http(void) {
    static const struct {
        const char *name;
        size_t cap;
        char *(*field)(pic_http_resp *);
    } f[] = {{"Retry-After", sizeof((pic_http_resp *)0)->retry_after, f_retry},
             {"request-id", sizeof((pic_http_resp *)0)->request_id, f_reqid},
             {"Content-Type", sizeof((pic_http_resp *)0)->content_type, f_ctype},
             {"ETag", sizeof((pic_http_resp *)0)->etag, f_etag},
             {"Last-Modified", sizeof((pic_http_resp *)0)->last_modified, f_lastmod},
             {"Pic-Peer", sizeof((pic_http_resp *)0)->peer, f_peer},
             {"X-Want", sizeof((pic_http_resp *)0)->wanted, f_wanted}};
    for (size_t i = 0; i < sizeof f / sizeof f[0]; i++) {
        /* a value one short of the field, exactly the field, one over: always a NUL inside it */
        http_field(f[i].name, f[i].cap - 2, f[i].cap, f[i].field);
        http_field(f[i].name, f[i].cap - 1, f[i].cap, f[i].field);
        http_field(f[i].name, f[i].cap, f[i].cap, f[i].field);
        http_field(f[i].name, f[i].cap + 1, f[i].cap, f[i].field);
    }
    /* the rate-limit lines: filled to the last byte that fits, then one more header dropped whole */
    {
        static pic_http_resp r;
        char *msg = malloc(4096), *b;
        size_t n = 0, total;
        int k = 0;
        assert(msg);
        n += (size_t)snprintf(msg + n, 4096 - n, "HTTP/1.1 204 No Content\r\n");
        while (n < 3500) {
            n += (size_t)snprintf(msg + n, 4096 - n, "X-RateLimit-%02d: %0*d\r\n", k, 60 + (k % 7), k);
            k++;
        }
        n += (size_t)snprintf(msg + n, 4096 - n, "\r\n");
        total = n;
        b = (char *)hb(total);
        memcpy(b, msg, total);
        free(msg);
        pic_http_resp_init(&r, http_sink, NULL);
        assert(pic_http_feed(&r, b, total) == 0 && strlen(r.ratelimit) < sizeof r.ratelimit);
        free(b);
    }
    /* a header line of exactly the line buffer's size, and one more */
    {
        static pic_http_resp r;
        size_t room = sizeof r.line, n;
        char *b;
        for (int over = 0; over < 2; over++) {
            size_t vlen = room - (sizeof "X-Long: " - 1) + (size_t)over;
            n = sizeof "HTTP/1.1 204 No Content\r\n" - 1 + (sizeof "X-Long: " - 1) + vlen + 4;
            b = (char *)hb(n);
            memcpy(b, "HTTP/1.1 204 No Content\r\nX-Long: ", sizeof "HTTP/1.1 204 No Content\r\nX-Long: " - 1);
            memset(b + n - vlen - 4, 'w', vlen);
            memcpy(b + n - 4, "\r\n\r\n", 4);
            pic_http_resp_init(&r, http_sink, NULL);
            (void)pic_http_feed(&r, b, n); /* either answer: no byte past the line buffer */
            free(b);
        }
    }
    puts("ok pic_http_feed's header fields and line buffer at their exact sizes");
}

/* ---- images ------------------------------------------------------------------------------------ */

static void image(void) {
    static const unsigned char png[] = {0x89, 'P', 'N', 'G', 13, 10, 26, 10, 0, 0, 0, 13, 'I', 'H', 'D', 'R', 0, 0, 0, 1, 0, 0, 0,
                                        1, 8, 6, 0, 0, 0, 0x1f, 0x15, 0xc4, 0x89, 0, 0, 0, 13, 'I', 'D', 'A', 'T', 0x78, 0x9c, 0x63,
                                        0, 1, 0, 0, 5, 0, 1, 0x0d, 0x0a, 0x2d, 0xb4, 0, 0, 0, 0, 'I', 'E', 'N', 'D', 0xae, 0x42, 0x60, 0x82};
    static const unsigned char gif[] = "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";
    static const unsigned char jpeg[] = {0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 16, 0, 32, 1, 1, 0x11, 0, 0xff, 0xd9};
    static const unsigned char webp_x[] = {'R', 'I', 'F', 'F', 22, 0, 0, 0, 'W', 'E', 'B', 'P', 'V', 'P', '8', 'X', 10, 0, 0, 0,
                                           0, 0, 0, 0, 1, 0, 0, 2, 0, 0};
    static const unsigned char webp_l[] = {'R', 'I', 'F', 'F', 22, 0, 0, 0, 'W', 'E', 'B', 'P', 'V', 'P', '8', 'L', 10, 0, 0, 0,
                                           0x2f, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    static const unsigned char webp_s[] = {'R', 'I', 'F', 'F', 22, 0, 0, 0, 'W', 'E', 'B', 'P', 'V', 'P', '8', ' ', 10, 0, 0, 0,
                                           0, 0, 0, 0x9d, 0x01, 0x2a, 3, 0, 4, 0};
    static const unsigned char bmp[] = {'B', 'M', 58, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 40, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0,
                                        24, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    struct {
        const char *name;
        const unsigned char *b;
        size_t n;
    } fx[] = {{"png", png, sizeof png},       {"gif", gif, sizeof gif - 1},    {"jpeg", jpeg, sizeof jpeg},
              {"webp VP8X", webp_x, sizeof webp_x}, {"webp VP8L", webp_l, sizeof webp_l}, {"webp VP8", webp_s, sizeof webp_s},
              {"bmp", bmp, sizeof bmp}};
    for (size_t i = 0; i < sizeof fx / sizeof fx[0]; i++) {
        /* pic_image_sniff and pic_image_inspect read every prefix of a real header from a buffer
         * of exactly that length: a read past the end is a report */
        for (size_t len = 0; len <= fx[i].n; len++) {
            unsigned char *b = hb(len);
            pic_image img;
            char *why = (char *)hb(160);
            if (len) {
                memcpy(b, fx[i].b, len);
            }
            (void)pic_image_sniff(b, len);
            memset(&img, 0, sizeof img);
            img.data = b;
            img.len = len;
            (void)pic_image_inspect(&img, NULL, why, 160);
            free(why);
            free(b);
        }
        /* the whole header must be understood */
        {
            unsigned char *b = hb(fx[i].n);
            pic_image img;
            char *why = (char *)hb(160);
            memcpy(b, fx[i].b, fx[i].n);
            memset(&img, 0, sizeof img);
            img.data = b;
            img.len = fx[i].n;
            assert(pic_image_sniff(b, fx[i].n) != NULL);
            if (strcmp(fx[i].name, "bmp") != 0) {
                assert(pic_image_inspect(&img, NULL, why, 160) == PIC_IMAGE_OK && img.width > 0 && img.height > 0);
            }
            free(why);
            free(b);
        }
    }
    /* the reason: a buffer of exactly its length (message and NUL), and cut where it is shorter */
    {
        unsigned char *b = hb(sizeof png);
        pic_image img;
        char probe[200], *why;
        size_t need;
        memcpy(b, png, sizeof png);
        memset(&img, 0, sizeof img);
        img.data = b;
        img.len = sizeof png;
        assert(pic_image_inspect(&img, "image/jpeg", probe, sizeof probe) == PIC_IMAGE_MISMATCH);
        need = strlen(probe) + 1;
        for (size_t cap = 1; cap <= need; cap++) {
            why = (char *)hb(cap);
            assert(pic_image_inspect(&img, "image/jpeg", why, cap) == PIC_IMAGE_MISMATCH);
            assert(strlen(why) == (cap < need ? cap - 1 : need - 1));
            free(why);
        }
        img.width = img.height = 9000; /* too large: pic_image_fit's reason, in a buffer of its exact size */
        assert(pic_image_fit(&img, probe, sizeof probe) == PIC_IMAGE_TOO_LARGE);
        need = strlen(probe) + 1;
        why = (char *)hb(need);
        assert(pic_image_fit(&img, why, need) == PIC_IMAGE_TOO_LARGE && strlen(why) == need - 1);
        free(why);
        free(b);
    }
    puts("ok pic_image_sniff, pic_image_inspect and pic_image_fit on exact-length buffers");
}

/* ---- credentials and key health ------------------------------------------------------------------ */

static void cred(void) {
    unsigned char key[PIC_CRED_KEY], *pt, *box, *back, salt[16], *dk;
    char *out;
    size_t sizes[] = {0, 1, 15, 16, 17, 200}, n;
    seq(key, sizeof key, 1);
    seq(salt, sizeof salt, 5);
    for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
        n = sizes[i];
        pt = hb(n);
        seq(pt, n, 100);
        /* pic_cred_seal: N + PIC_CRED_OVERHEAD bytes; pic_cred_open: N bytes back */
        box = hb(n + PIC_CRED_OVERHEAD);
        assert(pic_cred_seal(key, "aad", pt, n, box) == 0);
        back = hb(n);
        assert(pic_cred_open(key, "aad", box, n + PIC_CRED_OVERHEAD, back) == 0 && (n == 0 || memcmp(back, pt, n) == 0));
        free(back);
        free(box);
        free(pt);
    }
    /* a sealed row shorter than its overhead is refused, read from a buffer of exactly that length */
    for (n = 0; n < PIC_CRED_OVERHEAD; n++) {
        box = hb(n);
        back = hb(1);
        assert(pic_cred_open(key, "aad", box, n, back) == -1);
        free(back);
        free(box);
    }
    /* pic_cred_kdf: the 32 bytes of a key */
    dk = hb(PIC_CRED_KEY);
    pic_cred_kdf("pass", 4, salt, sizeof salt, 2, dk);
    free(dk);
    /* pic_cred_trim: at most CAP - 1 bytes and a NUL: exactly the trimmed length + 1, and cut below it */
    {
        const char *in = " \t sk-the-key-text \r\n";
        size_t want = strlen("sk-the-key-text");
        for (size_t cap = 1; cap <= want + 3; cap++) {
            size_t got;
            out = (char *)hb(cap);
            got = pic_cred_trim(in, out, cap);
            assert(got == (cap > want ? want : cap - 1) && strlen(out) == got);
            free(out);
        }
    }
    /* pic_oauth_random: (4 * BYTES + 2) / 3 characters and a NUL */
    for (size_t bytes = 0; bytes <= 96; bytes += 8) {
        size_t cap = (bytes * 4 + 2) / 3 + 1;
        out = (char *)hb(cap);
        assert(pic_oauth_random(out, cap, bytes) == 0 && strlen(out) == cap - 1);
        free(out);
        out = (char *)hb(cap - 1);
        assert(pic_oauth_random(out, cap - 1, bytes) == -1);
        free(out);
    }
    out = (char *)hb(200);
    assert(pic_oauth_random(out, 200, 97) == -1);
    free(out);
    /* pic_oauth_pkce: two 64-byte arrays, 43 characters and a NUL each */
    {
        char *v = (char *)hb(64), *c = (char *)hb(64);
        assert(pic_oauth_pkce(v, c) == 0 && strlen(v) == 43 && strlen(c) == 43);
        free(v);
        free(c);
    }
    puts("ok pic_cred_seal, open, kdf, trim, pic_oauth_random and pkce at their exact sizes");
}

static void keyhealth(void) {
    pic_key_health h;
    long long now = 1795000000000LL;
    char probe[512], *out;
    pic_keyhealth_classify("anthropic", 429, "{}", "", "", "900", now, &h);
    /* a reason cut to its field, whatever the body says */
    {
        char body[700], msg[400];
        memset(msg, 'm', sizeof msg - 1);
        msg[sizeof msg - 1] = '\0';
        (void)snprintf(body, sizeof body, "{\"error\":{\"type\":\"x\",\"message\":\"%s\"}}", msg);
        pic_keyhealth_classify("openai", 500, body, msg, "", "", now, &h);
        assert(strlen(h.reason) < sizeof h.reason);
    }
    pic_keyhealth_classify("anthropic", 429, "{}", "", "", "900", now, &h);
    for (int which = 0; which < 5; which++) {
        size_t need;
        for (int state = 0; state < 2; state++) {
            if (state) {
                pic_keyhealth_classify("anthropic", 402, "{}", "plain words", "", "", now, &h);
            } else {
                pic_keyhealth_classify("anthropic", 429, "{}", "slow down", "", "900", now, &h);
            }
#define FMT(buf, cap)                                                                                   \
    (which == 0   ? pic_keyhealth_until(h.until_ms ? h.until_ms : now + 600000, now, buf, cap)        \
     : which == 1 ? pic_keyhealth_phrase(&h, now, buf, cap)                                             \
     : which == 2 ? pic_keyhealth_alert(&h, now, buf, cap)                                              \
     : which == 3 ? pic_keyhealth_message("anthropic", "main", &h, now, buf, cap)                       \
                  : pic_keyhealth_headline("anthropic", "main", &h, now, buf, cap))
            FMT(probe, sizeof probe);
            need = strlen(probe) + 1;
            out = (char *)hb(need);
            FMT(out, need);
            assert(strlen(out) == need - 1);
            free(out);
            if (need > 1) {
                out = (char *)hb(need - 1);
                FMT(out, need - 1);
                assert(strlen(out) == need - 2);
                free(out);
            }
        }
    }
    puts("ok the key-health sentences (until, phrase, alert, message, headline) at their exact sizes");
}

/* A function that writes a NUL-terminated string into OUT of CAP bytes: for each CAP from one more than
 * the string needs down to 0, a heap buffer of exactly CAP bytes. It holds the string when it fits and
 * the string cut to CAP - 1 bytes, NUL-terminated, when not; at CAP 0 it is not touched. CALL uses
 * `out` and `cap`; WANT is the whole string. */
#define SWEEP(want, call) SWEEP_(want, call, 1)
/* EXACT 0: a cut message may lose the newlines it ends on, so it is only a prefix of the whole. */
#define SWEEP_(want, call, exactcut)                                                                          \
    do {                                                                                                      \
        size_t w_ = strlen(want);                                                                             \
        for (size_t cap = w_ + 2;; cap--) {                                                                   \
            char *out = (char *)hb(cap);                                                                      \
            (call);                                                                                           \
            if (cap == 0) {                                                                                   \
                assert((unsigned char)out[0] == 0xa5);                                                        \
            } else if (cap > w_) {                                                                            \
                assert(strcmp(out, (want)) == 0);                                                             \
            } else {                                                                                          \
                size_t got_ = strlen(out);                                                                    \
                assert(got_ < cap && memcmp(out, (want), got_) == 0 && (!(exactcut) || got_ == cap - 1));     \
            }                                                                                                 \
            free(out);                                                                                        \
            if (cap == 0) {                                                                                   \
                break;                                                                                        \
            }                                                                                                 \
        }                                                                                                     \
    } while (0)

/* A heap copy of exactly N bytes of S, with no NUL after them (WITH_NUL: one more, the NUL). */
static char *exact(const char *s, size_t n, int with_nul) {
    char *p = (char *)hb(n + (with_nul ? 1 : 0));
    memcpy(p, s, n);
    if (with_nul) {
        p[n] = '\0';
    }
    return p;
}

/* ---- sealed rows of the store, the provider helpers, and the endpoint URL -------------------------- */

static void box_rows(void) {
    static const char locked[] = "the credential store is locked";
    char err[64];
    int created = 0;
    size_t sizes[] = {0, 1, 15, 16, 17, 200};
    pic_cred_lock();
    {
        unsigned char *out = hb(PIC_CRED_OVERHEAD + 1);
        char *e = (char *)hb(sizeof locked), *e1 = (char *)hb(sizeof locked - 1);
        assert(pic_cred_box("aad", "x", 1, out, e, sizeof locked) == -1 && strcmp(e, locked) == 0);
        assert(pic_cred_box("aad", "x", 1, out, e1, sizeof locked - 1) == -1 && strlen(e1) == sizeof locked - 2);
        assert(pic_cred_unbox("aad", out, PIC_CRED_OVERHEAD + 1, e, e1, sizeof locked - 1) == -1);
        free(e1);
        free(e);
        free(out);
    }
    assert(pic_cred_unlock_with("a pass", 6, &created, err, sizeof err) == 0);
    for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
        size_t n = sizes[i];
        unsigned char *pt = hb(n), *box = hb(n + PIC_CRED_OVERHEAD), *back = hb(n);
        seq(pt, n, 7);
        /* pic_cred_box: N + PIC_CRED_OVERHEAD bytes; pic_cred_unbox: N bytes back */
        assert(pic_cred_box("aad", pt, n, box, err, sizeof err) == 0);
        assert(pic_cred_unbox("aad", box, n + PIC_CRED_OVERHEAD, back, err, sizeof err) == 0 &&
               (n == 0 || memcmp(back, pt, n) == 0));
        /* another row's aad, or a flipped byte, refused with the message cut to a heap buffer of its size */
        {
            const char *msg = "a sealed row does not open under the store's key";
            char *e = (char *)hb(strlen(msg) + 1), *e1 = (char *)hb(strlen(msg));
            assert(pic_cred_unbox("other", box, n + PIC_CRED_OVERHEAD, back, e, strlen(msg) + 1) == -1 && strcmp(e, msg) == 0);
            box[n + PIC_CRED_OVERHEAD - 1] ^= 1;
            assert(pic_cred_unbox("aad", box, n + PIC_CRED_OVERHEAD, back, e1, strlen(msg)) == -1 &&
                   strlen(e1) == strlen(msg) - 1);
            free(e1);
            free(e);
        }
        free(back);
        free(box);
        free(pt);
    }
    /* a sealed row shorter than its overhead is refused, read from a buffer of exactly that length */
    for (size_t n = 0; n < PIC_CRED_OVERHEAD; n++) {
        unsigned char *in = hb(n), *back = hb(1);
        assert(pic_cred_unbox("aad", in, n, back, err, sizeof err) == -1);
        free(back);
        free(in);
    }
    pic_cred_lock();
    puts("ok pic_cred_box and pic_cred_unbox at their exact sizes");
}

static void provider_helpers(void) {
    char big[512];
    pic_model m;
    pic_cost c = {0.1, 0.25, 1e-7, 123456.789, 1234.5678, 1};
    pic_sbuf b;
    const pic_auth_style styles[] = {PIC_AUTH_X_API_KEY, PIC_AUTH_BEARER, PIC_AUTH_X_GOOG_API_KEY, PIC_AUTH_BASIC};

    /* pic_auth_line: every style, the basic one's base64 of user:password included */
    for (size_t i = 0; i < sizeof styles / sizeof styles[0]; i++) {
        const char *keys[] = {"k", "sk-ant-api03-abcdefghij", "user:pass", "ab:c"};
        for (size_t j = 0; j < sizeof keys / sizeof keys[0]; j++) {
            pic_auth_line(styles[i], keys[j], big, sizeof big);
            assert(big[0]);
            SWEEP(big, pic_auth_line(styles[i], keys[j], out, cap));
        }
    }

    /* pic_json_get: the scalar as SQLite prints it, cut to the buffer */
    {
        const char *json = "{\"a\":{\"b\":\"hello, world\"},\"n\":12345.5,\"t\":true,\"z\":null,\"e\":\"\"}";
        const char *paths[] = {"$.a.b", "$.n", "$.t", "$.e"};
        for (size_t i = 0; i < sizeof paths / sizeof paths[0]; i++) {
            assert(pic_json_get(json, paths[i], big, sizeof big) == 0);
            SWEEP(big, assert(pic_json_get(json, paths[i], out, cap) == 0));
        }
        assert(pic_json_get(json, "$.z", big, sizeof big) == -1 && pic_json_get(json, "$.nope", big, sizeof big) == -1 &&
               pic_json_get("{not json", "$.a", big, sizeof big) == -1);
    }

    /* pic_model_url and pic_cost_json */
    memset(&m, 0, sizeof m);
    snprintf(m.provider, sizeof m.provider, "p");
    snprintf(m.id, sizeof m.id, "some-model-id");
    snprintf(m.base_url, sizeof m.base_url, "https://api.example.com/v1");
    {
        const char *apis[] = {"anthropic-messages", "openai-completions", "openai-responses", "google-generative-ai"};
        for (size_t i = 0; i < sizeof apis / sizeof apis[0]; i++) {
            snprintf(m.api, sizeof m.api, "%s", apis[i]);
            pic_model_url(&m, big, sizeof big);
            assert(strncmp(big, m.base_url, strlen(m.base_url)) == 0);
            SWEEP(big, pic_model_url(&m, out, cap));
        }
        /* the longest base URL and id the model holds: the Gemini URL is the one that carries both */
        memset(m.base_url, 'u', sizeof m.base_url - 1);
        memset(m.id, 'i', sizeof m.id - 1);
        pic_model_url(&m, big, sizeof big);
        SWEEP(big, pic_model_url(&m, out, cap));
    }
    pic_cost_json(&c, big, sizeof big);
    assert(strstr(big, "totalFromProvider"));
    SWEEP(big, pic_cost_json(&c, out, cap));
    c.total_from_provider = 0;
    c.total = 1e300;
    pic_cost_json(&c, big, sizeof big);
    SWEEP(big, pic_cost_json(&c, out, cap));

    /* pic_sb_add: the buffer grows by doubling from 64; fill to the last byte it holds, then one more */
    memset(&b, 0, sizeof b);
    pic_sb_add(&b, NULL, 0);
    assert(b.len == 0 && b.buf && b.buf[0] == '\0');
    memset(big, 'q', sizeof big);
    pic_sb_add(&b, big, 63); /* 63 + NUL: all 64 */
    assert(b.len == 63 && b.cap == 64 && b.buf[63] == '\0');
    pic_sb_add(&b, big, 1); /* 64 + NUL: one more than it holds */
    assert(b.len == 64 && b.cap == 128 && b.buf[64] == '\0');
    pic_sb_add(&b, big, 63); /* 127 + NUL: exactly the 128 */
    assert(b.len == 127 && b.cap == 128 && b.buf[127] == '\0' && !b.oom);
    pic_sb_add(&b, big, 300);
    assert(b.len == 427 && strlen(b.buf) == 427);
    free(b.buf);
    memset(&b, 0, sizeof b);
    pic_sb_add(&b, big, 200); /* a first piece larger than the 64 start */
    assert(b.len == 200 && b.cap == 256 && strlen(b.buf) == 200);
    {
        char *t = pic_sb_take(&b);
        assert(t && strlen(t) == 200);
        free(t);
    }
    puts("ok pic_auth_line, pic_json_get, pic_model_url, pic_cost_json and pic_sb_add at their exact sizes");
}

static void endpoint_url(void) {
    char err[256], *e, *out2;
    const char *url = "https://example.com:8443/v1///";
    const char *norm = "https://example.com:8443/v1";
    size_t n = strlen(norm);
    /* pic_endpoint_url_check: the URL without its trailing slashes and a NUL, or refused at one byte less */
    out2 = (char *)hb(n + 1);
    assert(pic_endpoint_url_check(url, out2, n + 1, err, sizeof err) == 0 && strcmp(out2, norm) == 0);
    free(out2);
    out2 = (char *)hb(n);
    memset(out2, 'z', n);
    assert(pic_endpoint_url_check(url, out2, n, err, sizeof err) == -1 && strstr(err, "longer") && out2[0] == 'z');
    free(out2);
    out2 = (char *)hb(1);
    assert(pic_endpoint_url_check(url, out2, 0, err, sizeof err) == -1);
    free(out2);
    /* the limit of the stored URL: PIC_ENDPOINT_URL_CAP - 1 bytes, and one more */
    for (size_t len = PIC_ENDPOINT_URL_CAP - 2; len <= PIC_ENDPOINT_URL_CAP; len++) {
        char *in = (char *)hb(len + 1);
        memset(in, 'a', len);
        memcpy(in, "https://h.example/", 18);
        in[len] = '\0';
        out2 = (char *)hb(PIC_ENDPOINT_URL_CAP);
        assert(pic_endpoint_url_check(in, out2, PIC_ENDPOINT_URL_CAP, err, sizeof err) == (len < PIC_ENDPOINT_URL_CAP ? 0 : -1));
        if (len < PIC_ENDPOINT_URL_CAP) {
            assert(strlen(out2) == len);
        }
        free(out2);
        free(in);
    }
    /* its messages, into a heap buffer of exactly their size and one byte less */
    {
        const char *bad[] = {"ftp://x", "https://a b/", "https://h/v1?x=1", "https://u:p@h/", "http://example.com/",
                             "https://:80/"};
        for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {
            char big[256], *dst = (char *)hb(300);
            assert(pic_endpoint_url_check(bad[i], dst, 300, big, sizeof big) == -1);
            SWEEP(big, assert(pic_endpoint_url_check(bad[i], dst, 300, out, cap) == -1));
            free(dst);
        }
    }
    e = (char *)hb(1);
    out2 = (char *)hb(300);
    assert(pic_endpoint_url_check("ftp://x", out2, 300, e, 0) == -1);
    free(out2);
    free(e);
    puts("ok pic_endpoint_url_check at its exact sizes");
}

static void oauth_param(void) {
    static const struct {
        const char *query, *name, *want;
    } t[] = {{"code=abc&state=xyz", "code", "abc"},       {"code=abc&state=xyz", "state", "xyz"},
             {"a=%41%62+c&b=1", "a", "Ab c"},             {"a=%4", "a", "%4"},
             {"a=%", "a", "%"},                           {"a=%4&b=1", "a", "%4"},
             {"a=%zz&", "a", "%zz"},                      {"a=&b=1", "a", ""},
             {"a=1", "b", NULL},                          {"aa=1&a=2", "a", "2"}};
    for (size_t i = 0; i < sizeof t / sizeof t[0]; i++) {
        char *q = exact(t[i].query, strlen(t[i].query), 1), *got = pic_oauth_param(q, t[i].name);
        assert(t[i].want ? got && strcmp(got, t[i].want) == 0 : got == NULL);
        free(got);
        free(q);
    }
    puts("ok pic_oauth_param's percent decoder at the end of its query");
}

/* ---- the terminal UI's parsers and formatters --------------------------------------------------- */

static void json_inputs(void) {
    static const char *docs[] = {
        "{\"a\":[1,2.5,-3e2,true,false,null],\"s\":\"x\\n\\u00e9\\ud83d\\ude00\\ud800\\/\",\"o\":{}}",
        "\"a string with \\u0041 and \\\\ in it\"",
        "[\"\\u12\"]",
        "\xEF\xBB\xBF{\"bom\":1}",
        "-12345678901234567890123456789012345678901234567890123456789012345678901234567890",
        "12345678901234567890123456789012345678901234567890123456789012",
        "123456789012345678901234567890123456789012345678901234567890123",
        "  [ ] ",
        "{\"a\":1,}",
        "[1 2]",
        "tru",
        "nul",
        "fals",
        "{\"k\"",
        "\"unterminated\\",
    };
    char err[64];
    for (size_t d = 0; d < sizeof docs / sizeof docs[0]; d++) {
        size_t n = strlen(docs[d]);
        /* every prefix of the document, as a heap buffer of exactly that length and no NUL after it */
        for (size_t k = 0; k <= n; k++) {
            char *in = exact(docs[d], k, 0);
            mj *v = mj_parse(in, k, err, sizeof err);
            if (v) {
                mj_free(v);
                assert(err[0] == '\0');
            } else {
                assert(err[0] != '\0' && strlen(err) < sizeof err);
            }
            free(in);
        }
        /* its message into a heap buffer of exactly its size, and one byte less */
        {
            size_t cut = n ? n - 1 : 0;
            char *in = exact(docs[d], cut, 0), big[160];
            mj *v = mj_parse(in, cut, big, sizeof big);
            if (!v) {
                SWEEP(big, mj_free(mj_parse(in, cut, out, cap)));
            } else {
                mj_free(v);
            }
            free(in);
        }
    }
    /* the whole of the first one is valid */
    {
        char *in = exact(docs[0], strlen(docs[0]), 0);
        mj *v = mj_parse(in, strlen(docs[0]), NULL, 0);
        assert(v);
        mj_free(v);
        free(in);
    }
    puts("ok mj_parse on every prefix of its documents, in buffers of exactly that length");
}

static void theme_inputs(void) {
    char big[4096];
    size_t dcap = 4096, n = 0, total = 0;
    char *doc = malloc(dcap), *in;
    tui_theme th;
    tui_color col;
    const char *colors[] = {"", "#0af", "#00aaff", "#00AAFF", "oklch(62% 0.1 200)", "oklch(0.62 0.1 200)", "okhsl(250 60% 55%)",
                            "#12", "#gggggg", "oklch(2 0 0)", "oklch(0.5 -1 0)", "okhsl(", "rgb(1,2,3)", "oklch(50% 0.1 200"};
    assert(doc);
    /* tui_color_parse: a string with its NUL, and its message cut */
    for (size_t i = 0; i < sizeof colors / sizeof colors[0]; i++) {
        in = exact(colors[i], strlen(colors[i]), 1);
        if (tui_color_parse(in, &col, big, sizeof big) != 0) {
            assert(big[0]);
            SWEEP(big, assert(tui_color_parse(in, &col, out, cap) == -1));
        }
        (void)tui_color_parse(in, &col, NULL, 0);
        free(in);
    }
    /* tui_theme_parse: a full theme of every token, as text of exactly its length */
    n += (size_t)snprintf(doc + n, dcap - n, "{\"name\":\"cap\",\"colors\":{");
    for (int t = 0; t < TUI_T_N; t++) {
        n += (size_t)snprintf(doc + n, dcap - n, "%s\"%s\":\"#%02x%02x%02x\"", t ? "," : "", tui_token_name((tui_token)t), t, 255 - t, 7);
        assert(n + 100 < dcap);
    }
    n += (size_t)snprintf(doc + n, dcap - n, "}}");
    total = n;
    in = exact(doc, total, 0);
    assert(tui_theme_parse(in, total, "cap", &th, big, sizeof big) == 0);
    free(in);
    /* every prefix of it, and the same with each token's value spoiled: the messages in exact buffers */
    for (size_t k = 0; k < total; k += 7) {
        in = exact(doc, k, 0);
        if (tui_theme_parse(in, k, "cap.json", &th, big, sizeof big) != 0) {
            assert(big[0] && strlen(big) < sizeof big);
            SWEEP_(big, assert(tui_theme_parse(in, k, "cap.json", &th, out, cap) == -1), 0);
        }
        free(in);
    }
    free(doc);
    {
        /* missing tokens, extras and bad values: the longest of the messages, whole and cut */
        static const char *bad[] = {"{\"name\":\"a/b\",\"colors\":{}}", "{\"colors\":{\"nope\":1,\"text\":\"red\"},\"x\":1}",
                                    "[1]", "{\"name\":\"n\",\"appearance\":\"x\",\"vars\":{\"a\":300},\"export\":{\"q\":1},\"colors\":{}}"};
        for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {
            size_t bn = strlen(bad[i]);
            in = exact(bad[i], bn, 0);
            assert(tui_theme_parse(in, bn, "bad.json", &th, big, sizeof big) == -1 && big[0]);
            SWEEP_(big, assert(tui_theme_parse(in, bn, "bad.json", &th, out, cap) == -1), 0);
            free(in);
        }
    }
    puts("ok tui_color_parse and tui_theme_parse, over exact-length input and into exact message buffers");
}

static void fmt_helpers(void) {
    char big[64];
    const long ms[] = {-5, 0, 999, 59999, 60000, 61500, 3599999, 3600000, 86399000, 1000000000L};
    const long long tok[] = {0, 999, 1000, 9999, 10000, 999999, 1000000, 9999999, 10000000, 123456789012LL};
    const size_t sz[] = {0, 1023, 1024, 1048575, 1048576, (size_t)1 << 40};
    for (size_t i = 0; i < sizeof ms / sizeof ms[0]; i++) {
        tui_fmt_duration(ms[i], big, sizeof big);
        SWEEP(big, tui_fmt_duration(ms[i], out, cap));
    }
    for (size_t i = 0; i < sizeof tok / sizeof tok[0]; i++) {
        tui_fmt_tokens(tok[i], big, sizeof big);
        SWEEP(big, tui_fmt_tokens(tok[i], out, cap));
    }
    for (size_t i = 0; i < sizeof sz / sizeof sz[0]; i++) {
        tui_fmt_size(sz[i], big, sizeof big);
        SWEEP(big, tui_fmt_size(sz[i], out, cap));
    }
    puts("ok tui_fmt_duration, tui_fmt_tokens and tui_fmt_size at their exact sizes");
}

static void setting_shown(void) {
    char big[128], *values[] = {"a", "b"}, *labels[] = {"Alpha", "Beta, the second"};
    tui_setting s;
    memset(&s, 0, sizeof s);
    s.def_label = "the default, worked out";
    s.values = values;
    s.labels = labels;
    s.nvalues = 2;
    s.kind = "choice";
    s.unit = "seconds";
    for (int v = 0; v < 5; v++) {
        s.value = v == 0 ? "" : v == 1 ? "a" : v == 2 ? "b" : v == 3 ? "not a choice" : "12";
        s.kind = v == 4 ? "number" : "choice";
        s.unit = v == 4 ? "seconds" : NULL;
        tui_setting_shown(&s, big, sizeof big);
        assert(big[0]);
        SWEEP(big, tui_setting_shown(&s, out, cap));
    }
    s.kind = "number";
    s.unit = "ms";
    s.value = "250";
    s.nvalues = 0;
    tui_setting_shown(&s, big, sizeof big);
    assert(strcmp(big, "250 ms") == 0);
    SWEEP(big, tui_setting_shown(&s, out, cap));
    puts("ok tui_setting_shown at its exact sizes");
}

static void term_and_keys(void) {
    char big[128];
    tui_keymap *m = tui_keymap_new();
    size_t shown = 0;
    assert(m);
    /* tui_term_done_signal: the whole sequence or nothing, never a byte past CAP */
    for (int variant = 0; variant < 2; variant++) {
        size_t want;
        if (variant) {
            setenv("VTE_VERSION", "7000", 1);
        } else {
            unsetenv("VTE_VERSION");
            setenv("TERM", "xterm-256color", 1);
        }
        want = tui_term_done_signal(big, sizeof big, 0, 0, "needs you");
        assert(want > 0 && strlen(big) == want);
        for (size_t cap = want + 2;; cap--) {
            char *out = (char *)hb(cap);
            size_t got = tui_term_done_signal(out, cap, 0, 0, "needs you");
            if (cap == 0) {
                assert(got == 0 && (unsigned char)out[0] == 0xa5);
            } else if (cap > want) {
                assert(got == want && strcmp(out, big) == 0);
            } else {
                assert(got == 0 && strlen(out) < cap);
            }
            free(out);
            if (cap == 0) {
                break;
            }
        }
        /* no signal at all: nothing written beyond the NUL, in a buffer of one byte */
        {
            char *out = (char *)hb(1);
            assert(tui_term_done_signal(out, 1, 1, 0, "x") == 0 && out[0] == '\0');
            free(out);
        }
    }
    unsetenv("VTE_VERSION");
    /* tui_keymap_keys: each action's keys, ", " between them */
    for (size_t i = 0; i < 400; i++) {
        tui_keymap_keys(m, i, big, sizeof big);
        if (big[0]) {
            shown++;
        }
        SWEEP(big, tui_keymap_keys(m, i, out, cap));
    }
    assert(shown > 20);
    tui_keymap_free(m);
    puts("ok tui_term_done_signal and tui_keymap_keys at their exact sizes");
}

static void atfile_tokens(void) {
    static const struct {
        const char *text;
        const char *query;
        int quoted, found;
        size_t start;
    } t[] = {{"see @src/ma", "src/ma", 0, 1, 4},     {"@", "", 0, 1, 0},
             {"x (@a/b", "a/b", 0, 1, 3},            {"look @\"my fi", "my fi", 1, 1, 5},
             {"@\"", "", 1, 1, 0},                   {"no token here", "", 0, 0, 0},
             {"a\n@line/two", "line/two", 0, 1, 2},  {"email@host", "", 0, 0, 0}};
    for (size_t i = 0; i < sizeof t / sizeof t[0]; i++) {
        size_t cursor = strlen(t[i].text), start = 99, qn = strlen(t[i].query);
        int quoted = -1;
        /* the text of exactly CURSOR bytes (no NUL after it), the query into exactly its size and one less */
        char *text = exact(t[i].text, cursor, 0), *q = (char *)hb(qn + 1);
        assert(atfile_token(text, cursor, &start, q, qn + 1, &quoted) == t[i].found);
        if (t[i].found) {
            assert(strcmp(q, t[i].query) == 0 && start == t[i].start && quoted == t[i].quoted);
            free(q);
            q = (char *)hb(qn);
            assert(atfile_token(text, cursor, &start, q, qn, &quoted) == 1);
            assert(qn == 0 ? (unsigned char)q[0] == 0xa5 : strlen(q) == qn - 1 && memcmp(q, t[i].query, qn - 1) == 0);
            free(q);
            q = (char *)hb(1);
            assert(atfile_token(text, cursor, &start, q, 0, &quoted) == 1 && (unsigned char)q[0] == 0xa5);
        }
        /* every cursor position of it */
        for (size_t c = 0; c <= cursor; c++) {
            char *tx = exact(t[i].text, c, 0), *qq = (char *)hb(8);
            (void)atfile_token(tx, c, &start, qq, 8, &quoted);
            free(qq);
            free(tx);
        }
        free(q);
        free(text);
    }
    puts("ok atfile_token over text of exactly the cursor's length and into exact query buffers");
}

/* ---- the URL splitters that sit in front of the network -------------------------------------- */

static int wf_started(void *ctx, const char *a, size_t n) {
    (void)ctx, (void)a, (void)n;
    return 0;
}

/* web_fetch's answer to a call whose URL is URL (a JSON string's worth of bytes, none needing escapes). */
static char *wf_call(const char *url, int *is_error) {
    pic_tool_args args;
    pic_tool_hooks h;
    size_t n = strlen(url) + 64;
    char *input = (char *)hb(n), *res;
    memset(&args, 0, sizeof args);
    memset(&h, 0, sizeof h);
    snprintf(input, n, "{\"url\":\"%s\"}", url);
    h.input = input;
    h.started = wf_started;
    res = pic_webfetch_tool.run(NULL, ".", "web_fetch", &args, &h, is_error);
    free(input);
    return res;
}

static void url_splitters(void) {
    /* wf_clean_url keeps a 4096-byte copy: a URL of 4095 bytes fits whole, 4096 does not. A host this
     * long is refused after that, and on its length, so nothing here reaches the network. */
    for (size_t len = 4094; len <= 4097; len++) {
        char *url = (char *)hb(len + 1), *res;
        int is_err = 0;
        memset(url, 'a', len);
        memcpy(url, "http://", 7);
        url[len] = '\0';
        res = wf_call(url, &is_err);
        assert(res && is_err);
        assert((len >= 4096) == (strstr(res, "control character, or is too long") != NULL));
        free(res);
        free(url);
    }
    /* bytes at or above 0x80 are written as %XX: three for one, the last of them with the NUL in the
     * 4096th byte, and one more refused */
    for (size_t k = 0; k < 3; k++) {
        size_t plain = 4088 + k; /* the cleaned URL is plain + 6 bytes, and the last needs 3 and the NUL */
        char *url = (char *)hb(plain + 3), *res;
        int is_err = 0;
        memset(url, 'a', plain);
        memcpy(url, "http://", 7);
        url[plain] = (char)0xc3;
        url[plain + 1] = (char)0xa9;
        url[plain + 2] = '\0';
        res = wf_call(url, &is_err);
        assert(res && is_err);
        assert((plain >= 4090) == (strstr(res, "control character, or is too long") != NULL));
        free(res);
        free(url);
    }
    /* pic_http_get's URL splitter: refusals come before any connection, with the message into a heap
     * buffer of exactly its size */
    {
        const char *msg = "unsupported URL";
        char *url;
        static pic_http_resp r;
        for (int i = 0; i < 10; i++) {
            const char *u[] = {"ftp://x/", "http://x", "https://", "https:///x", "http://[::1/", "http://[::1]x/", "http://:80/",
                               "http://h:99999/", "http://h:8x/", "http://h:0/"};
            char *e = (char *)hb(strlen(msg) + 1), *e1 = (char *)hb(strlen(msg));
            url = exact(u[i], strlen(u[i]), 1);
            assert(pic_http_get(NULL, url, NULL, 0, &r, 1, 1, e, strlen(msg) + 1) == -1 && strcmp(e, msg) == 0);
            assert(pic_http_get(NULL, url, NULL, 0, &r, 1, 1, e1, strlen(msg)) == -1 && strlen(e1) == strlen(msg) - 1);
            free(url);
            free(e1);
            free(e);
        }
        /* a host of 256 bytes and longer, which the 256-byte host buffer cannot hold with its NUL */
        for (size_t hn = 256; hn <= 399; hn += 143) {
            char *e = (char *)hb(strlen(msg) + 1);
            url = (char *)hb(hn + 12);
            memcpy(url, "https://", 8);
            memset(url + 8, 'h', hn);
            memcpy(url + 8 + hn, "/x", 3);
            assert(pic_http_get(NULL, url, NULL, 0, &r, 1, 1, e, strlen(msg) + 1) == -1 && strcmp(e, msg) == 0);
            free(url);
            free(e);
        }
    }
    puts("ok web_fetch's URL cleaner and the HTTP client's URL splitter at their exact sizes");
}

int main(void) {
    noise_ik();
    noise_prekey();
    noise_transport();
    noise_small();
    b64();
    webpush();
    sse();
    sqlar();
    http();
    image();
    cred();
    keyhealth();
    box_rows();
    provider_helpers();
    endpoint_url();
    oauth_param();
    json_inputs();
    theme_inputs();
    fmt_helpers();
    setting_shown();
    term_and_keys();
    atfile_tokens();
    url_splitters();
    puts("ok capacity");
    return 0;
}