Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Where a Microsoft 365 tenant's OAuth endpoints are.//!//! Unlike Google, the identity platform has no single pair of URLs: the tenant//! is *in* the path, so `https://login.microsoftonline.com/common/oauth2/v2.0/token`//! and `https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token`//! are different endpoints of the same service. This builds the//! `oidc.Provider` for whichever one an application is registered against.//!//! ## Which tenant to name//!//! - `common` -- work, school *and* personal Microsoft accounts. The right//! answer for an application that is registered multi-tenant and wants to//! accept anybody.//! - `organizations` -- work and school accounts only.//! - `consumers` -- personal Microsoft accounts only (outlook.com, hotmail.com).//! - A tenant id (a GUID) or a verified domain -- one organisation, which is//! what a single-tenant registration requires.//!//! ## The issuer caveat, which costs an afternoon//!//! `Provider.issuer` is the value an ID token's `iss` claim must equal, and for//! these it very often does not. A token issued through `common` carries the//! **tenant-specific** issuer of whoever actually signed in --//! `https://login.microsoftonline.com/<the tenant's GUID>/v2.0` -- and not//! `.../common/v2.0`. So `oidc.Client.readIdToken` against a `common` provider//! fails with `IssuerMismatch` even though nothing is wrong.//!//! Nothing in this library reads an ID token, so this only bites a caller that//! chooses to. There are two ways out, and which is right depends on why the//! token is being read. If the application is single-tenant, name that tenant//! here by its **GUID** -- a domain name will not do, because the `iss` claim//! is always spelled with the GUID whatever was used to reach the endpoint.//! If it is genuinely multi-tenant, the issuer is not knowable in advance and//! the check has to be done against the `tid` claim after the fact, which is//! what Microsoft's own guidance says.//!//! ## National clouds//!//! `host` is a field rather than a constant because the endpoints move: US//! Government is `login.microsoftonline.us` and China operated by 21Vianet is//! `login.partner.microsoftonline.cn`. The Graph endpoint moves with it, which//! is `Client.base_url`'s business rather than this file's.
const std = @import("std");const oidc = @import("oidc");
/// The worldwide identity platform. The default, and what/// `graph.microsoft.com` pairs with.pub const default_host = "login.microsoftonline.com";
/// US Government L4 and L5, which pair with `graph.microsoft.us`.pub const us_government_host = "login.microsoftonline.us";
/// China, operated by 21Vianet, which pairs with/// `microsoftgraph.chinacloudapi.cn`.pub const china_host = "login.partner.microsoftonline.cn";
/// Work, school and personal accounts.pub const common_id = "common";/// Work and school accounts only.pub const organizations_id = "organizations";/// Personal Microsoft accounts only.pub const consumers_id = "consumers";
/// UserInfo is served by Graph rather than by the login host, and its URL has/// no tenant in it.pub const userinfo_endpoint = "https://graph.microsoft.com/oidc/userinfo";
/// The `common` tenant, built at compile time so that the common case needs/// neither an allocation nor a round trip.////// Read the issuer caveat above before handing this to/// `oidc.Client.readIdToken`.pub const common: oidc.Provider = build(default_host, common_id);
/// Work and school accounts only.pub const organizations: oidc.Provider = build(default_host, organizations_id);
/// Personal Microsoft accounts only.pub const consumers: oidc.Provider = build(default_host, consumers_id);
pub const Error = error{ /// The tenant is empty, or contains something that would take the /// endpoints somewhere other than where they were meant to go. See /// `validate`. InvalidTenant,} || std.mem.Allocator.Error;
/// A provider for one tenant, and the arena its URLs live in.////// The `oidc.Provider` borrows from the arena, so it must not outlive this --/// the same rule as `oidc.Provider.Discovered`, and for the same reason.pub const Tenant = struct { provider: oidc.Provider, arena: std.heap.ArenaAllocator,
pub fn deinit(t: *Tenant) void { t.arena.deinit(); t.* = undefined; }};
pub const InitOptions = struct { /// Which cloud. `us_government_host` and `china_host` are the others. host: []const u8 = default_host,};
/// Builds the endpoints for `tenant_id`, which may be a GUID, a verified/// domain, or one of `common`, `organizations` and `consumers`.////// ```zig/// var tenant = try o365.tenant.init(gpa, "contoso.onmicrosoft.com", .{});/// defer tenant.deinit();////// const oauth: oidc.Client = .{/// .provider = tenant.provider,/// .client_id = client_id,/// .redirect_uri = redirect_uri,/// .scopes = o365.scopes.mirror,/// };/// ```pub fn init( gpa: std.mem.Allocator, tenant_id: []const u8, options: InitOptions,) Error!Tenant { try validate(tenant_id); try validate(options.host);
var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const alloc = arena.allocator();
const base = try std.fmt.allocPrint(alloc, "https://{s}/{s}", .{ options.host, tenant_id });
return .{ .provider = .{ .issuer = try std.fmt.allocPrint(alloc, "{s}/v2.0", .{base}), .authorization_endpoint = try std.fmt.allocPrint( alloc, "{s}/oauth2/v2.0/authorize", .{base}, ), .token_endpoint = try std.fmt.allocPrint(alloc, "{s}/oauth2/v2.0/token", .{base}), .userinfo_endpoint = userinfo_endpoint, .jwks_uri = try std.fmt.allocPrint(alloc, "{s}/discovery/v2.0/keys", .{base}), // The identity platform has no RFC 7009 revocation endpoint. // Consent is withdrawn by the user at myaccount.microsoft.com or // by an administrator, not by a request from here; `logout_url` // is the nearest thing and only ends a browser session. .revocation_endpoint = null, .device_authorization_endpoint = try std.fmt.allocPrint( alloc, "{s}/oauth2/v2.0/devicecode", .{base}, ), .code_challenge_methods_supported = &.{ "plain", "S256" }, }, .arena = arena, };}
/// The same, at compile time, for a tenant that is written into the program.////// This is what `common` and the two beside it are; a program with its own/// tenant id in its source can use it the same way and never allocate.pub fn build(comptime host: []const u8, comptime tenant_id: []const u8) oidc.Provider { comptime { // The same check as `init`, as a compile error rather than a runtime // one. A literal with a `/` in it is a typo, and this is where to find // out. validate(tenant_id) catch @compileError("invalid tenant id: " ++ tenant_id); validate(host) catch @compileError("invalid host: " ++ host); const base = "https://" ++ host ++ "/" ++ tenant_id; return .{ .issuer = base ++ "/v2.0", .authorization_endpoint = base ++ "/oauth2/v2.0/authorize", .token_endpoint = base ++ "/oauth2/v2.0/token", .userinfo_endpoint = userinfo_endpoint, .jwks_uri = base ++ "/discovery/v2.0/keys", .revocation_endpoint = null, .device_authorization_endpoint = base ++ "/oauth2/v2.0/devicecode", .code_challenge_methods_supported = &.{ "plain", "S256" }, }; }}
/// The issuer a token from this tenant will actually claim, for the/// single-tenant case where that is knowable.////// Only true when `tenant_id` is the tenant's **GUID**. Reached through a/// domain name, `common`, `organizations` or `consumers`, the `iss` claim/// still names the GUID, so there is nothing this can return that would be/// right -- see the caveat at the top of this file.pub fn issuerFor( gpa: std.mem.Allocator, tenant_guid: []const u8, options: InitOptions,) Error![]u8 { try validate(tenant_guid); try validate(options.host); return std.fmt.allocPrint(gpa, "https://{s}/{s}/v2.0", .{ options.host, tenant_guid });}
/// Whether the tenant id looks like a GUID, which is the only form for which/// `issuerFor` says anything true.pub fn isGuid(tenant_id: []const u8) bool { if (tenant_id.len != 36) return false; for (tenant_id, 0..) |c, i| { switch (i) { 8, 13, 18, 23 => if (c != '-') return false, else => if (!std.ascii.isHex(c)) return false, } } return true;}
/// Refuses anything that would move the endpoint rather than name a tenant.////// This is a security check and not a tidiness one. The tenant goes into the/// *path* of the token endpoint, so a value carrying `/` could address a/// different path on the login host, and one carrying `?` or `#` could turn/// the rest of the URL into a query or a fragment -- in either case sending a/// client secret and an authorization code somewhere they were not meant to/// go. Tenant ids reach a program from configuration files and command lines,/// so they are not trusted here.pub fn validate(tenant_id: []const u8) error{InvalidTenant}!void { if (tenant_id.len == 0) return error.InvalidTenant; // Long enough for a GUID, the three keywords, and any verified domain: a // DNS name cannot exceed 253 characters. if (tenant_id.len > 253) return error.InvalidTenant; for (tenant_id) |c| { switch (c) { 'a'...'z', 'A'...'Z', '0'...'9', '-', '.' => {}, else => return error.InvalidTenant, } } // A leading or trailing dot is not a domain, and `..` is a path segment // that climbs. if (tenant_id[0] == '.' or tenant_id[tenant_id.len - 1] == '.') return error.InvalidTenant; if (std.mem.indexOf(u8, tenant_id, "..") != null) return error.InvalidTenant;}
const testing = std.testing;
test "the common tenant, built at compile time" { try testing.expectEqualStrings("https://login.microsoftonline.com/common/v2.0", common.issuer); try testing.expectEqualStrings( "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", common.authorization_endpoint, ); try testing.expectEqualStrings( "https://login.microsoftonline.com/common/oauth2/v2.0/token", common.token_endpoint, ); try testing.expectEqualStrings( "https://graph.microsoft.com/oidc/userinfo", common.userinfo_endpoint.?, ); // The identity platform has no revocation endpoint; claiming one would // make `oidc.Client.revoke` send a refresh token to a 404. try testing.expectEqual(@as(?[]const u8, null), common.revocation_endpoint); try testing.expect(common.supportsPkceMethod("S256"));}
test "organizations and consumers differ from common and from each other" { try testing.expect(!std.mem.eql(u8, common.token_endpoint, organizations.token_endpoint)); try testing.expect(!std.mem.eql(u8, consumers.token_endpoint, organizations.token_endpoint)); try testing.expect(std.mem.indexOf(u8, consumers.issuer, "/consumers/") != null);}
test "a named tenant" { var tenant = try init(testing.allocator, "contoso.onmicrosoft.com", .{}); defer tenant.deinit();
try testing.expectEqualStrings( "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token", tenant.provider.token_endpoint, ); try testing.expectEqualStrings( "https://login.microsoftonline.com/contoso.onmicrosoft.com/discovery/v2.0/keys", tenant.provider.jwks_uri.?, ); try testing.expectEqualStrings( "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/devicecode", tenant.provider.device_authorization_endpoint.?, );}
test "a national cloud" { var tenant = try init(testing.allocator, "common", .{ .host = us_government_host }); defer tenant.deinit(); try testing.expectEqualStrings( "https://login.microsoftonline.us/common/oauth2/v2.0/authorize", tenant.provider.authorization_endpoint, );}
test "a tenant id cannot move the endpoint" { // The point of `validate`: every one of these, interpolated unchecked, // sends an authorization code somewhere other than the token endpoint. for ([_][]const u8{ "", "../../evil", "common/../../evil", "common?x=", "common#x", "evil.example.com/path", "common\r\nHost: evil", "common ", "..", ".contoso.com", "contoso.com.", "a..b", "tenant/", "//evil.example.com", }) |bad| { try testing.expectError(error.InvalidTenant, validate(bad)); try testing.expectError(error.InvalidTenant, init(testing.allocator, bad, .{})); }
// And a host that is not a host is refused the same way. try testing.expectError( error.InvalidTenant, init(testing.allocator, "common", .{ .host = "evil.example.com/login.microsoftonline.com" }), );}
test "the shapes a tenant id really takes are all accepted" { for ([_][]const u8{ "common", "organizations", "consumers", "72f988bf-86f1-41af-91ab-2d7cd011db47", "contoso.onmicrosoft.com", "contoso.com", }) |good| { try validate(good); var tenant = try init(testing.allocator, good, .{}); defer tenant.deinit(); try testing.expect(std.mem.indexOf(u8, tenant.provider.token_endpoint, good) != null); }}
test "only a GUID has a knowable issuer" { try testing.expect(isGuid("72f988bf-86f1-41af-91ab-2d7cd011db47")); try testing.expect(isGuid("72F988BF-86F1-41AF-91AB-2D7CD011DB47")); try testing.expect(!isGuid("common")); try testing.expect(!isGuid("contoso.onmicrosoft.com")); // Right length, wrong shape. try testing.expect(!isGuid("72f988bf086f1-41af-91ab-2d7cd011db4")); try testing.expect(!isGuid("72f988bf-86f1-41af-91ab-2d7cd011dbZZ"));
const issuer = try issuerFor(testing.allocator, "72f988bf-86f1-41af-91ab-2d7cd011db47", .{}); defer testing.allocator.free(issuer); try testing.expectEqualStrings( "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0", issuer, );}