Skip to main content

bynk_check/
email.rs

1//! Inbound email: the `from email("addr")` service protocol (#3328, slice 1).
2//!
3//! The checker side of the protocol's seventh member: address validation,
4//! handler shape (`on message(mail: InboundEmail) -> Effect[EmailVerdict]`), the
5//! one-claim-per-address rule (DECISION A), and the slice-1 refusal to emit a
6//! `from email` service as a Worker (slice 2 builds the `email()` export).
7//!
8//! `InboundEmail`, `EmailVerdict` and the rest are first-party types exported
9//! by `bynk.cloudflare`, so the handler-shape checks compare type *names*; the
10//! body is then type-checked against the real declarations like any other.
11
12use std::collections::{BTreeMap, HashMap};
13
14use bynk_syntax::ast::{
15    CommonsItem, Handler, HandlerKind, ServiceDecl, ServiceProtocol, SourceUnit, TypeRef,
16};
17use bynk_syntax::error::CompileError;
18use bynk_syntax::span::Span;
19
20use crate::context_checks::ts_type_ref_display;
21use crate::project_model::ErrorSink;
22use bynk_project::{ParsedFile, UnitKind};
23
24/// The first-party type a `from email` handler receives.
25pub const INBOUND_EMAIL: &str = "InboundEmail";
26/// The first-party verdict a `from email` handler returns.
27pub const EMAIL_VERDICT: &str = "EmailVerdict";
28
29/// Why an address is not a claimable recipient, or `None` if it is.
30///
31/// A claim is `local@domain`, or `*@domain` for the domain's catch-all. The
32/// domain is dotted labels of letters, digits and `-` (not starting or ending
33/// a label with `-`). A local part is non-empty and free of whitespace,
34/// control, angle-bracket, quote, comma, `*` and `@` characters. Display
35/// names (`Support <a@b>`) are refused: Email Routing matches the bare
36/// address.
37pub fn address_problem(address: &str) -> Option<&'static str> {
38    let Some((local, domain)) = address.split_once('@') else {
39        return Some("it has no `@`");
40    };
41    if local.is_empty() {
42        return Some("the part before `@` is empty");
43    }
44    if local != "*"
45        && local
46            .chars()
47            .any(|c| c.is_whitespace() || c.is_control() || "<>\"',@*()[]\\;:".contains(c))
48    {
49        return Some("the part before `@` has a character an address cannot hold");
50    }
51    if domain.is_empty() || !domain.contains('.') {
52        return Some("the domain needs at least two dot-separated labels");
53    }
54    let label_ok = |l: &str| {
55        !l.is_empty()
56            && !l.starts_with('-')
57            && !l.ends_with('-')
58            && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
59    };
60    if !domain.split('.').all(label_ok) {
61        return Some("the domain is not dotted labels of letters, digits and `-`");
62    }
63    None
64}
65
66/// The routing key two claims are compared by: the domain is
67/// case-insensitive, and so is the local part, deliberately: RFC 5321 allows a
68/// case-sensitive local part, but Email Routing matches addresses without
69/// regard to case, so two claims differing only in case would be one rule.
70fn claim_key(address: &str) -> String {
71    address.to_ascii_lowercase()
72}
73
74/// Check every `from email` service of one context: address, handler shape and
75/// the one-service-per-address rule.
76pub fn check_email_services(table: &crate::symbols::UnitTable, errors: &mut Vec<CompileError>) {
77    let services = &table.services;
78    let mut first_claim: HashMap<String, Span> = HashMap::new();
79    // Source order, so "first claimed here" is the earlier declaration.
80    let mut ordered: Vec<&ServiceDecl> = services.values().collect();
81    ordered.sort_by_key(|s| s.name.span);
82    for service in ordered {
83        let ServiceProtocol::Email { address } = &service.protocol else {
84            continue;
85        };
86        if let Some(why) = address_problem(address) {
87            errors.push(
88                CompileError::new(
89                    "bynk.email.invalid_address",
90                    service.name.span,
91                    format!("`{address}` is not an address a service can claim: {why}"),
92                )
93                .with_note(
94                    "write a bare address, `from email(\"[email protected]\")`, or a domain's catch-all, `from email(\"*@shop.example\")`",
95                ),
96            );
97        } else if let Some(prev) = first_claim.get(&claim_key(address)).copied() {
98            errors.push(
99                CompileError::new(
100                    "bynk.email.duplicate_address",
101                    service.name.span,
102                    format!("another `from email` service already claims `{address}`"),
103                )
104                .with_label(prev, "first claimed here")
105                .with_note(
106                    "mail is dispatched by its envelope recipient, so each address has one service; a literal address and `*@domain` may coexist, and the literal wins",
107                ),
108            );
109        } else {
110            first_claim.insert(claim_key(address), service.name.span);
111        }
112        let messages: Vec<&Handler> = service
113            .handlers
114            .iter()
115            .filter(|h| h.kind == HandlerKind::Message)
116            .collect();
117        for extra in messages.iter().skip(1) {
118            errors.push(
119                CompileError::new(
120                    "bynk.email.duplicate_handler",
121                    extra.span,
122                    format!(
123                        "the `from email` service `{}` has more than one `on message` handler — it needs exactly one",
124                        service.name.name
125                    ),
126                )
127                .with_label(messages[0].span, "the service's first `on message` handler"),
128            );
129        }
130        for handler in messages {
131            validate_handler(handler, table, errors);
132        }
133    }
134}
135
136/// The protocol-shape checks of one context, then the email ones (kept apart
137/// so the long protocol checker does not grow).
138pub(crate) fn check_service_protocols_and_email(
139    table: &crate::symbols::UnitTable,
140    types: &HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
141    errors: &mut Vec<CompileError>,
142    tys: &std::sync::Arc<crate::checker::Types>,
143) {
144    crate::context_checks::check_service_protocols(table, types, errors, tys);
145    crate::context_checks::check_one_call_handler(table, errors);
146    check_email_services(table, errors);
147    check_sender_only_on_email(table, errors);
148}
149
150/// `Sender` yields the envelope sender of inbound mail, so (like `Caller`,
151/// which is `on call`'s) it is admissible only on a `from email` handler,
152/// though its `Internal` scheme is otherwise valid on cron, queue and events.
153fn check_sender_only_on_email(table: &crate::symbols::UnitTable, errors: &mut Vec<CompileError>) {
154    for service in table.services.values() {
155        if matches!(service.protocol, ServiceProtocol::Email { .. }) {
156            continue;
157        }
158        let handler_by = service.handlers.iter().filter_map(|h| h.by_clause.as_ref());
159        for by in handler_by.chain(service.default_by.as_ref()) {
160            let names_sender = by
161                .actors
162                .iter()
163                .any(|a| a.name == "Sender" && !table.actors.contains_key(&a.name));
164            if names_sender {
165                errors.push(
166                    CompileError::new(
167                        "bynk.actor.scheme_not_admissible",
168                        by.span,
169                        "the `Sender` actor is not admissible outside a `from email` service",
170                    )
171                    .with_note(
172                        "`Sender` carries the envelope sender of inbound mail; cron takes `Scheduler`, queue takes `Producer`",
173                    ),
174                );
175            }
176        }
177    }
178}
179
180/// `on message(mail: InboundEmail) -> Effect[EmailVerdict]`.
181fn validate_handler(
182    handler: &Handler,
183    table: &crate::symbols::UnitTable,
184    errors: &mut Vec<CompileError>,
185) {
186    // A type of the same name declared in this context is not the first-party
187    // one the Worker's `email()` entry builds and reads, so it does not count.
188    let first_party = |name: &str| !table.types.contains_key(name);
189    match handler.params.as_slice() {
190        [p] => {
191            if named(&p.type_ref) != Some(INBOUND_EMAIL) || !first_party(INBOUND_EMAIL) {
192                errors.push(
193                    CompileError::new(
194                        "bynk.email.bad_params",
195                        p.type_ref.span(),
196                        format!(
197                            "an email `on message` handler takes the message as `InboundEmail`, but this parameter is `{}`",
198                            ts_type_ref_display(&p.type_ref)
199                        ),
200                    )
201                    .with_note(
202                        "import it: `consumes bynk.cloudflare { InboundEmail, EmailVerdict }`; a type of that name declared in this context is not the first-party one",
203                    ),
204                );
205            }
206        }
207        params => errors.push(
208            CompileError::new(
209                "bynk.email.bad_params",
210                handler.span,
211                format!(
212                    "an email `on message` handler takes exactly one parameter (the `InboundEmail`), got {}",
213                    params.len()
214                ),
215            )
216            .with_note("write `on message(mail: InboundEmail) -> Effect[EmailVerdict]`"),
217        ),
218    }
219    let verdict = matches!(
220        &handler.return_type,
221        TypeRef::Effect(inner, _)
222            if named(inner) == Some(EMAIL_VERDICT) && first_party(EMAIL_VERDICT)
223    );
224    if !verdict {
225        errors.push(
226            CompileError::new(
227                "bynk.email.return_not_email_verdict",
228                handler.return_type.span(),
229                format!(
230                    "an email `on message` handler must return `Effect[EmailVerdict]`, but got `{}`",
231                    ts_type_ref_display(&handler.return_type)
232                ),
233            )
234            .with_note(
235                "the verdict is the decision: `Accept`, `Reject(reason)`, `Forward(to)` or `Reply(message)`",
236            ),
237        );
238    }
239}
240
241fn named(t: &TypeRef) -> Option<&str> {
242    match t {
243        TypeRef::Named(id) => Some(id.name.as_str()),
244        _ => None,
245    }
246}
247
248/// #3328 slice 2: two *contexts* claiming one address is an error too. Slice 1
249/// checks each context on its own ([`check_email_services`]); routing is
250/// project-wide (one rule per address, on the account), so this sees every
251/// context. A claim inside one context is that check's, so only a claim by a
252/// different context is reported here, on the later one (contexts in name
253/// order, so the report does not depend on discovery order).
254pub fn phase_duplicate_addresses(
255    parsed: &[ParsedFile],
256    groups: &BTreeMap<String, Vec<usize>>,
257    kinds: &BTreeMap<String, UnitKind>,
258    errors: &mut ErrorSink,
259) {
260    // routing key -> the first context to claim it.
261    let mut first: HashMap<String, &str> = HashMap::new();
262    for (name, indices) in groups {
263        if kinds.get(name) != Some(&UnitKind::Context) {
264            continue;
265        }
266        let mut here: Vec<(Span, &String, usize)> = Vec::new();
267        for &i in indices {
268            let SourceUnit::Context(ctx) = &parsed[i].unit() else {
269                continue;
270            };
271            for item in &ctx.items {
272                let CommonsItem::Service(s) = item else {
273                    continue;
274                };
275                if let ServiceProtocol::Email { address } = &s.protocol
276                    && address_problem(address).is_none()
277                {
278                    here.push((s.name.span, address, i));
279                }
280            }
281        }
282        here.sort_by_key(|(span, _, _)| *span);
283        for (span, address, i) in here {
284            match first.get(&claim_key(address)) {
285                Some(other) if *other != name.as_str() => errors.push_for(
286                    Some(&parsed[i].identity_path()),
287                    CompileError::new(
288                        "bynk.email.duplicate_address",
289                        span,
290                        format!("context `{other}` already claims `{address}`"),
291                    )
292                    .with_note(
293                        "mail is routed project-wide by its envelope recipient, so each address has one service in the whole project; a literal address and `*@domain` may coexist, and the literal wins",
294                    ),
295                ),
296                Some(_) => {}
297                None => {
298                    first.insert(claim_key(address), name.as_str());
299                }
300            }
301        }
302    }
303}
304
305/// The addresses a context's `from email` services claim, lower-cased (Email
306/// Routing matches without regard to case, ADR 0805 A), sorted and de-duplicated:
307/// what the Worker's `wrangler.toml` lists as its top-level `addresses`.
308pub fn routed_addresses(table: &crate::symbols::UnitTable) -> Vec<String> {
309    let mut addresses: Vec<String> = table
310        .services
311        .values()
312        .filter_map(|s| match &s.protocol {
313            ServiceProtocol::Email { address } => Some(address.to_lowercase()),
314            _ => None,
315        })
316        .collect();
317    addresses.sort();
318    addresses.dedup();
319    addresses
320}
321
322#[cfg(test)]
323mod tests {
324    use super::address_problem;
325
326    #[test]
327    fn addresses() {
328        for ok in ["[email protected]", "*@shop.example", "[email protected]"] {
329            assert_eq!(address_problem(ok), None, "{ok}");
330        }
331        for bad in [
332            "support",
333            "@shop.example",
334            "a@b",
335            "a [email protected]",
336            "Support <[email protected]>",
337            "a*@shop.example",
338            "[email protected]",
339            "[email protected]",
340            "[email protected],[email protected]",
341        ] {
342            assert!(address_problem(bad).is_some(), "{bad}");
343        }
344    }
345}