fakecloud-ses 0.12.0

SES implementation for FakeCloud (v2 REST + v1 inbound Query)
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! SES event fanout: publishes send/delivery/bounce/complaint events
//! to configured event destinations (SNS topics, EventBridge buses).

use chrono::Utc;
use serde_json::json;
use std::sync::Arc;

use fakecloud_core::delivery::DeliveryBus;

use crate::state::{EventDestination, SentEmail, SharedSesState, SuppressedDestination};

/// Shared references needed for cross-service event delivery.
#[derive(Clone)]
pub struct SesDeliveryContext {
    pub ses_state: SharedSesState,
    pub delivery_bus: Arc<DeliveryBus>,
}

/// Mailbox simulator addresses.
const BOUNCE_ADDR: &str = "bounce@simulator.amazonses.com";
const COMPLAINT_ADDR: &str = "complaint@simulator.amazonses.com";
#[cfg(test)]
const SUCCESS_ADDR: &str = "success@simulator.amazonses.com";
const SUPPRESSION_ADDR: &str = "suppressionlist@simulator.amazonses.com";

/// The event types we generate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SesEventType {
    Send,
    Delivery,
    Bounce,
    Complaint,
}

impl SesEventType {
    fn as_str(self) -> &'static str {
        match self {
            SesEventType::Send => "SEND",
            SesEventType::Delivery => "DELIVERY",
            SesEventType::Bounce => "BOUNCE",
            SesEventType::Complaint => "COMPLAINT",
        }
    }

    fn event_type_name(self) -> &'static str {
        match self {
            SesEventType::Send => "Send",
            SesEventType::Delivery => "Delivery",
            SesEventType::Bounce => "Bounce",
            SesEventType::Complaint => "Complaint",
        }
    }
}

/// Build the SES event JSON payload matching the AWS notification format.
pub fn build_ses_event(event_type: SesEventType, email: &SentEmail) -> serde_json::Value {
    let mut event = json!({
        "eventType": event_type.event_type_name(),
        "mail": {
            "messageId": email.message_id,
            "source": email.from,
            "destination": email.to,
            "timestamp": email.timestamp.to_rfc3339(),
        },
    });

    // Add event-type-specific detail blocks
    match event_type {
        SesEventType::Send => {
            event["send"] = json!({});
        }
        SesEventType::Delivery => {
            event["delivery"] = json!({
                "timestamp": Utc::now().to_rfc3339(),
                "recipients": email.to,
                "processingTimeMillis": 42,
                "smtpResponse": "250 2.0.0 Ok",
            });
        }
        SesEventType::Bounce => {
            let bounced: Vec<serde_json::Value> = email
                .to
                .iter()
                .map(|addr| {
                    json!({
                        "emailAddress": addr,
                        "action": "failed",
                        "status": "5.1.1",
                        "diagnosticCode": "smtp; 550 5.1.1 user unknown",
                    })
                })
                .collect();
            event["bounce"] = json!({
                "bounceType": "Permanent",
                "bounceSubType": "General",
                "bouncedRecipients": bounced,
                "timestamp": Utc::now().to_rfc3339(),
            });
        }
        SesEventType::Complaint => {
            let complained: Vec<serde_json::Value> = email
                .to
                .iter()
                .map(|addr| json!({ "emailAddress": addr }))
                .collect();
            event["complaint"] = json!({
                "complainedRecipients": complained,
                "complaintFeedbackType": "abuse",
                "timestamp": Utc::now().to_rfc3339(),
            });
        }
    }

    event
}

