openzeppelin_monitor/services/notification/
email.rs

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
//! Email notification implementation.
//!
//! Provides functionality to send formatted messages to email addresses
//! via SMTP, supporting message templates with variable substitution.

use async_trait::async_trait;
use email_address::EmailAddress;
use lettre::{
	message::{
		header::{self, ContentType},
		Mailbox, Mailboxes,
	},
	transport::smtp::authentication::Credentials,
	Message, SmtpTransport, Transport,
};
use std::collections::HashMap;

use crate::{
	models::TriggerTypeConfig,
	services::notification::{NotificationError, Notifier},
};
use pulldown_cmark::{html, Options, Parser};

/// Implementation of email notifications via SMTP
pub struct EmailNotifier<T: Transport + Send + Sync> {
	/// Email subject
	subject: String,
	/// Message template with variable placeholders
	body_template: String,
	/// SMTP client for email delivery
	client: T,
	/// Email sender
	sender: EmailAddress,
	/// Email recipients
	recipients: Vec<EmailAddress>,
}

/// Configuration for SMTP connection
#[derive(Clone)]
pub struct SmtpConfig {
	pub host: String,
	pub port: u16,
	pub username: String,
	pub password: String,
}

/// Configuration for email content
#[derive(Clone)]
pub struct EmailContent {
	pub subject: String,
	pub body_template: String,
	pub sender: EmailAddress,
	pub recipients: Vec<EmailAddress>,
}

impl<T: Transport + Send + Sync> EmailNotifier<T>
where
	T::Error: std::fmt::Display,
{
	/// Creates a new email notifier instance with a custom transport
	///
	/// # Arguments
	/// * `email_content` - Email content configuration
	/// * `transport` - SMTP transport
	///
	/// # Returns
	/// * `Self` - Email notifier instance
	pub fn with_transport(email_content: EmailContent, transport: T) -> Self {
		Self {
			subject: email_content.subject,
			body_template: email_content.body_template,
			sender: email_content.sender,
			recipients: email_content.recipients,
			client: transport,
		}
	}
}

impl EmailNotifier<SmtpTransport> {
	/// Creates a new email notifier instance
	///
	/// # Arguments
	/// * `smtp_config` - SMTP server configuration
	/// * `email_content` - Email content configuration
	///
	/// # Returns
	/// * `Result<Self, NotificationError>` - Email notifier instance or error
	pub fn new(
		smtp_config: SmtpConfig,
		email_content: EmailContent,
	) -> Result<Self, Box<NotificationError>> {
		let client = SmtpTransport::relay(&smtp_config.host)
			.map_err(|e| {
				NotificationError::internal_error(
					format!("Failed to create SMTP relay: {}", e),
					None,
					None,
				)
			})?
			.port(smtp_config.port)
			.credentials(Credentials::new(smtp_config.username, smtp_config.password))
			.build();

		Ok(Self {
			subject: email_content.subject,
			body_template: email_content.body_template,
			sender: email_content.sender,
			recipients: email_content.recipients,
			client,
		})
	}

	/// Formats a message by substituting variables in the template and converts it to HTML
	///
	/// # Arguments
	/// * `variables` - Map of variable names to values
	///
	/// # Returns
	/// * `String` - Formatted message with variables replaced and converted to HTML
	pub fn format_message(&self, variables: &HashMap<String, String>) -> String {
		let formatted_message = variables
			.iter()
			.fold(self.body_template.clone(), |message, (key, value)| {
				message.replace(&format!("${{{}}}", key), value)
			});

		Self::markdown_to_html(&formatted_message)
	}

	/// Convert a Markdown string into HTML
	pub fn markdown_to_html(md: &str) -> String {
		// enable all the extensions you like; or just Parser::new(md) for pure CommonMark
		let opts = Options::all();
		let parser = Parser::new_ext(md, opts);

		let mut html_out = String::new();
		html::push_html(&mut html_out, parser);
		html_out
	}

	/// Creates an email notifier from a trigger configuration
	///
	/// # Arguments
	/// * `config` - Trigger configuration containing email parameters
	///
	/// # Returns
	/// * `Option<Self>` - Notifier instance if config is email type
	pub fn from_config(config: &TriggerTypeConfig) -> Option<Self> {
		match config {
			TriggerTypeConfig::Email {
				host,
				port,
				username,
				password,
				message,
				sender,
				recipients,
			} => {
				let smtp_config = SmtpConfig {
					host: host.clone(),
					port: port.unwrap_or(465),
					username: username.as_ref().to_string(),
					password: password.as_ref().to_string(),
				};

				let email_content = EmailContent {
					subject: message.title.clone(),
					body_template: message.body.clone(),
					sender: sender.clone(),
					recipients: recipients.clone(),
				};

				Self::new(smtp_config, email_content).ok()
			}
			_ => None,
		}
	}
}

