Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The client against a Microsoft Graph on a loopback socket.//!//! Everything in `src/` stops at the network: the unit tests there check what a//! response turns into and never open a socket. This is the other half -- an//! `std.http.Client` really talking to an `std.http.Server` -- and it is where//! the things that are not in any one function show up: that pagination follows//! `@odata.nextLink` and stops, that a delta walk ends holding the token to//! resume from, that an expired token is refreshed *before* the call rather//! than after it fails, that a 401 arriving anyway is spent on one refresh and//! not an infinite loop, that throttling is waited out for as long as//! `Retry-After` asks and no longer, and -- the one worth having most -- that a//! continuation link pointing at another host is refused rather than followed//! with a bearer token attached.//!//! The server is a few hundred lines of scripted responses rather than Graph, so//! it proves the client and the API reference agree, not that Graph does.
const std = @import("std");const o365 = @import("o365");const oidc = @import("oidc");
const testing = std.testing;
/// Enough of Microsoft Graph to answer this client, and strict about what it is/// sent so that a malformed request fails here rather than passing quietly.const FakeGraph = struct { server: std.Io.net.Server, io: std.Io, gpa: std.mem.Allocator,
/// The access token that works. Anything else gets a 401 with Graph's /// error object. valid_access_token: []const u8 = "at-good", /// What the token endpoint hands out when the refresh token is spent. refreshed_access_token: []const u8 = "at-fresh", valid_refresh_token: []const u8 = "rt-good",
/// Queued replies, consumed in order. A request with nothing queued gets /// the default handler. scripted: std.ArrayList(Scripted) = .empty,
/// Recorded for the test to assert on. requests: std.ArrayList(Seen) = .empty, refreshes: usize = 0,
requests_to_serve: usize = 1,
const Scripted = struct { status: std.http.Status, body: []const u8, /// Sent as `Retry-After` when set, which is the header Graph uses to /// say how long to wait and which this client is supposed to obey. retry_after: ?[]const u8 = null, content_type: []const u8 = "application/json", /// Sent as `Content-Encoding`. The client asks for `identity`, but a /// proxy in the way need not honour that, so the path that inflates a /// body it did not ask for has to work. content_encoding: ?[]const u8 = null, };
const Seen = struct { target: []u8, authorization: ?[]u8, prefer: ?[]u8, accept: ?[]u8, /// The request body, for the one endpoint that has one. body: ?[]u8 = null,
fn deinit(s: *Seen, gpa: std.mem.Allocator) void { gpa.free(s.target); if (s.authorization) |a| gpa.free(a); if (s.prefer) |p| gpa.free(p); if (s.accept) |a| gpa.free(a); if (s.body) |b| gpa.free(b); } };
fn listen(io: std.Io, gpa: std.mem.Allocator) !FakeGraph { const address: std.Io.net.IpAddress = .{ .ip4 = .loopback(0) }; const server = try address.listen(io, .{ .mode = .stream, .reuse_address = true }); return .{ .server = server, .io = io, .gpa = gpa }; }
fn deinit(f: *FakeGraph) void { for (f.requests.items) |*r| r.deinit(f.gpa); f.requests.deinit(f.gpa); f.scripted.deinit(f.gpa); f.server.deinit(f.io); }
fn port(f: *const FakeGraph) u16 { return f.server.socket.address.getPort(); }
fn baseUrl(f: *const FakeGraph, buf: []u8) ![]const u8 { return std.fmt.bufPrint(buf, "http://127.0.0.1:{d}", .{f.port()}); }
fn script(f: *FakeGraph, status: std.http.Status, body: []const u8) !void { try f.scripted.append(f.gpa, .{ .status = status, .body = body }); }
fn scriptFull(f: *FakeGraph, s: Scripted) !void { try f.scripted.append(f.gpa, s); }
/// The query string of the request at `index`, without the `?`. fn queryOf(f: *const FakeGraph, index: usize) []const u8 { const target = f.requests.items[index].target; const q = std.mem.indexOfScalar(u8, target, '?') orelse return ""; return target[q + 1 ..]; }
fn pathOf(f: *const FakeGraph, index: usize) []const u8 { const target = f.requests.items[index].target; const q = std.mem.indexOfScalar(u8, target, '?') orelse return target; return target[0..q]; }
fn run(f: *FakeGraph) void { for (0..f.requests_to_serve) |_| { f.serveOne() catch |err| switch (err) { error.Canceled => return, else => { std.debug.print("fake graph: {t}\n", .{err}); return; }, }; } }
fn serveOne(f: *FakeGraph) !void { var stream = try f.server.accept(f.io); defer stream.close(f.io);
var recv: [16 * 1024]u8 = undefined; var send: [4096]u8 = undefined; var reader = stream.reader(f.io, &recv); var writer = stream.writer(f.io, &send); var http_server: std.http.Server = .init(&reader.interface, &writer.interface);
var request = try http_server.receiveHead();
var seen: Seen = .{ .target = try f.gpa.dupe(u8, request.head.target), .authorization = null, .prefer = null, .accept = null, }; var headers = request.iterateHeaders(); while (headers.next()) |header| { if (std.ascii.eqlIgnoreCase(header.name, "authorization")) { seen.authorization = try f.gpa.dupe(u8, header.value); } else if (std.ascii.eqlIgnoreCase(header.name, "prefer")) { seen.prefer = try f.gpa.dupe(u8, header.value); } else if (std.ascii.eqlIgnoreCase(header.name, "accept")) { seen.accept = try f.gpa.dupe(u8, header.value); } }
var body: []u8 = &.{}; defer f.gpa.free(body); if (request.head.method == .POST) { var body_buf: [16 * 1024]u8 = undefined; const body_reader = request.readerExpectNone(&body_buf); var collected: std.Io.Writer.Allocating = .init(f.gpa); defer collected.deinit(); _ = try body_reader.streamRemaining(&collected.writer); body = try f.gpa.dupe(u8, collected.written()); }
if (body.len > 0) seen.body = try f.gpa.dupe(u8, body);
// The head lives in the receive buffer, which reading the body // overwrites, so everything from it comes from the copy above. try f.requests.append(f.gpa, seen); const path = f.pathOf(f.requests.items.len - 1);
// The token endpoint is the identity platform, not Graph, and answers // whatever the access token situation is. if (std.mem.eql(u8, path, "/token")) return f.serveToken(&request, body);
const authorization = seen.authorization orelse return respond(&request, .{ .status = .unauthorized, .body = unauthorized_body });
var expected: [128]u8 = undefined; const good = try std.fmt.bufPrint(&expected, "Bearer {s}", .{f.valid_access_token}); const fresh = try std.fmt.bufPrint( expected[good.len..], "Bearer {s}", .{f.refreshed_access_token}, ); if (!std.mem.eql(u8, authorization, good) and !std.mem.eql(u8, authorization, fresh)) { return respond(&request, .{ .status = .unauthorized, .body = unauthorized_body }); }
// A scripted reply takes precedence, so that a test can make one call // fail without teaching this server about every failure mode. if (f.scripted.items.len > 0) { const s = f.scripted.orderedRemove(0); return respond(&request, s); }
if (std.mem.endsWith(u8, path, "/$batch")) { return respond(&request, .{ .status = .ok, .body = batch_default }); } if (std.mem.endsWith(u8, path, "/messages/delta")) { return respond(&request, .{ .status = .ok, .body = delta_final }); } if (std.mem.endsWith(u8, path, "/$value")) { return respond(&request, .{ .status = .ok, .body = mime_body, .content_type = "text/plain", }); } if (std.mem.endsWith(u8, path, "/attachments")) { return respond(&request, .{ .status = .ok, .body = attachments_body }); } if (std.mem.indexOf(u8, path, "/messages/") != null) { return respond(&request, .{ .status = .ok, .body = message_body }); } if (std.mem.endsWith(u8, path, "/messages")) { return respond(&request, .{ .status = .ok, .body = messages_last }); } if (std.mem.indexOf(u8, path, "/mailFolders/") != null and std.mem.endsWith(u8, path, "/childFolders")) { return respond(&request, .{ .status = .ok, .body = no_children }); } if (std.mem.endsWith(u8, path, "/mailFolders")) { return respond(&request, .{ .status = .ok, .body = folders_body }); } if (std.mem.indexOf(u8, path, "/mailFolders/") != null) { return respond(&request, .{ .status = .ok, .body = inbox_folder }); } // `/v1.0/me`, or `/v1.0/users/<id>` with nothing after the id. if (std.mem.endsWith(u8, path, "/me") or isUserRoot(path)) { return respond(&request, .{ .status = .ok, .body = user_body }); }
return respond(&request, .{ .status = .not_found, .body = not_found_body }); }
fn isUserRoot(path: []const u8) bool { const prefix = "/v1.0/users/"; if (!std.mem.startsWith(u8, path, prefix)) return false; const id = path[prefix.len..]; return id.len > 0 and std.mem.indexOfScalar(u8, id, '/') == null; }
fn serveToken(f: *FakeGraph, request: *std.http.Server.Request, body: []const u8) !void { var params = try oidc.QueryParams.parse(f.gpa, body); defer params.deinit();
const grant_type = params.getUnique("grant_type") orelse ""; if (!std.mem.eql(u8, grant_type, "refresh_token")) { return respond(request, .{ .status = .bad_request, .body = "{\"error\":\"unsupported_grant_type\"}", }); } const presented = params.getUnique("refresh_token") orelse ""; if (!std.mem.eql(u8, presented, f.valid_refresh_token)) { return respond(request, .{ .status = .bad_request, .body = "{\"error\":\"invalid_grant\"}", }); }
f.refreshes += 1;
var buf: [512]u8 = undefined; // Microsoft rotates the refresh token on nearly every refresh, which // is the behaviour `replaceWithRefreshed` and the `on_refresh` hook // exist for, so the fake does it too. const reply = try std.fmt.bufPrint(&buf, \\{{"access_token":"{s}","token_type":"Bearer","expires_in":3600, \\ "refresh_token":"rt-rotated", \\ "scope":"https://graph.microsoft.com/Mail.Read offline_access"}} , .{f.refreshed_access_token}); return respond(request, .{ .status = .ok, .body = reply }); }
fn respond(request: *std.http.Server.Request, s: Scripted) !void { var headers: [4]std.http.Header = undefined; var count: usize = 0; headers[count] = .{ .name = "content-type", .value = s.content_type }; count += 1; // Graph puts one of these on every response. It matters here because // it is the one thing the client copies out of a *successful* response // and keeps: `Diagnostics.request_id` survives until the next request // resets it, which is what makes the allocator it was made with a // lifetime question rather than a detail. headers[count] = .{ .name = "request-id", .value = response_request_id }; count += 1; if (s.retry_after) |value| { headers[count] = .{ .name = "Retry-After", .value = value }; count += 1; } if (s.content_encoding) |value| { headers[count] = .{ .name = "Content-Encoding", .value = value }; count += 1; } try request.respond(s.body, .{ .status = s.status, .keep_alive = false, .extra_headers = headers[0..count], }); }};
/// The `request-id` the fake puts on every response. A GUID, like Graph's.const response_request_id = "00000000-0000-4000-8000-000000000001";
const unauthorized_body = \\{"error":{"code":"InvalidAuthenticationToken", \\ "message":"Access token has expired or is not yet valid.", \\ "innerError":{"date":"2026-01-01T00:00:00","request-id":"req-401", \\ "code":"CompactToken parsing failed with error code: 80049217"}}};
const not_found_body = \\{"error":{"code":"ResourceNotFound","message":"Resource not found for the segment.", \\ "innerError":{"request-id":"req-404"}}};
const user_body = \\{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#users/$entity", \\ "displayName":"Jeff Ollie","givenName":"Jeff","surname":"Ollie", \\ "mail":"jeff@ocjtech.us","userPrincipalName":"jeff@ocjtech.us", \\ "id":"87d349ed-44d7-43e1-9a83-5f2406dee5bd"};
const inbox_folder = \\{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#mailFolders/$entity", \\ "id":"folder-inbox","displayName":"Inbox","parentFolderId":"folder-root", \\ "childFolderCount":0,"totalItemCount":1024,"unreadItemCount":17,"isHidden":false};
const folders_body = \\{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#mailFolders", \\ "value":[ \\ {"id":"folder-inbox","displayName":"Inbox","parentFolderId":"folder-root", \\ "childFolderCount":1,"totalItemCount":1024,"unreadItemCount":17}, \\ {"id":"folder-sent","displayName":"Sent Items","parentFolderId":"folder-root", \\ "childFolderCount":0,"totalItemCount":300,"unreadItemCount":0}]};
const inbox_children = \\{"value":[{"id":"folder-zig","displayName":"zig","parentFolderId":"folder-inbox", \\ "childFolderCount":0,"totalItemCount":42,"unreadItemCount":3}]};
const no_children = "{\"value\":[]}";
const message_body = \\{"@odata.etag":"W/\"CQAAABYAAAC4\"","id":"m1","parentFolderId":"folder-inbox", \\ "internetMessageId":"<one@example.com>","subject":"the first one", \\ "receivedDateTime":"2024-03-01T12:00:00Z","sentDateTime":"2024-03-01T11:59:58Z", \\ "isRead":false,"isDraft":false,"hasAttachments":true,"importance":"normal", \\ "categories":["zig"], \\ "body":{"contentType":"text","content":"the body, as text"}, \\ "from":{"emailAddress":{"name":"A Sender","address":"sender@example.com"}}, \\ "toRecipients":[{"emailAddress":{"address":"jeff@ocjtech.us"}}], \\ "internetMessageHeaders":[{"name":"Subject","value":"the first one"}, \\ {"name":"Received","value":"one"},{"name":"Received","value":"two"}]};
const mime_body = "Subject: the first one\r\nFrom: sender@example.com\r\n\r\nthe body, as text\r\n";
const messages_last = \\{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#messages", \\ "value":[{"id":"m9","subject":"only one"}]};
const attachments_body = \\{"value":[ \\ {"@odata.type":"#microsoft.graph.fileAttachment","id":"att-1","name":"invoice.pdf", \\ "contentType":"application/pdf","size":98765,"isInline":false}, \\ {"@odata.type":"#microsoft.graph.referenceAttachment","id":"att-2","name":"Budget.xlsx", \\ "sourceUrl":"https://contoso.sharepoint.com/Budget.xlsx","size":0}]};
const attachment_with_bytes = \\{"@odata.type":"#microsoft.graph.fileAttachment","id":"att-1","name":"hello.txt", \\ "contentType":"text/plain","size":16,"isInline":false, \\ "contentBytes":"aGVsbG8gd29ybGQ="};
const delta_final = \\{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#Collection(message)", \\ "@odata.deltaLink":"http://127.0.0.1:PORT/v1.0/me/mailFolders/inbox/messages/delta?$deltatoken=tok-2", \\ "value":[]};
/// Two successful message fetches, deliberately **out of order** -- which is/// what the reference says the service is free to do, and what the client has/// to put right.const batch_default = \\{"responses":[ \\ {"id":"1","status":200,"headers":{"Content-Type":"application/json"}, \\ "body":{"id":"m2","subject":"the second one"}}, \\ {"id":"0","status":200,"headers":{"Content-Type":"application/json"}, \\ "body":{"id":"m1","subject":"the first one"}}]};
const throttled_body = \\{"error":{"code":"TooManyRequests","message":"Please retry again later.", \\ "innerError":{"code":"429","request-id":"req-429","status":"429"}}};
const forbidden_body = \\{"error":{"code":"ErrorAccessDenied", \\ "message":"Access is denied. Check credentials and try again.", \\ "innerError":{"request-id":"req-403"}}};
const resync_body = \\{"error":{"code":"resyncRequired","message":"Resync required. Replace local state.", \\ "innerError":{"request-id":"req-410"}}};
/// Everything a test needs: an `Io` that can run two things at once, a fake/// Graph on a socket, a token set, and a client wired to both.const Harness = struct { threaded: std.Io.Threaded, io: std.Io, fake: FakeGraph, group: std.Io.Group, tokens: oidc.TokenSet, diagnostics: o365.Client.Diagnostics, url_buf: [64]u8, token_url_buf: [96]u8, /// Bodies built by `withPort`, kept until the harness is torn down: the /// fake holds borrowed slices of them until it has answered. owned: std.ArrayList([]u8),
/// `expires_in` on the token this starts with. Negative means the client /// should refresh before its first call. fn init(h: *Harness, requests: usize, expires_in: i64) !void { h.threaded = .init(testing.allocator, .{}); h.io = h.threaded.io(); h.fake = try FakeGraph.listen(h.io, testing.allocator); h.fake.requests_to_serve = requests; h.group = .init; h.diagnostics = .init(testing.allocator); h.owned = .empty;
var buf: [256]u8 = undefined; const response = try std.fmt.bufPrint(&buf, \\{{"access_token":"at-good","token_type":"Bearer", \\ "refresh_token":"rt-good","expires_in":{d}}} , .{expires_in}); h.tokens = try oidc.TokenSet.parseResponse( testing.allocator, response, .now(h.io, .real), );
try h.group.concurrent(h.io, FakeGraph.run, .{&h.fake}); }
fn deinit(h: *Harness) void { h.group.cancel(h.io); for (h.owned.items) |b| testing.allocator.free(b); h.owned.deinit(testing.allocator); h.diagnostics.deinit(); h.tokens.deinit(); h.fake.deinit(); h.threaded.deinit(); }
fn client(h: *Harness) !o365.Client { const base = try h.fake.baseUrl(&h.url_buf); const token_endpoint = try std.fmt.bufPrint(&h.token_url_buf, "{s}/token", .{base}); return .{ .gpa = testing.allocator, .oauth = .{ .provider = .{ .issuer = "https://login.microsoftonline.com/common/v2.0", .authorization_endpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", .token_endpoint = token_endpoint, }, .client_id = "test-client", .redirect_uri = "http://127.0.0.1:1/callback", .scopes = o365.scopes.mirror, }, .tokens = &h.tokens, .base_url = base, // Fast enough that a test asserting the retry happened does not // spend half a second per attempt asserting it. .retry = .{ .max_attempts = 3, .initial_backoff = .fromNanoseconds(1), .max_backoff = .fromMilliseconds(1), .max_retry_after = .fromSeconds(2), }, }; }
/// Keeps a copy of `data` until the harness is torn down, for a body a /// test builds at run time. The fake holds borrowed slices until it has /// answered, so the storage has to outlive the call that queues it. fn own(h: *Harness, data: []const u8) ![]const u8 { const owned = try testing.allocator.dupe(u8, data); errdefer testing.allocator.free(owned); try h.owned.append(testing.allocator, owned); return owned; }
/// `data` as a gzip stream, kept until the harness is torn down. fn gzip(h: *Harness, data: []const u8) ![]const u8 { // A fixed writer rather than an allocating one: `Compress.init` // asserts its output has more than eight bytes of buffer, and an // `Allocating` starts with none. var out_buf: [64 * 1024]u8 = undefined; var out: std.Io.Writer = .fixed(&out_buf);
const window = try testing.allocator.alloc(u8, std.compress.flate.max_window_len); defer testing.allocator.free(window);
var compress = try std.compress.flate.Compress.init(&out, window, .gzip, .default); try compress.writer.writeAll(data); try compress.finish();
const owned = try testing.allocator.dupe(u8, out.buffered()); errdefer testing.allocator.free(owned); try h.owned.append(testing.allocator, owned); return owned; }
/// A response body with `PORT` replaced by the port this fake is on, for /// the fixtures that carry an absolute continuation URL -- which is most /// of them, since that is how Graph paginates. /// /// Each call gets storage of its own, freed when the harness is. A shared /// buffer would not do: the fake holds these until it has answered, so a /// second call would rewrite a body the first one is still queued to send. fn withPort(h: *Harness, template: []const u8) ![]const u8 { var out: std.Io.Writer.Allocating = .init(testing.allocator); errdefer out.deinit(); var rest = template; while (std.mem.indexOf(u8, rest, "PORT")) |i| { try out.writer.writeAll(rest[0..i]); try out.writer.print("{d}", .{h.fake.port()}); rest = rest[i + 4 ..]; } try out.writer.writeAll(rest);
const owned = try out.toOwnedSlice(); errdefer testing.allocator.free(owned); try h.owned.append(testing.allocator, owned); return owned; }};
test "the user, and the token that fetched it" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
var c = try h.client(); var user = try c.getUser(h.io, testing.allocator, &h.diagnostics); defer user.deinit();
try testing.expectEqualStrings("jeff@ocjtech.us", user.value.address().?); try testing.expectEqualStrings("Jeff Ollie", user.value.label());
// The path is `/me` and not `/users/me`, and the token went on the request // rather than into the query string. try testing.expectEqualStrings("/v1.0/me", h.fake.pathOf(0)); try testing.expectEqualStrings("Bearer at-good", h.fake.requests.items[0].authorization.?); try testing.expectEqual(@as(usize, 0), h.fake.refreshes);}
test "a call's allocator may be an arena the caller then drops" { var h: Harness = undefined; try h.init(2, 3600); defer h.deinit();
var c = try h.client();
// The shape a caller reaching for an arena has in mind: everything this // call produces is read and thrown away before the next one starts. What // makes it a hazard is that a successful response leaves the `request-id` // behind in the diagnostics, where it stays until the *next* request // resets it -- long after this arena is gone. { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
var user = try c.getUser(h.io, arena.allocator(), &h.diagnostics); defer user.deinit(); try testing.expectEqualStrings("jeff@ocjtech.us", user.value.address().?); }
// The header really was copied, or the rest of this proves nothing. try testing.expectEqualStrings(response_request_id, h.diagnostics.requestId().?);
// And the second request resets the diagnostics on the way in. If the // `request-id` had been made with the arena above, this is where it would // be freed a second time -- as a segmentation fault inside `memset`, with // nothing on the stack to suggest an arena had anything to do with it. var again = try c.getUser(h.io, testing.allocator, &h.diagnostics); defer again.deinit(); try testing.expectEqualStrings(response_request_id, h.diagnostics.requestId().?);}
test "a mailbox that is not the signed-in user" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
var c = try h.client(); c.user_id = "someone+else@example.com";
var user = try c.getUser(h.io, testing.allocator, &h.diagnostics); defer user.deinit();
// The `+` is encoded, which is the whole reason the id goes through the // encoder: unencoded it would read as a space. try testing.expectEqualStrings( "/v1.0/users/someone%2Belse%40example.com", h.fake.pathOf(0), );}
test "a folder, by its well-known name" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
var c = try h.client(); var folder = try c.getMailFolder(h.io, testing.allocator, "inbox", &h.diagnostics); defer folder.deinit();
try testing.expectEqualStrings("folder-inbox", folder.value.id); try testing.expectEqualStrings("Inbox", folder.value.display_name.?); try testing.expectEqual(@as(u32, 17), folder.value.unread()); try testing.expectEqualStrings("/v1.0/me/mailFolders/inbox", h.fake.pathOf(0));}
test "the page size goes out as a Prefer header, not as $top" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
var c = try h.client(); var page = try c.listMessages(h.io, testing.allocator, .{ .folder = "inbox", .select = o365.Client.walk_select, .page_size = 50, }, &h.diagnostics); defer page.deinit();
try testing.expectEqualStrings("/v1.0/me/mailFolders/inbox/messages", h.fake.pathOf(0));
// `$top` is a limit on the whole result rather than a page size, so using // it for pagination would stop the walk at `$top` messages. The header is // the one that means "this many per page". const query = h.fake.queryOf(0); try testing.expect(std.mem.indexOf(u8, query, "$top") == null); try testing.expectEqualStrings( "odata.maxpagesize=50", h.fake.requests.items[0].prefer.?, );
// And `$select` went out readable rather than as `%24select`. try testing.expect(std.mem.startsWith(u8, query, "$select=")); try testing.expect(std.mem.indexOf(u8, query, "internetMessageId") != null); try testing.expect(std.mem.indexOf(u8, query, "body") == null);}
test "the message iterator follows every nextLink and stops" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit();
// Page two has a link and no messages, which a filtered listing really // does return. Stopping there would silently truncate the walk. try h.fake.script(.ok, try h.withPort( \\{"@odata.nextLink":"http://127.0.0.1:PORT/v1.0/me/messages?$skiptoken=page-2", \\ "value":[{"id":"m1","subject":"one"},{"id":"m2","subject":"two"}]} )); try h.fake.script(.ok, try h.withPort( \\{"@odata.nextLink":"http://127.0.0.1:PORT/v1.0/me/messages?$skiptoken=page-3", \\ "value":[]} )); try h.fake.script(.ok, \\{"value":[{"id":"m3","subject":"three"}]} );
var c = try h.client(); var it = try c.messageIterator(testing.allocator, .{ .page_size = 2 }); defer it.deinit();
var ids: std.ArrayList([]const u8) = .empty; defer { for (ids.items) |id| testing.allocator.free(id); ids.deinit(testing.allocator); }
while (try it.next(h.io, &h.diagnostics)) |stub| { // Copied, because the next call frees the page it came from. try ids.append(testing.allocator, try testing.allocator.dupe(u8, stub.id)); }
try testing.expectEqual(@as(usize, 3), ids.items.len); try testing.expectEqualStrings("m1", ids.items[0]); try testing.expectEqualStrings("m2", ids.items[1]); try testing.expectEqualStrings("m3", ids.items[2]); try testing.expectEqual(@as(?[]const u8, null), it.next_url);
// The skip tokens threaded through without the caller touching them. try testing.expect(std.mem.indexOf(u8, h.fake.queryOf(1), "$skiptoken=page-2") != null); try testing.expect(std.mem.indexOf(u8, h.fake.queryOf(2), "$skiptoken=page-3") != null); try testing.expectEqual(@as(usize, 3), h.fake.requests.items.len);}
test "a nextLink pointing at another host is refused, not followed" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
// The warning this provokes is the point of the test, so it is not also // printed into the middle of the test runner's progress output. const saved = testing.log_level; testing.log_level = .err; defer testing.log_level = saved;
// The failure this check exists for. Followed, this sends a bearer token // good for the whole mailbox to whoever wrote the response body. try h.fake.script(.ok, \\{"@odata.nextLink":"https://evil.example.com/collect", \\ "value":[{"id":"m1"}]} );
var c = try h.client(); var it = try c.messageIterator(testing.allocator, .{}); defer it.deinit();
// The first page still comes back: the link is refused when it is // followed, not when it is parsed, so nothing already fetched is lost. const first = (try it.next(h.io, &h.diagnostics)).?; try testing.expectEqualStrings("m1", first.id);
try testing.expectError(error.UntrustedLink, it.next(h.io, &h.diagnostics)); // And exactly one request was made: the second was never sent. try testing.expectEqual(@as(usize, 1), h.fake.requests.items.len);}
test "a stored delta link pointing at another host is refused before any request" { var h: Harness = undefined; try h.init(0, 3600); defer h.deinit();
var c = try h.client(); // A delta link comes back out of a file between runs, which is a second // place it could have been changed, so it is checked exactly as one off // the wire is. try testing.expectError(error.UntrustedLink, c.messageDelta(testing.allocator, .{ .folder = "inbox", .delta_link = "https://evil.example.com/v1.0/me/mailFolders/inbox/messages/delta", })); try testing.expectEqual(@as(usize, 0), h.fake.requests.items.len);}
test "a full message, and the MIME behind it" { var h: Harness = undefined; try h.init(2, 3600); defer h.deinit();
var c = try h.client(); { var message = try c.getMessage(h.io, testing.allocator, "m1", .{ .body_type = .text, }, &h.diagnostics); defer message.deinit();
const m = message.value; try testing.expectEqualStrings("the first one", m.subject.?); try testing.expectEqualStrings("sender@example.com", m.fromAddress().?); try testing.expectEqualStrings("<one@example.com>", m.internet_message_id.?); try testing.expectEqual(@as(?bool, false), m.is_read); try testing.expect(m.hasCategory("zig")); try testing.expectEqualStrings("one", m.header("received").?); try testing.expectEqual(o365.Message.BodyType.text, m.body.?.content_type);
// The body content type is a `Prefer` header, quoted, which is how the // reference writes it. try testing.expectEqualStrings( "outlook.body-content-type=\"text\"", h.fake.requests.items[0].prefer.?, ); } { // And the other body: the bytes as they arrived, which is what goes in // a maildir. const mime = try c.getMime(h.io, testing.allocator, "m1", &h.diagnostics); defer testing.allocator.free(mime);
try testing.expectEqualStrings(mime_body, mime); try testing.expectEqualStrings("/v1.0/me/messages/m1/$value", h.fake.pathOf(1)); // Not asked for as JSON, because it is not JSON. try testing.expect(std.mem.indexOf( u8, h.fake.requests.items[1].accept.?, "text/plain", ) != null); }}
test "an id with punctuation in it cannot address another endpoint" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
var c = try h.client(); // Graph's ids really are base64-shaped. Unencoded, this would address // `/v1.0/me/messages/../../users`. var message = try c.getMessage( h.io, testing.allocator, "../../users?x=", .{}, &h.diagnostics, ); defer message.deinit();
try testing.expectEqualStrings( "/v1.0/me/messages/..%2F..%2Fusers%3Fx%3D", h.fake.pathOf(0), );}
test "a delta walk ends holding the token to resume from" { var h: Harness = undefined; try h.init(2, 3600); defer h.deinit();
try h.fake.script(.ok, try h.withPort( \\{"@odata.nextLink":"http://127.0.0.1:PORT/v1.0/me/mailFolders/inbox/messages/delta?$skiptoken=s1", \\ "value":[{"id":"m1","subject":"changed"}, \\ {"id":"m2","@removed":{"reason":"deleted"}}]} )); try h.fake.script(.ok, try h.withPort(delta_final));
var c = try h.client(); var it = try c.messageDelta(testing.allocator, .{ .folder = "inbox", .select = o365.Client.walk_select, }); defer it.deinit();
var changed: usize = 0; var removed: usize = 0; while (try it.next(h.io, &h.diagnostics)) |message| { if (message.isRemoved()) { removed += 1; try testing.expectEqualStrings("m2", message.id); try testing.expect(message.removed.?.isDeleted()); } else { changed += 1; try testing.expectEqualStrings("m1", message.id); } }
try testing.expectEqual(@as(usize, 1), changed); try testing.expectEqual(@as(usize, 1), removed);
// The whole point: what to store and pass as `delta_link` next time. try testing.expect(std.mem.indexOf(u8, it.delta_link.?, "$deltatoken=tok-2") != null);
try testing.expectEqualStrings("/v1.0/me/mailFolders/inbox/messages/delta", h.fake.pathOf(0)); try testing.expect(std.mem.indexOf(u8, h.fake.queryOf(1), "$skiptoken=s1") != null);}
test "a delta walk resumed from a stored link sends it unchanged" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
try h.fake.script(.ok, try h.withPort(delta_final));
var base_buf: [64]u8 = undefined; const base = try h.fake.baseUrl(&base_buf); var link_buf: [256]u8 = undefined; const stored = try std.fmt.bufPrint( &link_buf, "{s}/v1.0/me/mailFolders/inbox/messages/delta?$deltatoken=tok-1", .{base}, );
var c = try h.client(); var it = try c.messageDelta(testing.allocator, .{ .folder = "inbox", .delta_link = stored, // Ignored when resuming: Graph encodes the original query into the // token, so this must not appear on the request. .select = &.{"subject"}, }); defer it.deinit();
try testing.expectEqual(@as(?o365.Message, null), try it.next(h.io, &h.diagnostics));
try testing.expectEqualStrings("$deltatoken=tok-1", h.fake.queryOf(0)); try testing.expect(std.mem.indexOf(u8, h.fake.queryOf(0), "$select") == null);}
test "a delta token that has aged out is its own error" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
try h.fake.script(.gone, resync_body);
var base_buf: [64]u8 = undefined; const base = try h.fake.baseUrl(&base_buf); var link_buf: [256]u8 = undefined; const stored = try std.fmt.bufPrint( &link_buf, "{s}/v1.0/me/mailFolders/inbox/messages/delta?$deltatoken=stale", .{base}, );
var c = try h.client(); var it = try c.messageDelta(testing.allocator, .{ .folder = "inbox", .delta_link = stored }); defer it.deinit();
// Not `error.ApiError`: this one means the incremental path is gone and // the folder has to be walked in full, which is a different decision from // any other failure. try testing.expectError(error.ResyncRequired, it.next(h.io, &h.diagnostics));}
test "the folder tree walks into children and builds paths" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit();
// The top level, then the inbox's children, then the zig folder's (none). try h.fake.script(.ok, folders_body); try h.fake.script(.ok, inbox_children);
var c = try h.client(); var tree = try c.folderTree(h.io, testing.allocator, .{}, &h.diagnostics); defer tree.deinit();
try testing.expectEqual(@as(usize, 3), tree.count()); try testing.expectEqualStrings("Inbox", tree.path("folder-inbox").?); try testing.expectEqualStrings("Sent Items", tree.path("folder-sent").?); // The one a single listing does not give: a nested folder, with its // ancestors in front of it. try testing.expectEqualStrings("Inbox/zig", tree.path("folder-zig").?); try testing.expectEqual(@as(?[]const u8, null), tree.path("folder-nonexistent"));
try testing.expectEqual(@as(?u32, 3), tree.get("folder-zig").?.unread_item_count);
// Three folders, two requests. Only a folder whose `childFolderCount` is // more than zero is descended into, so `Sent Items` and `zig` cost // nothing -- which is the difference between a request per folder and a // request per folder that has any. try testing.expectEqual(@as(usize, 2), h.fake.requests.items.len);}
test "listing attachments leaves the bytes out unless they are asked for" { var h: Harness = undefined; try h.init(2, 3600); defer h.deinit();
var c = try h.client(); { var page = try c.listAttachments(h.io, testing.allocator, "m1", .{}, &h.diagnostics); defer page.deinit();
try testing.expectEqual(@as(usize, 2), page.items.len); try testing.expectEqual(o365.Attachment.Kind.file, page.items[0].kind); try testing.expectEqualStrings("invoice.pdf", page.items[0].name.?); // The default `$select`, which is what keeps a listing from being the // whole mailbox downloaded twice. try testing.expect(!page.items[0].has_content); try testing.expectEqual(o365.Attachment.Kind.reference, page.items[1].kind);
const query = h.fake.queryOf(0); try testing.expect(std.mem.indexOf(u8, query, "contentBytes") == null); try testing.expect(std.mem.indexOf(u8, query, "$select=id,name") != null); } { try h.fake.script(.ok, attachment_with_bytes); var attachment = try c.getAttachment( h.io, testing.allocator, "m1", "att-1", &h.diagnostics, ); defer attachment.deinit();
try testing.expect(attachment.value.has_content); try testing.expectEqualStrings("hello world", attachment.value.content.?); try testing.expectEqualStrings( "/v1.0/me/messages/m1/attachments/att-1", h.fake.pathOf(1), ); }}
test "an expired token is refreshed before the call, not after it fails" { var h: Harness = undefined; // One refresh plus one API call. try h.init(2, -60); defer h.deinit();
var c = try h.client(); var user = try c.getUser(h.io, testing.allocator, &h.diagnostics); defer user.deinit();
try testing.expectEqual(@as(usize, 1), h.fake.refreshes); try testing.expectEqualStrings("/token", h.fake.pathOf(0)); // The API call carried the new token and was never made with the old one. try testing.expectEqualStrings("/v1.0/me", h.fake.pathOf(1)); try testing.expectEqualStrings("Bearer at-fresh", h.fake.requests.items[1].authorization.?);
// Microsoft rotates the refresh token, and the merge took the new one. // Keeping the old one here is the bug that makes the *next* run fail. try testing.expectEqualStrings("rt-rotated", h.tokens.refresh_token.?); try testing.expectEqualStrings("at-fresh", h.tokens.access_token);}
test "a refresh writes through the hook" { var h: Harness = undefined; try h.init(2, -60); defer h.deinit();
const Recorder = struct { calls: usize = 0, last: [64]u8 = undefined, last_len: usize = 0,
fn onRefresh(context: ?*anyopaque, tokens: *const oidc.TokenSet) anyerror!void { const self: *@This() = @ptrCast(@alignCast(context.?)); self.calls += 1; const rt = tokens.refresh_token orelse ""; @memcpy(self.last[0..rt.len], rt); self.last_len = rt.len; } }; var recorder: Recorder = .{};
var c = try h.client(); c.on_refresh = .{ .context = &recorder, .func = Recorder.onRefresh };
var user = try c.getUser(h.io, testing.allocator, &h.diagnostics); defer user.deinit();
try testing.expectEqual(@as(usize, 1), recorder.calls); // The rotated one, which is the whole reason the hook has to run. try testing.expectEqualStrings("rt-rotated", recorder.last[0..recorder.last_len]);}
test "a hook that cannot persist fails the call" { var h: Harness = undefined; try h.init(2, -60); defer h.deinit();
const Failing = struct { fn onRefresh(_: ?*anyopaque, _: *const oidc.TokenSet) anyerror!void { return error.DiskFull; } };
var c = try h.client(); var unused: u8 = 0; c.on_refresh = .{ .context = &unused, .func = Failing.onRefresh };
// The warning this provokes is the point of the test, so it is not also // printed into the middle of the test runner's progress output. const saved = testing.log_level; testing.log_level = .err; defer testing.log_level = saved;
// Deliberately fatal: a rotated refresh token that was not written down is // one the next run does not have. try testing.expectError( error.RefreshHookFailed, c.getUser(h.io, testing.allocator, &h.diagnostics), );}
test "a 401 on a token that looked good is spent on one refresh" { var h: Harness = undefined; // The rejected call, the refresh, the retry. try h.init(3, 3600); defer h.deinit();
// The clock says the token is good for an hour; the server disagrees, // which is what withdrawn consent or a conditional access policy looks // like. try h.fake.script(.unauthorized, unauthorized_body);
var c = try h.client(); var user = try c.getUser(h.io, testing.allocator, &h.diagnostics); defer user.deinit();
try testing.expectEqualStrings("jeff@ocjtech.us", user.value.mail.?); try testing.expectEqual(@as(usize, 1), h.fake.refreshes); try testing.expectEqual(@as(usize, 3), h.fake.requests.items.len); try testing.expectEqualStrings("Bearer at-good", h.fake.requests.items[0].authorization.?); try testing.expectEqualStrings("/token", h.fake.pathOf(1)); try testing.expectEqualStrings("Bearer at-fresh", h.fake.requests.items[2].authorization.?);}
test "a 401 that survives the refresh is not retried forever" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit();
try h.fake.script(.unauthorized, unauthorized_body); // Still refused after the refresh: the grant is genuinely gone. try h.fake.script(.unauthorized, unauthorized_body);
var c = try h.client(); try testing.expectError( error.Unauthorized, c.getUser(h.io, testing.allocator, &h.diagnostics), ); try testing.expectEqual(@as(usize, 1), h.fake.refreshes); // Exactly three: call, refresh, call. Not a loop. try testing.expectEqual(@as(usize, 3), h.fake.requests.items.len);}
test "throttling is waited out, and Retry-After is what is obeyed" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit();
// One second, which is far longer than the schedule in this harness -- // `initial_backoff` is a nanosecond -- so a run that finishes in // measurably more than a second is one that read the header. try h.fake.scriptFull(.{ .status = .too_many_requests, .body = throttled_body, .retry_after = "1", });
const started = std.Io.Timestamp.now(h.io, .awake);
var c = try h.client(); var user = try c.getUser(h.io, testing.allocator, &h.diagnostics); defer user.deinit();
const elapsed = std.Io.Timestamp.now(h.io, .awake).nanoseconds - started.nanoseconds;
try testing.expectEqualStrings("jeff@ocjtech.us", user.value.mail.?); try testing.expectEqual(@as(u32, 2), h.diagnostics.http.attempts); // Microsoft's guidance is explicit that obeying the header is the fastest // way out of a throttle, because usage keeps being logged against a client // that comes back early. try testing.expect(elapsed >= std.time.ns_per_s);}
test "a Retry-After longer than this will wait gives up instead of sleeping" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
const saved = testing.log_level; testing.log_level = .err; defer testing.log_level = saved;
// The harness allows two seconds. Obeying this would park the test for an // hour on the say-so of the far end. try h.fake.scriptFull(.{ .status = .too_many_requests, .body = throttled_body, .retry_after = "3600", });
var c = try h.client(); try testing.expectError( error.TooManyRetries, c.getUser(h.io, testing.allocator, &h.diagnostics), ); // And it gave up rather than waiting: one request, not the three the // retry budget allows. try testing.expectEqual(@as(usize, 1), h.fake.requests.items.len);}
test "throttling that never clears gives up" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit();
for (0..3) |_| try h.fake.script(.too_many_requests, throttled_body);
var c = try h.client(); try testing.expectError( error.TooManyRetries, c.getUser(h.io, testing.allocator, &h.diagnostics), ); // `max_attempts` and not one more. try testing.expectEqual(@as(usize, 3), h.fake.requests.items.len);}
test "a permission failure is not retried" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
try h.fake.script(.forbidden, forbidden_body);
var c = try h.client(); try testing.expectError( error.ApiError, c.getUser(h.io, testing.allocator, &h.diagnostics), );
// Once. In Graph a 403 is permission or licensing and never quota -- // unlike Google, where it may mean "slow down" -- so retrying it spends // the budget on a certainty. try testing.expectEqual(@as(usize, 1), h.fake.requests.items.len);
const api = h.diagnostics.apiError().?; try testing.expectEqualStrings("ErrorAccessDenied", api.code.?); try testing.expect(api.isPermissionFailure(.forbidden)); // The identifier a support request has to quote, lifted off the inner // error where Graph puts it. try testing.expectEqualStrings("req-403", h.diagnostics.requestId().?);
var buf: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try h.diagnostics.format(&w); try testing.expect(std.mem.indexOf(u8, w.buffered(), "ErrorAccessDenied") != null);}
test "a token set with no refresh token cannot be refreshed" { var h: Harness = undefined; try h.init(0, 3600); defer h.deinit();
// Replace the token set with one that has no refresh token, expired -- // which is what signing in without `offline_access` leaves behind. h.tokens.deinit(); h.tokens = try oidc.TokenSet.parseResponse( testing.allocator, "{\"access_token\":\"at-old\",\"expires_in\":-60}", .now(h.io, .real), );
var c = try h.client(); try testing.expectError( error.NoRefreshToken, c.getUser(h.io, testing.allocator, &h.diagnostics), );}
test "a body that arrives compressed anyway is inflated" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
// `identity` is what the request asks for, and Graph honours it -- but a // proxy in the way need not, and `Response.reader` does not decompress, so // believing the header blindly would hand the JSON parser a gzip stream. // // This test exists because that path had none: the decompressor and its // window buffer were scoped to the branch that built them, so both were // dead by the time the first byte was read. try h.fake.scriptFull(.{ .status = .ok, .body = try h.gzip(user_body), .content_encoding = "gzip", });
var c = try h.client(); var user = try c.getUser(h.io, testing.allocator, &h.diagnostics); defer user.deinit();
try testing.expectEqualStrings("jeff@ocjtech.us", user.value.mail.?); try testing.expectEqualStrings("Jeff Ollie", user.value.display_name.?);}
test "a response larger than the ceiling is an error rather than the process' memory" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
try h.fake.script(.ok, user_body);
var c = try h.client(); c.max_response_bytes = 16;
try testing.expectError( error.ResponseTooLarge, c.getUser(h.io, testing.allocator, &h.diagnostics), );}
// -- $batch -----------------------------------------------------------------
test "a batch posts one envelope and puts the answers back in order" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
var c = try h.client(); var batch = c.batch(testing.allocator); defer batch.deinit();
const first = try batch.getMessage("m1", .{ .select = o365.Client.walk_select }); const second = try batch.getMessage("m2", .{});
var results = try batch.send(h.io, &h.diagnostics); defer results.deinit();
try testing.expectEqual(@as(usize, 2), results.responses.len); try testing.expectEqual(@as(u32, 1), results.round_trips); try testing.expectEqual(@as(usize, 2), results.okCount());
// The fake answered `1` before `0`, which is exactly what the reference // says the service may do. The caller never sees that. try testing.expectEqualStrings("0", results.responses[0].id); try testing.expectEqualStrings("1", results.responses[1].id); try testing.expectEqualStrings( "the first one", o365.json.string(results.responses[0].body.?, "subject").?, ); try testing.expectEqualStrings( "the second one", o365.json.string(results.responses[1].body.?, "subject").?, );
// And they are findable by the id `add` handed back. try testing.expectEqualStrings("m1", o365.json.string(results.get(first).?.body.?, "id").?); try testing.expectEqualStrings("m2", o365.json.string(results.get(second).?.body.?, "id").?);
// One POST to the service root -- note the mailbox is *not* in this path; // each entry names its own. try testing.expectEqualStrings("/v1.0/$batch", h.fake.pathOf(0));
const sent = h.fake.requests.items[0].body.?; try testing.expect(std.mem.startsWith(u8, sent, "{\"requests\":[")); // Entry URLs are relative to the version root, because the version is // already in the URL the batch went to. try testing.expect(std.mem.indexOf(u8, sent, "\"url\":\"/me/messages/m1") != null); try testing.expect(std.mem.indexOf(u8, sent, "graph.microsoft.com") == null); try testing.expect(std.mem.indexOf(u8, sent, "/v1.0/me/messages") == null); // The `$select` rode along on the entry. try testing.expect(std.mem.indexOf(u8, sent, "internetMessageId") != null);}
test "a failure inside a batch is a result, not an error" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
// A 200 envelope carrying nothing but failures, which is the shape that // makes every layer below this one think the call went fine. try h.fake.script(.ok, \\{"responses":[ \\ {"id":"0","status":404, \\ "body":{"error":{"code":"ErrorItemNotFound","message":"Not found."}}}, \\ {"id":"1","status":403, \\ "body":{"error":{"code":"ErrorAccessDenied","message":"Access is denied."}}}]} );
var c = try h.client(); var batch = c.batch(testing.allocator); defer batch.deinit(); _ = try batch.getMessage("gone", .{}); _ = try batch.getMessage("forbidden", .{});
// Not an error: the envelope succeeded, and what is in it is the answer. var results = try batch.send(h.io, &h.diagnostics); defer results.deinit();
try testing.expectEqual(@as(usize, 0), results.okCount()); try testing.expect(results.responses[0].status == .not_found); try testing.expect(results.responses[1].status == .forbidden);
var api = results.responses[1].apiError(testing.allocator).?; defer api.deinit(); try testing.expect(api.isPermissionFailure(results.responses[1].status));}
test "a throttled entry inside a batch is retried, which nothing else would do" { var h: Harness = undefined; try h.init(2, 3600); defer h.deinit();
const saved = testing.log_level; testing.log_level = .err; defer testing.log_level = saved;
// Outside a batch `http.zig` would see this 429 and wait it out. Inside // one it is a field in a 200, so if this type did not retry it the request // would simply be lost -- silently, in the middle of a mailbox walk. try h.fake.script(.ok, \\{"responses":[ \\ {"id":"0","status":200,"body":{"id":"m1","subject":"went through"}}, \\ {"id":"1","status":429,"headers":{"Retry-After":"0"}, \\ "body":{"error":{"code":"TooManyRequests"}}}]} ); // The second pass carries only the entry that was throttled. try h.fake.script(.ok, \\{"responses":[{"id":"1","status":200,"body":{"id":"m2","subject":"second time"}}]} );
var c = try h.client(); var batch = c.batch(testing.allocator); defer batch.deinit(); _ = try batch.getMessage("m1", .{}); _ = try batch.getMessage("m2", .{});
var results = try batch.send(h.io, &h.diagnostics); defer results.deinit();
try testing.expectEqual(@as(usize, 2), results.okCount()); try testing.expectEqual(@as(u32, 2), results.round_trips); try testing.expectEqualStrings( "second time", o365.json.string(results.responses[1].body.?, "subject").?, );
// The retry resent only the throttled entry, not the one that worked. const second_envelope = h.fake.requests.items[1].body.?; try testing.expect(std.mem.indexOf(u8, second_envelope, "\"id\":\"1\"") != null); try testing.expect(std.mem.indexOf(u8, second_envelope, "\"id\":\"0\"") == null);}
test "an entry still throttled when the attempts run out is reported, not dropped" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit();
const saved = testing.log_level; testing.log_level = .err; defer testing.log_level = saved;
for (0..3) |_| { try h.fake.script(.ok, \\{"responses":[{"id":"0","status":429,"headers":{"Retry-After":"0"}, \\ "body":{"error":{"code":"TooManyRequests"}}}]} ); }
var c = try h.client(); var batch = c.batch(testing.allocator); batch.retry = .{ .max_attempts = 3, .max_retry_after = .fromSeconds(2) }; defer batch.deinit(); _ = try batch.getMessage("m1", .{});
var results = try batch.send(h.io, &h.diagnostics); defer results.deinit();
// Given back throttled rather than silently missing: a walk that quietly // skips a message is worse than one that says which it could not fetch. try testing.expectEqual(@as(usize, 1), results.responses.len); try testing.expect(results.responses[0].throttled()); try testing.expectEqual(@as(u32, 3), results.round_trips);}
test "a Retry-After longer than the batch will wait stops rather than sleeping" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
const saved = testing.log_level; testing.log_level = .err; defer testing.log_level = saved;
try h.fake.script(.ok, \\{"responses":[{"id":"0","status":429,"headers":{"Retry-After":"3600"}, \\ "body":{"error":{"code":"TooManyRequests"}}}]} );
var c = try h.client(); var batch = c.batch(testing.allocator); batch.retry = .{ .max_attempts = 4, .max_retry_after = .fromSeconds(2) }; defer batch.deinit(); _ = try batch.getMessage("m1", .{});
var results = try batch.send(h.io, &h.diagnostics); defer results.deinit();
// One round trip: it gave up rather than parking the process for an hour // on the say-so of the far end. try testing.expectEqual(@as(u32, 1), results.round_trips); try testing.expect(results.responses[0].throttled());}
test "more than twenty requests are split into chunks of twenty" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit();
var c = try h.client(); var batch = c.batch(testing.allocator); defer batch.deinit();
// Forty-five: three envelopes of 20, 20 and 5. for (0..45) |i| { var id_buf: [16]u8 = undefined; const id = try std.fmt.bufPrint(&id_buf, "m{d}", .{i}); _ = try batch.getMessage(id, .{}); } try testing.expectEqual(@as(usize, 45), batch.count());
// Each chunk is answered with exactly the ids it asked for, echoed back. for (0..3) |chunk| { var body: std.Io.Writer.Allocating = .init(testing.allocator); defer body.deinit(); try body.writer.writeAll("{\"responses\":["); const start = chunk * 20; const end = @min(start + 20, 45); for (start..end) |i| { if (i != start) try body.writer.writeByte(','); try body.writer.print( "{{\"id\":\"{d}\",\"status\":200,\"body\":{{\"id\":\"m{d}\"}}}}", .{ i, i }, ); } try body.writer.writeAll("]}"); try h.fake.script(.ok, try h.own(body.written())); }
var results = try batch.send(h.io, &h.diagnostics); defer results.deinit();
try testing.expectEqual(@as(usize, 45), results.responses.len); try testing.expectEqual(@as(usize, 45), results.okCount()); try testing.expectEqual(@as(u32, 3), results.round_trips); try testing.expectEqual(@as(usize, 3), h.fake.requests.items.len);
// In order, across the chunk boundaries. for (results.responses, 0..) |r, i| { var want: [16]u8 = undefined; try testing.expectEqualStrings( try std.fmt.bufPrint(&want, "m{d}", .{i}), o365.json.string(r.body.?, "id").?, ); }}
test "a request the service never answered is reported rather than dropped" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
// Two asked for, one answered. Graph should not do this; if it ever does, // the missing one must not read as a message that simply has no fields. try h.fake.script(.ok, \\{"responses":[{"id":"0","status":200,"body":{"id":"m1"}}]} );
var c = try h.client(); var batch = c.batch(testing.allocator); defer batch.deinit(); _ = try batch.getMessage("m1", .{}); _ = try batch.getMessage("m2", .{});
var results = try batch.send(h.io, &h.diagnostics); defer results.deinit();
try testing.expectEqual(@as(usize, 2), results.responses.len); try testing.expect(results.responses[0].ok()); try testing.expect(!results.responses[1].ok()); try testing.expectEqual(@as(?std.json.Value, null), results.responses[1].body);}
test "getMessages is the walk's second half, in order and with the failures kept" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
try h.fake.script(.ok, \\{"responses":[ \\ {"id":"2","status":200,"body":{"id":"m3","subject":"third", \\ "receivedDateTime":"2024-03-03T00:00:00Z"}}, \\ {"id":"0","status":200,"body":{"id":"m1","subject":"first", \\ "receivedDateTime":"2024-03-01T00:00:00Z"}}, \\ {"id":"1","status":404, \\ "body":{"error":{"code":"ErrorItemNotFound","message":"Not found."}}}]} );
var c = try h.client(); var fetched = try c.getMessages( h.io, testing.allocator, &.{ "m1", "m2", "m3" }, .{ .select = o365.Client.walk_select }, &h.diagnostics, ); defer fetched.deinit();
try testing.expectEqual(@as(usize, 3), fetched.items.len); try testing.expectEqual(@as(usize, 2), fetched.okCount()); try testing.expectEqual(@as(u32, 1), fetched.round_trips);
try testing.expectEqualStrings("first", fetched.items[0].message.?.subject.?); // Deleted between the listing and the fetch, which a walk has to survive. try testing.expectEqual(@as(?o365.Message, null), fetched.items[1].message); try testing.expect(fetched.items[1].status == .not_found); try testing.expectEqualStrings("third", fetched.items[2].message.?.subject.?);}
test "a batch envelope that is not a batch response is an error" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit();
try h.fake.script(.ok, "{\"value\":[]}");
var c = try h.client(); var batch = c.batch(testing.allocator); defer batch.deinit(); _ = try batch.getMessage("m1", .{});
try testing.expectError(error.MalformedBatch, batch.send(h.io, &h.diagnostics));}
test "the batch POST itself still refreshes an expired token" { var h: Harness = undefined; try h.init(2, -60); defer h.deinit();
var c = try h.client(); var batch = c.batch(testing.allocator); defer batch.deinit(); _ = try batch.getMessage("m1", .{});
var results = try batch.send(h.io, &h.diagnostics); defer results.deinit();
try testing.expectEqual(@as(usize, 1), h.fake.refreshes); try testing.expectEqualStrings("/token", h.fake.pathOf(0)); try testing.expectEqualStrings("/v1.0/$batch", h.fake.pathOf(1)); try testing.expectEqualStrings("Bearer at-fresh", h.fake.requests.items[1].authorization.?);}