// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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)); }