// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A `v=DMARC1` record, parsed but not applied. //! //! The grammar is [RFC 7489 //! §6.4](https://datatracker.ietf.org/doc/html/rfc7489#section-6.4) — //! DKIM's tag-value syntax, with a fixed first tag and everything else //! in any order. Nothing here allocates: every value is a slice of the //! record text the caller still owns. //! //! What a DMARC record says is short: *what did you mean by the domain //! in the `From:` field, and what should I do when a message does not //! live up to it*. Everything else in the record is about reporting. const std = @import("std"); const Record = @This(); /// What the domain owner asks a receiver to do with a message that /// fails. §6.3's `p`. pub const Policy = enum { /// "Tell me, but deliver it." Where every sensible deployment /// starts, and where a great many stay. none, /// "Treat it as suspicious." What that means is the receiver's. quarantine, /// "Refuse it," during the SMTP transaction if possible. reject, fn parse(text: []const u8) ?Policy { if (std.ascii.eqlIgnoreCase(text, "none")) return .none; if (std.ascii.eqlIgnoreCase(text, "quarantine")) return .quarantine; if (std.ascii.eqlIgnoreCase(text, "reject")) return .reject; return null; } }; /// How closely an authenticated identifier has to match the `From:` /// domain. §3.1. pub const Alignment = enum { /// The two need only share an organizational domain, so a message /// signed by `example.com` may say `From: news.example.com`. The /// default, and what makes DMARC deployable by an organization that /// sends from more than one subdomain. relaxed, /// The names must match exactly. strict, fn parse(text: []const u8) ?Alignment { if (std.ascii.eqlIgnoreCase(text, "r")) return .relaxed; if (std.ascii.eqlIgnoreCase(text, "s")) return .strict; return null; } }; /// §4.10's `psd`, which is what makes the tree walk terminate /// correctly: it says whether the name that published this record is a /// public suffix — a name under which anyone may register — or an /// organization's own. /// /// The tag is from the coming revision rather than from RFC 7489, and /// it is here because the walk is: without it there is no way to tell /// `example.com` from `co.uk` by looking, which is the whole problem a /// public suffix list was invented to solve. pub const Psd = enum { /// `y`: this name is a public suffix, so an organization's domain is /// one label below it. yes, /// `n`: this name is an organizational domain — for itself and for /// everything under it. The walk stops here. no, /// The tag was absent, which is the ordinary case. unstated, fn parse(text: []const u8) ?Psd { if (std.ascii.eqlIgnoreCase(text, "y")) return .yes; if (std.ascii.eqlIgnoreCase(text, "n")) return .no; if (std.ascii.eqlIgnoreCase(text, "u")) return .unstated; return null; } }; /// When to ask for a failure report. §6.3's `fo`, which is a /// colon-separated list rather than one value. pub const FailureOptions = packed struct { /// `0`: report when *every* mechanism failed to produce an aligned /// pass. The default, and the quietest. all_failed: bool = false, /// `1`: report when *any* mechanism produced something other than /// an aligned pass. Much noisier, and what an operator actually /// wants while working out where their mail comes from. any_failed: bool = false, /// `d`: report a DKIM signature that failed to verify, aligned or /// not. dkim_failed: bool = false, /// `s`: report an SPF failure, aligned or not. spf_failed: bool = false, }; /// §6.6.3 step 5 and step 6: the ways a name can fail to yield a policy. /// None of them is an error in the mail — DMARC simply does not apply. pub const Error = error{ /// The text does not begin with `v=DMARC1`. /// /// Kept apart from the rest for the same reason SPF keeps its /// version check apart: §6.6.3 discards records failing this test /// while *selecting* one, so a domain whose TXT records are /// something else has no DMARC policy rather than a broken one. NotDmarc, /// A record with no usable `p` tag and no `rua` to fall back on. /// §6.6.3 step 6: with a reporting address such a record is treated /// as `p=none` and without one it is not treated at all, so the /// decision needs the whole record and is made here. NoPolicy, }; /// `p`. Never null: a record that reaches the caller has a policy, even /// if §6.6.3 step 6 had to supply `none` for it. policy: Policy, /// `sp`, the policy for subdomains of this one. Null means "the same as /// `policy`", which is what §6.3 says the absence of the tag means. subdomain_policy: ?Policy = null, /// `np`, the policy for subdomains that do not exist at all — RFC /// 9091's addition, and the sharpest tag in the record. /// /// A name nobody registered cannot be sending legitimate mail, so a /// domain owner can say `reject` for those while leaving real /// subdomains alone. Null falls back to `sp`, then to `p`. non_existent_policy: ?Policy = null, /// `psd`. See `Psd`. psd: Psd = .unstated, /// `adkim`. dkim_alignment: Alignment = .relaxed, /// `aspf`. spf_alignment: Alignment = .relaxed, /// `pct`: the share of failing mail the policy is applied to, for an /// operator rolling one out. 0 to 100. percent: u8 = 100, /// `rua`, unparsed: a comma-separated list of URIs, each with an /// optional `!size` limit. Reporting is not this library's job, so the /// list is handed over as written. aggregate_reports: ?[]const u8 = null, /// `ruf`, likewise. failure_reports: ?[]const u8 = null, /// `fo`. failure_options: FailureOptions = .{ .all_failed = true }, /// `rf`, the requested failure report format. Only `afrf` is defined. report_format: ?[]const u8 = null, /// `ri`, requested seconds between aggregate reports. The default is a /// day, and §6.3 warns that it is a request rather than a promise. report_interval: u32 = 86400, /// True when §6.6.3 step 6 had to supply the policy because the record /// did not carry a usable one. /// /// Worth reporting rather than hiding: the domain owner published /// something they believed was a policy and it is not being applied. assumed_policy: bool = false, /// Whether `text` claims to be a DMARC record at all: a `v` tag whose /// value is `DMARC1`, first. /// /// §6.6.3 steps 2 and 4 apply this to every TXT record at a name before /// any of them is parsed, which is how a domain's DMARC record is picked /// out of the ownership tokens it shares a name with. pub fn isDmarc(text: []const u8) bool { var rest = std.mem.trimStart(u8, text, " \t"); if (rest.len == 0 or (rest[0] != 'v' and rest[0] != 'V')) return false; rest = std.mem.trimStart(u8, rest[1..], " \t"); if (rest.len == 0 or rest[0] != '=') return false; rest = std.mem.trimStart(u8, rest[1..], " \t"); if (!std.ascii.startsWithIgnoreCase(rest, "DMARC1")) return false; // The version must end there: `v=DMARC1x` is a different version and // not one this understands. const after = rest["DMARC1".len..]; const end = std.mem.trimStart(u8, after, " \t"); return end.len == 0 or end[0] == ';'; } /// Parses a record. /// /// Unknown tags are ignored, which §6.3 requires — the tag registry is /// meant to grow, and a receiver that refused a record carrying a tag it /// had not heard of would stop honouring policies the day one was added. /// A *known* tag with an unusable value falls back to its default for /// the same reason, except for `p` and `sp`, where §6.6.3 makes the /// question of whether there is a policy at all turn on it. pub fn parse(text: []const u8) Error!Record { if (!isDmarc(text)) return error.NotDmarc; var record: Record = .{ .policy = .none }; var found_policy = false; var bad_subdomain_policy = false; var tags = std.mem.splitScalar(u8, text, ';'); // The version, already checked by `isDmarc`. _ = tags.next(); while (tags.next()) |tag| { const trimmed = std.mem.trim(u8, tag, " \t"); if (trimmed.len == 0) continue; const equals = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; const name = std.mem.trim(u8, trimmed[0..equals], " \t"); const value = std.mem.trim(u8, trimmed[equals + 1 ..], " \t"); if (std.ascii.eqlIgnoreCase(name, "p")) { if (Policy.parse(value)) |policy| { record.policy = policy; found_policy = true; } } else if (std.ascii.eqlIgnoreCase(name, "sp")) { if (Policy.parse(value)) |policy| { record.subdomain_policy = policy; } else { bad_subdomain_policy = true; } } else if (std.ascii.eqlIgnoreCase(name, "np")) { if (Policy.parse(value)) |policy| { record.non_existent_policy = policy; } else { bad_subdomain_policy = true; } } else if (std.ascii.eqlIgnoreCase(name, "psd")) { if (Psd.parse(value)) |psd| record.psd = psd; } else if (std.ascii.eqlIgnoreCase(name, "adkim")) { if (Alignment.parse(value)) |alignment| record.dkim_alignment = alignment; } else if (std.ascii.eqlIgnoreCase(name, "aspf")) { if (Alignment.parse(value)) |alignment| record.spf_alignment = alignment; } else if (std.ascii.eqlIgnoreCase(name, "pct")) { if (std.fmt.parseInt(u8, value, 10) catch null) |percent| { if (percent <= 100) record.percent = percent; } } else if (std.ascii.eqlIgnoreCase(name, "ri")) { if (std.fmt.parseInt(u32, value, 10) catch null) |interval| { record.report_interval = interval; } } else if (std.ascii.eqlIgnoreCase(name, "rua")) { if (value.len > 0) record.aggregate_reports = value; } else if (std.ascii.eqlIgnoreCase(name, "ruf")) { if (value.len > 0) record.failure_reports = value; } else if (std.ascii.eqlIgnoreCase(name, "rf")) { if (value.len > 0) record.report_format = value; } else if (std.ascii.eqlIgnoreCase(name, "fo")) { record.failure_options = parseFailureOptions(value); } // Anything else is a tag from a later extension, and §6.3 says // to ignore it. } // §6.6.3 step 6, which is the one piece of policy *discovery* that // can only be decided from the record itself. A record with no // usable policy but a reporting address is a domain owner watching // rather than asking for anything, so it is read as `p=none`; one // with neither is not a policy record at all. if (!found_policy or bad_subdomain_policy) { if (record.aggregate_reports == null) return error.NoPolicy; record.policy = .none; record.subdomain_policy = null; record.non_existent_policy = null; record.assumed_policy = true; } return record; } fn parseFailureOptions(value: []const u8) FailureOptions { var options: FailureOptions = .{}; var any = false; var parts = std.mem.splitScalar(u8, value, ':'); while (parts.next()) |part| { const trimmed = std.mem.trim(u8, part, " \t"); if (trimmed.len != 1) continue; switch (trimmed[0]) { '0' => options.all_failed = true, '1' => options.any_failed = true, 'd', 'D' => options.dkim_failed = true, 's', 'S' => options.spf_failed = true, else => continue, } any = true; } return if (any) options else .{ .all_failed = true }; } /// The policy that applies to `name`, given that this record was found /// at `owner`. /// /// The distinction `sp` draws is the whole reason policy discovery walks /// upwards: an organization can say "reject anything claiming to be /// `example.com`" while leaving a subdomain it has not finished /// inventorying at `none`. pub fn policyFor(record: Record, owner: []const u8, name: []const u8, exists: bool) Policy { const same = std.ascii.eqlIgnoreCase( std.mem.trimEnd(u8, owner, "."), std.mem.trimEnd(u8, name, "."), ); if (same) return record.policy; // A name nobody registered cannot be sending legitimate mail, so // `np` is looked at first and is usually the strictest of the three. if (!exists) { if (record.non_existent_policy) |policy| return policy; } return record.subdomain_policy orelse record.policy; } const testing = std.testing; test "the shape of a record people actually publish" { const record = try parse("v=DMARC1; p=reject; rua=mailto:dmarc@example.com; pct=100"); try testing.expectEqual(Policy.reject, record.policy); try testing.expectEqual(@as(?Policy, null), record.subdomain_policy); try testing.expectEqual(Alignment.relaxed, record.dkim_alignment); try testing.expectEqual(Alignment.relaxed, record.spf_alignment); try testing.expectEqual(@as(u8, 100), record.percent); try testing.expectEqualStrings("mailto:dmarc@example.com", record.aggregate_reports.?); try testing.expect(!record.assumed_policy); } test "every tag" { const record = try parse( "v=DMARC1; p=quarantine; sp=none; adkim=s; aspf=s; pct=25;" ++ " rua=mailto:a@example.com,mailto:b@example.net!10m;" ++ " ruf=mailto:f@example.com; fo=1:d:s; rf=afrf; ri=3600", ); try testing.expectEqual(Policy.quarantine, record.policy); try testing.expectEqual(Policy.none, record.subdomain_policy.?); try testing.expectEqual(Alignment.strict, record.dkim_alignment); try testing.expectEqual(Alignment.strict, record.spf_alignment); try testing.expectEqual(@as(u8, 25), record.percent); try testing.expectEqualStrings( "mailto:a@example.com,mailto:b@example.net!10m", record.aggregate_reports.?, ); try testing.expectEqualStrings("mailto:f@example.com", record.failure_reports.?); try testing.expectEqualStrings("afrf", record.report_format.?); try testing.expectEqual(@as(u32, 3600), record.report_interval); try testing.expect(record.failure_options.any_failed); try testing.expect(record.failure_options.dkim_failed); try testing.expect(record.failure_options.spf_failed); try testing.expect(!record.failure_options.all_failed); } test "the version must be first and must be this version" { _ = try parse("v=DMARC1; p=none"); // §6.4 allows whitespace around the separators. _ = try parse("v = DMARC1 ; p = none"); _ = try parse("V=dmarc1; p=none"); try testing.expectError(error.NotDmarc, parse("p=reject; v=DMARC1")); try testing.expectError(error.NotDmarc, parse("v=DMARC2; p=none")); try testing.expectError(error.NotDmarc, parse("v=DMARC10; p=none")); try testing.expectError(error.NotDmarc, parse("v=spf1 -all")); try testing.expectError(error.NotDmarc, parse("")); // A TXT record that is something else entirely, which is what a // `_dmarc` name shares space with in the real world. try testing.expectError(error.NotDmarc, parse("google-site-verification=abc")); } test "a record with no usable policy" { // §6.6.3 step 6: with a reporting address, a domain owner who has // published something unusable is watching rather than asking, so // the record is read as `p=none` and reports still go out. const watching = try parse("v=DMARC1; rua=mailto:dmarc@example.com"); try testing.expectEqual(Policy.none, watching.policy); try testing.expect(watching.assumed_policy); // An `sp` that is not a policy poisons the record the same way, // because a receiver cannot tell which half the owner meant. const confused = try parse("v=DMARC1; p=reject; sp=maybe; rua=mailto:d@example.com"); try testing.expectEqual(Policy.none, confused.policy); try testing.expectEqual(@as(?Policy, null), confused.subdomain_policy); try testing.expect(confused.assumed_policy); // Without one there is nothing to do and nobody to tell, so DMARC // does not apply at all. try testing.expectError(error.NoPolicy, parse("v=DMARC1")); try testing.expectError(error.NoPolicy, parse("v=DMARC1; p=maybe")); try testing.expectError(error.NoPolicy, parse("v=DMARC1; p=reject; sp=maybe")); } test "an unknown tag is ignored rather than fatal" { // §6.3: the registry is meant to grow. A receiver that refused a // record carrying a tag it had not heard of would stop honouring // policies the day one was added. const record = try parse("v=DMARC1; p=reject; unknown=whatever; x-thing=1"); try testing.expectEqual(Policy.reject, record.policy); try testing.expect(!record.assumed_policy); } test "np is for names nobody registered" { const record = try parse("v=DMARC1; p=none; sp=quarantine; np=reject"); // The domain itself. try testing.expectEqual(Policy.none, record.policyFor("example.com", "example.com", true)); // A subdomain that exists. try testing.expectEqual( Policy.quarantine, record.policyFor("example.com", "news.example.com", true), ); // And one that does not, which cannot be sending legitimate mail — // so a domain owner can be strict about those while leaving the // real ones alone. try testing.expectEqual( Policy.reject, record.policyFor("example.com", "typo.example.com", false), ); // Without `np`, a non-existent subdomain falls back to `sp`. const without = try parse("v=DMARC1; p=none; sp=quarantine"); try testing.expectEqual( Policy.quarantine, without.policyFor("example.com", "typo.example.com", false), ); // An `np` that is not a policy poisons the record the way `sp` does. try testing.expectError(error.NoPolicy, parse("v=DMARC1; p=reject; np=maybe")); } test "psd says whether a name is one anybody may register under" { try testing.expectEqual(Psd.yes, (try parse("v=DMARC1; p=reject; psd=y")).psd); try testing.expectEqual(Psd.no, (try parse("v=DMARC1; p=reject; psd=n")).psd); try testing.expectEqual(Psd.unstated, (try parse("v=DMARC1; p=reject; psd=u")).psd); try testing.expectEqual(Psd.unstated, (try parse("v=DMARC1; p=reject")).psd); // An unusable value is not fatal, like every tag but `p`, `sp` and // `np`. try testing.expectEqual(Psd.unstated, (try parse("v=DMARC1; p=reject; psd=maybe")).psd); } test "a known tag with an unusable value falls back to its default" { // Everywhere except `p` and `sp`, where §6.6.3 makes the question of // whether there is a policy at all turn on the value. const record = try parse("v=DMARC1; p=reject; pct=200; adkim=maybe; ri=soon"); try testing.expectEqual(Policy.reject, record.policy); try testing.expectEqual(@as(u8, 100), record.percent); try testing.expectEqual(Alignment.relaxed, record.dkim_alignment); try testing.expectEqual(@as(u32, 86400), record.report_interval); } test "sp is what the walk upwards is for" { const record = try parse("v=DMARC1; p=reject; sp=none"); // The domain that published it gets `p`. try testing.expectEqual(Policy.reject, record.policyFor("example.com", "example.com", true)); try testing.expectEqual(Policy.reject, record.policyFor("example.com", "example.com.", true)); // Anything under it gets `sp` — which is how an organization // refuses forgeries of its own name while leaving a subdomain it has // not finished inventorying alone. try testing.expectEqual(Policy.none, record.policyFor("example.com", "news.example.com", true)); // With no `sp`, subdomains inherit. const plain = try parse("v=DMARC1; p=quarantine"); try testing.expectEqual(Policy.quarantine, plain.policyFor("example.com", "news.example.com", true)); } test "a trailing semicolon and stray whitespace" { // §6.4's `[dmarc-sep]` at the end, and `*WSP` everywhere. const record = try parse(" v=DMARC1 ; p = reject ; adkim = s ; "); try testing.expectEqual(Policy.reject, record.policy); try testing.expectEqual(Alignment.strict, record.dkim_alignment); }