The platform for continuously improving AI agents.
use axum::{
extract::{Request, State},
http::{HeaderMap, header},
middleware::Next,
response::Response,
};
use controlplane::{AuthRegistry, ControlPlaneError, Principal};
pub const HEADER_PROJECT_ID: &str = "x-project-id";
const HEADER_PROJECT_ALT: &str = "x-overmind-project-id";
const TOKEN_HEADERS: [&str; 3] = ["x-overmind-api-key", "x-api-key", "x-auth-token"];
const AUTHORIZATION_SCHEMES: [&str; 3] = ["bearer", "apikey", "token"];
#[derive(Debug, Clone)]
pub enum Credential {
Anonymous,
Authenticated(Principal),
/// A token was sent but no verifier accepted it.
Rejected(String),
/// Verification itself failed (storage error), so the request cannot be judged.
Unavailable,
}
#[derive(Debug, Clone)]
pub struct AuthContext {
pub credential: Credential,
pub requested_project_id: Option<String>,
pub client_ip: Option<String>,
}
impl AuthContext {
/// `Ok(None)` for anonymous callers. A sent-but-invalid token is always an error.
pub fn principal(&self) -> Result<Option<&Principal>, ControlPlaneError> {
match &self.credential {
Credential::Anonymous => Ok(None),
Credential::Authenticated(principal) => Ok(Some(principal)),
Credential::Rejected(msg) => Err(ControlPlaneError::Unauthorized(msg.clone())),
Credential::Unavailable => Err(ControlPlaneError::Storage(anyhow::anyhow!(
"credential verification failed"
))),
}
}
}
fn header_str<'a>(headers: &'a HeaderMap, name: impl header::AsHeaderName) -> Option<&'a str> {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|s| !s.is_empty())
}
/// Token headers in priority order, then `Authorization: Bearer|ApiKey|Token <token>`.
pub fn extract_token(headers: &HeaderMap) -> Option<&str> {
if let Some(token) = TOKEN_HEADERS
.iter()
.find_map(|name| header_str(headers, *name))
{
return Some(token);
}
let (scheme, token) = header_str(headers, header::AUTHORIZATION)?.split_once(' ')?;
let token = token.trim();
(AUTHORIZATION_SCHEMES.contains(&scheme.to_ascii_lowercase().as_str()) && !token.is_empty())
.then_some(token)
}
fn client_ip(headers: &HeaderMap) -> Option<String> {
header_str(headers, "fly-client-ip")
.or_else(|| {
header_str(headers, "x-forwarded-for")
.map(|value| value.split(',').next().unwrap_or(value).trim())
})
.map(str::to_string)
}
pub async fn attach_auth_context(
State(registry): State<AuthRegistry>,
mut req: Request,
next: Next,
) -> Response {
let headers = req.headers().clone();
let ip = client_ip(&headers);
let credential = match extract_token(&headers).map(ToOwned::to_owned) {
None => Credential::Anonymous,
Some(token) => match registry.authenticate_token(&token, ip.as_deref()).await {
Ok(principal) => Credential::Authenticated(principal),
Err(ControlPlaneError::Storage(err)) => {
tracing::error!(?err, "credential verification failed");
Credential::Unavailable
}
Err(ControlPlaneError::Unauthorized(msg)) => Credential::Rejected(msg),
Err(err) => Credential::Rejected(err.to_string()),
},
};
let requested_project_id = header_str(&headers, HEADER_PROJECT_ID)
.or_else(|| header_str(&headers, HEADER_PROJECT_ALT))
.map(ToOwned::to_owned);
req.extensions_mut().insert(AuthContext {
credential,
requested_project_id,
client_ip: ip,
});
next.run(req).await
}