A Microsoft 365 mail client library for Zig, over Microsoft Graph
README.md

zig-o365 #

A Microsoft 365 mail client for Zig, over Microsoft Graph: folders, messages, the RFC 5322 bytes behind them, and the delta queries that turn a second run into an update rather than another full download.

It was pulled out of allthemail, where the Office 365 half had been left as a stub — a credentials file, a message listing, and a great deal that was commented out. What is here is that idea finished against the current Graph API, and shaped after its sibling zig-gmail, which was extracted from the same project.

The OAuth 2.0 half is zig-oidc, which this takes a Client and a TokenSet from and does no signing in of its own.

The API documentation is generated from the doc comments — which is where most of the explanation lives — and published at https://jeff.jcollie.page/zig-o365/.

What it does #

  • Folders, including the whole tree: folderTree walks from the root and works out the path of every folder, which is what turns a message's parentFolderId into something a person would recognise.
  • Messages, listed with $select, $filter, $orderby and $search, and paginated by following @odata.nextLink to the end.
  • The message itself — getMime fetches /$value, which is the RFC 5322 bytes exactly as they arrived. That is what belongs in a maildir; Graph's own body is Outlook's rendering of the message rather than the message.
  • Delta queries: the changes to a folder since a stored token, ending with a new token to store. Deletions arrive as tombstones.
  • Attachments, listed without their bytes by default and fetched one at a time when wanted.
  • $batch, up to twenty requests per round trip, with the entries a batch reports as throttled retried — which nothing else in the stack can do.
  • Token bookkeeping: refresh before a call when the access token is due, once more if a call comes back 401 anyway, and a hook so the rotated refresh token is written down at the moment it is issued.
  • Throttling, waited out for as long as Retry-After asks and no longer.

What it does not #

  • No OAuth. zig-oidc does that. The two were one library until the OAuth half was pulled out, and keeping them apart is what lets each be tested against something that is not Microsoft.
  • No writing. No sending, no moving, no deleting, no drafts, no folder creation, no mailbox settings, no rules, no subscriptions. Every request this makes is a GET, so a token scoped to Mail.Read is all it can use — which is the point.
  • No calendar and no contacts, though both are the same API shape.
  • No signature verification of ID tokens, because nothing here reads one. See src/tenant.zig for the issuer caveat that matters if you decide to.

Four things that are not like Gmail #

If you have used zig-gmail, these are the differences that are real rather than spelling:

A message is in one folder, not carrying a set of labels — and moving it between folders changes its id. A message moved out of the inbox appears in one folder's delta as an addition and in the other's as a removal, with nothing to connect the two. internetMessageId is what survives, and is what a local store should key on.

Change tracking is per folder. There is no mailbox-wide history feed, so a synchronised mailbox is one delta walk and one stored token for every folder.

Pagination is by URL. A page carries the complete URL of the next one, which this library checks against base_url before following. That check is not decoration: a response body saying "@odata.nextLink": "https://evil.example.com/collect" would otherwise have a bearer token good for the whole mailbox posted to whoever wrote it. src/odata.zig says more, and tests/fuzz.zig states it as a property.

Throttling carries Retry-After, and Microsoft's guidance is that obeying it is the fastest way out — usage keeps being logged against a client that comes back early, so an impatient one stays throttled longer. This honours it, up to a ceiling, because the header is a number chosen by the far end.

Using it #

It needs Zig 0.17.0, which the development shell and the Nix package take from nixpkgs.

$ zig fetch --save git+https://git.jcollie.dev/jeff/zig-o365.git

For Zig 0.16.0, use the zig-0.16 branch, or the v0.1.0 tag it was made from:

$ zig fetch --save git+https://git.jcollie.dev/jeff/zig-o365.git#zig-0.16
const o365_dep = b.dependency("o365", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("o365", o365_dep.module("o365"));

Signing in, which is zig-oidc's half:

const o365 = @import("o365");
const oidc = @import("oidc");

var tenant = try o365.tenant.init(gpa, "common", .{});
defer tenant.deinit();

var listener = try oidc.loopback.Listener.listen(io, .{});
defer listener.deinit(io);
const redirect_uri = try listener.redirectUri(gpa);
defer gpa.free(redirect_uri);

const oauth: oidc.Client = .{
    .provider = tenant.provider,
    .client_id = client_id,
    .redirect_uri = redirect_uri,
    // `offline_access` is in here. Without it no refresh token comes back
    // and the grant dies in about an hour -- it is the Microsoft equivalent
    // of Google's `access_type=offline`, and it is not implied.
    .scopes = o365.scopes.mirror,
};

Then walking a mailbox:

var client: o365.Client = .{
    // The long-lived allocator: the token set a refresh produces replaces the
    // one behind `tokens`, and outlives any one call. The `gpa` each call
    // takes below is a different thing -- it is for what that call returns,
    // and an arena is fine there.
    .gpa = gpa,
    .oauth = oauth,
    .tokens = &tokens,
    // Microsoft rotates the refresh token on nearly every refresh, so a
    // program that keeps only what it signed in with works exactly once.
    .on_refresh = store.refreshHook(),
};

var d: o365.Client.Diagnostics = .init(client.gpa);
defer d.deinit();

var it = try client.messageIterator(gpa, .{
    .folder = "inbox",
    // Naming the properties wanted is the single largest thing a caller can
    // do about how long a walk takes. Left off, Graph sends every property of
    // every message, `body` included.
    .select = o365.Client.walk_select,
});
defer it.deinit();

while (try it.next(io, &d)) |stub| {
    const mime = try client.getMime(io, gpa, stub.id, &d);
    defer gpa.free(mime);
    // `mime` is the whole message, exactly as it arrived.
}

And catching up next time, per folder:

var it = try client.messageDelta(gpa, .{
    .folder = folder_id,
    .delta_link = stored_token, // null on the first run
    .select = o365.Client.walk_select,
});
defer it.deinit();

while (try it.next(io, &d)) |message| {
    if (message.isRemoved()) {
        // A tombstone: an id, and nothing else.
    }
}
// Store this. It is borrowed from the iterator, so copy it before `deinit`.
const next_token = it.delta_link.?;

error.ResyncRequired is the one to handle: Graph answers a stale delta token with 410, which means the incremental path is gone and the folder has to be walked in full. It is not a failure to retry.

Batching the fetches #

A walk is one listing and then a fetch per message, and the fetches are where the time goes. $batch takes twenty at a time:

var fetched = try client.getMessages(io, gpa, ids, .{
    .select = o365.Client.walk_select,
}, &d);
defer fetched.deinit();

for (fetched.items) |item| {
    const message = item.message orelse continue; // `item.status` says why not
    _ = message;
}

Results come back in the order the ids were given, whatever order the service answered in, and a message deleted between the listing and the fetch is a 404 on that one entry rather than a failure of the call.

A 200 on a batch says nothing about what is in it. Every entry carries its own status, so a batch of twenty 403s is a successful call — Response.ok is the check that matters. And a throttled entry inside a batch is retried by nobody: outside a batch the HTTP layer sees the 429 and waits out the Retry-After, but inside one the 429 is a field in a successful response, so Batch has retry logic of its own. src/Batch.zig says more.

The command line client #

zig build run builds a program that runs against a real mailbox. It is how the library is checked against actual Microsoft 365; everything in tests/ talks to a Graph written a few hundred lines away.

$ zig build run -- login --client-id <application id> --tenant common \
    --store ~/.cache/zig-o365/tokens.json
$ zig build run -- whoami   --client-id ... --store ...
$ zig build run -- folders  --client-id ... --store ...
$ zig build run -- messages --folder inbox --limit 20 --client-id ... --store ...
$ zig build run -- mime <message id> --client-id ... --store ... > message.eml
$ zig build run -- delta --folder inbox --client-id ... --store ...

Register the application as a public client with a redirect URI of http://localhost and no secret: a desktop program cannot keep one, and PKCE is what protects the flow instead. --client-secret is there for a confidential client.

The store is a plain JSON file holding a refresh token. It is written 0600 and belongs somewhere that stays that way.

Building and testing #

Everything comes out of the Nix flake:

$ nix develop
$ zig build test --summary all   # 185 tests
$ zig build                      # the command line client
$ zig build docs-serve           # the API documentation, at :8000

The tests are in three layers. The unit tests beside each source file check what goes onto the wire and what comes back off it, and never open a socket. tests/e2e.zig stands up a Graph on a loopback socket and runs the whole client against it — that is where a mistake in the shape of a request shows up: a page size sent as $top instead of as a Prefer header, a Prefer value that should have been quoted, a refresh that happens after the call instead of before it. tests/fuzz.zig states the properties that must hold for input nobody wrote, two of which are security properties rather than robustness ones: no string may be accepted as a continuation link unless it really is the same origin, and no configured tenant id may produce a token endpoint on another host.

$ zig build fuzz --fuzz                   # Zig's fuzzer, until interrupted
$ zig build fuzz --fuzz=1M                # a bounded run, then a report
$ zig build fuzz -Dfuzz-filter=origin --fuzz

Zig's fuzzer steers by coverage, which it only gets when LLVM compiles the test binary, so build.zig sets use_llvm on it. Its report has one entry for the whole binary, named after the first fuzz test in it; the others did run. A second driver, tools/fuzz.zig, mutates the seeds beside each target without coverage feedback, but runs a fixed number of inputs from a seed and is what CI uses:

$ zig build fuzz-run                      # a minute per target
$ zig build fuzz-run -- --seconds 600 --target message
$ zig build fuzz-run -- --iterations 100000 --seed 12345

That second driver found a real bug while this was being written — an error body carrying a throttling code but arriving with a 401 was classified as both "wait and try again" and "the token is the problem", so a client would have spent its retry budget instead of refreshing the one thing that would have worked.

Dependencies #

There is one, zig-oidc, and it is fetched by the Zig package manager. A Nix build has no network, so build.zig.zon.nix is generated from the manifest by zon2nix and committed; regenerate it whenever the manifest changes:

$ nix develop -c zon2nix --17 --nix=build.zig.zon.nix build.zig.zon

Where this lives #

$ git clone https://git.jcollie.dev/jeff/zig-o365.git

It is mirrored on Tangled at https://tangled.org/jcollie.dev/zig-o365, and it is also on the Radicle network, where the repository's identifier is

rad:z3GYUKZSsFLrBgh1TTMnjfLhs9Mtv

and rad clone rad:z3GYUKZSsFLrBgh1TTMnjfLhs9Mtv fetches it from any node that seeds it. Any of the three is the whole project.

License #

MIT. The project follows the REUSE specification; reuse lint passes.