road_runner_common/
auth.rs1use serde::{Deserialize, Serialize};
2use uuid::Uuid;
3
4use crate::error::AppError;
5
6#[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#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct UserContext {
49 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 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub tenant_id: Option<String>,
72
73 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub api_key_id: Option<String>,
76}
77
78impl UserContext {
79 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 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 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 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 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 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}