Skip to content

DKIM / SPF / DMARC Builder & Checker — Rust source

Build the three email-authentication DNS records — SPF, DKIM, and DMARC — as ready-to-paste TXT values, or look up a domain's live records over DNS-over-HTTPS. Import existing records, catch publishing mistakes, share via URL. Entirely client-side.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! dkim-spf-dmarc — Email authentication (SPF / DKIM / DMARC) record parsing.
//!
//! Language: Rust (std only — no external crates).
//! Ported from src/lib/dkim-spf-dmarc.ts
//! display source — part of CosmoDev's polyglot tool pages
//!
//! This file ports the pure parser layer of the TypeScript reference
//! (parse_spf / parse_dkim / parse_dmarc plus the shared domain helpers) —
//! deterministic, never panics on record input, testable without network.
//! The TS check functions add one DNS-over-HTTPS fetch to Cloudflare's
//! resolver; `std` has no HTTP client, so fetch the TXT records with your
//! platform resolver (or a reqwest/ureq call to the DoH JSON API) and feed
//! the newline-joined strings to the parsers. Map a parse to a status the
//! way the TS layer does: warnings empty → pass, else warn.
//!
//! Specs: SPF RFC 7208, DKIM RFC 6376, DMARC RFC 7489.

/// One parsed SPF term: the qualifier defaults to `+` when omitted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpfMechanism {
    pub qualifier: char, // '+', '-', '~' or '?'
    pub kind: String,    // all | include | a | mx | ip4 | ip6 | exists | ptr
    pub value: Option<String>,
}

/// Result of parsing one or more (newline-joined) SPF TXT strings.
#[derive(Debug, Clone, Default)]
pub struct SpfRecord {
    pub valid: bool,
    pub version: Option<String>,
    pub mechanisms: Vec<SpfMechanism>,
    pub redirect: Option<String>,
    pub exp: Option<String>,
    /// Mechanisms that cost a DNS query under RFC 7208 §4.6.4 (limit 10).
    pub lookup_count: usize,
    /// Number of `v=spf1` records found (more than one is a hard error).
    pub record_count: usize,
    pub warnings: Vec<String>,
}

/// Result of parsing a `<selector>._domainkey` TXT string.
#[derive(Debug, Clone, Default)]
pub struct DkimRecord {
    pub valid: bool,
    pub version: Option<String>,
    pub key_type: String,
    /// Public key, base64, whitespace-stripped.
    pub public_key: Option<String>,
    /// Approximate modulus size in bits (RSA only; from DER byte length).
    pub key_bits: Option<usize>,
    pub hashes: Vec<String>,
    pub services: Vec<String>,
    pub flags: Vec<String>,
    pub warnings: Vec<String>,
}

/// Result of parsing a `_dmarc` TXT string.
#[derive(Debug, Clone, Default)]
pub struct DmarcRecord {
    pub valid: bool,
    pub policy: Option<String>,         // none | quarantine | reject
    pub subdomain_policy: Option<String>, // none | quarantine | reject
    pub aggregate_uris: Vec<String>,
    pub forensic_uris: Vec<String>,
    pub percent: Option<u32>,
    pub dkim_alignment: Option<char>, // 'r' | 's'
    pub spf_alignment: Option<char>,  // 'r' | 's'
    pub warnings: Vec<String>,
}

/// Regex-free equivalents of the TS lib's DOMAIN_RE / SELECTOR_RE guards.
fn is_domain_char(c: char) -> bool {
    c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'
}

