alien-core 2.1.1

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use crate::error::{ErrorData, Result};
use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef};
use crate::ResourceType;
use alien_error::AlienError;
use bon::Builder;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::BTreeMap;
use std::fmt::Debug;

/// Email infrastructure for sending and receiving mail on customer-owned
/// domains. On AWS this is backed by SES: a shared configuration set, optional
/// inbound/event wiring, and one email identity (Easy DKIM) per seed domain.
///
/// # Infrastructure vs runtime data
///
/// This resource owns the email *infrastructure* and the capability to use it,
/// not the domain lifecycle. Deployment manages the configuration set, the
/// event topology, the inbound receipt topology, and any seed identities
/// listed in `domains`. Email identities created at runtime through the
/// `email/manage-identities` grant are application data: they are not tracked
/// by the deployment, are not removed when the stack is deleted, and their
/// lifecycle — including deletion — belongs to the application.
///
/// The operator (or the application, for runtime-created identities) owns DNS:
/// the per-domain DKIM CNAME records surfaced in [`EmailOutputs`] must be
/// created before SES verifies a domain and allows sending from it.
///
/// # Inbound mail (AWS)
///
/// When `inbound` is set, a SES receipt rule set is provisioned that writes
/// raw incoming mail into the linked Storage bucket. The receipt rule is a
/// catch-all (no recipient filter), so mail for identities verified at runtime
/// lands in the bucket without any infrastructure change. Two caveats apply:
///
/// * SES allows only **one active receipt rule set per AWS account**, and
///   CloudFormation has no resource that activates a rule set. Activating the
///   provisioned rule set is a documented post-deploy step:
///   `aws ses set-active-receipt-rule-set --rule-set-name <ruleSetName>`.
/// * SES email receiving is only available in a subset of AWS regions (see the
///   SES endpoints documentation). Deploying `inbound` to an unsupported
///   region fails at the CloudFormation layer.
///
/// # Update semantics
///
/// `domains` is append-friendly: adding a domain provisions a new identity,
/// removing a domain deletes its identity (and its DKIM verification state).
/// The list may be empty. `inbound` and `events` may be added, removed, or
/// repointed; removing them tears down the corresponding receipt rule set /
/// event destination wiring.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(start_fn = new)]
pub struct Email {
    /// Identifier for the email resource. Must contain only alphanumeric
    /// characters, hyphens, and underscores ([A-Za-z0-9-_]). Maximum 64 characters.
    #[builder(start_fn)]
    pub id: String,

    /// Seed mail domains provisioned at deploy time (one SES identity each).
    /// Useful for day-0 bootstrap and products with a static domain set.
    /// May be empty (the default): products that create and verify domains
    /// dynamically should manage identities at runtime through the
    /// `email/manage-identities` grant instead of listing them here.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[builder(default)]
    pub domains: Vec<String>,

    /// Optional inbound-mail configuration: raw incoming mail (for any
    /// identity the account receives mail for — the receipt rule is a
    /// catch-all) is written to the linked Storage bucket.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inbound: Option<EmailInbound>,

    /// Optional sending-event configuration: send / delivery / bounce /
    /// complaint / delivery-delay / reject events are delivered to the
    /// linked Queue.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub events: Option<EmailEvents>,
}

/// Inbound-mail configuration for an [`Email`] resource.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EmailInbound {
    /// The Storage resource that receives raw incoming mail objects.
    pub storage: ResourceRef,
}

/// Sending-event configuration for an [`Email`] resource.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EmailEvents {
    /// The Queue resource that receives sending events.
    pub queue: ResourceRef,
}

impl Email {
    /// The resource type identifier for Email.
    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("email");

    /// Returns the email resource's unique identifier.
    pub fn id(&self) -> &str {
        &self.id
    }
}

/// A single DKIM CNAME record the operator must create in DNS.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct EmailDkimToken {
    /// CNAME record host name.
    pub name: String,
    /// CNAME record value.
    pub value: String,
}

/// Per-domain DNS records the operator must create.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct EmailDomainOutputs {
    /// Easy-DKIM CNAME tokens (three per domain). The domain is verified once
    /// these records exist in its DNS configuration.
    pub dkim_tokens: Vec<EmailDkimToken>,
}

