Skip to content

Check if an email address exists without sending any email, written in Rust. Comes with a ⚙️ HTTP backend.

feat: Add sentry logging to worker

Amaury5aa6026e6147
diff --git a/.github/workflows/deploy_backend.yml b/.github/workflows/deploy_backend.yml
index 88d06057..3b82248c 100644
--- a/.github/workflows/deploy_backend.yml
+++ b/.github/workflows/deploy_backend.yml
@@ -22,3 +22,4 @@ jobs:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
tags: "${{ steps.vars.outputs.GITHUB_TAG }}"
+ dockerfile: Dockerfile.backend
diff --git a/Cargo.lock b/Cargo.lock
index 1cf4cfdd..0cddfadd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2430,10 +2430,12 @@ name = "reacher_worker"
version = "0.1.0"
dependencies = [
"async-global-executor",
+ "async-smtp",
"check-if-email-exists",
"futures-lite 2.1.0",
"lapin",
"reqwest",
+ "sentry",
"serde",
"serde_json",
"tokio",
diff --git a/Dockerfile b/Dockerfile.backend
similarity index 100%
rename from Dockerfile
rename to Dockerfile.backend
diff --git a/worker/Cargo.toml b/worker/Cargo.toml
index 8ec59402..0637bae5 100644
--- a/worker/Cargo.toml
+++ b/worker/Cargo.toml
@@ -9,11 +9,13 @@ publish = false
[dependencies]
+async-smtp = "0.6"
async-global-executor = "2.4.0"
check-if-email-exists = { path = "../core", features = ["headless"] }
futures-lite = "2.1.0"
lapin = "2.3.1"
reqwest = { version = "0.11.22", features = ["json"] }
+sentry = "0.23"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.29", features = ["macros"] }
diff --git a/worker/src/main.rs b/worker/src/main.rs
index f9f3e1da..a6668ba8 100644
--- a/worker/src/main.rs
+++ b/worker/src/main.rs
@@ -1,15 +1,36 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2023 Reacher
+
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
use std::env;
use futures_lite::StreamExt;
use lapin::{options::*, types::FieldTable, Connection, ConnectionProperties};
use tracing::{error, info};
+mod sentry_util;
mod worker;
+use sentry_util::setup_sentry;
use worker::process_check_email;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+ // Setup sentry bug tracking.
+ let _guard = setup_sentry();
+
tracing_subscriber::fmt::init();
let addr = env::var("RCH_AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672".into());
diff --git a/worker/src/sentry_util.rs b/worker/src/sentry_util.rs
new file mode 100644
index 00000000..38a1e6ca
--- /dev/null
+++ b/worker/src/sentry_util.rs
@@ -0,0 +1,189 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2023 Reacher
+
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//! Helper functions to send events to Sentry.
+//!
+//! This module also contains functions that check if the error's given by
+//! `check-if-email-exists` are known errors, in which case we don't log them
+//! to Sentry.
+
+use std::borrow::Cow;
+use std::env;
+
+use async_smtp::smtp::error::Error as AsyncSmtpError;
+use check_if_email_exists::misc::MiscError;
+use check_if_email_exists::mx::MxError;
+use check_if_email_exists::{smtp::SmtpError, CheckEmailOutput};
+use sentry::protocol::{Event, Exception, Level, Values};
+use tracing::{debug, info};
+
+use super::sentry_util;
+
+pub const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
+
+/// Setup Sentry.
+pub fn setup_sentry() -> sentry::ClientInitGuard {
+ // Use an empty string if we don't have any env variable for sentry. Sentry
+ // will just silently ignore.
+ let sentry = sentry::init(env::var("RCH_SENTRY_DSN").unwrap_or_else(|_| "".into()));
+ if sentry.is_enabled() {
+ info!("Sentry is successfully set up.")
+ }
+
+ sentry
+}
+
+/// If RCH_BACKEND_NAME environment variable is set, add it to the sentry
+/// `server_name` properties.
+/// For backwards compatibility, we also support HEROKU_APP_NAME env variable.
+fn get_backend_name<'a>() -> Option<Cow<'a, str>> {
+ if let Ok(n) = env::var("RCH_BACKEND_NAME") {
+ return Some(n.into());
+ } else if let Ok(n) = env::var("HEROKU_APP_NAME") {
+ return Some(n.into());
+ }
+
+ None
+}
+
+#[derive(Debug)]
+enum SentryError<'a> {
+ // TODO: Probably a good idea would be to `impl std:error:Error` for the
+ // three errors below.
+ Misc(&'a MiscError),
+ Mx(&'a MxError),
+ Smtp(&'a SmtpError),
+}
+
+impl<'a> SentryError<'a> {
+ /// Get the error type to be passed into Sentry's Exception `ty` field.
+ fn get_exception_type(&self) -> String {
+ match self {
+ SentryError::Misc(_) => "MiscError".into(),
+ SentryError::Mx(_) => "MxError".into(),
+ SentryError::Smtp(_) => "SmtpError".into(),
+ }
+ }
+}
+
+/// Helper function to send an Error event to Sentry. We redact all sensitive
+/// info before sending to Sentry, by removing all instances of `username`.
+fn error(err: SentryError, result: &CheckEmailOutput) {
+ let exception_value = redact(format!("{err:?}").as_str(), &result.syntax.username);
+ debug!("Sending error to Sentry: {}", exception_value);
+
+ let exception = Exception {
+ ty: err.get_exception_type(),
+ value: Some(exception_value),
+ ..Default::default()
+ };
+
+ sentry::capture_event(Event {
+ exception: Values {
+ values: vec![exception],
+ },
+ level: Level::Error,
+ environment: Some("production".into()),
+ release: Some(CARGO_PKG_VERSION.into()),
+ message: Some(redact(
+ format!("{result:#?}").as_str(),
+ &result.syntax.username,
+ )),
+ server_name: get_backend_name(),
+ transaction: Some(format!("check_email:{}", result.syntax.domain)),
+ ..Default::default()
+ });
+}
+
+/// Function to replace all usernames from email, and replace them with
+/// `***@domain.com` for privacy reasons.
+fn redact(input: &str, username: &str) -> String {
+ input.replace(username, "***")
+}
+
+/// Check if the message contains known SMTP Transient errors.
+fn skip_smtp_transient_errors(message: &[String]) -> bool {
+ let first_line = message[0].to_lowercase();
+
+ // 4.3.2 Please try again later
+ first_line.contains("try again") ||
+ // Temporary local problem - please try later
+ first_line.contains("try later")
+}
+
+/// Checks if the output from `check-if-email-exists` has a known error, in
+/// which case we don't log to Sentry to avoid spamming it.
+pub fn log_unknown_errors(result: &CheckEmailOutput) {
+ match (&result.misc, &result.mx, &result.smtp) {
+ (Err(err), _, _) => {
+ // We log all misc errors.
+ sentry_util::error(SentryError::Misc(err), result);
+ }
+ (_, Err(err), _) => {
+ // We log all mx errors.
+ sentry_util::error(SentryError::Mx(err), result);
+ }
+ (_, _, Err(err)) if err.get_description().is_some() => {
+ // If the SMTP error is known, we don't track it in Sentry.
+ }
+ (_, _, Err(SmtpError::SmtpError(AsyncSmtpError::Transient(response))))
+ if skip_smtp_transient_errors(&response.message) =>
+ {
+ // If the SMTP error is transient and known, we don't track it in
+ // Sentry, just log it locally.
+ let redacted = redact(
+ response.message[0].as_str(),
+ result.syntax.username.as_str(),
+ );
+ debug!(email=?redacted, "Transient error");
+ }
+ (_, _, Err(err)) => {
+ // If it's a SMTP error we didn't catch above, we log to
+ // Sentry, to be able to debug them better. We don't want to
+ // spam Sentry and log all instances of the error, hence the
+ // `count` check.
+ sentry_util::error(SentryError::Smtp(err), result);
+ }
+ // If everything is ok, we just return the result.
+ (Ok(_), Ok(_), Ok(_)) => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::redact;
+
+ #[test]
+ fn test_redact() {
+ assert_eq!("***@gmail.com", redact("[email protected]", "someone"));
+ assert_eq!(
+ "my email is ***@gmail.com.",
+ redact("my email is [email protected].", "someone")
+ );
+ assert_eq!(
+ "my email is ***@gmail.com., I repeat, my email is ***@gmail.com.",
+ redact(
+ "my email is [email protected]., I repeat, my email is [email protected].",
+ "someone"
+ )
+ );
+ assert_eq!(
+ "*** @ gmail . com",
+ redact("someone @ gmail . com", "someone")
+ );
+ assert_eq!("*** is here.", redact("someone is here.", "someone"));
+ }
+}
diff --git a/worker/src/worker.rs b/worker/src/worker.rs
index d768e3a8..cd3e3bb7 100644
--- a/worker/src/worker.rs
+++ b/worker/src/worker.rs
@@ -1,11 +1,31 @@
+// Reacher - Email Verification
+// Copyright (C) 2018-2023 Reacher
+
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+use std::env;
+
use check_if_email_exists::CheckEmailInput;
-use check_if_email_exists::{check_email, CheckEmailOutput};
+use check_if_email_exists::{check_email as ciee_check_email, CheckEmailOutput};
use lapin::message::Delivery;
use lapin::options::*;
use serde::Deserialize;
use serde::Serialize;
use tracing::{debug, info};
+use crate::sentry_util::log_unknown_errors;
+
#[derive(Debug, Deserialize)]
pub struct CheckEmailPayload {
pub input: CheckEmailInput,
@@ -32,7 +52,7 @@ pub async fn process_check_email(
info!(email=?payload.input.to_email, "Start check");
debug!(payload=?payload);
- let output = check_email(&payload.input).await;
+ let output = check_email(payload.input).await;
debug!(email=output.input,output=?output, "Done check-if-email-exists");
if let Some(webhook) = payload.webhook {
@@ -51,11 +71,33 @@ pub async fn process_check_email(
.text()
.await?;
debug!(email=?webhook_output.output.input,res=?res, "Received webhook response");
+ info!(email=?webhook_output.output.input, "Finished check");
}
delivery.ack(BasicAckOptions::default()).await?;
- info!(email=?payload.input.to_email, "Finished check");
-
Ok(())
}
+
+/// Same as `check-if-email-exists`'s check email, but adds some additional
+/// inputs and error handling.
+async fn check_email(input: CheckEmailInput) -> CheckEmailOutput {
+ let from_email =
+ env::var("RCH_FROM_EMAIL").unwrap_or_else(|_| CheckEmailInput::default().from_email);
+ let hello_name: String =
+ env::var("RCH_HELLO_NAME").unwrap_or_else(|_| CheckEmailInput::default().hello_name);
+
+ let input = CheckEmailInput {
+ // If we want to override core check-if-email-exists's default values
+ // for CheckEmailInput for the backend, we do it here.
+ from_email,
+ hello_name,
+ ..input
+ };
+
+ let res = ciee_check_email(&input).await;
+
+ log_unknown_errors(&res);
+
+ res
+}