// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The `Authentication-Results` header field of [RFC //! 8601](https://datatracker.ietf.org/doc/html/rfc8601). //! //! Where `Received-SPF` records one mechanism's verdict, this records //! all of them in one place — and for DMARC that matters, because the //! DMARC result is only meaningful next to the SPF and DKIM results it //! was computed from. A `dmarc=fail` on its own tells a reader nothing //! about *why*; beside `spf=pass smtp.mailfrom=example.net` it tells //! them the message was authenticated by somebody who is not the domain //! in the `From:` field, which is the whole story. //! //! # This field is only worth what the receiver's own boundary is worth //! //! §7.1 of RFC 8601 is blunt about it: anyone can write an //! `Authentication-Results` field, so a receiver MUST remove any field //! bearing its own `authserv-id` from messages arriving from outside, //! before adding its own. This library writes the field; deleting the //! forgeries above it is the caller's, and nothing here can do it for //! them. //! //! Every value in the field came from the message being judged, so the //! escaping is the job rather than a detail — see `Received-SPF` in //! zig-spf for the same reasoning at greater length. const std = @import("std"); const Io = std.Io; const evaluation = @import("evaluate.zig"); const Record = @import("Record.zig"); pub const AuthResult = evaluation.AuthResult; /// Which SMTP identity SPF was run against. §2.7.2: the property is /// `mailfrom` or `helo`, and nothing else. pub const SpfIdentity = enum { mailfrom, helo, }; pub const Spf = struct { result: AuthResult, identity: SpfIdentity = .mailfrom, /// The address or domain that was checked. value: []const u8, }; pub const Dkim = struct { result: AuthResult, /// The signature's `d=`, reported as `header.d`. §2.7.1 is careful /// about this: the ptype is `header` and the property is a *tag* /// from the signature field, not a header field of its own. domain: []const u8, /// The signature's `s=`, if it is worth reporting. selector: ?[]const u8 = null, }; pub const Dmarc = struct { result: AuthResult, /// The domain of the `From:` field. RFC 7489 §11.1 registers the /// method with ptype `header` and property `from`, and this is its /// value. from_domain: []const u8, /// What the domain owner asked for, when the result was `fail`. /// Reported as a `policy.dmarc` property, which is not registered /// and so is written only when asked for — an unregistered property /// is an extension, and §2.3 asks that those be recognizable. policy: ?Record.Policy = null, }; /// One message's authentication results. pub const AuthenticationResults = struct { /// The receiving host, and the thing a reader has to trust before /// any of the rest means anything. §2.5 asks for a name the ADMD /// controls. authserv_id: []const u8, spf: ?Spf = null, dkim: []const Dkim = &.{}, dmarc: ?Dmarc = null, /// Writes the whole field, `Authentication-Results:` and the /// terminating CRLF included. Use the `{f}` specifier. pub fn format(results: AuthenticationResults, w: *Io.Writer) Io.Writer.Error!void { try w.writeAll("Authentication-Results: "); _ = try writeValue(w, results.authserv_id); var wrote_any = false; if (results.spf) |spf| { try w.writeAll(";\r\n "); try w.print("spf={t} smtp.{t}=", .{ spf.result, spf.identity }); _ = try writeValue(w, spf.value); wrote_any = true; } for (results.dkim) |dkim| { try w.writeAll(";\r\n "); try w.print("dkim={t} header.d=", .{dkim.result}); _ = try writeValue(w, dkim.domain); if (dkim.selector) |selector| { try w.writeAll(" header.s="); _ = try writeValue(w, selector); } wrote_any = true; } if (results.dmarc) |dmarc| { try w.writeAll(";\r\n "); try w.print("dmarc={t} header.from=", .{dmarc.result}); _ = try writeValue(w, dmarc.from_domain); if (dmarc.policy) |policy| { try w.print(" policy.dmarc={t}", .{policy}); } wrote_any = true; } // §2.2's `no-result`: the field still goes on, saying that this // host looked and did nothing. A reader can then tell "nobody // checked" from "the field was stripped". if (!wrote_any) try w.writeAll("; none"); try w.writeAll("\r\n"); } pub fn bufPrint( results: AuthenticationResults, buffer: []u8, ) Io.Writer.Error![]u8 { var w: Io.Writer = .fixed(buffer); try results.format(&w); return buffer[0..w.end]; } }; /// A `pvalue`: written bare when it is a token or an address, and as a /// quoted-string when it is not. /// /// §2.2 takes `value` from RFC 2045, whose `token` excludes the /// `tspecials` — and one of those is `@`, which every address contains, /// so the ABNF allows an address unquoted as a separate alternative. /// Anything else with a special in it has to be quoted, and a field that /// wrote it bare would parse as something shorter than what was written. fn writeValue(w: *Io.Writer, value: []const u8) Io.Writer.Error!usize { if (isBare(value)) { try w.writeAll(value); return value.len; } var written: usize = 2; try w.writeByte('"'); for (value) |byte| switch (byte) { '"', '\\' => { try w.writeByte('\\'); try w.writeByte(byte); written += 2; }, // There is no spelling of these that belongs in a header field, // and the alternative is a sender who can end the field and // begin one of their own. '\r', '\n' => {}, 0x00...0x08, 0x0b, 0x0c, 0x0e...0x1f, 0x7f...0xff => { try w.writeByte('?'); written += 1; }, else => { try w.writeByte(byte); written += 1; }, }; try w.writeByte('"'); return written; } fn isBare(value: []const u8) bool { if (value.len == 0) return false; var at_signs: usize = 0; for (value) |byte| { if (byte == '@') { at_signs += 1; continue; } if (!isToken(byte)) return false; } // At most one `@`, because what the ABNF allows unquoted besides a // token is an address, and an address has one. return at_signs <= 1; } /// RFC 2045 §5.1's `token`: anything but space, a control character, or /// one of the `tspecials`. fn isToken(byte: u8) bool { return switch (byte) { '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"' => false, '/', '[', ']', '?', '=' => false, ' ', 0x00...0x1f, 0x7f...0xff => false, else => true, }; } const testing = std.testing; test "the worked example of RFC 8601 appendix B.3" { var buffer: [512]u8 = undefined; const results: AuthenticationResults = .{ .authserv_id = "example.com", .spf = .{ .result = .pass, .identity = .mailfrom, .value = "example.net" }, }; try testing.expectEqualStrings( "Authentication-Results: example.com;\r\n" ++ " spf=pass smtp.mailfrom=example.net\r\n", try results.bufPrint(&buffer), ); } test "the three methods together, which is the point of the field" { var buffer: [1024]u8 = undefined; const results: AuthenticationResults = .{ .authserv_id = "mx.example.org", .spf = .{ .result = .pass, .value = "bounces.example.net" }, .dkim = &.{.{ .result = .pass, .domain = "example.net", .selector = "s1" }}, .dmarc = .{ .result = .fail, .from_domain = "example.com", .policy = .reject }, }; const text = try results.bufPrint(&buffer); // A `dmarc=fail` on its own says nothing about why. Beside the other // two it says the message was authenticated by somebody who is not // the domain in the `From:` field, which is the whole story. try testing.expect(std.mem.containsAtLeast(u8, text, 1, "spf=pass smtp.mailfrom=bounces.example.net")); try testing.expect(std.mem.containsAtLeast(u8, text, 1, "dkim=pass header.d=example.net header.s=s1")); try testing.expect(std.mem.containsAtLeast(u8, text, 1, "dmarc=fail header.from=example.com")); try testing.expect(std.mem.containsAtLeast(u8, text, 1, "policy.dmarc=reject")); } test "a host that checked nothing still says so" { var buffer: [256]u8 = undefined; const results: AuthenticationResults = .{ .authserv_id = "mx.example.org" }; // §2.2's `no-result`. A reader can then tell "nobody checked" from // "the field was stripped on the way". try testing.expectEqualStrings( "Authentication-Results: mx.example.org; none\r\n", try results.bufPrint(&buffer), ); } test "several signatures each get their own result" { var buffer: [1024]u8 = undefined; const results: AuthenticationResults = .{ .authserv_id = "mx.example.org", .dkim = &.{ .{ .result = .pass, .domain = "list.example.net" }, .{ .result = .fail, .domain = "example.com" }, }, }; const text = try results.bufPrint(&buffer); try testing.expect(std.mem.containsAtLeast(u8, text, 1, "dkim=pass header.d=list.example.net")); try testing.expect(std.mem.containsAtLeast(u8, text, 1, "dkim=fail header.d=example.com")); } test "a sender cannot write their own header fields" { var buffer: [1024]u8 = undefined; const results: AuthenticationResults = .{ .authserv_id = "mx.example.org", // Everything in this field came from the message being judged. .spf = .{ .result = .fail, .value = "evil.example.net\r\nX-Spam-Status: No\r\nFrom: bank@example.com", }, .dkim = &.{.{ .result = .pass, .domain = "a\"b; dmarc=pass header.from=bank.example" }}, }; const text = try results.bufPrint(&buffer); // Every line break in the output is one this code wrote: the field // name, or a fold. var lines = std.mem.splitSequence(u8, text, "\r\n"); while (lines.next()) |line| { if (line.len == 0) continue; try testing.expect(line[0] == 'A' or line[0] == ' '); } try testing.expect(!std.mem.containsAtLeast(u8, text, 1, "X-Spam-Status:\r\n")); // The quote and the semicolon that would have ended the quoted // string and started a result of the sender's own choosing. try testing.expect(std.mem.containsAtLeast(u8, text, 1, "\"a\\\"b; dmarc=pass header.from=bank.example\"")); } test "a bare token, an address, and everything else quoted" { var buffer: [512]u8 = undefined; // A domain is a token and needs no quotes. const plain: AuthenticationResults = .{ .authserv_id = "mx.example.org", .spf = .{ .result = .pass, .value = "example.com" }, }; try testing.expect(std.mem.containsAtLeast( u8, try plain.bufPrint(&buffer), 1, "smtp.mailfrom=example.com", )); // An address is the ABNF's other bare alternative, because `@` is a // tspecial and an address would otherwise never fit. const addressed: AuthenticationResults = .{ .authserv_id = "mx.example.org", .spf = .{ .result = .pass, .value = "alice@example.com" }, }; try testing.expect(std.mem.containsAtLeast( u8, try addressed.bufPrint(&buffer), 1, "smtp.mailfrom=alice@example.com", )); // Two of them is neither, so it is quoted. const doubled: AuthenticationResults = .{ .authserv_id = "mx.example.org", .spf = .{ .result = .pass, .value = "a@b@c" }, }; try testing.expect(std.mem.containsAtLeast( u8, try doubled.bufPrint(&buffer), 1, "smtp.mailfrom=\"a@b@c\"", )); } test "the SPF identity is named, because the two are different claims" { var buffer: [512]u8 = undefined; const helo: AuthenticationResults = .{ .authserv_id = "mx.example.org", .spf = .{ .result = .pass, .identity = .helo, .value = "mail.example.net" }, }; // A pass for the greeting says nothing about the envelope sender, // and a reader who could not tell which was checked would not know // that. try testing.expect(std.mem.containsAtLeast( u8, try helo.bufPrint(&buffer), 1, "spf=pass smtp.helo=mail.example.net", )); }