Something went wrong. Try again.
A Gmail API client library for Zig: labels, messages, and the mailbox history that turns a second sync into an update.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the parsers must do with input nobody wrote.//!//! Everything this library parses arrived over the network from a service//! nobody here controls, and the failure that matters is not "a strange//! message is misread" -- it is "a strange message stops the sync", because a//! mailbox walk that dies on message 40,000 has to be understood before it//! can be resumed. So each target states a property rather than an example://! whatever arrives, the parser terminates, stays inside its buffers, leaks//! nothing, and never invents a field that was not there.//!//! The strongest property here is the lenient one. Gmail omits empty fields,//! adds new ones without warning, and sends 64-bit numbers as quoted strings;//! a parser that failed on any of those would work in testing and stop//! working on somebody's real mailbox. `message` and `history` assert that//! anything with an id parses, and that everything else is either read//! correctly or reported absent -- never read as something else.//!//! 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.//!//! 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 more, and `tools/fuzz.zig` is the loop that stands in.
const builtin = @import("builtin");const std = @import("std");const testing = std.testing;const Allocator = std.mem.Allocator;const Smith = std.testing.Smith;
const gmail = @import("gmail");
/// 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;
/// Parses `input` as JSON and hands the value to `f`, along with an arena for/// whatever it builds. Input that is not JSON is not interesting: every/// parser here is reached only after `std.json` has already accepted the/// body, so feeding them non-JSON would fuzz `std.json` instead.fn withJson( input: []const u8, comptime f: fn (Allocator, std.json.Value) anyerror!void,) !void { var parsed = std.json.parseFromSlice(std.json.Value, backing, input, .{}) catch return; defer parsed.deinit();
var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit();
try f(arena.allocator(), parsed.value);}
// -- messages ---------------------------------------------------------------
const message_seeds = [_][]const u8{ \\{"id":"a","threadId":"b","labelIds":["INBOX"],"internalDate":"1700000000000"} , \\{"id":"a","payload":{"mimeType":"multipart/mixed","headers":[{"name":"Subject","value":"x"}], \\ "parts":[{"mimeType":"text/plain","body":{"data":"aGk","size":2}}]}} , \\{"id":"a","raw":"U3ViamVjdDogaGkKCmJvZHkK"} , \\{"id":"a","raw":"!!!!"} , \\{"id":"a","historyId":"18446744073709551615","internalDate":"-9223372036854775808"} , \\{"id":"a","historyId":18446744073709551615,"sizeEstimate":-1} , \\{"id":"a","labelIds":[null,1,{},[],"X"],"payload":{"headers":[{},{"name":"A"}]}} , \\{"threadId":"no id here"} , \\{"id":"","labelIds":[],"payload":{}} , "{}", "[]", "null", \\{"id":"a","payload":{"parts":[{"parts":[{"parts":[{"mimeType":"text/plain"}]}]}]}} , \\{"id":"a","internalDate":"not a number","historyId":""} ,};
/// Anything with a string `id` parses; anything without one is `Malformed`,/// and nothing in between. Every optional field is either absent or holds/// what the input actually said.fn messageProperty(alloc: Allocator, value: std.json.Value) !void { const has_id = value == .object and if (value.object.get("id")) |i| i == .string else false;
const message = gmail.Message.fromJson(alloc, value) catch |err| { try testing.expectEqual(error.Malformed, err); try testing.expect(!has_id); return; }; try testing.expect(has_id);
// A thread id is never null: absent, it is the message's own id. try testing.expect(message.thread_id.len > 0 or message.id.len == 0);
// Every label is a string that was in the input's label array. const input_labels = if (value.object.get("labelIds")) |l| switch (l) { .array => |a| a.items.len, else => 0, } else 0; try testing.expect(message.label_ids.len <= input_labels); for (message.label_ids) |l| try testing.expect(message.hasLabel(l));
// `hasLabel` for something not in the list is false, always. try testing.expect(!message.hasLabel("\x00 no label is spelled like this"));
// A timestamp exists exactly when an internal date does, and converting // it does not overflow: the widest `internalDate` is an i64 of // milliseconds, which is an i96 of nanoseconds. if (message.internal_date) |ms| { const ts = message.timestamp().?; try testing.expectEqual(@as(i96, ms) * std.time.ns_per_ms, ts.nanoseconds); } else { try testing.expectEqual(@as(?std.Io.Timestamp, null), message.timestamp()); }
// The tree is bounded, and every part in it is reachable by walking it. if (message.payload) |p| { const depth = try depthOf(&p, 0); try testing.expect(depth < gmail.Message.max_depth); // A header lookup for a name that cannot occur finds nothing, at any // depth, without recursing forever. try testing.expectEqual(@as(?[]const u8, null), p.header("\x00")); try testing.expectEqual( @as(?*const gmail.Message.MessagePart, null), p.findByMimeType("\x00/\x00"), ); }}
fn depthOf(part: *const gmail.Message.MessagePart, depth: usize) !usize { // The parser caps the tree, so this cannot run away; asserting it here // would be circular, so the bound is asserted by the caller instead. try testing.expect(depth < gmail.Message.max_depth); var deepest = depth; for (part.parts) |*child| deepest = @max(deepest, try depthOf(child, depth + 1)); return deepest;}
test "fuzz messages" { for (message_seeds) |seed| try withJson(seed, messageProperty); try testing.fuzz({}, fuzzMessage, .{});}
fn fuzzMessage(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try withJson(buffer[0..len], messageProperty);}
// -- history ----------------------------------------------------------------
const history_seeds = [_][]const u8{ \\{"id":"1","messagesAdded":[{"message":{"id":"m1"}}]} , \\{"id":"1","messages":[{"id":"m1"}],"messagesDeleted":[{"message":{"id":"m2"}}], \\ "labelsAdded":[{"message":{"id":"m3"},"labelIds":["A","B"]}], \\ "labelsRemoved":[{"message":{"id":"m3"},"labelIds":[]}]} , \\{"id":"18446744073709551615"} , \\{"id":"-1"} , \\{"id":1} , \\{"messages":[]} , \\{"id":"1","labelsAdded":[{"labelIds":["A"]},{"message":{}},42,null]} , \\{"id":"1","messagesAdded":"not an array"} , "{}", "[]",};
/// A record with a numeric `id` parses and one without does not; every change/// the iterator yields names a message that was in one of the four lists.fn historyProperty(alloc: Allocator, value: std.json.Value) !void { const history = gmail.History.fromJson(alloc, value) catch |err| { try testing.expectEqual(error.Malformed, err); return; };
var counted: usize = 0; var it = history.changes(); while (it.next()) |change| : (counted += 1) { const id = change.messageId(); // Every change points at a message the parser kept, so the id is a // slice of the arena and not a dangling one. Touching it is the test. try testing.expect(id.len == id.len);
switch (change) { .labels_added, .labels_removed => |l| { for (l.label_ids) |label| try testing.expect(label.len == label.len); }, .added, .deleted => {}, } // A history page is bounded by the input, so the walk terminates. try testing.expect(counted < 1_000_000); }
try testing.expectEqual( history.messages_added.len + history.messages_deleted.len + history.labels_added.len + history.labels_removed.len, counted, );
// Iterating twice gives the same answer: the iterator holds no state that // outlives it. var again = history.changes(); var second: usize = 0; while (again.next()) |_| second += 1; try testing.expectEqual(counted, second);}
test "fuzz history" { for (history_seeds) |seed| try withJson(seed, historyProperty); try testing.fuzz({}, fuzzHistory, .{});}
fn fuzzHistory(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try withJson(buffer[0..len], historyProperty);}
// -- labels -----------------------------------------------------------------
const label_seeds = [_][]const u8{ \\{"id":"INBOX","name":"INBOX","type":"system"} , \\{"id":"Label_1","name":"x","type":"user","messagesTotal":1, \\ "color":{"textColor":"#fff","backgroundColor":"#000"}} , \\{"id":"X","type":"shimmer","messageListVisibility":"maybe", \\ "labelListVisibility":"labelMaybe"} , \\{"id":"X","color":"not an object","messagesTotal":"12"} , \\{"id":"CATEGORY_FORUMS","type":"system"} , \\{"name":"no id"} , "{}", "[]",};
/// A label with a string `id` parses, and its conventional name is always/// something: a system label's is fixed, and a user label's is its own name.fn labelProperty(_: Allocator, value: std.json.Value) !void { const label = gmail.Label.fromJson(value) catch |err| { try testing.expectEqual(error.Malformed, err); return; };
const conventional = label.conventionalName(); if (gmail.Label.SystemId.fromId(label.id)) |s| { // A known system id always maps to a fixed non-empty name, whatever // the rest of the object claimed. try testing.expectEqualStrings(s.conventionalName(), conventional); try testing.expect(conventional.len > 0); } else { try testing.expectEqualStrings(label.name, conventional); }
// The enums are always one of their tags -- an unrecognised wire value // becomes the documented default rather than an invalid enum. try testing.expect(std.enums.tagName(gmail.Label.Type, label.type) != null); try testing.expect(std.enums.tagName( gmail.Label.MessageListVisibility, label.message_list_visibility, ) != null); try testing.expect(std.enums.tagName( gmail.Label.LabelListVisibility, label.label_list_visibility, ) != null);}
test "fuzz labels" { for (label_seeds) |seed| try withJson(seed, labelProperty); try testing.fuzz({}, fuzzLabel, .{});}
fn fuzzLabel(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try withJson(buffer[0..len], labelProperty);}
// -- error objects ----------------------------------------------------------
const api_error_seeds = [_][]const u8{ \\{"error":{"code":429,"message":"slow down","errors":[{"reason":"rateLimitExceeded"}]}} , \\{"error":{"code":403,"errors":[{"reason":"dailyLimitExceeded"}]}} , \\{"error":{"code":401,"status":"UNAUTHENTICATED"}} , \\{"error":{"errors":[1,null,{},{"reason":null}]}} , \\{"error":{"code":999999999999999}} , \\{"error":"invalid_grant"} , \\{"error":{}} , "{}", "<html>502 Bad Gateway</html>", "",};
/// Whatever the body, `parse` either refuses it or produces an object whose/// two questions -- retryable, auth failure -- answer without crashing for/// every status. `dailyLimitExceeded` is never retryable, which is the one/// answer a wrong parse could make expensive.fn apiErrorProperty(input: []const u8) !void { var e = gmail.ApiError.parse(backing, input) catch |err| { try testing.expectEqual(error.NotAnError, err); return; }; defer e.deinit();
for ([_]std.http.Status{ .ok, .bad_request, .unauthorized, .forbidden, .not_found, .too_many_requests, .internal_server_error, .bad_gateway, .service_unavailable, }) |status| { const retryable = e.isRetryable(status); _ = e.isAuthFailure(status);
// A 2xx or a 404 is never worth retrying, whatever the body says. if (status == .ok or status == .not_found) try testing.expect(!retryable);
if (e.reason()) |r| { if (std.mem.eql(u8, r, "dailyLimitExceeded") and status == .forbidden) { try testing.expect(!retryable); } } }
// Formatting never writes more than the buffer, and never fails for any // other reason. var buf: [4096]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); e.format(&w) catch |err| try testing.expectEqual(error.WriteFailed, err);
// Every detail's reason, if there is one, is findable by `reason`. if (e.details.len > 0) { for (e.details) |d| { if (d.reason != null) { try testing.expect(e.reason() != null); break; } } } else { try testing.expectEqual(@as(?[]const u8, null), e.reason()); }}
test "fuzz error objects" { for (api_error_seeds) |seed| try apiErrorProperty(seed); try testing.fuzz({}, fuzzApiError, .{});}
fn fuzzApiError(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try apiErrorProperty(buffer[0..len]);}
// -- batch responses --------------------------------------------------------
const batch_seeds = [_][]const u8{ "\r\n--b\r\nContent-Type: application/http\r\nContent-ID: <response-0>\r\n\r\n" ++ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"id\":\"m1\"}\n\r\n--b--\r\n", "\r\n--b\r\nContent-ID: <response-1>\r\n\r\nHTTP/1.1 404 Not Found\r\n\r\n" ++ "{\"error\":{\"code\":404}}\r\n--b--\r\n", // Every way a Content-ID can fail to be a number. "\r\n--b\r\nContent-ID: response-\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{}\r\n--b--\r\n", "\r\n--b\r\nContent-ID: <response-99999999999999999999>\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{}\r\n--b--\r\n", "\r\n--b\r\nContent-ID: <item1:1@example.com>\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{}\r\n--b--\r\n", // A status line that is not one, and one whose number is not a status. "\r\n--b\r\n\r\nnot a status line\r\n\r\n{}\r\n--b--\r\n", "\r\n--b\r\n\r\nHTTP/1.1 99999 What\r\n\r\n{}\r\n--b--\r\n", "\r\n--b\r\n\r\nHTTP/1.1\r\n\r\n{}\r\n--b--\r\n", // Cut short in the middle of a part, and in the middle of the delimiter. "\r\n--b\r\nContent-ID: <response-0>\r\n\r\nHTTP/1.1 200 O", "\r\n--b", // Not a multipart body at all, which is what something in front of the // API answers with. "{\"error\":{\"code\":500}}", "<html>502 Bad Gateway</html>", "--\r\n--\r\n--\r\n", "\n\n\n", "",};
/// Whatever the bytes, reading a batch response either refuses them or yields/// replies that are windows into them: every body is a slice of the input/// rather than something invented, the walk ends, and it ends the same way/// twice.////// This is the parser that is handed the most bytes by the least trustworthy/// route -- one response holds fifty messages, and the boundary that separates/// them is chosen by the server rather than by this library.fn batchProperty(input: []const u8) !void { var it = gmail.batch.iterate(input) catch |err| { try testing.expectEqual(error.MalformedBatch, err); return; };
const start = @intFromPtr(input.ptr); var count: usize = 0; while (it.next()) |reply| : (count += 1) { // A reply with no body has nothing to point at and is allowed to // point nowhere; one with a body points into the input. if (reply.body.len > 0) { const body = @intFromPtr(reply.body.ptr); try testing.expect(body >= start); try testing.expect(body + reply.body.len <= start + input.len); } // A part costs at least a delimiter, so there can never be more // replies than bytes -- which is also why this loop terminates. try testing.expect(count <= input.len); }
// Ended stays ended. try testing.expectEqual(@as(?gmail.batch.Reply, null), it.next());
// And a second walk of the same bytes says the same thing: the iterator // holds no state that outlives it. var again = gmail.batch.iterate(input) catch unreachable; var second: usize = 0; while (again.next()) |_| second += 1; try testing.expectEqual(count, second);}
test "fuzz batch responses" { for (batch_seeds) |seed| try batchProperty(seed); try testing.fuzz({}, fuzzBatch, .{});}
fn fuzzBatch(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try batchProperty(buffer[0..len]);}
// -- base64url --------------------------------------------------------------
const base64_seeds = [_][]const u8{ "aGVsbG8gd29ybGQ", "aGVsbG8gd29ybGQ=", "", "=", "====", "a", "ab", "abc", "abcd", "a+b/c", "\xff\xff\xff\xff", "-_-_-_-_",};
/// Decoding either fails or produces exactly the bytes the length formula/// predicted, and never reads or writes outside them. An attachment is/// arbitrary bytes chosen by whoever sent the mail, so this is the one place/// a hostile message reaches a hand-written length calculation.fn base64Property(input: []const u8) !void { const out = gmail.json.decodeBase64Url(backing, input) catch |err| { try testing.expectEqual(error.InvalidBase64, err); return; }; defer backing.free(out);
// Four characters in, three bytes out, so the output is never longer // than three quarters of the input plus rounding. try testing.expect(out.len <= input.len); try testing.expect(out.len * 4 <= (input.len + 3) * 3);}
test "fuzz base64url" { for (base64_seeds) |seed| try base64Property(seed); try testing.fuzz({}, fuzzBase64, .{});}
fn fuzzBase64(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try base64Property(buffer[0..len]);}
// -- backoff ----------------------------------------------------------------
// Whatever the schedule and however many attempts have been made, the wait// is non-negative, is inside `max_backoff`, and does not overflow. The shift// in there is the reason: an attempt count from a long-running sync is not// bounded by anything a test would think to try.test "fuzz backoff" { try testing.fuzz({}, fuzzBackoff, .{}); // And the seeds, for a run without --fuzz. var prng: std.Random.DefaultPrng = .init(0); for ([_]u32{ 0, 1, 2, 3, 63, 64, 65, 1000, std.math.maxInt(u32) }) |attempt| { try backoffProperty(.{}, attempt, prng.random()); }}
fn fuzzBackoff(_: void, smith: *Smith) !void { const retry: gmail.http.Retry = .{ .max_attempts = smith.valueRangeAtMost(u32, 1, 100), .initial_backoff = .fromNanoseconds( smith.valueRangeAtMost(i64, 0, std.time.ns_per_s), ), .max_backoff = .fromNanoseconds( smith.valueRangeAtMost(i64, 0, std.time.ns_per_s * 3600), ), }; const attempt = smith.valueRangeAtMost(u32, 0, std.math.maxInt(u32));
var prng: std.Random.DefaultPrng = .init( smith.valueRangeAtMost(u64, 0, std.math.maxInt(u64)), ); try backoffProperty(retry, attempt, prng.random());}
fn backoffProperty(retry: gmail.http.Retry, attempt: u32, rng: std.Random) !void { const wait = retry.backoff(attempt, rng).toNanoseconds(); try testing.expect(wait >= 0); try testing.expect(wait <= retry.max_backoff.toNanoseconds()); // The first attempt is not a retry and never waits. if (attempt < 2) try testing.expectEqual(@as(i96, 0), wait);}
// -- the same targets, for a driver that is not the test runner -------------
/// One fuzz target, addressable by name.////// `zig build test` reaches these through the `test` blocks above and Zig's/// own fuzzer would reach them through `std.testing.fuzz`. This is the third/// way in, for `tools/fuzz.zig`, which exists because on this toolchain the/// second one does not work.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); } };}
const no_corpus: []const []const u8 = &.{};
pub const all = [_]Target{ .{ .name = "message", .run = Driven(fuzzMessage).run, .corpus = &message_seeds, .content_max = 4096 }, .{ .name = "history", .run = Driven(fuzzHistory).run, .corpus = &history_seeds, .content_max = 4096 }, .{ .name = "label", .run = Driven(fuzzLabel).run, .corpus = &label_seeds, .content_max = 1024 }, .{ .name = "error", .run = Driven(fuzzApiError).run, .corpus = &api_error_seeds, .content_max = 2048 }, .{ .name = "base64", .run = Driven(fuzzBase64).run, .corpus = &base64_seeds, .content_max = 4096 }, .{ .name = "batch", .run = Driven(fuzzBatch).run, .corpus = &batch_seeds, .content_max = 4096 }, // No corpus: this one reads numbers rather than a string, so there is // nothing for a mutator to start from. .{ .name = "backoff", .run = Driven(fuzzBackoff).run, .corpus = no_corpus, .content_max = 0 },};