Skip to content

The platform for continuously improving AI agents.

16.7 KB
Raw Blame
use std::{fmt, net::IpAddr};

use ipnet::IpNet;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use uuid::Uuid;

use crate::{
    model::{ControlPlaneError, Result, User, VerifiedApiKey, normalize_uuid},
    store::PgControlPlaneStore,
};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Principal {
    User { user: User, auth_scheme: String },
    ApiKey { key: VerifiedApiKey },
}

impl Principal {
    pub fn user_id(&self) -> i64 {
        match self {
            Self::User { user, .. } => user.id,
            Self::ApiKey { key } => key.user_id,
        }
    }

    pub fn is_guest(&self) -> bool {
        match self {
            Self::User { user, .. } => user.is_guest,
            Self::ApiKey { key } => key.is_guest,
        }
    }

    pub fn auth_kind(&self) -> &str {
        match self {
            Self::User { auth_scheme, .. } => auth_scheme,
            Self::ApiKey { .. } => "api_key",
        }
    }

    pub fn user(&self) -> Option<&User> {
        match self {
            Self::User { user, .. } => Some(user),
            Self::ApiKey { .. } => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProjectAccess {
    Ingest,
    Read,
    Write,
}

pub fn looks_like_jwt(token: &str) -> bool {
    let mut parts = token.split('.');
    matches!(
        (parts.next(), parts.next(), parts.next(), parts.next()),
        (Some(_), Some(_), Some(_), None)
    ) && token.starts_with("eyJ")
}

/// Django `ip_allowed`: empty list allows every address. A listed CIDR must contain the client.
pub fn ip_allowed(allowed_ips: &[String], client_ip: Option<&str>) -> bool {
    if allowed_ips.is_empty() {
        return true;
    }
    let Some(raw) = client_ip.map(str::trim).filter(|ip| !ip.is_empty()) else {
        return false;
    };
    let Ok(mut address) = raw.parse::<IpAddr>() else {
        return false;
    };
    if let IpAddr::V6(v6) = address
        && let Some(v4) = v6.to_ipv4_mapped()
    {
        address = IpAddr::V4(v4);
    }
    allowed_ips.iter().any(|value| {
        value
            .parse::<IpNet>()
            .ok()
            .is_some_and(|net| net.contains(&address))
            || value.parse::<IpAddr>().ok().is_some_and(|ip| ip == address)
    })
}

pub fn verified_key_from_scope(
    key_id: Uuid,
    user_id: i64,
    is_guest: bool,
    project_fk: Option<Uuid>,
    scope: &Value,
    memberships: &[Uuid],
) -> Result<VerifiedApiKey> {
    let kind = scope.get("scope").and_then(Value::as_str).unwrap_or("");
    let account_scoped = kind == "account";
    let permissions: Vec<String> = scope
        .get("permission")
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter_map(|item| item.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();
    let resource_ids: Vec<Uuid> = scope
        .get("resourceIds")
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter_map(|item| item.as_str().and_then(|raw| Uuid::parse_str(raw).ok()))
                .collect()
        })
        .unwrap_or_default();
    let project_ids = if account_scoped {
        memberships.to_vec()
    } else {
        let pinned = if resource_ids.is_empty() {
            project_fk.into_iter().collect::<Vec<_>>()
        } else {
            resource_ids
        };
        memberships
            .iter()
            .copied()
            .filter(|id| pinned.contains(id))
            .collect()
    };
    Ok(VerifiedApiKey {
        key_id,
        user_id,
        is_guest,
        account_scoped,
        project_ids,
        can_read: permissions.iter().any(|p| p == "read"),
        can_write: permissions.iter().any(|p| p == "write"),
    })
}

/// Resolves the Django project UUID this credential may use for `access`.
/// `fallback_project_id` is the OTLP resource attribute, used when the request names no project.
pub async fn authorize_project(
    store: &PgControlPlaneStore,
    principal: &Principal,
    requested_project_id: Option<&str>,
    fallback_project_id: Option<&str>,
    access: ProjectAccess,
) -> Result<Uuid> {
    if principal.is_guest() && access != ProjectAccess::Read {
        return Err(ControlPlaneError::Forbidden(
            "Create an account to continue.".into(),
        ));
    }
    let requested = match requested_project_id.or(fallback_project_id) {
        Some(raw) => Some(normalize_uuid(raw)?),
        None => None,
    };

    match principal {
        Principal::ApiKey { key } => {
            let allowed = access_allowed(key.can_read, key.can_write, access);
            if !allowed {
                return Err(ControlPlaneError::Forbidden(
                    "This API key is read-only.".into(),
                ));
            }
            pick_project(
                store,
                key.user_id,
                &key.project_ids,
                key.account_scoped,
                requested,
            )
            .await
        }
        Principal::User { user, .. } => {
            let projects = store.list_active_projects_for_user(user.id).await?;
            let ids: Vec<Uuid> = projects.iter().map(|project| project.id).collect();
            pick_project(store, user.id, &ids, true, requested).await
        }
    }
}

fn access_allowed(can_read: bool, can_write: bool, access: ProjectAccess) -> bool {
    match access {
        ProjectAccess::Read => can_read || can_write,
        ProjectAccess::Ingest | ProjectAccess::Write => can_write,
    }
}

async fn pick_project(
    store: &PgControlPlaneStore,
    user_id: i64,
    allowed: &[Uuid],
    account_scoped: bool,
    requested: Option<Uuid>,
) -> Result<Uuid> {
    if let Some(id) = requested {
        if !allowed.contains(&id) {
            return Err(ControlPlaneError::Forbidden(
                "Project access denied.".into(),
            ));
        }
        return Ok(id);
    }
    if !account_scoped && allowed.len() == 1 {
        return Ok(allowed[0]);
    }
    if let Some(id) = store.first_project_for_user(user_id).await? {
        if allowed.contains(&id) {
            return Ok(id);
        }
    }
    Err(ControlPlaneError::InvalidArgument(
        "X-Project-Id header required".into(),
    ))
}

#[derive(Clone)]
pub struct DjangoApiKeyAuth {
    store: PgControlPlaneStore,
}

impl DjangoApiKeyAuth {
    pub fn new(store: PgControlPlaneStore) -> Self {
        Self { store }
    }

    pub async fn authenticate(
        &self,
        token: &str,
        client_ip: Option<&str>,
    ) -> Result<Option<Principal>> {
        if looks_like_jwt(token) {
            return Ok(None);
        }
        match self.store.verify_api_key(token, client_ip).await? {
            Some(key) => Ok(Some(Principal::ApiKey { key })),
            None => Err(ControlPlaneError::Unauthorized("Invalid API key.".into())),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct DjangoClaims {
    // simplejwt stringifies every primary key, including integer ones.
    #[serde(deserialize_with = "deserialize_user_id")]
    user_id: i64,
    #[serde(default)]
    token_type: Option<String>,
    exp: i64,
}

fn deserialize_user_id<'de, D>(deserializer: D) -> std::result::Result<i64, D::Error>
where
    D: Deserializer<'de>,
{
    struct UserId;

    impl<'de> serde::de::Visitor<'de> for UserId {
        type Value = i64;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a user id")
        }

        fn visit_i64<E: serde::de::Error>(self, value: i64) -> std::result::Result<i64, E> {
            Ok(value)
        }

        fn visit_u64<E: serde::de::Error>(self, value: u64) -> std::result::Result<i64, E> {
            i64::try_from(value).map_err(E::custom)
        }

        fn visit_str<E: serde::de::Error>(self, value: &str) -> std::result::Result<i64, E> {
            value.parse().map_err(E::custom)
        }
    }

    deserializer.deserialize_any(UserId)
}

#[derive(Clone)]
pub struct DjangoJwtAuth {
    store: PgControlPlaneStore,
    secret: Vec<u8>,
}

impl DjangoJwtAuth {
    pub fn new(store: PgControlPlaneStore, secret: impl Into<Vec<u8>>) -> Result<Self> {
        let secret = secret.into();
        if secret.is_empty() {
            return Err(ControlPlaneError::InvalidArgument(
                "django secret must not be empty".into(),
            ));
        }
        Ok(Self { store, secret })
    }

    pub fn sign_access_token(&self, user_id: i64, exp: i64) -> Result<String> {
        let claims = DjangoClaims {
            user_id,
            token_type: Some("access".into()),
            exp,
        };
        encode(
            &Header::new(Algorithm::HS256),
            &claims,
            &EncodingKey::from_secret(&self.secret),
        )
        .map_err(|err| ControlPlaneError::Storage(anyhow::anyhow!("signing jwt: {err}")))
    }

    /// `Ok(None)` when the token is not an HS256 JWT, so another verifier can run.
    pub fn verify(&self, token: &str) -> Result<Option<i64>> {
        verify_hs256(&self.secret, token)
    }

    pub async fn authenticate(&self, token: &str) -> Result<Option<Principal>> {
        let Some(user_id) = self.verify(token)? else {
            return Ok(None);
        };
        let user = self.store.get_user_by_id(user_id).await?.ok_or_else(|| {
            ControlPlaneError::Unauthorized("jwt subject is not an active user".into())
        })?;
        Ok(Some(Principal::User {
            user,
            auth_scheme: "jwt".into(),
        }))
    }
}

pub fn verify_hs256(secret: &[u8], token: &str) -> Result<Option<i64>> {
    if jsonwebtoken::decode_header(token)
        .ok()
        .as_ref()
        .map(|header| header.alg)
        != Some(Algorithm::HS256)
    {
        return Ok(None);
    }
    let mut validation = Validation::new(Algorithm::HS256);
    validation.validate_aud = false;
    let data = decode::<DjangoClaims>(token, &DecodingKey::from_secret(secret), &validation)
        .map_err(|err| {
            let message = match err.kind() {
                jsonwebtoken::errors::ErrorKind::InvalidSignature => "invalid jwt signature",
                _ => "invalid jwt",
            };
            ControlPlaneError::Unauthorized(message.into())
        })?;
    if data.claims.token_type.as_deref() == Some("refresh") {
        return Err(ControlPlaneError::Unauthorized(
            "refresh tokens are not accepted".into(),
        ));
    }
    Ok(Some(data.claims.user_id))
}

#[derive(Clone)]
pub struct AuthRegistry {
    api_keys: DjangoApiKeyAuth,
    clerk: Option<crate::clerk::ClerkAuthExtension>,
    jwt: Option<DjangoJwtAuth>,
}

impl AuthRegistry {
    pub fn new(
        store: PgControlPlaneStore,
        django_secret: impl Into<Vec<u8>>,
        clerk: Option<crate::clerk::ClerkAuthExtension>,
    ) -> Result<Self> {
        let secret = django_secret.into();
        let jwt = if secret.is_empty() {
            None
        } else {
            Some(DjangoJwtAuth::new(store.clone(), secret)?)
        };
        Ok(Self {
            api_keys: DjangoApiKeyAuth::new(store),
            clerk,
            jwt,
        })
    }

    pub fn jwt(&self) -> Option<&DjangoJwtAuth> {
        self.jwt.as_ref()
    }

    pub async fn authenticate_token(
        &self,
        raw_token: &str,
        client_ip: Option<&str>,
    ) -> Result<Principal> {
        let token = raw_token.trim();
        if !looks_like_jwt(token) {
            return self
                .api_keys
                .authenticate(token, client_ip)
                .await?
                .ok_or_else(|| {
                    ControlPlaneError::Unauthorized("unrecognized auth token format".into())
                });
        }
        if let Some(clerk) = &self.clerk
            && let Some(principal) = clerk.authenticate(token).await?
        {
            return Ok(principal);
        }
        if let Some(jwt) = &self.jwt
            && let Some(principal) = jwt.authenticate(token).await?
        {
            return Ok(principal);
        }
        Err(ControlPlaneError::Unauthorized(
            "unrecognized auth token format".into(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::PgControlPlaneStore;
    use serde_json::json;

    #[test]
    fn ip_allow_list_matches_django() {
        assert!(ip_allowed(&[], None));
        assert!(!ip_allowed(&["10.0.0.0/8".into()], None));
        assert!(ip_allowed(&["10.0.0.0/8".into()], Some("10.1.2.3")));
        assert!(!ip_allowed(&["10.0.0.0/8".into()], Some("11.0.0.1")));
        assert!(ip_allowed(&["10.0.0.0/8".into()], Some("::ffff:10.1.2.3")));
    }

    #[test]
    fn project_scope_intersects_membership() {
        let project = Uuid::nil();
        let other = Uuid::from_u128(1);
        let scope = json!({"scope": "project", "resourceIds": [project.to_string()], "permission": ["read"]});
        let key =
            verified_key_from_scope(project, 1, false, Some(project), &scope, &[project, other])
                .unwrap();
        assert_eq!(key.project_ids, vec![project]);
        assert!(key.can_read);
        assert!(!key.can_write);
        assert!(!key.account_scoped);

        let account = json!({"scope": "account", "permission": ["read", "write"]});
        let key =
            verified_key_from_scope(project, 1, false, None, &account, &[project, other]).unwrap();
        assert!(key.account_scoped);
        assert_eq!(key.project_ids.len(), 2);
        assert!(key.can_write);
    }

    #[test]
    fn hs256_round_trip_rejects_a_foreign_secret() {
        let secret = b"django-secret".to_vec();
        let claims = DjangoClaims {
            user_id: 7,
            token_type: Some("access".into()),
            exp: 4_102_444_800,
        };
        let token = encode(
            &Header::new(Algorithm::HS256),
            &claims,
            &EncodingKey::from_secret(&secret),
        )
        .unwrap();
        assert_eq!(verify_hs256(&secret, &token).unwrap(), Some(7));
        #[derive(Serialize)]
        struct StringUserId {
            user_id: String,
            token_type: String,
            exp: i64,
        }
        let string_id = encode(
            &Header::new(Algorithm::HS256),
            &StringUserId {
                user_id: "7".into(),
                token_type: "access".into(),
                exp: 4_102_444_800,
            },
            &EncodingKey::from_secret(&secret),
        )
        .unwrap();
        assert_eq!(verify_hs256(&secret, &string_id).unwrap(), Some(7));
        assert!(matches!(
            verify_hs256(b"other", &token),
            Err(ControlPlaneError::Unauthorized(_))
        ));
        let header = base64::Engine::encode(
            &base64::engine::general_purpose::URL_SAFE_NO_PAD,
            r#"{"alg":"RS256","typ":"JWT"}"#,
        );
        assert_eq!(
            verify_hs256(&secret, &format!("{header}.e30.c2ln")).unwrap(),
            None
        );
    }

    #[tokio::test]
    async fn django_credentials_resolve_against_postgres() {
        let url = std::env::var("DATABASE_URL")
            .unwrap_or_else(|_| "postgres://overbae:[email protected]:5432/overbae".into());
        let store = PgControlPlaneStore::connect(&url)
            .await
            .expect("django postgres");
        let email = format!("otel-auth-{}@example.com", Uuid::new_v4());
        let tenant = crate::fixtures::seed_tenant(&store, &email, false, &["read", "write"])
            .await
            .unwrap();
        let key = store
            .verify_api_key(&tenant.raw_key, None)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(key.project_ids, vec![tenant.project_id]);
        assert!(key.can_write);

        let registry = AuthRegistry::new(store.clone(), b"unit-secret".to_vec(), None).unwrap();
        let token = registry
            .jwt()
            .unwrap()
            .sign_access_token(tenant.user_id, 4_102_444_800)
            .unwrap();
        let principal = registry.authenticate_token(&token, None).await.unwrap();
        assert_eq!(principal.user().unwrap().email, email);
        let project = authorize_project(&store, &principal, None, None, ProjectAccess::Ingest)
            .await
            .unwrap();
        assert_eq!(project, tenant.project_id);

        let other = Uuid::from_u128(9);
        assert!(matches!(
            authorize_project(
                &store,
                &principal,
                Some(&other.to_string()),
                None,
                ProjectAccess::Read
            )
            .await,
            Err(ControlPlaneError::Forbidden(_))
        ));
        crate::fixtures::delete_user(&store, tenant.user_id).await;
    }
}