Skip to main content

cognee_http_server/
auth_resolver.rs

1//! Injection seam for closed-side authentication.
2//!
3//! The OSS http-server keeps no JWT/cookie/API-key state — those moved
4//! to the closed `cognee-http-cloud` crate alongside the auth router
5//! family. To let closed embedders plug their auth chain back into the
6//! OSS `AuthenticatedUser` extractor, OSS stores an optional
7//! `Arc<dyn AuthResolver>` on `AppState`.
8//!
9//! - `AuthResolver::resolve` is the full chain (Bearer → cookie → API key
10//!   → optional `ExtraAuthValidator` hook). Returns `Some(user)` if any
11//!   method succeeds, else `None` so the extractor can fall through to
12//!   the default-user path (or 401 when `require_authentication=true`).
13//! - `ExtraAuthValidator` is the narrower Auth0/OIDC-only hook the plan
14//!   names explicitly. A closed embedder that only wants to add an Auth0
15//!   hook (and not replace the whole chain) installs only this — the OSS
16//!   `RouterBuilder::with_extra_validator(...)` wraps it in a default
17//!   resolver that calls just the validator.
18
19use std::sync::Arc;
20
21use async_trait::async_trait;
22use axum::http::HeaderMap;
23use axum::http::request::Parts;
24
25use crate::auth::AuthenticatedUser;
26
27#[async_trait]
28pub trait AuthResolver: Send + Sync + 'static {
29    /// Attempt to authenticate the request. Return `None` to fall
30    /// through to OSS default-user behaviour (when
31    /// `require_authentication` is false) or to a 401 (when true).
32    async fn resolve(&self, parts: &mut Parts) -> Option<AuthenticatedUser>;
33}
34
35#[async_trait]
36pub trait ExtraAuthValidator: Send + Sync + 'static {
37    /// Validate Auth0 / OIDC tokens (or any external auth source) given
38    /// the request headers. Closed embedders inject this via
39    /// `RouterBuilder::with_extra_validator(...)`.
40    async fn validate(&self, headers: &HeaderMap) -> Option<AuthenticatedUser>;
41}
42
43/// Wrap an `ExtraAuthValidator` into an `AuthResolver` that performs only
44/// the validator step.
45pub fn resolver_from_validator(v: Arc<dyn ExtraAuthValidator>) -> Arc<dyn AuthResolver> {
46    Arc::new(ExtraValidatorOnly { v })
47}
48
49struct ExtraValidatorOnly {
50    v: Arc<dyn ExtraAuthValidator>,
51}
52
53#[async_trait]
54impl AuthResolver for ExtraValidatorOnly {
55    async fn resolve(&self, parts: &mut Parts) -> Option<AuthenticatedUser> {
56        self.v.validate(&parts.headers).await
57    }
58}