Check if an email address exists without sending any email, written in Rust. Comes with a ⚙️ HTTP backend.
Rust emailemail-validationemail-validation-apiemail-verificationemail-verification-apiemail-verifierhacktoberfest
refactor!: Use config-rs instead of env vars (#1530)
Amaurybcd2dc867b7d
diff --git a/.github/workflows/deploy_backend.yml b/.github/workflows/deploy_backend.ymlindex 754bcf20..c1b700d3 100644--- a/.github/workflows/deploy_backend.yml+++ b/.github/workflows/deploy_backend.yml@@ -19,7 +19,7 @@ jobs:uses: elgohr/Publish-Docker-Github-Action@v5with:name: reacherhq/backend- dockerfile: docker/Dockerfile.backend+ dockerfile: backend/Dockerfileusername: ${{ secrets.DOCKER_USERNAME }}password: ${{ secrets.DOCKER_PASSWORD }}tags: "${{ steps.vars.outputs.GITHUB_TAG }},beta"diff --git a/.github/workflows/deploy_worker.yml b/.github/workflows/deploy_worker.ymldeleted file mode 100644index 080d546d..00000000--- a/.github/workflows/deploy_worker.yml+++ /dev/null@@ -1,25 +0,0 @@-name: deploy_worker--on:- push:- tags:- - "worker/v*.*.*"--jobs:- docker-publish:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@master- - name: Set GITHUB_TAG arg- id: vars- run: echo ::set-output name=GITHUB_TAG::${GITHUB_REF:17} # Remove /refs/head/worker/- - name: Print version- run: echo "Publishing reacherhq/worker:${{ steps.vars.outputs.GITHUB_TAG }}"- - name: Publish to Registry- uses: elgohr/Publish-Docker-Github-Action@v5- with:- name: reacherhq/worker- dockerfile: docker/Dockerfile.worker- username: ${{ secrets.DOCKER_USERNAME }}- password: ${{ secrets.DOCKER_PASSWORD }}- tags: "${{ steps.vars.outputs.GITHUB_TAG }},beta"diff --git a/Cargo.lock b/Cargo.lockindex a13236a1..d0b34519 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -246,7 +246,7 @@ dependencies = ["async-task","concurrent-queue","fastrand 2.1.0",- "futures-lite 2.3.0",+ "futures-lite 2.5.0","slab",]@@ -261,15 +261,15 @@ dependencies = ["async-io 2.3.3","async-lock 3.4.0","blocking",- "futures-lite 2.3.0",+ "futures-lite 2.5.0","once_cell",][[package]]name = "async-global-executor-trait"-version = "2.1.0"+version = "2.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "33dd14c5a15affd2abcff50d84efd4009ada28a860f01c14f9d654f3e81b3f75"+checksum = "80f19936c1a84fb48ceb8899b642d2a72572587d1021cc561bfb24de9f33ee89"dependencies = ["async-global-executor","async-trait",@@ -306,7 +306,7 @@ dependencies = ["cfg-if","concurrent-queue","futures-io",- "futures-lite 2.3.0",+ "futures-lite 2.5.0","parking","polling 3.7.2","rustix 0.38.34",@@ -524,7 +524,7 @@ dependencies = ["async-channel","async-task","futures-io",- "futures-lite 2.3.0",+ "futures-lite 2.5.0","piper",]@@ -581,6 +581,7 @@ dependencies = ["async-recursion","async-smtp","chrono",+ "config","fantoccini","fast-socks5 0.9.6","futures",@@ -1172,9 +1173,9 @@ dependencies = [[[package]]name = "executor-trait"-version = "2.1.0"+version = "2.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1a1052dd43212a7777ec6a69b117da52f5e52f07aec47d00c1a2b33b85d06b08"+checksum = "13c39dff9342e4e0e16ce96be751eb21a94e94a87bb2f6e63ad1961c2ce109bf"dependencies = ["async-trait",]@@ -1378,9 +1379,9 @@ dependencies = [[[package]]name = "futures-lite"-version = "2.3.0"+version = "2.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5"+checksum = "cef40d21ae2c515b51041df9ed313ed21e572df340ea58a922a0aefe7e8891a1"dependencies = ["fastrand 2.1.0","futures-core",@@ -2926,6 +2927,7 @@ version = "0.7.0"dependencies = ["async-smtp","check-if-email-exists",+ "config","csv","dotenv","openssl",@@ -2948,7 +2950,7 @@ dependencies = ["async-smtp","check-if-email-exists","config",- "futures-lite 2.3.0",+ "futures-lite 2.5.0","lapin","openssl","reqwest 0.12.5",@@ -4132,9 +4134,9 @@ dependencies = [[[package]]name = "tokio-executor-trait"-version = "2.1.1"+version = "2.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "802ccf58e108fe16561f35348fabe15ff38218968f033d587e399a84937533cc"+checksum = "96a1593beae7759f592e1100c5997fe9e9ebf4b5968062f1fbcd807989cd1b79"dependencies = ["async-trait","executor-trait",diff --git a/backend/Cargo.toml b/backend/Cargo.tomlindex cf71a04b..fab5e20b 100644--- a/backend/Cargo.toml+++ b/backend/Cargo.toml@@ -7,7 +7,8 @@ publish = false[dependencies]async-smtp = "0.6"-check-if-email-exists = { path = "../core", features = ["headless", "sentry"] }+check-if-email-exists = { path = "../core", features = ["sentry"] }+config = "0.14"csv = "1.3.0"dotenv = "0.15.0"openssl = { version = "0.10.64", features = ["vendored"] }diff --git a/docker/Dockerfile.backend b/backend/Dockerfilesimilarity index 84%rename from docker/Dockerfile.backendrename to backend/Dockerfileindex 7ddbfc21..fea4dbac 100644--- a/docker/Dockerfile.backend+++ b/backend/Dockerfile@@ -31,19 +31,17 @@ USER rootRUN apk add --no-cache chromium-chromedriverCOPY --from=cargo-build /usr/src/reacher/target/x86_64-unknown-linux-musl/release/reacher_backend .-COPY --from=cargo-build /usr/src/reacher/docker/backend.sh .-COPY --from=cargo-build /usr/src/reacher/docker/wait-for-it.sh .+COPY --from=cargo-build /usr/src/reacher/backend/docker.sh .+COPY --from=cargo-build /usr/src/reacher/backend/backend_config.toml .RUN chown chrome:chrome reacher_backend-RUN chown chrome:chrome backend.sh+RUN chown chrome:chrome docker.sh# User chrome was created in zenika/alpine-chromeUSER chromeENV RUST_LOG=reacher=infoENV RCH_HTTP_HOST=0.0.0.0-ENV PORT=8080-ENV RCH_WEBDRIVER_ADDR=http://localhost:9515EXPOSE 8080@@ -51,4 +49,4 @@ EXPOSE 8080# https://stackoverflow.com/questions/40122152/how-to-remove-entrypoint-from-parent-image-on-dockerfileENTRYPOINT []-CMD ["./backend.sh"]+CMD ["./docker.sh"]diff --git a/backend/backend_config.toml b/backend/backend_config.tomlnew file mode 100644index 00000000..ba4d4ddd--- /dev/null+++ b/backend/backend_config.toml@@ -0,0 +1,35 @@+# Backend configuration++# Backend name to identify the backend.+backend_name = "backend-dev"++# Backend host to bind to.+http_host = "127.0.0.1"++# Backend port.+http_port = 8080++# Shared secret between a trusted client and the backend, that must be present+# in the `x-reacher-secret` header of all incoming requests.+# header_secret = "my-secret"++# The name to use during the EHLO/HELO command in the SMTP conversation.+# Ideally, this should match the reverse DNS of the IP address of the server.+hello_name = "reacher"++# The email to use during the MAIL FROM command in the SMTP conversation.+# Ideally, the domain of this email should match the "hello_name" above.+from_email = "[email protected]"++# The address of the Chrome WebDriver server to use for making headless email+# verifications.+webdriver_addr = "http://localhost:9515"++# Throttle the maximum number of requests per second, per minute, per hour, an+# per day for this worker.+# All fields are optional, comment them out to disable the limit.+[throttle]+# max_requests_per_second = 20+# max_requests_per_minute = 100+# max_requests_per_hour = 1000+max_requests_per_day = 20000diff --git a/docker/backend.sh b/backend/docker.shsimilarity index 100%rename from docker/backend.shrename to backend/docker.shdiff --git a/backend/migrations/20220117025847_email_data.down.sql b/backend/migrations/20220117025847_email_data.down.sqlindex ed211e33..5309e662 100644--- a/backend/migrations/20220117025847_email_data.down.sql+++ b/backend/migrations/20220117025847_email_data.down.sql@@ -1,4 +1,4 @@-DROP INDEX job_emails;-DROP TABLE email_results;-DROP TABLE bulk_jobs;+DROP INDEX v0_job_emails;+DROP TABLE v0_bulk_results;+DROP TABLE v0_bulk_jobs;DROP TYPE valid_status;\ No newline at end of filediff --git a/backend/migrations/20220117025847_email_data.up.sql b/backend/migrations/20220117025847_email_data.up.sqlindex d53e83d5..2fb0ee81 100644--- a/backend/migrations/20220117025847_email_data.up.sql+++ b/backend/migrations/20220117025847_email_data.up.sql@@ -1,12 +1,12 @@-CREATE TABLE bulk_jobs (+CREATE TABLE v0_bulk_jobs (id SERIAL PRIMARY KEY,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),total_records INTEGER NOT NULL);-CREATE TABLE email_results (+CREATE TABLE v0_bulk_results (id SERIAL PRIMARY KEY,job_id INTEGER,result JSONB,- FOREIGN KEY (job_id) REFERENCES bulk_jobs(id)+ FOREIGN KEY (job_id) REFERENCES v0_bulk_jobs(id));-CREATE INDEX job_emails ON email_results USING HASH (job_id);\ No newline at end of file+CREATE INDEX v0_job_emails ON v0_bulk_results USING HASH (job_id);\ No newline at end of filediff --git a/backend/migrations/20220810141100_result_created_at.down.sql b/backend/migrations/20220810141100_result_created_at.down.sqlindex 80b95f10..e761e47e 100644--- a/backend/migrations/20220810141100_result_created_at.down.sql+++ b/backend/migrations/20220810141100_result_created_at.down.sql@@ -1,2 +1,2 @@-ALTER TABLE email_results+ALTER TABLE v0_bulk_resultsDROP COLUMN created_at;diff --git a/backend/migrations/20220810141100_result_created_at.up.sql b/backend/migrations/20220810141100_result_created_at.up.sqlindex ab28f019..ee522dda 100644--- a/backend/migrations/20220810141100_result_created_at.up.sql+++ b/backend/migrations/20220810141100_result_created_at.up.sql@@ -1,2 +1,2 @@-ALTER TABLE email_results+ALTER TABLE v0_bulk_resultsADD created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();\ No newline at end of filediff --git a/backend/src/check.rs b/backend/src/check.rsindex b891e2a2..182f848c 100644--- a/backend/src/check.rs+++ b/backend/src/check.rs@@ -16,28 +16,11 @@//! This file contains shared logic for checking one email.-use std::env;+use check_if_email_exists::{check_email as ciee_check_email, CheckEmailInput, CheckEmailOutput};-use warp::Filter;+use crate::config::BackendConfig;-/// The header which holds the Reacher backend secret.-pub const REACHER_SECRET_HEADER: &str = "x-reacher-secret";--/// Warp filter to check that the header secret is correct, if the environment-/// variable `RCH_HEADER_SECRET` is set-pub fn check_header() -> warp::filters::BoxedFilter<()> {- let env_var = env::var("RCH_HEADER_SECRET");-- match env_var {- Ok(secret) => {- if secret.len() == 0 {- return warp::any().boxed();- }-- let secret: &'static str = Box::leak(Box::new(secret));-- warp::header::exact(REACHER_SECRET_HEADER, secret).boxed()- }- Err(_) => warp::any().boxed(),- }+pub async fn check_email(mut input: CheckEmailInput, config: &BackendConfig) -> CheckEmailOutput {+ input.from_email = config.from_email.clone();+ ciee_check_email(&input, &config.get_reacher_config()).await}diff --git a/backend/src/config.rs b/backend/src/config.rsnew file mode 100644index 00000000..fec4c83d--- /dev/null+++ b/backend/src/config.rs@@ -0,0 +1,74 @@+use check_if_email_exists::config::ReacherConfig;+use check_if_email_exists::SentryConfig;+use config::Config;+use serde::Deserialize;++#[derive(Debug, Deserialize)]+pub struct BackendConfig {+ /// Name of the backend.+ pub backend_name: String,++ // Reacher config+ pub from_email: String,+ pub hello_name: String,+ pub webdriver_addr: String,++ // Backend-specific config+ /// Backend host+ pub http_host: String,+ /// Backend port+ pub http_port: u16,+ /// Shared secret between a trusted client and the backend.+ pub header_secret: Option<String>,+ pub throttle: ThrottleConfig,+ pub webhook: Option<WebhookConfig>,+ pub sentry: Option<SentryConfig>,+}++impl BackendConfig {+ pub fn get_reacher_config(&self) -> ReacherConfig {+ ReacherConfig {+ backend_name: self.backend_name.clone(),+ sentry: self.sentry.clone(),+ webdriver_addr: self.webdriver_addr.clone(),+ }+ }+}++#[derive(Debug, Deserialize, Clone)]+pub struct ThrottleConfig {+ pub max_requests_per_second: Option<u32>,+ pub max_requests_per_minute: Option<u32>,+ pub max_requests_per_hour: Option<u32>,+ pub max_requests_per_day: Option<u32>,+}++impl ThrottleConfig {+ /// Create a new ThrottleConfig with no throttling.+ pub fn new_without_throttle() -> Self {+ Self {+ max_requests_per_second: None,+ max_requests_per_minute: None,+ max_requests_per_hour: None,+ max_requests_per_day: None,+ }+ }+}++#[derive(Debug, Deserialize, Clone)]+pub struct WebhookConfig {+ pub url: String,+}++/// Load the worker configuration from the worker_config.toml file and from the+/// environment.+pub fn load_config() -> Result<BackendConfig, config::ConfigError> {+ let cfg = Config::builder()+ .add_source(config::File::with_name("backend_config"))+ .add_source(config::Environment::with_prefix("RCH"))+ .build()?;++ let cfg = cfg.try_deserialize::<BackendConfig>()?;++ Ok(cfg)+}diff --git a/backend/src/http/mod.rs b/backend/src/http/mod.rsindex 97634f10..0428c682 100644--- a/backend/src/http/mod.rs+++ b/backend/src/http/mod.rs@@ -17,27 +17,30 @@mod v0;mod version;-use std::env;-use std::net::IpAddr;-use check_if_email_exists::LOG_TARGET;use sqlx::postgres::PgPoolOptions;use sqlx::{Pool, Postgres};use sqlxmq::JobRunnerHandle;+use std::env;+use std::net::IpAddr;+use std::sync::Arc;use tracing::info;use warp::Filter;+use crate::config::BackendConfig;+use super::errors;/// Creates the routes for the HTTP server./// Making it public so that it can be used in tests/check_email.rs.pub fn create_routes(+ config: Arc<BackendConfig>,o: Option<Pool<Postgres>>,) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {version::get::get_version()- .or(v0::check_email::post::post_check_email())+ .or(v0::check_email::post::post_check_email(config.clone()))// The 3 following routes will 404 if o is None.- .or(v0::bulk::post::create_bulk_job(o.clone()))+ .or(v0::bulk::post::create_bulk_job(config, o.clone())).or(v0::bulk::get::get_bulk_job_status(o.clone())).or(v0::bulk::results::get_bulk_job_result(o)).recover(errors::handle_rejection)@@ -51,17 +54,21 @@ pub fn create_routes(/// job listener is enabled. The handle can be used to stop the listener or to/// keep it alive.pub async fn run_warp_server(+ config: Arc<BackendConfig>,) -> Result<Option<JobRunnerHandle>, Box<dyn std::error::Error + Send + Sync>> {- let host = env::var("RCH_HTTP_HOST")- .unwrap_or_else(|_| "127.0.0.1".into())+ let host = config+ .http_host.parse::<IpAddr>()- .expect("Environment variable RCH_HTTP_HOST is malformed.");+ .unwrap_or_else(|_| panic!("Invalid host: {}", config.http_host));+ // For backwards compatibility, we allow the port to be set via the+ // environment variable PORT, instead of the new configuration file. The+ // PORT environment variable takes precedence.let port = env::var("PORT").map(|port: String| {port.parse::<u16>()- .expect("Environment variable PORT is malformed.")+ .unwrap_or_else(|_| panic!("Invalid port: {}", port))})- .unwrap_or(8080);+ .unwrap_or(config.http_port);// Run bulk job listener.let is_bulk_enabled = env::var("RCH_ENABLE_BULK").unwrap_or_else(|_| "0".into()) == "1";@@ -73,7 +80,7 @@ pub async fn run_warp_server((None, None)};- let routes = create_routes(db);+ let routes = create_routes(config.clone(), db);info!(target: LOG_TARGET, host=?host,port=?port, "Server is listening");warp::serve(routes).run((host, port)).await;@@ -82,24 +89,42 @@ pub async fn run_warp_server(Ok(runner)}-/// Create a DB pool.+/// Create a DB pool for the deprecated /v0/bulk endpoints.async fn create_db() -> Result<Pool<Postgres>, sqlx::Error> {- let pg_conn =- env::var("DATABASE_URL").expect("Environment variable DATABASE_URL should be set");- let pg_max_conn = env::var("RCH_DATABASE_MAX_CONNECTIONS").map_or(5, |var| {- var.parse::<u32>()- .expect("Environment variable RCH_DATABASE_MAX_CONNECTIONS should parse to u32")- });+ let pg_conn = env::var("DATABASE_URL").expect("Environment variable DATABASE_URL must be set");// create connection pool with database// connection pool internally the shared db connection// with arc so it can safely be cloned and shared across threads- let pool = PgPoolOptions::new()- .max_connections(pg_max_conn)- .connect(pg_conn.as_str())- .await?;+ let pool = PgPoolOptions::new().connect(pg_conn.as_str()).await?;sqlx::migrate!("./migrations").run(&pool).await?;Ok(pool)}++/// The header which holds the Reacher backend secret.+pub const REACHER_SECRET_HEADER: &str = "x-reacher-secret";++/// Warp filter to check that the header secret is correct, if the header is+/// set in the config.+pub fn check_header(config: Arc<BackendConfig>) -> warp::filters::BoxedFilter<()> {+ if let Some(secret) = config.header_secret.clone() {+ if secret.is_empty() {+ return warp::any().boxed();+ }++ let secret: &'static str = Box::leak(Box::new(secret));++ warp::header::exact(REACHER_SECRET_HEADER, secret).boxed()+ } else {+ warp::any().boxed()+ }+}++/// Warp filter that adds the BackendConfig to the handler.+pub fn with_config(+ config: Arc<BackendConfig>,+) -> impl Filter<Extract = (Arc<BackendConfig>,), Error = std::convert::Infallible> + Clone {+ warp::any().map(move || config.clone())+}diff --git a/backend/src/http/v0/bulk/db.rs b/backend/src/http/v0/bulk/db.rsindex 9d995f04..9cab6e47 100644--- a/backend/src/http/v0/bulk/db.rs+++ b/backend/src/http/v0/bulk/db.rs@@ -23,7 +23,7 @@ pub fn with_db(o: Option<Pool<Postgres>>,) -> impl Filter<Extract = (Pool<Postgres>,), Error = warp::Rejection> + Clone {warp::any().and_then(move || {- let o = o.clone(); // Still not 100% sure why I need to clone here...+ let o = o.clone();async move {if let Some(conn_pool) = o {Ok(conn_pool)diff --git a/backend/src/http/v0/bulk/post.rs b/backend/src/http/v0/bulk/post.rsindex 3cdad66b..22e01777 100644--- a/backend/src/http/v0/bulk/post.rs+++ b/backend/src/http/v0/bulk/post.rs@@ -20,15 +20,15 @@ use check_if_email_exists::CheckEmailInputProxy;use check_if_email_exists::LOG_TARGET;use serde::{Deserialize, Serialize};use sqlx::{Pool, Postgres};+use std::sync::Arc;use tracing::{debug, error};use warp::Filter;-use super::{- db::with_db,- error::BulkError,- task::{submit_job, TaskInput},-};-use crate::check::check_header;+use super::db::with_db;+use super::error::BulkError;+use super::task::{submit_job, TaskInput};+use crate::config::BackendConfig;+use crate::http::check_header;/// Endpoint request body.#[derive(Clone, Debug, Deserialize, Serialize)]@@ -134,11 +134,12 @@ async fn create_bulk_request(/// The endpoint accepts list of email address and creates/// a new job to check them.pub fn create_bulk_job(+ config: Arc<BackendConfig>,o: Option<Pool<Postgres>>,) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {warp::path!("v0" / "bulk").and(warp::post())- .and(check_header())+ .and(check_header(config)).and(with_db(o))// When accepting a body, we want a JSON body (and to reject huge// payloads)...diff --git a/backend/src/http/v0/bulk/task.rs b/backend/src/http/v0/bulk/task.rsindex 108033c2..3345952c 100644--- a/backend/src/http/v0/bulk/task.rs+++ b/backend/src/http/v0/bulk/task.rs@@ -17,11 +17,13 @@//! This file implements the `POST /bulk` endpoint.use check_if_email_exists::{- check_email, CheckEmailInput, CheckEmailInputProxy, CheckEmailOutput, Reachable, LOG_TARGET,+ check_email, config::ReacherConfig, CheckEmailInput, CheckEmailInputProxy, CheckEmailOutput,+ Reachable, SentryConfig, LOG_TARGET,};use serde::{Deserialize, Serialize};use sqlx::{Pool, Postgres};use sqlxmq::{job, CurrentJob};+use std::env;use std::error::Error;use tracing::{debug, error};use uuid::Uuid;@@ -158,8 +160,25 @@ pub async fn email_verification_task(current_job.id(),);+ // Currently, for the legacy and deprecated /v0/bulk endpoints, we+ // don't pass in a BackendConfig to the job. Therefore, we must create+ // an ad-hoc ReacherConfig here, using the legacy env::var() method.+ // This is a temporary solution until the /v0/bulk endpoints are+ // removed.+ let backend_name = env::var("RCH_BACKEND_NAME").unwrap_or_else(|_| "reacher".into());+ let sentry_dsn = env::var("RCH_SENTRY_DSN");+ let webdriver_addr =+ env::var("RCH_WEBDRIVER_ADDR").unwrap_or_else(|_| "localhost:9515".into());+ let config = ReacherConfig {+ backend_name: backend_name.clone(),+ webdriver_addr,+ sentry: sentry_dsn+ .ok()+ .map(|dsn| SentryConfig { dsn, backend_name }),+ };+let to_email = check_email_input.to_email.clone();- let response = check_email(&check_email_input).await;+ let response = check_email(&check_email_input, &config).await;debug!(target: LOG_TARGET,diff --git a/backend/src/http/v0/check_email/post.rs b/backend/src/http/v0/check_email/post.rsindex fdd76922..1dd11d83 100644--- a/backend/src/http/v0/check_email/post.rs+++ b/backend/src/http/v0/check_email/post.rs@@ -17,13 +17,18 @@//! This file implements the `POST /v0/check_email` endpoint.use check_if_email_exists::{check_email, CheckEmailInput, LOG_TARGET};+use std::sync::Arc;use warp::{http, Filter};-use crate::check::check_header;+use crate::config::BackendConfig;use crate::errors;+use crate::http::{check_header, with_config};/// The main endpoint handler that implements the logic of this route.-async fn handler(body: CheckEmailInput) -> Result<impl warp::Reply, warp::Rejection> {+async fn handler(+ config: Arc<BackendConfig>,+ body: CheckEmailInput,+) -> Result<impl warp::Reply, warp::Rejection> {// The to_email field must be presentif body.to_email.is_empty() {Err(warp::reject::custom(errors::ReacherResponseError {@@ -32,16 +37,20 @@ async fn handler(body: CheckEmailInput) -> Result<impl warp::Reply, warp::Reject}))} else {// Run the future to check an email.- Ok(warp::reply::json(&check_email(&body).await))+ Ok(warp::reply::json(+ &check_email(&body, &config.get_reacher_config()).await,+ ))}}/// Create the `POST /check_email` endpoint.-pub fn post_check_email(-) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {+pub fn post_check_email<'a>(+ config: Arc<BackendConfig>,+) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone + 'a {warp::path!("v0" / "check_email").and(warp::post())- .and(check_header())+ .and(check_header(config.clone()))+ .and(with_config(config))// When accepting a body, we want a JSON body (and to reject huge// payloads)....and(warp::body::content_length_limit(1024 * 16))diff --git a/backend/src/lib.rs b/backend/src/lib.rsindex 3914908e..20b2c13b 100644--- a/backend/src/lib.rs+++ b/backend/src/lib.rs@@ -15,6 +15,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.pub mod check;+pub mod config;mod errors;pub mod http;diff --git a/backend/src/main.rs b/backend/src/main.rsindex fcdbe518..f3f74038 100644--- a/backend/src/main.rs+++ b/backend/src/main.rs@@ -18,8 +18,10 @@//! functions, depending on whether the `bulk` feature is enabled or not.use check_if_email_exists::{setup_sentry, LOG_TARGET};+use std::sync::Arc;use tracing::info;+use reacher_backend::config::load_config;use reacher_backend::http::run_warp_server;const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");@@ -30,11 +32,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {// Initialize logging.tracing_subscriber::fmt::init();info!(target: LOG_TARGET, version=?CARGO_PKG_VERSION, "Running Reacher");+ let config = load_config()?;// Setup sentry bug tracking.- let _guard: sentry::ClientInitGuard = setup_sentry();+ let _guard: sentry::ClientInitGuard;+ if let Some(sentry_config) = &config.sentry {+ _guard = setup_sentry(sentry_config);+ }- let _bulk_job_runner = run_warp_server().await?;+ let _bulk_job_runner = run_warp_server(Arc::new(config)).await?;Ok(())}diff --git a/backend/tests/check_email.rs b/backend/tests/check_email.rsindex dbe37499..b5eac1b6 100644--- a/backend/tests/check_email.rs+++ b/backend/tests/check_email.rs@@ -14,27 +14,40 @@// 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 std::sync::Arc;use check_if_email_exists::CheckEmailInput;-use reacher_backend::check::REACHER_SECRET_HEADER;-use reacher_backend::http::create_routes;+use reacher_backend::config::{BackendConfig, ThrottleConfig};+use reacher_backend::http::{create_routes, REACHER_SECRET_HEADER};use warp::http::StatusCode;use warp::test::request;const FOO_BAR_RESPONSE: &str = r#"{"input":"foo@bar","is_reachable":"invalid","misc":{"is_disposable":false,"is_role_account":false,"gravatar_url":null,"haveibeenpwned":null},"mx":{"accepts_mail":false,"records":[]},"smtp":{"can_connect_smtp":false,"has_full_inbox":false,"is_catch_all":false,"is_deliverable":false,"is_disabled":false},"syntax":{"address":null,"domain":"","is_valid_syntax":false,"username":"","normalized_email":null,"suggestion":null}"#;const FOO_BAR_BAZ_RESPONSE: &str = r#"{"input":"[email protected]","is_reachable":"invalid","misc":{"is_disposable":false,"is_role_account":false,"gravatar_url":null,"haveibeenpwned":null},"mx":{"accepts_mail":false,"records":[]},"smtp":{"can_connect_smtp":false,"has_full_inbox":false,"is_catch_all":false,"is_deliverable":false,"is_disabled":false},"syntax":{"address":"[email protected]","domain":"bar.baz","is_valid_syntax":true,"username":"foo","normalized_email":"[email protected]","suggestion":null}"#;+fn create_backend_config(header_secret: &str) -> Arc<BackendConfig> {+ Arc::new(BackendConfig {+ backend_name: "reacher-test".into(),+ from_email: "test".into(),+ hello_name: "test".into(),+ webdriver_addr: "localhost:9515".into(),+ http_host: "localhost".into(),+ http_port: 8080,+ header_secret: Some(header_secret.to_string()),+ throttle: ThrottleConfig::new_without_throttle(),+ sentry: None,+ webhook: None,+ })+}+#[tokio::test]async fn test_input_foo_bar() {- env::set_var("RCH_HEADER_SECRET", "foobar");-let resp = request().path("/v0/check_email").method("POST").header(REACHER_SECRET_HEADER, "foobar").json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "foo@bar"}"#).unwrap())- .reply(&create_routes(None))+ .reply(&create_routes(create_backend_config("foobar"), None)).await;assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());@@ -43,14 +56,12 @@ async fn test_input_foo_bar() {#[tokio::test]async fn test_input_foo_bar_baz() {- env::set_var("RCH_HEADER_SECRET", "foobar");-let resp = request().path("/v0/check_email").method("POST").header(REACHER_SECRET_HEADER, "foobar").json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "[email protected]"}"#).unwrap())- .reply(&create_routes(None))+ .reply(&create_routes(create_backend_config("foobar"), None)).await;assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());@@ -59,13 +70,11 @@ async fn test_input_foo_bar_baz() {#[tokio::test]async fn test_reacher_secret_missing_header() {- env::set_var("RCH_HEADER_SECRET", "foobar");-let resp = request().path("/v0/check_email").method("POST").json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "[email protected]"}"#).unwrap())- .reply(&create_routes(None))+ .reply(&create_routes(create_backend_config("foobar"), None)).await;assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());@@ -74,14 +83,12 @@ async fn test_reacher_secret_missing_header() {#[tokio::test]async fn test_reacher_secret_wrong_secret() {- env::set_var("RCH_HEADER_SECRET", "foobar");-let resp = request().path("/v0/check_email").method("POST").header(REACHER_SECRET_HEADER, "barbaz").json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "[email protected]"}"#).unwrap())- .reply(&create_routes(None))+ .reply(&create_routes(create_backend_config("foobar"), None)).await;assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());@@ -90,14 +97,12 @@ async fn test_reacher_secret_wrong_secret() {#[tokio::test]async fn test_reacher_secret_correct_secret() {- env::set_var("RCH_HEADER_SECRET", "foobar");-let resp = request().path("/v0/check_email").method("POST").header(REACHER_SECRET_HEADER, "foobar").json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": "foo@bar"}"#).unwrap())- .reply(&create_routes(None))+ .reply(&create_routes(create_backend_config("foobar"), None)).await;assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());@@ -106,14 +111,12 @@ async fn test_reacher_secret_correct_secret() {#[tokio::test]async fn test_reacher_to_mail_empty() {- env::set_var("RCH_HEADER_SECRET", "foobar");-let resp = request().path("/v0/check_email").method("POST").header(REACHER_SECRET_HEADER, "foobar").json(&serde_json::from_str::<CheckEmailInput>(r#"{"to_email": ""}"#).unwrap())- .reply(&create_routes(None))+ .reply(&create_routes(create_backend_config("foobar"), None)).await;assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());@@ -122,14 +125,12 @@ async fn test_reacher_to_mail_empty() {#[tokio::test]async fn test_reacher_to_mail_missing() {- env::set_var("RCH_HEADER_SECRET", "foobar");-let resp = request().path("/v0/check_email").method("POST").header(REACHER_SECRET_HEADER, "foobar").json(&serde_json::from_str::<CheckEmailInput>(r#"{}"#).unwrap())- .reply(&create_routes(None))+ .reply(&create_routes(create_backend_config("foobar"), None)).await;assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{:?}", resp.body());diff --git a/cli/Cargo.toml b/cli/Cargo.tomlindex 7dc98281..b178b156 100644--- a/cli/Cargo.toml+++ b/cli/Cargo.toml@@ -13,7 +13,7 @@ name = "check_if_email_exists"path = "src/main.rs"[dependencies]-check-if-email-exists = { path = "../core", features = ["headless"] }+check-if-email-exists = { path = "../core" }clap = { version = "3.2", features = ["derive", "env"] }env_logger = "0.11"once_cell = "1.19"diff --git a/cli/src/main.rs b/cli/src/main.rsindex 94b5127f..7da7c954 100644--- a/cli/src/main.rs+++ b/cli/src/main.rs@@ -15,8 +15,8 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.use check_if_email_exists::{- check_email, CheckEmailInput, CheckEmailInputProxy, GmailVerifMethod, HotmailVerifMethod,- YahooVerifMethod,+ check_email, config::ReacherConfig, CheckEmailInput, CheckEmailInputProxy, GmailVerifMethod,+ HotmailVerifMethod, YahooVerifMethod,};use clap::Parser;use once_cell::sync::Lazy;@@ -108,8 +108,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {password: CONF.proxy_password.clone(),});}+ let config = ReacherConfig {+ backend_name: "reacher-cli".to_string(),+ ..Default::default()+ };- let result = check_email(&input).await;+ let result = check_email(&input, &config).await;match serde_json::to_string_pretty(&result) {Ok(output) => {diff --git a/core/Cargo.toml b/core/Cargo.tomlindex 421b8da2..7d6e9a45 100644--- a/core/Cargo.toml+++ b/core/Cargo.toml@@ -17,8 +17,9 @@ async-native-tls = { version = "0.4", default-features = false }async-recursion = "1.0.5"async-smtp = { version = "0.6.0", features = ["socks5"] }chrono = "0.4.31"-fantoccini = { version = "0.21.2", optional = true }-futures = { version = "0.3.30", optional = true }+config = "0.14"+fantoccini = { version = "0.21.2" }+futures = { version = "0.3.30" }fast-socks5 = "0.9.2"hickory-proto = "0.24.0"hickory-resolver = "0.24.0"@@ -38,6 +39,3 @@ tracing = "0.1.40"[dev-dependencies]tokio = { version = "1.40.0" }--[features]-headless = ["fantoccini", "futures"]diff --git a/core/src/util/constants.rs b/core/src/config.rssimilarity index 56%rename from core/src/util/constants.rsrename to core/src/config.rsindex f4fc8f77..71a60450 100644--- a/core/src/util/constants.rs+++ b/core/src/config.rs@@ -14,5 +14,26 @@// 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/>.-/// The target where to log check-if-email-exists logs.-pub const LOG_TARGET: &str = "reacher";+use crate::SentryConfig;++/// Configuration needed to run Reacher.+#[derive(Debug)]+pub struct ReacherConfig {+ /// Identifier for the service currently running Reacher.+ pub backend_name: String,+ /// The address of the WebDriver server.+ pub webdriver_addr: String,+ #[cfg(feature = "sentry")]+ pub sentry: Option<SentryConfig>,+}++impl Default for ReacherConfig {+ fn default() -> Self {+ ReacherConfig {+ backend_name: "backend-dev".into(),+ webdriver_addr: "http://localhost:9515".into(),+ #[cfg(feature = "sentry")]+ sentry: Default::default(),+ }+ }+}diff --git a/core/src/haveibeenpwned.rs b/core/src/haveibeenpwned.rsindex fdce20ab..e462e667 100644--- a/core/src/haveibeenpwned.rs+++ b/core/src/haveibeenpwned.rs@@ -14,7 +14,7 @@// 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 crate::util::constants::LOG_TARGET;+use crate::LOG_TARGET;use pwned::api::PwnedBuilder;/// Check if the email has been found in any breach or paste using thediff --git a/core/src/lib.rs b/core/src/lib.rsindex b1f96c61..1fc2d622 100644--- a/core/src/lib.rs+++ b/core/src/lib.rs@@ -35,6 +35,7 @@//!//! ```rust//! use check_if_email_exists::{check_email, CheckEmailInput, CheckEmailInputProxy};+//! use check_if_email_exists::config::ReacherConfig;//!//! async fn check() {//! // Let's say we want to test the deliverability of [email protected].@@ -53,8 +54,14 @@//! password: None//! });//!+//! // We also need to set some configuration parameters.+//! let config = ReacherConfig {+//! backend_name: "my-backend".into(),+//! ..Default::default()+//! };+//!//! // Verify this input, using async/await syntax.-//! let result = check_email(&input).await;+//! let result = check_email(&input, &config).await;//!//! // `result` is a `Vec<CheckEmailOutput>`, where the CheckEmailOutput//! // struct contains all information about one email.@@ -62,6 +69,7 @@//! }//! ```+pub mod config;mod haveibeenpwned;pub mod misc;pub mod mx;@@ -70,6 +78,7 @@ pub mod smtp;pub mod syntax;mod util;+use config::ReacherConfig;use hickory_proto::rr::rdata::MX;use misc::{check_misc, MiscDetails};use mx::check_mx;@@ -77,13 +86,15 @@ use rand::Rng;use smtp::{check_smtp, SmtpDetails, SmtpError};use std::time::{Duration, SystemTime};use syntax::{check_syntax, get_similar_mail_provider};-pub use util::constants::LOG_TARGET;pub use util::input_output::*;#[cfg(feature = "sentry")]pub use util::sentry::*;use crate::rules::{has_rule, Rule};+/// The target where to log check-if-email-exists logs.+pub const LOG_TARGET: &str = "reacher";+/// Given an email's misc and smtp details, calculate an estimate of our/// confidence on how reachable the email is.///@@ -115,7 +126,7 @@ fn calculate_reachable(misc: &MiscDetails, smtp: &Result<SmtpDetails, SmtpError>////// Returns a `CheckEmailOutput` output, whose `is_reachable` field is one of/// `Safe`, `Invalid`, `Risky` or `Unknown`.-pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput {+pub async fn check_email(input: &CheckEmailInput, config: &ReacherConfig) -> CheckEmailOutput {let start_time = SystemTime::now();let to_email = &input.to_email;@@ -240,6 +251,7 @@ pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput {input.smtp_port,my_syntax.domain.as_ref(),input,+ config,).await;@@ -248,7 +260,8 @@ pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput {}let end_time = SystemTime::now();- let res = CheckEmailOutput {++ CheckEmailOutput {input: to_email.to_string(),is_reachable: calculate_reachable(&my_misc, &my_smtp),misc: Ok(my_misc),@@ -262,12 +275,7 @@ pub async fn check_email(input: &CheckEmailInput) -> CheckEmailOutput {.duration_since(start_time).unwrap_or(Duration::from_secs(0)),smtp: smtp_debug,- ..Default::default()+ backend_name: config.backend_name.clone(),},- };-- #[cfg(feature = "sentry")]- log_unknown_errors(&res);-- res+ }}diff --git a/core/src/misc/gravatar.rs b/core/src/misc/gravatar.rsindex c7cfbf0a..638e516a 100644--- a/core/src/misc/gravatar.rs+++ b/core/src/misc/gravatar.rs@@ -14,8 +14,7 @@// 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 crate::util::constants::LOG_TARGET;-use md5;+use crate::LOG_TARGET;use md5::Digest;const API_BASE_URL: &str = "https://www.gravatar.com/avatar/";diff --git a/core/src/smtp/connect.rs b/core/src/smtp/connect.rsindex ae804b07..a7c85000 100644--- a/core/src/smtp/connect.rs+++ b/core/src/smtp/connect.rs@@ -28,9 +28,10 @@ use std::time::Duration;use super::parser;use super::{SmtpDetails, SmtpError};+use crate::LOG_TARGET;use crate::{rules::{has_rule, Rule},- util::{constants::LOG_TARGET, input_output::CheckEmailInput},+ util::input_output::CheckEmailInput,};/// Try to send an smtp command, close and return Err if fails.@@ -374,7 +375,6 @@ pub async fn check_smtp_with_retry(// Don't retry if we used Hotmail or Yahoo API. This two options should// be non-callable, as this function only deals with actual SMTP// connection errors.- #[cfg(feature = "headless")]Err(SmtpError::HeadlessError(_)) => result,Err(SmtpError::YahooError(_)) => result,Err(SmtpError::GmailError(_)) => result,@@ -414,6 +414,6 @@ mod tests {assert!(!smtp_transport.is_connected()); // We shouldn't connect to google servers.assert!(r.is_ok());- assert_eq!(false, r.unwrap())+ assert!(!r.unwrap())}}diff --git a/core/src/smtp/error.rs b/core/src/smtp/error.rsindex 8cc74c72..86efc9a5 100644--- a/core/src/smtp/error.rs+++ b/core/src/smtp/error.rs@@ -15,7 +15,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.use super::gmail::GmailError;-#[cfg(feature = "headless")]+use super::headless::HeadlessError;use super::outlook::microsoft365::Microsoft365Error;use super::parser;@@ -40,7 +40,6 @@ pub enum SmtpError {/// Error when verifying a Gmail email via a HTTP request.GmailError(GmailError),/// Error when verifying a Hotmail email via headless browser.- #[cfg(feature = "headless")]HeadlessError(HeadlessError),/// Error when verifying a Microsoft 365 email via HTTP request.Microsoft365Error(Microsoft365Error),@@ -66,7 +65,6 @@ impl From<GmailError> for SmtpError {}}-#[cfg(feature = "headless")]impl From<HeadlessError> for SmtpError {fn from(e: HeadlessError) -> Self {SmtpError::HeadlessError(e)diff --git a/core/src/smtp/gmail.rs b/core/src/smtp/gmail.rsindex d4eba430..49a95bd6 100644--- a/core/src/smtp/gmail.rs+++ b/core/src/smtp/gmail.rs@@ -15,11 +15,10 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.use super::SmtpDetails;+use crate::LOG_TARGET;use crate::{smtp::http_api::create_client,- util::{- constants::LOG_TARGET, input_output::CheckEmailInput, ser_with_display::ser_with_display,- },+ util::{input_output::CheckEmailInput, ser_with_display::ser_with_display},};use async_smtp::EmailAddress;use reqwest::Error as ReqwestError;diff --git a/core/src/smtp/http_api.rs b/core/src/smtp/http_api.rsindex b056c5df..289488ad 100644--- a/core/src/smtp/http_api.rs+++ b/core/src/smtp/http_api.rs@@ -14,7 +14,8 @@// 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 crate::util::{constants::LOG_TARGET, input_output::CheckEmailInput};+use crate::util::input_output::CheckEmailInput;+use crate::LOG_TARGET;use reqwest::Error as ReqwestError;/// Helper function to create a reqwest client, with optional proxy.diff --git a/core/src/smtp/mod.rs b/core/src/smtp/mod.rsindex 42751af2..20af6133 100644--- a/core/src/smtp/mod.rs+++ b/core/src/smtp/mod.rs@@ -17,7 +17,7 @@mod connect;mod error;mod gmail;-#[cfg(feature = "headless")]+mod headless;mod http_api;mod outlook;@@ -25,14 +25,14 @@ mod parser;mod yahoo;use std::default::Default;-use std::env;use async_smtp::EmailAddress;use hickory_proto::rr::Name;use serde::{Deserialize, Serialize};use crate::{- util::input_output::CheckEmailInput, GmailVerifMethod, HotmailVerifMethod, YahooVerifMethod,+ config::ReacherConfig, util::input_output::CheckEmailInput, GmailVerifMethod,+ HotmailVerifMethod, YahooVerifMethod,};use connect::check_smtp_with_retry;pub use error::*;@@ -96,6 +96,7 @@ pub async fn check_smtp(port: u16,domain: &str,input: &CheckEmailInput,+ config: &ReacherConfig,) -> (Result<SmtpDetails, SmtpError>, SmtpDebug) {let host = host.to_string();let to_email_str = to_email.to_string();@@ -111,15 +112,9 @@ pub async fn check_smtp();}- let webdriver_addr = env::var("RCH_WEBDRIVER_ADDR");-if is_hotmail(&host) {- match (- &input.hotmail_verif_method,- webdriver_addr,- is_microsoft365(&host),- ) {- (HotmailVerifMethod::OneDriveApi, _, true) => {+ match (&input.hotmail_verif_method, is_microsoft365(&host)) {+ (HotmailVerifMethod::OneDriveApi, true) => {match outlook::microsoft365::check_microsoft365_api(to_email, input).await {Ok(Some(smtp_details)) => {return {@@ -143,12 +138,15 @@ pub async fn check_smtp(_ => {}}}- #[cfg(feature = "headless")]- (HotmailVerifMethod::Headless, Ok(a), false) => {++ (HotmailVerifMethod::Headless, false) => {return (- outlook::headless::check_password_recovery(to_email.to_string().as_str(), &a)- .await- .map_err(|err| err.into()),+ outlook::headless::check_password_recovery(+ to_email.to_string().as_str(),+ &config.webdriver_addr,+ )+ .await+ .map_err(|err| err.into()),SmtpDebug {verif_method: VerifMethod::Headless,},@@ -168,8 +166,8 @@ pub async fn check_smtp();};} else if is_yahoo(&host) {- match (&input.yahoo_verif_method, webdriver_addr) {- (YahooVerifMethod::Api, _) => {+ match &input.yahoo_verif_method {+ YahooVerifMethod::Api => {return (yahoo::check_api(&to_email_str, input).await@@ -179,10 +177,10 @@ pub async fn check_smtp(},)}- #[cfg(feature = "headless")]- (YahooVerifMethod::Headless, Ok(a)) => {++ YahooVerifMethod::Headless => {return (- yahoo::check_headless(&to_email_str, &a)+ yahoo::check_headless(&to_email_str, &config.webdriver_addr).await.map_err(|e| e.into()),SmtpDebug {@@ -208,6 +206,8 @@ pub async fn check_smtp(#[cfg(test)]mod tests {+ use crate::config::ReacherConfig;+use super::{check_smtp, CheckEmailInput, SmtpConnection, SmtpError};use async_smtp::{smtp::error::Error, EmailAddress};use hickory_proto::rr::Name;@@ -223,9 +223,16 @@ mod tests {let mut input = CheckEmailInput::default();input.set_gmail_verif_method(crate::GmailVerifMethod::Smtp);input.set_smtp_timeout(Some(Duration::from_millis(1)));+ let config = ReacherConfig::default();- let (res, smtp_debug) =- runtime.block_on(check_smtp(&to_email, &host, 25, "gmail.com", &input));+ let (res, smtp_debug) = runtime.block_on(check_smtp(+ &to_email,+ &host,+ 25,+ "gmail.com",+ &input,+ &config,+ ));assert_eq!(smtp_debug.verif_method,super::VerifMethod::Smtp(SmtpConnection {@@ -248,9 +255,16 @@ mod tests {let host = Name::from_str("mx01.mail.icloud.com.").unwrap();let mut input = CheckEmailInput::default();input.set_skipped_domains(vec![".mail.icloud.com.".into()]);+ let config = ReacherConfig::default();- let (res, smtp_debug) =- runtime.block_on(check_smtp(&to_email, &host, 25, "icloud.com", &input));+ let (res, smtp_debug) = runtime.block_on(check_smtp(+ &to_email,+ &host,+ 25,+ "icloud.com",+ &input,+ &config,+ ));assert_eq!(smtp_debug.verif_method, super::VerifMethod::Skipped);match res {Err(SmtpError::SkippedDomain(_)) => (),diff --git a/core/src/smtp/outlook/headless.rs b/core/src/smtp/outlook/headless.rsindex 5d1cda7d..53bc7d41 100644--- a/core/src/smtp/outlook/headless.rs+++ b/core/src/smtp/outlook/headless.rs@@ -131,7 +131,7 @@ mod tests {// It should not error.for _ in 0..10 {// This email does not exist.- let res = check_password_recovery(&"[email protected]", "http://localhost:9515")+ let res = check_password_recovery("[email protected]", "http://localhost:9515").await.unwrap();assert!(!res.is_deliverable);diff --git a/core/src/smtp/outlook/mod.rs b/core/src/smtp/outlook/mod.rsindex eaf88aa6..4fae77f7 100644--- a/core/src/smtp/outlook/mod.rs+++ b/core/src/smtp/outlook/mod.rs@@ -1,4 +1,3 @@-#[cfg(feature = "headless")]pub mod headless;pub mod microsoft365;diff --git a/core/src/smtp/yahoo/api.rs b/core/src/smtp/yahoo/api.rsindex 9801b513..04ff5531 100644--- a/core/src/smtp/yahoo/api.rs+++ b/core/src/smtp/yahoo/api.rs@@ -15,9 +15,10 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.use super::YahooError;+use crate::LOG_TARGET;use crate::{smtp::{http_api::create_client, SmtpDetails},- util::{constants::LOG_TARGET, input_output::CheckEmailInput},+ util::input_output::CheckEmailInput,};use regex::Regex;use serde::{Deserialize, Serialize};diff --git a/core/src/smtp/yahoo/mod.rs b/core/src/smtp/yahoo/mod.rsindex 6ce620f1..977df9af 100644--- a/core/src/smtp/yahoo/mod.rs+++ b/core/src/smtp/yahoo/mod.rs@@ -15,7 +15,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.mod api;-#[cfg(feature = "headless")]+mod headless;use crate::util::ser_with_display::ser_with_display;@@ -25,7 +25,7 @@ use serde_json::error::Error as SerdeError;use std::fmt;pub use api::check_api;-#[cfg(feature = "headless")]+pub use headless::check_headless;/// Possible errors when checking Yahoo email addresses.diff --git a/core/src/util/input_output.rs b/core/src/util/input_output.rsindex f7d27924..b6fc44bc 100644--- a/core/src/util/input_output.rs+++ b/core/src/util/input_output.rs@@ -14,7 +14,6 @@// 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 std::str::FromStr;use std::time::{Duration, SystemTime};@@ -83,7 +82,6 @@ pub enum YahooVerifMethod {/// its endpoint, usually http://localhost:9515, into the environment/// variable RCH_WEBDRIVER_ADDR. We recommend running chromedriver (and not/// geckodriver) as it allows parallel requests.- #[cfg(feature = "headless")]Headless,/// Use Yahoo's SMTP servers to check if an email exists.Smtp,@@ -95,7 +93,7 @@ impl FromStr for YahooVerifMethod {fn from_str(s: &str) -> Result<Self, Self::Err> {match s {"Api" => Ok(Self::Api),- #[cfg(feature = "headless")]+"Headless" => Ok(Self::Headless),"Smtp" => Ok(Self::Smtp),_ => Err(format!("Unknown yahoo verify method: {}", s)),@@ -135,7 +133,6 @@ pub enum HotmailVerifMethod {/// its endpoint, usually http://localhost:9515, into the environment/// variable RCH_WEBDRIVER_ADDR. We recommend running chromedriver (and not/// geckodriver) as it allows parallel requests.- #[cfg(feature = "headless")]Headless,/// Use Hotmail's SMTP servers to check if an email exists.Smtp,@@ -147,7 +144,7 @@ impl FromStr for HotmailVerifMethod {fn from_str(s: &str) -> Result<Self, Self::Err> {match s {"OneDriveApi" => Ok(Self::OneDriveApi),- #[cfg(feature = "headless")]+"Headless" => Ok(Self::Headless),"Smtp" => Ok(Self::Smtp),_ => Err(format!("Unknown hotmail verify method: {}", s)),@@ -237,25 +234,14 @@ impl Default for CheckEmailInput {fn default() -> Self {CheckEmailInput {to_email: "".into(),- from_email: env::var("RCH_FROM_EMAIL")- .unwrap_or_else(|_| "[email protected]".into()), // Unused, owned by Reacher- hello_name: env::var("RCH_HELLO_NAME").unwrap_or_else(|_| "gmail.com".into()),+ from_email: "[email protected]".into(), // Unused, owned by Reacher+ hello_name: "gmail.com".into(),proxy: None,smtp_port: 25,smtp_security: SmtpSecurity::default(),- smtp_timeout: env::var("RCH_SMTP_TIMEOUT")- .ok()- .and_then(|s| s.parse::<u64>().ok())- .map(Duration::from_secs)- .or(Some(Duration::from_secs(30))),- #[cfg(not(feature = "headless"))]- yahoo_verif_method: YahooVerifMethod::Api,- #[cfg(feature = "headless")]+ smtp_timeout: Some(Duration::from_secs(30)),yahoo_verif_method: YahooVerifMethod::Headless,gmail_verif_method: GmailVerifMethod::Smtp,- #[cfg(not(feature = "headless"))]- hotmail_verif_method: HotmailVerifMethod::OneDriveApi,- #[cfg(feature = "headless")]hotmail_verif_method: HotmailVerifMethod::Headless,check_gravatar: false,haveibeenpwned_api_key: None,@@ -435,9 +421,8 @@ pub enum Reachable {/// Details about the email verification used for debugging.#[derive(Debug, Deserialize, Serialize)]pub struct DebugDetails {- /// The name of the server that performed the email verification.- /// It's generally passed as an environment variable RCH_BACKEND_NAME.- pub server_name: String,+ /// Identifier for the service currently running Reacher.+ pub backend_name: String,/// The time when the email verification started.pub start_time: DateTime<Utc>,/// The time when the email verification ended.@@ -451,11 +436,11 @@ pub struct DebugDetails {impl Default for DebugDetails {fn default() -> Self {Self {- server_name: env::var("RCH_BACKEND_NAME").unwrap_or_else(|_| String::new()),start_time: SystemTime::now().into(),end_time: SystemTime::now().into(),duration: Duration::default(),smtp: SmtpDebug::default(),+ backend_name: "backend-dev".into(),}}}diff --git a/core/src/util/mod.rs b/core/src/util/mod.rsindex a9cb0d33..c8d0d2a6 100644--- a/core/src/util/mod.rs+++ b/core/src/util/mod.rs@@ -14,7 +14,6 @@// 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/>.-pub mod constants;pub mod input_output;#[cfg(feature = "sentry")]pub mod sentry;diff --git a/core/src/util/sentry.rs b/core/src/util/sentry.rsindex 827f3bb1..6bc184dd 100644--- a/core/src/util/sentry.rs+++ b/core/src/util/sentry.rs@@ -20,11 +20,9 @@//! `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 sentry::protocol::{Event, Exception, Level, Values};+use serde::Deserialize;use tracing::{debug, info};use crate::misc::MiscError;@@ -34,11 +32,17 @@ use crate::{smtp::SmtpError, CheckEmailOutput};const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");+#[derive(Clone, Debug, Default, Deserialize)]+pub struct SentryConfig {+ pub dsn: String,+ pub backend_name: String,+}+/// Setup Sentry.-pub fn setup_sentry() -> sentry::ClientInitGuard {+pub fn setup_sentry(config: &SentryConfig) -> 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()));+ let sentry = sentry::init(config.dsn.clone());if sentry.is_enabled() {info!(target: LOG_TARGET, "Sentry is successfully set up.")}@@ -46,19 +50,6 @@ pub fn setup_sentry() -> sentry::ClientInitGuard {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@@ -81,7 +72,7 @@ impl<'a> SentryError<'a> {/// 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) {+fn error(err: SentryError, result: &CheckEmailOutput, config: &SentryConfig) {let exception_value = redact(format!("{err:?}").as_str(), &result.syntax.username);debug!(target: LOG_TARGET, "Sending error to Sentry: {}", exception_value);@@ -99,7 +90,7 @@ fn error(err: SentryError, result: &CheckEmailOutput) {environment: Some("production".into()),release: Some(CARGO_PKG_VERSION.into()),message: Some(format!("{result:#?}")),- server_name: get_backend_name(),+ server_name: Some(config.backend_name.clone().into()),transaction: Some(format!("check_email:{}", result.syntax.domain)),..Default::default()});@@ -123,15 +114,15 @@ fn skip_smtp_transient_errors(message: &[String]) -> bool {/// 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) {+pub fn log_unknown_errors(result: &CheckEmailOutput, config: &SentryConfig) {match (&result.misc, &result.mx, &result.smtp) {(Err(err), _, _) => {// We log all misc errors.- error(SentryError::Misc(err), result);+ error(SentryError::Misc(err), result, config);}(_, Err(err), _) => {// We log all mx errors.- error(SentryError::Mx(err), result);+ error(SentryError::Mx(err), result, config);}(_, _, Err(err)) if err.get_description().is_some() => {// If the SMTP error is known, we don't track it in Sentry.@@ -154,7 +145,7 @@ pub fn log_unknown_errors(result: &CheckEmailOutput) {// 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.- error(SentryError::Smtp(err), result);+ error(SentryError::Smtp(err), result, config);}// If everything is ok, we just return the result.(Ok(_), Ok(_), Ok(_)) => {}diff --git a/docker/Dockerfile.worker b/docker/Dockerfile.workerdeleted file mode 100644index f2fc39b1..00000000--- a/docker/Dockerfile.worker+++ /dev/null@@ -1,54 +0,0 @@-# From https://shaneutt.com/blog/rust-fast-small-docker-image-builds/--# -------------------------------------------------------------------------------# Cargo Build Stage-# --------------------------------------------------------------------------------FROM messense/rust-musl-cross:x86_64-musl as cargo-build--WORKDIR /usr/src/reacher--RUN rm -f target/x86_64-unknown-linux-musl/release/deps/reacher*--COPY . .--ENV SQLX_OFFLINE=true--RUN cargo build --bin reacher_worker --release --target=x86_64-unknown-linux-musl--# -------------------------------------------------------------------------------# Final Stage-# --------------------------------------------------------------------------------FROM zenika/alpine-chrome--WORKDIR /home/reacher/--USER root--# Install chromedriver-# https://github.com/Zenika/alpine-chrome/blob/master/with-chromedriver/Dockerfile-RUN apk add --no-cache chromium-chromedriver--COPY --from=cargo-build /usr/src/reacher/target/x86_64-unknown-linux-musl/release/reacher_worker .-COPY --from=cargo-build /usr/src/reacher/docker/worker.sh .-COPY --from=cargo-build /usr/src/reacher/worker/worker_config.toml .--RUN chown chrome:chrome reacher_worker-RUN chown chrome:chrome worker.sh--# User chrome was created in zenika/alpine-chrome-USER chrome--ENV RUST_LOG=reacher=info-ENV RCH_HTTP_HOST=0.0.0.0-ENV PORT=8080-ENV RCH_WEBDRIVER_ADDR=http://localhost:9515--EXPOSE 8080--# Remove entrypoint from parent Docker file-# https://stackoverflow.com/questions/40122152/how-to-remove-entrypoint-from-parent-image-on-dockerfile-ENTRYPOINT []--CMD ["./worker.sh"]diff --git a/docker/worker.sh b/docker/worker.shdeleted file mode 100755index ba37a5b2..00000000--- a/docker/worker.sh+++ /dev/null@@ -1,7 +0,0 @@-#!/bin/ash--# This is the Dockerfile's entrypoint script.--# https://docs.docker.com/config/containers/multi-service_container/-chromedriver &-./reacher_workerdiff --git a/worker/Cargo.toml b/worker/Cargo.tomlindex 0338010e..627cda59 100644--- a/worker/Cargo.toml+++ b/worker/Cargo.toml@@ -10,7 +10,7 @@ lapin = { version = "2.3.1" }tokio-executor-trait = { version = "2.1.1" }tokio-reactor-trait = { version = "1.1.0" }async-smtp = "0.6"-check-if-email-exists = { path = "../core", features = ["headless", "sentry"] }+check-if-email-exists = { path = "../core", features = ["sentry"] }openssl = { version = "0.10.64", features = ["vendored"] }reqwest = { version = "0.12.5", features = ["json", "socks"] }sentry = "0.23"diff --git a/worker/src/check_email.rs b/worker/src/check_email.rsindex 5dab15be..dd2bfeba 100644--- a/worker/src/check_email.rs+++ b/worker/src/check_email.rs@@ -16,6 +16,7 @@use crate::config::WorkerConfig;use crate::db::save_to_db;+use check_if_email_exists::config::ReacherConfig;use check_if_email_exists::{check_email, CheckEmailInput, CheckEmailOutput};use check_if_email_exists::{Reachable, LOG_TARGET};use lapin::message::Delivery;@@ -46,7 +47,7 @@ pub async fn process_queue_message(pg_pool: PgPool,config: WorkerConfig,) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {- let worker_output = process_check_email(&payload, delivery, channel, config.clone()).await;+ let worker_output = process_check_email(payload, delivery, channel, config.clone()).await;save_to_db(pg_pool, config, payload, worker_output).await}@@ -58,7 +59,11 @@ async fn process_check_email() -> Result<CheckEmailOutput, Box<dyn std::error::Error + Send + Sync>> {info!(target: LOG_TARGET, email=payload.input.to_email, "Start email verification");- let output = check_email(&payload.input).await;+ let reacher_config = ReacherConfig {+ backend_name: config.name.clone(),+ ..Default::default()+ };+ let output = check_email(&payload.input, &reacher_config).await;let reply_payload = serde_json::to_string(&output)?;let reply_payload = reply_payload.as_bytes();diff --git a/worker/src/config.rs b/worker/src/config.rsindex 3ae5e80d..edaca92f 100644--- a/worker/src/config.rs+++ b/worker/src/config.rs@@ -1,3 +1,4 @@+use check_if_email_exists::SentryConfig;use config::Config;use serde::de::{self, Deserializer, Visitor};use serde::Deserialize;@@ -11,6 +12,7 @@ pub struct WorkerConfig {pub throttle: ThrottleConfig,pub db: DBConfig,pub webhook: WebhookConfig,+ pub sentry: SentryConfig,}#[derive(Debug, Deserialize, Clone)]diff --git a/worker/src/main.rs b/worker/src/main.rsindex 2ae274c1..9cd3413c 100644--- a/worker/src/main.rs+++ b/worker/src/main.rs@@ -30,10 +30,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {tracing_subscriber::fmt::init();info!(target: LOG_TARGET, version=?CARGO_PKG_VERSION, "Running Reacher Worker");+ let config = load_config()?;+// Setup sentry bug tracking.- let _guard: sentry::ClientInitGuard = setup_sentry();+ let _guard: sentry::ClientInitGuard = setup_sentry(&config.sentry);- let config = load_config()?;let pg_pool = create_db(&config).await?;run_worker(config, pg_pool).awaitdiff --git a/worker/src/worker.rs b/worker/src/worker.rsindex ff2740dd..a7aacba9 100644--- a/worker/src/worker.rs+++ b/worker/src/worker.rs@@ -40,10 +40,7 @@ pub async fn setup_rabbit_mq(config: &WorkerConfig) -> Result<Channel, lapin::Er// Set up prefetch (concurrency) limit using qoschannel- .basic_qos(- config.rabbitmq.concurrency.into(),- BasicQosOptions::default(),- )+ .basic_qos(config.rabbitmq.concurrency, BasicQosOptions::default()).await?;info!(target: LOG_TARGET, queue=?queue_name, "Worker will start consuming messages");