#[async_trait]
impl<T: Transport + Send + Sync> Notifier for EmailNotifier<T>
where
	T::Error: std::fmt::Display,
{
	/// Sends a formatted message to email
	///
	/// # Arguments
	/// * `message` - The formatted message to send
	///
	/// # Returns
	/// * `Result<(), anyhow::Error>` - Success or error
	async fn notify(&self, message: &str) -> Result<(), anyhow::Error> {
		let recipients_str = self
			.recipients
			.iter()
			.map(ToString::to_string)
			.collect::<Vec<_>>()
			.join(", ");

		let mailboxes: Mailboxes = recipients_str
			.parse::<Mailboxes>()
			.map_err(|e| anyhow::anyhow!(e.to_string()))?;
		let recipients_header: header::To = mailboxes.into();

		let email = Message::builder()
			.mailbox(recipients_header)
			.from(
				self.sender
					.to_string()
					.parse::<Mailbox>()
					.map_err(|e| anyhow::anyhow!(e.to_string()))?,
			)
			.reply_to(
				self.sender
					.to_string()
					.parse::<Mailbox>()
					.map_err(|e| anyhow::anyhow!(e.to_string()))?,
			)
			.subject(&self.subject)
			.header(ContentType::TEXT_HTML)
			.body(message.to_owned())
			.map_err(|e| anyhow::anyhow!(e.to_string()))?;

		self.client
			.send(&email)
			.map_err(|e| anyhow::anyhow!(e.to_string()))?;

		Ok(())
	}
}

#[cfg(test)]
mod tests {
	use crate::models::{NotificationMessage, SecretString, SecretValue};

	use super::*;

	fn create_test_notifier() -> EmailNotifier<SmtpTransport> {
		let smtp_config = SmtpConfig {
			host: "dummy.smtp.com".to_string(),
			port: 465,
			username: "test".to_string(),
			password: "test".to_string(),
		};

		let email_content = EmailContent {
			subject: "Test Subject".to_string(),
			body_template: "Hello ${name}, your balance is ${balance}".to_string(),
			sender: "sender@test.com".parse().unwrap(),
			recipients: vec!["recipient@test.com".parse().unwrap()],
		};

		EmailNotifier::new(smtp_config, email_content).unwrap()
	}

	fn create_test_email_config(port: Option<u16>) -> TriggerTypeConfig {
		TriggerTypeConfig::Email {
			host: "smtp.test.com".to_string(),
			port,
			username: SecretValue::Plain(SecretString::new("testuser".to_string())),
			password: SecretValue::Plain(SecretString::new("testpass".to_string())),
			message: NotificationMessage {
				title: "Test Subject".to_string(),
				body: "Hello ${name}".to_string(),
			},
			sender: "sender@test.com".parse().unwrap(),
			recipients: vec!["recipient@test.com".parse().unwrap()],
		}
	}

	////////////////////////////////////////////////////////////
	// format_message tests
	////////////////////////////////////////////////////////////

	#[test]
	fn test_format_message_basic_substitution() {
		let notifier = create_test_notifier();
		let mut variables = HashMap::new();
		variables.insert("name".to_string(), "Alice".to_string());
		variables.insert("balance".to_string(), "100".to_string());

		let result = notifier.format_message(&variables);
		let expected_result = "<p>Hello Alice, your balance is 100</p>\n";
		assert_eq!(result, expected_result);
	}

	#[test]
	fn test_format_message_missing_variable() {
		let notifier = create_test_notifier();
		let mut variables = HashMap::new();
		variables.insert("name".to_string(), "Bob".to_string());

		let result = notifier.format_message(&variables);
		let expected_result = "<p>Hello Bob, your balance is ${balance}</p>\n";
		assert_eq!(result, expected_result);
	}

	#[test]
	fn test_format_message_empty_variables() {
		let notifier = create_test_notifier();
		let variables = HashMap::new();

		let result = notifier.format_message(&variables);
		let expected_result = "<p>Hello ${name}, your balance is ${balance}</p>\n";
		assert_eq!(result, expected_result);
	}

	#[test]
	fn test_format_message_with_empty_values() {
		let notifier = create_test_notifier();
		let mut variables = HashMap::new();
		variables.insert("name".to_string(), "".to_string());
		variables.insert("balance".to_string(), "".to_string());

		let result = notifier.format_message(&variables);
		let expected_result = "<p>Hello , your balance is</p>\n";
		assert_eq!(result, expected_result);
	}

	////////////////////////////////////////////////////////////
	// from_config tests
	////////////////////////////////////////////////////////////

	#[test]
	fn test_from_config_valid_email_config() {
		let config = create_test_email_config(Some(587));

		let notifier = EmailNotifier::from_config(&config);
		assert!(notifier.is_some());

		let notifier = notifier.unwrap();
		assert_eq!(notifier.subject, "Test Subject");
		assert_eq!(notifier.body_template, "Hello ${name}");
		assert_eq!(notifier.sender.to_string(), "sender@test.com");
		assert_eq!(notifier.recipients.len(), 1);
		assert_eq!(notifier.recipients[0].to_string(), "recipient@test.com");
	}

	#[test]
	fn test_from_config_default_port() {
		let config = create_test_email_config(None);

		let notifier = EmailNotifier::from_config(&config);
		assert!(notifier.is_some());
	}

	////////////////////////////////////////////////////////////
	// notify tests
	////////////////////////////////////////////////////////////

	#[tokio::test]
	async fn test_notify_failure() {
		let notifier = create_test_notifier();
		let result = notifier.notify("Test message").await;
		// Expected to fail since we're using a dummy SMTP server
		assert!(result.is_err());
	}
}