Skip to main content

khive_runtime/
outbound_email_policy.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
5use sha2::{Digest, Sha256};
6
7/// The unsubscribe token format version carried as the first token byte.
8const UNSUBSCRIBE_TOKEN_VERSION: u8 = 0x01;
9/// A raw recipient key is one SHA-256 digest.
10const RECIPIENT_KEY_BYTES: usize = 32;
11/// The truncated HMAC tag length carried by a token.
12const UNSUBSCRIBE_TAG_BYTES: usize = 16;
13/// A token is `0x01 || key_id || recipient_key || tag`, base64url (no padding).
14const UNSUBSCRIBE_TOKEN_BYTES: usize = 1 + 1 + RECIPIENT_KEY_BYTES + UNSUBSCRIBE_TAG_BYTES;
15/// The placeholder the operator's footer must carry for the mailto instruction.
16const UNSUBSCRIBE_PLACEHOLDER: &str = "{unsubscribe}";
17/// A recipient-key secret and every token key must decode to at least this many bytes.
18const MIN_KEY_BYTES: usize = 32;
19
20const LIST_FOOTER_ENV: &str = "KHIVE_EMAIL_LIST_FOOTER_FILE";
21
22const MIRROR_URL_ENV: &str = "KHIVE_EMAIL_SUPPRESSION_MIRROR_URL";
23const MIRROR_TOKEN_ENV: &str = "KHIVE_EMAIL_SUPPRESSION_MIRROR_TOKEN";
24const MIRROR_MAX_AGE_ENV: &str = "KHIVE_EMAIL_SUPPRESSION_MIRROR_MAX_AGE_SECS";
25
26/// The remote suppression mirror (ADR-200 §6): the URL that answers the complete set of
27/// suppressed recipient keys, the bearer credential that reads it, and how old the last
28/// successful refresh may be before external admission refuses.
29#[derive(Clone)]
30pub struct SuppressionMirror {
31    url: Arc<str>,
32    credential: Arc<str>,
33    max_age: std::time::Duration,
34}
35
36impl SuppressionMirror {
37    /// The URL the delivery component reads the complete remote set from.
38    pub fn url(&self) -> &str {
39        &self.url
40    }
41
42    /// The bearer credential for the read. It is never written to a log or an error.
43    pub fn credential(&self) -> &str {
44        &self.credential
45    }
46
47    /// The age past which the last successful refresh no longer admits an external message.
48    pub fn max_age(&self) -> std::time::Duration {
49        self.max_age
50    }
51}
52
53/// Boot-resolved recipient policy shared by comm admission and email delivery.
54/// An absent policy permits queuing without claiming that delivery is configured.
55#[derive(Clone)]
56pub struct OutboundEmailPolicy {
57    recipients: Option<Arc<[String]>>,
58    external_senders: Option<Arc<[String]>>,
59    external_daily_cap: Option<u64>,
60    /// The recipient-key secret. Present only when external senders are configured; the derived
61    /// key for an address is `HMAC-SHA256(K_rk, normalized address)` in lowercase hex.
62    recipient_key_secret: Option<Arc<[u8]>>,
63    /// Token keys by key id, ascending. Every retired id stays present so a link in an old
64    /// message keeps verifying; the highest id mints new tokens.
65    token_keys: Arc<BTreeMap<u8, Arc<[u8]>>>,
66    /// The operator's external footer text, or the reason it is unavailable. `None` while
67    /// external senders are unset, in which case no footer is ever consulted.
68    external_footer: Option<Result<Arc<str>, Arc<str>>>,
69    /// The separate list footer for external `traffic:list` messages. It never falls back to
70    /// the default external footer; `None` only while external senders are unset.
71    list_footer: Option<Result<Arc<str>, Arc<str>>>,
72    /// The remote suppression mirror. `None` when it is not configured or external senders are
73    /// unset.
74    suppression_mirror: Option<SuppressionMirror>,
75    external_admission: Arc<tokio::sync::Mutex<()>>,
76}
77
78impl Default for OutboundEmailPolicy {
79    fn default() -> Self {
80        Self {
81            recipients: None,
82            external_senders: None,
83            external_daily_cap: None,
84            recipient_key_secret: None,
85            token_keys: Arc::default(),
86            external_footer: None,
87            list_footer: None,
88            suppression_mirror: None,
89            external_admission: Arc::new(tokio::sync::Mutex::new(())),
90        }
91    }
92}
93
94/// HMAC-SHA256 (RFC 2104) over `sha2::Sha256`.
95///
96/// The 64-byte block is fixed for SHA-256. A key longer than the block is hashed first; a
97/// shorter one is zero-padded to the block. Returns the full 32-byte MAC.
98fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
99    const BLOCK: usize = 64;
100    let mut block = [0u8; BLOCK];
101    if key.len() > BLOCK {
102        block[..32].copy_from_slice(&Sha256::digest(key));
103    } else {
104        block[..key.len()].copy_from_slice(key);
105    }
106    let mut inner_pad = [0x36u8; BLOCK];
107    let mut outer_pad = [0x5cu8; BLOCK];
108    for index in 0..BLOCK {
109        inner_pad[index] ^= block[index];
110        outer_pad[index] ^= block[index];
111    }
112    let mut inner = Sha256::new();
113    inner.update(inner_pad);
114    inner.update(data);
115    let inner_digest = inner.finalize();
116    let mut outer = Sha256::new();
117    outer.update(outer_pad);
118    outer.update(inner_digest);
119    let mut mac = [0u8; 32];
120    mac.copy_from_slice(&outer.finalize());
121    mac
122}
123
124/// The direction stored on one email suppression entry.
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub enum EmailSuppressionScope {
127    Outbound,
128    Inbound,
129}
130
131/// The identity form stored on one email suppression entry.
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub enum EmailSuppressionKind {
134    Address,
135    Domain,
136    RecipientKey,
137}
138
139/// The matching fields needed by outbound admission and delivery.
140#[derive(Clone, Debug, PartialEq, Eq)]
141pub struct EmailSuppression {
142    pub scope: EmailSuppressionScope,
143    pub kind: EmailSuppressionKind,
144    pub value: String,
145}
146
147/// Check one already-normalized recipient against the suppression rows supplied by the caller.
148///
149/// Address normalization is shared with [`OutboundEmailPolicy`]; callers must use
150/// `khive_types::email_address::normalize_email_recipient` before calling this function.
151/// Domain comparison is exact, and recipient keys compare byte-for-byte.
152pub fn outbound_email_is_suppressed(
153    normalized_recipient: &str,
154    recipient_key: Option<&str>,
155    entries: &[EmailSuppression],
156) -> bool {
157    let recipient_domain = normalized_recipient
158        .rsplit_once('@')
159        .map(|(_, domain)| domain);
160    entries.iter().any(|entry| {
161        if entry.scope != EmailSuppressionScope::Outbound {
162            return false;
163        }
164        match entry.kind {
165            EmailSuppressionKind::Address => entry.value == normalized_recipient,
166            EmailSuppressionKind::Domain => recipient_domain == Some(entry.value.as_str()),
167            EmailSuppressionKind::RecipientKey => recipient_key == Some(entry.value.as_str()),
168        }
169    })
170}
171
172/// Check one already-normalized inbound sender address against the suppression rows supplied by
173/// the caller. Only `inbound` entries can match, and only `address` and `domain` kinds can: an
174/// inbound sender has no recipient key. Address comparison is exact after normalization, and
175/// domain comparison is exact with no subdomain wildcard, so a `domain` entry for `example.com`
176/// never blocks `user@sub.example.com`.
177///
178/// Callers must normalize the sender address with
179/// `khive_types::email_address::normalize_email_recipient` before calling this function.
180pub fn inbound_email_is_suppressed(normalized_sender: &str, entries: &[EmailSuppression]) -> bool {
181    let sender_domain = normalized_sender.rsplit_once('@').map(|(_, domain)| domain);
182    entries.iter().any(|entry| {
183        if entry.scope != EmailSuppressionScope::Inbound {
184            return false;
185        }
186        match entry.kind {
187            EmailSuppressionKind::Address => entry.value == normalized_sender,
188            EmailSuppressionKind::Domain => sender_domain == Some(entry.value.as_str()),
189            EmailSuppressionKind::RecipientKey => false,
190        }
191    })
192}
193
194impl OutboundEmailPolicy {
195    /// Install a normalized recipient set; an explicitly empty set denies all recipients.
196    pub fn configured(recipients: Vec<String>) -> Result<Self, String> {
197        let recipients = recipients
198            .iter()
199            .map(|value| {
200                khive_types::email_address::normalize_email_recipient(value)
201                    .ok_or_else(|| "outbound email policy contains an invalid address".to_string())
202            })
203            .collect::<Result<Vec<_>, _>>()?;
204        Ok(Self {
205            recipients: Some(recipients.into()),
206            ..Self::default()
207        })
208    }
209
210    pub fn is_configured(&self) -> bool {
211        self.recipients.is_some()
212    }
213
214    pub fn allows(&self, recipient: &str) -> bool {
215        self.recipients.as_ref().is_none_or(|recipients| {
216            khive_types::email_address::normalize_email_recipient(recipient)
217                .is_some_and(|recipient| recipients.iter().any(|allowed| allowed == &recipient))
218        })
219    }
220
221    pub fn allows_external_sender(&self, actor_id: &str) -> bool {
222        self.external_senders
223            .as_ref()
224            .is_some_and(|senders| senders.iter().any(|sender| sender == actor_id))
225    }
226
227    pub fn has_external_senders(&self) -> bool {
228        self.external_senders.is_some()
229    }
230
231    pub fn external_daily_cap(&self) -> Option<u64> {
232        self.external_daily_cap
233    }
234
235    pub async fn lock_external_admission(&self) -> tokio::sync::OwnedMutexGuard<()> {
236        Arc::clone(&self.external_admission).lock_owned().await
237    }
238
239    /// The recipient key a `recipient_key` suppression entry matches, derived on demand as
240    /// `HMAC-SHA256(K_rk, normalized address)` in lowercase hex; the raw bytes are never stored.
241    /// `None` when no recipient-key secret is configured (external senders unset).
242    pub fn recipient_key(&self, normalized_recipient: &str) -> Option<String> {
243        self.recipient_key_secret
244            .as_deref()
245            .map(|secret| hex_lower(&hmac_sha256(secret, normalized_recipient.as_bytes())))
246    }
247
248    /// The recipient key's raw 32 bytes, used as the token body.
249    fn recipient_key_bytes(&self, normalized_recipient: &str) -> Option<[u8; RECIPIENT_KEY_BYTES]> {
250        self.recipient_key_secret
251            .as_deref()
252            .map(|secret| hmac_sha256(secret, normalized_recipient.as_bytes()))
253    }
254
255    /// The footer text for external messages, or the reason it is unavailable. `None` while
256    /// external senders are unset.
257    pub fn external_footer(&self) -> Option<Result<&str, &str>> {
258        self.external_footer.as_ref().map(|value| {
259            value
260                .as_ref()
261                .map(|text| &**text)
262                .map_err(|reason| &**reason)
263        })
264    }
265
266    /// The separate footer for external list traffic, or the reason it is unavailable.
267    /// `None` while external senders are unset; never consults the default footer.
268    pub fn list_footer(&self) -> Option<Result<&str, &str>> {
269        self.list_footer.as_ref().map(|value| {
270            value
271                .as_ref()
272                .map(|text| &**text)
273                .map_err(|reason| &**reason)
274        })
275    }
276
277    /// Select the footer for an external send. List traffic never falls back to the default.
278    pub fn external_footer_for_list(&self, is_list: bool) -> Option<Result<&str, &str>> {
279        if is_list {
280            self.list_footer()
281        } else {
282            self.external_footer()
283        }
284    }
285
286    fn resolve_list_footer(&mut self, path: Option<&str>) {
287        if self.has_external_senders() {
288            self.list_footer = Some(read_list_footer(path));
289        }
290    }
291
292    /// The remote suppression mirror, when one is configured (ADR-200 §6).
293    pub fn suppression_mirror(&self) -> Option<&SuppressionMirror> {
294        self.suppression_mirror.as_ref()
295    }
296
297    /// Mint the unsubscribe token for a normalized external recipient, or `None` when the
298    /// recipient-key secret or any token key is unavailable. The highest configured key id mints.
299    pub fn mint_unsubscribe_token(&self, normalized_recipient: &str) -> Option<String> {
300        let recipient_key = self.recipient_key_bytes(normalized_recipient)?;
301        let (&key_id, key) = self.token_keys.iter().next_back()?;
302        Some(encode_unsubscribe_token(key_id, key, &recipient_key))
303    }
304
305    /// Verify an unsubscribe token and return the recipient key text it identifies, or `None`
306    /// on any malformed input or tag mismatch. Retired key ids keep verifying.
307    pub fn verify_unsubscribe_token(&self, token: &str) -> Option<String> {
308        let decoded = URL_SAFE_NO_PAD.decode(token).ok()?;
309        if decoded.len() != UNSUBSCRIBE_TOKEN_BYTES {
310            return None;
311        }
312        if decoded[0] != UNSUBSCRIBE_TOKEN_VERSION {
313            return None;
314        }
315        let key_id = decoded[1];
316        let key = self.token_keys.get(&key_id)?;
317        let (body, tag) = decoded.split_at(decoded.len() - UNSUBSCRIBE_TAG_BYTES);
318        let expected = hmac_sha256(key, body);
319        if !constant_time_eq(&expected[..UNSUBSCRIBE_TAG_BYTES], tag) {
320            return None;
321        }
322        let recipient_key = &body[2..];
323        Some(hex_lower(recipient_key))
324    }
325
326    /// Read only public policy inputs, without loading a connector or credentials.
327    ///
328    /// The unsubscribe key variables, the footer files and the suppression mirror variables are
329    /// read only when external senders are configured; while the senders variable is unset none
330    /// of them is consulted.
331    pub fn from_env() -> Result<Self, String> {
332        fn read(name: &str) -> Result<Option<String>, String> {
333            match std::env::var(name) {
334                Ok(value) => Ok(Some(value)),
335                Err(std::env::VarError::NotPresent) => Ok(None),
336                Err(std::env::VarError::NotUnicode(_)) => {
337                    Err(format!("{name} must contain valid Unicode text"))
338                }
339            }
340        }
341        let external_senders = read("KHIVE_EMAIL_EXTERNAL_SENDERS")?;
342        let external_daily_cap = read("KHIVE_EMAIL_EXTERNAL_DAILY_CAP")?;
343        let explicit = read("KHIVE_EMAIL_SEND_ALLOWED_RECIPIENTS")?;
344        let maintainer = read("KHIVE_EMAIL_MAINTAINER_ADDRESS")?;
345        let (recipient_key_secret, token_keys) = if external_senders.is_some() {
346            (
347                read("KHIVE_EMAIL_UNSUBSCRIBE_RK_KEY")?,
348                read("KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS")?,
349            )
350        } else {
351            (None, None)
352        };
353        let footer_file = if external_senders.is_some() {
354            read("KHIVE_EMAIL_EXTERNAL_FOOTER_FILE")?
355        } else {
356            None
357        };
358        let list_footer_file = if external_senders.is_some() {
359            read(LIST_FOOTER_ENV)?
360        } else {
361            None
362        };
363        let (mirror_url, mirror_token, mirror_max_age) = if external_senders.is_some() {
364            (
365                read(MIRROR_URL_ENV)?,
366                read(MIRROR_TOKEN_ENV)?,
367                read(MIRROR_MAX_AGE_ENV)?,
368            )
369        } else {
370            (None, None, None)
371        };
372        let mut policy = Self::resolve_with_external(
373            explicit.as_deref(),
374            maintainer.as_deref(),
375            external_senders.as_deref(),
376            external_daily_cap.as_deref(),
377            recipient_key_secret.as_deref(),
378            token_keys.as_deref(),
379            footer_file.as_deref(),
380        )?;
381        policy.resolve_list_footer(list_footer_file.as_deref());
382        policy.suppression_mirror = parse_suppression_mirror(
383            mirror_url.as_deref(),
384            mirror_token.as_deref(),
385            mirror_max_age.as_deref(),
386        )?;
387        Ok(policy)
388    }
389
390    #[cfg(test)]
391    fn resolve(explicit: Option<&str>, maintainer: Option<&str>) -> Result<Self, String> {
392        Self::resolve_with_external(explicit, maintainer, None, None, None, None, None)
393    }
394
395    /// Build a fully enabled policy for debug-build tests: recipients, the external sender
396    /// set, the daily cap, fixed test key material and a footer carrying `{unsubscribe}`.
397    #[cfg(any(test, debug_assertions))]
398    #[doc(hidden)]
399    pub fn configured_for_tests(
400        recipients: Vec<String>,
401        external_senders: Vec<String>,
402        daily_cap: u64,
403    ) -> Result<Self, String> {
404        let token_keys = format!("0:{},1:{}", "11".repeat(32), "22".repeat(32));
405        Self::configured_for_tests_with(
406            recipients,
407            external_senders,
408            daily_cap,
409            &"cc".repeat(32),
410            &token_keys,
411            Ok("Reply to unsubscribe: {unsubscribe}"),
412        )
413    }
414
415    /// Build an enabled policy with explicit key material and footer state for tests that need
416    /// to exercise configuration or footer unavailability.
417    #[cfg(any(test, debug_assertions))]
418    #[doc(hidden)]
419    #[allow(clippy::too_many_arguments)]
420    pub fn configured_for_tests_with(
421        recipients: Vec<String>,
422        external_senders: Vec<String>,
423        daily_cap: u64,
424        recipient_key_secret_hex: &str,
425        token_keys: &str,
426        footer: Result<&str, &str>,
427    ) -> Result<Self, String> {
428        if daily_cap == 0 {
429            return Err("KHIVE_EMAIL_EXTERNAL_DAILY_CAP must be a positive integer".into());
430        }
431        let external_senders = parse_external_senders(&external_senders.join(","))?;
432        if external_senders.is_empty() {
433            return Err("KHIVE_EMAIL_EXTERNAL_SENDERS must contain at least one actor id".into());
434        }
435        let mut policy = Self::configured(recipients)?;
436        policy.external_senders = Some(external_senders.into());
437        policy.external_daily_cap = Some(daily_cap);
438        let secret = parse_hex_key("KHIVE_EMAIL_UNSUBSCRIBE_RK_KEY", recipient_key_secret_hex)?;
439        policy.recipient_key_secret = Some(Arc::from(secret.as_slice()));
440        policy.token_keys = Arc::new(parse_token_keys(token_keys)?);
441        policy.external_footer = Some(footer.map(Arc::from).map_err(Arc::from));
442        policy.resolve_list_footer(None);
443        Ok(policy)
444    }
445
446    /// Replace the footer state on a test policy (available/unavailable) without touching keys.
447    #[cfg(any(test, debug_assertions))]
448    #[doc(hidden)]
449    pub fn with_external_footer_for_tests(mut self, footer: Result<&str, &str>) -> Self {
450        self.external_footer = Some(footer.map(Arc::from).map_err(Arc::from));
451        self
452    }
453
454    /// Replace the list footer state on a test policy without changing the default footer.
455    #[cfg(any(test, debug_assertions))]
456    #[doc(hidden)]
457    pub fn with_list_footer_for_tests(mut self, footer: Result<&str, &str>) -> Self {
458        self.list_footer = Some(footer.map(Arc::from).map_err(Arc::from));
459        self
460    }
461
462    /// Attach a remote suppression mirror to a test policy. Any URL is accepted, so a test can
463    /// point the mirror at a local listener.
464    #[cfg(any(test, debug_assertions))]
465    #[doc(hidden)]
466    pub fn with_suppression_mirror_for_tests(
467        mut self,
468        url: &str,
469        credential: &str,
470        max_age: std::time::Duration,
471    ) -> Self {
472        self.suppression_mirror = Some(SuppressionMirror {
473            url: Arc::from(url),
474            credential: Arc::from(credential),
475            max_age,
476        });
477        self
478    }
479
480    #[allow(clippy::too_many_arguments)]
481    fn resolve_with_external(
482        explicit: Option<&str>,
483        maintainer: Option<&str>,
484        external_senders: Option<&str>,
485        external_daily_cap: Option<&str>,
486        recipient_key_secret: Option<&str>,
487        token_keys: Option<&str>,
488        footer_file: Option<&str>,
489    ) -> Result<Self, String> {
490        let senders = external_senders.map(parse_external_senders).transpose()?;
491        let cap = match external_daily_cap {
492            Some(value) => {
493                let parsed = value.parse::<u64>().map_err(|_| {
494                    "KHIVE_EMAIL_EXTERNAL_DAILY_CAP must be a positive integer".to_string()
495                })?;
496                if parsed == 0 {
497                    return Err("KHIVE_EMAIL_EXTERNAL_DAILY_CAP must be a positive integer".into());
498                }
499                Some(parsed)
500            }
501            None if senders.is_some() => {
502                return Err("KHIVE_EMAIL_EXTERNAL_DAILY_CAP is required when KHIVE_EMAIL_EXTERNAL_SENDERS is set".into());
503            }
504            None => None,
505        };
506        let mut policy = Self::resolve_recipients(explicit, maintainer)?;
507        policy.external_daily_cap = cap;
508        if let Some(senders) = senders {
509            policy.external_senders = Some(senders.into());
510            let recipient_key_secret = parse_hex_key(
511                "KHIVE_EMAIL_UNSUBSCRIBE_RK_KEY",
512                recipient_key_secret.ok_or_else(|| {
513                    "KHIVE_EMAIL_UNSUBSCRIBE_RK_KEY is required when KHIVE_EMAIL_EXTERNAL_SENDERS is set".to_string()
514                })?,
515            )?;
516            let token_keys = parse_token_keys(token_keys.ok_or_else(|| {
517                "KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS is required when KHIVE_EMAIL_EXTERNAL_SENDERS is set".to_string()
518            })?)?;
519            policy.recipient_key_secret = Some(Arc::from(recipient_key_secret.as_slice()));
520            policy.token_keys = Arc::new(token_keys);
521            policy.external_footer = Some(read_external_footer(footer_file));
522            policy.resolve_list_footer(None);
523        }
524        Ok(policy)
525    }
526
527    fn resolve_recipients(
528        explicit: Option<&str>,
529        maintainer: Option<&str>,
530    ) -> Result<Self, String> {
531        if let Some(policy) = Self::explicit(explicit)? {
532            // A present maintainer value is read the way the email connector reads it at
533            // start, so a value the connector would refuse is refused here too, even
534            // when the explicit list supplies the recipients. An unset one is not an error.
535            if let Some(raw) = maintainer {
536                Self::maintainer_primary(raw)?;
537            }
538            return Ok(policy);
539        }
540        Self::maintainer(maintainer, explicit.is_some())
541    }
542
543    fn explicit(raw: Option<&str>) -> Result<Option<Self>, String> {
544        let recipients: Vec<String> = raw
545            .unwrap_or_default()
546            .split(',')
547            .map(str::trim)
548            .filter(|value| !value.is_empty())
549            .map(str::to_owned)
550            .collect();
551        if recipients.is_empty() {
552            return Ok(None);
553        }
554        Self::configured(recipients)
555            .map(Some)
556            .map_err(|_| "KHIVE_EMAIL_SEND_ALLOWED_RECIPIENTS contains an invalid address".into())
557    }
558
559    fn maintainer(raw: Option<&str>, explicit_was_set: bool) -> Result<Self, String> {
560        let Some(raw) = raw else {
561            if explicit_was_set {
562                return Err(
563                    "configured outbound email policy must contain at least one address".into(),
564                );
565            }
566            return Ok(Self::default());
567        };
568        Self::configured(vec![Self::maintainer_primary(raw)?])
569    }
570
571    /// Validate a present maintainer value and return its first (primary) address:
572    /// split on commas, trim, drop empty values, every remaining value must parse
573    /// and at least one must remain.
574    fn maintainer_primary(raw: &str) -> Result<String, String> {
575        let addresses = raw
576            .split(',')
577            .map(str::trim)
578            .filter(|value| !value.is_empty())
579            .map(|value| {
580                khive_types::email_address::normalize_email_recipient(value).ok_or_else(|| {
581                    "KHIVE_EMAIL_MAINTAINER_ADDRESS contains an invalid address".to_string()
582                })
583            })
584            .collect::<Result<Vec<_>, _>>()?;
585        let Some(primary) = addresses.into_iter().next() else {
586            return Err("KHIVE_EMAIL_MAINTAINER_ADDRESS must contain at least one address".into());
587        };
588        Ok(primary)
589    }
590}
591
592/// Parse the remote suppression mirror's variables (ADR-200 §6). All three unset means no
593/// mirror. The URL requires the other two, and either of the other two without the URL is an
594/// error, so a partly configured mirror is refused at start instead of reading as an absent one.
595/// No error repeats the credential.
596fn parse_suppression_mirror(
597    url: Option<&str>,
598    credential: Option<&str>,
599    max_age: Option<&str>,
600) -> Result<Option<SuppressionMirror>, String> {
601    let Some(url) = url else {
602        if credential.is_some() {
603            return Err(format!(
604                "{MIRROR_TOKEN_ENV} is set but {MIRROR_URL_ENV} is not"
605            ));
606        }
607        if max_age.is_some() {
608            return Err(format!(
609                "{MIRROR_MAX_AGE_ENV} is set but {MIRROR_URL_ENV} is not"
610            ));
611        }
612        return Ok(None);
613    };
614    let host = url
615        .strip_prefix("https://")
616        .ok_or_else(|| format!("{MIRROR_URL_ENV} must be an https:// URL"))?;
617    if host.is_empty()
618        || host.starts_with('/')
619        || url.chars().any(|c| c.is_whitespace() || c.is_control())
620    {
621        return Err(format!(
622            "{MIRROR_URL_ENV} must be an https:// URL with a host"
623        ));
624    }
625    let credential = credential
626        .ok_or_else(|| format!("{MIRROR_TOKEN_ENV} is required when {MIRROR_URL_ENV} is set"))?;
627    if credential.is_empty() || !credential.bytes().all(|byte| byte.is_ascii_graphic()) {
628        return Err(format!(
629            "{MIRROR_TOKEN_ENV} must be non-empty printable ASCII without spaces"
630        ));
631    }
632    let max_age = max_age
633        .ok_or_else(|| format!("{MIRROR_MAX_AGE_ENV} is required when {MIRROR_URL_ENV} is set"))?;
634    let seconds = max_age
635        .parse::<u64>()
636        .ok()
637        .filter(|seconds| *seconds > 0)
638        .ok_or_else(|| format!("{MIRROR_MAX_AGE_ENV} must be a positive integer"))?;
639    Ok(Some(SuppressionMirror {
640        url: Arc::from(url),
641        credential: Arc::from(credential),
642        max_age: std::time::Duration::from_secs(seconds),
643    }))
644}
645
646fn parse_external_senders(raw: &str) -> Result<Vec<String>, String> {
647    raw.split(',')
648        .map(str::trim)
649        .map(|actor_id| {
650            if actor_id.is_empty() {
651                return Err("KHIVE_EMAIL_EXTERNAL_SENDERS contains an empty actor id".to_string());
652            }
653            khive_types::Namespace::parse(actor_id).map_err(|_| {
654                format!("KHIVE_EMAIL_EXTERNAL_SENDERS contains an invalid actor id {actor_id:?}")
655            })?;
656            Ok(actor_id.to_string())
657        })
658        .collect()
659}
660
661/// Decode a hex key for `name`, requiring at least [`MIN_KEY_BYTES`] bytes. The value is never
662/// echoed in the error.
663fn parse_hex_key(name: &str, raw: &str) -> Result<Vec<u8>, String> {
664    let value = raw.trim().to_ascii_lowercase();
665    if !value.len().is_multiple_of(2) || !khive_types::is_lowercase_hex(&value) {
666        return Err(format!(
667            "{name} must be hex-encoded key material of at least {MIN_KEY_BYTES} bytes"
668        ));
669    }
670    let mut bytes = Vec::with_capacity(value.len() / 2);
671    for pair in value.as_bytes().chunks_exact(2) {
672        let high = (pair[0] as char)
673            .to_digit(16)
674            .expect("validated lowercase hex");
675        let low = (pair[1] as char)
676            .to_digit(16)
677            .expect("validated lowercase hex");
678        bytes.push((high * 16 + low) as u8);
679    }
680    if bytes.len() < MIN_KEY_BYTES {
681        return Err(format!(
682            "{name} must be hex-encoded key material of at least {MIN_KEY_BYTES} bytes"
683        ));
684    }
685    Ok(bytes)
686}
687
688/// Parse `KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS`: comma-separated `id:key` pairs, `id` a decimal
689/// integer 0-255, no duplicate ids, key material hex of at least [`MIN_KEY_BYTES`] bytes.
690fn parse_token_keys(raw: &str) -> Result<BTreeMap<u8, Arc<[u8]>>, String> {
691    const NAME: &str = "KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS";
692    let mut keys = BTreeMap::new();
693    for pair in raw.split(',') {
694        let pair = pair.trim();
695        if pair.is_empty() {
696            return Err(format!("{NAME} contains an empty `id:key` pair"));
697        }
698        let Some((id_text, key_text)) = pair.split_once(':') else {
699            return Err(format!("{NAME} entries must be `id:key` pairs"));
700        };
701        let id = id_text
702            .trim()
703            .parse::<u16>()
704            .ok()
705            .filter(|id| *id <= u8::MAX as u16)
706            .ok_or_else(|| format!("{NAME} key ids must be decimal integers 0-255"))?
707            as u8;
708        if keys.contains_key(&id) {
709            return Err(format!("{NAME} contains a duplicate key id"));
710        }
711        let key = parse_hex_key(NAME, key_text)?;
712        keys.insert(id, Arc::from(key.as_slice()));
713    }
714    if keys.is_empty() {
715        return Err(format!("{NAME} must contain at least one `id:key` pair"));
716    }
717    Ok(keys)
718}
719
720/// Read the operator's external footer once at start-up. A missing, unreadable or
721/// placeholder-less footer is not a start-up error; it is recorded as an unavailability reason
722/// that refuses external admission.
723fn read_external_footer(path: Option<&str>) -> Result<Arc<str>, Arc<str>> {
724    read_footer_file(path, "KHIVE_EMAIL_EXTERNAL_FOOTER_FILE")
725}
726
727fn read_list_footer(path: Option<&str>) -> Result<Arc<str>, Arc<str>> {
728    read_footer_file(path, LIST_FOOTER_ENV)
729}
730
731fn read_footer_file(path: Option<&str>, name: &str) -> Result<Arc<str>, Arc<str>> {
732    let Some(path) = path else {
733        return Err(Arc::<str>::from(format!("{name} is not set")));
734    };
735    let text = std::fs::read_to_string(path)
736        .map_err(|_| Arc::<str>::from(format!("{name} could not be read")))?;
737    if !text.contains(UNSUBSCRIBE_PLACEHOLDER) {
738        return Err(Arc::<str>::from(format!(
739            "{name} does not contain {UNSUBSCRIBE_PLACEHOLDER}"
740        )));
741    }
742    Ok(Arc::from(text))
743}
744
745/// Lowercase hex of a byte slice (no `hex` crate dependency).
746/// Encode an unsubscribe token: `0x01 || key_id || recipient_key || tag`, where the tag is the
747/// first [`UNSUBSCRIBE_TAG_BYTES`] bytes of `HMAC-SHA256(key, 0x01 || key_id || recipient_key)`,
748/// as base64url without padding.
749fn encode_unsubscribe_token(
750    key_id: u8,
751    key: &[u8],
752    recipient_key: &[u8; RECIPIENT_KEY_BYTES],
753) -> String {
754    let mut token = Vec::with_capacity(UNSUBSCRIBE_TOKEN_BYTES);
755    token.push(UNSUBSCRIBE_TOKEN_VERSION);
756    token.push(key_id);
757    token.extend_from_slice(recipient_key);
758    let tag = hmac_sha256(key, &token);
759    token.extend_from_slice(&tag[..UNSUBSCRIBE_TAG_BYTES]);
760    URL_SAFE_NO_PAD.encode(token)
761}
762
763fn hex_lower(bytes: &[u8]) -> String {
764    const DIGITS: &[u8; 16] = b"0123456789abcdef";
765    let mut out = String::with_capacity(bytes.len() * 2);
766    for byte in bytes {
767        out.push(DIGITS[(byte >> 4) as usize] as char);
768        out.push(DIGITS[(byte & 0x0f) as usize] as char);
769    }
770    out
771}
772
773/// Constant-time comparison over two equal-length byte slices (XOR-fold, no early return).
774fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
775    if left.len() != right.len() {
776        return false;
777    }
778    let mut diff = 0u8;
779    for (a, b) in left.iter().zip(right.iter()) {
780        diff |= a ^ b;
781    }
782    diff == 0
783}
784
785#[cfg(test)]
786mod tests {
787    use super::*;
788
789    #[test]
790    fn explicit_policy_and_requests_share_maintainer_normalization() {
791        let policy =
792            OutboundEmailPolicy::explicit(Some(" , First@Example.com , second@example.com,,"))
793                .unwrap()
794                .unwrap();
795        assert!(policy.allows("First@Example.com"));
796        assert!(policy.allows("second@example.com"));
797        assert!(policy.allows("first@example.com"));
798        assert!(policy.allows(" First@Example.com "));
799        assert!(policy.allows("First <FIRST@EXAMPLE.COM>"));
800        assert!(!policy.allows("other@example.com"));
801        assert!(!policy.allows("not-an-address"));
802        assert!(policy.is_configured());
803        assert_eq!(
804            policy.recipients.as_deref().unwrap(),
805            ["first@example.com", "second@example.com"]
806        );
807        assert!(OutboundEmailPolicy::explicit(Some(" , , "))
808            .unwrap()
809            .is_none());
810        assert!(OutboundEmailPolicy::explicit(Some("not-an-address")).is_err());
811    }
812
813    #[test]
814    fn fallback_validates_all_maintainers_and_allows_only_normalized_primary() {
815        let policy = OutboundEmailPolicy::maintainer(
816            Some("Owner <Primary@Example.com>, second@example.com"),
817            false,
818        )
819        .unwrap();
820        assert!(policy.allows("primary@example.com"));
821        assert!(policy.allows("Primary@Example.com"));
822        assert!(policy.allows("Owner <PRIMARY@EXAMPLE.COM>"));
823        assert!(!policy.allows("second@example.com"));
824        assert!(
825            OutboundEmailPolicy::maintainer(Some("primary@example.com,invalid"), false).is_err()
826        );
827        assert!(OutboundEmailPolicy::maintainer(Some(" , "), false).is_err());
828        assert!(OutboundEmailPolicy::maintainer(None, true).is_err());
829        assert!(
830            OutboundEmailPolicy::maintainer(Some("primary@example.com"), true)
831                .unwrap()
832                .allows("PRIMARY@example.com")
833        );
834        assert!(OutboundEmailPolicy::maintainer(None, false)
835            .unwrap()
836            .allows("backlog@example.com"));
837        assert!(!OutboundEmailPolicy::default().is_configured());
838        let deny_all = OutboundEmailPolicy::configured(vec![]).unwrap();
839        assert!(deny_all.is_configured());
840        assert!(!deny_all.allows("backlog@example.com"));
841        assert!(OutboundEmailPolicy::configured(vec!["invalid".into()]).is_err());
842    }
843
844    #[test]
845    fn present_maintainer_is_validated_beside_an_explicit_list_and_an_unset_one_is_not() {
846        let resolve = OutboundEmailPolicy::resolve;
847        let explicit = Some("allowed@example.com");
848        for maintainer in [
849            "",
850            " , ",
851            "primary@example.com,invalid",
852            "invalid,primary@example.com",
853        ] {
854            assert!(
855                resolve(explicit, Some(maintainer)).is_err(),
856                "maintainer {maintainer:?} beside a valid explicit list must be refused"
857            );
858        }
859        let unset = resolve(explicit, None).unwrap();
860        assert!(unset.is_configured());
861        assert!(unset.allows("ALLOWED@example.com"));
862        assert!(!unset.allows("primary@example.com"));
863        let list = Some("Owner <Primary@Example.com>, second@example.com");
864        let valid = resolve(explicit, list).unwrap();
865        assert!(valid.allows("allowed@example.com"));
866        assert!(!valid.allows("primary@example.com"));
867        let blank = Some(" , ");
868        let fallback = resolve(blank, list).unwrap();
869        assert!(fallback.allows("primary@example.com"));
870        assert!(!fallback.allows("second@example.com"));
871        assert!(resolve(blank, None).is_err());
872        assert!(resolve(Some("not-an-address"), None).is_err());
873        assert!(resolve(None, Some("primary@example.com,invalid")).is_err());
874        assert!(!resolve(None, None).unwrap().is_configured());
875    }
876
877    #[test]
878    fn comparison_folds_ascii_case_only() {
879        let policy = OutboundEmailPolicy::configured(vec!["kevin@example.com".into()]).unwrap();
880        // U+212A KELVIN SIGN lowercases to ASCII `k` under Unicode rules; it is a different
881        // address.
882        assert!(!policy.allows("\u{212A}evin@example.com"));
883        assert!(policy.allows("KEVIN@Example.COM"));
884        assert!(policy.allows("kevin@example.com"));
885    }
886
887    #[test]
888    fn configured_entries_and_requests_share_one_normalization() {
889        // The entry and the request pass through the same function, so a non-ASCII letter in
890        // an entry matches only its exact spelling while ASCII case still folds on both sides.
891        let policy =
892            OutboundEmailPolicy::configured(vec!["\u{212A}evin@Example.COM".into()]).unwrap();
893        assert_eq!(
894            policy.recipients.as_deref().unwrap(),
895            ["\u{212A}evin@example.com"]
896        );
897        assert!(policy.allows("\u{212A}evin@EXAMPLE.com"));
898        assert!(!policy.allows("kevin@example.com"));
899        let accented =
900            OutboundEmailPolicy::maintainer(Some("\u{C9}mile@Example.com"), false).unwrap();
901        assert!(accented.allows("\u{C9}mile@example.COM"));
902        assert!(!accented.allows("\u{E9}mile@example.com"));
903    }
904
905    #[test]
906    fn suppression_matching_checks_exact_address_domain_and_recipient_key() {
907        let address = [EmailSuppression {
908            scope: EmailSuppressionScope::Outbound,
909            kind: EmailSuppressionKind::Address,
910            value: "a@example.com".into(),
911        }];
912        assert!(outbound_email_is_suppressed(
913            "a@example.com",
914            None,
915            &address
916        ));
917        assert!(!outbound_email_is_suppressed(
918            "b@example.com",
919            None,
920            &address
921        ));
922
923        let entries = [
924            EmailSuppression {
925                scope: EmailSuppressionScope::Outbound,
926                kind: EmailSuppressionKind::Address,
927                value: "a@example.com".into(),
928            },
929            EmailSuppression {
930                scope: EmailSuppressionScope::Outbound,
931                kind: EmailSuppressionKind::Domain,
932                value: "x.com".into(),
933            },
934            EmailSuppression {
935                scope: EmailSuppressionScope::Outbound,
936                kind: EmailSuppressionKind::RecipientKey,
937                value: "key-1".into(),
938            },
939            EmailSuppression {
940                scope: EmailSuppressionScope::Inbound,
941                kind: EmailSuppressionKind::Address,
942                value: "b@example.com".into(),
943            },
944        ];
945
946        assert!(outbound_email_is_suppressed(
947            "a@example.com",
948            None,
949            &entries
950        ));
951        assert!(outbound_email_is_suppressed("b@x.com", None, &entries));
952        assert!(!outbound_email_is_suppressed("b@sub.x.com", None, &entries));
953        assert!(outbound_email_is_suppressed(
954            "c@example.com",
955            Some("key-1"),
956            &entries
957        ));
958        assert!(!outbound_email_is_suppressed(
959            "c@example.com",
960            Some("key-2"),
961            &entries
962        ));
963        assert!(!outbound_email_is_suppressed(
964            "b@example.com",
965            None,
966            &entries
967        ));
968    }
969
970    #[test]
971    fn inbound_matching_checks_exact_address_and_domain_and_ignores_recipient_keys() {
972        let entries = [
973            EmailSuppression {
974                scope: EmailSuppressionScope::Inbound,
975                kind: EmailSuppressionKind::Address,
976                value: "a@example.com".into(),
977            },
978            EmailSuppression {
979                scope: EmailSuppressionScope::Inbound,
980                kind: EmailSuppressionKind::Domain,
981                value: "blocked.com".into(),
982            },
983            EmailSuppression {
984                scope: EmailSuppressionScope::Inbound,
985                kind: EmailSuppressionKind::RecipientKey,
986                value: "key-1".into(),
987            },
988            // An outbound-only entry never blocks an inbound sender.
989            EmailSuppression {
990                scope: EmailSuppressionScope::Outbound,
991                kind: EmailSuppressionKind::Address,
992                value: "c@example.com".into(),
993            },
994        ];
995
996        assert!(inbound_email_is_suppressed("a@example.com", &entries));
997        assert!(!inbound_email_is_suppressed("b@example.com", &entries));
998        assert!(inbound_email_is_suppressed("z@blocked.com", &entries));
999        assert!(!inbound_email_is_suppressed("z@sub.blocked.com", &entries));
1000        assert!(!inbound_email_is_suppressed("c@example.com", &entries));
1001        assert!(!inbound_email_is_suppressed("key-1", &entries));
1002    }
1003
1004    #[test]
1005    fn cloned_policy_keeps_the_same_immutable_recipient_set() {
1006        let policy = OutboundEmailPolicy::configured(vec!["allowed@example.com".into()]).unwrap();
1007        let clone = policy.clone();
1008        assert!(Arc::ptr_eq(
1009            policy.recipients.as_ref().unwrap(),
1010            clone.recipients.as_ref().unwrap()
1011        ));
1012    }
1013
1014    fn rk() -> String {
1015        "cc".repeat(32) // 32 bytes of 0xcc
1016    }
1017
1018    fn token_keys_hex() -> String {
1019        format!("0:{},1:{}", "11".repeat(32), "22".repeat(32))
1020    }
1021
1022    fn enabled() -> OutboundEmailPolicy {
1023        OutboundEmailPolicy::configured_for_tests_with(
1024            vec!["allowed@example.com".into()],
1025            vec!["actor:sender".into()],
1026            5,
1027            &rk(),
1028            &token_keys_hex(),
1029            Ok("Reply to unsubscribe: {unsubscribe}"),
1030        )
1031        .unwrap()
1032    }
1033
1034    fn unhex(hex: &str) -> Vec<u8> {
1035        hex.as_bytes()
1036            .chunks_exact(2)
1037            .map(|pair| {
1038                let high = (pair[0] as char).to_digit(16).unwrap();
1039                let low = (pair[1] as char).to_digit(16).unwrap();
1040                (high * 16 + low) as u8
1041            })
1042            .collect()
1043    }
1044
1045    #[test]
1046    fn hmac_sha256_matches_rfc_4231_vectors() {
1047        let case1 = hmac_sha256(&[0x0b; 20], b"Hi There");
1048        assert_eq!(
1049            hex_lower(&case1),
1050            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
1051        );
1052        let case2 = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
1053        assert_eq!(
1054            hex_lower(&case2),
1055            "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
1056        );
1057        let case6 = hmac_sha256(
1058            &[0xaa; 131],
1059            b"Test Using Larger Than Block-Size Key - Hash Key First",
1060        );
1061        assert_eq!(
1062            hex_lower(&case6),
1063            "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"
1064        );
1065    }
1066
1067    #[test]
1068    fn key_configuration_refuses_malformed_values_when_senders_are_set() {
1069        // Missing recipient-key secret.
1070        let missing_rk = OutboundEmailPolicy::resolve_with_external(
1071            None,
1072            Some("maintainer@example.com"),
1073            Some("actor:sender"),
1074            Some("5"),
1075            None,
1076            Some(&token_keys_hex()),
1077            None,
1078        )
1079        .err()
1080        .expect("start-up policy is refused");
1081        assert!(
1082            missing_rk.contains("KHIVE_EMAIL_UNSUBSCRIBE_RK_KEY"),
1083            "{missing_rk}"
1084        );
1085
1086        // Missing token keys.
1087        let missing_tokens = OutboundEmailPolicy::resolve_with_external(
1088            None,
1089            Some("maintainer@example.com"),
1090            Some("actor:sender"),
1091            Some("5"),
1092            Some(&rk()),
1093            None,
1094            None,
1095        )
1096        .err()
1097        .expect("start-up policy is refused");
1098        assert!(
1099            missing_tokens.contains("KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS"),
1100            "{missing_tokens}"
1101        );
1102
1103        for (rk, tokens, needle) in [
1104            (
1105                rk(),
1106                "0:nothex".to_string(),
1107                "KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS",
1108            ),
1109            (rk(), "0".to_string(), "KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS"),
1110            (
1111                rk(),
1112                "0:abcd".to_string(),
1113                "KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS",
1114            ),
1115            (
1116                rk(),
1117                format!("0:{},0:{}", "11".repeat(32), "22".repeat(32)),
1118                "KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS",
1119            ),
1120            (
1121                rk(),
1122                format!("256:{}", "11".repeat(32)),
1123                "KHIVE_EMAIL_UNSUBSCRIBE_TOKEN_KEYS",
1124            ),
1125        ] {
1126            let error = OutboundEmailPolicy::resolve_with_external(
1127                None,
1128                Some("maintainer@example.com"),
1129                Some("actor:sender"),
1130                Some("5"),
1131                Some(rk.as_str()),
1132                Some(tokens.as_str()),
1133                None,
1134            )
1135            .err()
1136            .expect("start-up policy is refused");
1137            assert!(error.contains(needle), "{error}");
1138            assert!(
1139                !error.contains(&"11".repeat(32)),
1140                "key material leaked: {error}"
1141            );
1142        }
1143
1144        // Short recipient-key secret (31 bytes) and non-hex secret.
1145        for rk in ["cc".repeat(31), "cc".repeat(16), "zz".repeat(32)] {
1146            let error = OutboundEmailPolicy::resolve_with_external(
1147                None,
1148                Some("maintainer@example.com"),
1149                Some("actor:sender"),
1150                Some("5"),
1151                Some(&rk),
1152                Some(&token_keys_hex()),
1153                None,
1154            )
1155            .err()
1156            .expect("start-up policy is refused");
1157            assert!(error.contains("KHIVE_EMAIL_UNSUBSCRIBE_RK_KEY"), "{error}");
1158            assert!(!error.contains(&rk), "key material leaked: {error}");
1159        }
1160    }
1161
1162    #[test]
1163    fn key_variables_are_ignored_when_senders_are_unset() {
1164        // A malformed key value is never read while the senders variable is unset.
1165        let policy = OutboundEmailPolicy::resolve_with_external(
1166            None,
1167            Some("maintainer@example.com"),
1168            None,
1169            None,
1170            Some("not hex"),
1171            Some("garbage"),
1172            Some("/nonexistent/footer"),
1173        )
1174        .unwrap();
1175        assert!(!policy.has_external_senders());
1176        assert!(policy.recipient_key("a@example.com").is_none());
1177        assert!(policy.mint_unsubscribe_token("a@example.com").is_none());
1178        assert!(policy.external_footer().is_none());
1179    }
1180
1181    #[test]
1182    fn recipient_key_is_normalized_hex_and_stable_across_case() {
1183        let policy = enabled();
1184        let key = policy.recipient_key("person@example.com").unwrap();
1185        assert_eq!(key.len(), 64);
1186        assert!(khive_types::is_lowercase_hex(&key));
1187        // Callers pass a normalized address (ADR-200 §5.1); normalization folds ASCII case.
1188        let other_case =
1189            khive_types::email_address::normalize_email_recipient("Person@Example.COM").unwrap();
1190        assert_eq!(key, policy.recipient_key(&other_case).unwrap());
1191        let secret = unhex(&rk());
1192        assert_eq!(key, hex_lower(&hmac_sha256(&secret, b"person@example.com")));
1193    }
1194
1195    #[test]
1196    fn token_round_trips_and_rejects_tampering() {
1197        let policy = enabled();
1198        let token = policy.mint_unsubscribe_token("person@example.com").unwrap();
1199        let recipient_key = policy.recipient_key("person@example.com").unwrap();
1200        assert_eq!(
1201            policy.verify_unsubscribe_token(&token).as_deref(),
1202            Some(recipient_key.as_str())
1203        );
1204
1205        // A flipped tag byte fails.
1206        let mut bytes = URL_SAFE_NO_PAD.decode(&token).unwrap();
1207        let last = bytes.len() - 1;
1208        bytes[last] ^= 0x01;
1209        assert!(policy
1210            .verify_unsubscribe_token(&URL_SAFE_NO_PAD.encode(&bytes))
1211            .is_none());
1212
1213        // A wrong version byte fails.
1214        let mut bytes = URL_SAFE_NO_PAD.decode(&token).unwrap();
1215        bytes[0] = 0x02;
1216        assert!(policy
1217            .verify_unsubscribe_token(&URL_SAFE_NO_PAD.encode(&bytes))
1218            .is_none());
1219
1220        // An unknown key id fails.
1221        let mut bytes = URL_SAFE_NO_PAD.decode(&token).unwrap();
1222        bytes[1] = 9;
1223        assert!(policy
1224            .verify_unsubscribe_token(&URL_SAFE_NO_PAD.encode(&bytes))
1225            .is_none());
1226
1227        // A truncated token fails.
1228        assert!(policy.verify_unsubscribe_token("AAAA").is_none());
1229    }
1230
1231    // A published test vector for the token format, shared with an independent verifier so that
1232    // a change to how either side mints or verifies fails a suite. The token key is test
1233    // material, never deployment key material.
1234    const VECTOR_KEY_ID: u8 = 3;
1235    const VECTOR_TOKEN_KEY_HEX: &str =
1236        "efaaa78a85da8a505a5278b5ad7d202a8b5028bb0b279c7a01f410c0ff84c09d";
1237    const VECTOR_RECIPIENT_KEY_HEX: &str =
1238        "cd5ac2457bd4442f53a23cfa9972cc3cdf3d0f1bcf1722bd5503ab20acfa3930";
1239    const VECTOR_TOKEN: &str =
1240        "AQPNWsJFe9REL1OiPPqZcsw83z0PG88XIr1VA6sgrPo5MFRThmznJxzUr1otDEzmcaE";
1241    const VECTOR_TOKEN_FLIPPED_TAG: &str =
1242        "AQPNWsJFe9REL1OiPPqZcsw83z0PG88XIr1VA6sgrPo5MFRThmznJxzUr1otDEzmcaA";
1243
1244    #[test]
1245    fn shared_vector_mints_and_verifies_byte_for_byte() {
1246        let recipient_key: [u8; RECIPIENT_KEY_BYTES] = unhex(VECTOR_RECIPIENT_KEY_HEX)
1247            .try_into()
1248            .expect("the vector recipient key is 32 bytes");
1249        assert_eq!(
1250            encode_unsubscribe_token(VECTOR_KEY_ID, &unhex(VECTOR_TOKEN_KEY_HEX), &recipient_key),
1251            VECTOR_TOKEN,
1252            "minting the vector inputs must reproduce the vector token"
1253        );
1254
1255        let policy = OutboundEmailPolicy::configured_for_tests_with(
1256            vec!["allowed@example.com".into()],
1257            vec!["actor:sender".into()],
1258            5,
1259            &rk(),
1260            &format!("{VECTOR_KEY_ID}:{VECTOR_TOKEN_KEY_HEX}"),
1261            Ok("Reply to unsubscribe: {unsubscribe}"),
1262        )
1263        .unwrap();
1264        assert_eq!(
1265            policy.verify_unsubscribe_token(VECTOR_TOKEN).as_deref(),
1266            Some(VECTOR_RECIPIENT_KEY_HEX),
1267            "the vector token verifies to the vector recipient key"
1268        );
1269        assert!(
1270            policy
1271                .verify_unsubscribe_token(VECTOR_TOKEN_FLIPPED_TAG)
1272                .is_none(),
1273            "the vector token with one tag bit flipped does not verify"
1274        );
1275    }
1276
1277    #[test]
1278    fn retired_key_ids_keep_verifying_and_the_highest_id_mints() {
1279        let policy = enabled();
1280        // A token minted under the higher id (1) verifies.
1281        let token_high = policy.mint_unsubscribe_token("person@example.com").unwrap();
1282        let decoded = URL_SAFE_NO_PAD.decode(&token_high).unwrap();
1283        assert_eq!(decoded[1], 1, "minting must use the highest configured id");
1284        assert!(policy.verify_unsubscribe_token(&token_high).is_some());
1285
1286        // Rebuild with a retired id 0 kept alongside the higher id 1.
1287        let retired = OutboundEmailPolicy::configured_for_tests_with(
1288            vec!["allowed@example.com".into()],
1289            vec!["actor:sender".into()],
1290            5,
1291            &rk(),
1292            &token_keys_hex(),
1293            Ok("footer {unsubscribe}"),
1294        )
1295        .unwrap();
1296        // A token that was minted under id 0 before rotation still verifies after id 1 exists.
1297        let mut body = Vec::new();
1298        body.push(0x01u8);
1299        body.push(0u8);
1300        body.extend_from_slice(&unhex(
1301            &retired.recipient_key("person@example.com").unwrap(),
1302        ));
1303        let tag = hmac_sha256(&unhex(&"11".repeat(32)), &body);
1304        body.extend_from_slice(&tag[..16]);
1305        let old_token = URL_SAFE_NO_PAD.encode(&body);
1306        assert_eq!(
1307            retired.verify_unsubscribe_token(&old_token).as_deref(),
1308            Some(
1309                retired
1310                    .recipient_key("person@example.com")
1311                    .unwrap()
1312                    .as_str()
1313            )
1314        );
1315    }
1316
1317    #[test]
1318    fn footer_state_is_recorded_without_a_start_up_error() {
1319        let policy = OutboundEmailPolicy::configured_for_tests_with(
1320            vec!["allowed@example.com".into()],
1321            vec!["actor:sender".into()],
1322            5,
1323            &rk(),
1324            &token_keys_hex(),
1325            Err("KHIVE_EMAIL_EXTERNAL_FOOTER_FILE is not set"),
1326        )
1327        .unwrap();
1328        assert_eq!(
1329            policy.external_footer(),
1330            Some(Err("KHIVE_EMAIL_EXTERNAL_FOOTER_FILE is not set"))
1331        );
1332    }
1333
1334    #[test]
1335    fn footer_file_must_exist_be_readable_and_carry_the_placeholder() {
1336        let missing = read_external_footer(Some("/nonexistent/khive-footer"));
1337        assert!(missing.is_err());
1338        let dir = std::env::temp_dir();
1339        let without = dir.join("khive-footer-without-placeholder.txt");
1340        std::fs::write(&without, "no placeholder here").unwrap();
1341        assert!(read_external_footer(without.to_str()).is_err());
1342        let with = dir.join("khive-footer-with-placeholder.txt");
1343        std::fs::write(&with, "Contact us.\n{unsubscribe}\n").unwrap();
1344        assert_eq!(
1345            read_external_footer(with.to_str()).unwrap().as_ref(),
1346            "Contact us.\n{unsubscribe}\n"
1347        );
1348        assert!(read_external_footer(None).is_err());
1349    }
1350
1351    #[test]
1352    fn suppression_mirror_variables_parse_as_one_unit() {
1353        let token = "mirror-read-credential-value";
1354        assert!(parse_suppression_mirror(None, None, None)
1355            .unwrap()
1356            .is_none());
1357        let mirror = parse_suppression_mirror(
1358            Some("https://mirror.example.com/admin/email-suppression"),
1359            Some(token),
1360            Some("900"),
1361        )
1362        .unwrap()
1363        .expect("a complete mirror configuration parses");
1364        assert_eq!(
1365            mirror.url(),
1366            "https://mirror.example.com/admin/email-suppression"
1367        );
1368        assert_eq!(mirror.credential(), token);
1369        assert_eq!(mirror.max_age(), std::time::Duration::from_secs(900));
1370
1371        let url = Some("https://mirror.example.com/x");
1372        for (url, credential, max_age, needle) in [
1373            (
1374                None,
1375                Some(token),
1376                None,
1377                "KHIVE_EMAIL_SUPPRESSION_MIRROR_TOKEN is set but",
1378            ),
1379            (
1380                None,
1381                None,
1382                Some("60"),
1383                "KHIVE_EMAIL_SUPPRESSION_MIRROR_MAX_AGE_SECS is set but",
1384            ),
1385            (
1386                url,
1387                None,
1388                Some("60"),
1389                "KHIVE_EMAIL_SUPPRESSION_MIRROR_TOKEN is required",
1390            ),
1391            (
1392                url,
1393                Some(token),
1394                None,
1395                "KHIVE_EMAIL_SUPPRESSION_MIRROR_MAX_AGE_SECS is required",
1396            ),
1397            (url, Some(token), Some("0"), "must be a positive integer"),
1398            (url, Some(token), Some("-5"), "must be a positive integer"),
1399            (url, Some(token), Some("ten"), "must be a positive integer"),
1400            (
1401                url,
1402                Some(""),
1403                Some("60"),
1404                "must be non-empty printable ASCII",
1405            ),
1406            (
1407                url,
1408                Some("two words"),
1409                Some("60"),
1410                "must be non-empty printable ASCII",
1411            ),
1412            (
1413                Some("http://mirror.example.com/x"),
1414                Some(token),
1415                Some("60"),
1416                "must be an https:// URL",
1417            ),
1418            (
1419                Some("HTTPS://mirror.example.com/x"),
1420                Some(token),
1421                Some("60"),
1422                "must be an https:// URL",
1423            ),
1424            (Some("https://"), Some(token), Some("60"), "with a host"),
1425            (
1426                Some("https:///path"),
1427                Some(token),
1428                Some("60"),
1429                "with a host",
1430            ),
1431            (
1432                Some("https://mirror.example.com/a b"),
1433                Some(token),
1434                Some("60"),
1435                "with a host",
1436            ),
1437        ] {
1438            let error = parse_suppression_mirror(url, credential, max_age)
1439                .err()
1440                .expect("a partial or malformed mirror configuration is refused");
1441            assert!(error.contains(needle), "{error}");
1442            assert!(!error.contains(token), "credential leaked: {error}");
1443        }
1444    }
1445
1446    #[test]
1447    fn suppression_mirror_is_off_unless_configured() {
1448        assert!(enabled().suppression_mirror().is_none());
1449        assert!(OutboundEmailPolicy::default()
1450            .suppression_mirror()
1451            .is_none());
1452    }
1453
1454    #[test]
1455    fn external_constructors_record_a_named_missing_list_footer() {
1456        let resolved = OutboundEmailPolicy::resolve_with_external(
1457            None,
1458            Some("maintainer@example.com"),
1459            Some("actor:sender"),
1460            Some("5"),
1461            Some(&rk()),
1462            Some(&token_keys_hex()),
1463            None,
1464        )
1465        .unwrap();
1466        let configured = OutboundEmailPolicy::configured_for_tests(
1467            vec!["allowed@example.com".into()],
1468            vec!["actor:sender".into()],
1469            5,
1470        )
1471        .unwrap();
1472        for policy in [resolved, configured, enabled()] {
1473            assert_eq!(
1474                policy.list_footer(),
1475                Some(Err("KHIVE_EMAIL_LIST_FOOTER_FILE is not set"))
1476            );
1477            assert_eq!(policy.external_footer_for_list(true), policy.list_footer());
1478        }
1479        let mut internal = OutboundEmailPolicy::default();
1480        internal.resolve_list_footer(Some("/nonexistent/unused-list-footer"));
1481        assert!(internal.list_footer().is_none());
1482        assert!(internal.external_footer_for_list(true).is_none());
1483    }
1484
1485    #[test]
1486    fn list_footer_selection_never_falls_back_or_requires_the_default_footer() {
1487        let policy = enabled();
1488        assert_eq!(
1489            policy.external_footer_for_list(false),
1490            Some(Ok("Reply to unsubscribe: {unsubscribe}"))
1491        );
1492        assert_eq!(
1493            policy.external_footer_for_list(true),
1494            Some(Err("KHIVE_EMAIL_LIST_FOOTER_FILE is not set"))
1495        );
1496        let policy = policy
1497            .with_list_footer_for_tests(Ok("List notice: {unsubscribe}\n"))
1498            .with_external_footer_for_tests(Err("KHIVE_EMAIL_EXTERNAL_FOOTER_FILE is not set"));
1499        assert_eq!(
1500            policy.external_footer_for_list(true),
1501            Some(Ok("List notice: {unsubscribe}\n"))
1502        );
1503        assert_eq!(
1504            policy.external_footer_for_list(false),
1505            Some(Err("KHIVE_EMAIL_EXTERNAL_FOOTER_FILE is not set"))
1506        );
1507    }
1508
1509    #[test]
1510    fn list_footer_file_validation_is_named_and_cached() {
1511        let dir = std::env::temp_dir().join(format!(
1512            "khive-list-footer-{}-{}",
1513            std::process::id(),
1514            std::time::SystemTime::now()
1515                .duration_since(std::time::UNIX_EPOCH)
1516                .unwrap()
1517                .as_nanos()
1518        ));
1519        std::fs::create_dir(&dir).unwrap();
1520        let unreadable = dir.join("directory-not-a-footer");
1521        std::fs::create_dir(&unreadable).unwrap();
1522        let without_placeholder = dir.join("without-placeholder.txt");
1523        std::fs::write(&without_placeholder, "operator-footer-content-sentinel").unwrap();
1524        let mut policy = enabled();
1525        for (path, reason) in [
1526            (None, "KHIVE_EMAIL_LIST_FOOTER_FILE is not set"),
1527            (
1528                Some(unreadable.to_str().unwrap()),
1529                "KHIVE_EMAIL_LIST_FOOTER_FILE could not be read",
1530            ),
1531            (
1532                Some(without_placeholder.to_str().unwrap()),
1533                "KHIVE_EMAIL_LIST_FOOTER_FILE does not contain {unsubscribe}",
1534            ),
1535        ] {
1536            policy.resolve_list_footer(path);
1537            assert_eq!(policy.list_footer(), Some(Err(reason)));
1538            assert_eq!(
1539                policy.external_footer(),
1540                Some(Ok("Reply to unsubscribe: {unsubscribe}"))
1541            );
1542        }
1543        let valid = dir.join("with-placeholder.txt");
1544        let original = "List contact.\n{unsubscribe}\n";
1545        std::fs::write(&valid, original).unwrap();
1546        policy.resolve_list_footer(valid.to_str());
1547        assert_eq!(policy.list_footer(), Some(Ok(original)));
1548        std::fs::write(&valid, "changed after startup").unwrap();
1549        std::fs::remove_file(&valid).unwrap();
1550        assert_eq!(policy.list_footer(), Some(Ok(original)));
1551        assert_eq!(policy.clone().list_footer(), Some(Ok(original)));
1552        std::fs::remove_dir_all(&dir).unwrap();
1553    }
1554}