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
feat(backend): Add header secret to protect against public requests (#1158)
Amauryfa6a56b62f4b
diff --git a/backend/README.md b/backend/README.mdindex a43f0921..1e6df52a 100644--- a/backend/README.md+++ b/backend/README.md@@ -10,7 +10,7 @@<br /><br />-This create holds the backend for [Reacher](https://reacher.email). The backend is a HTTP server with the following components:+This crate holds the backend for [Reacher](https://reacher.email). The backend is a HTTP server with the following components:- [`check-if-email-exists`](https://github.com/reacherhq/check-if-email-exists), which performs the core email verification logic,- [`warp`](https://github.com/seanmonstar/warp) web framework.@@ -48,18 +48,19 @@ Then send a `POST http://localhost:8080/v0/check_email` request with the followiThese are the environment variables used to configure the HTTP server. To pass them to the Docker container, use the `-e {ENV_VAR}={VALUE}` flag.-| Env Var | Required? | Description | Default |-| ----------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------ |-| `RCH_ENABLE_BULK` | No | If set to 1, then bulk verification endpoints will be added to the backend. | 0 |-| `DATABASE_URL` | Yes if `RCH_ENABLE_BULK==1` | Database connection string for storing results and task queue | not defined |-| `RCH_HTTP_HOST` | No | The host name to bind the HTTP server to. | `127.0.0.1` |-| `PORT` | No | The port to bind the HTTP server to, often populated by the cloud provider. | `8080` |-| `RCH_FROM_EMAIL` | No | The email to use in the `MAIL FROM:` SMTP command. | `[email protected]` |-| `RCH_SENTRY_DSN` | No | If set, bug reports will be sent to this [Sentry](https://sentry.io) DSN. | not defined |-| `RCH_DATABASE_MAX_CONNECTIONS` | No | (Bulk) Connections created for the database pool | 5 |-| `RCH_MINIMUM_TASK_CONCURRENCY` | No | (Bulk) Minimum number of concurrent running tasks below which more tasks are fetched | 10 |-| `RCH_MAXIMUM_CONCURRENT_TASK_FETCH` | No | (Bulk) Maximum number of tasks fetched at once | 20 |-| `RUST_LOG` | No | One of `trace,debug,warn,error,info`. 💡 PRO TIP: `RUST_LOG=debug` is very handful for debugging purposes. | not defined |+| Env Var | Required? | Description | Default |+| ----------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |+| `RCH_ENABLE_BULK` | No | If set to 1, then bulk verification endpoints will be added to the backend. | 0 |+| `DATABASE_URL` | Yes if `RCH_ENABLE_BULK==1` | Database connection string for storing results and task queue | not defined |+| `RCH_HTTP_HOST` | No | The host name to bind the HTTP server to. | `127.0.0.1` |+| `PORT` | No | The port to bind the HTTP server to, often populated by the cloud provider. | `8080` |+| `RCH_FROM_EMAIL` | No | The email to use in the `MAIL FROM:` SMTP command. | `[email protected]` |+| `RCH_SENTRY_DSN` | No | If set, bug reports will be sent to this [Sentry](https://sentry.io) DSN. | not defined |+| `RCH_HEADER_SECRET` | No | If set, then all HTTP requests must have the `x-reacher-secret` header set to this value. This is used to protect the backend against public unwanted HTTP requests. | undefined |+| `RCH_DATABASE_MAX_CONNECTIONS` | No | (Bulk) Connections created for the database pool | 5 |+| `RCH_MINIMUM_TASK_CONCURRENCY` | No | (Bulk) Minimum number of concurrent running tasks below which more tasks are fetched | 10 |+| `RCH_MAXIMUM_CONCURRENT_TASK_FETCH` | No | (Bulk) Maximum number of tasks fetched at once | 20 |+| `RUST_LOG` | No | One of `trace,debug,warn,error,info`. 💡 PRO TIP: `RUST_LOG=debug` is very handful for debugging purposes. | not defined |## REST API Documentationdiff --git a/backend/src/check.rs b/backend/src/check.rsindex 15377c99..182d99c7 100644--- a/backend/src/check.rs+++ b/backend/src/check.rs@@ -16,10 +16,14 @@//! This file contains shared logic for checking one email.-use super::sentry_util;-use check_if_email_exists::{check_email as ciee_check_email, CheckEmailInput, CheckEmailOutput};+use std::env;use std::time::Duration;+use check_if_email_exists::{check_email as ciee_check_email, CheckEmailInput, CheckEmailOutput};+use warp::Filter;++use super::sentry_util;+/// Timeout after which we drop the `check-if-email-exists` check. We run the/// checks twice (to avoid greylisting), so each verification takes 60s max.const SMTP_TIMEOUT: u64 = 30;@@ -35,3 +39,21 @@ pub async fn check_email(mut input: CheckEmailInput) -> CheckEmailOutput {res}++/// 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) => {+ let secret: &'static str = Box::leak(Box::new(secret));++ warp::header::exact("x-reacher-secret", secret).boxed()+ }+ Err(_) => warp::any().boxed(),+ }+}diff --git a/backend/src/routes/bulk/get.rs b/backend/src/routes/bulk/get.rsindex 77d89958..7059465e 100644--- a/backend/src/routes/bulk/get.rs+++ b/backend/src/routes/bulk/get.rs@@ -16,13 +16,14 @@//! This file implements the `GET /bulk/{id}` endpoint.-use super::{db::with_db, error::BulkError};-use check_if_email_exists::LOG_TARGET;use serde::Serialize;use sqlx::types::chrono::{DateTime, Utc};use sqlx::{Pool, Postgres};use warp::Filter;+use super::{db::with_db, error::BulkError};+use check_if_email_exists::LOG_TARGET;+/// NOTE: Type conversions from postgres to rust types/// are according to the table given by/// [sqlx here](https://docs.rs/sqlx/latest/sqlx/postgres/types/index.html)diff --git a/backend/src/routes/bulk/post.rs b/backend/src/routes/bulk/post.rsindex a87430b5..a4d09b04 100644--- a/backend/src/routes/bulk/post.rs+++ b/backend/src/routes/bulk/post.rs@@ -16,17 +16,19 @@//! This file implements the `POST /bulk` endpoint.-use super::{- db::with_db,- error::BulkError,- task::{submit_job, TaskInput},-};use check_if_email_exists::CheckEmailInputProxy;use check_if_email_exists::LOG_TARGET;use serde::{Deserialize, Serialize};use sqlx::{Pool, Postgres};use warp::Filter;+use super::{+ db::with_db,+ error::BulkError,+ task::{submit_job, TaskInput},+};+use crate::check::check_header;+/// Endpoint request body.#[derive(Clone, Debug, Deserialize, Serialize)]struct CreateBulkRequestBody {@@ -137,6 +139,7 @@ pub fn create_bulk_job() -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {warp::path!("v0" / "bulk").and(warp::post())+ .and(check_header()).and(with_db(o))// When accepting a body, we want a JSON body (and to reject huge// payloads)...diff --git a/backend/src/routes/bulk/results.rs b/backend/src/routes/bulk/results.rsindex 73970265..2e0952a6 100644--- a/backend/src/routes/bulk/results.rs+++ b/backend/src/routes/bulk/results.rs@@ -16,17 +16,19 @@//! This file implements the /bulk/{id}/results endpoints.-use super::{- db::with_db,- error::{BulkError, CsvError},-};+use std::convert::{TryFrom, TryInto};+use check_if_email_exists::LOG_TARGET;use csv::WriterBuilder;use serde::{Deserialize, Serialize};use sqlx::{Executor, Pool, Postgres, Row};-use std::convert::{TryFrom, TryInto};use warp::Filter;+use super::{+ db::with_db,+ error::{BulkError, CsvError},+};+/// Defines the download format, passed in as a query param.#[derive(Serialize, Deserialize)]#[serde(rename_all = "lowercase")]diff --git a/backend/src/routes/check_email/post.rs b/backend/src/routes/check_email/post.rsindex 7d82ad87..d74a680a 100644--- a/backend/src/routes/check_email/post.rs+++ b/backend/src/routes/check_email/post.rs@@ -16,13 +16,15 @@//! This file implements the `POST /check_email` endpoint.-use crate::check::check_email;+use std::env;+use check_if_email_exists::LOG_TARGET;use check_if_email_exists::{CheckEmailInput, CheckEmailInputProxy};use serde::{Deserialize, Serialize};-use std::env;use warp::Filter;+use crate::check::{check_email, check_header};+/// Endpoint request body.#[derive(Clone, Debug, Deserialize, Serialize)]pub struct EndpointRequest {@@ -66,6 +68,7 @@ pub fn post_check_email() -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {warp::path!("v0" / "check_email").and(warp::post())+ .and(check_header())// 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/tests/check_email.rs b/backend/tests/check_email.rsindex d379bdc8..8679ec32 100644--- a/backend/tests/check_email.rs+++ b/backend/tests/check_email.rs@@ -14,6 +14,9 @@// 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 reacher_backend::check::REACHER_SECRET_HEADER;use reacher_backend::routes::{check_email::post::EndpointRequest, create_routes};use serde_json;use warp::http::StatusCode;@@ -24,6 +27,8 @@ const FOO_BAR_BAZ_RESPONSE: &str = r#"{"input":"[email protected]","is_reachable":"inv#[tokio::test]async fn test_input_foo_bar() {+ env::remove_var("RCH_HEADER_SECRET");+let resp = request().path("/v0/check_email").method("POST")@@ -37,6 +42,8 @@ async fn test_input_foo_bar() {#[tokio::test]async fn test_input_foo_bar_baz() {+ env::remove_var("RCH_HEADER_SECRET");+let resp = request().path("/v0/check_email").method("POST")@@ -44,6 +51,53 @@ async fn test_input_foo_bar_baz() {.reply(&create_routes(None)).await;- assert_eq!(resp.status(), StatusCode::OK);+ assert_eq!(resp.status(), StatusCode::OK, "{:?}", resp.body());assert_eq!(resp.body(), FOO_BAR_BAZ_RESPONSE);}++#[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::<EndpointRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())+ .reply(&create_routes(None))+ .await;++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ assert_eq!(resp.body(), r#"Missing request header "x-reacher-secret""#);+}++#[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::<EndpointRequest>(r#"{"to_email": "[email protected]"}"#).unwrap())+ .reply(&create_routes(None))+ .await;++ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ assert_eq!(resp.body(), r#"Invalid request header "x-reacher-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::<EndpointRequest>(r#"{"to_email": "foo@bar"}"#).unwrap())+ .reply(&create_routes(None))+ .await;++ assert_eq!(resp.status(), StatusCode::OK);+ assert_eq!(resp.body(), FOO_BAR_RESPONSE);+}