/// Determine which event types to generate based on recipient addresses.
/// Returns the list of event types to emit and whether to add to suppression list.
pub fn classify_recipients(recipients: &[String]) -> (Vec<SesEventType>, bool) {
    let mut events = Vec::new();
    let mut suppress = false;

    // Check for simulator addresses in any recipient
    let has_bounce = recipients.iter().any(|r| r == BOUNCE_ADDR);
    let has_complaint = recipients.iter().any(|r| r == COMPLAINT_ADDR);
    let has_suppression = recipients.iter().any(|r| r == SUPPRESSION_ADDR);
    // success@simulator is the default behavior, no special handling needed

    if has_bounce {
        events.push(SesEventType::Send);
        events.push(SesEventType::Bounce);
    } else if has_complaint {
        events.push(SesEventType::Send);
        events.push(SesEventType::Delivery);
        events.push(SesEventType::Complaint);
    } else if has_suppression {
        events.push(SesEventType::Send);
        events.push(SesEventType::Bounce);
        suppress = true;
    } else {
        // Normal send or success@simulator
        events.push(SesEventType::Send);
        events.push(SesEventType::Delivery);
    }

    (events, suppress)
}

/// Check if any recipient is on the suppression list.
/// Returns the suppressed address if found.
pub fn check_suppression_list(ses_state: &SharedSesState, recipients: &[String]) -> Option<String> {
    let mas = ses_state.read();
    let state = mas.default_ref();
    for addr in recipients {
        if state.suppressed_destinations.contains_key(addr) {
            return Some(addr.clone());
        }
    }
    None
}

/// Resolve the configuration set name for an email send.
/// Checks the explicit request param first, then the identity's default.
pub fn resolve_config_set(
    ses_state: &SharedSesState,
    explicit_config_set: Option<&str>,
    from_address: &str,
) -> Option<String> {
    if let Some(name) = explicit_config_set {
        return Some(name.to_string());
    }

    // Check identity's default configuration set
    let mas = ses_state.read();
    let state = mas.default_ref();
    if let Some(identity) = state.identities.get(from_address) {
        return identity.configuration_set_name.clone();
    }
    // Also check domain identity
    if let Some(at_pos) = from_address.find('@') {
        let domain = &from_address[at_pos + 1..];
        if let Some(identity) = state.identities.get(domain) {
            return identity.configuration_set_name.clone();
        }
    }
    None
}

/// Get enabled event destinations for a configuration set that match the given event type.
fn get_matching_destinations(
    ses_state: &SharedSesState,
    config_set_name: &str,
    event_type: SesEventType,
) -> Vec<EventDestination> {
    let mas = ses_state.read();
    let state = mas.default_ref();
    let event_type_str = event_type.as_str();

    state
        .event_destinations
        .get(config_set_name)
        .map(|dests| {
            dests
                .iter()
                .filter(|d| d.enabled && d.matching_event_types.iter().any(|t| t == event_type_str))
                .cloned()
                .collect()
        })
        .unwrap_or_default()
}

/// Fan out a single event to all matching destinations.
fn deliver_event(
    ctx: &SesDeliveryContext,
    event: &serde_json::Value,
    event_type: SesEventType,
    config_set_name: &str,
) {
    let destinations = get_matching_destinations(&ctx.ses_state, config_set_name, event_type);

    for dest in destinations {
        // SNS destination
        if let Some(ref sns_dest) = dest.sns_destination {
            if let Some(topic_arn) = sns_dest["TopicArn"].as_str() {
                let message = event.to_string();
                tracing::info!(
                    topic_arn = %topic_arn,
                    event_type = ?event_type,
                    "SES event fanout -> SNS"
                );
                ctx.delivery_bus.publish_to_sns(
                    topic_arn,
                    &message,
                    Some("Amazon SES Email Event"),
                );
            }
        }

        // EventBridge destination
        if dest.event_bridge_destination.is_some() {
            let detail = event.to_string();
            tracing::info!(
                event_type = ?event_type,
                "SES event fanout -> EventBridge"
            );
            ctx.delivery_bus.put_event_to_eventbridge(
                "aws.ses",
                "SES Email Sending",
                &detail,
                "default",
            );
        }
    }
}

