Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Building OData query strings, and checking the URLs that come back.//!//! ## Why not `oidc.QueryBuilder`//!//! Because it percent-encodes the key as well as the value, and an OData system//! query option's name begins with a `$`. `%24select=...` is *accepted* by//! Graph, but it makes every request in a log unreadable and it relies on//! behaviour nothing documents. The keys here are library constants rather than//! caller input -- `$select`, `$top`, `$filter` -- so they are written through//! unchanged and checked to be what they claim, and only the values are//! encoded.//!//! ## Why `sameOrigin` exists//!//! This is the part worth reading. Graph paginates by handing back a//! **complete, absolute URL** in `@odata.nextLink`, and a delta query ends by//! handing back another one in `@odata.deltaLink`. The obvious implementation//! of "fetch the next page" is to take that URL and send the request -- with//! the access token on it.//!//! That is a redirect that nothing is checking. A response body that says//! `"@odata.nextLink": "https://evil.example.com/collect"` would have this//! library post a bearer token good for somebody's entire mailbox to whoever//! asked for it. It takes a compromised proxy, or a `base_url` pointed at//! something untrustworthy, or simply a bug at the far end -- but the cost of//! refusing is one string comparison, and the cost of not refusing is the//! mailbox.//!//! So every link is checked against the base URL it was fetched from before it//! is followed, and `Client` turns a mismatch into `error.UntrustedLink`. The//! same check applies to a `@odata.deltaLink` that was stored in a file between//! runs, where the file is a second place the URL could have been changed.
const std = @import("std");
const QueryBuilder = @import("oidc").QueryBuilder;
/// One OData query string, built up option by option.pub const Query = struct { buffer: std.Io.Writer.Allocating,
pub fn init(gpa: std.mem.Allocator) Query { return .{ .buffer = .init(gpa) }; }
pub fn deinit(q: *Query) void { q.buffer.deinit(); }
/// Appends `key=value`, with the value percent-encoded and the key written /// as it stands. /// /// The key is asserted to be a safe token rather than encoded, because /// every one of them is a literal in this library and a key that is not is /// a programming error rather than something to escape around. pub fn add(q: *Query, key: []const u8, value: []const u8) std.mem.Allocator.Error!void { std.debug.assert(isSafeKey(key)); return q.addInner(key, value) catch error.OutOfMemory; }
fn addInner(q: *Query, key: []const u8, value: []const u8) std.Io.Writer.Error!void { const w = &q.buffer.writer; if (q.buffer.written().len > 0) try w.writeByte('&'); try w.writeAll(key); try w.writeByte('='); try QueryBuilder.encode(w, value); }
/// `add`, but an absent value is left out rather than sent empty. Most of /// an OData request is optional. pub fn addOptional( q: *Query, key: []const u8, value: ?[]const u8, ) std.mem.Allocator.Error!void { if (value) |v| if (v.len > 0) try q.add(key, v); }
/// Appends `key=` and the comma-joined `values`, which is how OData writes /// a list inside one option: `$select=id,subject,from`. pub fn addCommaSeparated( q: *Query, key: []const u8, values: []const []const u8, ) std.mem.Allocator.Error!void { if (values.len == 0) return; std.debug.assert(isSafeKey(key)); return q.addCommaSeparatedInner(key, values) catch error.OutOfMemory; }
fn addCommaSeparatedInner( q: *Query, key: []const u8, values: []const []const u8, ) std.Io.Writer.Error!void { const w = &q.buffer.writer; if (q.buffer.written().len > 0) try w.writeByte('&'); try w.writeAll(key); try w.writeByte('='); for (values, 0..) |value, i| { // The separator is written literally and the values encoded // around it, so that a comma *inside* a value cannot add a member // to the list. if (i > 0) try w.writeByte(','); try QueryBuilder.encode(w, value); } }
/// `add` with a formatted value, for the numbers: `$top`, `$skip`. pub fn print( q: *Query, key: []const u8, comptime fmt: []const u8, args: anytype, ) std.mem.Allocator.Error!void { var buf: [64]u8 = undefined; const value = std.fmt.bufPrint(&buf, fmt, args) catch return error.OutOfMemory; return q.add(key, value); }
/// What has been built so far. Owned by the query; valid until the next /// `add` or `deinit`. pub fn written(q: *Query) []const u8 { return q.buffer.written(); }};
/// Whether a key may be written into a query string unencoded: the OData/// system options and anything else made of ordinary token characters.pub fn isSafeKey(key: []const u8) bool { if (key.len == 0) return false; for (key) |c| { switch (c) { 'a'...'z', 'A'...'Z', '0'...'9', '$', '-', '_', '.' => {}, else => return false, } } return true;}
pub const OriginError = error{ /// The link is not a URL, or is one with no host. InvalidLink, /// The link points somewhere other than the base URL it came from. UntrustedLink,};
/// Refuses a link that does not belong to the same service as `base_url`.////// Scheme, host and port must all match; the path may be anything, since that/// is what a continuation URL is for. The host comparison is/// case-insensitive, because DNS names are, and the port comparison uses the/// scheme's default when one is not written out -- so `https://graph.microsoft.com`/// and `https://graph.microsoft.com:443` are the same origin, which they are.////// See the note at the top of this file for what this is actually protecting.pub fn sameOrigin(base_url: []const u8, link: []const u8) OriginError!void { const base = std.Uri.parse(base_url) catch return error.InvalidLink; const target = std.Uri.parse(link) catch return error.InvalidLink;
if (!std.ascii.eqlIgnoreCase(base.scheme, target.scheme)) return error.UntrustedLink;
var base_buf: [std.Io.net.HostName.max_len]u8 = undefined; var target_buf: [std.Io.net.HostName.max_len]u8 = undefined; const base_host = std.Io.net.HostName.fromUri(base, &base_buf) catch return error.InvalidLink; const target_host = std.Io.net.HostName.fromUri(target, &target_buf) catch return error.InvalidLink; if (!std.ascii.eqlIgnoreCase(base_host.bytes, target_host.bytes)) return error.UntrustedLink;
if (defaultPort(base.scheme, base.port) != defaultPort(target.scheme, target.port)) { return error.UntrustedLink; }}
fn defaultPort(scheme: []const u8, port: ?u16) u16 { if (port) |p| return p; if (std.ascii.eqlIgnoreCase(scheme, "https")) return 443; if (std.ascii.eqlIgnoreCase(scheme, "http")) return 80; return 0;}
const testing = std.testing;
test "the option names stay readable" { var q: Query = .init(testing.allocator); defer q.deinit();
try q.add("$select", "id,subject"); try q.print("$top", "{d}", .{50});
// The `$` is not `%24`, which is what makes a request log readable; the // comma is encoded, which is what keeps a value from adding list members. try testing.expectEqualStrings("$select=id%2Csubject&$top=50", q.written());}
test "a filter value is encoded whole" { var q: Query = .init(testing.allocator); defer q.deinit();
try q.add("$filter", "receivedDateTime ge 2024-01-01T00:00:00Z"); try testing.expectEqualStrings( "$filter=receivedDateTime%20ge%202024-01-01T00%3A00%3A00Z", q.written(), );}
test "a comma inside a value cannot add a member to the list" { var q: Query = .init(testing.allocator); defer q.deinit();
// A caller passing this as one field name gets one encoded field name, // not two fields. try q.addCommaSeparated("$select", &.{ "id", "subject,internetMessageHeaders" }); try testing.expectEqualStrings( "$select=id,subject%2CinternetMessageHeaders", q.written(), );}
test "an empty list writes nothing at all" { var q: Query = .init(testing.allocator); defer q.deinit();
try q.addCommaSeparated("$select", &.{}); try q.addOptional("$filter", null); try q.addOptional("$search", ""); try testing.expectEqualStrings("", q.written());
// And the first real option still gets no leading `&`. try q.add("$top", "10"); try testing.expectEqualStrings("$top=10", q.written());}
test "a value that tries to be another parameter is encoded" { var q: Query = .init(testing.allocator); defer q.deinit();
try q.add("$search", "\"subject:hi\"&$top=999999"); try testing.expect(std.mem.indexOf(u8, q.written(), "&$top") == null); try testing.expect(std.mem.indexOf(u8, q.written(), "%26") != null);}
test "what may be written as a key unencoded" { try testing.expect(isSafeKey("$select")); try testing.expect(isSafeKey("$skiptoken")); try testing.expect(isSafeKey("changeType")); try testing.expect(isSafeKey("includeHiddenFolders")); try testing.expect(!isSafeKey("")); try testing.expect(!isSafeKey("a b")); try testing.expect(!isSafeKey("a&b=c")); try testing.expect(!isSafeKey("a=b"));}
test "a continuation link is followed only back to the same service" { const base = "https://graph.microsoft.com";
// What Graph really sends. try sameOrigin(base, "https://graph.microsoft.com/v1.0/me/messages?$skiptoken=abc"); // The default port written out is the same origin. try sameOrigin(base, "https://graph.microsoft.com:443/v1.0/me/messages"); try sameOrigin("https://graph.microsoft.com:443", "https://graph.microsoft.com/v1.0/me"); // DNS is case-insensitive. try sameOrigin(base, "https://GRAPH.microsoft.COM/v1.0/me/messages");}
test "a continuation link that points elsewhere is refused" { const base = "https://graph.microsoft.com";
for ([_][]const u8{ // The whole reason this check exists: a bearer token good for a // mailbox, sent wherever the response body asked for. "https://evil.example.com/collect", "https://graph.microsoft.com.evil.example.com/v1.0/me/messages", "https://evil.example.com/graph.microsoft.com/v1.0/me/messages", // Downgraded to plaintext, which would put the token on the wire. "http://graph.microsoft.com/v1.0/me/messages", // A different port is a different service. "https://graph.microsoft.com:8443/v1.0/me/messages", // Userinfo that makes the real host look like a path. "https://graph.microsoft.com@evil.example.com/v1.0/me", }) |link| { try testing.expectError(error.UntrustedLink, sameOrigin(base, link)); }}
test "something that is not a link at all" { const base = "https://graph.microsoft.com"; for ([_][]const u8{ "", "not a url", "/v1.0/me/messages", "https://", }) |link| { try testing.expectError(error.InvalidLink, sameOrigin(base, link)); }}
test "a loopback base URL, which is what the tests run against" { // The end-to-end tests point `base_url` at a socket, and the check has to // let that through or nothing could be tested. try sameOrigin("http://127.0.0.1:41234", "http://127.0.0.1:41234/v1.0/me/messages?$top=2"); try testing.expectError( error.UntrustedLink, sameOrigin("http://127.0.0.1:41234", "http://127.0.0.1:41235/v1.0/me/messages"), );}