/// True when `domain` looks like a plausible multi-label domain (example.com).
pub fn is_domain_like(domain: &str) -> bool {
    if domain.len() > 253 {
        return false;
    }
    let labels: Vec<&str> = domain.split('.').collect();
    if labels.len() < 2 {
        return false;
    }
    // Every label: alnum start/end, hyphens only inside. TLD: alpha, 2+.
    labels.iter().enumerate().all(|(i, label)| {
        let chars: Vec<char> = label.chars().collect();
        if chars.len() < (if i + 1 == labels.len() { 2 } else { 1 }) {
            return false;
        }
        let body_ok = chars[0].is_ascii_lowercase() || chars[0].is_ascii_digit();
        let last_ok = chars[chars.len() - 1].is_ascii_lowercase() || chars[chars.len() - 1].is_ascii_digit();
        let tld_ok = i + 1 != labels.len() || chars.iter().all(|c| c.is_ascii_lowercase());
        body_ok && last_ok && tld_ok && chars.iter().all(|&c| is_domain_char(c))
    }) && domain.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '-')
}

/// True when the selector is a safe DNS label chain (no spaces, no traversal).
pub fn is_valid_selector(selector: &str) -> bool {
    let s = selector.trim();
    if s.is_empty() || s.len() > 100 || s.contains("..") {
        return false;
    }
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphanumeric() => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
}

/// Strip a leading scheme, userinfo, path, query, port, and trailing dot.
pub fn normalize_domain(raw: &str) -> String {
    let mut s = raw.trim().to_string();
    if let Some(pos) = s.find("://") {
        let scheme_ok = s[..pos].chars().next().map_or(false, |c| c.is_ascii_alphabetic())
            && s[..pos].chars().all(|c| c.is_ascii_alphanumeric() || "+.-".contains(c));
        if scheme_ok {
            s = s[pos + 3..].to_string();
        }
    }
    let lower = s.to_lowercase();
    if lower.starts_with("mailto:") {
        s = s[7..].to_string();
    }
    if let Some(at) = s.rfind('@') {
        s = s[at + 1..].to_string();
    }
    for stop in ['/', '?', ':'] {
        if let Some(pos) = s.find(stop) {
            s.truncate(pos);
        }
    }
    let trimmed = s.trim_end_matches('.').to_lowercase();
    trimmed
}

/// Strip one layer of surrounding double quotes, as TXT records carry.
fn unquote(value: &str) -> &str {
    if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') {
        &value[1..value.len() - 1]
    } else {
        value
    }
}

/// Split a `k=v; k=v` tag list into a map, recording malformed terms.
fn parse_tag_list(txt: &str, warnings: &mut Vec<String>) -> Vec<(String, String)> {
    let mut tags = Vec::new();
    for part in txt.split(';') {
        let term = unquote(part.trim()).trim();
        if term.is_empty() {
            continue;
        }
        match term.find('=') {
            Some(0) | None => warnings.push(format!("Malformed tag \"{term}\" ignored.")),
            Some(eq) => tags.push((term[..eq].trim().to_lowercase(), term[eq + 1..].trim().to_string())),
        }
    }
    tags
}

fn tag<'a>(tags: &'a [(String, String)], key: &str) -> Option<&'a str> {
    tags.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
}

fn colon_list(value: Option<&str>) -> Vec<String> {
    value.unwrap_or("").split(':').map(|s| s.trim()).filter(|s| !s.is_empty()).map(String::from).collect()
}

fn comma_list(value: Option<&str>) -> Vec<String> {
    value.unwrap_or("").split(',').map(|s| s.trim()).filter(|s| !s.is_empty()).map(String::from).collect()
}

const SPF_KINDS: [&str; 8] = ["all", "include", "a", "mx", "ip4", "ip6", "exists", "ptr"];
const DMARC_POLICIES: [&str; 3] = ["none", "quarantine", "reject"];

