Something went wrong. Try again.
Mirrors a Microsoft 365 mailbox into a local allthemail archive, turning each message's folder and categories into notmuch tags.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What to sync, from where, to where.//!//! A file rather than flags, because a sync run from a timer has no one to//! type them and because an OAuth application id and a tenant are not things//! to keep in a unit file. It is JSON for the same reason allthemail's is://! there is a parser in the standard library and the file is read once at//! startup.//!//! ## Nothing in here is a secret//!//! The OAuth client id is named by path rather than written down, as is the//! archive's API token, and that is the whole reason the arrangement is worth//! the extra files. A configuration with a credential in it is a configuration//! that cannot go in the Nix store, cannot be committed, and has to be mode//! 0600 wherever it lands. One that only names paths can be generated,//! world-readable and checked in, with the credentials arriving separately --//! from systemd's `LoadCredential`, from agenix, or from a file somebody wrote//! by hand.//!//! The permission check moves with them: it is the credential files that are//! refused if anyone but their owner can read them, and this file is not//! checked at all, because there is nothing in it to protect.//!//! ## The client secret is optional, and should be absent//!//! This is the first place Microsoft differs from Google. A desktop//! application is registered as a **public** client -- no secret at all -- and//! PKCE is what protects the authorization code instead, because a program//! shipped to somebody's laptop cannot keep a secret and pretending otherwise//! only makes the secret public. `client_secret_path` is here for a//! confidential client and is null by default.//!//! The client id is needed at all because `o365.TokenStore` deliberately holds//! only the tokens, and every refresh is a request made as the application --//! so a `sync` run from a timer days after `login` has to be able to find it.//!//! ## The tenant//!//! The identity platform has no single pair of OAuth endpoints: the tenant is//! in the path. `common` accepts work, school and personal accounts and is the//! right answer for a multi-tenant registration; a single-tenant application//! names its own tenant by GUID or by verified domain. See `o365.tenant` for//! the issuer caveat, which does not bite here because nothing in this program//! reads an ID token.
const Config = @This();
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const known_folders = @import("known-folders");
const AllTheMail = @import("AllTheMail.zig");
/// The directory everything this program owns goes under, inside whichever/// base directory is right for the kind of thing it is.const dir_name = "allthemail-o365";
/// Graph's hard limit on requests in one `$batch`: a batch carrying more is/// rejected with a `400` rather than truncated. Restated here rather than/// imported so that a configuration can be validated without a Graph client.pub const max_batch = 20;
/// Where the ledger is.////// Absent, which is the default, puts it at `allthemail-o365/state.db` under/// the data directory -- `$XDG_DATA_HOME`, or its equivalent elsewhere. The/// directory is created; see `databasePath`.database: ?[]const u8 = null,
/// The archive's base URL, without a trailing slash:/// `http://127.0.0.1:8080`.allthemail: []const u8,
/// File holding the API token to present to the archive, and nothing else.////// Absent, which is the default, sends no credential at all — right for an/// archive with `auth` off, which is allthemail's default too, and reached/// over loopback or through something in front of it that authenticates.////// A path rather than the token itself, for the same reason the OAuth client/// credentials are paths: it keeps every secret out of a file that can be/// generated into the Nix store and committed. The permission check moves with/// it — this file is refused if anyone but its owner can read it, and the/// configuration naming it is not checked at all.////// Mint it from the archive's reading UI with **both `read` and `write`**:/// `write` is what `POST /archive` needs, and `read` is what the pre-check/// needs to save uploading a mailbox the archive already holds.allthemail_token_path: ?[]const u8 = null,
/// What every folder and category becomes a tag under. The inbox becomes/// `o365/inbox`, a subfolder of it `o365/inbox/zig`, and an Outlook category/// `zig` becomes `o365/category/zig`.////// Null sends no tags at all, which is what an archive fed by one mailbox and/// uninterested in where a message was filed wants.tag_prefix: ?[]const u8 = "o365/",
/// How many messages to fetch in one `$batch`.////// Twenty is Graph's own ceiling and there is nothing to gain by asking for/// less unless the responses are enormous: these are whole messages, and/// twenty of a mailbox full of attachments is a large response. The client's/// `max_message_bytes` is what actually caps it, and a batch that overruns is/// split rather than failed.chunk_size: usize = max_batch,
/// How many times a message may fail before it stops being retried every run./// Without a cap, one permanently broken message makes every future sync busy/// and noisy. `atm-o365 retry` clears the count.max_attempts: i64 = 5,
/// Fetch the RFC 5322 bytes through `$batch` rather than one request each.////// Worth twenty times the throughput when it works, and zig-o365 is explicit/// that whether Graph serves `/$value` inside a batch is not something its/// test suite can settle. So this is a preference rather than an instruction:/// a batch that comes back with every entry refused in a way a serial fetch/// would not produce turns it off for the rest of the run and the messages are/// fetched one at a time instead. Setting it false skips the experiment.batch_mime: bool = true,
/// Walk hidden folders too. Graph leaves them out of a listing unless asked,/// and they are mostly Outlook's own bookkeeping rather than mail.include_hidden: bool = false,
/// Skip the folders that hold deleted, failed, or otherwise not-really-mail/// items: `Conflicts`, `Local Failures`, `Server Failures`, `Sync Issues`,/// `Recoverable Items`, and the search folders, which are saved queries rather/// than places a message lives.////// `Recoverable Items` is the one that matters: it holds everything that has/// ever been shift-deleted or emptied out of Deleted Items, so a mirror that/// walks it is a mirror of the mailbox's whole history rather than of the/// mailbox. Turn this off deliberately, if that is what is wanted.skip_detritus: bool = true,
/// Folders to leave out by tag path, compared case-insensitively against the/// path `folders.joinPath` produced: `sent`, `inbox/noise`, `Archive 2019`.////// A named folder's children go with it, because a folder skipped and its/// subfolders kept would put messages in the archive under a tag whose parent/// was never mirrored.skip_folders: []const []const u8 = &.{},
accounts: []const Account = &.{},
/// Where Graph is. Absent, which is the normal case and the default, means/// Microsoft's own endpoints.////// This exists because the round-trip test in `tests/nixos` has to stand a/// Graph up on a loopback socket: everything else in that test is real -- a/// real `atm`, a real notmuch database, the real `allthemail-o365` binary --/// and the one thing that cannot be is the mailbox. Overriding it from the/// configuration is how the binary under test is pointed at the substitute,/// rather than building a special one.////// It is also the setting to reach for in a national cloud, where both the/// Graph endpoint and the login host move: `https://graph.microsoft.us` with/// `https://login.microsoftonline.us/...` for US Government.graph: ?Endpoints = null,
pub const Endpoints = struct { /// `o365.Client.base_url`: the host the API calls go to, without a /// trailing slash. Every `@odata.nextLink` is checked against it before it /// is followed, so pointing this somewhere is also saying which links are /// safe to follow. base_url: []const u8, /// The OAuth token endpoint, which on Microsoft is a different host from /// Graph and carries the tenant in its path, so it cannot be derived from /// `base_url`. token_endpoint: []const u8,};
pub const Account = struct { /// The mailbox address. Also the key in the ledger, and the envelope /// recipient sent to the archive. address: []const u8, /// Which tenant's OAuth endpoints to use: `common`, `organizations`, /// `consumers`, a tenant GUID, or a verified domain. tenant: []const u8 = "common", /// File holding the OAuth application (client) id, and nothing else. Read /// when it is needed rather than at startup, so that a command which never /// talks to Graph -- `status`, `retry` -- does not require it to be /// present at all. client_id_path: []const u8, /// File holding the client secret, for a confidential client. Absent is /// the right answer for a desktop application; see the note at the top. client_secret_path: ?[]const u8 = null, /// Whose mailbox to read. Absent means `me`, the signed-in user, which is /// almost always right; a shared mailbox's address goes here otherwise and /// needs `Mail.Read.Shared`. user_id: ?[]const u8 = null, /// Where the refresh token is kept. Defaulted from the address when it is /// not given; see `tokenPath`. token_path: ?[]const u8 = null,};
/// One account's OAuth application credentials, read from the files that name/// them.pub const Credentials = struct { client_id: []const u8, /// Null for a public client, which is what a desktop application is. client_secret: ?[]const u8,
pub fn deinit(self: Credentials, gpa: Allocator) void { gpa.free(self.client_id); if (self.client_secret) |secret| gpa.free(secret); }};
pub const CredentialError = error{ NotFound, Unreadable, /// Readable by somebody other than its owner. TooOpen, /// Empty, or not one opaque token: a file with spaces or line breaks in /// the middle of it is a file somebody pointed at by mistake. Malformed,} || Allocator.Error;
/// Which file a `CredentialError` was about, so that the message can name it/// rather than listing both and leaving the reader to work it out.pub const CredentialDiagnostics = struct { path: ?[]const u8 = null,};
/// Largest credential file this will read. An application id is a GUID, which/// is thirty-six characters; a client secret runs to about forty. A file near/// this size is the wrong file.pub const max_credential_bytes = 4096;
/// Reads the credential files for `account`. The secret is only read when the/// account names one.pub fn credentials( io: Io, gpa: Allocator, dir: Io.Dir, for_account: Account, diagnostics: ?*CredentialDiagnostics,) CredentialError!Credentials { if (diagnostics) |d| d.path = for_account.client_id_path; const client_id = try readCredential(io, gpa, dir, for_account.client_id_path); errdefer gpa.free(client_id);
const client_secret: ?[]const u8 = if (for_account.client_secret_path) |path| secret: { if (diagnostics) |d| d.path = path; break :secret try readCredential(io, gpa, dir, path); } else null;
if (diagnostics) |d| d.path = null; return .{ .client_id = client_id, .client_secret = client_secret };}
/// One credential file: its contents, with surrounding whitespace removed.////// The trailing newline is the point of the trimming -- every editor adds one,/// and an application id with a newline on the end is rejected by the identity/// platform with an error that says nothing about newlines.fn readCredential( io: Io, gpa: Allocator, dir: Io.Dir, path: []const u8,) CredentialError![]const u8 { var file = dir.openFile(io, path, .{}) catch |err| switch (err) { error.FileNotFound => return error.NotFound, else => return error.Unreadable, }; defer file.close(io);
if (statIsTooOpen(io, file)) return error.TooOpen;
var buffer: [512]u8 = undefined; var reader = file.reader(io, &buffer); const source = reader.interface.allocRemaining(gpa, .limited(max_credential_bytes)) catch return error.Unreadable; defer gpa.free(source);
const trimmed = std.mem.trim(u8, source, " \t\r\n"); if (trimmed.len == 0) return error.Malformed;
// An application id or a client secret is one opaque run of characters. // Anything with a space or a control character inside it is a key file, or // a note, or a pretty-printed document -- something pointed at by mistake, // and worth saying so about rather than sending to Microsoft to be refused // with an error that describes none of this. for (trimmed) |c| { if (std.ascii.isWhitespace(c) or std.ascii.isControl(c)) return error.Malformed; }
// The likeliest mistake of all, and the one the check above misses: a JSON // document -- an app registration exported from the portal, say -- pointed // at instead of the value inside it. Written compactly it has no // whitespace to catch it by, and neither an application id nor a secret // begins with either of these. if (trimmed[0] == '{' or trimmed[0] == '[') return error.Malformed;
return try gpa.dupe(u8, trimmed);}
/// The API token for the archive, or null when none is configured. Allocated.////// Read once for a whole run rather than per account: the token belongs to the/// archive, and every account posts to the same one.pub fn archiveToken( io: Io, gpa: Allocator, dir: Io.Dir, self: Config, diagnostics: ?*CredentialDiagnostics,) CredentialError!?[]const u8 { const path = self.allthemail_token_path orelse return null;
if (diagnostics) |d| d.path = path; const token = try readCredential(io, gpa, dir, path); errdefer gpa.free(token);
// Refused here rather than at the first request, so that the answer is one // line at startup naming the file instead of a failed sync. A token is // fifty characters; a file this long is a key, or a note, or a mailbox. if (token.len > AllTheMail.max_token_bytes) return error.Malformed;
if (diagnostics) |d| d.path = null; return token;}
/// The parsed file and the arena its strings live in.pub const Parsed = struct { value: Config, arena: std.heap.ArenaAllocator,
pub fn deinit(self: *Parsed) void { self.arena.deinit(); self.* = undefined; }};
pub const ParseError = error{ /// The file is not JSON, or not the shape this expects. Malformed, /// The file parsed but says something that cannot be acted on. Invalid,} || Allocator.Error;
pub const LoadError = ParseError || error{ NotFound, Unreadable,};
/// Largest config this will read. A file bigger than this is a mistake, not a/// configuration.pub const max_bytes = 1 << 20;
/// Reads and validates the file at `path`.pub fn load(io: Io, gpa: Allocator, dir: Io.Dir, path: []const u8) LoadError!Parsed { var file = dir.openFile(io, path, .{}) catch |err| switch (err) { error.FileNotFound => return error.NotFound, else => return error.Unreadable, }; defer file.close(io);
// Deliberately not checked for permissions: there is nothing in it to // protect. The credential files it names are the ones that are checked, // in `readCredential`.
var buffer: [4096]u8 = undefined; var reader = file.reader(io, &buffer); const source = reader.interface.allocRemaining(gpa, .limited(max_bytes)) catch return error.Unreadable; defer gpa.free(source);
return parse(gpa, source);}
/// Whether the file is readable or writable by its group or by anyone else.////// A credential anyone on the machine can read is not a configuration problem/// to be logged, it is a credential to stop using.////// `Io.File.Permissions` is `std.Options.FilePermissions` on POSIX and a/// platform default elsewhere, and only the POSIX one has a mode to look at,/// so this asks rather than assuming — on a platform with no mode there is/// nothing to check and nothing to refuse.fn statIsTooOpen(io: Io, file: Io.File) bool { const stat = file.stat(io) catch return false; const Permissions = @TypeOf(stat.permissions); if (!@hasDecl(Permissions, "toMode")) return false; return stat.permissions.toMode() & 0o077 != 0;}
pub fn parse(gpa: Allocator, source: []const u8) ParseError!Parsed { var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit();
const parsed = std.json.parseFromSliceLeaky(Config, arena.allocator(), source, .{ .allocate = .alloc_always, }) catch return error.Malformed;
try validate(parsed); return .{ .value = parsed, .arena = arena };}
/// An absolute HTTP URL with no trailing slash.////// The trailing slash is refused where it can be seen rather than trimmed/// where it cannot: every URL built from one would contain `//`, which works/// everywhere and looks like a bug in every log line.fn validateUrl(url: []const u8) ParseError!void { if (std.mem.endsWith(u8, url, "/")) return error.Invalid; const uri = std.Uri.parse(url) catch return error.Invalid; if (!std.mem.eql(u8, uri.scheme, "http") and !std.mem.eql(u8, uri.scheme, "https")) return error.Invalid; if (uri.host == null) return error.Invalid;}
/// The check `o365.tenant.validate` applies, restated so that a tenant which/// would send the token request somewhere else is a startup error rather than/// a sign-in that quietly went to the wrong host.fn validateTenant(tenant: []const u8) ParseError!void { if (tenant.len == 0) return error.Invalid; for (tenant) |c| { if (std.ascii.isControl(c)) return error.Invalid; // The tenant goes into a path, so any of these would take the // endpoints somewhere other than where they were meant to go. switch (c) { '/', '\\', '?', '#', '%', '@', ':', ' ' => return error.Invalid, else => {}, } }}
fn validate(self: Config) ParseError!void { if (self.database) |path| { if (path.len == 0) return error.Invalid; } if (self.accounts.len == 0) return error.Invalid; if (self.chunk_size == 0) return error.Invalid; // Graph rejects a larger batch outright, so a configuration asking for one // is a run that fails on its first fetch rather than a slow one. if (self.chunk_size > max_batch) return error.Invalid; if (self.max_attempts <= 0) return error.Invalid;
try validateUrl(self.allthemail);
// Named but empty is a configuration that meant to point somewhere. The // way to send no token is to leave the field out. if (self.allthemail_token_path) |path| { if (path.len == 0) return error.Invalid; }
if (self.tag_prefix) |prefix| { // These are the rules `Archive.validateTag` applies on the far side. // Catching a bad prefix here means one error at startup rather than a // `400` on every message in the mailbox. if (!std.unicode.utf8ValidateSlice(prefix)) return error.Invalid; for (prefix) |c| if (std.ascii.isControl(c)) return error.Invalid; // The archive reserves its `recipient_tag_prefix` -- `to/` unless the // operator changed it -- for its own statement about delivery. Only // the default can be checked from here; a configured one comes back as // `reserved_tag_prefix` on the first message. if (std.mem.startsWith(u8, prefix, "to/")) return error.Invalid; }
for (self.skip_folders) |path| { if (path.len == 0) return error.Invalid; if (!std.unicode.utf8ValidateSlice(path)) return error.Invalid; }
if (self.graph) |endpoints| { // Both are asked for rather than derived, because on Microsoft they // are different hosts and the token endpoint carries a tenant in its // path; a base URL that could imply it would be an assumption that // holds for exactly one deployment. try validateUrl(endpoints.base_url); try validateUrl(endpoints.token_endpoint); }
for (self.accounts, 0..) |a, i| { if (a.address.len == 0) return error.Invalid; if (a.client_id_path.len == 0) return error.Invalid; // Absent means "a public client, which is what this should be". // Present and empty means somebody wrote something wrong, and treating // the two alike would silently sign in as the wrong kind of client. if (a.client_secret_path) |path| { if (path.len == 0) return error.Invalid; } if (a.user_id) |id| { if (id.len == 0) return error.Invalid; } try validateTenant(a.tenant); // One ledger keyed by address cannot hold the same address twice, and // two entries differing only in credentials is a typo either way. for (self.accounts[0..i]) |earlier| { if (std.mem.eql(u8, earlier.address, a.address)) return error.Invalid; } }}
/// The account with this address, or null.pub fn account(self: Config, address: []const u8) ?Account { for (self.accounts) |a| { if (std.mem.eql(u8, a.address, address)) return a; } return null;}
/// Whether a folder at this tag path is one the configuration says to leave/// alone. A named folder takes its children with it.pub fn skipsFolder(self: Config, path: []const u8) bool { for (self.skip_folders) |skipped| { if (std.ascii.eqlIgnoreCase(skipped, path)) return true; if (path.len > skipped.len and path[skipped.len] == '/' and std.ascii.eqlIgnoreCase(skipped, path[0..skipped.len])) return true; } return false;}
/// Errors from working a default path out. `NoKnownFolder` is what it means/// when the platform cannot say where a cache or a data directory is -- no/// `HOME`, most likely -- and the answer is to say so rather than to invent/// somewhere.pub const PathError = error{NoKnownFolder} || Allocator.Error || Io.Cancelable;
/// `<base>/allthemail-o365/<rest>`, for whichever base directory `folder`/// names.fn underKnownFolder( io: Io, gpa: Allocator, env: *const std.process.Environ.Map, folder: known_folders.KnownFolder, rest: []const u8,) PathError![]const u8 { const base = try known_folders.getPath(io, gpa, env, folder) orelse return error.NoKnownFolder; defer gpa.free(base); return std.fmt.allocPrint(gpa, "{s}/{s}/{s}", .{ base, dir_name, rest });}
/// Where the ledger lives: what the configuration says, or/// `allthemail-o365/state.db` under the data directory. Allocated.pub fn databasePath( io: Io, gpa: Allocator, env: *const std.process.Environ.Map, self: Config,) PathError![]const u8 { if (self.database) |path| return try gpa.dupe(u8, path); // The ledger is data rather than cache: losing it costs a full delta walk // of every folder of every mailbox, which is minutes of somebody's Graph // quota rather than a rebuild nobody notices. return underKnownFolder(io, gpa, env, .data, "state.db");}
/// Where an account's tokens live: what it says, or a file named after the/// address under the cache directory. Allocated.////// The cache rather than anywhere more permanent because a lost refresh token/// costs one `atm-o365 login` and nothing else -- there is nothing in there/// that cannot be asked for again.pub fn tokenPath( io: Io, gpa: Allocator, env: *const std.process.Environ.Map, a: Account,) PathError![]const u8 { if (a.token_path) |path| return try gpa.dupe(u8, path);
var name_buffer: [512]u8 = undefined; const name = std.fmt.bufPrint(&name_buffer, "{s}.json", .{a.address}) catch return error.OutOfMemory; return underKnownFolder(io, gpa, env, .cache, name);}
/// Where to look for the config when `--config` was not given:/// `$ALLTHEMAIL_O365_CONFIG`, then `allthemail-o365/config.json` under the/// configuration directory.pub fn defaultPath( io: Io, gpa: Allocator, env: *const std.process.Environ.Map,) PathError![]const u8 { if (env.get("ALLTHEMAIL_O365_CONFIG")) |path| return try gpa.dupe(u8, path); // `local_configuration` rather than `roaming_configuration`: this names // paths on this machine and a token store on this machine, so following a // user between machines would carry nothing that is true there. return underKnownFolder(io, gpa, env, .local_configuration, "config.json");}
const testing = std.testing;
const minimal = \\{ \\ "database": "/tmp/state.db", \\ "allthemail": "http://127.0.0.1:8080", \\ "accounts": [ \\ {"address": "a@example.com", \\ "client_id_path": "/run/credentials/client-id"} \\ ] \\};
test "a minimal config parses and takes the defaults" { var parsed = try parse(testing.allocator, minimal); defer parsed.deinit();
try testing.expectEqualStrings("/tmp/state.db", parsed.value.database.?); try testing.expectEqualStrings("o365/", parsed.value.tag_prefix.?); try testing.expectEqual(@as(usize, 20), parsed.value.chunk_size); try testing.expectEqual(@as(i64, 5), parsed.value.max_attempts); try testing.expect(parsed.value.batch_mime); try testing.expect(parsed.value.skip_detritus); try testing.expect(!parsed.value.include_hidden); try testing.expectEqual(@as(usize, 1), parsed.value.accounts.len); // A desktop application is a public client, so there is no secret to name. try testing.expectEqual(@as(?[]const u8, null), parsed.value.accounts[0].client_secret_path); try testing.expectEqualStrings("common", parsed.value.accounts[0].tenant); try testing.expectEqual(@as(?[]const u8, null), parsed.value.accounts[0].user_id); try testing.expectEqual(@as(?[]const u8, null), parsed.value.accounts[0].token_path); // No token named is no `Authorization` header sent, which is what an // archive with `auth` off wants. try testing.expectEqual(@as(?[]const u8, null), parsed.value.allthemail_token_path);}
test "a token path named but empty is refused" { // Naming the field meant to point somewhere; the way to send no token is // to leave it out, and an empty path would otherwise be a missing file // found only at the first message. const source = \\{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "allthemail_token_path": "", \\ "accounts": [{"address": "a@example.com", "client_id_path": "/i"}]} ; try testing.expectError(error.Invalid, parse(testing.allocator, source));}
test "an account is found by address" { var parsed = try parse(testing.allocator, minimal); defer parsed.deinit();
try testing.expectEqualStrings( "/run/credentials/client-id", parsed.value.account("a@example.com").?.client_id_path, ); try testing.expectEqual(@as(?Account, null), parsed.value.account("b@example.com"));}
test "a config with nothing to sync is refused" { const source = \\{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", "accounts": []} ; try testing.expectError(error.Invalid, parse(testing.allocator, source));}
test "the same address twice is refused" { const source = \\{ \\ "database": "/tmp/s.db", \\ "allthemail": "http://127.0.0.1:8080", \\ "accounts": [ \\ {"address": "a@x.com", "client_id_path": "/i"}, \\ {"address": "a@x.com", "client_id_path": "/i"} \\ ] \\} ; try testing.expectError(error.Invalid, parse(testing.allocator, source));}
test "a bad archive URL is refused at startup rather than on every message" { for ([_][]const u8{ "http://127.0.0.1:8080/", // trailing slash "127.0.0.1:8080", // no scheme "ftp://127.0.0.1", // not HTTP "", // nothing }) |url| { const source = try std.fmt.allocPrint(testing.allocator, \\{{"database": "/tmp/s.db", "allthemail": "{s}", \\ "accounts": [{{"address":"a@x.com","client_id_path":"/i"}}]}} , .{url}); defer testing.allocator.free(source); try testing.expectError(error.Invalid, parse(testing.allocator, source)); }}
test "a tenant that would move the token endpoint is refused" { // `o365.tenant.init` refuses these too, but by then the sign-in has been // started and the error names nothing the operator wrote. for ([_][]const u8{ "", "common/../evil", "login.evil.example.com/common", "a b", "tenant%2Fevil", }) |tenant| { const source = try std.fmt.allocPrint(testing.allocator, \\{{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "accounts": [{{"address":"a@x.com","client_id_path":"/i","tenant":"{s}"}}]}} , .{tenant}); defer testing.allocator.free(source); try testing.expectError(error.Invalid, parse(testing.allocator, source)); }
// A GUID and a verified domain both work, which is the whole point. for ([_][]const u8{ "common", "organizations", "consumers", "72f988bf-86f1-41af-91ab-2d7cd011db47", "contoso.onmicrosoft.com", }) |tenant| { const source = try std.fmt.allocPrint(testing.allocator, \\{{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "accounts": [{{"address":"a@x.com","client_id_path":"/i","tenant":"{s}"}}]}} , .{tenant}); defer testing.allocator.free(source); var parsed = try parse(testing.allocator, source); defer parsed.deinit(); try testing.expectEqualStrings(tenant, parsed.value.accounts[0].tenant); }}
test "a tag prefix that allthemail would reject is refused here first" { for ([_][]const u8{ "to/", // the archive's reserved prefix "o365\n/", // a control character }) |prefix| { const source = try std.fmt.allocPrint(testing.allocator, \\{{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "tag_prefix": "{f}", \\ "accounts": [{{"address":"a@x.com","client_id_path":"/i"}}]}} , .{std.zig.fmtString(prefix)}); defer testing.allocator.free(source); try testing.expectError(error.Invalid, parse(testing.allocator, source)); }}
test "Graph's endpoints default to Microsoft's and can be overridden together" { { var parsed = try parse(testing.allocator, minimal); defer parsed.deinit(); try testing.expectEqual(@as(?Endpoints, null), parsed.value.graph); }
const source = \\{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "graph": {"base_url": "http://127.0.0.1:9001", \\ "token_endpoint": "http://127.0.0.1:9001/token"}, \\ "accounts": [{"address":"a@x.com","client_id_path":"/i"}]} ; var parsed = try parse(testing.allocator, source); defer parsed.deinit(); try testing.expectEqualStrings("http://127.0.0.1:9001", parsed.value.graph.?.base_url); try testing.expectEqualStrings( "http://127.0.0.1:9001/token", parsed.value.graph.?.token_endpoint, );}
test "an override that is not a usable URL is refused" { for ([_][]const u8{ \\{"base_url": "http://x/", "token_endpoint": "http://x/token"} , \\{"base_url": "notaurl", "token_endpoint": "http://x/token"} , \\{"base_url": "http://x", "token_endpoint": "ftp://x/token"} , // Half an override is not an override: the token endpoint is a // different host on Microsoft and cannot be derived. \\{"base_url": "http://x"} , }) |endpoints| { const source = try std.fmt.allocPrint(testing.allocator, \\{{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "graph": {s}, \\ "accounts": [{{"address":"a@x.com","client_id_path":"/i"}}]}} , .{endpoints}); defer testing.allocator.free(source); try testing.expectError(error.Invalid, parse(testing.allocator, source) catch |err| switch (err) { // A missing required field is a shape problem, not a value one. error.Malformed => return, else => err, }); }}
test "a null tag prefix means no tags and is allowed" { const source = \\{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "tag_prefix": null, \\ "accounts": [{"address":"a@x.com","client_id_path":"/i"}]} ; var parsed = try parse(testing.allocator, source); defer parsed.deinit(); try testing.expectEqual(@as(?[]const u8, null), parsed.value.tag_prefix);}
test "a batch larger than Graph will take is refused" { for ([_][]const u8{ "0", "21", "100" }) |size| { const source = try std.fmt.allocPrint(testing.allocator, \\{{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "chunk_size": {s}, \\ "accounts": [{{"address":"a@x.com","client_id_path":"/i"}}]}} , .{size}); defer testing.allocator.free(source); try testing.expectError(error.Invalid, parse(testing.allocator, source)); }}
test "a skipped folder takes its children with it" { const source = \\{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "skip_folders": ["trash", "Archive 2019"], \\ "accounts": [{"address":"a@x.com","client_id_path":"/i"}]} ; var parsed = try parse(testing.allocator, source); defer parsed.deinit(); const config = parsed.value;
try testing.expect(config.skipsFolder("trash")); // Case-insensitively, because a configuration will say `Trash` and the // conventional name is lowercase. try testing.expect(config.skipsFolder("TRASH")); // A folder skipped and its subfolders kept would put messages in the // archive under a tag whose parent was never mirrored. try testing.expect(config.skipsFolder("trash/old")); try testing.expect(config.skipsFolder("Archive 2019/January"));
try testing.expect(!config.skipsFolder("inbox")); // A prefix that is not a path component is not a match. try testing.expect(!config.skipsFolder("trashcan")); try testing.expect(!config.skipsFolder("Archive 2020"));}
test "a credential is read, trimmed, and refused when it is not one" { if (!@hasDecl(Io.File.Permissions, "fromMode")) return error.SkipZigTest;
const gpa = testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup();
const owner_only: Io.File.Permissions = .fromMode(0o600);
const write = struct { fn f(d: Io.Dir, i: Io, name: []const u8, body: []const u8, perms: Io.File.Permissions) !void { var file = try d.createFile(i, name, .{ .permissions = perms }); defer file.close(i); try file.writeStreamingAll(i, body); } }.f;
// The trailing newline every editor adds. Left on, the identity platform // refuses the grant with an error that says nothing about newlines. try write(tmp.dir, io, "id", " 4f2c1f9a-0000-0000-0000-000000000001\n", owner_only); try write(tmp.dir, io, "secret", "client-secret-here\n", owner_only); try write(tmp.dir, io, "empty", "\n\n", owner_only); // The wrong file, in its two shapes: a JSON document pretty-printed, and // the same thing compact, which has no whitespace to be caught by. try write(tmp.dir, io, "notacred", "{\"appId\": \"x\"}\n", owner_only); try write(tmp.dir, io, "notacred-compact", "{\"appId\":\"x\"}\n", owner_only); try write(tmp.dir, io, "world-readable", "4f2c1f9a-0000\n", .fromMode(0o644));
// A public client: the id and nothing else, which is the normal case. { const creds = try credentials(io, gpa, tmp.dir, .{ .address = "a@example.com", .client_id_path = "id", }, null); defer creds.deinit(gpa); try testing.expectEqualStrings("4f2c1f9a-0000-0000-0000-000000000001", creds.client_id); try testing.expectEqual(@as(?[]const u8, null), creds.client_secret); }
// A confidential one, which names a second file. { const creds = try credentials(io, gpa, tmp.dir, .{ .address = "a@example.com", .client_id_path = "id", .client_secret_path = "secret", }, null); defer creds.deinit(gpa); try testing.expectEqualStrings("client-secret-here", creds.client_secret.?); }
try testing.expectError(error.NotFound, credentials(io, gpa, tmp.dir, .{ .address = "a", .client_id_path = "nothing-here", }, null));
try testing.expectError(error.Malformed, credentials(io, gpa, tmp.dir, .{ .address = "a", .client_id_path = "empty", }, null));
for ([_][]const u8{ "notacred", "notacred-compact" }) |wrong| { try testing.expectError(error.Malformed, credentials(io, gpa, tmp.dir, .{ .address = "a", .client_id_path = wrong, }, null)); }
try testing.expectError(error.TooOpen, credentials(io, gpa, tmp.dir, .{ .address = "a", .client_id_path = "world-readable", }, null));
// The secret is checked as thoroughly as the id, and the id is not leaked // when the secret fails. var diagnostics: CredentialDiagnostics = .{}; try testing.expectError(error.TooOpen, credentials(io, gpa, tmp.dir, .{ .address = "a", .client_id_path = "id", .client_secret_path = "world-readable", }, &diagnostics)); // And the caller is told which of the two it was, rather than being left // to guess between them -- which is the whole reason to name two files. try testing.expectEqualStrings("world-readable", diagnostics.path.?);
{ const creds = try credentials(io, gpa, tmp.dir, .{ .address = "a", .client_id_path = "id", }, &diagnostics); defer creds.deinit(gpa); // Cleared on success, so a stale path cannot be reported later. try testing.expectEqual(@as(?[]const u8, null), diagnostics.path); }}
test "a configuration naming no client id is refused" { const source = \\{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "accounts": [{"address":"a@x.com","client_id_path":""}]} ; try testing.expectError(error.Invalid, parse(testing.allocator, source));
// Absent means a public client; present and empty is a typo. const empty_secret = \\{"database": "/tmp/s.db", "allthemail": "http://127.0.0.1:8080", \\ "accounts": [{"address":"a@x.com","client_id_path":"/i","client_secret_path":""}]} ; try testing.expectError(error.Invalid, parse(testing.allocator, empty_secret));}
test "the token path is taken from the config, or built from the cache directory" { const gpa = testing.allocator; const io = std.testing.io;
var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("HOME", "/home/someone");
{ const path = try tokenPath(io, gpa, &env, .{ .address = "a@x.com", .client_id_path = "/i", .token_path = "/somewhere/else.json", }); defer gpa.free(path); try testing.expectEqualStrings("/somewhere/else.json", path); }
try env.put("XDG_CACHE_HOME", "/cache"); { const path = try tokenPath(io, gpa, &env, .{ .address = "a@x.com", .client_id_path = "/i", }); defer gpa.free(path); try testing.expectEqualStrings("/cache/allthemail-o365/a@x.com.json", path); }}
test "the ledger defaults into the data directory" { const gpa = testing.allocator; const io = std.testing.io;
var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("HOME", "/home/someone"); try env.put("XDG_DATA_HOME", "/data");
{ var parsed = try parse(gpa, minimal); defer parsed.deinit(); // `minimal` names one, so nothing is worked out. const path = try databasePath(io, gpa, &env, parsed.value); defer gpa.free(path); try testing.expectEqualStrings("/tmp/state.db", path); }
const without = \\{ \\ "allthemail": "http://127.0.0.1:8080", \\ "accounts": [{"address": "a@example.com", "client_id_path": "/i"}] \\} ; var parsed = try parse(gpa, without); defer parsed.deinit(); try testing.expectEqual(@as(?[]const u8, null), parsed.value.database);
const path = try databasePath(io, gpa, &env, parsed.value); defer gpa.free(path); // Data, not cache: losing it costs a full walk of every folder. try testing.expectEqualStrings("/data/allthemail-o365/state.db", path);}
test "an empty database path is refused rather than defaulted" { // Absent means "work it out"; empty means somebody wrote something wrong, // and silently treating the two alike would put the ledger somewhere they // did not ask for. const source = \\{"database": "", "allthemail": "http://127.0.0.1:8080", \\ "accounts": [{"address":"a@x.com","client_id_path":"/i"}]} ; try testing.expectError(error.Invalid, parse(testing.allocator, source));}
test "the config path ladder prefers the environment variable" { const gpa = testing.allocator; const io = std.testing.io;
var env: std.process.Environ.Map = .init(gpa); defer env.deinit();
// Nothing to go on at all: said rather than guessed at. try testing.expectError(error.NoKnownFolder, defaultPath(io, gpa, &env));
try env.put("HOME", "/home/someone"); { const path = try defaultPath(io, gpa, &env); defer gpa.free(path); try testing.expectEqualStrings("/home/someone/.config/allthemail-o365/config.json", path); }
try env.put("XDG_CONFIG_HOME", "/conf"); { const path = try defaultPath(io, gpa, &env); defer gpa.free(path); try testing.expectEqualStrings("/conf/allthemail-o365/config.json", path); }
try env.put("ALLTHEMAIL_O365_CONFIG", "/explicit.json"); { const path = try defaultPath(io, gpa, &env); defer gpa.free(path); try testing.expectEqualStrings("/explicit.json", path); }}
test "the archive token is read like a credential, or is null when none is named" { if (!@hasDecl(Io.File.Permissions, "fromMode")) return error.SkipZigTest;
const gpa = testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup();
const write = struct { fn f(d: Io.Dir, i: Io, name: []const u8, body: []const u8, perms: Io.File.Permissions) !void { var file = try d.createFile(i, name, .{ .permissions = perms }); defer file.close(i); try file.writeStreamingAll(i, body); } }.f;
const owner_only: Io.File.Permissions = .fromMode(0o600); try write(tmp.dir, io, "token", "atm_abcdef\n", owner_only); try write(tmp.dir, io, "world-readable", "atm_abcdef\n", .fromMode(0o644));
const long = &@as([AllTheMail.max_token_bytes + 1]u8, @splat('a')); try write(tmp.dir, io, "too-long", long, owner_only);
const base: Config = .{ .allthemail = "http://127.0.0.1:8080" };
// An archive with `auth` off: nothing named, nothing read, nothing sent. try testing.expectEqual( @as(?[]const u8, null), try archiveToken(io, gpa, tmp.dir, base, null), );
{ var with = base; with.allthemail_token_path = "token"; const token = (try archiveToken(io, gpa, tmp.dir, with, null)).?; defer gpa.free(token); // The trailing newline every editor adds would be a header value with // a newline in it, which is a panic in the HTTP client. try testing.expectEqualStrings("atm_abcdef", token); }
// A token anybody on the machine can read is a token to stop using, and // the diagnostics name the file rather than leaving it to be guessed. { var open_one = base; open_one.allthemail_token_path = "world-readable"; var diagnostics: CredentialDiagnostics = .{}; try testing.expectError( error.TooOpen, archiveToken(io, gpa, tmp.dir, open_one, &diagnostics), ); try testing.expectEqualStrings("world-readable", diagnostics.path.?); }
{ var missing = base; missing.allthemail_token_path = "nothing-here"; try testing.expectError( error.NotFound, archiveToken(io, gpa, tmp.dir, missing, null), ); }
// Longer than anything that could go in the header, caught at startup // rather than at the first message. { var big = base; big.allthemail_token_path = "too-long"; try testing.expectError( error.Malformed, archiveToken(io, gpa, tmp.dir, big, null), ); }}