// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the parsers must do with input nobody wrote. //! //! Everything here is a property rather than an example: not "this response //! parses to that" — the unit tests have those — but "whatever arrives, the //! parser terminates, stays inside its buffers, and if it claims to have //! understood the input then writing it back out and reading it again gives //! the same answer". //! //! Two of those properties are worth naming, because they are the ones a //! zero-copy parser can break in a way a unit test will not notice: //! //! * everything a parser hands back must point **into its input**. The whole //! library promises that a token, an attribute or a status text borrows //! the read buffer, so a slice pointing anywhere else is a bug that would //! outlive the buffer it was supposed to be tied to. //! * a response must **end**. A literal announces its own length and a //! parenthesized list has to balance, and a reader that keeps going when //! the stream is exhausted is a loop rather than an error. //! //! Each target is an ordinary test as well as a fuzz target. Without `--fuzz` //! it runs the seeds beside it, so `zig build test` exercises the same //! properties on input that has already been interesting once. //! //! With `zig build test --fuzz` Zig's own fuzzer drives them, steered by //! coverage; `zig build fuzz` runs a standalone loop over the same targets. const builtin = @import("builtin"); const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const Smith = std.testing.Smith; const imap = @import("imap"); /// The allocator the targets run against. /// /// Under `zig build test` that is the testing allocator, which reports a leak /// as a failure. `tools/fuzz.zig` cannot name it — it is not a test build — /// so it sets this to a checked allocator of its own instead. pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined; /// Whether `slice` points into `haystack`, which is what every borrowed /// slice in this library promises. fn borrows(haystack: []const u8, slice: []const u8) bool { if (slice.len == 0) return true; // an empty slice borrows nothing const start = @intFromPtr(slice.ptr); const base = @intFromPtr(haystack.ptr); return start >= base and start + slice.len <= base + haystack.len; } // -- tokens ------------------------------------------------------------------ /// `s` laid end to end `n` times, for seeds too long to write out. Zig 0.17 /// has no `**` operator to do it. fn repeat(comptime s: []const u8, comptime n: usize) *const [s.len * n]u8 { comptime { var out: [s.len * n]u8 = undefined; for (0..n) |i| @memcpy(out[i * s.len ..][0..s.len], s); const final = out; return &final; } } const token_seeds = [_][]const u8{ "FLAGS (\\Seen \\Draft) UID 42 NIL", "\"quoted \\\"string\\\" with \\\\ escapes\"", "{12}", "{12+}", "{5}\r\nhello UID 3", "(a (b (c)) \"d\") [e]", "BODY[HEADER.FIELDS (FROM TO)]<0> {3}", "\"unterminated", "\"bad \\n escape\"", "{}", "{x}", "{5} more", "(((((((((((((((((((((", ")", "", "\x00", "atom\x7f", }; /// Every token borrows the input, a quoted string unescapes to no more /// than its raw length, and a literal in memory is exactly as long as it /// said. fn tokenProperty(input: []const u8) !void { var s: imap.Scanner = .init(input); var tokens: usize = 0; while (s.next() catch return) |t| { tokens += 1; try testing.expect(tokens <= input.len); switch (t) { .atom => |a| { try testing.expect(borrows(input, a)); try testing.expect(a.len > 0); }, .quoted => |q| { try testing.expect(borrows(input, q)); const str = t.asString().?; try testing.expect(str.len() <= q.len); var buf: [2048]u8 = undefined; const plain = try str.unescape(&buf); try testing.expectEqual(str.len(), plain.len); try testing.expect(str.eql(plain)); const owned = try str.dupe(backing); defer backing.free(owned); try testing.expectEqualStrings(plain, owned); }, .string => |lit| try testing.expect(borrows(input, lit)), .literal => { // A literal on the wire is the last thing on its line. try testing.expect(s.atEnd()); try testing.expectEqual(imap.parser.trailingLiteral(input), t.literal); }, else => {}, } } // And item by item, a list either balances or fails; it never yields a // slice that reaches past the input. var items: imap.Scanner = .init(input); while (true) { if (items.atEnd()) break; const item = items.item() catch break; try testing.expect(borrows(input, item)); try testing.expect(item.len > 0); } } test "fuzz tokens" { for (token_seeds) |seed| try tokenProperty(seed); try testing.fuzz({}, fuzzTokens, .{}); } fn fuzzTokens(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try tokenProperty(buffer[0..len]); } // -- response lines ---------------------------------------------------------- const response_seeds = [_][]const u8{ "* OK [CAPABILITY IMAP4rev2 AUTH=PLAIN] ready", "* PREAUTH ready", "* BYE going down", "A001 OK [READ-WRITE] SELECT completed", "A002 NO [AUTHENTICATIONFAILED] Authentication failed.", "A003 BAD", "+ ", "+", "+ PDE4OTY+", "* 172 EXISTS", "* 1 RECENT", "* 44 EXPUNGE", "* 12 FETCH (FLAGS (\\Seen) UID 4827313)", "* 12 FETCH (BODY[] {100}", "* CAPABILITY IMAP4rev1 IMAP4rev2 AUTH=PLAIN LITERAL+ IDLE", "* LIST (\\Noselect \\HasChildren) \"/\" ~/Mail/foo", "* LIST () \"\\\\\" INBOX", "* LIST () NIL {12}", "* LSUB () \"/\" \"Sent Items\"", "* STATUS blurdybloop (MESSAGES 231 UIDNEXT 44292)", "* STATUS {5}", "* SEARCH 2 84 882", "* ESEARCH (TAG \"A282\") MIN 2 COUNT 3", "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)", "* NAMESPACE ((\"\" \"/\")) NIL NIL", "* ENABLED UTF8=ACCEPT", "* ID NIL", "* QUOTAROOT INBOX \"\"", "* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited", "* OK [UIDVALIDITY 3857529045] UIDs valid", "* OK []", "* OK [unterminated", "", "*", "* ", "A001", "(tag) OK", " OK an empty tag", "220 smtp.example.com ESMTP", "\x00\x00\x00", }; /// Whatever arrives, a parsed response borrows its input, and a status /// response survives a round trip. fn responseProperty(input: []const u8) !void { const r = imap.Response.parse(input) catch return; switch (r) { .continuation => |text| try testing.expect(borrows(input, text)), .tagged => |t| { try testing.expect(borrows(input, t.tag)); try testing.expect(t.tag.len > 0); try statusProperty(input, t.status); }, .untagged => |u| switch (u) { .status => |s| try statusProperty(input, s), .capability, .search, .esearch, .flags, .namespace, .enabled, .id => |text| { try testing.expect(borrows(input, text)); }, .list, .lsub => |l| { try testing.expect(borrows(input, l.attributes)); switch (l.name) { .atom, .quoted, .string => |name| try testing.expect(borrows(input, name)), .literal => try testing.expectEqual(imap.parser.trailingLiteral(input), l.name.literal), else => return error.TestUnexpectedResult, } }, .status_item => |s| { if (s.attributes) |a| { try testing.expect(borrows(input, a)); _ = imap.MailboxStatus.parse(a) catch {}; } else { try testing.expect(s.name == .literal); } }, .fetch => |f| try testing.expect(borrows(input, f.attributes)), .other => |o| { try testing.expect(borrows(input, o.name)); try testing.expect(borrows(input, o.rest)); }, .exists, .recent, .expunge => {}, }, } } fn statusProperty(input: []const u8, s: imap.StatusResponse) !void { try testing.expect(borrows(input, s.text)); if (s.code) |code| { try testing.expect(borrows(input, code.name)); try testing.expect(borrows(input, code.args)); try testing.expect(code.name.len > 0); try testing.expect(std.mem.findScalar(u8, code.name, ']') == null); try testing.expect(s.hasCode(code.name)); } // Written back out in the canonical form, it reads the same. var buf: [4096]u8 = undefined; var w: Io.Writer = .fixed(&buf); w.print("* {s}", .{@tagName(s.status)}) catch return; if (s.code) |code| { w.print(" [{s}", .{code.name}) catch return; if (code.args.len > 0) w.print(" {s}", .{code.args}) catch return; w.writeAll("]") catch return; } if (s.text.len > 0) w.print(" {s}", .{s.text}) catch return; const again = (try imap.Response.parse(w.buffered())).untagged.status; try testing.expectEqual(s.status, again.status); try testing.expectEqualStrings(s.text, again.text); try testing.expectEqual(s.code == null, again.code == null); if (s.code) |code| { try testing.expectEqualStrings(code.name, again.code.?.name); try testing.expectEqualStrings(code.args, again.code.?.args); } } test "fuzz responses" { for (response_seeds) |seed| try responseProperty(seed); try testing.fuzz({}, fuzzResponse, .{}); } fn fuzzResponse(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try responseProperty(buffer[0..len]); } // -- typed payloads ---------------------------------------------------------- const payload_seeds = [_][]const u8{ "IMAP4rev1 IMAP4rev2 STARTTLS AUTH=PLAIN AUTH=LOGIN SASL-IR LITERAL+ IDLE APPENDLIMIT=35651584", "AUTH=" ++ repeat("X", 300), "(FLAGS (\\Seen) UID 4827313 RFC822.SIZE 44827 BODY[HEADER.FIELDS (FROM TO)] {5}\r\nhello BODY[TEXT]<0> NIL)", "(\"date\" \"subject\" ((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\")) NIL NIL NIL NIL NIL NIL \"\")", "(NIL {6}\r\nh\xc3\xa9llo NIL NIL NIL NIL NIL NIL NIL NIL)", "38505 304,319:320 3956:3958", "1:3,7,10:9", "1:*", "0", "4294967295:4294967295", "(MESSAGES 231 UIDNEXT 44292 UNSEEN 0 SIZE 18446744073709551615)", "", "(", ")", "(UID)", }; /// The parsers built on the scanner: none may panic, and what they hand /// back borrows the input. fn payloadProperty(input: []const u8) !void { const caps = imap.Capabilities.parse(input); try testing.expect(caps.known); // Copied, never borrowed: the list has to survive the read buffer. try testing.expect(!borrows(input, caps.raw.list()) or caps.raw.list().len == 0); try testing.expect(!borrows(input, caps.auth.list()) or caps.auth.list().len == 0); // Parsing the copy again gives the same flags. const again = imap.Capabilities.parse(caps.raw.list()); try testing.expectEqual(caps.idle, again.idle); try testing.expectEqual(caps.imap4rev2, again.imap4rev2); try testing.expectEqualStrings(caps.auth.list(), again.auth.list()); var items: imap.FetchIterator = .init(input); while (items.next() catch null) |item| { try testing.expect(borrows(input, item.name)); if (item.section) |s| try testing.expect(borrows(input, s)); switch (item.value) { .list => |l| { try testing.expect(borrows(input, l)); _ = imap.Envelope.parse(l) catch {}; }, .token => |t| if (t.asString()) |s| try testing.expect(borrows(input, s.raw)), } } if (imap.Envelope.parse(input)) |e| { inline for (.{ e.from, e.sender, e.reply_to, e.to, e.cc, e.bcc }) |list| { try testing.expect(borrows(input, list)); var addresses = imap.Envelope.addresses(list); while (addresses.next() catch null) |a| { if (a.mailbox) |m| try testing.expect(borrows(input, m.raw)); } } } else |_| {} var numbers: imap.SequenceIterator = .init(input); var count: usize = 0; while (numbers.next() catch null) |n| { try testing.expect(n > 0); count += 1; // A range can expand to billions of numbers, which is the server's // right; the iterator is lazy, so stop where a test would. if (count > 100_000) break; } _ = imap.MailboxStatus.parse(input) catch {}; if (imap.UidResult.parse(input, .copy)) |r| { try testing.expect(borrows(input, r.uids)); try testing.expect(borrows(input, r.source)); } else |_| {} } test "fuzz payloads" { for (payload_seeds) |seed| try payloadProperty(seed); try testing.fuzz({}, fuzzPayload, .{}); } fn fuzzPayload(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try payloadProperty(buffer[0..len]); } // -- modified UTF-7 ---------------------------------------------------------- const utf7_seeds = [_][]const u8{ "INBOX", "Entw\xc3\xbcrfe", "Fish & Chips", "~peter/mail/\xe5\x8f\xb0\xe5\x8c\x97/\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e", "\xf0\x9f\x93\xa7", "&APw-", "&-", "&", "&APw", "&APx-", "&2D0-", "&AD0-", "&*-", "", "\xff", "\xed\xa0\x80", }; /// Valid UTF-8 survives a round trip; anything decodes without panicking, /// and what decodes re-encodes to itself. fn utf7Property(input: []const u8) !void { var encoded_buf: [8192]u8 = undefined; if (imap.utf7.encodeBuf(&encoded_buf, input)) |encoded| { try testing.expect(std.unicode.utf8ValidateSlice(input)); for (encoded) |c| try testing.expect(c >= 0x20 and c <= 0x7e); var decoded_buf: [8192]u8 = undefined; const decoded = try imap.utf7.decodeBuf(&decoded_buf, encoded); try testing.expectEqualStrings(input, decoded); try testing.expectEqual(imap.utf7.needsEncoding(input), !std.mem.eql(u8, input, encoded)); } else |err| switch (err) { error.InvalidUtf8 => try testing.expect(!std.unicode.utf8ValidateSlice(input)), error.NoSpaceLeft => {}, } var decoded_buf: [8192]u8 = undefined; if (imap.utf7.decodeBuf(&decoded_buf, input)) |decoded| { try testing.expect(std.unicode.utf8ValidateSlice(decoded)); var again_buf: [8192]u8 = undefined; const again = try imap.utf7.encodeBuf(&again_buf, decoded); try testing.expectEqualStrings(input, again); } else |_| {} } test "fuzz utf7" { for (utf7_seeds) |seed| try utf7Property(seed); try testing.fuzz({}, fuzzUtf7, .{}); } fn fuzzUtf7(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try utf7Property(buffer[0..len]); } // -- whole sessions ---------------------------------------------------------- const session_seeds = [_][]const u8{ "* OK [CAPABILITY IMAP4rev2 AUTH=PLAIN SASL-IR UIDPLUS] ready\r\n" ++ "A0001 OK authenticated\r\n" ++ "* 2 EXISTS\r\n* FLAGS (\\Seen)\r\n* OK [UIDVALIDITY 1] ok\r\nA0002 OK [READ-WRITE] selected\r\n" ++ "* LIST () \"/\" INBOX\r\n* LIST () \"/\" {5}\r\nhello\r\nA0003 OK\r\n" ++ "* SEARCH 1 2\r\nA0004 OK\r\n" ++ "* 1 FETCH (UID 10 BODY[] {14}\r\nSubject: a\r\n\r\n)\r\nA0005 OK\r\n" ++ "* 1 FETCH (UID 10 ENVELOPE (NIL {2}\r\nhi NIL NIL NIL NIL NIL NIL NIL NIL))\r\nA0006 OK\r\n" ++ "* STATUS INBOX (MESSAGES 2)\r\nA0007 OK\r\n" ++ "A0008 OK\r\n* 1 EXPUNGE\r\nA0009 OK\r\n* BYE\r\nA0010 OK\r\n", "* PREAUTH ready\r\nA0001 NO\r\n", "* BYE go away\r\n", "* OK ready\r\n+ \r\nA0001 OK\r\n* 1 EXISTS\r\nA0002 OK\r\n", "* OK ready\r\nA0001 OK\r\n* 1 FETCH (BODY[] {100000}\r\n", "* OK ready\r\nA0001 OK\r\n* 1 FETCH (BODY[] {3}\r\nabc {3}\r\ndef {3}\r\nghi)\r\nA0002 OK\r\n", "* OK ready\r\nA0001 OK\r\nA0002 OK\r\n* LIST () \"/\" {3}\r\n", "* OK ready\r\nA0001 OK\r\nA0002 OK\r\n* LIST () \"/\" {3}\r\nabc\r\nA0003 OK\r\n", "* OK ready\r\nA001 OK\r\nA0002 OK\r\n* LIST ()1 \"\" {3}\r\nabc\r\nA0003 OK\r\n", "* OK ready\r\nA0001 OK\r\nA0002 OK\r\n* LIST () \"/\" {0}\r\n\r\nA0003 OK\r\n", "", "\r\n\r\n\r\n", "* OK\r\n" ++ repeat("* 1 EXISTS\r\n", 50), }; /// A whole session against arbitrary server output: nothing here may panic, /// leak, or fail to terminate, however far from IMAP the answers are. fn sessionProperty(input: []const u8) !void { var reader: Io.Reader = .fixed(input); var write_buf: [8192]u8 = undefined; var writer: Io.Writer = .fixed(&write_buf); var client: imap.Client = .init(&reader, &writer, .encrypted); const greeting = client.readGreeting() catch return; try testing.expect(borrows(input, greeting.text)); _ = client.authenticate("alice", "s3cret") catch {}; _ = client.select("INBOX") catch {}; if (client.mailbox) |m| { // Copied out of the responses, never borrowed. try testing.expect(!borrows(input, m.flags.list()) or m.flags.list().len == 0); } if (client.listAlloc(backing, "", "*", .{})) |list| { var l = list; // Freed before any check can fail, or the failure would be reported // as a leak instead. defer l.deinit(backing); for (l.entries) |e| { // Copied out of the responses, never borrowed -- except that an // empty name borrows nothing, and a server may send one. try testing.expect(!borrows(input, e.name) or e.name.len == 0); try testing.expect(!borrows(input, e.attributes) or e.attributes.len == 0); } } else |_| {} if (client.searchAlloc(backing, .uid, "ALL")) |found| backing.free(found) else |_| {} var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); _ = client.fetchTo(&out.writer, .uid, 10, "", .{ .limit = .limited(1 << 16) }) catch {}; if (client.fetchAlloc(backing, .uid, 10, "(ENVELOPE)", .limited(1 << 16))) |f| { var owned = f; var items = owned.items(); while (items.next() catch null) |_| {} owned.deinit(backing); } else |_| {} _ = client.status("INBOX", "MESSAGES") catch {}; client.store(.uid, "10", .add, "\\Deleted", .{}) catch {}; client.expunge() catch {}; client.logout() catch {}; } test "fuzz sessions" { for (session_seeds) |seed| try sessionProperty(seed); try testing.fuzz({}, fuzzSession, .{}); } fn fuzzSession(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try sessionProperty(buffer[0..len]); } // -- authentication exchanges ------------------------------------------------ const auth_seeds = [_][]const u8{ "A0001 OK authenticated\r\n", "+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2UucmVzdG9uLm1jaS5uZXQ+\r\nA0001 OK ok\r\n", "+ \r\nA0001 OK ok\r\n", "+\r\nA0001 OK ok\r\n", "+ not base64!!\r\n", "+ " ++ repeat("QUJD", 200) ++ "\r\n", "A0001 NO [AUTHENTICATIONFAILED] bad credentials\r\n", "A0001 NO [PRIVACYREQUIRED] not here\r\n", "* CAPABILITY IMAP4rev2\r\n+ VXNlcm5hbWU6\r\n+ UGFzc3dvcmQ6\r\nA0001 OK ok\r\n", "+ AAAA\r\n+ AAAA\r\n+ AAAA\r\n+ AAAA\r\n", "", "+ ====\r\n", "A0002 OK wrong tag\r\n", }; /// The AUTHENTICATE exchanges, which are the part of the protocol that /// decodes what the server sends. A challenge too large for the buffer, or /// one that is not base64, has to come back as an error rather than a mess. fn authProperty(input: []const u8) !void { inline for (.{ "plain", "login", "cram", "external", "xoauth2" }) |which| { inline for (.{ false, true }) |sasl_ir| { var reader: Io.Reader = .fixed(input); var write_buf: [16384]u8 = undefined; var writer: Io.Writer = .fixed(&write_buf); var client: imap.Client = .init(&reader, &writer, .encrypted); client.capabilities.sasl_ir = sasl_ir; var plain: imap.sasl.Plain = .init("tim", "tanstaaftanstaaf"); var login: imap.sasl.Login = .init("tim", "tanstaaftanstaaf"); var cram: imap.sasl.CramMd5 = .init("tim", "tanstaaftanstaaf"); var ext: imap.sasl.External = .init(""); var oauth: imap.sasl.XOAuth2 = .init("tim@example.com", "ya29.token"); const mechanism: imap.sasl.Client = if (comptime std.mem.eql(u8, which, "plain")) plain.client() else if (comptime std.mem.eql(u8, which, "login")) login.client() else if (comptime std.mem.eql(u8, which, "cram")) cram.client() else if (comptime std.mem.eql(u8, which, "external")) ext.client() else oauth.client(); client.authenticateSasl(mechanism) catch {}; } } } test "fuzz authentication" { for (auth_seeds) |seed| try authProperty(seed); try testing.fuzz({}, fuzzAuth, .{}); } fn fuzzAuth(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try authProperty(buffer[0..len]); } // -- the target table -------------------------------------------------------- pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating: the same seeds the tests above run, which are /// what stands in for the coverage feedback a real fuzzer would have. corpus: []const []const u8, /// The buffer this target reads its input into. /// /// `Smith.slice` yields an *empty* slice for a length larger than the /// buffer rather than a truncated one, so a generator that does not know /// this number hands the target nothing at all most of the time. content_max: usize, }; /// Wraps one of the `fuzz*` functions above so that it takes raw bytes. fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } }; } pub const all = [_]Target{ .{ .name = "tokens", .run = Driven(fuzzTokens).run, .corpus = &token_seeds, .content_max = 2048, }, .{ .name = "responses", .run = Driven(fuzzResponse).run, .corpus = &response_seeds, .content_max = 2048, }, .{ .name = "payloads", .run = Driven(fuzzPayload).run, .corpus = &payload_seeds, .content_max = 2048, }, .{ .name = "utf7", .run = Driven(fuzzUtf7).run, .corpus = &utf7_seeds, .content_max = 1024, }, .{ .name = "sessions", .run = Driven(fuzzSession).run, .corpus = &session_seeds, .content_max = 4096, }, .{ .name = "auth", .run = Driven(fuzzAuth).run, .corpus = &auth_seeds, .content_max = 2048, }, };