athena_rs 0.83.0

Database gateway API
Documentation
use actix_web::{HttpRequest, HttpResponse};
use serde_json::json;
use std::collections::HashMap;
use std::env;

/// Extract an API key from standard request locations.
///
/// The first non-empty value wins.
pub fn extract_api_key(req: &HttpRequest) -> Option<String> {
    req.headers()
        .get("Authorization")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.strip_prefix("Bearer ").map(str::to_string))
        .or_else(|| {
            req.headers()
                .get("apikey")
                .and_then(|value| value.to_str().ok())
                .map(str::to_string)
        })
        .or_else(|| {
            req.headers()
                .get("x-api-key")
                .and_then(|value| value.to_str().ok())
                .map(str::to_string)
        })
        .or_else(|| {
            req.headers()
                .get("x-athena-key")
                .and_then(|value| value.to_str().ok())
                .map(str::to_string)
        })
        .or_else(|| {
            req.uri().query().and_then(|query| {
                serde_urlencoded::from_str::<HashMap<String, String>>(query)
                    .ok()
                    .and_then(|params| params.get("api_key").cloned())
            })
        })
        .filter(|value| !value.trim().is_empty())
}

/// Validate the static admin key stored in `ATHENA_KEY_12`.
pub fn authorize_static_admin_key(req: &HttpRequest) -> Result<(), HttpResponse> {
    let expected = env::var("ATHENA_KEY_12")
        .ok()
        .filter(|value| !value.is_empty());
    let provided = extract_api_key(req);

    match (expected, provided) {
        (None, _) => Err(HttpResponse::InternalServerError().json(json!({
            "error": "ATHENA_KEY_12 is not configured"
        }))),
        (Some(expected), Some(provided)) if expected == provided => Ok(()),
        _ => Err(HttpResponse::Unauthorized().json(json!({
            "error": "Invalid or missing API key. Use ?api_key=, Authorization: Bearer <key>, X-Athena-Key, apikey, or X-API-Key."
        }))),
    }
}