Skip to content
pi-c Documentation
Login

Documentation

/* libFuzzer target: SSE framer plus Messages API decoder.
 * Properties checked on every input:
 *   - no crash, leak or undefined behaviour (sanitizers);
 *   - the outcome and message do not depend on how the bytes are chunked;
 *   - a decoded message's content is a valid JSON array. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "anthropic.h"
#include "sse.h"

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);

static sqlite3 *db;

/* Returns a malloc'd canonical summary of decoding data in chunks of `chunk`. */
static char *decode(const char *bytes, size_t n, size_t chunk) {
    pic_anthropic d;
    pic_sse p;
    int rc = 0;
    char *out;
    size_t cap;
    if (pic_anthropic_init(&d, db) != 0 || pic_sse_init(&p, 4096, 1u << 16, pic_anthropic_event, &d) != 0) {
        abort();
    }
    for (size_t i = 0; i < n && rc == 0; i += chunk) {
        rc = pic_sse_feed(&p, bytes + i, n - i < chunk ? n - i : chunk);
    }
    if (rc == 0) {
        rc = pic_anthropic_finish(&d);
    }
    if (rc == 0 && d.msg.content) {
        sqlite3_stmt *st;
        if (sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1) = 'array'", -1, &st, NULL) != SQLITE_OK) {
            abort();
        }
        sqlite3_bind_text(st, 1, d.msg.content, -1, SQLITE_STATIC);
        if (sqlite3_step(st) != SQLITE_ROW || sqlite3_column_int(st, 0) != 1) {
            fprintf(stderr, "decoded content is not a JSON array: %s\n", d.msg.content);
            abort();
        }
        sqlite3_finalize(st);
    }
    cap = 64 + strlen(d.err) + (d.msg.content ? strlen(d.msg.content) : 0) + (d.msg.usage ? strlen(d.msg.usage) : 0) +
          (d.msg.stop_reason ? strlen(d.msg.stop_reason) : 0) + (d.msg.error ? strlen(d.msg.error) : 0);
    out = malloc(cap);
    if (!out) {
        abort();
    }
    (void)snprintf(out, cap, "%d|%s|%s|%s|%s|%s", rc, rc == 0 ? "" : d.err, d.msg.content ? d.msg.content : "",
                   d.msg.usage ? d.msg.usage : "", d.msg.stop_reason ? d.msg.stop_reason : "",
                   d.msg.error ? d.msg.error : "");
    pic_sse_free(&p);
    pic_anthropic_free(&d);
    return out;
}

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    const char *bytes = (const char *)data;
    char *whole, *split;
    size_t chunk;
    if (!db && sqlite3_open(":memory:", &db) != SQLITE_OK) {
        abort();
    }
    if (size == 0) {
        return 0;
    }
    /* The first byte picks a chunk size; the rest is the stream. */
    chunk = (size_t)(data[0] % 16) + 1;
    whole = decode(bytes + 1, size - 1, size);
    split = decode(bytes + 1, size - 1, chunk);
    if (strcmp(whole, split) != 0) {
        fprintf(stderr, "chunk size %zu changed the result\nwhole: %s\nsplit: %s\n", chunk, whole, split);
        abort();
    }
    free(whole);
    free(split);
    return 0;
}