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 api_key_id: Option<String>,
72}
73
74impl UserContext {
75 pub fn user_id(&self) -> Result<Uuid, AppError> {
77 Uuid::parse_str(&self.subject).map_err(|_| AppError::Unauthorized {
78 message: "subject is not a valid user id".to_string(),
79 })
80 }
81
82 pub fn user_id_opt(&self) -> Option<Uuid> {
84 Uuid::parse_str(&self.subject).ok()
85 }
86
87 pub fn is_user(&self) -> bool {
88 self.principal == PrincipalKind::User
89 }
90
91 pub fn is_api_key(&self) -> bool {
92 self.principal == PrincipalKind::ApiKey
93 }
94
95 pub fn is_service(&self) -> bool {
96 self.principal == PrincipalKind::Service
97 }
98
99 pub fn has_role(&self, role: &str) -> bool {
102 self.roles.iter().any(|r| r == role)
103 }
104
105 pub fn has_any_role(&self, roles: &[&str]) -> bool {
106 roles.iter().any(|role| self.has_role(role))
107 }
108
109 pub fn require_role(&self, role: &str) -> Result<(), AppError> {
110 if self.has_role(role) {
111 Ok(())
112 } else {
113 Err(AppError::Forbidden {
114 message: format!("Missing role: {role}"),
115 })
116 }
117 }
118
119 pub fn require_any_role(&self, roles: &[&str]) -> Result<(), AppError> {
120 if self.has_any_role(roles) {
121 Ok(())
122 } else {
123 Err(AppError::Forbidden {
124 message: format!("Missing any of roles: {}", roles.join(", ")),
125 })
126 }
127 }
128
129 pub fn is_admin(&self) -> bool {
131 self.roles.iter().any(|role| {
132 let upper = role.to_ascii_uppercase();
133 upper == "ADMIN" || upper.ends_with("_ADMIN")
134 })
135 }
136
137 pub fn require_admin(&self) -> Result<(), AppError> {
138 if self.is_admin() {
139 Ok(())
140 } else {
141 Err(AppError::Forbidden {
142 message: "Admin role required".to_string(),
143 })
144 }
145 }
146
147 pub fn has_scope(&self, scope: &str) -> bool {
150 self.scopes.iter().any(|s| s == scope)
151 }
152
153 pub fn require_scope(&self, scope: &str) -> Result<(), AppError> {
154 if self.has_scope(scope) {
155 Ok(())
156 } else {
157 Err(AppError::Forbidden {
158 message: format!("Missing scope: {scope}"),
159 })
160 }
161 }
162}
163
164#[cfg(feature = "web")]
165mod web_impl {
166 use super::*;
167 use actix_web::{dev::Payload, FromRequest, HttpMessage, HttpRequest};
168 use futures_util::future::{ready, Ready};
169
170 impl FromRequest for UserContext {
173 type Error = AppError;
174 type Future = Ready<Result<Self, Self::Error>>;
175
176 fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
177 match req.extensions().get::<UserContext>().cloned() {
178 Some(ctx) => ready(Ok(ctx)),
179 None => ready(Err(AppError::Unauthorized {
180 message: "Missing user context".to_string(),
181 })),
182 }
183 }
184 }
185}