/// Outputs generated by a successfully provisioned Email resource.
///
/// Domain verification status cannot be known at provisioning time — SES
/// verifies a domain asynchronously once its DKIM records exist in DNS — so
/// the outputs carry the records the operator must create rather than a
/// verification result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct EmailOutputs {
    /// DNS records per mail domain.
    pub domains: BTreeMap<String, EmailDomainOutputs>,
    /// The provisioned configuration set name (used when sending).
    pub configuration_set: String,
    /// The inbound receipt rule set name, when `inbound` is configured.
    /// Activating it is a manual post-deploy step — CloudFormation cannot
    /// activate a receipt rule set, and only one can be active per account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rule_set_name: Option<String>,
}

impl ResourceOutputsDefinition for EmailOutputs {
    fn get_resource_type(&self) -> ResourceType {
        Email::RESOURCE_TYPE.clone()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
        Box::new(self.clone())
    }

    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
        other.as_any().downcast_ref::<EmailOutputs>() == Some(self)
    }

    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
        serde_json::to_value(self)
    }
}

impl ResourceDefinition for Email {
    fn get_resource_type(&self) -> ResourceType {
        Self::RESOURCE_TYPE
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn get_dependencies(&self) -> Vec<ResourceRef> {
        let mut dependencies = Vec::new();
        if let Some(inbound) = &self.inbound {
            dependencies.push(inbound.storage.clone());
        }
        if let Some(events) = &self.events {
            dependencies.push(events.queue.clone());
        }
        dependencies
    }

    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
        let new_email = new_config.as_any().downcast_ref::<Email>().ok_or_else(|| {
            AlienError::new(ErrorData::UnexpectedResourceType {
                resource_id: self.id.clone(),
                expected: Self::RESOURCE_TYPE,
                actual: new_config.get_resource_type(),
            })
        })?;

        if self.id != new_email.id {
            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
                resource_id: self.id.clone(),
                reason: "the 'id' field is immutable".to_string(),
            }));
        }

        // Seed domains are append-friendly: adding provisions a new identity
        // and removing deletes one (including its DKIM verification state).
        // An empty list is valid — runtime-created identities are managed
        // outside the deployment.

        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
        Box::new(self.clone())
    }

    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
        other.as_any().downcast_ref::<Email>() == Some(self)
    }

    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
        serde_json::to_value(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resources::{Queue, Storage};

    fn email_with_links() -> Email {
        let storage = Storage::new("mailbox".to_string()).build();
        let queue = Queue::new("mail-events".to_string()).build();
        Email::new("mailer".to_string())
            .domains(vec!["mail.example.com".to_string()])
            .inbound(EmailInbound {
                storage: ResourceRef::from(&storage),
            })
            .events(EmailEvents {
                queue: ResourceRef::from(&queue),
            })
            .build()
    }

    #[test]
    fn builder_produces_expected_config() {
        let email = email_with_links();
        assert_eq!(email.id, "mailer");
        assert_eq!(email.domains, vec!["mail.example.com"]);
        assert_eq!(
            email.inbound.as_ref().expect("inbound").storage.id,
            "mailbox"
        );
        assert_eq!(
            email.events.as_ref().expect("events").queue.id,
            "mail-events"
        );
    }

    #[test]
    fn resource_type_is_email() {
        assert_eq!(Email::RESOURCE_TYPE.as_ref(), "email");
    }

    #[test]
    fn dependencies_include_inbound_storage_and_events_queue() {
        let email = email_with_links();
        let dependencies = email.get_dependencies();
        assert_eq!(dependencies.len(), 2);
        assert_eq!(dependencies[0].resource_type, Storage::RESOURCE_TYPE);
        assert_eq!(dependencies[0].id, "mailbox");
        assert_eq!(dependencies[1].resource_type, Queue::RESOURCE_TYPE);
        assert_eq!(dependencies[1].id, "mail-events");
    }

    #[test]
    fn dependencies_are_empty_without_links() {
        let email = Email::new("mailer".to_string())
            .domains(vec!["mail.example.com".to_string()])
            .build();
        assert!(email.get_dependencies().is_empty());
    }

    #[test]
    fn validate_update_rejects_id_change() {
        let original = Email::new("mailer".to_string())
            .domains(vec!["mail.example.com".to_string()])
            .build();
        let renamed = Email::new("other".to_string())
            .domains(vec!["mail.example.com".to_string()])
            .build();

        let error = original
            .validate_update(&renamed)
            .expect_err("changing the id must be rejected");
        assert!(error.to_string().contains("'id' field is immutable"));
    }

    #[test]
    fn validate_update_allows_adding_and_removing_domains() {
        let original = Email::new("mailer".to_string())
            .domains(vec![
                "mail.example.com".to_string(),
                "mail.example.org".to_string(),
            ])
            .build();
        let appended = Email::new("mailer".to_string())
            .domains(vec![
                "mail.example.com".to_string(),
                "mail.example.org".to_string(),
                "mail.example.net".to_string(),
            ])
            .build();
        let removed = Email::new("mailer".to_string())
            .domains(vec!["mail.example.com".to_string()])
            .build();

        original
            .validate_update(&appended)
            .expect("adding a domain must be allowed");
        original
            .validate_update(&removed)
            .expect("removing a domain must be allowed");
    }

    #[test]
    fn validate_update_allows_removing_all_seed_domains() {
        let original = Email::new("mailer".to_string())
            .domains(vec!["mail.example.com".to_string()])
            .build();
        let emptied = Email::new("mailer".to_string()).build();

        original
            .validate_update(&emptied)
            .expect("removing all seed domains must be allowed");
    }

    #[test]
    fn builder_defaults_to_no_seed_domains() {
        let email = Email::new("mailer".to_string()).build();
        assert!(email.domains.is_empty());
        assert!(email.inbound.is_none());
        assert!(email.events.is_none());
        assert!(email.get_dependencies().is_empty());
    }

    #[test]
    fn empty_domains_are_omitted_from_serialization_and_roundtrip() {
        let email = Email::new("mailer".to_string()).build();
        let json = serde_json::to_value(&email).expect("email should serialize");
        assert_eq!(json, serde_json::json!({ "id": "mailer" }));

        let roundtrip: Email = serde_json::from_value(json).expect("email should deserialize");
        assert_eq!(email, roundtrip);
    }

    #[test]
    fn validate_update_allows_link_changes() {
        let original = email_with_links();
        let unlinked = Email::new("mailer".to_string())
            .domains(vec!["mail.example.com".to_string()])
            .build();

        original
            .validate_update(&unlinked)
            .expect("removing inbound/events must be allowed");
        unlinked
            .validate_update(&original)
            .expect("adding inbound/events must be allowed");
    }

    #[test]
    fn serializes_with_camel_case_and_roundtrips() {
        let email = email_with_links();
        let json = serde_json::to_value(&email).expect("email should serialize");
        assert_eq!(json["domains"][0], "mail.example.com");
        assert_eq!(json["inbound"]["storage"]["id"], "mailbox");
        assert_eq!(json["inbound"]["storage"]["type"], "storage");
        assert_eq!(json["events"]["queue"]["id"], "mail-events");

        let roundtrip: Email = serde_json::from_value(json).expect("email should deserialize");
        assert_eq!(email, roundtrip);
    }

    #[test]
    fn outputs_roundtrip() {
        let outputs = EmailOutputs {
            domains: BTreeMap::from([(
                "mail.example.com".to_string(),
                EmailDomainOutputs {
                    dkim_tokens: vec![EmailDkimToken {
                        name: "token._domainkey.mail.example.com".to_string(),
                        value: "token.dkim.amazonses.com".to_string(),
                    }],
                },
            )]),
            configuration_set: "stack-mailer".to_string(),
            rule_set_name: Some("stack-mailer".to_string()),
        };
        let json = serde_json::to_string(&outputs).expect("outputs should serialize");
        let deserialized: EmailOutputs =
            serde_json::from_str(&json).expect("outputs should deserialize");
        assert_eq!(outputs, deserialized);
    }
}