From bca67d2f0608a359360778816a683b61f61ff960 Mon Sep 17 00:00:00 2001 From: Ben Grant Date: Tue, 16 May 2023 02:18:13 +1000 Subject: [PATCH] Fix logic and document CRON_KEY env variable --- api/README.md | 4 ++++ api/src/routes/tasks.rs | 14 +++++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/api/README.md b/api/README.md index 3b9eade..4ae479f 100644 --- a/api/README.md +++ b/api/README.md @@ -24,3 +24,7 @@ Some adaptors require environment variables to be set. You can specify them in a ### Adding an adaptor See [adding an adaptor](adaptors/README.md#adding-an-adaptor) in the adaptors readme. + +## Cleanup task + +By default, anyone can run the cleanup task at `/tasks/cleanup`. This is usually not an issue, as it's based on when the events were last visited, and not when it's run, but if you'd prefer to restrict runs of the cleanup task (as it can be intensive), set a `CRON_KEY` environment variable in `.env`. This will require sending an `X-Cron-Key` header to the route with a value that matches `CRON_KEY`, or the route will return a 401 Unauthorized error. diff --git a/api/src/routes/tasks.rs b/api/src/routes/tasks.rs index b7a328f..b8c60a8 100644 --- a/api/src/routes/tasks.rs +++ b/api/src/routes/tasks.rs @@ -24,13 +24,13 @@ pub async fn cleanup( headers: HeaderMap, ) -> Result<(), ApiError> { // Check cron key - let cron_key_header = headers.get("X-Cron-Key"); - if let Some(cron_key) = cron_key_header { - if let Ok(key) = env::var("CRON_KEY") { - if !key.is_empty() && *cron_key != key { - return Err(ApiError::NotAuthorized); - } - } + let cron_key_header: String = headers + .get("X-Cron-Key") + .map(|k| k.to_str().unwrap_or_default().into()) + .unwrap_or_default(); + let env_key = env::var("CRON_KEY").unwrap_or_default(); + if !env_key.is_empty() && cron_key_header != env_key { + return Err(ApiError::NotAuthorized); } info!("Running cleanup task");