Skip to main content

systemprompt_traits/
auth.rs

1//! Authentication and role-management provider traits.
2//!
3//! These traits are dispatched as trait objects (`dyn _`), so they use
4//! `#[async_trait]`; native `async fn` in traits is not yet `dyn`-compatible.
5//!
6//! Copyright (c) systemprompt.io — Business Source License 1.1.
7//! See <https://systemprompt.io> for licensing details.
8
9use async_trait::async_trait;
10use std::sync::Arc;
11use systemprompt_identifiers::UserId;
12
13pub type AuthResult<T> = Result<T, AuthProviderError>;
14
15#[derive(Debug, thiserror::Error)]
16#[non_exhaustive]
17pub enum AuthProviderError {
18    #[error("Invalid credentials")]
19    InvalidCredentials,
20
21    #[error("User not found")]
22    UserNotFound,
23
24    #[error("Invalid token")]
25    InvalidToken,
26
27    #[error("Token expired")]
28    TokenExpired,
29
30    #[error("Insufficient permissions")]
31    InsufficientPermissions,
32
33    #[error("Internal error: {0}")]
34    Internal(String),
35}
36
37#[derive(Debug, Clone)]
38pub struct AuthUser {
39    pub id: UserId,
40    pub name: String,
41    pub email: String,
42    pub roles: Vec<String>,
43    pub is_active: bool,
44}
45
46/// Federated-identity claim payload passed to
47/// [`UserProvider::find_or_create_federated`].
48///
49/// Carries only the OIDC fields needed to seed a freshly federated user — the
50/// trait stays free of any concrete JWT type so it can live in
51/// `systemprompt-traits` without taking a dependency on `systemprompt-models`.
52#[derive(Debug, Clone, Default)]
53pub struct FederatedIdentityClaims {
54    pub email: Option<String>,
55    /// Whether the upstream `IdP` has asserted `email_verified=true` for this
56    /// subject. When `false`, callers must refuse to link the federated
57    /// identity to a local account that owns the same email — a hostile
58    /// upstream could otherwise claim arbitrary accounts.
59    pub email_verified: bool,
60    pub name: Option<String>,
61    pub preferred_username: Option<String>,
62    pub roles: Vec<String>,
63}
64
65#[async_trait]
66pub trait UserProvider: Send + Sync {
67    async fn find_by_id(&self, id: &UserId) -> AuthResult<Option<AuthUser>>;
68    async fn find_by_email(&self, email: &str) -> AuthResult<Option<AuthUser>>;
69    async fn find_by_name(&self, name: &str) -> AuthResult<Option<AuthUser>>;
70    async fn create_user(
71        &self,
72        name: &str,
73        email: &str,
74        full_name: Option<&str>,
75    ) -> AuthResult<AuthUser>;
76    async fn create_anonymous(&self, fingerprint: &str) -> AuthResult<AuthUser>;
77    async fn assign_roles(&self, user_id: &UserId, roles: &[String]) -> AuthResult<()>;
78
79    /// Resolve an externally-issued identity (`issuer`, `external_sub`) to a
80    /// stable local `UserId`. On first touch creates a new `users` row plus a
81    /// `federated_identities` mapping; subsequent calls advance `last_seen_at`
82    /// and return the existing id. Implementations MUST perform both writes
83    /// in a single transaction.
84    async fn find_or_create_federated(
85        &self,
86        issuer: &str,
87        external_sub: &str,
88        claims: &FederatedIdentityClaims,
89    ) -> AuthResult<UserId>;
90}
91
92#[async_trait]
93pub trait RoleProvider: Send + Sync {
94    async fn get_roles(&self, user_id: &UserId) -> AuthResult<Vec<String>>;
95    async fn assign_role(&self, user_id: &UserId, role: &str) -> AuthResult<()>;
96    async fn revoke_role(&self, user_id: &UserId, role: &str) -> AuthResult<()>;
97    async fn list_users_by_role(&self, role: &str) -> AuthResult<Vec<AuthUser>>;
98}
99
100pub type DynUserProvider = Arc<dyn UserProvider>;
101pub type DynRoleProvider = Arc<dyn RoleProvider>;