// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The client against a Gmail 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 stops, 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, and that a quota failure is waited out //! while a permission failure is not. //! //! The server is a few hundred lines of scripted responses rather than Gmail, //! so it proves the client and the API reference agree, not that Gmail does. const std = @import("std"); const gmail = @import("gmail"); const oidc = @import("oidc"); const testing = std.testing; /// Enough of the Gmail API to answer this client, and strict about what it is /// sent so that a malformed request fails here rather than passing quietly. const FakeGmail = struct { server: std.Io.net.Server, io: std.Io, gpa: std.mem.Allocator, /// The access token that works. Anything else gets a 401 with Google'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, for the paths a test wants to /// script. A path with nothing queued gets the default handler. scripted: std.ArrayList(Scripted) = .empty, /// Queued replies for the *parts* of a batch, consumed in order. A part /// with nothing queued is answered by the same routing as a call made on /// its own. batch_parts: std.ArrayList(Scripted) = .empty, /// Answer the parts of a batch back to front, which Google is explicit /// that it may do: the calls are executed in any order. batch_reversed: bool = false, /// The request line of every call this server has been sent inside a /// batch, in the order they arrived. batch_targets: std.ArrayList([]u8) = .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, }; const Seen = struct { target: []u8, authorization: ?[]u8, content_type: ?[]u8 = null, fn deinit(s: *Seen, gpa: std.mem.Allocator) void { gpa.free(s.target); if (s.authorization) |a| gpa.free(a); if (s.content_type) |c| gpa.free(c); } }; fn listen(io: std.Io, gpa: std.mem.Allocator) !FakeGmail { 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: *FakeGmail) void { for (f.requests.items) |*r| r.deinit(f.gpa); f.requests.deinit(f.gpa); for (f.batch_targets.items) |t| f.gpa.free(t); f.batch_targets.deinit(f.gpa); f.scripted.deinit(f.gpa); f.batch_parts.deinit(f.gpa); f.server.deinit(f.io); } fn baseUrl(f: *const FakeGmail, buf: []u8) ![]const u8 { return std.fmt.bufPrint(buf, "http://127.0.0.1:{d}", .{f.server.socket.address.getPort()}); } fn script(f: *FakeGmail, status: std.http.Status, body: []const u8) !void { try f.scripted.append(f.gpa, .{ .status = status, .body = body }); } /// The reply to the next call inside a batch. fn scriptPart(f: *FakeGmail, status: std.http.Status, body: []const u8) !void { try f.batch_parts.append(f.gpa, .{ .status = status, .body = body }); } /// The query string of the request at `index`, without the `?`. fn queryOf(f: *const FakeGmail, 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 FakeGmail, 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: *FakeGmail) void { for (0..f.requests_to_serve) |_| { f.serveOne() catch |err| switch (err) { error.Canceled => return, else => { std.debug.print("fake gmail: {t}\n", .{err}); return; }, }; } } fn serveOne(f: *FakeGmail) !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, }; 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, "content-type")) { seen.content_type = 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()); } // 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 OAuth server, not the API, 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, .unauthorized, 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, .unauthorized, 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.status, s.body); } if (std.mem.eql(u8, path, "/batch/gmail/v1")) { return f.serveBatch(&request, seen.content_type, body); } if (std.mem.endsWith(u8, path, "/profile")) return respond(&request, .ok, profile_body); if (std.mem.endsWith(u8, path, "/labels")) return respond(&request, .ok, labels_body); if (std.mem.indexOf(u8, path, "/messages/") != null) { return respond(&request, .ok, message_body); } if (std.mem.endsWith(u8, path, "/messages")) return respond(&request, .ok, messages_page_1); if (std.mem.endsWith(u8, path, "/history")) return respond(&request, .ok, history_body); return respond(&request, .not_found, "{\"error\":{\"code\":404}}"); } /// Answers a `multipart/mixed` batch with a `multipart/mixed` batch, /// built the way Google builds one: a leading blank line, a part per /// call, `Content-ID: ` echoing the number the call carried, /// and a whole HTTP response inside each part. /// /// The request is split by hand rather than with `gmail.batch`, which /// parses responses and not requests -- and which would prove only that /// this library agrees with itself. fn serveBatch( f: *FakeGmail, request: *std.http.Server.Request, content_type: ?[]const u8, body: []const u8, ) !void { const ct = content_type orelse return respond(request, .bad_request, "{\"error\":{\"code\":400}}"); const prefix = "multipart/mixed; boundary="; if (!std.mem.startsWith(u8, ct, prefix)) { return respond(request, .bad_request, "{\"error\":{\"code\":400}}"); } var delimiter: std.ArrayList(u8) = .empty; defer delimiter.deinit(f.gpa); try delimiter.appendSlice(f.gpa, "--"); try delimiter.appendSlice(f.gpa, ct[prefix.len..]); var out: std.Io.Writer.Allocating = .init(f.gpa); defer out.deinit(); const w = &out.writer; var parts = std.mem.splitSequence(u8, body, delimiter.items); _ = parts.next(); var answered: usize = 0; var replies: std.ArrayList([]u8) = .empty; defer { for (replies.items) |r| f.gpa.free(r); replies.deinit(f.gpa); } while (parts.next()) |chunk| { if (std.mem.startsWith(u8, chunk, "--")) break; // The part's own headers, then the call inside it. const blank = std.mem.find(u8, chunk, "\r\n\r\n") orelse continue; const part_headers = chunk[0..blank]; const call = std.mem.trim(u8, chunk[blank + 4 ..], "\r\n"); const request_line = call[0 .. std.mem.findScalar(u8, call, '\r') orelse call.len]; const id = partHeader(part_headers, "Content-ID") orelse ""; const number = std.mem.trim(u8, id, "<>"); try f.batch_targets.append(f.gpa, try f.gpa.dupe(u8, request_line)); const status, const reply = if (f.batch_parts.items.len > 0) part: { const s = f.batch_parts.orderedRemove(0); break :part .{ s.status, s.body }; } else .{ std.http.Status.ok, message_body }; try replies.append(f.gpa, try std.fmt.allocPrint( f.gpa, "\r\n{s}\r\n" ++ "Content-Type: application/http\r\n" ++ "Content-ID: \r\n" ++ "\r\n" ++ "HTTP/1.1 {d} {s}\r\n" ++ "Content-Type: application/json; charset=UTF-8\r\n" ++ "\r\n" ++ "{s}\n", .{ delimiter.items, number, @intFromEnum(status), status.phrase() orelse "", reply }, )); answered += 1; } if (f.batch_reversed) std.mem.reverse([]u8, replies.items); for (replies.items) |r| try w.writeAll(r); try w.print("\r\n{s}--\r\n", .{delimiter.items}); var boundary_header: [128]u8 = undefined; return request.respond(out.written(), .{ .status = .ok, .keep_alive = false, .extra_headers = &.{.{ .name = "content-type", .value = try std.fmt.bufPrint(&boundary_header, "{s}{s}", .{ prefix, ct[prefix.len..], }), }}, }); } fn partHeader(headers: []const u8, name: []const u8) ?[]const u8 { var lines = std.mem.splitScalar(u8, headers, '\n'); while (lines.next()) |raw| { const line = std.mem.trimEnd(u8, raw, "\r"); const colon = std.mem.findScalar(u8, line, ':') orelse continue; if (!std.ascii.eqlIgnoreCase(std.mem.trim(u8, line[0..colon], " \t"), name)) continue; return std.mem.trim(u8, line[colon + 1 ..], " \t"); } return null; } fn serveToken(f: *FakeGmail, 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, .bad_request, "{\"error\":\"unsupported_grant_type\"}"); } const presented = params.getUnique("refresh_token") orelse ""; if (!std.mem.eql(u8, presented, f.valid_refresh_token)) { return respond(request, .bad_request, "{\"error\":\"invalid_grant\"}"); } f.refreshes += 1; var buf: [512]u8 = undefined; const reply = try std.fmt.bufPrint(&buf, \\{{"access_token":"{s}","token_type":"Bearer","expires_in":3600, \\ "scope":"https://www.googleapis.com/auth/gmail.readonly"}} , .{f.refreshed_access_token}); return respond(request, .ok, reply); } fn respond(request: *std.http.Server.Request, status: std.http.Status, body: []const u8) !void { try request.respond(body, .{ .status = status, .keep_alive = false, .extra_headers = &.{.{ .name = "content-type", .value = "application/json" }}, }); } }; const unauthorized_body = \\{"error":{"code":401,"message":"Invalid Credentials", \\ "errors":[{"domain":"global","reason":"authError","message":"Invalid Credentials"}], \\ "status":"UNAUTHENTICATED"}} ; const profile_body = \\{"emailAddress":"jeff@ocjtech.us","messagesTotal":1234, \\ "threadsTotal":567,"historyId":"8800112233"} ; const labels_body = \\{"labels":[ \\ {"id":"INBOX","name":"INBOX","type":"system"}, \\ {"id":"SENT","name":"SENT","type":"system"}, \\ {"id":"CATEGORY_PROMOTIONS","name":"CATEGORY_PROMOTIONS","type":"system"}, \\ {"id":"Label_17","name":"zig/mailing list","type":"user"}]} ; const messages_page_1 = \\{"messages":[{"id":"m1","threadId":"t1"},{"id":"m2","threadId":"t1"}], \\ "nextPageToken":"page-2","resultSizeEstimate":5} ; const messages_page_2_empty = \\{"nextPageToken":"page-3","resultSizeEstimate":5} ; const messages_page_3_last = \\{"messages":[{"id":"m3","threadId":"t3"}],"resultSizeEstimate":5} ; const message_body = \\{"id":"m1","threadId":"t1","labelIds":["INBOX","UNREAD"], \\ "snippet":"hello","historyId":"8800112200","internalDate":"1700000000000", \\ "sizeEstimate":2048,"raw":"U3ViamVjdDogaGkKCmJvZHkK"} ; const history_body = \\{"history":[{"id":"8800112234", \\ "messagesAdded":[{"message":{"id":"m7","threadId":"t7"}}]}], \\ "historyId":"8800112240"} ; const history_gone_body = \\{"error":{"code":404,"message":"Requested entity was not found.", \\ "errors":[{"domain":"global","reason":"notFound"}],"status":"NOT_FOUND"}} ; const rate_limit_body = \\{"error":{"code":429,"message":"User-rate limit exceeded.", \\ "errors":[{"domain":"usageLimits","reason":"userRateLimitExceeded"}], \\ "status":"RESOURCE_EXHAUSTED"}} ; const forbidden_body = \\{"error":{"code":403,"message":"Request had insufficient authentication scopes.", \\ "errors":[{"domain":"global","reason":"insufficientPermissions"}], \\ "status":"PERMISSION_DENIED"}} ; /// Everything a test needs: an `Io` that can run two things at once, a fake /// Gmail on a socket, a token set, and a client wired to both. const Harness = struct { threaded: std.Io.Threaded, io: std.Io, fake: FakeGmail, group: std.Io.Group, tokens: oidc.TokenSet, diagnostics: gmail.Client.Diagnostics, url_buf: [128]u8, token_url_buf: [160]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 FakeGmail.listen(h.io, testing.allocator); h.fake.requests_to_serve = requests; h.group = .init; h.diagnostics = .{}; 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, FakeGmail.run, .{&h.fake}); } fn deinit(h: *Harness) void { h.group.cancel(h.io); h.diagnostics.deinit(testing.allocator); h.tokens.deinit(); h.fake.deinit(); h.threaded.deinit(); } fn client(h: *Harness) !gmail.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 .{ .oauth = .{ .provider = .{ .issuer = "https://accounts.google.com", .authorization_endpoint = "https://accounts.google.com/o/oauth2/v2/auth", .token_endpoint = token_endpoint, }, .client_id = "test-client", .client_secret = "test-secret", .redirect_uri = "http://127.0.0.1:1/callback", .scopes = &.{gmail.scopes.readonly}, }, .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), }, }; } }; test "the profile, and the token that fetched it" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); var c = try h.client(); var profile = try c.getProfile(h.io, testing.allocator, &h.diagnostics); defer profile.deinit(); try testing.expectEqualStrings("jeff@ocjtech.us", profile.value.email_address); try testing.expectEqual(@as(?u64, 8800112233), profile.value.history_id); try testing.expectEqual(@as(?u32, 1234), profile.value.messages_total); // The path is built from `user_id`, and the token went on the request // rather than into the query string. try testing.expectEqualStrings("/gmail/v1/users/me/profile", 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 mailbox that is not `me`" { 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 profile = try c.getProfile(h.io, testing.allocator, &h.diagnostics); defer profile.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( "/gmail/v1/users/someone%2Belse%40example.com/profile", h.fake.pathOf(0), ); } test "labels become a map of conventional names" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); var c = try h.client(); var map = try c.labelMap(h.io, testing.allocator, &h.diagnostics); defer map.deinit(); try testing.expectEqual(@as(usize, 4), map.count()); try testing.expectEqualStrings("inbox", map.get("INBOX").?); try testing.expectEqualStrings("sent", map.get("SENT").?); try testing.expectEqualStrings("category/promotions", map.get("CATEGORY_PROMOTIONS").?); // A user label keeps the name its owner gave it. try testing.expectEqualStrings("zig/mailing list", map.get("Label_17").?); try testing.expectEqual(@as(?[]const u8, null), map.get("Label_nonexistent")); } test "the message iterator walks every page, empty ones included" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit(); // Page 2 has a token and no messages, which Gmail really does return when // a query filters out everything on a page. Stopping there would silently // truncate the walk. try h.fake.script(.ok, messages_page_1); try h.fake.script(.ok, messages_page_2_empty); try h.fake.script(.ok, messages_page_3_last); var c = try h.client(); var it = c.messageIterator(.{ .q = "-in:chat", .include_spam_trash = true, .max_results = 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, testing.allocator, &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_page_token); // The options went out as query parameters, and the page token threaded // through without the caller touching it. const first = h.fake.queryOf(0); try testing.expect(std.mem.indexOf(u8, first, "maxResults=2") != null); try testing.expect(std.mem.indexOf(u8, first, "includeSpamTrash=true") != null); try testing.expect(std.mem.indexOf(u8, first, "q=-in%3Achat") != null); try testing.expect(std.mem.indexOf(u8, first, "pageToken") == null); try testing.expect(std.mem.indexOf(u8, h.fake.queryOf(1), "pageToken=page-2") != null); try testing.expect(std.mem.indexOf(u8, h.fake.queryOf(2), "pageToken=page-3") != null); } test "an interrupted walk resumes from a stored page token" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); try h.fake.script(.ok, messages_page_3_last); var c = try h.client(); // What an application stored last time. The library keeps no state file // of its own, which is the point of exposing the token. var it = c.messageIterator(.{ .page_token = "page-3" }); defer it.deinit(); const first = (try it.next(h.io, testing.allocator, &h.diagnostics)).?; try testing.expectEqualStrings("m3", first.id); try testing.expectEqual( @as(?gmail.Message, null), try it.next(h.io, testing.allocator, &h.diagnostics), ); try testing.expect(std.mem.indexOf(u8, h.fake.queryOf(0), "pageToken=page-3") != null); } test "a raw message comes back decoded" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); var c = try h.client(); var message = try c.getMessage( h.io, testing.allocator, "m1", .{ .format = .raw }, &h.diagnostics, ); defer message.deinit(); try testing.expectEqualStrings("m1", message.value.id); try testing.expectEqualStrings("Subject: hi\n\nbody\n", message.value.raw.?); try testing.expect(message.value.hasLabel("UNREAD")); try testing.expectEqual(@as(?i64, 1700000000000), message.value.internal_date); try testing.expectEqualStrings("/gmail/v1/users/me/messages/m1", h.fake.pathOf(0)); try testing.expectEqualStrings("format=raw", h.fake.queryOf(0)); } 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(); // Gmail's ids are opaque. Unencoded, this would address // `/messages/../../profile?x=` -- a different endpoint entirely. var message = try c.getMessage( h.io, testing.allocator, "../../profile?x=", .{ .format = .minimal }, &h.diagnostics, ); defer message.deinit(); try testing.expectEqualStrings( "/gmail/v1/users/me/messages/..%2F..%2Fprofile%3Fx%3D", h.fake.pathOf(0), ); } test "metadata headers are named on the request" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); var c = try h.client(); var message = try c.getMessage(h.io, testing.allocator, "m1", .{ .format = .metadata, .metadata_headers = &.{ "Subject", "From" }, }, &h.diagnostics); defer message.deinit(); const query = h.fake.queryOf(0); try testing.expect(std.mem.indexOf(u8, query, "format=metadata") != null); try testing.expect(std.mem.indexOf(u8, query, "metadataHeaders=Subject") != null); try testing.expect(std.mem.indexOf(u8, query, "metadataHeaders=From") != null); } test "history, and the id to resume from" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); var c = try h.client(); var it = c.historyIterator(.{ .start_history_id = 8800112233, .history_types = &.{ .messageAdded, .labelAdded }, }); defer it.deinit(); const record = (try it.next(h.io, testing.allocator, &h.diagnostics)).?; try testing.expectEqual(@as(u64, 8800112234), record.id); try testing.expectEqual(@as(usize, 1), record.messages_added.len); try testing.expectEqualStrings("m7", record.messages_added[0].id); try testing.expectEqual( @as(?gmail.History, null), try it.next(h.io, testing.allocator, &h.diagnostics), ); // The mailbox's id as of the last page, not the largest record id: the // difference is anything that happened during the walk. try testing.expectEqual(@as(?u64, 8800112240), it.history_id); const query = h.fake.queryOf(0); try testing.expect(std.mem.indexOf(u8, query, "startHistoryId=8800112233") != null); try testing.expect(std.mem.indexOf(u8, query, "historyTypes=messageAdded") != null); try testing.expect(std.mem.indexOf(u8, query, "historyTypes=labelAdded") != null); } test "a history id that has aged out is its own error" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); try h.fake.script(.not_found, history_gone_body); var c = try h.client(); // Not `error.ApiError`: this one means the incremental path is gone and // the mailbox has to be listed in full, which is a different decision // from any other failure. try testing.expectError(error.HistoryTooOld, c.listHistory( h.io, testing.allocator, .{ .start_history_id = 1 }, &h.diagnostics, )); } 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 profile = try c.getProfile(h.io, testing.allocator, &h.diagnostics); defer profile.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("/gmail/v1/users/me/profile", h.fake.pathOf(1)); try testing.expectEqualStrings("Bearer at-fresh", h.fake.requests.items[1].authorization.?); // The merge kept the refresh token the response left out. try testing.expectEqualStrings("rt-good", 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; @memcpy(self.last[0..tokens.access_token.len], tokens.access_token); self.last_len = tokens.access_token.len; } }; var recorder: Recorder = .{}; var c = try h.client(); c.on_refresh = .{ .context = &recorder, .func = Recorder.onRefresh }; var profile = try c.getProfile(h.io, testing.allocator, &h.diagnostics); defer profile.deinit(); try testing.expectEqual(@as(usize, 1), recorder.calls); try testing.expectEqualStrings("at-fresh", 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.getProfile(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 a revoked grant or a skewed clock looks like. try h.fake.script(.unauthorized, unauthorized_body); var c = try h.client(); var profile = try c.getProfile(h.io, testing.allocator, &h.diagnostics); defer profile.deinit(); try testing.expectEqualStrings("jeff@ocjtech.us", profile.value.email_address); 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.getProfile(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 "a quota failure is waited out" { var h: Harness = undefined; try h.init(3, 3600); defer h.deinit(); try h.fake.script(.too_many_requests, rate_limit_body); try h.fake.script(.too_many_requests, rate_limit_body); var c = try h.client(); var profile = try c.getProfile(h.io, testing.allocator, &h.diagnostics); defer profile.deinit(); try testing.expectEqualStrings("jeff@ocjtech.us", profile.value.email_address); try testing.expectEqual(@as(u32, 3), h.diagnostics.http.attempts); } test "a quota failure 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, rate_limit_body); var c = try h.client(); try testing.expectError( error.TooManyRetries, c.getProfile(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.getProfile(h.io, testing.allocator, &h.diagnostics), ); // Once. A 403 that is about scopes does not improve with waiting, and // retrying it would spend the retry budget on a certainty. try testing.expectEqual(@as(usize, 1), h.fake.requests.items.len); const api = h.diagnostics.apiError().?; try testing.expectEqualStrings("insufficientPermissions", api.reason().?); 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(), "insufficientPermissions") != 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. 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.getProfile(h.io, testing.allocator, &h.diagnostics), ); } test "a batch is one request that answers every call" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); var c = try h.client(); var got = try c.batchGetMessages( h.io, testing.allocator, &.{ "m1", "m2", "m3" }, .{ .format = .raw }, &h.diagnostics, ); defer got.deinit(); try testing.expectEqual(@as(usize, 3), got.items.len); try testing.expectEqual(@as(usize, 3), got.okCount()); for (got.items, [_][]const u8{ "m1", "m2", "m3" }) |item, id| { try testing.expectEqualStrings(id, item.id); try testing.expectEqual(std.http.Status.ok, item.status.?); try testing.expectEqualStrings("Subject: hi\n\nbody\n", item.value.?.raw.?); } // One request, three calls. That is the whole point. try testing.expectEqual(@as(usize, 1), h.fake.requests.items.len); try testing.expectEqualStrings("/batch/gmail/v1", h.fake.pathOf(0)); try testing.expectEqualStrings("Bearer at-good", h.fake.requests.items[0].authorization.?); try testing.expect(std.mem.startsWith( u8, h.fake.requests.items[0].content_type.?, "multipart/mixed; boundary=batch_zig_gmail_", )); // And each call inside it addressed exactly what the single-message fetch // would have addressed. try testing.expectEqual(@as(usize, 3), h.fake.batch_targets.items.len); try testing.expectEqualStrings( "GET /gmail/v1/users/me/messages/m1?format=raw HTTP/1.1", h.fake.batch_targets.items[0], ); try testing.expectEqualStrings( "GET /gmail/v1/users/me/messages/m3?format=raw HTTP/1.1", h.fake.batch_targets.items[2], ); } test "a reply is paired with its call by number, not by arrival" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); // Google says the calls may be executed in any order, so this server // answers them backwards. h.fake.batch_reversed = true; try h.fake.scriptPart(.ok, "{\"id\":\"m1\",\"snippet\":\"first\"}"); try h.fake.scriptPart(.ok, "{\"id\":\"m2\",\"snippet\":\"second\"}"); try h.fake.scriptPart(.ok, "{\"id\":\"m3\",\"snippet\":\"third\"}"); var c = try h.client(); var got = try c.batchGetMessages( h.io, testing.allocator, &.{ "m1", "m2", "m3" }, .{}, &h.diagnostics, ); defer got.deinit(); // The items are in the order the calls were made even though the replies // were not. try testing.expectEqualStrings("first", got.items[0].value.?.snippet.?); try testing.expectEqualStrings("second", got.items[1].value.?.snippet.?); try testing.expectEqualStrings("third", got.items[2].value.?.snippet.?); } test "one call failing inside a batch costs one call" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); try h.fake.scriptPart(.ok, message_body); try h.fake.scriptPart(.not_found, history_gone_body); try h.fake.scriptPart(.too_many_requests, rate_limit_body); // A 200 whose body is not what this expected, which is neither a message // nor an error object. try h.fake.scriptPart(.ok, "not json"); var c = try h.client(); var got = try c.batchGetMessages( h.io, testing.allocator, &.{ "m1", "gone", "busy", "odd" }, .{}, &h.diagnostics, ); defer got.deinit(); try testing.expectEqual(@as(usize, 1), got.okCount()); try testing.expect(got.items[0].ok()); // The failure is the call's own, with Google's error object on it, and // the batch itself succeeded. try testing.expect(!got.items[1].ok()); try testing.expectEqual(std.http.Status.not_found, got.items[1].status.?); try testing.expectEqualStrings("notFound", got.items[1].err.?.reason().?); // Quota inside a batch is not retried here: the outer request succeeded, // so there is nothing for the backoff to have retried. The id is what to // ask for again. try testing.expectEqual(std.http.Status.too_many_requests, got.items[2].status.?); try testing.expectEqualStrings("userRateLimitExceeded", got.items[2].err.?.reason().?); try testing.expectEqualStrings("busy", got.items[2].id); try testing.expectEqual(@as(u32, 1), h.diagnostics.http.attempts); // A reply that was neither: the status is all there is to say about it. try testing.expectEqual(std.http.Status.ok, got.items[3].status.?); try testing.expectEqual(@as(?gmail.Message, null), got.items[3].value); try testing.expectEqual(@as(?gmail.ApiError, null), got.items[3].err); var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try got.items[3].format(&w); try testing.expectEqualStrings("odd: HTTP 200 OK (unreadable)", w.buffered()); } test "a batch whose every call is refused is spent on one refresh" { var h: Harness = undefined; // The batch, the refresh, the batch again. try h.init(3, 3600); defer h.deinit(); // The clock says the token is good; the server disagrees. Inside a batch // that arrives as a *successful* response full of 401s, which is the one // thing about this endpoint that could make a sync fetch nothing while // appearing to work. for (0..2) |_| try h.fake.scriptPart(.unauthorized, unauthorized_body); var c = try h.client(); var got = try c.batchGetMessages( h.io, testing.allocator, &.{ "m1", "m2" }, .{}, &h.diagnostics, ); defer got.deinit(); try testing.expectEqual(@as(usize, 2), got.okCount()); try testing.expectEqual(@as(usize, 1), h.fake.refreshes); try testing.expectEqual(@as(usize, 3), h.fake.requests.items.len); try testing.expectEqualStrings("/token", h.fake.pathOf(1)); try testing.expectEqualStrings("Bearer at-fresh", h.fake.requests.items[2].authorization.?); } test "one call refused out of many is not a token problem" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); // A single 401 is a call asking for something this grant does not cover, // and no refresh will help; spending one would cost a round trip and // rotate a refresh token for nothing. try h.fake.scriptPart(.unauthorized, unauthorized_body); try h.fake.scriptPart(.ok, message_body); var c = try h.client(); var got = try c.batchGetMessages(h.io, testing.allocator, &.{ "m1", "m2" }, .{}, &h.diagnostics); defer got.deinit(); try testing.expectEqual(@as(usize, 0), h.fake.refreshes); try testing.expectEqual(@as(usize, 1), h.fake.requests.items.len); try testing.expectEqual(std.http.Status.unauthorized, got.items[0].status.?); try testing.expect(got.items[1].ok()); } test "a batch larger than Gmail accepts is refused before it is sent" { var h: Harness = undefined; try h.init(0, 3600); defer h.deinit(); const ids: [gmail.batch.max_calls + 1][]const u8 = @splat("m1"); var c = try h.client(); try testing.expectError(error.TooManyCalls, c.batchGetMessages( h.io, testing.allocator, &ids, .{}, &h.diagnostics, )); // Refused here rather than by Google, which refuses the whole batch. try testing.expectEqual(@as(usize, 0), h.fake.requests.items.len); } test "a batch of nothing asks for nothing" { var h: Harness = undefined; try h.init(0, 3600); defer h.deinit(); var c = try h.client(); var got = try c.batchGetMessages(h.io, testing.allocator, &.{}, .{}, &h.diagnostics); defer got.deinit(); try testing.expectEqual(@as(usize, 0), got.items.len); try testing.expectEqual(@as(usize, 0), h.fake.requests.items.len); } test "a batch of calls this library has no method for" { var h: Harness = undefined; try h.init(1, 3600); defer h.deinit(); try h.fake.scriptPart(.ok, "{\"id\":\"INBOX\",\"messagesTotal\":12}"); try h.fake.scriptPart(.ok, "{\"id\":\"SENT\",\"messagesTotal\":34}"); var c = try h.client(); var got = try c.batchJson(h.io, testing.allocator, &.{ .{ .target = "/gmail/v1/users/me/labels/INBOX" }, .{ .target = "/gmail/v1/users/me/labels/SENT" }, }, &h.diagnostics); defer got.deinit(); try testing.expectEqual(@as(usize, 2), got.okCount()); try testing.expectEqualStrings("INBOX", got.items[0].value.?.object.get("id").?.string); try testing.expectEqual(@as(i64, 34), got.items[1].value.?.object.get("messagesTotal").?.integer); // The call's target is the only name it has. try testing.expectEqualStrings("/gmail/v1/users/me/labels/SENT", got.items[1].id); } test "a mailbox that is not `me` is encoded in every call of a batch" { 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 got = try c.batchGetMessages(h.io, testing.allocator, &.{"m1"}, .{}, &h.diagnostics); defer got.deinit(); try testing.expectEqualStrings( "GET /gmail/v1/users/someone%2Belse%40example.com/messages/m1?format=full HTTP/1.1", h.fake.batch_targets.items[0], ); }