Something went wrong. Try again.
A Zig library for driving Elgato Stream Deck devices over USB HID.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The fuzz targets, and the table of them that both drivers read.//!//! What is worth fuzzing here is everything that turns bytes the//! hardware said into something this library believes. A Stream Deck is//! not hostile, but it is a USB device: it can be unplugged mid-report,//! it can be a model this library has the wrong table for, and the//! kernel can hand back a short read. None of that is checked by//! anything else.//!//! Two drivers run these. `zig build test` runs each target over the//! corpus below as an ordinary test, which is what keeps them//! compiling and catches a regression on a known input. `zig build//! fuzz` runs `tools/fuzz.zig`, which generates inputs and keeps going.
const std = @import("std");const builtin = @import("builtin");
const streamdeck = @import("streamdeck");
const Smith = std.testing.Smith;
/// The allocator the targets use.////// A target is reached from the test runner and from a standalone/// driver, and `std.testing.allocator` does not exist outside a test/// build, so it cannot simply be named here. In a test build this is/// that allocator; in the driver, `tools/fuzz.zig` points it at one it/// checks for leaks after every input.pub var backing: std.mem.Allocator = if (builtin.is_test) std.testing.allocator else undefined;
/// How many inputs got far enough to produce something.////// This is here because the way a fuzzing run fails is not by crashing/// but by being silently empty: `Smith.slice` hands back nothing at all/// for a length it does not like, and `Smith.value` answers a range's/// minimum when the input is exhausted, so a generator that is subtly/// wrong reports millions of iterations having tested the empty string/// every time. A driver that prints this alongside the run count can/// tell the difference.pub var accepted: usize = 0;
/// A `StreamDeck` of the given model with nothing behind it. None of/// the decoding below touches the handle -- that is the point of having/// split `Events.decode` out of `Events.read` -- so a fuzz target needs/// no device.fn deck(t: streamdeck.StreamDeck.Type) streamdeck.StreamDeck { return .{ .type = t, .device = .none };}
/// Whether an error is one a malformed report is *supposed* to produce.////// Listed rather than swallowed wholesale: the point of the exercise is/// that a parser handed nonsense refuses it in a way it documents, so/// any other error coming out of one is a finding and has to reach the/// driver.fn refused(err: anyerror) bool { return switch (err) { error.ShortReport, error.UnknownReportType, error.UnknownControlType, error.UnknownEventType, => true, else => false, };}
/// Pick a model. Every target does this first, so that the tables are/// fuzzed as well as the parsers: a report that is harmless for one/// model is a different length and a different shape for another.fn anyModel(smith: *Smith) streamdeck.StreamDeck.Type { const models = comptime std.enums.values(streamdeck.StreamDeck.Type); return models[smith.valueRangeAtMost(u8, 0, models.len - 1)];}
/// The whole of `Events.decode`: the report header, the control it/// names, and the body handed on to whichever parser owns it. This is/// the outermost thing a device's bytes reach.fn eventsDecode(smith: *Smith) anyerror!void { // The leading values come first and the payload after, because that // is the order a generator has to write them in. Reading them the // other way round is not an error anything reports: the target sees // the first four bytes of the model number as a length, and every // input is quietly refused. var sd = deck(anyModel(smith));
var buf: [max_report]u8 = undefined; const data = buf[0..smith.slice(&buf)];
const event = sd.events.decode(backing, .{ .nanoseconds = 0 }, data) catch |err| { if (refused(err)) return; return err; }; defer event.deinit(backing); accepted += 1;
// Whatever came back has to be one of the three, and has to be // internally consistent enough to free. switch (event) { .keys => |e| for (e.event.push.states) |s| std.debug.assert(s == .up or s == .down), .encoders => |e| switch (e.event) { .push => |p| for (p.states) |s| std.debug.assert(s == .up or s == .down), .turn => {}, }, .touchscreen => {}, }}
/// The key report parser on its own, without the framing in front of/// it, so that a body of any length is tried rather than only the ones/// the framing would produce.fn keysEvent(smith: *Smith) anyerror!void { var buf: [max_report]u8 = undefined; const data = buf[0..smith.slice(&buf)];
const event = streamdeck.Keys.Event.init(backing, .{ .nanoseconds = 0 }, data) catch |err| { if (refused(err)) return; return err; }; defer event.deinit(backing); accepted += 1;
// One state per byte of the report, always. std.debug.assert(event.event.push.states.len == data.len);}
/// The encoder report parser, which reads an event type out of the/// first byte and the states out of the rest.fn encodersEvent(smith: *Smith) anyerror!void { var buf: [max_report]u8 = undefined; const data = buf[0..smith.slice(&buf)];
const event = streamdeck.Encoders.Event.init(backing, .{ .nanoseconds = 0 }, data) catch |err| { if (refused(err)) return; return err; }; defer event.deinit(backing); accepted += 1;
// An event only comes back when there was a type byte to read, and // the states are then the rest of the report. std.debug.assert(data.len >= 1); switch (event.event) { .push => |p| std.debug.assert(p.states.len == data.len - 1), .turn => |t| std.debug.assert(t.states.len == data.len - 1), }}
/// The touchscreen report parser, which allocates nothing and so can/// only fail by reading past the end of what it was given.fn touchscreenEvent(smith: *Smith) anyerror!void { var buf: [max_report]u8 = undefined; const data = buf[0..smith.slice(&buf)];
const event = streamdeck.Touchscreen.Event.init(.{ .nanoseconds = 0 }, data) catch |err| { if (refused(err)) return; return err; }; defer event.deinit(backing); accepted += 1;
std.debug.assert(data.len >= streamdeck.Touchscreen.report_size);}
/// A diagnostic image at whatever size and index. The arithmetic in/// `keyIndexImage` divides by things derived from the size, and clips/// rather than bounds-checks, so a size no real key has is exactly/// what is worth trying.fn diagnosticImage(smith: *Smith) anyerror!void { const width = smith.valueRangeAtMost(u16, 1, 512); const height = smith.valueRangeAtMost(u16, 1, 512); const index = smith.valueRangeAtMost(u16, 0, 9999); const polarity: streamdeck.diagnostic.Polarity = if (smith.value(bool)) .yellow_on_black else .black_on_yellow;
var surface = try streamdeck.diagnostic.keyIndexImage(backing, width, height, index, polarity); defer surface.deinit(backing);
std.debug.assert(surface.getWidth() == width); std.debug.assert(surface.getHeight() == height); accepted += 1;}
/// A drawn surface all the way to the bytes that would go on the wire./// The encoders are handed a buffer sized by arithmetic in `bmp.zig`/// and `jpeg.zig` that assumes the result fits; an odd enough size is/// how that assumption would be found wrong.fn imageEncode(smith: *Smith) anyerror!void { const width = smith.valueRangeAtMost(u16, 1, 200); const height = smith.valueRangeAtMost(u16, 1, 200);
var sd = deck(anyModel(smith)); const key = smith.valueRangeAtMost(u8, 0, 63);
const feature = sd.keys.getImageFeature(key) orelse return;
var surface = try streamdeck.diagnostic.keyIndexImage( backing, width, height, key, .yellow_on_black, ); defer surface.deinit(backing);
const data = try streamdeck.Keys.encodeImage(backing, surface, feature); defer backing.free(data); accepted += 1;
// Whatever the size, the encoder produced the format the key asked // for; `Keys.setImage` refuses anything else. switch (feature.image_format) { .BMP => std.debug.assert(std.mem.eql(u8, data[0..2], &.{ 0x42, 0x4d })), .JPEG => std.debug.assert(std.mem.eql(u8, data[0..2], &.{ 0xff, 0xd8 })), }}
/// The framing a networked deck speaks, fed whatever bytes.////// This is the most hostile input anything in this library takes. The/// rest of these targets parse what a USB device said, which is at/// worst a device with the wrong tables; this parses what came out of a/// socket, and a header that declares its own payload length is exactly/// the shape of thing that reads past the end of a buffer when it is/// got wrong.fn framingDecode(smith: *Smith) anyerror!void { // The magic is put in front rather than hoped for. Random bytes // contain it about once in four billion, so a target that waited // for one would spend the whole run in the early return and never // reach the length arithmetic below it -- which is the part worth // fuzzing. The shapes that have no magic, or have it late, are in // the corpus instead, where they are deliberate. var buf: [max_report]u8 = undefined; const magic = streamdeck.framing.magic; @memcpy(buf[0..magic.len], &magic);
var rest: [max_report]u8 = undefined; const n = @min(smith.slice(&rest), buf.len - magic.len); @memcpy(buf[magic.len..][0..n], rest[0..n]); const data = buf[0 .. magic.len + n];
const frame = streamdeck.framing.decode(data) catch |err| { if (refusedFraming(err)) return; return err; } orelse return; accepted += 1;
// A frame that came back has to describe itself honestly: the // payload is the length the header declared, and the whole of it // lies inside what was handed in. std.debug.assert(frame.payload.len == frame.header.payload_len); std.debug.assert(frame.consumed <= data.len); std.debug.assert(frame.payload.len + streamdeck.framing.header_size <= frame.consumed);
// And it has to be exactly the tail of what was consumed, which is // what says the decoder counted the bytes it skipped resynchronising. const start = frame.consumed - frame.payload.len; std.debug.assert(frame.payload.ptr == data[start..].ptr);
// Classifying the payload is a total function: every payload is one // of these or none of them, and never two at once. const probe = streamdeck.framing.isKeepaliveProbe(frame.payload); const child = streamdeck.framing.isChildNotification(frame.payload); const input = streamdeck.framing.isInputReport(frame.payload); std.debug.assert(@as(u8, @intFromBool(probe)) + @intFromBool(child) + @intFromBool(input) <= 1);
if (probe) { // A probe always has a connection number to quote back, and an // acknowledgement can always be built for it. var ack_buf: [32]u8 = undefined; const ack = try streamdeck.framing.keepaliveAck(&ack_buf, frame.payload); std.debug.assert(ack[2] == streamdeck.framing.keepaliveConnection(frame.payload)); }}
/// A host command reply, which is where the protocol's one big-endian/// length lives. A device that lies about that length must not make the/// parser read past what actually arrived.fn framingHostReply(smith: *Smith) anyerror!void { var buf: [max_report]u8 = undefined; const n = smith.slice(&buf); if (n < 4) return;
// As with the magic above: a reply begins `0x03`, and waiting for // random bytes to do that tests the early return and nothing else. // What is worth reaching is the declared length -- the one // big-endian field in the protocol -- and whether a body can be cut // out of the payload that outlives it. buf[0] = 0x03; const data = buf[0..n];
const reply = streamdeck.framing.HostReply.parse(data) orelse return; accepted += 1;
// The body lies inside the payload, whatever length was declared. std.debug.assert(reply.body.len + 4 <= data.len); std.debug.assert(reply.body.ptr == data[4..].ptr);
// And the string is a prefix of the body with no terminator in it. const string = streamdeck.framing.replyString(reply); std.debug.assert(string.len <= reply.body.len); std.debug.assert(std.mem.findScalar(u8, string, 0) == null);}
/// Whether a framing error is one malformed bytes are supposed to/// produce. As with `refused` above, these are listed rather than/// swallowed wholesale.fn refusedFraming(err: anyerror) bool { return switch (err) { error.PayloadTooLarge, error.BufferTooSmall, error.UnknownFraming, => true, else => false, };}
/// The largest report any target reads into. `Smith.slice` hands back/// an *empty* slice for a length larger than the buffer rather than/// reducing it into range, so a generator has to know this number or/// it spends its time testing the empty string.pub const max_report = 256;
/// One thing to fuzz.pub const Target = struct { name: []const u8, /// How many values the target asks for before it asks for its /// payload. Each costs eight bytes of input, and a value outside /// the range asked for comes back as that range's minimum, so a /// generator has to write small numbers on purpose. leading_values: usize, /// Whether the target reads a payload slice at all, and so whether /// a generator should write a length in front of one. takes_payload: bool, run: *const fn (smith: *Smith) anyerror!void,};
pub const targets = [_]Target{ .{ .name = "events-decode", .leading_values = 1, .takes_payload = true, .run = eventsDecode }, .{ .name = "keys-event", .leading_values = 0, .takes_payload = true, .run = keysEvent }, .{ .name = "encoders-event", .leading_values = 0, .takes_payload = true, .run = encodersEvent }, .{ .name = "touchscreen-event", .leading_values = 0, .takes_payload = true, .run = touchscreenEvent }, .{ .name = "diagnostic-image", .leading_values = 4, .takes_payload = false, .run = diagnosticImage }, .{ .name = "image-encode", .leading_values = 4, .takes_payload = false, .run = imageEncode }, .{ .name = "framing-decode", .leading_values = 0, .takes_payload = true, .run = framingDecode }, .{ .name = "framing-host-reply", .leading_values = 0, .takes_payload = true, .run = framingHostReply },};
/// A corpus entry carrying `payload` as the slice a target reads.////// `Smith.slice` reads four bytes of little-endian length before the/// content, so an entry written as bare bytes is read as a length and/// then whatever follows -- which is usually nothing. This writes the/// length, so that an entry means what it looks like it means.fn payload(comptime bytes: []const u8) []const u8 { const length: [4]u8 = .{ @intCast(bytes.len & 0xff), @intCast((bytes.len >> 8) & 0xff), 0, 0, }; return &(length ++ bytes[0..bytes.len].*);}
/// A whole `cora` frame: the header this library writes, and `body`/// behind it.fn coraFrame(comptime flags: u16, comptime op: u8, comptime body: []const u8) []const u8 { return &(streamdeck.framing.magic ++ [_]u8{ @intCast(flags & 0xff), @intCast(flags >> 8), op, 0, 1, 0, 0, 0, @intCast(body.len & 0xff), @intCast((body.len >> 8) & 0xff), 0, 0, } ++ body[0..body.len].*);}
/// Inputs worth keeping: the shapes a real device produces, and the/// edges around them. `zig build test` runs every target over every one/// of these, and the driver mutates them.pub const corpus = [_][]const u8{ // Nothing at all, and one byte of nothing. &.{}, &.{0}, // A v1 key report: one header byte, then a state per key. &.{ 0x01, 0, 0, 0, 0, 0, 0 }, &.{ 0x01, 1, 0, 0, 0, 0, 0 }, // A v2 key report: four header bytes, then a state per key. &([_]u8{ 0x01, 0x00, 0x0f, 0x00 } ++ @as([15]u8, @splat(0))), &([_]u8{ 0x01, 0x00, 0x0f, 0x00, 1 } ++ @as([14]u8, @splat(0))), // A touchscreen report, short tap and a drag. &.{ 0x01, 0x02, 0x0e, 0x00, 1, 0, 0x20, 0x01, 0x30, 0x00, 0, 0, 0, 0 }, &.{ 0x01, 0x02, 0x0e, 0x00, 3, 0, 0x10, 0x00, 0x20, 0x00, 0x30, 0x00, 0x40, 0x00 }, // An encoder report, a push and a turn. &.{ 0x01, 0x03, 0x05, 0x00, 0, 0, 1, 0, 0 }, &.{ 0x01, 0x03, 0x05, 0x00, 1, 1, 0xff, 0, 0 }, // A report that claims a length it does not carry. &.{ 0x01, 0x00, 0xff, 0xff, 0 }, // Control and report types that do not exist. &.{ 0x7f, 0x7f, 0x00, 0x00, 0 }, &.{ 0x01, 0x7f, 0x00, 0x00, 0 }, // Truncated in the middle of the header. &.{0x01}, &.{ 0x01, 0x00 }, &.{ 0x01, 0x00, 0x0f },
// A keepalive probe in a `cora` frame, which is the first thing a // networked device ever sends. payload(coraFrame(0x0200, 0x00, &.{ 0x01, 0x0a, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00 })), // An input report in one: a key went down on a gen2 device. payload(coraFrame(0x8000, 0x00, &.{ 0x01, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00 })), // A dock saying something was plugged in. payload(coraFrame(0x0000, 0x00, &.{ 0x01, 0x0b, 0x7c, 0x00, 0x02, 0x00 })), // A frame behind junk, which the decoder has to resynchronise past. payload(&([_]u8{ 0x00, 0x00, 0xde, 0xad } ++ coraFrame(0x8000, 0x00, &.{ 0x01, 0x00, 0x00, 0x00 })[0..20].*)), // The magic and nothing else, and then a header cut short. payload(&streamdeck.framing.magic), payload(&(streamdeck.framing.magic ++ [_]u8{ 0, 0, 0, 0, 0, 0 })), // A header declaring a payload far larger than anything real. payload(&(streamdeck.framing.magic ++ [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, })), // A header declaring a payload it does not carry. payload(&(streamdeck.framing.magic ++ [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0x20, 0, 0, 0, 1, 2, 3, })),
// A host command reply: the serial number, whose length is the one // big-endian field in the protocol. payload(&.{ 0x03, 0x84, 0x00, 0x04, 'A', 'B', '1', '2' }), // One claiming far more than it carries. payload(&.{ 0x03, 0x84, 0xff, 0xff, 'x', 'y' }), // One whose declared length runs into its own padding. payload(&.{ 0x03, 0x84, 0x00, 0x08, 'C', 'L', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }), // An identity reply. payload(&.{ 0x03, 0x80, 0x00, 0x0c, 0, 0, 0, 0, 0, 0, 0, 0, 0xd9, 0x0f, 0xaa, 0x00, }),};
test "every target survives every corpus entry" { for (targets) |target| { for (corpus) |input| { var smith: Smith = .{ .in = input }; try target.run(&smith); } }}
/// One input, for the compiler's own fuzzer: pick a target and run it.fn fuzzOne(_: void, smith: *Smith) anyerror!void { const which = smith.valueRangeAtMost(u8, 0, targets.len - 1); inline for (targets, 0..) |target, i| { if (i == which) return target.run(smith); }}
test "fuzz" { // `zig build test --fuzz` reaches this, with coverage feedback // because the test binary is compiled with LLVM; `zig build fuzz` // drives the same targets from `tools/fuzz.zig` without it. try std.testing.fuzz({}, fuzzOne, .{ .corpus = &corpus });}
test "the target table is well formed" { for (targets) |target| { try std.testing.expect(target.name.len > 0); try std.testing.expect(target.leading_values <= 8); }}