1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
//! Azure Active Directory (Entra) OAuth / OIDC provider implementation.
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use crate::{
error::Result,
oidc_provider::OidcProvider,
provider::{OAuthProvider, TokenResponse, UserInfo},
};
/// Azure AD OAuth provider wrapper
///
/// Handles Azure Active Directory (Entra) OAuth flows and app role mapping.
/// Supports both app roles and directory roles.
#[derive(Debug)]
pub struct AzureADOAuth {
oidc: OidcProvider,
tenant: String,
}
/// Azure AD user information
#[derive(Debug, Clone, Deserialize)]
pub struct AzureADUser {
/// Object ID — the immutable, unique user identifier in Azure AD (`oid` claim)
pub oid: String,
/// User principal name (UPN), typically `user@domain.com`
pub preferred_username: Option<String>,
/// Primary email address (may differ from UPN in some tenants)
pub email: Option<String>,
/// User's display name as configured in Azure AD
pub name: Option<String>,
/// Given (first) name
pub given_name: Option<String>,
/// Surname (family / last name)
pub surname: Option<String>,
/// Job title from the directory
#[serde(rename = "jobTitle")]
pub job_title: Option<String>,
/// Department from the directory
pub department: Option<String>,
}
impl AzureADOAuth {
/// Create a new Azure AD OAuth provider
///
/// # Arguments
/// * `client_id` - Azure AD application (client) ID
/// * `client_secret` - Azure AD client secret
/// * `tenant` - Azure AD tenant ID or domain (e.g., "contoso.onmicrosoft.com" or
/// "12345678-1234-1234-1234-123456789012")
/// * `redirect_uri` - Redirect URI after authentication
///
/// # Errors
///
/// Returns `AuthError` if OIDC discovery against the Azure AD tenant fails.
pub async fn new(
client_id: String,
client_secret: String,
tenant: String,
redirect_uri: String,
) -> Result<Self> {
let issuer_url = format!("https://login.microsoftonline.com/{}/v2.0", tenant);
let oidc =
OidcProvider::new("azure_ad", &issuer_url, &client_id, &client_secret, &redirect_uri)
.await?;
Ok(Self { oidc, tenant })
}
/// Extract app roles from JWT claims
///
/// Azure AD stores app roles assigned to the user in the `roles` claim.
/// # Arguments
/// * `raw_claims` - Raw JWT claims from token
#[must_use]
pub fn extract_app_roles(raw_claims: &serde_json::Value) -> Vec<String> {
raw_claims
.get("roles")
.and_then(|roles| roles.as_array())
.map(|roles| roles.iter().filter_map(|r| r.as_str().map(|s| s.to_string())).collect())
.unwrap_or_default()
}
/// Extract groups from JWT claims
///
/// Azure AD can include group membership in the `groups` claim if configured.
/// # Arguments
/// * `raw_claims` - Raw JWT claims from token
#[must_use]
pub fn extract_groups(raw_claims: &serde_json::Value) -> Vec<String> {
raw_claims
.get("groups")
.and_then(|groups| groups.as_array())
.map(|groups| groups.iter().filter_map(|g| g.as_str().map(|s| s.to_string())).collect())
.unwrap_or_default()
}
/// Extract group IDs from JWT claims (object IDs)
///
/// Azure AD group object IDs for use with Microsoft Graph API
/// # Arguments
/// * `raw_claims` - Raw JWT claims from token
#[must_use]
pub fn extract_group_ids(raw_claims: &serde_json::Value) -> Vec<String> {
raw_claims
.get("_claim_sources")
.and_then(|sources| sources.get("src1"))
.and_then(|src| src.get("groups"))
.and_then(|groups| groups.as_array())
.map(|groups| groups.iter().filter_map(|g| g.as_str().map(|s| s.to_string())).collect())
.unwrap_or_default()
}
/// Map Azure AD app roles to FraiseQL roles
///
/// Azure AD app roles are configured in the application manifest.
/// Common role naming: fraiseql.admin, fraiseql.operator, fraiseql.viewer
///
/// # Arguments
/// * `azure_roles` - List of Azure AD app roles
#[must_use]
pub fn map_azure_roles_to_fraiseql(azure_roles: Vec<String>) -> Vec<String> {
azure_roles
.into_iter()
.filter_map(|role| {
let role_lower = role.to_lowercase();
// Support various Azure role naming conventions
if role_lower.contains("admin") {
Some("admin".to_string())
} else if role_lower.contains("operator") {
Some("operator".to_string())
} else if role_lower.contains("viewer") || role_lower.contains("reader") {
Some("viewer".to_string())
} else if role == "fraiseql.admin" || role == "fraiseql_admin" {
Some("admin".to_string())
} else if role == "fraiseql.operator" || role == "fraiseql_operator" {
Some("operator".to_string())
} else if role == "fraiseql.viewer" || role == "fraiseql_viewer" {
Some("viewer".to_string())
} else {
None
}
})
.collect()
}
/// Extract user's email or principal name
///
/// Azure AD typically provides either email or preferred_username
#[must_use]
pub fn get_user_identifier(raw_claims: &serde_json::Value) -> Option<String> {
raw_claims
.get("preferred_username")
.and_then(|u| u.as_str())
.map(|s| s.to_string())
.or_else(|| raw_claims.get("email").and_then(|e| e.as_str()).map(|s| s.to_string()))
}
/// Get user's display name
#[must_use]
pub fn get_user_display_name(raw_claims: &serde_json::Value) -> Option<String> {
raw_claims.get("name").and_then(|n| n.as_str()).map(|s| s.to_string())
}
}
// Reason: OAuthProvider is defined with #[async_trait]; all implementations must match
// its transformed method signatures to satisfy the trait contract
// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
#[async_trait]
impl OAuthProvider for AzureADOAuth {
fn name(&self) -> &'static str {
"azure_ad"
}
fn authorization_url(&self, state: &str) -> String {
self.oidc.authorization_url(state)
}
async fn exchange_code(&self, code: &str) -> Result<TokenResponse> {
self.oidc.exchange_code(code).await
}
async fn user_info(&self, access_token: &str) -> Result<UserInfo> {
let mut user_info = self.oidc.user_info(access_token).await?;
// Extract Azure AD specific claims
let app_roles = Self::extract_app_roles(&user_info.raw_claims);
let groups = Self::extract_groups(&user_info.raw_claims);
let group_ids = Self::extract_group_ids(&user_info.raw_claims);
// Store extracted data for role mapping
user_info.raw_claims["azure_app_roles"] = json!(app_roles);
user_info.raw_claims["azure_groups"] = json!(groups);
user_info.raw_claims["azure_group_ids"] = json!(group_ids);
user_info.raw_claims["azure_tenant"] = json!(&self.tenant);
// Extract org_id from custom claim or use tenant as fallback
if let Some(org_id_val) = user_info.raw_claims.get("org_id") {
if let Some(org_id_str) = org_id_val.as_str() {
user_info.raw_claims["org_id"] = json!(org_id_str);
}
} else {
// Fallback: use tenant ID as org_id
user_info.raw_claims["org_id"] = json!(&self.tenant);
}
// Extract user identifier (UPN or email)
if let Some(identifier) = Self::get_user_identifier(&user_info.raw_claims) {
user_info.raw_claims["azure_user_identifier"] = json!(identifier);
}
// Extract display name
if let Some(display_name) = Self::get_user_display_name(&user_info.raw_claims) {
user_info.raw_claims["azure_display_name"] = json!(display_name);
}
Ok(user_info)
}
async fn refresh_token(&self, refresh_token: &str) -> Result<TokenResponse> {
self.oidc.refresh_token(refresh_token).await
}
async fn revoke_token(&self, token: &str) -> Result<()> {
self.oidc.revoke_token(token).await
}
}