api_shared/
auth.rs

1//! Authentication helpers shared by the gRPC and REST APIs.
2//!
3//! ## Purpose
4//! Provides simple API key validation used by API front-ends.
5//!
6//! ## Intended use
7//! This module contains API-level authentication utilities only. It is not used by `vpr-core`.
8
9use std::env;
10
11/// Validates the provided API key against the expected API key from environment.
12///
13/// This function compares the provided API key with the value of the `API_KEY`
14/// environment variable. It's used by both gRPC and REST authentication mechanisms.
15///
16/// # Arguments
17/// * `provided_key` - The API key provided by the client
18///
19/// # Returns
20/// * `Ok(())` - If the provided key matches the expected key
21///
22/// # Errors
23/// Returns `tonic::Status` if:
24/// - `API_KEY` is not set (`INTERNAL`),
25/// - the provided key does not match (`UNAUTHENTICATED`).
26///
27/// # Environment Variables
28/// * `API_KEY` - The expected API key value (must be set)
29#[allow(clippy::result_large_err)]
30pub fn validate_api_key(provided_key: &str) -> Result<(), tonic::Status> {
31    let expected_key = env::var("API_KEY")
32        .map_err(|_| tonic::Status::internal("API_KEY not set in environment"))?;
33
34    if provided_key == expected_key {
35        Ok(())
36    } else {
37        Err(tonic::Status::unauthenticated("Invalid API key"))
38    }
39}