use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::header;
use axum::http::request::Parts;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::sync::Arc;
use crate::error::{AppError, FormattedError};
use crate::response::Format;
pub const AGENT_KEY_PREFIX: &str = "ferrik_ak_";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UserSession {
pub user_id: String,
pub email: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AgentPrincipal {
pub agent_id: i32,
pub name: String,
pub scopes: Vec<String>,
}
impl AgentPrincipal {
pub fn has_scope(&self, required: &str) -> bool {
if self.scopes.iter().any(|s| s == "*" || s == required) {
return true;
}
if let Some((prefix, _)) = required.split_once(':') {
let wildcard = format!("{}:*", prefix);
if self.scopes.iter().any(|s| s == &wildcard) {
return true;
}
}
false
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuthActor {
Human(UserSession),
Agent(AgentPrincipal),
}
impl AuthActor {
pub fn require_scope(&self, scope: &str) -> Result<(), AppError> {
match self {
AuthActor::Human(_) => Ok(()),
AuthActor::Agent(agent) => {
if agent.has_scope(scope) {
Ok(())
} else {
Err(AppError::Forbidden(format!(
"Agent '{}' is missing required scope '{}'",
agent.name, scope
)))
}
}
}
}
}
pub fn generate_agent_key() -> (String, String) {
let mut bytes = [0u8; 24];
rand::thread_rng().fill_bytes(&mut bytes);
let raw_key = format!("{}{}", AGENT_KEY_PREFIX, hex::encode(bytes));
let key_hash = hash_agent_key(&raw_key);
(raw_key, key_hash)
}
pub fn hash_agent_key(raw_key: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(raw_key.as_bytes());
hex::encode(hasher.finalize())
}
pub fn parse_scopes(raw: &str) -> Vec<String> {
raw.split([',', ' '])
.map(str::trim)
.filter(|s| !s.is_empty())
.map(String::from)
.collect()
}
pub fn extract_raw_api_key(headers: &axum::http::HeaderMap) -> Option<String> {
if let Some(auth) = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
{
if let Some(token) = auth.strip_prefix("Bearer ").or_else(|| auth.strip_prefix("bearer ")) {
let trimmed = token.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
}
if let Some(key) = headers.get("x-agent-key").and_then(|v| v.to_str().ok()) {
let trimmed = key.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
None
}
#[async_trait]
pub trait AgentKeyStore: Send + Sync {
async fn resolve_by_hash(&self, key_hash: &str) -> Result<Option<AgentPrincipal>, AppError>;
}
pub trait HasAgentKeyStore {
fn agent_key_store(&self) -> Arc<dyn AgentKeyStore>;
}
#[async_trait]
impl<S> FromRequestParts<S> for AuthActor
where
S: HasAgentKeyStore + Send + Sync,
{
type Rejection = FormattedError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let format = Format::negotiate(parts.uri.path(), &parts.headers);
let Some(raw_key) = extract_raw_api_key(&parts.headers) else {
return Err(AppError::Unauthorized(
"Missing Agent API key (provide Authorization: Bearer ferrik_ak_... or X-Agent-Key)".to_string(),
)
.with_format(format));
};
let key_hash = hash_agent_key(&raw_key);
let store = state.agent_key_store();
let principal = store
.resolve_by_hash(&key_hash)
.await
.map_err(|e| e.with_format(format))?;
match principal {
Some(agent) => Ok(AuthActor::Agent(agent)),
None => Err(AppError::Unauthorized("Invalid or revoked Agent API key".to_string())
.with_format(format)),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OAuthTokenRequest {
pub grant_type: String,
pub client_id: String,
pub client_secret: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OAuthTokenResponse {
pub access_token: String,
pub token_type: String,
pub scope: String,
pub expires_in: u64,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::TestApp;
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router};
use std::collections::HashMap;
#[derive(Clone)]
struct InMemoryStore {
keys: Arc<HashMap<String, AgentPrincipal>>,
}
#[async_trait]
impl AgentKeyStore for InMemoryStore {
async fn resolve_by_hash(
&self,
key_hash: &str,
) -> Result<Option<AgentPrincipal>, AppError> {
Ok(self.keys.get(key_hash).cloned())
}
}
impl HasAgentKeyStore for InMemoryStore {
fn agent_key_store(&self) -> Arc<dyn AgentKeyStore> {
Arc::new(self.clone())
}
}
async fn protected(
actor: AuthActor,
Format(fmt): Format,
) -> Result<Json<AuthActor>, FormattedError> {
actor
.require_scope("posts:write")
.map_err(|e| e.with_format(fmt))?;
Ok(Json(actor))
}
#[test]
fn generates_and_hashes_agent_keys_and_scopes() {
let (raw, digest) = generate_agent_key();
assert!(raw.starts_with(AGENT_KEY_PREFIX));
assert_eq!(digest, hash_agent_key(&raw));
assert_eq!(digest.len(), 64);
let agent = AgentPrincipal {
agent_id: 1,
name: "bot".into(),
scopes: parse_scopes("posts:read, tags:*"),
};
assert!(agent.has_scope("posts:read"));
assert!(!agent.has_scope("posts:write"));
assert!(agent.has_scope("tags:delete"));
let human = AuthActor::Human(UserSession {
user_id: "u1".into(),
email: Some("dev@ferrik.dev".into()),
});
assert!(human.require_scope("anything:write").is_ok());
}
#[tokio::test]
async fn enforces_401_403_and_200_with_auth_actor_extractor() {
let (writer_key, writer_hash) = generate_agent_key();
let (reader_key, reader_hash) = generate_agent_key();
let mut map = HashMap::new();
map.insert(
writer_hash,
AgentPrincipal {
agent_id: 1,
name: "writer-bot".into(),
scopes: vec!["posts:write".into()],
},
);
map.insert(
reader_hash,
AgentPrincipal {
agent_id: 2,
name: "reader-bot".into(),
scopes: vec!["posts:read".into()],
},
);
let store = InMemoryStore {
keys: Arc::new(map),
};
let app = TestApp::spawn_with(move |_db| async move {
Router::new()
.route("/secret", get(protected))
.with_state(store)
})
.await;
app.get_json("/secret")
.await
.assert_status(StatusCode::UNAUTHORIZED);
app.as_agent(&[])
.with_api_key("ferrik_ak_invalid")
.get_ai("/secret")
.await
.assert_status(StatusCode::UNAUTHORIZED);
app.as_agent(&["posts:read"])
.with_api_key(&reader_key)
.get_ai("/secret")
.await
.assert_status(StatusCode::FORBIDDEN);
app.as_agent(&["posts:write"])
.with_api_key(&writer_key)
.get_ai("/secret")
.await
.assert_ok()
.assert_contains("writer-bot");
}
}