// 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 header //! parses to that" — the unit tests have those — but "whatever arrives, the //! parser terminates, stays inside its buffers, frees what it allocated, and //! if it claims to have understood the input then writing it back out and //! reading it again gives the same answer". //! //! Round-tripping is the property that earns its keep. A parser and a writer //! drift apart one small decision at a time — where a fold goes, whether a //! trailing space survives, which of two `@` signs separates an address — and //! a test written against a fixed example cannot see it, because the example //! was written to agree with whatever the code did that day. The message //! target asks for the *second* write to equal the first rather than for the //! output to equal the input: input may legitimately be repaired on the way //! in, but repairing it twice must change nothing. //! //! 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. //! //! Note that Zig 0.16.0 cannot build a test executable in fuzz mode without a //! patched standard library, and leaves the fuzzer's coverage table empty even //! then; `flake.nix` says what the patch is and `tools/fuzz.zig` is the loop //! that stands in for the fuzzer. The properties are worth having either way. const builtin = @import("builtin"); const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const mime = @import("mime"); /// 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; /// One fuzz target: what to call it, what it already knows to be interesting, /// how much of an input it can read, and the property itself. pub const Target = struct { name: []const u8, corpus: []const []const u8, /// The size of the buffer the target reads its slice into. /// /// `Smith.slice` answers a length larger than its buffer with an *empty* /// slice rather than a truncated one, so a generator that does not know /// this number will silently hand the target nothing at all. content_max: usize, run: *const fn (input: []const u8) anyerror!void, }; pub const all = [_]Target{ .{ .name = "message", .corpus = &message_seeds, .content_max = message_max, .run = runMessage }, .{ .name = "headers", .corpus = &header_seeds, .content_max = header_max, .run = runHeaders }, .{ .name = "address", .corpus = &address_seeds, .content_max = address_max, .run = runAddress }, .{ .name = "date", .corpus = &date_seeds, .content_max = date_max, .run = runDate }, .{ .name = "encoded-word", .corpus = &encoded_word_seeds, .content_max = word_max, .run = runEncodedWord }, .{ .name = "parameters", .corpus = ¶meter_seeds, .content_max = parameter_max, .run = runParameters }, .{ .name = "base64", .corpus = &codec_seeds, .content_max = codec_max, .run = runBase64 }, .{ .name = "quoted-printable", .corpus = &codec_seeds, .content_max = codec_max, .run = runQuotedPrintable }, .{ .name = "flowed", .corpus = &flowed_seeds, .content_max = flowed_max, .run = runFlowed }, .{ .name = "uuencode", .corpus = &uuencode_seeds, .content_max = uuencode_max, .run = runUuencode }, .{ .name = "idn", .corpus = &idn_seeds, .content_max = idn_max, .run = runIdn }, .{ .name = "parser", .corpus = &message_seeds, .content_max = message_max, .run = runParser }, .{ .name = "mailto", .corpus = &mailto_seeds, .content_max = mailto_max, .run = runMailto }, .{ .name = "received", .corpus = &received_seeds, .content_max = received_max, .run = runReceived }, .{ .name = "report", .corpus = &report_seeds, .content_max = report_max, .run = runReport }, .{ .name = "build", .corpus = &build_seeds, .content_max = build_max, .run = runBuild }, .{ .name = "chunks", .corpus = &chunk_seeds, .content_max = chunk_max, .run = runChunks }, .{ .name = "encode-stream", .corpus = &build_seeds, .content_max = chunk_max, .run = runEncodeStream }, .{ .name = "headers-edit", .corpus = &header_seeds, .content_max = header_max, .run = runHeadersEdit }, }; // -- whole messages --------------------------------------------------------- const message_max = 8192; const message_seeds = [_][]const u8{ "From: jeff@example.com\r\nSubject: hello\r\n\r\nbody\r\n", "Content-Type: multipart/mixed; boundary=B\r\n\r\n--B\r\n\r\na\r\n--B\r\n\r\nb\r\n--B--\r\n", "Content-Type: multipart/mixed; boundary=B\r\n\r\n--B\r\n\r\ntruncated", "Content-Type: multipart/mixed\r\n\r\nno boundary at all\r\n", "Content-Type: message/rfc822\r\n\r\nSubject: inner\r\n\r\ninner body\r\n", "Content-Type: multipart/digest; boundary=B\r\n\r\n--B\r\n\r\nSubject: x\r\n\r\ny\r\n--B--\r\n", "Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\nY2Fmw6k=\r\n", "Content-Type: text/plain\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\ncaf=C3=A9=\r\n", "Content-Disposition: attachment; filename*=UTF-8''caf%C3%A9.txt\r\n\r\nx\r\n", "Content-Type: multipart/mixed; boundary=\"\"\r\n\r\n--\r\n\r\na\r\n----\r\n", // Preamble and epilogue, which nothing reads and everything must keep. "Content-Type: multipart/mixed; boundary=B\r\n\r\npreamble\r\n--B\r\n\r\na\r\n--B--\r\nepilogue\r\n", // Not a message. "", "\r\n", "no headers and no blank line", "From nobody Mon Jan 1 00:00:00 2001\r\nFrom: x@y\r\n\r\n", }; /// Parsing, writing and parsing again must reach a fixed point. /// /// The first write may differ from the input — a message whose lines end in LF /// comes back with CRLF, and a header the parser could not make sense of is /// dropped — but the second must not differ from the first. A writer that adds /// a line ending, or a parser that eats one, shows up here as a message that /// grows or shrinks every time it is opened. fn messageProperty(input: []const u8) !void { var first: mime.Message = try .parse(backing, input, .{}); defer first.deinit(); // Everything a reader would ask, because a question that allocates is a // question that can leak, and because a `filename` or a `subject` is read // out of the same bytes the parser has just been handed. var walker = first.root.walk(); while (walker.next()) |part| { _ = try part.subject(); _ = try part.filename(); _ = try part.sentAt(); _ = part.isAttachment(); _ = part.transferEncoding(); var addresses = try part.addresses(backing, "from"); defer addresses.deinit(backing); var mailboxes = addresses.mailboxIterator(); while (mailboxes.next()) |mailbox| _ = mailbox.isValid(); const decoded = try part.decodeAlloc(backing); defer backing.free(decoded); const text = try part.textAlloc(backing); defer backing.free(text); if (part.media_type.isText()) { try testing.expect(std.unicode.utf8ValidateSlice(text)); } } const once = try first.toBytesAlloc(backing); defer backing.free(once); var second: mime.Message = try .parse(backing, once, .{}); defer second.deinit(); const twice = try second.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(once, twice); } test "fuzz messages" { for (message_seeds) |seed| try messageProperty(seed); try testing.fuzz({}, fuzzMessage, .{}); } fn fuzzMessage(_: void, smith: *testing.Smith) !void { var buffer: [message_max]u8 = undefined; try messageProperty(buffer[0..smith.slice(&buffer)]); } fn runMessage(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [message_max]u8 = undefined; return messageProperty(buffer[0..smith.slice(&buffer)]); } // -- header blocks ---------------------------------------------------------- const header_max = 4096; const header_seeds = [_][]const u8{ "From: jeff@example.com\r\n", "Subject: =?UTF-8?Q?caf=C3=A9?=\r\n", "To: a@x,\r\n b@y,\r\n\tc@z\r\n", "Received: from a\r\nReceived: from b\r\n", "X: \r\n", ": no name\r\n", "NoColon\r\n", "A:1\r\nA:2\r\nA:3\r\n", " leading continuation with no field\r\n", "Subject: a value that is long enough to need folding when it is written " ++ "back out again, several times over in fact\r\n", }; /// A header block written back out and read again gives the same fields, and /// the bytes reach a fixed point. Values are stored in wire form precisely so /// that this is a copy rather than a reconstruction. fn headersProperty(input: []const u8) !void { var first: mime.Headers = try .parse(backing, input); defer first.deinit(); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try first.write(&once.writer); var second: mime.Headers = try .parse(backing, once.written()); defer second.deinit(); try testing.expectEqual(first.fields.items.len, second.fields.items.len); for (first.fields.items, second.fields.items) |a, b| { try testing.expectEqualStrings(a.name, b.name); try testing.expectEqualStrings(a.value, b.value); } var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try second.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); // Every derived form has to be reachable without crashing or leaking. for (first.fields.items) |f| { _ = try first.getUnfolded(f.name); const utf8 = (try first.getUtf8(f.name)).?; try testing.expect(std.unicode.utf8ValidateSlice(utf8)); } } test "fuzz headers" { for (header_seeds) |seed| try headersProperty(seed); try testing.fuzz({}, fuzzHeaders, .{}); } fn fuzzHeaders(_: void, smith: *testing.Smith) !void { var buffer: [header_max]u8 = undefined; try headersProperty(buffer[0..smith.slice(&buffer)]); } fn runHeaders(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [header_max]u8 = undefined; return headersProperty(buffer[0..smith.slice(&buffer)]); } // -- addresses -------------------------------------------------------------- const address_max = 1024; const address_seeds = [_][]const u8{ "jeff@example.com", "Jeff Ollie ", "\"Ollie, Jeff\" , alice@example.net", "Friends: a@x, b@y;, c@z", "undisclosed-recipients:;", "jeff@example.com (Ollie, Jeff)", "=?UTF-8?Q?Jos=C3=A9?= ", "<@relay1,@relay2:jeff@example.com>", "\"quoted\\\"escape\"@example.com", "jeff@[192.0.2.1]", "postmaster", ",,,", "a@b@c", "\"unterminated ", "((nested (comments))) x@y", "", }; /// An address list written back out and parsed again names the same /// mailboxes, and the bytes reach a fixed point. /// /// The local part and the domain are compared only where every mailbox in the /// list is one — `Mailbox.isValid` — because that is the promise worth making: /// **an address that is an address is never changed by being written**. A /// mailbox parsed out of something that was not an address is repaired on the /// way out, quoted or bracketed or stripped of the control characters that /// would end the header line, and there is nothing useful to say about what it /// should turn into. What must hold for those is that the bytes settle, which /// the fixed-point check above says. fn addressProperty(input: []const u8) !void { var first: mime.address.List = try .parse(backing, input); defer first.deinit(backing); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try first.write(&once.writer); var second: mime.address.List = try .parse(backing, once.written()); defer second.deinit(backing); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try second.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); var check = first.mailboxIterator(); while (check.next()) |mailbox| { if (!mailbox.isValid()) return; } var a = first.mailboxIterator(); var b = second.mailboxIterator(); while (a.next()) |expected| { const found = b.next() orelse return error.LostAMailbox; try testing.expectEqualStrings(expected.local_part, found.local_part); try testing.expectEqualStrings(expected.domain, found.domain); } try testing.expectEqual(null, b.next()); } test "fuzz addresses" { for (address_seeds) |seed| try addressProperty(seed); try testing.fuzz({}, fuzzAddress, .{}); } fn fuzzAddress(_: void, smith: *testing.Smith) !void { var buffer: [address_max]u8 = undefined; try addressProperty(buffer[0..smith.slice(&buffer)]); } fn runAddress(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [address_max]u8 = undefined; return addressProperty(buffer[0..smith.slice(&buffer)]); } // -- dates ------------------------------------------------------------------ const date_max = 256; const date_seeds = [_][]const u8{ "Tue, 01 Jul 2003 10:52:37 +0200", "1 Jul 2003 9:52 -0500", "Sun, 01 Jul 2003 10:52:37 -0000", "Mon, 3 Jan 94 12:00:00 EST", "Tue, 1 Jul 2003 (the first) 10:52:37 +0200 (CEST)", "31 Feb 2003 00:00:00 +0000", "99 Jan 9999 99:99:99 +0000", "Thu, 01 Jan 1970 00:00:00 +0000", "", }; /// A date that parses must survive being written and read again, and must /// name the same instant both times. fn dateProperty(input: []const u8) !void { const first = mime.date.parse(input) catch return; var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); mime.date.write(&w, first.time) catch return; const second = try mime.date.parse(w.buffered()); try testing.expectEqual(first.time.toInstant().timestamp, second.time.toInstant().timestamp); var again: [256]u8 = undefined; var w2: Io.Writer = .fixed(&again); try mime.date.write(&w2, second.time); try testing.expectEqualStrings(w.buffered(), w2.buffered()); } test "fuzz dates" { for (date_seeds) |seed| try dateProperty(seed); try testing.fuzz({}, fuzzDate, .{}); } fn fuzzDate(_: void, smith: *testing.Smith) !void { var buffer: [date_max]u8 = undefined; try dateProperty(buffer[0..smith.slice(&buffer)]); } fn runDate(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [date_max]u8 = undefined; return dateProperty(buffer[0..smith.slice(&buffer)]); } // -- encoded words ---------------------------------------------------------- const word_max = 1024; const encoded_word_seeds = [_][]const u8{ "=?UTF-8?Q?caf=C3=A9?=", "=?UTF-8?B?Y2Fmw6k=?=", "=?iso-8859-1?Q?caf=E9?=", "=?shift_jis?B?gqCCog==?=", "=?UTF-8?Q?a?= =?UTF-8?Q?b?=", "Re: =?UTF-8?Q?caf=C3=A9?= today", "look at =?this?= thing", "=?utf-8*en?Q?x?=", "=?utf-8?Q?unterminated", "=??Q?x?=", "plain ascii", "", }; /// Decoding always produces valid UTF-8, and text that is encoded and decoded /// again is the text that went in. /// /// The first half is what makes the result safe to hand to anything else in /// the program; the second is what makes the encoder and the decoder each /// other's inverse, including across the split that a long subject needs. fn encodedWordProperty(input: []const u8) !void { const decoded = try mime.encoded_word.decodeUtf8Alloc(backing, input); defer backing.free(decoded); try testing.expect(std.unicode.utf8ValidateSlice(decoded)); // And back the other way, from whatever the input happens to be. const encoded = try mime.encoded_word.encodeAlloc(backing, input, .{}); defer backing.free(encoded); for (encoded) |c| try testing.expect(c < 0x80); const again = try mime.encoded_word.decodeUtf8Alloc(backing, encoded); defer backing.free(again); if (std.unicode.utf8ValidateSlice(input)) { try testing.expectEqualStrings(input, again); } } test "fuzz encoded words" { for (encoded_word_seeds) |seed| try encodedWordProperty(seed); try testing.fuzz({}, fuzzEncodedWord, .{}); } fn fuzzEncodedWord(_: void, smith: *testing.Smith) !void { var buffer: [word_max]u8 = undefined; try encodedWordProperty(buffer[0..smith.slice(&buffer)]); } fn runEncodedWord(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [word_max]u8 = undefined; return encodedWordProperty(buffer[0..smith.slice(&buffer)]); } // -- parameters ------------------------------------------------------------- const parameter_max = 1024; const parameter_seeds = [_][]const u8{ "text/plain; charset=utf-8", "attachment; filename=\"a file.txt\"", "attachment; filename*=UTF-8''caf%C3%A9.txt", "attachment; filename*0=\"a \"; filename*1=\"b\"", "attachment; filename*0*=UTF-8''a%20; filename*1*=b", "attachment; filename*0=a; filename*2=c", "attachment; filename=\"=?UTF-8?B?Y2Fmw6kudHh0?=\"", "x; a=1; a=2", "x; ; ; =", "x; unterminated=\"quote", "", }; /// A value written as a parameter reads back as itself, whatever is in it. /// /// This is the property that matters for a filename: the whole apparatus of /// RFC 2231 exists so that a name survives the trip, and a writer that picks /// the wrong form, or splits a continuation in the wrong place, silently /// renames somebody's attachment. fn parameterProperty(input: []const u8) !void { var parsed: mime.parameters.Parameters = try .parse(backing, input); defer parsed.deinit(backing); for (parsed.list) |parameter| { const utf8 = (try parsed.getUtf8Alloc(backing, parameter.name)).?; defer backing.free(utf8); try testing.expect(std.unicode.utf8ValidateSlice(utf8)); } var written: Io.Writer.Allocating = .init(backing); defer written.deinit(); try written.writer.writeAll("x"); try mime.parameters.writeParameter(&written.writer, "filename", input, .{}); var read: mime.parameters.Parameters = try .parse(backing, written.written()); defer read.deinit(backing); // An empty value cannot be told from a missing one, and that is the only // input this does not claim to round-trip. if (input.len != 0) { try testing.expectEqualStrings(input, read.get("filename").?); } } test "fuzz parameters" { for (parameter_seeds) |seed| try parameterProperty(seed); try testing.fuzz({}, fuzzParameters, .{}); } fn fuzzParameters(_: void, smith: *testing.Smith) !void { var buffer: [parameter_max]u8 = undefined; try parameterProperty(buffer[0..smith.slice(&buffer)]); } fn runParameters(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [parameter_max]u8 = undefined; return parameterProperty(buffer[0..smith.slice(&buffer)]); } // -- the codecs ------------------------------------------------------------- const codec_max = 4096; const codec_seeds = [_][]const u8{ "", "f", "fo", "foo", "plain ASCII text\r\n", "a café in Paris\r\n", "trailing space \r\nand a tab\t\r\n", "From the desk of\r\n.\r\n", "=\r\n=3D\r\n=zz\r\n", "Zm9vYmFy", "Zm9v\r\nYmFy", "x" ** 200, "\x00\x01\x02\xff\xfe", }; /// Anything encoded and decoded again is what went in, and anything at all can /// be decoded without failing. fn base64Property(input: []const u8) !void { // Decoding is total: RFC 2045 says to ignore what is not in the alphabet, // so there is no input that is not base64 for something. const decoded = try mime.base64.decodeAlloc(backing, input); defer backing.free(decoded); const encoded = try mime.base64.encodeAlloc(backing, input, .{}); defer backing.free(encoded); var lines = std.mem.splitSequence(u8, encoded, "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 76); const again = try mime.base64.decodeAlloc(backing, encoded); defer backing.free(again); try testing.expectEqualSlices(u8, input, again); } test "fuzz base64" { for (codec_seeds) |seed| try base64Property(seed); try testing.fuzz({}, fuzzBase64, .{}); } fn fuzzBase64(_: void, smith: *testing.Smith) !void { var buffer: [codec_max]u8 = undefined; try base64Property(buffer[0..smith.slice(&buffer)]); } fn runBase64(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [codec_max]u8 = undefined; return base64Property(buffer[0..smith.slice(&buffer)]); } /// Binary mode is exactly lossless; text mode is lossless for input that is /// already in canonical form, which is what it documents itself as needing. fn quotedPrintableProperty(input: []const u8) !void { const decoded = try mime.quoted_printable.decodeAlloc(backing, input); defer backing.free(decoded); const binary = try mime.quoted_printable.encodeAlloc(backing, input, .{ .mode = .binary }); defer backing.free(binary); var lines = std.mem.splitSequence(u8, binary, "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 76); const again = try mime.quoted_printable.decodeAlloc(backing, binary); defer backing.free(again); try testing.expectEqualSlices(u8, input, again); // Text mode, over input put into canonical form first, which is what the // library does to a body before encoding it. var canonical: Io.Writer.Allocating = .init(backing); defer canonical.deinit(); try mime.line_ending.toCanonical(&canonical.writer, input); const text = try mime.quoted_printable.encodeAlloc(backing, canonical.written(), .{}); defer backing.free(text); const text_again = try mime.quoted_printable.decodeAlloc(backing, text); defer backing.free(text_again); try testing.expectEqualSlices(u8, canonical.written(), text_again); } test "fuzz quoted-printable" { for (codec_seeds) |seed| try quotedPrintableProperty(seed); try testing.fuzz({}, fuzzQuotedPrintable, .{}); } fn fuzzQuotedPrintable(_: void, smith: *testing.Smith) !void { var buffer: [codec_max]u8 = undefined; try quotedPrintableProperty(buffer[0..smith.slice(&buffer)]); } fn runQuotedPrintable(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [codec_max]u8 = undefined; return quotedPrintableProperty(buffer[0..smith.slice(&buffer)]); } // -- format=flowed ---------------------------------------------------------- const flowed_max = 2048; const flowed_seeds = [_][]const u8{ "one line\r\n", "a wrapped \r\nparagraph\r\n", "> quoted and wrapped \r\n> continued\r\n", ">>nested\r\n>one\r\nnone\r\n", " stuffed\r\n From here\r\n", "the message\r\n-- \r\nsignature\r\n", "hello world with a run of spaces\r\n", "日本語のテキストです\r\n", "a line ending in a space \r\n", ">\r\n>>\r\n>>>\r\n", "", " ", "\r\n\r\n\r\n", }; /// Wrapping text and joining it again gives the text back, at every width. /// /// The input has to be normalised first, and the normalisation is the format's /// own limitation rather than a convenience: a line ending in a space *is* a /// wrapped line, so a paragraph that ends in one cannot be told from one that /// continues, and no encoding can preserve the difference. Stripping those is /// exactly what a generator has to do, and what is left is what the format can /// carry. fn flowedProperty(input: []const u8) !void { // Joining is total: there is no input that is not a flowed body for // something, and it must never fail on one. const joined = try mime.flowed.unflowAlloc(backing, input, .{}); defer backing.free(joined); const deleted = try mime.flowed.unflowAlloc(backing, input, .{ .delete_space = true }); defer backing.free(deleted); const normalised = try normaliseParagraphs(input); defer backing.free(normalised); for ([_]usize{ 1, 5, 20, 72, 998 }) |width| { for ([_]bool{ false, true }) |delete_space| { const wrapped = try mime.flowed.flowAlloc(backing, normalised, .{ .width = width, .delete_space = delete_space, }); defer backing.free(wrapped); // The width is deliberately not asserted here. A line is allowed // to run over it in three different ways -- an unbreakable word, a // break pushed out so that it did not come out as the signature // separator, and the separator itself -- and a property that has // to enumerate its own exceptions tests the exceptions rather than // the rule. The wrapping tests beside `flowWriter` pin the width // on inputs where the answer is known; what is worth checking over // input nobody wrote is that nothing is lost. const back = try mime.flowed.unflowAlloc(backing, wrapped, .{ .delete_space = delete_space, }); defer backing.free(back); try testing.expectEqualStrings(normalised, back); } } } /// The input as paragraphs the format can carry: CRLF endings, and no line /// ending in a space. fn normaliseParagraphs(input: []const u8) ![]u8 { var out: Io.Writer.Allocating = .init(backing); errdefer out.deinit(); var rest = input; while (rest.len != 0) { const nl = std.mem.findScalar(u8, rest, '\n'); const end = if (nl) |at| (if (at != 0 and rest[at - 1] == '\r') at - 1 else at) else rest.len; try out.writer.writeAll(std.mem.trimEnd(u8, rest[0..end], " ")); try out.writer.writeAll("\r\n"); rest = if (nl) |at| rest[at + 1 ..] else rest[rest.len..]; } return out.toOwnedSlice(); } test "fuzz flowed" { for (flowed_seeds) |seed| try flowedProperty(seed); try testing.fuzz({}, fuzzFlowed, .{}); } fn fuzzFlowed(_: void, smith: *testing.Smith) !void { var buffer: [flowed_max]u8 = undefined; try flowedProperty(buffer[0..smith.slice(&buffer)]); } fn runFlowed(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [flowed_max]u8 = undefined; return flowedProperty(buffer[0..smith.slice(&buffer)]); } // -- uuencode --------------------------------------------------------------- const uuencode_max = 4096; const uuencode_seeds = [_][]const u8{ "begin 644 cat.txt\r\n#0V%T\r\n`\r\nend\r\n", "#0V%T\n`\n", "!80 \n \n", "begin 755 script.sh\n#0V%T\n`\nend\n", "a note first\n\nbegin 644 x\n#0V%T\n`\nend\n", "begin 644 truncated\n#0V%T\n", "begin\n", "X0V%T\n`\n", "not uuencode at all\n", "", }; /// Decoding a uuencoded body never fails, and anything encoded and decoded /// again is what went in — including the name, which is the one thing this /// encoding carries that the others do not. fn uuencodeProperty(input: []const u8) !void { const uuencode = mime.transfer_encoding.TransferEncoding.uuencode; // Total, like every other decoder here: a damaged attachment arrives // damaged rather than not arriving. const decoded = try uuencode.decodeAlloc(backing, input); defer backing.free(decoded); var encoded: Io.Writer.Allocating = .init(backing); defer encoded.deinit(); uuencode.encodeWriter(&encoded.writer, input, .{ .name = "fuzz.bin" }) catch return error.OutOfMemory; // Every line is inside what a transport will carry. var lines = std.mem.splitSequence(u8, encoded.written(), "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 998); try testing.expectEqualStrings("fuzz.bin", uuencode.embeddedName(encoded.written()).?); const again = try uuencode.decodeAlloc(backing, encoded.written()); defer backing.free(again); try testing.expectEqualSlices(u8, input, again); } test "fuzz uuencode" { for (uuencode_seeds) |seed| try uuencodeProperty(seed); try testing.fuzz({}, fuzzUuencode, .{}); } fn fuzzUuencode(_: void, smith: *testing.Smith) !void { var buffer: [uuencode_max]u8 = undefined; try uuencodeProperty(buffer[0..smith.slice(&buffer)]); } fn runUuencode(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [uuencode_max]u8 = undefined; return uuencodeProperty(buffer[0..smith.slice(&buffer)]); } // -- internationalized domain names ----------------------------------------- const idn_max = 512; const idn_seeds = [_][]const u8{ "example.com", "bücher.example", "xn--bcher-kva.example", "BÜCHER.EXAMPLE", "日本語.jp", "xn--wgv71a119e.jp", "a.b.c.example.com", "mail_1.example.com", "[192.0.2.1]", "a..b.example", "xn--", "xn--not-punycode", "example.com.", "", }; /// The A-label form is ASCII, is free of anything that could end a header /// line, and is a fixed point; and a name that survives the trip to Unicode /// and back is the same name. fn idnProperty(input: []const u8) !void { // Display is total: whatever arrives, something can be shown. const shown = try mime.idn.toUnicodeAlloc(backing, input); defer backing.free(shown); const ascii = mime.idn.toAsciiAlloc(backing, input) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // A name that will not encode is refused, which is the whole point of // that function: an address that cannot be encoded cannot be // delivered to, and guessing would deliver it somewhere else. error.InvalidDomain => return, }; defer backing.free(ascii); // What comes out is safe to put in a header, which is what it is for. try testing.expect(mime.idn.isAscii(ascii)); try testing.expect(!mime.idn.hasControl(ascii)); // Encoding an A-label again changes nothing. A conversion that is not a // fixed point is one that corrupts an address every time it is forwarded. const twice = try mime.idn.toAsciiAlloc(backing, ascii); defer backing.free(twice); try testing.expectEqualStrings(ascii, twice); // And the round trip through the displayed form is the same name, which // is the property that makes it safe to show one and send the other. const back = try mime.idn.toUnicodeAlloc(backing, ascii); defer backing.free(back); const again = mime.idn.toAsciiAlloc(backing, back) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.InvalidDomain => return, }; defer backing.free(again); try testing.expectEqualStrings(ascii, again); } test "fuzz idn" { for (idn_seeds) |seed| try idnProperty(seed); try testing.fuzz({}, fuzzIdn, .{}); } fn fuzzIdn(_: void, smith: *testing.Smith) !void { var buffer: [idn_max]u8 = undefined; try idnProperty(buffer[0..smith.slice(&buffer)]); } fn runIdn(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [idn_max]u8 = undefined; return idnProperty(buffer[0..smith.slice(&buffer)]); } // -- the streaming parser against the tree ---------------------------------- /// The two parsers see the same message. /// /// This is the property that makes a second parser safe to have at all. Two /// implementations of one format drift apart the moment either is touched, and /// the ways they can disagree — where a part begins, which delimiter closed /// what, whether a fold was joined the same way — are exactly the ways a /// message gets misread. Rather than assert that separately for each, both are /// asked to describe what they saw and the descriptions are compared. fn parserProperty(input: []const u8) !void { var message: mime.Message = try .parse(backing, input, .{}); defer message.deinit(); // The one documented difference: a `message/rfc822` that is transfer // encoded is decoded and opened by the tree, and left as bytes by the // stream, because opening it would mean holding it. var walker = message.root.walk(); while (walker.next()) |part| { if (part.media_type.isEncapsulatedMessage() and !part.transferEncoding().isIdentity()) { return; } } var from_tree: Io.Writer.Allocating = .init(backing); defer from_tree.deinit(); try describeTree(&from_tree.writer, &message.root, 0); var from_stream: Io.Writer.Allocating = .init(backing); defer from_stream.deinit(); // A small buffer on purpose: the awkward cases are the ones where a line // does not fit in it. var buffer: [128]u8 = undefined; var fixed: Io.Reader = .fixed(input); var limited = fixed.limited(.unlimited, &buffer); try describeStream(&from_stream.writer, &limited.interface); try testing.expectEqualStrings(from_tree.written(), from_stream.written()); } fn describeTree(w: *Io.Writer, part: *mime.Message.Part, depth: u8) !void { try w.print("begin {d}\n", .{depth}); for (part.headers.fields.items) |f| { const unfolded = try mime.field.unfoldAlloc(backing, f.value); defer backing.free(unfolded); try w.print("field {s}={s}\n", .{ f.name, std.mem.trim(u8, unfolded, " \t") }); } try w.print("headers {s}/{s}\n", .{ part.media_type.type, part.media_type.subtype }); switch (part.body) { .raw => |bytes| if (bytes.len != 0) { try w.print("body {f}\n", .{std.ascii.hexEscape(bytes, .lower)}); }, .multipart => |multipart| for (multipart.parts.items) |child| { try describeTree(w, child, depth + 1); }, .message => |inner| try describeTree(w, inner, depth + 1), } try w.print("end {d}\n", .{depth}); } fn describeStream(w: *Io.Writer, input: *Io.Reader) !void { var parser: mime.Parser = .init(backing, input, .{}); defer parser.deinit(); // The body arrives in as many chunks as the reader's buffer dictates, and // the tree has it whole, so it is gathered before being described. var body: Io.Writer.Allocating = .init(backing); defer body.deinit(); while (true) switch (try parser.next()) { .begin => |d| try w.print("begin {d}\n", .{d}), .field => |f| try w.print("field {s}={s}\n", .{ f.name, f.value }), .headers_end => try w.print("headers {s}/{s}\n", .{ parser.mediaType().type, parser.mediaType().subtype, }), .body => |chunk| try body.writer.writeAll(chunk), .end => |d| { if (body.written().len != 0) { try w.print("body {f}\n", .{std.ascii.hexEscape(body.written(), .lower)}); body.clearRetainingCapacity(); } try w.print("end {d}\n", .{d}); }, .eof => break, }; } test "fuzz the parser against the tree" { for (message_seeds) |seed| try parserProperty(seed); try testing.fuzz({}, fuzzParser, .{}); } fn fuzzParser(_: void, smith: *testing.Smith) !void { var buffer: [message_max]u8 = undefined; try parserProperty(buffer[0..smith.slice(&buffer)]); } fn runParser(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [message_max]u8 = undefined; return parserProperty(buffer[0..smith.slice(&buffer)]); } // -- mailto URLs ------------------------------------------------------------ const mailto_max = 2048; const mailto_seeds = [_][]const u8{ "mailto:alice@example.net", "mailto:alice@example.net?subject=Lunch&body=Shall%20we%3F", "mailto:a@x,b@y?to=c@z&cc=d@w&bcc=e@v", "mailto:?subject=Hello", "mailto:alice@example.net?from=bank@example.com", "mailto:jeff%2Blists@example.com", "mailto:%22Ollie%2C%20Jeff%22%20%3Cjeff@example.com%3E", "mailto:x?subject=%C3%BC&body=%", "mailto:x?=&=&a=b=c", "mailto:", "https://example.com", "", }; /// A URL is attacker-supplied by construction — it arrives in a web page — so /// what matters is what it cannot make the message become. fn mailtoProperty(input: []const u8) !void { var message = mime.mailto.parse(backing, input, .{}) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.NotMailto => return, }; defer message.deinit(); // Nothing outside the safe list was set, however the URL spelled it. // `MIME-Version` and the `Content-*` headers are deliberately absent from // this list: those are written by the library rather than by the URL. const forbidden = [_][]const u8{ "from", "reply-to", "sender", "return-path", "received", "message-id", "date", "resent-from", "disposition-notification-to", }; for (forbidden) |name| try testing.expect(!message.root.headers.has(name)); // The Content-Type is the one this library wrote. try testing.expect(message.root.media_type.is("text", "plain")); try testing.expectEqual(1, message.root.headers.count("content-type")); // What comes out is a message a transport will carry, and — the part that // matters — reading it back finds no field the URL was not allowed to set. // A header injected through a URL would appear here and nowhere else. // // Not asserted: that it is all ASCII. A local part may be UTF-8 under RFC // 6532, a `mailto:` is a UTF-8 URI, and refusing one would be refusing an // address that works. const written = try message.toBytesAlloc(backing); defer backing.free(written); var lines = std.mem.splitSequence(u8, written, "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 998); var reread: mime.Message = try .parse(backing, written, .{}); defer reread.deinit(); for (forbidden) |name| try testing.expect(!reread.root.headers.has(name)); // Whatever it parsed to, it parses to the same thing again. var again = try mime.mailto.parse(backing, input, .{}); defer again.deinit(); const twice = try again.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(written, twice); } test "fuzz mailto" { for (mailto_seeds) |seed| try mailtoProperty(seed); try testing.fuzz({}, fuzzMailto, .{}); } fn fuzzMailto(_: void, smith: *testing.Smith) !void { var buffer: [mailto_max]u8 = undefined; try mailtoProperty(buffer[0..smith.slice(&buffer)]); } fn runMailto(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [mailto_max]u8 = undefined; return mailtoProperty(buffer[0..smith.slice(&buffer)]); } // -- received --------------------------------------------------------------- const received_max = 1024; const received_seeds = [_][]const u8{ "client.example.com", "evil\r\nBcc: victim@example.test", "evil\nX-Spam-Status: No", "closes) a paren (and opens one", "a\x00b", "\r", "\n", " ", "", }; /// A `Received:` is assembled almost entirely out of things the peer said — /// the `EHLO` name, and whatever the caller passed through from the session — /// so the property is containment: whatever goes into the clauses, what comes /// out is **one** header field, and the fields that were already there are /// still exactly themselves. /// /// The failure this is looking for is a hop that can be made to write a header /// of the sender's choosing into every message it relays. fn receivedProperty(input: []const u8) !void { var when: mime.datetime.DateTime = .{ .year = 2003, .month = .Jul, .day = 1, .hour = 10, .minute = 52, .second = 37, .offset = 2 * 60 * 60, }; when.updateDayOfWeek(); // Everything a server would take off the wire, taken off the wire. const received: mime.received.Received = .{ .from = input, .from_info = input, .by = input, .by_info = input, .via = input, .with = input, .id = input, .for_recipient = input, .received_at = when, }; var message: mime.Message = try .parse( backing, "From: alice@example.com\r\nSubject: seed\r\n\r\nbody\r\n", .{}, ); defer message.deinit(); try message.addReceived(received); const written = try message.toBytesAlloc(backing); defer backing.free(written); var again: mime.Message = try .parse(backing, written, .{}); defer again.deinit(); // One field, whatever was in it. try testing.expectEqual(1, again.root.headers.count("received")); try testing.expectEqual(3, again.root.headers.fields.items.len); // And it is still the first one: a trace field that has drifted down the // block no longer says when this hop received the message relative to the // hops below it. try testing.expect(std.ascii.eqlIgnoreCase(again.root.headers.fields.items[0].name, "Received")); // The fields that were already there are untouched. try testing.expectEqualStrings("alice@example.com", again.root.headers.get("from") orelse ""); try testing.expectEqualStrings("seed", again.root.headers.get("subject") orelse ""); // And the second write agrees with the first. const twice = try again.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(written, twice); } test "fuzz received" { for (received_seeds) |seed| try receivedProperty(seed); try testing.fuzz({}, fuzzReceived, .{}); } fn fuzzReceived(_: void, smith: *testing.Smith) !void { var buffer: [received_max]u8 = undefined; try receivedProperty(buffer[0..smith.slice(&buffer)]); } fn runReceived(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [received_max]u8 = undefined; return receivedProperty(buffer[0..smith.slice(&buffer)]); } // -- report ----------------------------------------------------------------- const report_max = 4096; const report_seeds = [_][]const u8{ "Reporting-MTA: dns; mx.example.net\r\nArrival-Date: Tue, 01 Jul 2003 10:00:00 +0200\r\n" ++ "\r\nFinal-Recipient: rfc822; nobody@example.com\r\nAction: failed\r\nStatus: 5.1.1\r\n" ++ "Diagnostic-Code: smtp; 550 5.1.1 No such user\r\n", // No per-message group at all, which happens. "Final-Recipient: rfc822; a@example.com\r\nAction: delayed\r\nStatus: 4.4.1\r\n", // Two recipients, and a group that is neither. "Reporting-MTA: dns; mx\r\n\r\nFinal-Recipient: rfc822; a@x\r\nAction: failed\r\n" ++ "\r\nFinal-Recipient: rfc822; b@x\r\nAction: delivered\r\n\r\nX-Junk: here\r\n", // A read receipt. "Reporting-UA: mail.example.net; Thunderbird\r\nFinal-Recipient: rfc822; a@x\r\n" ++ "Original-Message-ID: <1@x>\r\nDisposition: manual-action/MDN-sent-manually; displayed\r\n", // A spam complaint. "Feedback-Type: abuse\r\nUser-Agent: SomeGenerator/1.0\r\nVersion: 1\r\n" ++ "Original-Mail-From: \r\nArrival-Date: Tue, 01 Jul 2003 10:00:00 +0200\r\n" ++ "Source-IP: 192.0.2.1\r\nIncidents: 4\r\n", // Values that make no sense where a number or a status is wanted. "Feedback-Type: \r\nVersion: 999999999999\r\nIncidents: -1\r\n", "Final-Recipient: \r\nAction: \r\nStatus: ...\r\nStatus: 999.999.999\r\n", "Status: 5.1\r\nStatus: 5.1.1.1\r\nStatus: a.b.c\r\n", // Blank lines everywhere, which is what separates the groups. "\r\n\r\n\r\n", "\n\na: 1\n\n\nb: 2", "Diagnostic-Code: smtp;\r\n 550 folded\r\n onto three lines\r\n", "", }; /// Touches every accessor, so that the fuzzer reaches the parsing each of them /// does on top of the field it reads — a `Status` of `999.999.999`, a date /// that is not one, a `Version` too big for the integer it goes into. /// /// The answers are not checked against anything: what is being asked is that /// they can all be reached on any input at all, which is the question a /// program walking a bounce it did not write is really asking. fn touchDeliveryStatus(status: *mime.delivery_status.DeliveryStatus) !void { _ = try status.reportingMta(); _ = try status.arrivalDate(); _ = try status.hasPermanentFailure(); for (status.recipients.items) |*recipient| { _ = try recipient.finalRecipient(); _ = try recipient.originalRecipient(); _ = try recipient.action(); if (try recipient.status()) |found| { _ = found.isPermanentFailure(); _ = found.isTransientFailure(); _ = found.isSuccess(); // A status writes back out as the three numbers it holds, and // reading those again gives the same three. var buffer: [32]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try w.print("{f}", .{found}); const again = mime.delivery_status.Status.parse(w.buffered()) orelse return error.StatusDidNotSurviveItsOwnFormat; try testing.expectEqual(found, again); } _ = try recipient.remoteMta(); _ = try recipient.diagnosticCode(); _ = try recipient.lastAttempt(); _ = try recipient.willRetryUntil(); } } fn touchDispositionNotification(mdn: *mime.disposition_notification.DispositionNotification) !void { _ = try mdn.disposition(); _ = try mdn.finalRecipient(); _ = try mdn.originalRecipient(); _ = try mdn.originalMessageId(); _ = try mdn.reportingUa(); _ = try mdn.failure(); _ = try mdn.@"error"(); } fn touchFeedbackReport(arf: *mime.feedback_report.FeedbackReport) !void { _ = try arf.feedbackType(); _ = try arf.userAgent(); _ = try arf.version(); _ = try arf.originalMailFrom(); _ = try arf.originalRcptTo(); _ = try arf.removalRecipient(); _ = try arf.sourceIp(); _ = try arf.reportedDomain(); _ = try arf.arrivalDate(); _ = try arf.incidents(); } /// The bodies of the three report types, which arrive in a bounce and are /// therefore written by a system the recipient has never met — and, in the /// case of a spam complaint about a message the sender did send, partly by /// whoever provoked the report. /// /// The property is the one the message target asks for: parsing and writing /// may repair the input, but doing it twice must change nothing. A parser and /// a writer that disagree about where a group ends are how a bounce for one /// recipient turns into a bounce that names another. fn reportProperty(input: []const u8) !void { // Whatever the groups are, they are non-empty, in order, and inside the // input: the iterator returns subslices, and a caller keeps them. { var groups: mime.report.GroupIterator = .init(input); var end: usize = 0; while (groups.next()) |group| { try testing.expect(group.len != 0); const start = @intFromPtr(group.ptr) - @intFromPtr(input.ptr); try testing.expect(start >= end); end = start + group.len; try testing.expect(end <= input.len); } } { var first = try mime.report.firstGroup(backing, input); defer first.deinit(); } { var status: mime.delivery_status.DeliveryStatus = try .parse(backing, input); defer status.deinit(); try touchDeliveryStatus(&status); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try status.write(&once.writer); var again: mime.delivery_status.DeliveryStatus = try .parse(backing, once.written()); defer again.deinit(); try touchDeliveryStatus(&again); // The groups survive: a recipient lost or gained on the way out is a // bounce that reports on the wrong address. try testing.expectEqual(status.recipients.items.len, again.recipients.items.len); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); } { var mdn: mime.disposition_notification.DispositionNotification = try .parse(backing, input); defer mdn.deinit(); try touchDispositionNotification(&mdn); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try mdn.write(&once.writer); var again: mime.disposition_notification.DispositionNotification = try .parse(backing, once.written()); defer again.deinit(); try touchDispositionNotification(&again); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); } { var arf: mime.feedback_report.FeedbackReport = try .parse(backing, input); defer arf.deinit(); try touchFeedbackReport(&arf); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try arf.write(&once.writer); var again: mime.feedback_report.FeedbackReport = try .parse(backing, once.written()); defer again.deinit(); try touchFeedbackReport(&again); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); } // And the typed value the report fields are made of, on the raw input: // whatever it makes of it, writing it back gives something it makes the // same thing of. { const typed = mime.report.TypedValue.parse(input); var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); try typed.write(&out.writer); const again = mime.report.TypedValue.parse(out.written()); try testing.expectEqualStrings(typed.type, again.type); try testing.expectEqualStrings(typed.value, again.value); } } test "fuzz report" { for (report_seeds) |seed| try reportProperty(seed); try testing.fuzz({}, fuzzReport, .{}); } fn fuzzReport(_: void, smith: *testing.Smith) !void { var buffer: [report_max]u8 = undefined; try reportProperty(buffer[0..smith.slice(&buffer)]); } fn runReport(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [report_max]u8 = undefined; return reportProperty(buffer[0..smith.slice(&buffer)]); } // -- build ------------------------------------------------------------------ const build_max = 4096; const build_seeds = [_][]const u8{ "Hello, world.\r\n", "Hello, world.\n", "line one\rline two\r\nline three\n", "ünïcödé and a very long line that will have to be wrapped somewhere by whatever encoding gets chosen for it", "=3D already looks encoded\r\n", "trailing space \r\nand a tab\t\r\n", "-- \r\nsignature\r\n", ".\r\n", "From the beginning of a line\r\n", "\x00\x01\x02\x7f\xff", "a" ** 200, "\r\n\r\n\r\n", "", "résumé.pdf", "a/b/../c.txt", "..", "name with spaces and \"quotes\".txt", "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e.txt", }; /// A deterministic knob, so that the shape of the message being built varies /// with the input rather than with a random number the input cannot reach. fn knob(bytes: []const u8, salt: u8) u8 { var h: u8 = salt; for (bytes) |c| h = h ^ c ^ (h << 1); return h; } /// Composing a message and reading it back: the other direction from every /// other target here, and the one a program that *sends* mail depends on. /// /// The property is that a body survives the trip. A text body, an attachment, /// a subject and a filename go in; the message is written out, parsed by the /// same library, and each of them is asked for again. Nothing about the wire /// form is asserted — which encoding was chosen, where it wrapped, what the /// boundary was — because all of that is free to change. What is not free to /// change is the content. /// /// This is where an encoder and a decoder that disagree show up: a /// quoted-printable wrap that eats a space, a base64 line that loses a byte, /// an RFC 2231 filename that comes back in pieces, an encoded-word subject /// that arrives in the wrong charset. fn buildProperty(text: []const u8, name: []const u8) !void { var prng: std.Random.DefaultPrng = .init(knob(text, 7)); const random = prng.random(); const choice = knob(name, 3); var message: mime.Message = try .init(backing); defer message.deinit(); try message.root.setSubject(text); try message.setText(text, .{ .subtype = if (choice & 1 == 0) "plain" else "html", .format = if (choice & 2 == 0) .fixed else .flowed, .encoding = switch ((choice >> 2) & 3) { 0 => null, 1 => .quoted_printable, 2 => .base64, else => .eight_bit, }, }); const attached = try message.attach(random, text, .{ .filename = if (name.len == 0) null else name, .encoding = switch ((choice >> 4) & 3) { 0 => null, 1 => .quoted_printable, 2 => .base64, else => .uuencode, }, }); _ = attached; const wire = try message.toBytesAlloc(backing); defer backing.free(wire); var read: mime.Message = try .parse(backing, wire, .{}); defer read.deinit(); // The attachment is the thing a receiver saves to disk, and it must be // the bytes that were handed over -- not canonicalised, not re-wrapped. var found: ?*mime.Message.Part = null; var it = read.root.attachments(); while (it.next()) |part| found = part; const attachment = found orelse return error.AttachmentDisappeared; const bytes = try attachment.decodeAlloc(backing); defer backing.free(bytes); try testing.expectEqualStrings(text, bytes); // And the name it is saved under, when the name is one the library // promises to reproduce. `filename` decodes *to UTF-8*, so a name that is // not valid UTF-8 comes back with replacement characters in it and that is // the documented behaviour rather than a loss -- the name is going to be // shown to somebody. if (name.len != 0 and std.unicode.utf8ValidateSlice(name)) { if (try attachment.filename()) |got| { try testing.expectEqualStrings(name, got); } else return error.FilenameDisappeared; } // The text body comes back as what was written, with the line endings // `setText` canonicalised on the way in -- see its doc comment for why it // does that -- and, under `format=flowed`, rewrapped, which is the whole // point of that format and not a loss. // // And only when the text really is UTF-8, which is what `setText` // declared it to be: `textAlloc` decodes *to* UTF-8, so bytes that were // never UTF-8 come back as replacement characters. That is the library // repairing a caller that mislabelled its own text, not losing it. if (choice & 2 == 0 and choice & 1 == 0 and std.unicode.utf8ValidateSlice(text)) { const body = read.root.findText(&.{"plain"}) orelse return error.TextDisappeared; const got = try body.textAlloc(backing); defer backing.free(got); var canonical: Io.Writer.Allocating = .init(backing); defer canonical.deinit(); try mime.line_ending.toCanonical(&canonical.writer, text); try testing.expectEqualStrings(canonical.written(), got); } // Writing what was read gives what was written: the composer and the // parser agree about the message they are both describing. const twice = try read.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(wire, twice); } test "fuzz build" { for (build_seeds) |seed| { for (build_seeds) |name| try buildProperty(seed, name); } try testing.fuzz({}, fuzzBuild, .{}); } // Both buffers are `build_max`, and deliberately: `Smith.slice` answers a // length larger than the buffer it is given with an **empty** slice rather // than a truncated one, and the driver writes both lengths from the same // `content_max`. A smaller buffer for the name would therefore hand this // target no filename at all on most inputs, and the run would report its // millions of iterations without ever having encoded one. fn fuzzBuild(_: void, smith: *testing.Smith) !void { var text: [build_max]u8 = undefined; var name: [build_max]u8 = undefined; const body = text[0..smith.slice(&text)]; try buildProperty(body, name[0..smith.slice(&name)]); } fn runBuild(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var text: [build_max]u8 = undefined; var name: [build_max]u8 = undefined; const body = text[0..smith.slice(&text)]; return buildProperty(body, name[0..smith.slice(&name)]); } // -- chunks ----------------------------------------------------------------- const chunk_max = 4096; const chunk_seeds = [_][]const u8{ "SGVsbG8sIHdvcmxkLg==\r\n", "SGVsbG8s\r\nIHdvcmxkLg==\r\n", "SGVsbG8sIHdvcmxkLg", "=?", "a=3Db=\r\nc\r\n", "trailing=20\r\n", "=41=42=4", "=\r\n", "begin 644 cat.txt\r\n#0V%T\r\n`\r\nend\r\n", "begin 644 x\n#0V%T\n", "plain text, no encoding at all\r\n", "\x00\x01\x02\xff", "", }; /// The chunk-wise decoders, fed the same body split in every way the input /// asks for. /// /// Streaming extraction exists so that a twenty megabyte attachment does not /// have to be held whole, and the way it goes wrong is at the joins: a base64 /// group split across two chunks, a quoted-printable `=41` whose `4` ended one /// read and whose `1` began the next, a uuencoded line that arrived in /// pieces. None of that is reachable by a test that hands the decoder the /// whole body at once, and all of it is reachable by a reader whose buffer /// happens to fill at the wrong byte. /// /// So the property is that **where the splits fall makes no difference**: the /// same body decoded in one piece, in single bytes, and at the boundaries the /// input picks, gives the same output all three times. The slice decoder is /// the reference, which is also what keeps the two implementations one /// implementation. fn chunkProperty(input: []const u8, splits: []const u8) !void { const encodings = [_]mime.transfer_encoding.TransferEncoding{ .base64, .quoted_printable, .uuencode, .seven_bit, .eight_bit, .binary, }; for (encodings) |encoding| { // The reference: the whole body at once, through the slice form. const whole = try encoding.decodeAlloc(backing, input); defer backing.free(whole); // One byte at a time, which is the worst case for every join there is. { var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); var decoder: mime.transfer_encoding.Decoder = .init(encoding); defer decoder.deinit(backing); for (input) |c| try decoder.write(backing, &out.writer, &.{c}); try decoder.finish(backing, &out.writer); try testing.expectEqualStrings(whole, out.written()); } // And at the boundaries the input asks for, so that a join landing on // a particular byte -- the `=` of an escape, the `\r` of a line // ending, the last character of a base64 group -- is reachable. { var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); var decoder: mime.transfer_encoding.Decoder = .init(encoding); defer decoder.deinit(backing); var at: usize = 0; var which: usize = 0; while (at < input.len) { const step = if (splits.len == 0) input.len - at else @min(input.len - at, @as(usize, splits[which % splits.len]) + 1); which += 1; try decoder.write(backing, &out.writer, input[at..][0..step]); at += step; } try decoder.finish(backing, &out.writer); try testing.expectEqualStrings(whole, out.written()); } // An empty chunk is what a reader hands over when it happened to read // nothing, and must change nothing at all. { var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); var decoder: mime.transfer_encoding.Decoder = .init(encoding); defer decoder.deinit(backing); try decoder.write(backing, &out.writer, ""); try decoder.write(backing, &out.writer, input); try decoder.write(backing, &out.writer, ""); try decoder.finish(backing, &out.writer); try testing.expectEqualStrings(whole, out.written()); } } } test "fuzz chunks" { for (chunk_seeds) |seed| { for (chunk_seeds) |splits| try chunkProperty(seed, splits); try chunkProperty(seed, &.{ 0, 1, 2, 3 }); } try testing.fuzz({}, fuzzChunks, .{}); } fn fuzzChunks(_: void, smith: *testing.Smith) !void { var body: [chunk_max]u8 = undefined; var splits: [chunk_max]u8 = undefined; const content = body[0..smith.slice(&body)]; try chunkProperty(content, splits[0..smith.slice(&splits)]); } fn runChunks(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var body: [chunk_max]u8 = undefined; var splits: [chunk_max]u8 = undefined; const content = body[0..smith.slice(&body)]; return chunkProperty(content, splits[0..smith.slice(&splits)]); } // -- encode-stream ---------------------------------------------------------- /// The other side of `chunks`: encoding a body from a reader must produce /// exactly what encoding it from a slice produces. /// /// `Part.setDataStreaming` exists so that a file can be attached without being /// read into memory, and it reaches a different function from the one /// `setData` uses. Two functions that are supposed to write the same bytes is /// the shape this project keeps trying to avoid, and where it cannot be /// avoided the way to keep it honest is to make the fuzzer compare them — /// which also means the encoded body does not depend on how the file happened /// to be read. /// /// Only the encodings `streams` admits are asked; quoted-printable is not one /// of them, and `setDataStreaming` is the way in that handles that. fn encodeStreamProperty(input: []const u8, name: []const u8) !void { const encodings = [_]mime.transfer_encoding.TransferEncoding{ .base64, .uuencode, .seven_bit, .eight_bit, .binary, }; const options: mime.transfer_encoding.EncodeOptions = .{ .name = if (name.len == 0) null else name, }; for (encodings) |encoding| { try testing.expect(encoding.streams()); var whole: Io.Writer.Allocating = .init(backing); defer whole.deinit(); try encoding.encodeWriter(&whole.writer, input, options); // Through a reader whose buffer is deliberately small, so that the // encoder is handed the body in pieces it did not choose. var streamed: Io.Writer.Allocating = .init(backing); defer streamed.deinit(); var source: Io.Reader = .fixed(input); try encoding.encodeStream(&source, &streamed.writer, options); try testing.expectEqualStrings(whole.written(), streamed.written()); // And what either of them wrote decodes back to what went in. const back = try encoding.decodeAlloc(backing, whole.written()); defer backing.free(back); try testing.expectEqualStrings(input, back); } } test "fuzz encode-stream" { for (build_seeds) |seed| { for (build_seeds) |name| try encodeStreamProperty(seed, name); } try testing.fuzz({}, fuzzEncodeStream, .{}); } fn fuzzEncodeStream(_: void, smith: *testing.Smith) !void { var body: [chunk_max]u8 = undefined; var name: [chunk_max]u8 = undefined; const content = body[0..smith.slice(&body)]; try encodeStreamProperty(content, name[0..smith.slice(&name)]); } fn runEncodeStream(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var body: [chunk_max]u8 = undefined; var name: [chunk_max]u8 = undefined; const content = body[0..smith.slice(&body)]; return encodeStreamProperty(content, name[0..smith.slice(&name)]); } // -- headers-edit ----------------------------------------------------------- /// Editing a header block, rather than only reading one. /// /// `set` and `remove` walk the list freeing as they go and keeping an index /// that the list is shifting underneath them, which is the shape that produces /// a double free or a value read after it was freed. The `headers` target /// never reaches any of it: it parses and writes and never edits. A program /// that handles mail edits constantly — it sets a `Subject`, removes a /// `Bcc`, prepends a `Received` — and does it to a block somebody else wrote. /// /// The properties are the ones the names promise. `set` leaves exactly one /// field of that name and does not move it; `remove` leaves none; `prepend` /// and `prependTrace` put the field where each says it does; and after all of /// it the block still writes and parses back to itself. fn headersEditProperty(block: []const u8, text: []const u8) !void { var headers: mime.Headers = try .parse(backing, block); defer headers.deinit(); // A name taken from the input, so that the edits land on fields that are // really there as often as on ones that are not. A field name may not // hold a colon or a line ending, and `append` is entitled to assume that. var name_buffer: [64]u8 = undefined; var len: usize = 0; for (text) |c| { if (len == name_buffer.len) break; switch (c) { 0...0x20, 0x7f, ':' => continue, else => {}, } name_buffer[len] = c; len += 1; } const name = if (len == 0) "X-Fuzz" else name_buffer[0..len]; const before = headers.count(name); try testing.expectEqual(before, countByIterator(&headers, name)); try testing.expectEqual(before != 0, headers.has(name)); // `append` adds exactly one. try headers.append(name, text); try testing.expectEqual(before + 1, headers.count(name)); try testing.expect(headers.has(name)); // `prepend` puts it at the front. try headers.prepend(name, text); try testing.expect(std.ascii.eqlIgnoreCase(headers.fields.items[0].name, name)); try testing.expectEqual(before + 2, headers.count(name)); // `prependTrace` goes to the front too, unless a `Return-Path` is there, // in which case it goes under it and under no more than the run of them. try headers.prependTrace("Received", "by fuzz.example; Tue, 01 Jul 2003 10:52:37 +0200"); { var at: usize = 0; while (std.ascii.eqlIgnoreCase(headers.fields.items[at].name, "Return-Path")) : (at += 1) {} try testing.expect(std.ascii.eqlIgnoreCase(headers.fields.items[at].name, "Received")); } // `set` leaves exactly one, and leaves it where the first one was. const index_before = firstIndex(&headers, name); try headers.set(name, text); try testing.expectEqual(1, headers.count(name)); try testing.expectEqual(index_before, firstIndex(&headers, name)); // And what comes back is a fixed point: setting the value that was read // back reads back the same again. Asking instead for the text that went // in would need this test to model the folder -- where it breaks a long // line, which runs of whitespace it keeps, which bare line endings it // drops because a header value is one logical line -- and a model of a // thing is not a test of it. What matters to a caller is that a value // read out and put back does not drift on each pass. const read_back = (try headers.getUnfolded(name)) orelse return error.SetThenGetFoundNothing; const kept = try backing.dupe(u8, read_back); defer backing.free(kept); try headers.set(name, kept); if (try headers.getUnfolded(name)) |twice_over| { try testing.expectEqualStrings(kept, twice_over); } else return error.SetThenGetFoundNothing; // `remove` leaves none, and says how many it took. try testing.expectEqual(1, headers.remove(name)); try testing.expectEqual(0, headers.count(name)); try testing.expect(!headers.has(name)); try testing.expect(headers.get(name) == null); try testing.expectEqual(0, headers.remove(name)); // Whatever is left still writes and reads back to itself. var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try headers.write(&once.writer); var again: mime.Headers = try .parse(backing, once.written()); defer again.deinit(); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); } fn countByIterator(headers: *mime.Headers, name: []const u8) usize { var n: usize = 0; var it = headers.iterator(name); while (it.next() != null) n += 1; return n; } fn firstIndex(headers: *mime.Headers, name: []const u8) ?usize { for (headers.fields.items, 0..) |f, i| { if (std.ascii.eqlIgnoreCase(f.name, name)) return i; } return null; } test "fuzz headers-edit" { for (header_seeds) |seed| { for (header_seeds) |text| try headersEditProperty(seed, text); } try testing.fuzz({}, fuzzHeadersEdit, .{}); } fn fuzzHeadersEdit(_: void, smith: *testing.Smith) !void { var block: [header_max]u8 = undefined; var text: [header_max]u8 = undefined; const parsed = block[0..smith.slice(&block)]; try headersEditProperty(parsed, text[0..smith.slice(&text)]); } fn runHeadersEdit(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var block: [header_max]u8 = undefined; var text: [header_max]u8 = undefined; const parsed = block[0..smith.slice(&block)]; return headersEditProperty(parsed, text[0..smith.slice(&text)]); }