Fix logic and document CRON_KEY env variable

This commit is contained in:
Ben Grant 2023-05-16 02:18:13 +10:00
parent 68cf43164d
commit bca67d2f06
2 changed files with 11 additions and 7 deletions

View file

@ -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.

View file

@ -24,14 +24,14 @@ pub async fn cleanup<A: Adaptor>(
headers: HeaderMap,
) -> Result<(), ApiError<A>> {
// 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 {
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");