Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Something attached to a message: a file, another Outlook item, or a link to//! a file that lives elsewhere.//!//! Three types share one collection, and which one an entry is is said by its//! `@odata.type` rather than by its shape. Only a `fileAttachment` has bytes://! an `itemAttachment` holds a whole nested message or event, and a//! `referenceAttachment` holds nothing at all but a URL to OneDrive.//! `kind` is that distinction, and it is worth branching on before reaching for//! `content`.//!//! ## Listing costs bytes//!//! `GET /me/messages/{id}/attachments` returns `contentBytes` **inline**, base64//! encoded, for every file attachment on the message. A listing of a message//! with a 20 MB attachment on it is a 27 MB response, and a walk that lists//! attachments for every message downloads the whole mailbox twice over.//!//! `Client.listAttachments` therefore defaults to a `$select` that leaves the//! bytes out, and `Client.getAttachment` fetches one when it is actually//! wanted. `has_content` says whether what is in hand is the metadata or the//! thing itself.//!//! ## Or skip all of this//!//! A program that wants the message as it arrived does not want any of it.//! `Client.getMime` returns the RFC 5322 bytes with every attachment already in//! them, in one request and with no base64 round trip through JSON. This type//! is for the program that wants one named attachment out of a message and not//! the rest of it.
const Attachment = @This();
const std = @import("std");
const json = @import("json.zig");
/// Opaque, and unique only within its message.id: []const u8,/// Which of the three this is.kind: Kind = .unknown,/// The file name, as the sender wrote it. **Not safe to use as a path.** It/// arrives from whoever sent the message and has been seen to contain `/`,/// `..` and a NUL; anything writing it to disk has to sanitise it first.name: ?[]const u8 = null,/// The MIME type the sender claimed. Also not to be trusted -- it says what/// the sender wanted a mail client to do with the bytes, not what they are.content_type: ?[]const u8 = null,/// The length in bytes, as Graph reports it. This is the size of the/// attachment *as stored*, which for a file attachment is a little larger than/// `content.len` -- it includes the MIME encoding overhead -- so it is an/// estimate for sizing a progress bar and not a length to allocate by.size: ?u32 = null,/// Whether the attachment is displayed within the body rather than listed/// beside it: an image referenced by a `cid:` URL in the HTML.is_inline: ?bool = null,last_modified_date_time: ?std.Io.Timestamp = null,
/// `fileAttachment` only: the `Content-ID` an inline image is referenced by,/// which is what a `cid:` URL in the body matches against.content_id: ?[]const u8 = null,content_location: ?[]const u8 = null,/// `fileAttachment` only: the bytes, already base64-decoded.////// `null` both for an attachment fetched without them -- the default for a/// listing -- and for one whose `contentBytes` could not be decoded. `kind`/// and `has_content` are what tell those apart from an attachment that is not/// a file at all.content: ?[]const u8 = null,/// Whether `contentBytes` was present in the response, whatever came of/// decoding it. `false` means it was not asked for.has_content: bool = false,
/// `itemAttachment` only: the attached message, event or contact, as the raw/// JSON value Graph sent.////// Left as a `std.json.Value` rather than parsed into a `Message`, because it/// may be any of three resources and only its own `@odata.type` says which./// A caller that knows it is a message can hand this to `Message.fromJson`.item: ?std.json.Value = null,
/// `referenceAttachment` only: where the file actually is.source_url: ?[]const u8 = null,
pub const Kind = enum { /// Bytes, in `content`. file, /// A nested Outlook item, in `item`. item, /// A link, in `source_url`. Nothing is attached to the message itself, and /// reading the file needs whatever permissions that URL requires -- which /// this token may well not have. reference, /// Something Microsoft has added since, or an entry with no `@odata.type`. unknown,
/// Reads the OData type annotation. The leading `#` and the /// `microsoft.graph.` namespace are both optional here, because a /// `$select` that narrows the response has been seen to send the short /// form. pub fn fromODataType(odata_type: []const u8) Kind { var name = odata_type; if (std.mem.startsWith(u8, name, "#")) name = name[1..]; if (std.mem.lastIndexOfScalar(u8, name, '.')) |dot| name = name[dot + 1 ..];
if (std.ascii.eqlIgnoreCase(name, "fileAttachment")) return .file; if (std.ascii.eqlIgnoreCase(name, "itemAttachment")) return .item; if (std.ascii.eqlIgnoreCase(name, "referenceAttachment")) return .reference; return .unknown; }};
pub const ParseError = error{Malformed} || std.mem.Allocator.Error;
/// Reads one attachment. `alloc` should be an arena: the decoded content is/// allocated from it and is not freed individually.pub fn fromJson(alloc: std.mem.Allocator, value: std.json.Value) ParseError!Attachment { if (value != .object) return error.Malformed;
const content = try json.base64(alloc, value, "contentBytes");
return .{ .id = json.string(value, "id") orelse return error.Malformed, .kind = if (json.string(value, "@odata.type")) |t| Kind.fromODataType(t) else if (value.object.get("contentBytes") != null) // No annotation, but it has bytes, so it is a file. Graph always // sends the annotation; a proxy that strips OData metadata does // not. .file else if (value.object.get("item") != null) .item else .unknown, .name = json.string(value, "name"), .content_type = json.nonEmptyString(value, "contentType"), .size = json.unsigned(value, "size"), .is_inline = json.boolean(value, "isInline"), .last_modified_date_time = json.dateTime(value, "lastModifiedDateTime"), .content_id = json.nonEmptyString(value, "contentId"), .content_location = json.nonEmptyString(value, "contentLocation"), .content = content, .has_content = value.object.get("contentBytes") != null, .item = json.object(value, "item"), .source_url = json.nonEmptyString(value, "sourceUrl"), };}
/// A file name safe to create on disk, written into `buf` and returned.////// The name on an attachment is written by whoever sent the message and is not/// a name this program chose, so every separator, every `..` and every control/// character in it is replaced with `_`. A name that is empty, or is entirely/// dots, becomes `attachment`.////// This makes a *safe* name and not a *unique* one: two attachments on the/// same message may both be called `image001.png`, and distinguishing them is/// the caller's business.pub fn safeName(a: *const Attachment, buf: []u8) []const u8 { const fallback = "attachment"; const raw = a.name orelse return copyInto(buf, fallback);
var written: usize = 0; var all_dots = true; for (raw) |c| { if (written >= buf.len) break; const safe: u8 = switch (c) { // Path separators on every platform this might run on, the // characters Windows refuses outright, and everything below space. '/', '\\', 0...0x1f, 0x7f, ':', '*', '?', '"', '<', '>', '|' => '_', else => c, }; if (safe != '.') all_dots = false; buf[written] = safe; written += 1; }
// `.`, `..`, and the empty string are all names that mean something other // than a file. if (written == 0 or all_dots) return copyInto(buf, fallback); return buf[0..written];}
fn copyInto(buf: []u8, text: []const u8) []const u8 { const n = @min(buf.len, text.len); @memcpy(buf[0..n], text[0..n]); return buf[0..n];}
const testing = std.testing;
const TestAttachment = struct { parsed: std.json.Parsed(std.json.Value), arena: std.heap.ArenaAllocator, attachment: Attachment,
fn init(text: []const u8) !TestAttachment { var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, text, .{}); errdefer parsed.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); errdefer arena.deinit(); const attachment: Attachment = try .fromJson(arena.allocator(), parsed.value); return .{ .parsed = parsed, .arena = arena, .attachment = attachment }; }
fn deinit(t: *TestAttachment) void { t.arena.deinit(); t.parsed.deinit(); }};
test "a file attachment, with its bytes" { var t = try TestAttachment.init( \\{"@odata.type":"#microsoft.graph.fileAttachment", \\ "id":"AAMkAGUwNjQ4ZjIx","lastModifiedDateTime":"2017-01-26T19:31:10Z", \\ "name":"smile.gif","contentType":"image/gif","size":1008, \\ "isInline":false,"contentId":"f_iy8pzqm40","contentLocation":null, \\ "contentBytes":"aGVsbG8gd29ybGQ="} ); defer t.deinit(); const a = t.attachment;
try testing.expectEqual(Kind.file, a.kind); try testing.expectEqualStrings("smile.gif", a.name.?); try testing.expectEqualStrings("image/gif", a.content_type.?); try testing.expectEqual(@as(?u32, 1008), a.size); try testing.expectEqual(@as(?bool, false), a.is_inline); try testing.expectEqualStrings("f_iy8pzqm40", a.content_id.?); try testing.expectEqual(@as(?[]const u8, null), a.content_location); try testing.expect(a.has_content); try testing.expectEqualStrings("hello world", a.content.?); // `size` is the stored size, not the decoded length: they differ, and // allocating by `size` would be wrong. try testing.expect(a.size.? != a.content.?.len);}
test "a listing that left the bytes out" { // What `$select=id,name,contentType,size` returns, which is what a walk // should ask for: a message with a 20 MB attachment otherwise costs 27 MB // of base64 to list. var t = try TestAttachment.init( \\{"@odata.type":"#microsoft.graph.fileAttachment","id":"abc", \\ "name":"invoice.pdf","contentType":"application/pdf","size":98765} ); defer t.deinit();
try testing.expectEqual(Kind.file, t.attachment.kind); try testing.expect(!t.attachment.has_content); try testing.expectEqual(@as(?[]const u8, null), t.attachment.content);}
test "an item attachment holds a whole nested message" { var t = try TestAttachment.init( \\{"@odata.type":"#microsoft.graph.itemAttachment","id":"abc", \\ "name":"Forwarded message","size":2048, \\ "item":{"@odata.type":"#microsoft.graph.message","id":"inner", \\ "subject":"the one inside"}} ); defer t.deinit();
try testing.expectEqual(Kind.item, t.attachment.kind); try testing.expect(!t.attachment.has_content); // Left as a value: it may be a message, an event or a contact, and only // its own annotation says which. const Message = @import("Message.zig"); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const inner: Message = try .fromJson(arena.allocator(), t.attachment.item.?); try testing.expectEqualStrings("the one inside", inner.subject.?);}
test "a reference attachment has nothing attached" { var t = try TestAttachment.init( \\{"@odata.type":"#microsoft.graph.referenceAttachment","id":"abc", \\ "name":"Budget.xlsx","sourceUrl":"https://contoso.sharepoint.com/Budget.xlsx", \\ "size":0} ); defer t.deinit();
try testing.expectEqual(Kind.reference, t.attachment.kind); try testing.expectEqualStrings( "https://contoso.sharepoint.com/Budget.xlsx", t.attachment.source_url.?, ); try testing.expectEqual(@as(?[]const u8, null), t.attachment.content);}
test "the odata type, in every spelling it arrives in" { try testing.expectEqual(Kind.file, Kind.fromODataType("#microsoft.graph.fileAttachment")); try testing.expectEqual(Kind.file, Kind.fromODataType("microsoft.graph.fileAttachment")); try testing.expectEqual(Kind.file, Kind.fromODataType("fileAttachment")); try testing.expectEqual(Kind.item, Kind.fromODataType("#microsoft.graph.itemAttachment")); try testing.expectEqual( Kind.reference, Kind.fromODataType("#microsoft.graph.referenceAttachment"), ); // Something added since: not a file, and not an error either. try testing.expectEqual(Kind.unknown, Kind.fromODataType("#microsoft.graph.hologram")); try testing.expectEqual(Kind.unknown, Kind.fromODataType(""));}
test "an entry with no annotation is classified by what it carries" { var t = try TestAttachment.init("{\"id\":\"a\",\"contentBytes\":\"aGk=\"}"); defer t.deinit(); try testing.expectEqual(Kind.file, t.attachment.kind); try testing.expectEqualStrings("hi", t.attachment.content.?);}
test "content that will not decode is absent content, not a failed parse" { var t = try TestAttachment.init( \\{"@odata.type":"#microsoft.graph.fileAttachment","id":"a", \\ "name":"x","contentBytes":"!!! not base64 !!!"} ); defer t.deinit();
// The attachment still parses, and `has_content` is what distinguishes // "was not asked for" from "arrived and would not decode". try testing.expect(t.attachment.has_content); try testing.expectEqual(@as(?[]const u8, null), t.attachment.content);}
test "a file name from a stranger cannot escape the directory" { var buf: [256]u8 = undefined;
// The JSON is written out rather than built, so that what the test feeds // the parser is exactly what a hostile message would carry -- escapes // included. const cases = [_]struct { []const u8, []const u8 }{ .{ "{\"id\":\"a\",\"name\":\"smile.gif\"}", "smile.gif" }, .{ "{\"id\":\"a\",\"name\":\"../../etc/passwd\"}", ".._.._etc_passwd" }, .{ "{\"id\":\"a\",\"name\":\"/etc/passwd\"}", "_etc_passwd" }, .{ "{\"id\":\"a\",\"name\":\"..\\\\..\\\\windows\"}", ".._.._windows" }, .{ "{\"id\":\"a\",\"name\":\"with\\nnewline\"}", "with_newline" }, .{ "{\"id\":\"a\",\"name\":\"with\\u0000nul\"}", "with_nul" }, .{ "{\"id\":\"a\",\"name\":\"C:file.txt\"}", "C_file.txt" }, .{ "{\"id\":\"a\",\"name\":\"what?.txt\"}", "what_.txt" }, }; for (cases) |case| { const text, const expected = case; var t = try TestAttachment.init(text); defer t.deinit(); try testing.expectEqualStrings(expected, t.attachment.safeName(&buf)); }}
test "safeName never writes past the buffer it was given" { var t = try TestAttachment.init( "{\"id\":\"a\",\"name\":\"a-very-long-attachment-file-name.txt\"}", ); defer t.deinit();
var small: [8]u8 = undefined; const got = t.attachment.safeName(&small); try testing.expectEqual(@as(usize, 8), got.len); try testing.expectEqualStrings("a-very-l", got);}
test "a name that is no name at all gets one" { var buf: [256]u8 = undefined; for ([_][]const u8{ "{\"id\":\"a\"}", "{\"id\":\"a\",\"name\":\"\"}", "{\"id\":\"a\",\"name\":\"..\"}", "{\"id\":\"a\",\"name\":\".\"}" }) |text| { var t = try TestAttachment.init(text); defer t.deinit(); try testing.expectEqualStrings("attachment", t.attachment.safeName(&buf)); }}
test "no id is malformed" { var p = try std.json.parseFromSlice( std.json.Value, testing.allocator, "{\"name\":\"nameless\"}", .{}, ); defer p.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); try testing.expectError(error.Malformed, Attachment.fromJson(arena.allocator(), p.value));}