Skip to main content

road_runner_common/
auth.rs

1use serde::{Deserialize, Serialize};
2use uuid::Uuid;
3
4use crate::error::AppError;
5
6/// What kind of caller this context represents.
7///
8/// All principals carry a `user_id`:
9/// - `User`    → the authenticated end user.
10/// - `ApiKey`  → a machine key acting on behalf of its owning user (`user_id` = owner,
11///               `api_key_id` = the key).
12/// - `Service` → an internal service-to-service caller.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "lowercase")]
15pub enum PrincipalKind {
16    User,
17    ApiKey,
18    Service,
19}
20
21impl Default for PrincipalKind {
22    fn default() -> Self {
23        PrincipalKind::User
24    }
25}
26
27impl PrincipalKind {
28    pub fn as_str(self) -> &'static str {
29        match self {
30            PrincipalKind::User => "user",
31            PrincipalKind::ApiKey => "apikey",
32            PrincipalKind::Service => "service",
33        }
34    }
35
36    pub fn parse(raw: &str) -> Self {
37        match raw.trim().to_ascii_lowercase().as_str() {
38            "apikey" | "api_key" | "api-key" => PrincipalKind::ApiKey,
39            "service" => PrincipalKind::Service,
40            _ => PrincipalKind::User,
41        }
42    }
43}
44
45/// The authenticated caller, resolved once at the edge (gateway) and propagated to every
46/// service via signed headers. This is the single identity type shared across all services.
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct UserContext {
49    /// Canonical, opaque principal id. For `User` this is the user's UUID (as a string);
50    /// for `ApiKey`/`Service` it is the principal's stable id. Use [`UserContext::user_id`]
51    /// when a typed UUID is required.
52    pub subject: String,
53
54    #[serde(default)]
55    pub principal: PrincipalKind,
56
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub email: Option<String>,
59
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub username: Option<String>,
62
63    #[serde(default)]
64    pub roles: Vec<String>,
65
66    #[serde(default)]
67    pub scopes: Vec<String>,
68
69    /// Active organization / tenant, when the caller is operating in one.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub tenant_id: Option<String>,
72
73    /// Present only for `ApiKey` principals.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub api_key_id: Option<String>,
76}
77
78impl UserContext {
79    /// Parse the subject as a user UUID. Errors for non-UUID principals (e.g. API keys).
80    pub fn user_id(&self) -> Result<Uuid, AppError> {
81        Uuid::parse_str(&self.subject).map_err(|_| AppError::Unauthorized {
82            message: "subject is not a valid user id".to_string(),
83        })
84    }
85
86    /// Parse the subject as a user UUID, or `None` for non-UUID principals.
87    pub fn user_id_opt(&self) -> Option<Uuid> {
88        Uuid::parse_str(&self.subject).ok()
89    }
90
91    pub fn is_user(&self) -> bool {
92        self.principal == PrincipalKind::User
93    }
94
95    pub fn is_api_key(&self) -> bool {
96        self.principal == PrincipalKind::ApiKey
97    }
98
99    pub fn is_service(&self) -> bool {
100        self.principal == PrincipalKind::Service
101    }
102
103    // --- Roles --------------------------------------------------------------
104
105    pub fn has_role(&self, role: &str) -> bool {
106        self.roles.iter().any(|r| r == role)
107    }
108
109    pub fn has_any_role(&self, roles: &[&str]) -> bool {
110        roles.iter().any(|role| self.has_role(role))
111    }
112
113    pub fn require_role(&self, role: &str) -> Result<(), AppError> {
114        if self.has_role(role) {
115            Ok(())
116        } else {
117            Err(AppError::Forbidden {
118                message: format!("Missing role: {role}"),
119            })
120        }
121    }
122
123    pub fn require_any_role(&self, roles: &[&str]) -> Result<(), AppError> {
124        if self.has_any_role(roles) {
125            Ok(())
126        } else {
127            Err(AppError::Forbidden {
128                message: format!("Missing any of roles: {}", roles.join(", ")),
129            })
130        }
131    }
132
133    /// Platform-admin check: holds `ADMIN` or any `*_ADMIN` role (case-insensitive).
134    pub fn is_admin(&self) -> bool {
135        self.roles.iter().any(|role| {
136            let upper = role.to_ascii_uppercase();
137            upper == "ADMIN" || upper.ends_with("_ADMIN")
138        })
139    }
140
141    pub fn require_admin(&self) -> Result<(), AppError> {
142        if self.is_admin() {
143            Ok(())
144        } else {
145            Err(AppError::Forbidden {
146                message: "Admin role required".to_string(),
147            })
148        }
149    }
150
151    // --- Scopes -------------------------------------------------------------
152
153    pub fn has_scope(&self, scope: &str) -> bool {
154        self.scopes.iter().any(|s| s == scope)
155    }
156
157    pub fn require_scope(&self, scope: &str) -> Result<(), AppError> {
158        if self.has_scope(scope) {
159            Ok(())
160        } else {
161            Err(AppError::Forbidden {
162                message: format!("Missing scope: {scope}"),
163            })
164        }
165    }
166}
167
168#[cfg(feature = "web")]
169mod web_impl {
170    use super::*;
171    use actix_web::{dev::Payload, FromRequest, HttpMessage, HttpRequest};
172    use futures_util::future::{ready, Ready};
173
174    /// Actix extractor: reads the `UserContext` that the auth middleware inserted into
175    /// request extensions. Returns 401 when no context is present.
176    impl FromRequest for UserContext {
177        type Error = AppError;
178        type Future = Ready<Result<Self, Self::Error>>;
179
180        fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
181            match req.extensions().get::<UserContext>().cloned() {
182                Some(ctx) => ready(Ok(ctx)),
183                None => ready(Err(AppError::Unauthorized {
184                    message: "Missing user context".to_string(),
185                })),
186            }
187        }
188    }
189}