/// Parse one or more (newline-joined) TXT record strings for SPF. Pure.
pub fn parse_spf(txt: &str) -> SpfRecord {
    let lines: Vec<&str> = txt.split('\n').map(|l| unquote(l.trim())).filter(|l| !l.is_empty()).collect();
    let spf_lines: Vec<&str> = lines
        .iter()
        .cloned()
        .filter(|l| l.len() >= 6 && l[..6].eq_ignore_ascii_case("v=spf1") && (l.len() == 6 || l.as_bytes()[6].is_ascii_whitespace()))
        .collect();
    let mut record = SpfRecord::default();
    if spf_lines.is_empty() {
        record.warnings.push("No v=spf1 record found in the supplied text.".into());
        return record;
    }
    if spf_lines.len() > 1 {
        record.warnings.push(format!(
            "{} SPF records found — RFC 7208 allows exactly one. Receivers treat this as a permanent error and ignore SPF for the whole domain.",
            spf_lines.len()
        ));
    }
    record.record_count = spf_lines.len();
    record.valid = true;
    let terms: Vec<&str> = spf_lines[0].split_whitespace().collect();
    record.version = Some(terms[0].to_string());
    for term in &terms[1..] {
        // Modifiers use '=': redirect= and exp=
        if let Some(eq) = term.find('=') {
            let name = term[..eq].to_lowercase();
            if name.chars().next().map_or(false, |c| c.is_ascii_alphabetic())
                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
            {
                let value = term[eq + 1..].to_string();
                match name.as_str() {
                    "redirect" => record.redirect = Some(value),
                    "exp" => record.exp = Some(value),
                    _ => record.warnings.push(format!("Unknown modifier \"{term}\" ignored.")),
                }
                continue;
            }
        }
        // Mechanism: optional qualifier, kind, optional ":value".
        let bytes = term.as_bytes();
        let (qualifier, rest) = match bytes[0] {
            b'+' | b'-' | b'~' | b'?' => (bytes[0] as char, &term[1..]),
            _ => ('+', *term),
        };
        let (kind, value) = match rest.find(':') {
            Some(pos) => (&rest[..pos], Some(rest[pos + 1..].to_string())),
            None => (rest, None),
        };
        if kind.is_empty() || !kind.chars().all(|c| c.is_ascii_alphanumeric()) {
            record.warnings.push(format!("Unrecognized term \"{term}\" ignored."));
            continue;
        }
        let kind = kind.to_lowercase();
        if !SPF_KINDS.contains(&kind.as_str()) {
            record.warnings.push(format!("Unknown mechanism \"{term}\" ignored."));
            continue;
        }
        if value.as_deref().map_or(true, str::is_empty) && (kind == "include" || kind == "exists") {
            record.warnings.push(format!("Mechanism \"{term}\" is missing its required value."));
            continue;
        }
        record.mechanisms.push(SpfMechanism { qualifier, kind, value });
    }
    record.lookup_count = record.mechanisms.iter().filter(|m| matches!(m.kind.as_str(), "include" | "a" | "mx" | "exists" | "ptr")).count()
        + usize::from(record.redirect.is_some());
    let all = record.mechanisms.iter().find(|m| m.kind == "all");
    if all.is_none() && record.redirect.is_none() {
        record.warnings.push("No \"all\" mechanism and no \"redirect=\" — unmatched senders get a Neutral result, so anyone can still send mail that looks like this domain.".into());
    }
    if let Some(all) = all {
        match all.qualifier {
            '+' => record.warnings.push("\"+all\" explicitly allows every host on the internet to send mail as this domain — this defeats SPF entirely.".into()),
            '?' => record.warnings.push("\"?all\" (Neutral) lets unmatched senders through with no protection. Prefer \"~all\" or \"-all\".".into()),
            _ => {}
        }
    }
    if record.mechanisms.iter().any(|m| m.kind == "ptr") {
        record.warnings.push("The \"ptr\" mechanism is deprecated (RFC 7208 §5.5) and should not be used.".into());
    }
    if record.redirect.is_some() && all.is_some() {
        record.warnings.push("A \"redirect=\" modifier is ignored when an \"all\" mechanism is present.".into());
    }
    if record.lookup_count > 10 {
        record.warnings.push(format!(
            "{} DNS-lookup mechanisms — RFC 7208 §4.6.4 caps SPF at 10. Receivers that hit the cap return permerror and ignore the record.",
            record.lookup_count
        ));
    }
    record
}

