ferrik-core 0.0.4

Core runtime, triple-response engine, AI discovery, and testing framework for Ferrik
Documentation
//! Agent-native authentication (`ferrik_ak_...` scoped API keys, `AuthActor` extractor,
//! and OAuth2 Client Credentials handshake types).

use async_trait::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;

/// Prefix for all Ferrik Agent API keys.
pub const AGENT_KEY_PREFIX: &str = "ferrik_ak_";

/// Authenticated human user session.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UserSession {
    pub user_id: String,
    pub email: Option<String>,
}

/// Authenticated AI agent principal resolved from a scoped Agent API key.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AgentPrincipal {
    pub agent_id: i32,
    pub name: String,
    pub scopes: Vec<String>,
}

impl AgentPrincipal {
    /// Checks whether this agent holds the requested scope (supports `*` and `<prefix>:*`).
    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
    }
}

/// Unified controller extractor representing either a human user or an AI agent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuthActor {
    Human(UserSession),
    Agent(AgentPrincipal),
}

impl AuthActor {
    /// Ensures the authenticated actor has the required scope.
    ///
    /// Human sessions are authorized by default; AI agents must hold `scope`.
    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
                    )))
                }
            }
        }
    }
}

/// Generates a new cryptographically random Agent API key (`ferrik_ak_...`) and its SHA-256 hex digest.
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)
}

/// Computes the deterministic SHA-256 hex digest of a raw Agent API key.
pub fn hash_agent_key(raw_key: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(raw_key.as_bytes());
    hex::encode(hasher.finalize())
}

/// Parses a comma- or whitespace-separated scope list into clean scope tokens.
pub fn parse_scopes(raw: &str) -> Vec<String> {
    raw.split([',', ' '])
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(String::from)
        .collect()
}

/// Extracts a raw Agent API key from `Authorization: Bearer ...` or `X-Agent-Key`.
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())
    {
        let mut parts = auth.trim().splitn(2, char::is_whitespace);
        if let (Some(scheme), Some(token)) = (parts.next(), parts.next()) {
            if scheme.eq_ignore_ascii_case("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
}

/// Storage backend trait used by [`AuthActor`] to verify hashed Agent API keys.
#[async_trait]
pub trait AgentKeyStore: Send + Sync {
    async fn resolve_by_hash(&self, key_hash: &str) -> Result<Option<AgentPrincipal>, AppError>;
}

/// Implemented by application state structs that support [`AuthActor`] extraction.
pub trait HasAgentKeyStore {
    fn agent_key_store(&self) -> Arc<dyn AgentKeyStore>;
}

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)),
        }
    }
}

/// OAuth2 Client Credentials request body for `POST /ai/auth/token`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OAuthTokenRequest {
    pub grant_type: String,
    pub client_id: String,
    pub client_secret: String,
}

/// OAuth2 Client Credentials response body from `POST /ai/auth/token`.
#[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;

        // Missing key -> 401
        app.get_json("/secret")
            .await
            .assert_status(StatusCode::UNAUTHORIZED);

        // Wrong key -> 401
        app.as_agent(&[])
            .with_api_key("ferrik_ak_invalid")
            .get_ai("/secret")
            .await
            .assert_status(StatusCode::UNAUTHORIZED);

        // Valid key, missing scope -> 403
        app.as_agent(&["posts:read"])
            .with_api_key(&reader_key)
            .get_ai("/secret")
            .await
            .assert_status(StatusCode::FORBIDDEN);

        // Valid key with required scope -> 200
        app.as_agent(&["posts:write"])
            .with_api_key(&writer_key)
            .get_ai("/secret")
            .await
            .assert_ok()
            .assert_contains("writer-bot");
    }
}