// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Drives the library against a real IMAP server — Dovecot, in the NixOS //! virtual machine test under `tests/nixos/` — rather than against a peer //! this repository wrote. //! //! That is the whole point of it. The unit tests say what RFC 9051 says, and //! `tests/e2e.zig` says that the client and a toy server agree with each //! other; neither can catch the mistakes where both ends of the conversation //! share an assumption no real implementation makes. A server nobody here //! wrote cannot quietly agree. //! //! Usage: //! //! imap-integration [--user NAME] [--password PASS] [--messages N] //! //! Run by `tests/nixos/dovecot.nix`, which seeds the mailbox it expects. //! Every check prints a line, so a failing run says which one went wrong and //! what the server had said just before. const std = @import("std"); const imap = @import("imap"); /// One of the seeded messages holds this line. If this string changes, /// change it in `tests/nixos/dovecot.nix` too — that file writes the /// mailbox. const marker_line = ".signature delimiters look like a terminator"; /// The non-ASCII mailbox the driver creates, which a rev1 server has to /// see in modified UTF-7 and list back the same way. const odd_mailbox = "Entw\xc3\xbcrfe"; var out_buffer: [4096]u8 = undefined; var out: *std.Io.Writer = undefined; pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; var stdout_writer = std.Io.File.stdout().writer(io, &out_buffer); out = &stdout_writer.interface; defer out.flush() catch {}; var host: ?[]const u8 = null; var user: []const u8 = "alice"; var password: []const u8 = "foobar"; var messages: u32 = 3; var args = init.minimal.args.iterate(); _ = args.next(); while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--user")) { user = args.next() orelse return usage(); } else if (std.mem.eql(u8, arg, "--password")) { password = args.next() orelse return usage(); } else if (std.mem.eql(u8, arg, "--messages")) { messages = try std.fmt.parseUnsigned(u32, args.next() orelse return usage(), 10); } else if (host == null) { host = arg; } else { return usage(); } } const server = host orelse return usage(); try plaintextRefusesThePassword(gpa, io, server, user, password); const validity = try overStartTls(gpa, io, server, user, password, messages); try overImplicitTls(gpa, io, server, user, password, messages, validity); try mailboxesAndAppend(gpa, io, server, user, password); try deletionsHappenOnExpunge(gpa, io, server, user, password, messages); try out.writeAll("all checks passed\n"); } fn usage() noreturn { std.process.fatal( "usage: imap-integration [--user NAME] [--password PASS] [--messages N]", .{}, ); } // -- the phases -------------------------------------------------------------- /// Dovecot refuses a cleartext password from anywhere but localhost, and /// says so up front with LOGINDISABLED. The library's job is to refuse /// before sending anything, twice over: once because the transport is in /// the clear, and once because the server said not to. fn plaintextRefusesThePassword( gpa: std.mem.Allocator, io: std.Io, server: []const u8, user: []const u8, password: []const u8, ) !void { try out.writeAll("-- plaintext, port 143\n"); const conn = try imap.Connection.connect(gpa, io, server, .{ .tls = .off }); defer conn.destroy(); var client = conn.client(); try check(conn.security() == .plaintext, "the connection knows it is in the clear"); const greeting = try client.readGreeting(); try out.print(" greeting: {s}\n", .{greeting.text}); try check(greeting.status == .ok, "a login is needed"); try check(client.capabilities.known, "the greeting carried the capabilities"); try printCaps(&client.capabilities); try check(client.capabilities.starttls, "STARTTLS advertised before the handshake"); try check(client.capabilities.logindisabled, "LOGIN disabled in the clear"); try check(!client.capabilities.auth.any(), "and no AUTH= mechanism offered either"); try check( failedWith(client.login(user, password), error.LoginDisabled), "LOGIN is refused because the server disabled it", ); client.capabilities.logindisabled = false; try check( failedWith(client.login(user, password), error.InsecureTransport), "and because the transport is in the clear", ); try check( failedWith(client.authenticate(user, password), error.InsecureTransport), "with nothing safe to choose instead", ); try client.logout(); try check(client.bye, "the server said BYE"); } /// STARTTLS on the plaintext port, with the certificate verified against /// the root this machine was given — the upgrade path of RFC 9051, against a /// real TLS server. fn overStartTls( gpa: std.mem.Allocator, io: std.Io, server: []const u8, user: []const u8, password: []const u8, messages: u32, ) !u32 { try out.writeAll("-- STARTTLS, port 143 upgraded in place\n"); const conn = try imap.Connection.connect(gpa, io, server, .{ .tls = .off }); defer conn.destroy(); var client = conn.client(); _ = try client.readGreeting(); const before = client.capabilities; try check(before.starttls, "STARTTLS advertised"); try conn.startTls(&client, .{ .host = server }); try check(conn.security() == .encrypted, "the connection is encrypted afterwards"); try check(client.security == .encrypted, "and so is the client"); try check(!client.capabilities.known, "the pre-handshake capabilities were forgotten"); // RFC 9051 requires the pre-handshake list be thrown away, and this is // why: what comes back is not the same list. const after = try client.capability(); try printCaps(&after); try check(!after.starttls, "STARTTLS is gone once TLS is up"); try check(!after.logindisabled, "LOGIN is allowed now"); try check( after.auth.has("PLAIN") and !before.auth.has("PLAIN"), "AUTH=PLAIN appears only once the connection is private", ); // No override this time: the transport is encrypted, so the library is // willing. try check(client.allow_cleartext_auth == false, "no cleartext override needed"); const mechanism = try client.authenticate(user, password); try out.print(" authenticated with {t}\n", .{mechanism}); try check(mechanism == .plain, "AUTHENTICATE PLAIN was chosen over LOGIN"); const mailbox = try client.select("INBOX"); try transaction(gpa, &client, mailbox, messages); try client.logout(); return mailbox.uidvalidity.?; } /// IMAPS on 993: implicit TLS, which RFC 8314 prefers to the upgrade above. fn overImplicitTls( gpa: std.mem.Allocator, io: std.Io, server: []const u8, user: []const u8, password: []const u8, messages: u32, previous_validity: u32, ) !void { try out.writeAll("-- IMAPS, port 993\n"); const conn = try imap.Connection.connect(gpa, io, server, .{ .tls = .on }); defer conn.destroy(); var client = conn.client(); _ = try client.readGreeting(); try check(!client.capabilities.starttls, "STARTTLS is not advertised on the implicit-TLS port"); try check(client.capabilities.auth.has("PLAIN"), "AUTH=PLAIN is"); // LOGIN by name rather than through `authenticate`, so that the other // way in is driven against a real server too. try client.login(user, password); try out.writeAll(" authenticated with LOGIN\n"); const mailbox = try client.examine("INBOX"); try check(mailbox.read_only, "EXAMINE opens read-only"); try check( mailbox.uidvalidity.? == previous_validity, "UIDVALIDITY is unchanged across sessions", ); try transaction(gpa, &client, mailbox, messages); // IDLE, and the way out of it. Nothing will happen, which is the // common case; the point is that DONE is answered. var idling = try client.idle(); try idling.done(); try check(true, "IDLE and DONE"); try client.unselect(); try check(client.mailbox == null, "UNSELECT deselects"); try client.logout(); } /// CREATE, LIST, APPEND, STATUS and DELETE, on a mailbox whose name is not /// ASCII — which a rev1 server has to be sent in modified UTF-7 and has to /// list back in it, and which a rev2 server with UTF8=ACCEPT takes as it /// is. Either way the name that comes back has to be the one that went in. fn mailboxesAndAppend( gpa: std.mem.Allocator, io: std.Io, server: []const u8, user: []const u8, password: []const u8, ) !void { try out.writeAll("-- mailboxes\n"); const conn = try imap.Connection.connect(gpa, io, server, .{ .tls = .on }); defer conn.destroy(); var client = conn.client(); _ = try client.readGreeting(); _ = try client.authenticate(user, password); if (client.capabilities.utf8_accept) { try check(try client.enable("UTF8=ACCEPT"), "UTF8=ACCEPT enabled"); } else { try out.writeAll(" (no UTF8=ACCEPT: names go as modified UTF-7)\n"); } client.delete(odd_mailbox) catch {}; try client.create(odd_mailbox); try check(true, "CREATE with a non-ASCII name"); var mailboxes = try client.listAlloc(gpa, "", "*", .{}); defer mailboxes.deinit(gpa); var inbox_seen = false; var odd_seen = false; for (mailboxes.entries) |entry| { try out.print(" LIST: {s}\n", .{entry.name}); if (std.mem.eql(u8, entry.name, "INBOX")) inbox_seen = true; if (std.mem.eql(u8, entry.name, odd_mailbox)) odd_seen = true; } try check(inbox_seen, "INBOX is listed"); try check(odd_seen, "and so is the new mailbox, decoded to the name that was given"); const message = "From: root@server\r\nTo: alice@server\r\nSubject: appended\r\n" ++ "Message-ID: \r\n\r\nThis message was appended by the client.\r\n"; const result = try client.append(odd_mailbox, .{ .flags = "\\Seen" }, message); try check(result != null, "APPEND reports the new UID (UIDPLUS)"); try out.print(" APPENDUID {d} {s}\n", .{ result.?.uidvalidity, result.?.uids }); const status = try client.status(odd_mailbox, "MESSAGES UNSEEN UIDNEXT"); try check(status.messages.? == 1, "STATUS counts the appended message"); try check(status.unseen.? == 0, "which was appended \\Seen"); // Fetched back, it is exactly what went in: the octet count Dovecot // reports is the count the client delivers. const mailbox = try client.select(odd_mailbox); try check(mailbox.exists == 1, "SELECT sees it too"); var back: std.Io.Writer.Allocating = .init(gpa); defer back.deinit(); const uid = try std.fmt.parseUnsigned(u32, result.?.uids, 10); const n = try client.fetchTo(&back.writer, .uid, uid, "", .{}); try check(n == message.len, "the appended message comes back the same size"); try check(std.mem.eql(u8, back.written(), message), "and byte for byte"); try client.close(); try client.delete(odd_mailbox); try check(true, "DELETE"); try client.logout(); } /// STORE marks, EXPUNGE removes, and a flag removed before then is a /// message kept: checked across two sessions because that is the only /// place it is visible. fn deletionsHappenOnExpunge( gpa: std.mem.Allocator, io: std.Io, server: []const u8, user: []const u8, password: []const u8, messages: u32, ) !void { try out.writeAll("-- deletion, across sessions\n"); // Marked and unmarked: nothing may happen. { const conn = try imap.Connection.connect(gpa, io, server, .{ .tls = .on }); defer conn.destroy(); var client = conn.client(); _ = try client.readGreeting(); try client.login(user, password); _ = try client.select("INBOX"); try client.store(.sequence, "1", .add, "\\Deleted", .{}); const marked = try client.searchAlloc(gpa, .sequence, "DELETED"); defer gpa.free(marked); try check(marked.len == 1 and marked[0] == 1, "SEARCH DELETED finds the marked message"); try client.store(.sequence, "1", .remove, "\\Deleted", .{}); try client.expunge(); try check(client.mailbox.?.exists == messages, "EXPUNGE after unmarking removes nothing"); try client.logout(); } // Marked and expunged: now it is gone for good. { const conn = try imap.Connection.connect(gpa, io, server, .{ .tls = .on }); defer conn.destroy(); var client = conn.client(); _ = try client.readGreeting(); try client.login(user, password); _ = try client.select("INBOX"); try client.store(.sequence, "1", .add, "\\Deleted", .{}); try client.expunge(); try check(client.mailbox.?.exists == messages - 1, "EXPUNGE reports the removal"); try client.logout(); } { const conn = try imap.Connection.connect(gpa, io, server, .{ .tls = .on }); defer conn.destroy(); var client = conn.client(); _ = try client.readGreeting(); try client.login(user, password); const mailbox = try client.select("INBOX"); try out.print(" {d} messages left\n", .{mailbox.exists}); try check(mailbox.exists == messages - 1, "and the next session agrees"); try client.logout(); } } // -- what every selected session is asked ------------------------------------ /// The selected-state commands, and the properties that only a real server /// can be held to. fn transaction(gpa: std.mem.Allocator, client: *imap.Client, mailbox: imap.Mailbox, messages: u32) !void { try out.print(" SELECT: {d} messages, UIDVALIDITY {?d}, UIDNEXT {?d}\n", .{ mailbox.exists, mailbox.uidvalidity, mailbox.uidnext, }); try check(mailbox.exists == messages, "EXISTS counts the seeded messages"); try check(mailbox.uidvalidity != null, "UIDVALIDITY was given"); try check(mailbox.flags.has("\\Seen"), "FLAGS include \\Seen"); const all = try client.searchAlloc(gpa, .uid, "ALL"); defer gpa.free(all); try check(all.len == messages, "UID SEARCH ALL lists them all"); var marker_seen = false; for (all) |uid| { // The size the server reports is the size of what it sends, so the // two disagreeing means the client mishandled a literal or a line // ending. Nothing in a test against our own server could establish // that; Dovecot counted these octets itself. var summary = try client.fetchAlloc(gpa, .uid, uid, "(RFC822.SIZE ENVELOPE)", .limited(1 << 16)); defer summary.deinit(gpa); var size: ?u64 = null; var subject: ?imap.String = null; var items = summary.items(); while (try items.next()) |item| { if (item.is("RFC822.SIZE")) size = item.value.number(); if (item.is("ENVELOPE")) subject = (try imap.Envelope.parse(item.value.list)).subject; } try check(size != null and subject != null, "FETCH gives a size and an envelope"); var body: std.Io.Writer.Allocating = .init(gpa); defer body.deinit(); const n = try client.fetchTo(&body.writer, .uid, uid, "", .{}); try check(n == size.?, "BODY[] is exactly as many octets as RFC822.SIZE promised"); try check(std.mem.indexOf(u8, body.written(), "Subject:") != null, "and it has headers"); var lines = std.mem.splitSequence(u8, body.written(), "\r\n"); while (lines.next()) |line| { if (std.mem.eql(u8, line, marker_line)) marker_seen = true; } // Fetching with BODY.PEEK must not have set \Seen. var flags = try client.fetchAlloc(gpa, .uid, uid, "(FLAGS)", .limited(1024)); defer flags.deinit(gpa); var flag_items = flags.items(); var seen = false; while (try flag_items.next()) |item| { if (item.is("FLAGS") and imap.parser.listContains(item.value.list, "\\Seen")) seen = true; } try check(!seen, "BODY.PEEK left the message unseen"); } try check(marker_seen, "a line beginning with a dot arrives as it is"); // Headers alone. var headers: std.Io.Writer.Allocating = .init(gpa); defer headers.deinit(); _ = try client.fetchTo(&headers.writer, .uid, all[0], "HEADER", .{}); try check(std.mem.endsWith(u8, headers.written(), "\r\n\r\n"), "BODY[HEADER] ends at the header break"); try client.noop(); var none: std.Io.Writer.Allocating = .init(gpa); defer none.deinit(); try check( failedWith(client.fetchTo(&none.writer, .uid, all[all.len - 1] + 1000, "", .{}), error.NoSuchMessage), "a UID past the end fetches nothing", ); } /// Whether a call failed with exactly this error. Written out rather than /// compared directly, because an error union carrying a payload is not /// something to compare against an error value. fn failedWith(result: anytype, expected: anyerror) bool { if (result) |_| return false else |err| return err == expected; } fn printCaps(caps: *const imap.Capabilities) !void { try out.print(" capabilities: {s}\n", .{caps.raw.list()}); } /// Reports one check and fails the run if it did not hold. There is no /// `std.testing` here: this is a program, not a test binary. fn check(ok: bool, what: []const u8) !void { try out.print(" {s} {s}\n", .{ if (ok) "ok " else "FAIL", what }); if (!ok) { try out.flush(); return error.CheckFailed; } }