Skip to content
suit Artifact [14fce7d9c3]
Login

Artifact [14fce7d9c3]

Artifact 14fce7d9c3c69881c8c1e352fcd6e10a718d8bb61ec0ad72a7bf2d9c39d1d839:


// Fuzz target for the session record reader: any bytes, read as lines against
// a fixed set of rules, must never crash, read out of bounds or run forever.

#include "conf.h"
#include "platform.h"
#include "usage.h"

#include <stdint.h>
#include <string.h>

constexpr size_t INPUT_MAX = (2u << 20) + 1;

static const struct {
    UseKind kind;
    const char *text;
} rule_text[] = {
    {USE_SKILL, "message.content[] where type=tool_use name=Skill name input.skill id id"},
    {USE_AGENT, "message.content[] where type=tool_use name=Agent name input.subagent_type id id"},
    {USE_AGENT, "message.content[] where type=tool_use name=Task name input.subagent_type id id"},
    {USE_COMMAND, ". where type=user name message.content between <command-name>/ </command-name>"},
    {USE_SKILL, "a[].b.c name d"},
};

static UsageRule rules[sizeof rule_text / sizeof rule_text[0]];
static UsagePath time_path;
static UsagePath project_path;
static Usage reader;
static UsageSource source;
static uint8_t line[INPUT_MAX + 1];
[[maybe_unused]] static uint64_t events;
static bool ready;

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

static void sink(void *state, [[maybe_unused]] const UsageEvent *ev)
{
    (void)state;
    ensure(ev->name[0] != '\0' && strlen(ev->name) <= USAGE_NAME_MAX);
    ensure(strlen(ev->id) <= USAGE_ID_MAX && strlen(ev->time) <= USAGE_TIME_MAX);
    ensure(strlen(ev->project) <= USAGE_PROJECT_MAX);
    events++;
}

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
    if (!ready) {
        char msg[256];
        for (size_t i = 0; i < sizeof rule_text / sizeof rule_text[0]; i++) {
            [[maybe_unused]] bool ok = conf_rule_parse(&rules[i], rule_text[i].kind, rule_text[i].text, msg, sizeof msg);
            ensure(ok);
        }
        ensure(conf_path_parse(&time_path, "timestamp", false, false));
        ensure(conf_path_parse(&project_path, "cwd", false, false));
        usage_init(&reader, rules, sizeof rules / sizeof rules[0], &time_path, &project_path);
        ready = true;
    }
    uint64_t end;
    // As it comes: a last line with no newline is not read.
    usage_source_mem(&source, data, size);
    [[maybe_unused]] bool first = usage_read(&reader, &source, 0, &end, sink, nullptr);
    ensure(first && end <= size);
    // With a newline after it: the whole input is one more line.
    if (size < INPUT_MAX - 1) {
        memcpy(line, data, size);
        line[size] = '\n';
        usage_source_mem(&source, line, size + 1);
        [[maybe_unused]] bool second = usage_read(&reader, &source, 0, &end, sink, nullptr);
        ensure(second && end == size + 1);
    }
    return 0;
}