/// Decode base64 to bytes without failing on bad input; missing padding is
/// added first because DKIM p= values are frequently published unpadded.
fn decode_base64_lenient(b64: &str) -> Option<Vec<u8>> {
    let clean: Vec<u8> = b64.chars().filter(|c| !c.is_whitespace()).map(|c| c as u8).collect();
    let mut padded = clean.clone();
    while padded.len() % 4 != 0 {
        padded.push(b'=');
    }
    let mut out = Vec::with_capacity(padded.len() * 3 / 4);
    for chunk in padded.chunks(4) {
        if chunk.len() != 4 {
            return None; // only possible when a '=' landed mid-group
        }
        let mut sextets = [0u8; 4];
        for (j, &byte) in chunk.iter().enumerate() {
            sextets[j] = match byte {
                b'A'..=b'Z' => byte - b'A',
                b'a'..=b'z' => byte - b'a' + 26,
                b'0'..=b'9' => byte - b'0' + 52,
                b'+' => 62,
                b'/' => 63,
                b'=' => 0, // padding contributes zero bits
                _ => return None,
            };
        }
        let triple = ((sextets[0] as u32) << 18) | ((sextets[1] as u32) << 12) | ((sextets[2] as u32) << 6) | sextets[3] as u32;
        let pad = chunk.iter().filter(|&&b| b == b'=').count();
        out.push((triple >> 16) as u8);
        if pad < 2 {
            out.push((triple >> 8) as u8);
        }
        if pad < 1 {
            out.push(triple as u8);
        }
    }
    // The TS lib decodes to a byte string; callers only need the length.
    Some(out)
}

/// Parse a `<selector>._domainkey` TXT record. Pure.
pub fn parse_dkim(txt: &str) -> DkimRecord {
    let mut warnings = Vec::new();
    let tags = parse_tag_list(txt, &mut warnings);
    let version = tag(&tags, "v").map(String::from);
    if let Some(v) = &version {
        if !v.eq_ignore_ascii_case("DKIM1") {
            warnings.push(format!("Unusual version tag v={v} (expected DKIM1)."));
        }
    }
    let key_type = tag(&tags, "k").unwrap_or("rsa").to_string();
    let p = tag(&tags, "p").map(String::from);
    let hashes = colon_list(tag(&tags, "h"));
    let services = colon_list(tag(&tags, "s"));
    let flags = colon_list(tag(&tags, "t"));
    let mut record = DkimRecord {
        valid: true,
        version: version.as_ref().map(|v| v.to_uppercase()),
        key_type,
        hashes,
        services,
        flags,
        ..DkimRecord::default()
    };
    let Some(p) = p else {
        record.valid = false;
        warnings.push("No p= tag — this record is not a usable DKIM key.".into());
        record.warnings = warnings;
        return record;
    };
    if p.is_empty() {
        warnings.push("p= is empty — the key is revoked. Receivers will treat mail signed with this selector as unsigned.".into());
        record.warnings = warnings;
        return record;
    }
    let Some(decoded) = decode_base64_lenient(&p) else {
        warnings.push("The p= value is not valid base64 — the key could not be read.".into());
        record.warnings = warnings;
        return record;
    };
    record.public_key = Some(p.chars().filter(|c| !c.is_whitespace()).collect());
    if record.key_type == "rsa" {
        // SubjectPublicKeyInfo DER ≈ modulus bits/8 + ~24 bytes of ASN.1 overhead.
        let bits = decoded.len().saturating_sub(24) * 8;
        record.key_bits = Some(bits);
        if bits < 1024 {
            warnings.push(format!("Weak RSA key (~{bits} bits). Keys under 1024 bits are considered breakable; RFC 8301 discourages short keys."));
        } else if bits < 2048 {
            warnings.push(format!("RSA key of ~{bits} bits works today but is below the recommended 2048 bits (RFC 8301)."));
        }
    }
    if record.flags.iter().any(|f| f == "y") {
        warnings.push("t=y — the key is in test mode: receivers must treat signatures as if unsigned.".into());
    }
    if record.flags.iter().any(|f| f == "s") {
        warnings.push("t=s — strict domain matching: the key cannot be used for subdomain signatures (informational).".into());
    }
    record.warnings = warnings;
    record
}

