/* libFuzzer target: SSE framer plus OpenAI Responses decoder.
* Properties checked on every input:
* - no crash, leak or undefined behaviour (sanitizers);
* - the outcome and both forms of the message do not depend on chunking;
* - a decoded message's native and neutral forms are JSON arrays. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "openai_responses.h"
#include "sse.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);
static sqlite3 *db;
static void require_json(const char *sql, const char *value) {
sqlite3_stmt *st;
if (sqlite3_prepare_v2(db, sql, -1, &st, NULL) != SQLITE_OK) {
abort();
}
sqlite3_bind_text(st, 1, value, -1, SQLITE_STATIC);
if (sqlite3_step(st) != SQLITE_ROW || sqlite3_column_int(st, 0) != 1) {
fprintf(stderr, "bad decoded JSON: %s\n", value);
abort();
}
sqlite3_finalize(st);
}
static char *decode(const char *bytes, size_t n, size_t chunk) {
pic_responses c;
pic_sse p;
char *native = NULL, *neutral = NULL, *out;
size_t cap;
int rc = 0;
if (pic_responses_init(&c, db) != 0 || pic_sse_init(&p, 4096, 1u << 16, pic_responses_event, &c) != 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_sse_pending(&p) ? -1 : pic_responses_finish(&c);
}
if (rc == 0) {
native = pic_responses_native(&c);
neutral = pic_responses_neutral(&c);
if (!native || !neutral) {
abort();
}
require_json("SELECT json_valid(?1) AND json_type(?1) = 'array'", native);
require_json("SELECT json_valid(?1) AND json_type(?1) = 'array'", neutral);
}
cap = 64 + strlen(c.err) + (native ? strlen(native) : 0) + (neutral ? strlen(neutral) : 0);
out = malloc(cap);
if (!out) {
abort();
}
(void)snprintf(out, cap, "%d|%s|%s|%s|%s", rc, rc == 0 ? "" : c.err, native ? native : "", neutral ? neutral : "",
rc == 0 ? pic_responses_stop(&c) : "");
free(native);
free(neutral);
pic_sse_free(&p);
pic_responses_free(&c);
return out;
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
char *whole, *split;
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. */
whole = decode((const char *)data + 1, size - 1, size);
split = decode((const char *)data + 1, size - 1, (size_t)(data[0] % 16) + 1);
if (strcmp(whole, split) != 0) {
fprintf(stderr, "chunking changed the result\nwhole: %s\nsplit: %s\n", whole, split);
abort();
}
free(whole);
free(split);
return 0;
}