flare_core_infra/auth/
principal.rs1use std::collections::HashMap;
2
3use async_trait::async_trait;
4use thiserror::Error;
5
6use super::token::TokenClaims;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct TokenValidationRequest {
10 pub token: String,
11 pub trace_id: Option<String>,
12 pub request_id: Option<String>,
13 pub path: Option<String>,
14 pub method: Option<String>,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct AuthenticatedPrincipal {
19 pub user_id: String,
20 pub tenant_id: Option<String>,
21 pub device_id: Option<String>,
22 pub app_id: Option<String>,
23 pub expires_at: Option<i64>,
24 pub scopes: Vec<String>,
25 pub metadata: HashMap<String, String>,
26}
27
28impl AuthenticatedPrincipal {
29 pub fn from_token_claims(claims: TokenClaims) -> Self {
30 Self {
31 user_id: claims.sub,
32 tenant_id: claims.tenant_id,
33 device_id: claims.device_id,
34 app_id: None,
35 expires_at: Some(claims.exp as i64),
36 scopes: Vec::new(),
37 metadata: HashMap::new(),
38 }
39 }
40
41 pub fn has_scope(&self, required: &str) -> bool {
42 self.scopes
43 .iter()
44 .any(|scope| scope_matches(scope.as_str(), required))
45 }
46
47 pub fn has_any_scope(&self, required: &[&str]) -> bool {
48 required.iter().any(|scope| self.has_scope(scope))
49 }
50
51 pub fn has_gateway_admin_scope(&self) -> bool {
52 self.has_any_scope(&[
53 "admin_gateway:admin",
54 "admin_gateway:admin:*",
55 "core_gateway:admin",
56 "core_gateway:admin:*",
57 "gateway:admin",
58 "flare:admin",
59 "admin:*",
60 "admin",
61 ])
62 }
63}
64
65#[derive(Debug, Error)]
66pub enum AuthError {
67 #[error("authorization token is missing")]
68 MissingToken,
69 #[error("authorization token is invalid: {0}")]
70 InvalidToken(String),
71 #[error("authenticated principal is not allowed: {0}")]
72 Forbidden(String),
73 #[error("auth provider is unavailable: {0}")]
74 ProviderUnavailable(String),
75}
76
77#[async_trait]
78pub trait TokenValidator: Send + Sync {
79 async fn validate(
80 &self,
81 request: TokenValidationRequest,
82 ) -> Result<AuthenticatedPrincipal, AuthError>;
83}
84
85fn scope_matches(granted: &str, required: &str) -> bool {
86 let granted = granted.trim();
87 let required = required.trim();
88 if granted == "*" || granted == required {
89 return true;
90 }
91 if let Some(prefix) = granted.strip_suffix(":*") {
92 return required == prefix || required.starts_with(&format!("{prefix}:"));
93 }
94 false
95}