Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052// 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.//!//! Two of these are security properties rather than robustness ones, and they//! are the reason this file is worth more than its line count://!//! **`origin`** -- no string, however spelled, may be accepted as a//! continuation link unless it really is the same scheme, host and port as the//! base URL. That check is all that stands between a response body and a bearer//! token sent to whoever wrote it.//!//! **`tenant`** -- no configured tenant id may produce a token endpoint on a//! host other than the one asked for. A tenant id reaches a program from a//! configuration file, and it is interpolated into the path of the URL that a//! client secret and an authorization code are posted to.//!//! 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 build fuzz --fuzz` hands them to Zig's own fuzzer, which steers by//! coverage; `tools/fuzz.zig` is a second driver for the same targets that//! runs a fixed number of inputs from a seed, which is what CI wants.
const builtin = @import("builtin");const std = @import("std");const testing = std.testing;const Allocator = std.mem.Allocator;const Smith = std.testing.Smith;
const o365 = @import("o365");
/// 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","subject":"x","receivedDateTime":"2024-03-01T12:00:00Z","isRead":true} , \\{"id":"a","@removed":{"reason":"deleted"}} , \\{"id":"a","@removed":{"reason":"changed"}} , \\{"id":"a","@removed":{}} , \\{"id":"a","from":{"emailAddress":{"name":"N","address":"a@b"}}, \\ "toRecipients":[{"emailAddress":{"address":"c@d"}},{"emailAddress":{}}]} , \\{"id":"a","body":{"contentType":"html","content":"<b>x</b>"}, \\ "uniqueBody":{"contentType":"text","content":"x"}} , \\{"id":"a","internetMessageHeaders":[{"name":"A","value":"1"},{"name":"B"}, \\ {"value":"no name"},7,null]} , \\{"id":"a","categories":["red",7,null,{},"blue"],"flag":{"flagStatus":"flagged"}} , \\{"id":"a","importance":"apocalyptic","inferenceClassification":"sideways"} , \\{"id":"a","receivedDateTime":"not a date","sentDateTime":"9999-12-31T23:59:59Z"} , \\{"id":"a","receivedDateTime":"0000-01-01T00:00:00Z"} , \\{"id":"a","isRead":"true","hasAttachments":"false"} , \\{"id":"","subject":""} , \\{"subject":"no id here"} , "{}", "[]", "null",};
/// 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 = o365.Message.fromJson(alloc, value) catch |err| { try testing.expectEqual(error.Malformed, err); try testing.expect(!has_id); return; }; try testing.expect(has_id);
// A tombstone and a message are distinguishable, always. This is the check // a delta loop makes first, and getting it wrong means treating "this was // deleted" as "this was not selected". try testing.expectEqual(message.removed != null, message.isRemoved());
// No recipient list exceeds the cap, and every address in one is a // non-empty string that `hasRecipient` can find again. for ([_][]const o365.Message.Recipient{ message.to_recipients, message.cc_recipients, message.bcc_recipients, message.reply_to, }) |list| { try testing.expect(list.len <= o365.Message.max_recipients); for (list) |r| { if (r.address) |a| { try testing.expect(a.len > 0); try testing.expect(message.hasRecipient(a)); } } }
// A lookup for something that cannot occur finds nothing, and does not // wander off the end of a list. try testing.expect(!message.hasRecipient("\x00 nobody is addressed like this")); try testing.expect(!message.hasCategory("\x00")); try testing.expectEqual(@as(?[]const u8, null), message.header("\x00"));
// Every category came from the input's array and is findable again. for (message.categories) |c| try testing.expect(message.hasCategory(c));
// `fromAddress` never invents one, and never returns an empty string -- // which would be worse than nothing, because it looks like an address. if (message.fromAddress()) |a| { try testing.expect(a.len > 0); const from_ok = if (message.from) |f| if (f.address) |x| std.mem.eql(u8, x, a) else false else false; const sender_ok = if (message.sender) |s| if (s.address) |x| std.mem.eql(u8, x, a) else false else false; try testing.expect(from_ok or sender_ok); }
// The timestamp is one of the three it may fall back through, and never // something made up. if (message.timestamp()) |ts| { const matches = (if (message.received_date_time) |t| t.nanoseconds == ts.nanoseconds else false) or (if (message.sent_date_time) |t| t.nanoseconds == ts.nanoseconds else false) or (if (message.created_date_time) |t| t.nanoseconds == ts.nanoseconds else false); try testing.expect(matches); } else { try testing.expectEqual(@as(?std.Io.Timestamp, null), message.received_date_time); try testing.expectEqual(@as(?std.Io.Timestamp, null), message.sent_date_time); try testing.expectEqual(@as(?std.Io.Timestamp, null), message.created_date_time); }}
fn fuzzMessage(_: void, smith: *Smith) anyerror!void { var buffer: [16 * 1024]u8 = undefined; const text = buffer[0..smith.slice(&buffer)]; try withJson(text, messageProperty);}
test "message" { for (message_seeds) |seed| try withJson(seed, messageProperty); try testing.fuzz({}, fuzzMessage, .{});}
// -- folders ----------------------------------------------------------------
const folder_seeds = [_][]const u8{ \\{"id":"a","displayName":"Inbox","parentFolderId":"root","childFolderCount":2, \\ "totalItemCount":1024,"unreadItemCount":17,"isHidden":false} , \\{"id":"a","childFolders":[{"id":"b","childFolders":[{"id":"c"}]}]} , \\{"id":"a","childFolders":[7,null,{},{"id":"b"}]} , \\{"id":"a","totalItemCount":-1,"unreadItemCount":-5} , \\{"id":"a","parentFolderId":""} , \\{"displayName":"no id"} , "{}",};
/// Anything with a string `id` parses, the tree is bounded, and every count is/// either absent or a number that was in the input.fn folderProperty(alloc: Allocator, value: std.json.Value) !void { const has_id = value == .object and if (value.object.get("id")) |i| i == .string else false;
const folder = o365.MailFolder.fromJson(alloc, value) catch |err| { try testing.expectEqual(error.Malformed, err); try testing.expect(!has_id); return; }; try testing.expect(has_id);
// The tree is bounded and walking it terminates, which is the property // that matters for a recursive parser reading from a network. const depth = depthOf(&folder, 0); try testing.expect(depth < o365.MailFolder.max_depth);
// The counts are exactly what the input said, and nothing else. // // Note what is deliberately *not* asserted here: that `unread` is no // greater than `total`. That is a property of the mailbox, not of this // parser, and the two counts arrive from a service this library does not // control -- a response claiming 55 unread of 1 total is nonsense, but it // is the server's nonsense, and inventing a correction for it would lose // the only evidence that something upstream is wrong. An earlier version // of this target asserted it and the fuzzer duly produced one. try testing.expectEqual(countOf(value, "totalItemCount"), folder.total_item_count); try testing.expectEqual(countOf(value, "unreadItemCount"), folder.unread_item_count); try testing.expectEqual(countOf(value, "childFolderCount"), folder.child_folder_count); try testing.expectEqual(folder.unread_item_count orelse 0, folder.unread());
// An empty parent id reads as none rather than as a folder called "". if (folder.parent_folder_id) |p| try testing.expect(p.len > 0);}
/// The `u32` a count member holds, read independently of the library so that/// the check above is a comparison rather than a restatement.fn countOf(value: std.json.Value, name: []const u8) ?u32 { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .integer => |i| std.math.cast(u32, i), .string, .number_string => |t| std.fmt.parseInt(u32, t, 10) catch null, else => null, };}
fn depthOf(folder: *const o365.MailFolder, so_far: usize) usize { var deepest = so_far; for (folder.child_folders) |*child| { const d = depthOf(child, so_far + 1); if (d > deepest) deepest = d; } return deepest;}
fn fuzzFolder(_: void, smith: *Smith) anyerror!void { var buffer: [16 * 1024]u8 = undefined; const text = buffer[0..smith.slice(&buffer)]; try withJson(text, folderProperty);}
test "folder" { for (folder_seeds) |seed| try withJson(seed, folderProperty); try testing.fuzz({}, fuzzFolder, .{});}
// -- attachments ------------------------------------------------------------
const attachment_seeds = [_][]const u8{ \\{"@odata.type":"#microsoft.graph.fileAttachment","id":"a","name":"x.gif", \\ "contentType":"image/gif","size":1008,"isInline":false,"contentBytes":"aGk="} , \\{"@odata.type":"#microsoft.graph.itemAttachment","id":"a","item":{"id":"b"}} , \\{"@odata.type":"#microsoft.graph.referenceAttachment","id":"a", \\ "sourceUrl":"https://example.com/x"} , \\{"id":"a","contentBytes":"!!! not base64 !!!"} , \\{"id":"a","name":"../../etc/passwd"} , \\{"id":"a","name":".."} , \\{"id":"a","name":""} , \\{"id":"a","@odata.type":"#microsoft.graph.hologram"} , "{}",};
/// Anything with a string `id` parses, and -- the one that matters -- the name/// this hands back for a file on disk can never escape the directory it is/// meant for, whatever the sender called the attachment.fn attachmentProperty(alloc: Allocator, value: std.json.Value) !void { const has_id = value == .object and if (value.object.get("id")) |i| i == .string else false;
const attachment = o365.Attachment.fromJson(alloc, value) catch |err| { try testing.expectEqual(error.Malformed, err); try testing.expect(!has_id); return; }; try testing.expect(has_id);
var buf: [512]u8 = undefined; const name = attachment.safeName(&buf);
// Never empty, never longer than the buffer, and never anything a path // walker would follow somewhere else. try testing.expect(name.len > 0); try testing.expect(name.len <= buf.len); try testing.expect(std.mem.indexOfScalar(u8, name, '/') == null); try testing.expect(std.mem.indexOfScalar(u8, name, '\\') == null); try testing.expect(std.mem.indexOfScalar(u8, name, 0) == null); try testing.expect(!std.mem.eql(u8, name, ".")); try testing.expect(!std.mem.eql(u8, name, "..")); for (name) |c| try testing.expect(c >= 0x20 and c != 0x7f);
// And a smaller buffer is still respected, which is what a caller with a // fixed path buffer relies on. var small: [4]u8 = undefined; const short = attachment.safeName(&small); try testing.expect(short.len <= small.len);
// Content is present only when it arrived and decoded. if (attachment.content != null) try testing.expect(attachment.has_content);}
fn fuzzAttachment(_: void, smith: *Smith) anyerror!void { var buffer: [16 * 1024]u8 = undefined; const text = buffer[0..smith.slice(&buffer)]; try withJson(text, attachmentProperty);}
test "attachment" { for (attachment_seeds) |seed| try withJson(seed, attachmentProperty); try testing.fuzz({}, fuzzAttachment, .{});}
// -- the error object -------------------------------------------------------
const error_seeds = [_][]const u8{ \\{"error":{"code":"TooManyRequests","message":"Please retry again later.", \\ "innerError":{"code":"429","request-id":"r","date":"d","status":"429"}}} , \\{"error":{"code":"badRequest","innererror":{"code":"invalidRange"}, \\ "details":[{"code":"x","message":"y","target":"z"}]}} , \\{"error":{"code":"a","innerError":{"code":"b","innerError":{"code":"c"}}}} , \\{"error":{"code":"resyncRequired"}} , \\{"error":{"code":"InvalidAuthenticationToken"}} , \\{"error":{}} , \\{"error":"invalid_grant"} , "{}", "not json at all",};
/// The error object parses or is `NotAnError`, the chain is bounded, and the/// four questions asked of it never disagree with themselves.fn fuzzApiError(_: void, smith: *Smith) anyerror!void { var buffer: [16 * 1024]u8 = undefined; const text = buffer[0..smith.slice(&buffer)];
var e = o365.ApiError.parse(backing, text) catch |err| { try testing.expectEqual(error.NotAnError, err); return; }; defer e.deinit();
try testing.expect(e.inner.len <= o365.ApiError.max_inner_depth);
// `mostSpecificCode` returns something that is actually in the object // rather than something assembled. if (e.mostSpecificCode()) |specific| { try testing.expect(e.hasCode(specific)); } else { try testing.expectEqual(@as(?[]const u8, null), e.code); }
// A code nobody sent is never found, at any depth. try testing.expect(!e.hasCode("\x00 no error is coded like this"));
// The classifications a caller branches on must not contradict each other // on the statuses where each is decisive. An expired token is not a thing // to wait out, and throttling is not a thing to sign in again for. if (e.isRetryable(.too_many_requests)) { try testing.expect(!e.isNotFound(.too_many_requests)); } if (e.isAuthFailure(.unauthorized)) { try testing.expect(!e.isRetryable(.unauthorized)); } // 403 in Graph is permission and licensing, never quota, so it must never // be retried -- retrying spends the budget on a certainty. try testing.expect(!e.isRetryable(.forbidden));
// Formatting terminates and stays inside its buffer whatever is in there. var out: [1024]u8 = undefined; var w: std.Io.Writer = .fixed(&out); e.format(&w) catch {};}
test "api-error" { for (error_seeds) |seed| { var e = o365.ApiError.parse(backing, seed) catch continue; defer e.deinit(); try testing.expect(e.inner.len <= o365.ApiError.max_inner_depth); } try testing.fuzz({}, fuzzApiError, .{});}
// -- timestamps -------------------------------------------------------------
const timestamp_seeds = [_][]const u8{ "2018-09-09T03:15:05Z", "2018-09-09T03:15:05.1234567Z", "2018-09-09T03:15:05+02:00", "2018-09-09T03:15:05-05:00", "1900-01-01T00:00:00Z", "9999-12-31T23:59:59Z", "0000-01-01T00:00:00Z", "2016-12-31T23:59:60Z", "2024-02-29T00:00:00Z", "2023-02-29T00:00:00Z", "2018-99-09T03:15:05Z", "not a date", "",};
/// Parsing never panics, and anything that parses renders back to something/// that parses to the same second. The overflow traps in a date routine are/// what this is really looking for: a year that does not fit, an era/// multiplication that does not fit, and a `@mod` one day below the bottom of/// an `i64`.fn fuzzTimestamp(_: void, smith: *Smith) anyerror!void { var buffer: [256]u8 = undefined; const text = buffer[0..smith.slice(&buffer)];
const parsed = o365.iso8601.parse(text) orelse return;
var out: [64]u8 = undefined; const rendered = o365.iso8601.bufRender(&out, parsed); try testing.expect(rendered.len > 0);
// A round trip loses the fraction and nothing else, so what comes back // parses and lands in the same second. const again = o365.iso8601.parse(rendered) orelse return error.RenderedSomethingUnparseable; const floor_s = @divFloor(parsed.nanoseconds, std.time.ns_per_s); const again_s = @divFloor(again.nanoseconds, std.time.ns_per_s); // Unless the year was saturated into the four digits the format has, in // which case the instant genuinely cannot be written. if (floor_s >= o365.iso8601.secondsFromCivil(0, 1, 1, 0, 0, 0) and floor_s <= o365.iso8601.secondsFromCivil(9999, 12, 31, 23, 59, 59)) { try testing.expectEqual(floor_s, again_s); }}
test "timestamp" { for (timestamp_seeds) |seed| { const parsed = o365.iso8601.parse(seed) orelse continue; var out: [64]u8 = undefined; const rendered = o365.iso8601.bufRender(&out, parsed); try testing.expect(rendered.len > 0); }
// And the arithmetic itself, at both ends of what an `i64` of nanoseconds // can reach, where the traps are. for ([_]i64{ std.math.minInt(i64) / std.time.ns_per_s, std.math.maxInt(i64) / std.time.ns_per_s, -62135596800, 253402300799, 0, -1, }) |seconds| { var out: [64]u8 = undefined; const rendered = o365.iso8601.bufRender( &out, .fromNanoseconds(@as(i96, seconds) * std.time.ns_per_s), ); try testing.expect(rendered.len > 0); } try testing.fuzz({}, fuzzTimestamp, .{});}
// -- the origin check -------------------------------------------------------
const origin_seeds = [_][]const u8{ "https://graph.microsoft.com/v1.0/me/messages?$skiptoken=x", "https://graph.microsoft.com:443/v1.0/me", "https://GRAPH.MICROSOFT.COM/v1.0/me", "https://evil.example.com/collect", "https://graph.microsoft.com.evil.example.com/v1.0/me", "https://graph.microsoft.com@evil.example.com/v1.0/me", "http://graph.microsoft.com/v1.0/me", "https://graph.microsoft.com:8443/v1.0/me", "//evil.example.com/v1.0/me", "/v1.0/me", "https://", "",};
/// **A security property.** Whatever the string, `sameOrigin` accepts it only/// if `std.Uri` agrees that its scheme, host and port are the base URL's.////// This is the check that stands between a response body and an access token/// posted to whoever wrote it, so the test does not trust the function's own/// idea of what it compared: it re-derives scheme, host and port from the/// parsed URI and insists the verdict follows.fn fuzzOrigin(_: void, smith: *Smith) anyerror!void { var buffer: [2048]u8 = undefined; const link = buffer[0..smith.slice(&buffer)];
const base = "https://graph.microsoft.com";
o365.odata.sameOrigin(base, link) catch |err| { switch (err) { error.InvalidLink, error.UntrustedLink => {}, } return; };
// It said yes, so every part of that must independently hold. const uri = std.Uri.parse(link) catch return error.AcceptedSomethingUnparseable; try testing.expect(std.ascii.eqlIgnoreCase(uri.scheme, "https"));
var host_buf: [std.Io.net.HostName.max_len]u8 = undefined; const host = std.Io.net.HostName.fromUri(uri, &host_buf) catch return error.AcceptedSomethingWithNoHost; try testing.expect(std.ascii.eqlIgnoreCase(host.bytes, "graph.microsoft.com"));
// A host that merely *contains* the expected one is not the expected one, // which is the shape every one of these attacks takes. try testing.expectEqual(@as(usize, "graph.microsoft.com".len), host.bytes.len);
if (uri.port) |p| try testing.expectEqual(@as(u16, 443), p);}
test "origin" { const base = "https://graph.microsoft.com"; for (origin_seeds) |seed| try fuzzOriginOn(base, seed); try testing.fuzz({}, fuzzOrigin, .{});}
fn fuzzOriginOn(base: []const u8, link: []const u8) !void { o365.odata.sameOrigin(base, link) catch return; const uri = try std.Uri.parse(link); var host_buf: [std.Io.net.HostName.max_len]u8 = undefined; const host = try std.Io.net.HostName.fromUri(uri, &host_buf); try testing.expect(std.ascii.eqlIgnoreCase(host.bytes, "graph.microsoft.com"));}
// -- the tenant id ----------------------------------------------------------
const tenant_seeds = [_][]const u8{ "common", "organizations", "consumers", "72f988bf-86f1-41af-91ab-2d7cd011db47", "contoso.onmicrosoft.com", "../../evil", "common?x=", "common#x", "evil.example.com/path", "//evil.example.com", "a..b", ".contoso.com", "",};
/// **A security property.** A tenant id that `validate` accepts can never/// produce an endpoint on a host other than the one asked for.////// The tenant goes into the *path* of the URL that a client secret and an/// authorization code are posted to, and it arrives from a configuration file./// A `/` in it addresses a different path; a `?` or a `#` turns the rest of the/// URL into a query or a fragment. So the test parses what came out and insists/// the host is still the login host.fn fuzzTenant(_: void, smith: *Smith) anyerror!void { var buffer: [512]u8 = undefined; const id = buffer[0..smith.slice(&buffer)];
var built = o365.tenant.init(backing, id, .{}) catch |err| { switch (err) { error.InvalidTenant => {}, error.OutOfMemory => return err, } return; }; defer built.deinit();
for ([_][]const u8{ built.provider.issuer, built.provider.authorization_endpoint, built.provider.token_endpoint, built.provider.jwks_uri.?, built.provider.device_authorization_endpoint.?, }) |url| { const uri = std.Uri.parse(url) catch return error.BuiltSomethingUnparseable; try testing.expectEqualStrings("https", uri.scheme);
var host_buf: [std.Io.net.HostName.max_len]u8 = undefined; const host = try std.Io.net.HostName.fromUri(uri, &host_buf); // Not "contains", not "starts with": equal. `evil.example.com` with // the login host somewhere in its path would pass a weaker check. try testing.expectEqualStrings(o365.tenant.default_host, host.bytes);
// And nothing may have been smuggled into a query or a fragment. try testing.expectEqual(@as(?std.Uri.Component, null), uri.query); try testing.expectEqual(@as(?std.Uri.Component, null), uri.fragment); try testing.expectEqual(@as(?[]const u8, null), if (uri.user) |_| @as(?[]const u8, "") else null); }}
test "tenant" { for (tenant_seeds) |seed| { var built = o365.tenant.init(backing, seed, .{}) catch continue; defer built.deinit(); const uri = try std.Uri.parse(built.provider.token_endpoint); var host_buf: [std.Io.net.HostName.max_len]u8 = undefined; const host = try std.Io.net.HostName.fromUri(uri, &host_buf); try testing.expectEqualStrings(o365.tenant.default_host, host.bytes); } try testing.fuzz({}, fuzzTenant, .{});}
// -- the batch envelope -----------------------------------------------------
const batch_request_seeds = [_][]const u8{ "/me/messages/m1", "/me/messages/AAMkAGI1%2FAAAoZ%2BCfHAAA%3D", "/me/messages/m1?$select=id,subject", "/me/messages/m1/$value", "\"},{\"id\":\"evil\",\"url\":\"/me/messages/x", "/me/a\\\"b", "",};
/// **A security property.** A URL, however spelled, becomes exactly one request/// in the envelope and cannot add a second.////// A Graph message id is opaque and arrives from the service, so it reaches/// this encoder as data the program did not choose. If a quote in one could/// close the string it sits in, a hostile or merely odd id would inject an/// extra entry into a batch -- one that would be executed with the caller's/// token.fn fuzzBatchRequest(_: void, smith: *Smith) anyerror!void { var buffer: [4096]u8 = undefined; const url = buffer[0..smith.slice(&buffer)];
var client: o365.Client = .{ .gpa = backing, .oauth = undefined, .tokens = undefined }; var b: o365.Batch = .init(&client, backing); defer b.deinit();
// Bytes that cannot go into a JSON string are refused up front, which is // the property: never silently written as something that is not a string. _ = b.add(.{ .url = url }) catch |err| { try testing.expectEqual(error.InvalidRequest, err); try testing.expect(!std.unicode.utf8ValidateSlice(url)); return; }; _ = try b.add(.{ .url = url, .headers = &.{.{ .name = "X-Test", .value = url }} });
const body = try b.encodeForTest(); defer backing.free(body);
// It is JSON, and it holds exactly the two requests that were added -- // never three. var parsed = std.json.parseFromSlice(std.json.Value, backing, body, .{}) catch return error.EnvelopeWasNotJson; defer parsed.deinit();
const requests = parsed.value.object.get("requests") orelse return error.NoRequests; try testing.expect(requests == .array); try testing.expectEqual(@as(usize, 2), requests.array.items.len);
// Each entry's URL is the string that went in, unchanged -- escaped on the // wire and identical once parsed back. for (requests.array.items) |item| { try testing.expectEqualStrings(url, item.object.get("url").?.string); } // And the ids are the ones this assigned, not any that were smuggled in. try testing.expectEqualStrings("0", requests.array.items[0].object.get("id").?.string); try testing.expectEqualStrings("1", requests.array.items[1].object.get("id").?.string);}
test "batch-request" { for (batch_request_seeds) |seed| { var client: o365.Client = .{ .gpa = backing, .oauth = undefined, .tokens = undefined }; var b: o365.Batch = .init(&client, backing); defer b.deinit(); _ = b.add(.{ .url = seed }) catch continue;
const body = try b.encodeForTest(); defer backing.free(body);
var parsed = try std.json.parseFromSlice(std.json.Value, backing, body, .{}); defer parsed.deinit(); const requests = parsed.value.object.get("requests").?; try testing.expectEqual(@as(usize, 1), requests.array.items.len); try testing.expectEqualStrings(seed, requests.array.items[0].object.get("url").?.string); } try testing.fuzz({}, fuzzBatchRequest, .{});}
const batch_response_seeds = [_][]const u8{ \\{"responses":[{"id":"0","status":200,"body":{"id":"m1"}}]} , \\{"responses":[{"id":"0","status":429,"headers":{"Retry-After":"17"},"body":{}}]} , \\{"responses":[{"id":"0","status":424,"body":null}]} , \\{"responses":[{"id":"0","status":200,"body":"U3ViamVjdDogaGkK"}]} , \\{"responses":[{"id":"0","status":200,"body":"!!! not base64 !!!"}]} , \\{"responses":[{"id":"0","status":99999},{"id":"1","status":-1},{"id":"2"}]} , \\{"responses":[7,null,{"no":"id"},{"id":""}]} , \\{"responses":[]} , \\{"responses":7} , "{}", "[]", "not json",};
/// Decoding a batch envelope terminates, never invents an entry, and never/// turns a failure into a success.////// The last of those is the one that matters: `status` arrives as a number from/// the network, and a status this cannot make sense of has to read as a failure/// rather than as a 200 -- a batch walk that treats an unreadable status as/// success silently drops messages.fn fuzzBatchResponse(_: void, smith: *Smith) anyerror!void { var buffer: [16 * 1024]u8 = undefined; const text = buffer[0..smith.slice(&buffer)];
var client: o365.Client = .{ .gpa = backing, .oauth = undefined, .tokens = undefined }; var b: o365.Batch = .init(&client, backing); defer b.deinit();
var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit();
var out: std.ArrayList(o365.Batch.Response) = .empty; defer out.deinit(backing);
b.decodeForTest(arena.allocator(), text, &out) catch |err| { try testing.expectEqual(error.MalformedBatch, err); return; };
// However many came out, there were at least that many entries in the // input's array. const parsed = std.json.parseFromSlice(std.json.Value, backing, text, .{}) catch return; defer parsed.deinit(); const items = parsed.value.object.get("responses").?.array.items; try testing.expect(out.items.len <= items.len);
for (out.items) |r| { // Every response has a non-empty id, because that is what correlates // it with a request; one without is skipped rather than kept. try testing.expect(r.id.len > 0);
// `ok` and `throttled` never both hold: a caller branches on them in // order, and a 429 that read as success would be a lost request. if (r.ok()) { try testing.expect(!r.throttled()); try testing.expect(!r.failedDependency()); }
// A body is one thing or the other, never both. try testing.expect(r.body == null or r.raw == null);
// Formatting an error object out of whatever is there terminates and // leaks nothing. if (r.apiError(backing)) |api| { var e = api; defer e.deinit(); var buf: [512]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); e.format(&w) catch {}; } }}
test "batch-response" { for (batch_response_seeds) |seed| { var client: o365.Client = .{ .gpa = backing, .oauth = undefined, .tokens = undefined }; var b: o365.Batch = .init(&client, backing); defer b.deinit();
var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit();
var out: std.ArrayList(o365.Batch.Response) = .empty; defer out.deinit(backing);
b.decodeForTest(arena.allocator(), seed, &out) catch continue; for (out.items) |r| try testing.expect(r.id.len > 0); } try testing.fuzz({}, fuzzBatchResponse, .{});}
// -- the query builder ------------------------------------------------------
const query_seeds = [_][]const u8{ "id,subject", "receivedDateTime ge 2024-01-01T00:00:00Z", "\"subject:hi\"&$top=999999", "a&b=c#d", "%00%ff", "",};
/// A value, however spelled, can never become another parameter.////// The whole point of encoding: a `$search` term carrying `&$top=1` must not/// turn into a `$top` the caller did not ask for.fn fuzzQuery(_: void, smith: *Smith) anyerror!void { var buffer: [4096]u8 = undefined; const value = buffer[0..smith.slice(&buffer)];
var q: o365.odata.Query = .init(backing); defer q.deinit();
try q.add("$search", value); try q.addCommaSeparated("$select", &.{ "id", value });
const written = q.written();
// Exactly three `=` and one `&`: the ones this wrote. Anything else came // out of the value and should have been encoded. var equals: usize = 0; var ampersands: usize = 0; for (written) |c| { if (c == '=') equals += 1; if (c == '&') ampersands += 1; } try testing.expectEqual(@as(usize, 2), equals); try testing.expectEqual(@as(usize, 1), ampersands);
// And exactly one comma: the separator between the two `$select` members. var commas: usize = 0; for (written) |c| { if (c == ',') commas += 1; } try testing.expectEqual(@as(usize, 1), commas);
// Nothing that would end the query string or start a fragment. try testing.expect(std.mem.indexOfScalar(u8, written, '#') == null); try testing.expect(std.mem.indexOfScalar(u8, written, ' ') == null);}
test "query" { for (query_seeds) |seed| { var q: o365.odata.Query = .init(backing); defer q.deinit(); try q.add("$search", seed); try testing.expect(std.mem.indexOfScalar(u8, q.written(), '&') == null); } try testing.fuzz({}, fuzzQuery, .{});}
// -- the backoff schedule ---------------------------------------------------
/// A wait is never negative, never longer than the ceiling, and a/// `Retry-After` past what this will obey is refused rather than slept/// through -- which is what keeps a hostile or buggy service from parking the/// process for a day.fn fuzzBackoff(_: void, smith: *Smith) anyerror!void {
// `valueRangeAtMost` rather than `value`, because an unbounded `u32` of // milliseconds is a wait nothing would ever configure and the interesting // part of this target is the arithmetic near the ceiling. // // Note what each of these costs: `Smith` reads eight bytes per value // whatever the range, and answers a value outside the range with the // range's *minimum* rather than reducing it. So random bytes make every // one of these zero, and the generator in `tools/fuzz.zig` has to write // small numbers on purpose for this target to be testing anything. const attempt = smith.valueRangeAtMost(u32, 0, 1000); const initial_ms = smith.valueRangeAtMost(u32, 0, 100_000); const max_s = smith.valueRangeAtMost(u32, 0, 3600); const cap_s = smith.valueRangeAtMost(u32, 0, 3600); const asked_s = smith.valueRangeAtMost(u32, 0, 1_000_000); const has_header = smith.valueRangeAtMost(u8, 0, 1) == 1;
const retry: o365.http.Retry = .{ .initial_backoff = .fromMilliseconds(initial_ms), .max_backoff = .fromSeconds(max_s), .max_retry_after = .fromSeconds(cap_s), };
var prng: std.Random.DefaultPrng = .init(attempt); const rng = prng.random();
const plain = retry.backoff(attempt, rng); try testing.expect(plain.toNanoseconds() >= 0); try testing.expect(plain.toNanoseconds() <= @max( retry.max_backoff.toNanoseconds(), retry.initial_backoff.toNanoseconds(), )); // The first attempt is not a retry and must never wait. if (attempt < 2) try testing.expectEqual(@as(i96, 0), plain.toNanoseconds());
const header: ?std.Io.Duration = if (has_header) .fromSeconds(asked_s) else null; if (retry.wait(attempt, header, rng)) |waited| { try testing.expect(waited.toNanoseconds() >= 0); if (has_header and attempt >= 2) { // Obeyed, and never for longer than was asked plus the small slack // that keeps a rounding-down clock from coming back early. try testing.expect( waited.toNanoseconds() <= retry.max_retry_after.toNanoseconds() + std.time.ns_per_s, ); } } else { // The only reason to refuse is a header past the ceiling. try testing.expect(has_header); try testing.expect( @as(i96, asked_s) * std.time.ns_per_s > retry.max_retry_after.toNanoseconds(), ); }}
test "backoff" { var prng: std.Random.DefaultPrng = .init(7); const rng = prng.random(); const retry: o365.http.Retry = .{}; for (0..64) |attempt| { const waited = retry.backoff(@intCast(attempt), rng); try testing.expect(waited.toNanoseconds() >= 0); try testing.expect(waited.toNanoseconds() <= retry.max_backoff.toNanoseconds()); } try testing.fuzz({}, fuzzBackoff, .{});}
// -- the target table -------------------------------------------------------
pub const Target = struct { name: []const u8, run: *const fn (_: void, smith: *Smith) anyerror!void, /// The corpus `tools/fuzz.zig` mutates. Without one, a target that parses /// JSON spends its whole run being rejected by `std.json`. corpus: []const []const u8 = &.{}, /// The size of the buffer this target reads a slice into. /// /// It has to be carried here because `Smith.slice` answers a length larger /// than its buffer with an **empty** slice rather than a truncated one, so /// a generator writing a longer length silently fuzzes the empty string. /// Zero means the target reads no slice at all. content_max: usize,};
pub const all = [_]Target{ .{ .name = "message", .run = fuzzMessage, .corpus = &message_seeds, .content_max = 16 * 1024, }, .{ .name = "folder", .run = fuzzFolder, .corpus = &folder_seeds, .content_max = 16 * 1024, }, .{ .name = "attachment", .run = fuzzAttachment, .corpus = &attachment_seeds, .content_max = 16 * 1024, }, .{ .name = "api-error", .run = fuzzApiError, .corpus = &error_seeds, .content_max = 16 * 1024, }, .{ .name = "timestamp", .run = fuzzTimestamp, .corpus = ×tamp_seeds, .content_max = 256, }, .{ .name = "origin", .run = fuzzOrigin, .corpus = &origin_seeds, .content_max = 2048, }, .{ .name = "tenant", .run = fuzzTenant, .corpus = &tenant_seeds, .content_max = 512, }, .{ .name = "query", .run = fuzzQuery, .corpus = &query_seeds, .content_max = 4096, }, .{ .name = "batch-request", .run = fuzzBatchRequest, .corpus = &batch_request_seeds, .content_max = 4096, }, .{ .name = "batch-response", .run = fuzzBatchResponse, .corpus = &batch_response_seeds, .content_max = 16 * 1024, }, .{ // Reads numbers rather than a slice, so it has no corpus and // `makeInput` gives it nothing but the random tail. .name = "backoff", .run = fuzzBackoff, .content_max = 0, },};
test "every target has a name, and the table is consistent" { for (all, 0..) |target, i| { try testing.expect(target.name.len > 0); for (all[i + 1 ..]) |other| { try testing.expect(!std.mem.eql(u8, target.name, other.name)); } // A target that reads a slice needs a corpus, or a run of it is a run // against random bytes that are never JSON. if (target.content_max > 0) try testing.expect(target.corpus.len > 0); }}