/// Process event fanout for a sent email.
///
/// This is the main entry point called from SendEmail / SendBulkEmail.
/// It:
/// 1. Checks the suppression list (returns true if suppressed → caller should bounce)
/// 2. Classifies recipients for mailbox simulator behavior
/// 3. Generates appropriate events
/// 4. Fans out to configured destinations
///
/// Returns `true` if the email was suppressed (caller should handle accordingly).
pub fn process_send_events(
    ctx: &SesDeliveryContext,
    email: &SentEmail,
    config_set_name: Option<&str>,
) -> bool {
    let config_set = match resolve_config_set(&ctx.ses_state, config_set_name, &email.from) {
        Some(cs) => cs,
        None => return false, // No config set, no event destinations to fan out to
    };

    // Check suppression list
    if let Some(suppressed_addr) = check_suppression_list(&ctx.ses_state, &email.to) {
        tracing::info!(
            address = %suppressed_addr,
            "SES: recipient is on suppression list, generating bounce"
        );
        let bounce_event = build_ses_event(SesEventType::Bounce, email);
        deliver_event(ctx, &bounce_event, SesEventType::Bounce, &config_set);
        return true;
    }

    // Classify recipients for simulator behavior
    let (event_types, add_to_suppression) = classify_recipients(&email.to);

    // Handle suppression list addition
    if add_to_suppression {
        let mut mas = ctx.ses_state.write();
        let state = mas.default_mut();
        for addr in &email.to {
            if addr == SUPPRESSION_ADDR {
                state.suppressed_destinations.insert(
                    addr.clone(),
                    SuppressedDestination {
                        email_address: addr.clone(),
                        reason: "BOUNCE".to_string(),
                        last_update_time: Utc::now(),
                    },
                );
            }
        }
    }

    // Generate and deliver events
    for event_type in event_types {
        let event = build_ses_event(event_type, email);
        deliver_event(ctx, &event, event_type, &config_set);
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classify_normal_recipients() {
        let (events, suppress) = classify_recipients(&["user@example.com".to_string()]);
        assert_eq!(events.len(), 2);
        assert_eq!(events[0], SesEventType::Send);
        assert_eq!(events[1], SesEventType::Delivery);
        assert!(!suppress);
    }

    #[test]
    fn classify_bounce_simulator() {
        let (events, suppress) = classify_recipients(&[BOUNCE_ADDR.to_string()]);
        assert_eq!(events.len(), 2);
        assert_eq!(events[0], SesEventType::Send);
        assert_eq!(events[1], SesEventType::Bounce);
        assert!(!suppress);
    }

    #[test]
    fn classify_complaint_simulator() {
        let (events, suppress) = classify_recipients(&[COMPLAINT_ADDR.to_string()]);
        assert_eq!(events.len(), 3);
        assert_eq!(events[0], SesEventType::Send);
        assert_eq!(events[1], SesEventType::Delivery);
        assert_eq!(events[2], SesEventType::Complaint);
        assert!(!suppress);
    }

    #[test]
    fn classify_suppression_simulator() {
        let (events, suppress) = classify_recipients(&[SUPPRESSION_ADDR.to_string()]);
        assert_eq!(events.len(), 2);
        assert_eq!(events[0], SesEventType::Send);
        assert_eq!(events[1], SesEventType::Bounce);
        assert!(suppress);
    }

    #[test]
    fn classify_success_simulator() {
        let (events, suppress) = classify_recipients(&[SUCCESS_ADDR.to_string()]);
        assert_eq!(events.len(), 2);
        assert_eq!(events[0], SesEventType::Send);
        assert_eq!(events[1], SesEventType::Delivery);
        assert!(!suppress);
    }

    #[test]
    fn build_send_event_format() {
        let email = SentEmail {
            message_id: "test-msg-id".to_string(),
            from: "sender@example.com".to_string(),
            to: vec!["recipient@example.com".to_string()],
            cc: vec![],
            bcc: vec![],
            subject: Some("Hello".to_string()),
            html_body: None,
            text_body: None,
            raw_data: None,
            template_name: None,
            template_data: None,
            timestamp: Utc::now(),
        };
        let event = build_ses_event(SesEventType::Send, &email);
        assert_eq!(event["eventType"], "Send");
        assert_eq!(event["mail"]["messageId"], "test-msg-id");
        assert_eq!(event["mail"]["source"], "sender@example.com");
        assert!(event["send"].is_object());
    }

    #[test]
    fn build_bounce_event_format() {
        let email = SentEmail {
            message_id: "bounce-msg".to_string(),
            from: "sender@example.com".to_string(),
            to: vec!["bounce@simulator.amazonses.com".to_string()],
            cc: vec![],
            bcc: vec![],
            subject: None,
            html_body: None,
            text_body: None,
            raw_data: None,
            template_name: None,
            template_data: None,
            timestamp: Utc::now(),
        };
        let event = build_ses_event(SesEventType::Bounce, &email);
        assert_eq!(event["eventType"], "Bounce");
        assert_eq!(event["bounce"]["bounceType"], "Permanent");
        assert!(event["bounce"]["bouncedRecipients"].is_array());
    }

    #[test]
    fn build_delivery_event_format() {
        let email = SentEmail {
            message_id: "deliver-msg".to_string(),
            from: "sender@example.com".to_string(),
            to: vec!["user@example.com".to_string()],
            cc: vec![],
            bcc: vec![],
            subject: None,
            html_body: None,
            text_body: None,
            raw_data: None,
            template_name: None,
            template_data: None,
            timestamp: Utc::now(),
        };
        let event = build_ses_event(SesEventType::Delivery, &email);
        assert_eq!(event["eventType"], "Delivery");
        assert!(event["delivery"]["timestamp"].is_string());
        assert_eq!(event["delivery"]["smtpResponse"], "250 2.0.0 Ok");
    }

    #[test]
    fn build_complaint_event_format() {
        let email = SentEmail {
            message_id: "complaint-msg".to_string(),
            from: "sender@example.com".to_string(),
            to: vec!["complaint@simulator.amazonses.com".to_string()],
            cc: vec![],
            bcc: vec![],
            subject: None,
            html_body: None,
            text_body: None,
            raw_data: None,
            template_name: None,
            template_data: None,
            timestamp: Utc::now(),
        };
        let event = build_ses_event(SesEventType::Complaint, &email);
        assert_eq!(event["eventType"], "Complaint");
        assert_eq!(event["complaint"]["complaintFeedbackType"], "abuse");
    }

    #[test]
    fn classify_multiple_recipients_no_simulator() {
        let recipients = vec![
            "a@example.com".to_string(),
            "b@example.com".to_string(),
            "c@example.com".to_string(),
        ];
        let (events, suppress) = classify_recipients(&recipients);
        assert!(events.contains(&SesEventType::Send));
        assert!(events.contains(&SesEventType::Delivery));
        assert!(!suppress);
    }

    #[test]
    fn classify_empty_recipients() {
        let (events, suppress) = classify_recipients(&[]);
        assert!(!events.is_empty());
        assert!(!suppress);
    }

    fn shared_state() -> SharedSesState {
        use fakecloud_core::multi_account::MultiAccountState;
        Arc::new(parking_lot::RwLock::new(MultiAccountState::new(
            "123456789012",
            "us-east-1",
            "http://localhost:4566",
        )))
    }

    #[test]
    fn check_suppression_list_finds_suppressed() {
        let state = shared_state();
        state.write().default_mut().suppressed_destinations.insert(
            "blocked@example.com".to_string(),
            SuppressedDestination {
                email_address: "blocked@example.com".to_string(),
                reason: "BOUNCE".to_string(),
                last_update_time: Utc::now(),
            },
        );
        let hit = check_suppression_list(
            &state,
            &[
                "ok@example.com".to_string(),
                "blocked@example.com".to_string(),
            ],
        );
        assert_eq!(hit.as_deref(), Some("blocked@example.com"));
    }

    #[test]
    fn check_suppression_list_none_when_clean() {
        let state = shared_state();
        let hit = check_suppression_list(&state, &["ok@example.com".to_string()]);
        assert!(hit.is_none());
    }

    fn make_identity(name: &str, config_set: Option<&str>) -> crate::state::EmailIdentity {
        crate::state::EmailIdentity {
            identity_name: name.to_string(),
            identity_type: "EmailAddress".to_string(),
            verified: true,
            created_at: Utc::now(),
            dkim_signing_enabled: false,
            dkim_signing_attributes_origin: "AWS_SES".to_string(),
            dkim_domain_signing_private_key: None,
            dkim_domain_signing_selector: None,
            dkim_next_signing_key_length: None,
            email_forwarding_enabled: true,
            mail_from_domain: None,
            mail_from_behavior_on_mx_failure: "USE_DEFAULT_VALUE".to_string(),
            configuration_set_name: config_set.map(|s| s.to_string()),
        }
    }

    #[test]
    fn resolve_config_set_uses_explicit_arg_first() {
        let state = shared_state();
        let resolved = resolve_config_set(&state, Some("my-cs"), "sender@example.com");
        assert_eq!(resolved.as_deref(), Some("my-cs"));
    }

    #[test]
    fn resolve_config_set_uses_identity_default_when_no_explicit() {
        let state = shared_state();
        state.write().default_mut().identities.insert(
            "sender@example.com".to_string(),
            make_identity("sender@example.com", Some("identity-cs")),
        );
        let resolved = resolve_config_set(&state, None, "sender@example.com");
        assert_eq!(resolved.as_deref(), Some("identity-cs"));
    }

    #[test]
    fn resolve_config_set_falls_back_to_domain_identity() {
        let state = shared_state();
        state.write().default_mut().identities.insert(
            "example.com".to_string(),
            make_identity("example.com", Some("domain-cs")),
        );
        let resolved = resolve_config_set(&state, None, "sender@example.com");
        assert_eq!(resolved.as_deref(), Some("domain-cs"));
    }

    #[test]
    fn resolve_config_set_none_when_nothing_set() {
        let state = shared_state();
        assert!(resolve_config_set(&state, None, "sender@example.com").is_none());
    }

    #[test]
    fn get_matching_destinations_filters_by_enabled_and_event_type() {
        let state = shared_state();
        state.write().default_mut().event_destinations.insert(
            "cs".to_string(),
            vec![
                EventDestination {
                    name: "sns-dest".to_string(),
                    enabled: true,
                    matching_event_types: vec!["SEND".to_string(), "BOUNCE".to_string()],
                    kinesis_firehose_destination: None,
                    cloud_watch_destination: None,
                    sns_destination: Some(serde_json::json!({"TopicArn": "arn"})),
                    event_bridge_destination: None,
                    pinpoint_destination: None,
                },
                EventDestination {
                    name: "disabled".to_string(),
                    enabled: false,
                    matching_event_types: vec!["SEND".to_string()],
                    kinesis_firehose_destination: None,
                    cloud_watch_destination: None,
                    sns_destination: None,
                    event_bridge_destination: None,
                    pinpoint_destination: None,
                },
            ],
        );
        let dests = get_matching_destinations(&state, "cs", SesEventType::Send);
        assert_eq!(dests.len(), 1);
        assert_eq!(dests[0].name, "sns-dest");
        let none = get_matching_destinations(&state, "cs", SesEventType::Delivery);
        assert!(none.is_empty());
        let missing = get_matching_destinations(&state, "unknown", SesEventType::Send);
        assert!(missing.is_empty());
    }
}