/// Parse a `_dmarc` TXT record. Pure.
pub fn parse_dmarc(txt: &str) -> DmarcRecord {
    let mut warnings = Vec::new();
    let tags = parse_tag_list(txt, &mut warnings);
    let mut record = DmarcRecord { valid: true, ..DmarcRecord::default() };
    let fail = |record: &mut DmarcRecord, warnings: &mut Vec<String>, message: &str| {
        record.valid = false;
        warnings.push(message.to_string());
        record.warnings = std::mem::take(warnings);
    };
    let Some(version) = tag(&tags, "v") else {
        fail(&mut record, &mut warnings, "No v= tag — this is not a DMARC record.");
        return record;
    };
    if !version.eq_ignore_ascii_case("DMARC1") {
        fail(&mut record, &mut warnings, &format!("Unknown version v={version} (expected DMARC1)."));
        return record;
    }
    let policy = tag(&tags, "p").unwrap_or("").to_lowercase();
    if policy.is_empty() {
        fail(&mut record, &mut warnings, "No p= policy tag — DMARC requires it.");
        return record;
    }
    if !DMARC_POLICIES.contains(&policy.as_str()) {
        fail(&mut record, &mut warnings, &format!("Invalid policy p={policy} (expected none, quarantine, or reject)."));
        return record;
    }
    record.policy = Some(policy);
    if let Some(sp) = tag(&tags, "sp").map(|s| s.to_lowercase()) {
        if DMARC_POLICIES.contains(&sp.as_str()) {
            record.subdomain_policy = Some(sp);
        } else {
            warnings.push(format!("Invalid sp={sp} ignored (expected none, quarantine, or reject)."));
        }
    }
    record.aggregate_uris = comma_list(tag(&tags, "rua"));
    record.forensic_uris = comma_list(tag(&tags, "ruf"));
    if let Some(pct) = tag(&tags, "pct") {
        match pct.parse::<u32>() {
            Ok(n) if n <= 100 => record.percent = Some(n),
            _ => warnings.push(format!("Invalid pct={pct} ignored (must be 0-100).")),
        }
    }
    for (name, slot) in [("adkim", &mut record.dkim_alignment), ("aspf", &mut record.spf_alignment)] {
        match tag(&tags, name) {
            Some("r") | Some("s") => *slot = Some(tag(&tags, name).unwrap().chars().next().unwrap()),
            Some(other) => warnings.push(format!("Invalid {name}={other} ignored (expected r or s).")),
            None => {}
        }
    }
    if record.policy.as_deref() == Some("none") {
        warnings.push("p=none is monitor-only — no mail is quarantined or rejected, but you still need SPF/DKIM to pass for reports to be useful.".into());
    }
    if record.aggregate_uris.is_empty() {
        warnings.push("No rua= address — without aggregate reports you cannot see who is failing authentication. Add rua=mailto:reports@example.com.".into());
    } else if !record.forensic_uris.is_empty() {
        warnings.push("ruf= (forensic reports) is supported by few receivers and may leak message content to the report address (informational).".into());
    }
    if let Some(percent) = record.percent {
        if percent < 100 && record.policy.as_deref() != Some("none") {
            warnings.push(format!("pct={percent} applies the policy to only {percent}% of mail — the other {}% is unaffected.", 100 - percent));
        }
    }
    record.warnings = warnings;
    record
}

/// The TS check layer maps a parse to a status: no warnings → pass, else warn.
pub fn status_from_warnings(warning_count: usize) -> &'static str {
    if warning_count > 0 { "warn" } else { "pass" }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →