Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A refresh token on disk, in a file only its owner can read.//!//! This is the smallest thing that makes a command line program work twice://! sign in once, and every run afterwards starts from the file. It is//! deliberately a plain JSON file rather than anything cleverer, and just as//! deliberately written 0600 and replaced atomically -- a refresh token is a//! standing permission to read somebody's mail, and a half-written one is a//! grant that has to be re-authorised by hand.//!//! What goes in it is `oidc.TokenSet`'s stored form, which differs from the//! wire form in one way that matters here: the expiry is absolute rather than//! `expires_in` seconds from a moment that has passed.//!//! ```zig//! var store: o365.TokenStore = .{ .dir = dir, .path = "o365.json" };//! var tokens = try store.load(io, gpa);//! defer tokens.deinit();//!//! var client: o365.Client = .{//! .gpa = gpa,//! .oauth = oauth,//! .tokens = &tokens,//! // Written back after every refresh. Microsoft rotates the refresh//! // token on nearly every one of them, so a program that keeps only what//! // it signed in with stops working the first time it refreshes.//! .on_refresh = store.refreshHook(),//! };//! ```
const TokenStore = @This();
const std = @import("std");const oidc = @import("oidc");
const log = std.log.scoped(.o365);
/// The directory the file lives in. Opening it is the caller's business,/// because where an application keeps its state is the application's/// business: `$XDG_CACHE_HOME`, `$XDG_STATE_HOME`, or somewhere it was told.dir: std.Io.Dir,/// The file name within `dir`.path: []const u8,/// Held so that `refreshHook` has an `Io` to write through. A hook is called/// from inside an API call and cannot be handed one at the call site.io: std.Io,
/// How much of a token file will be read. A token set is a few kilobytes at/// the very most; an ID token is the largest part of it.pub const max_bytes = 64 * 1024;
pub const LoadError = error{ /// No such file. The first run, or the file was deleted; either way the /// answer is to sign in. NoStoredTokens, /// The file is there and is not a token set. Malformed,} || std.mem.Allocator.Error || std.Io.Cancelable;
/// Reads the stored token set.pub fn load(s: *const TokenStore, gpa: std.mem.Allocator) LoadError!oidc.TokenSet { // Capped by the read rather than after it: `--store /dev/zero` is a // plausible typo, and a check on the length of what was already read // would come too late to help. const contents = s.dir.readFileAlloc(s.io, s.path, gpa, .limited(max_bytes)) catch |err| switch (err) { error.FileNotFound => return error.NoStoredTokens, error.OutOfMemory => return error.OutOfMemory, error.Canceled => return error.Canceled, error.StreamTooLong => return error.Malformed, else => { log.debug("could not read {s}: {t}", .{ s.path, err }); return error.NoStoredTokens; }, }; defer gpa.free(contents);
return oidc.TokenSet.parseStored(gpa, contents) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.Malformed, };}
pub const SaveError = error{SaveFailed} || std.mem.Allocator.Error || std.Io.Cancelable;
/// Writes the token set, replacing whatever was there.////// Atomically, and 0600: the replacement is a rename over the old file, so a/// crash midway leaves the previous token set intact rather than a truncated/// one.pub fn save(s: *const TokenStore, tokens: *const oidc.TokenSet) SaveError!void { var atomic = s.dir.createFileAtomic(s.io, s.path, .{ .make_path = true, .permissions = .fromMode(0o600), .replace = true, }) catch |err| switch (err) { error.Canceled => return error.Canceled, else => { log.warn("could not create {s}: {t}", .{ s.path, err }); return error.SaveFailed; }, }; defer atomic.deinit(s.io);
var buffer: [4096]u8 = undefined; var file_writer = atomic.file.writer(s.io, &buffer); const w = &file_writer.interface;
var fmt = std.json.fmt(tokens, .{ .whitespace = .indent_2 }); fmt.format(w) catch return error.SaveFailed; w.writeByte('\n') catch return error.SaveFailed; w.flush() catch return error.SaveFailed;
atomic.replace(s.io) catch |err| switch (err) { error.Canceled => return error.Canceled, else => { log.warn("could not replace {s}: {t}", .{ s.path, err }); return error.SaveFailed; }, };}
/// Deletes the stored tokens. Signing out locally; it does not revoke the/// grant, which is `oidc.Client.revoke`.pub fn clear(s: *const TokenStore) std.Io.Cancelable!void { s.dir.deleteFile(s.io, s.path) catch |err| switch (err) { error.Canceled => return error.Canceled, else => {}, };}
const Client = @import("Client.zig");
/// The hook to hand `Client.on_refresh`, so that a rotated refresh token is/// written down at the moment it is issued rather than at the end of a run/// that may not reach its end.pub fn refreshHook(s: *TokenStore) Client.RefreshHook { return .{ .context = s, .func = onRefresh };}
fn onRefresh(context: ?*anyopaque, tokens: *const oidc.TokenSet) anyerror!void { const s: *TokenStore = @ptrCast(@alignCast(context.?)); return s.save(tokens);}
const testing = std.testing;
test "a round trip through a real file" { const io = testing.io;
var tmp = testing.tmpDir(.{}); defer tmp.cleanup();
var store: TokenStore = .{ .dir = tmp.dir, .path = "tokens.json", .io = io };
try testing.expectError(error.NoStoredTokens, store.load(testing.allocator));
var original = try oidc.TokenSet.parseResponse( testing.allocator, \\{"access_token":"at-1","token_type":"Bearer","refresh_token":"rt-1", \\ "scope":"https://graph.microsoft.com/Mail.Read offline_access","expires_in":3600} , .fromNanoseconds(0), ); defer original.deinit();
try store.save(&original);
var loaded = try store.load(testing.allocator); defer loaded.deinit();
try testing.expectEqualStrings("at-1", loaded.access_token); try testing.expectEqualStrings("rt-1", loaded.refresh_token.?); try testing.expectEqualStrings("Bearer", loaded.token_type); try testing.expect(loaded.hasScope("https://graph.microsoft.com/Mail.Read")); // The expiry survives as an absolute instant rather than as the // `expires_in` that produced it. try testing.expectEqual(original.expires_at.?.nanoseconds, loaded.expires_at.?.nanoseconds);
// And the file is readable only by its owner. const stat = try tmp.dir.statFile(io, "tokens.json", .{}); try expectOwnerOnly(stat);
try store.clear(); try testing.expectError(error.NoStoredTokens, store.load(testing.allocator));}
test "the refresh hook writes through" { const io = testing.io;
var tmp = testing.tmpDir(.{}); defer tmp.cleanup();
var store: TokenStore = .{ .dir = tmp.dir, .path = "tokens.json", .io = io };
var tokens = try oidc.TokenSet.parseResponse( testing.allocator, "{\"access_token\":\"at-2\",\"refresh_token\":\"rt-2\"}", .fromNanoseconds(0), ); defer tokens.deinit();
const hook = store.refreshHook(); try hook.func(hook.context, &tokens);
var loaded = try store.load(testing.allocator); defer loaded.deinit(); try testing.expectEqualStrings("at-2", loaded.access_token); try testing.expectEqualStrings("rt-2", loaded.refresh_token.?);}
test "a file that is not a token set" { const io = testing.io;
var tmp = testing.tmpDir(.{}); defer tmp.cleanup();
var store: TokenStore = .{ .dir = tmp.dir, .path = "tokens.json", .io = io };
try tmp.dir.writeFile(io, .{ .sub_path = "tokens.json", .data = "not json at all" }); try testing.expectError(error.Malformed, store.load(testing.allocator));
// JSON, but with no access token in it. try tmp.dir.writeFile(io, .{ .sub_path = "tokens.json", .data = "{\"hello\":1}" }); try testing.expectError(error.Malformed, store.load(testing.allocator));}
/// `Io.File.Permissions` is `std.Options.FilePermissions` on some targets and/// a platform default on others, and only the POSIX one has `toMode`.fn expectOwnerOnly(stat: std.Io.File.Stat) !void { const P = @TypeOf(stat.permissions); if (!@hasDecl(P, "toMode")) return; try testing.expectEqual(@as(u32, 0o600), @as(u32, stat.permissions.toMode()) & 0o777);}