1use super::{
16 FederatedIdentityRegistry, FederatedLoginSession, FederatedSession, FederatedSessionBinding, FederatedSessionTransaction,
17 FederationError, Result,
18};
19use crate::oidc::{OidcProviderConfig, OidcProviderSummary};
20
21const DEFAULT_OIDC_PROVIDER_ID: &str = "default";
22
23fn sorted_provider_summaries(mut providers: Vec<OidcProviderSummary>) -> Vec<OidcProviderSummary> {
24 providers.sort_by(|left, right| {
25 (left.provider_id != DEFAULT_OIDC_PROVIDER_ID)
26 .cmp(&(right.provider_id != DEFAULT_OIDC_PROVIDER_ID))
27 .then_with(|| left.provider_id.cmp(&right.provider_id))
28 });
29 providers
30}
31
32pub struct FederatedIdentityService {
33 registry: FederatedIdentityRegistry,
34}
35
36impl FederatedIdentityService {
37 pub fn new(registry: FederatedIdentityRegistry) -> Self {
38 Self { registry }
39 }
40
41 pub fn has_providers(&self) -> bool {
42 self.registry.standard_oidc().has_providers()
43 }
44
45 pub fn list_providers(&self) -> Vec<OidcProviderSummary> {
46 sorted_provider_summaries(self.registry.standard_oidc().list_providers())
47 }
48
49 pub fn list_visible_providers(&self) -> Vec<OidcProviderSummary> {
50 sorted_provider_summaries(self.registry.standard_oidc().list_visible_providers())
51 }
52
53 pub fn get_provider_config(&self, id: &str) -> Option<&OidcProviderConfig> {
54 self.registry.standard_oidc().provider_config(id)
55 }
56
57 pub async fn authorize_url(&self, provider_id: &str, redirect_uri: &str, redirect_after: Option<String>) -> Result<String> {
58 self.registry
59 .standard_oidc()
60 .authorize_url(provider_id, redirect_uri, redirect_after)
61 .await
62 }
63
64 pub async fn complete_authorization_code(
65 &self,
66 state: &str,
67 code: &str,
68 redirect_uri: &str,
69 duration_seconds: usize,
70 binding: &dyn FederatedSessionBinding,
71 ) -> Result<FederatedLoginSession> {
72 let exchange = self.registry.standard_oidc().exchange_code(state, code, redirect_uri).await?;
73 let provider_id = exchange.authorization.provider_id.clone();
74 let transaction = FederatedSessionTransaction {
75 authorization: exchange.authorization,
76 duration_seconds,
77 session_policy: None,
78 };
79 let credentials = binding.bind(&transaction).await?;
80 let logout_token = self
81 .registry
82 .standard_oidc()
83 .create_logout_token(&provider_id, &exchange.id_token)
84 .await?;
85
86 Ok(FederatedLoginSession {
87 session: FederatedSession {
88 credentials,
89 authorization: transaction.authorization,
90 },
91 redirect_after: exchange.redirect_after,
92 logout_token,
93 })
94 }
95
96 pub async fn assume_role_with_web_identity(
97 &self,
98 jwt: &str,
99 duration_seconds: usize,
100 session_policy: Option<String>,
101 binding: &dyn FederatedSessionBinding,
102 ) -> Result<FederatedSession> {
103 let authorization = self.registry.standard_oidc().verify_web_identity_token(jwt).await?;
104 if !authorization.has_authorization_context() {
105 tracing::warn!(
106 provider_id = %authorization.provider_id,
107 username = %authorization.claims.username,
108 sub = %authorization.claims.sub,
109 policy_count = authorization.policies.len(),
110 group_count = authorization.groups.len(),
111 "AssumeRoleWithWebIdentity has no mapped policies or groups"
112 );
113 return Err(FederationError::NoAuthorizationContext);
114 }
115 tracing::debug!(
116 provider_id = %authorization.provider_id,
117 username = %authorization.claims.username,
118 policy_count = authorization.policies.len(),
119 group_count = authorization.groups.len(),
120 policies = ?authorization.policies,
121 groups = ?authorization.groups,
122 "AssumeRoleWithWebIdentity mapped OIDC policies and groups"
123 );
124
125 let transaction = FederatedSessionTransaction {
126 authorization,
127 duration_seconds,
128 session_policy,
129 };
130 let credentials = binding.bind(&transaction).await?;
131
132 Ok(FederatedSession {
133 credentials,
134 authorization: transaction.authorization,
135 })
136 }
137
138 pub async fn build_logout_url(&self, logout_token: &str, post_logout_redirect_uri: &str) -> Result<Option<String>> {
139 self.registry
140 .standard_oidc()
141 .build_logout_url(logout_token, post_logout_redirect_uri)
142 .await
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149 use crate::federation::{
150 FederatedAuthorization, FederatedClaims, FederatedCodeExchange, FederatedIdentityProvider, FederatedSessionBindingError,
151 };
152 use crate::oidc::{OidcProviderConfig, OidcProviderSummary};
153 use rustfs_credentials::Credentials;
154 use std::sync::{Arc, Mutex};
155
156 #[derive(Clone, Copy, PartialEq, Eq)]
157 enum ProviderFailure {
158 None,
159 Exchange,
160 Verification,
161 Logout,
162 }
163
164 struct TestProvider {
165 with_policy: bool,
166 with_group: bool,
167 browser_provider_id: &'static str,
168 web_provider_id: &'static str,
169 failure: ProviderFailure,
170 events: Arc<Mutex<Vec<&'static str>>>,
171 expected_logout: (&'static str, &'static str),
172 listed_provider_ids: Vec<&'static str>,
173 visible_provider_ids: Vec<&'static str>,
174 }
175
176 impl TestProvider {
177 fn new(events: Arc<Mutex<Vec<&'static str>>>) -> Self {
178 Self {
179 with_policy: true,
180 with_group: false,
181 browser_provider_id: DEFAULT_OIDC_PROVIDER_ID,
182 web_provider_id: DEFAULT_OIDC_PROVIDER_ID,
183 failure: ProviderFailure::None,
184 events,
185 expected_logout: (DEFAULT_OIDC_PROVIDER_ID, "id-token"),
186 listed_provider_ids: Vec::new(),
187 visible_provider_ids: Vec::new(),
188 }
189 }
190
191 fn record(&self, event: &'static str) {
192 self.events.lock().expect("event log should not be poisoned").push(event);
193 }
194
195 fn authorization(&self, provider_id: &str) -> FederatedAuthorization {
196 FederatedAuthorization {
197 provider_id: provider_id.to_string(),
198 claims: FederatedClaims {
199 sub: "subject".to_string(),
200 email: String::new(),
201 username: "user".to_string(),
202 groups: vec!["source-group".to_string()],
203 raw: Default::default(),
204 },
205 policies: if self.with_policy {
206 vec!["readwrite".to_string()]
207 } else {
208 Vec::new()
209 },
210 groups: if self.with_group {
211 vec!["developers".to_string()]
212 } else {
213 Vec::new()
214 },
215 roles_claim_key: None,
216 roles: Vec::new(),
217 }
218 }
219 }
220
221 fn provider_summaries(provider_ids: &[&str]) -> Vec<OidcProviderSummary> {
222 provider_ids
223 .iter()
224 .map(|provider_id| OidcProviderSummary {
225 provider_id: (*provider_id).to_string(),
226 display_name: (*provider_id).to_string(),
227 })
228 .collect()
229 }
230
231 #[async_trait::async_trait]
232 impl FederatedIdentityProvider for TestProvider {
233 fn has_providers(&self) -> bool {
234 true
235 }
236
237 fn list_providers(&self) -> Vec<OidcProviderSummary> {
238 provider_summaries(&self.listed_provider_ids)
239 }
240
241 fn list_visible_providers(&self) -> Vec<OidcProviderSummary> {
242 provider_summaries(&self.visible_provider_ids)
243 }
244
245 fn provider_config(&self, _id: &str) -> Option<&OidcProviderConfig> {
246 None
247 }
248
249 async fn authorize_url(
250 &self,
251 _provider_id: &str,
252 _redirect_uri: &str,
253 _redirect_after: Option<String>,
254 ) -> Result<String> {
255 Ok("https://identity.example/authorize".to_string())
256 }
257
258 async fn exchange_code(&self, _state: &str, _code: &str, _redirect_uri: &str) -> Result<FederatedCodeExchange> {
259 self.record("exchange");
260 if self.failure == ProviderFailure::Exchange {
261 return Err(FederationError::CodeExchange("exchange failed".to_string()));
262 }
263 Ok(FederatedCodeExchange {
264 authorization: self.authorization(self.browser_provider_id),
265 redirect_after: Some("/browser".to_string()),
266 id_token: "id-token".to_string(),
267 })
268 }
269
270 async fn verify_web_identity_token(&self, _jwt: &str) -> Result<FederatedAuthorization> {
271 self.record("verify");
272 if self.failure == ProviderFailure::Verification {
273 return Err(FederationError::TokenVerification("verification failed".to_string()));
274 }
275 Ok(self.authorization(self.web_provider_id))
276 }
277
278 async fn create_logout_token(&self, provider_id: &str, id_token: &str) -> Result<String> {
279 self.record("logout");
280 assert_eq!((provider_id, id_token), self.expected_logout);
281 if self.failure == ProviderFailure::Logout {
282 return Err(FederationError::Logout("logout failed".to_string()));
283 }
284 Ok("logout-token".to_string())
285 }
286
287 async fn build_logout_url(&self, _logout_token: &str, _post_logout_redirect_uri: &str) -> Result<Option<String>> {
288 Ok(Some("https://identity.example/logout".to_string()))
289 }
290 }
291
292 struct RecordingBinding {
293 fail: bool,
294 events: Arc<Mutex<Vec<&'static str>>>,
295 transactions: Mutex<Vec<(String, usize, Option<String>)>>,
296 }
297
298 impl RecordingBinding {
299 fn new(events: Arc<Mutex<Vec<&'static str>>>) -> Self {
300 Self {
301 fail: false,
302 events,
303 transactions: Mutex::new(Vec::new()),
304 }
305 }
306 }
307
308 #[async_trait::async_trait]
309 impl FederatedSessionBinding for RecordingBinding {
310 async fn bind(
311 &self,
312 transaction: &FederatedSessionTransaction,
313 ) -> core::result::Result<Credentials, FederatedSessionBindingError> {
314 self.events.lock().expect("event log should not be poisoned").push("bind");
315 self.transactions.lock().expect("transactions should not be poisoned").push((
316 transaction.authorization.provider_id.clone(),
317 transaction.duration_seconds,
318 transaction.session_policy.clone(),
319 ));
320 if self.fail {
321 return Err(FederatedSessionBindingError::Internal("binding failed".to_string()));
322 }
323 Ok(Credentials {
324 access_key: transaction.authorization.claims.session_identity(),
325 ..Default::default()
326 })
327 }
328 }
329
330 #[test]
331 fn provider_listing_puts_default_first_and_sorts_named_providers() {
332 let events = Arc::new(Mutex::new(Vec::new()));
333 let mut provider = TestProvider::new(events);
334 provider.listed_provider_ids = vec!["zeta", "hidden", DEFAULT_OIDC_PROVIDER_ID, "alpha"];
335 provider.visible_provider_ids = vec!["zeta", DEFAULT_OIDC_PROVIDER_ID, "alpha"];
336 let service = FederatedIdentityService::new(FederatedIdentityRegistry::new(Arc::new(provider)));
337
338 assert_eq!(
339 service
340 .list_providers()
341 .into_iter()
342 .map(|provider| provider.provider_id)
343 .collect::<Vec<_>>(),
344 [DEFAULT_OIDC_PROVIDER_ID, "alpha", "hidden", "zeta"]
345 );
346 assert_eq!(
347 service
348 .list_visible_providers()
349 .into_iter()
350 .map(|provider| provider.provider_id)
351 .collect::<Vec<_>>(),
352 [DEFAULT_OIDC_PROVIDER_ID, "alpha", "zeta"]
353 );
354 assert_eq!(
355 sorted_provider_summaries(provider_summaries(&["zeta", "alpha"]))
356 .into_iter()
357 .map(|provider| provider.provider_id)
358 .collect::<Vec<_>>(),
359 ["alpha", "zeta"]
360 );
361 }
362
363 #[tokio::test]
364 async fn callback_and_web_identity_preserve_provider_and_transaction_boundaries() {
365 let events = Arc::new(Mutex::new(Vec::new()));
366 let mut provider = TestProvider::new(events.clone());
367 provider.browser_provider_id = "corp";
368 provider.web_provider_id = "partner";
369 provider.expected_logout = ("corp", "id-token");
370 let provider = Arc::new(provider);
371 let binding = Arc::new(RecordingBinding::new(events.clone()));
372 let service = FederatedIdentityService::new(FederatedIdentityRegistry::new(provider));
373
374 let login = service
375 .complete_authorization_code("state", "code", "https://console.example/callback", 3600, binding.as_ref())
376 .await
377 .expect("callback flow should complete");
378 assert_eq!(login.session.credentials.access_key, "user");
379 assert_eq!(login.session.authorization.provider_id, "corp");
380 assert_eq!(login.redirect_after.as_deref(), Some("/browser"));
381 assert_eq!(login.logout_token, "logout-token");
382 assert_eq!(
383 events.lock().expect("event log should not be poisoned").as_slice(),
384 ["exchange", "bind", "logout"]
385 );
386 events.lock().expect("event log should not be poisoned").clear();
387
388 let web_identity = service
389 .assume_role_with_web_identity("jwt", 7200, Some("session-policy".to_string()), binding.as_ref())
390 .await
391 .expect("web identity flow should complete");
392 assert_eq!(web_identity.credentials.access_key, "user");
393 assert_eq!(web_identity.authorization.provider_id, "partner");
394 assert_eq!(events.lock().expect("event log should not be poisoned").as_slice(), ["verify", "bind"]);
395 assert_eq!(
396 binding
397 .transactions
398 .lock()
399 .expect("transactions should not be poisoned")
400 .as_slice(),
401 [
402 ("corp".to_string(), 3600, None),
403 ("partner".to_string(), 7200, Some("session-policy".to_string())),
404 ]
405 );
406 }
407
408 #[tokio::test]
409 async fn web_identity_without_policy_or_group_is_not_bound() {
410 let events = Arc::new(Mutex::new(Vec::new()));
411 let mut provider = TestProvider::new(events.clone());
412 provider.with_policy = false;
413 let provider = Arc::new(provider);
414 let binding = Arc::new(RecordingBinding::new(events.clone()));
415 let service = FederatedIdentityService::new(FederatedIdentityRegistry::new(provider));
416
417 let error = service
418 .assume_role_with_web_identity("jwt", 3600, None, binding.as_ref())
419 .await
420 .expect_err("authorization context is required");
421
422 assert!(matches!(error, FederationError::NoAuthorizationContext));
423 assert_eq!(events.lock().expect("event log should not be poisoned").as_slice(), ["verify"]);
424 }
425
426 #[tokio::test]
427 async fn web_identity_group_only_authorization_is_bound_once() {
428 let events = Arc::new(Mutex::new(Vec::new()));
429 let mut provider = TestProvider::new(events.clone());
430 provider.with_policy = false;
431 provider.with_group = true;
432 let provider = Arc::new(provider);
433 let binding = Arc::new(RecordingBinding::new(events.clone()));
434 let service = FederatedIdentityService::new(FederatedIdentityRegistry::new(provider));
435
436 let session = service
437 .assume_role_with_web_identity("jwt", 3600, None, binding.as_ref())
438 .await
439 .expect("a mapped group is an authorization context");
440
441 assert!(session.authorization.policies.is_empty());
442 assert_eq!(session.authorization.groups, ["developers"]);
443 assert_eq!(events.lock().expect("event log should not be poisoned").as_slice(), ["verify", "bind"]);
444 }
445
446 #[tokio::test]
447 async fn callback_failures_preserve_existing_side_effect_order() {
448 for (provider_failure, binding_failure, expected_events) in [
449 (ProviderFailure::Exchange, false, vec!["exchange"]),
450 (ProviderFailure::None, true, vec!["exchange", "bind"]),
451 (ProviderFailure::Logout, false, vec!["exchange", "bind", "logout"]),
452 ] {
453 let events = Arc::new(Mutex::new(Vec::new()));
454 let mut provider = TestProvider::new(events.clone());
455 provider.failure = provider_failure;
456 let mut binding = RecordingBinding::new(events.clone());
457 binding.fail = binding_failure;
458 let binding = Arc::new(binding);
459 let service = FederatedIdentityService::new(FederatedIdentityRegistry::new(Arc::new(provider)));
460
461 let error = service
462 .complete_authorization_code("state", "code", "https://console.example/callback", 3600, binding.as_ref())
463 .await
464 .expect_err("the configured failure should be returned");
465
466 if provider_failure == ProviderFailure::Exchange {
467 assert!(matches!(error, FederationError::CodeExchange(ref message) if message == "exchange failed"));
468 } else if binding_failure {
469 assert!(matches!(
470 error,
471 FederationError::Binding(FederatedSessionBindingError::Internal(ref message))
472 if message == "binding failed"
473 ));
474 } else {
475 assert!(matches!(error, FederationError::Logout(ref message) if message == "logout failed"));
476 }
477
478 assert_eq!(
479 events.lock().expect("event log should not be poisoned").as_slice(),
480 expected_events,
481 "later callback steps must not run after a failure"
482 );
483 }
484 }
485
486 #[tokio::test]
487 async fn web_identity_failures_preserve_existing_side_effect_order() {
488 for (provider_failure, binding_failure, expected_events) in [
489 (ProviderFailure::Verification, false, vec!["verify"]),
490 (ProviderFailure::None, true, vec!["verify", "bind"]),
491 ] {
492 let events = Arc::new(Mutex::new(Vec::new()));
493 let mut provider = TestProvider::new(events.clone());
494 provider.failure = provider_failure;
495 let mut binding = RecordingBinding::new(events.clone());
496 binding.fail = binding_failure;
497 let binding = Arc::new(binding);
498 let service = FederatedIdentityService::new(FederatedIdentityRegistry::new(Arc::new(provider)));
499
500 let error = service
501 .assume_role_with_web_identity("jwt", 3600, None, binding.as_ref())
502 .await
503 .expect_err("the configured failure should be returned");
504
505 if provider_failure == ProviderFailure::Verification {
506 assert!(matches!(error, FederationError::TokenVerification(_)));
507 } else {
508 assert!(matches!(
509 error,
510 FederationError::Binding(FederatedSessionBindingError::Internal(ref message))
511 if message == "binding failed"
512 ));
513 }
514 assert_eq!(
515 events.lock().expect("event log should not be poisoned").as_slice(),
516 expected_events,
517 "later web identity steps must not run after a failure"
518 );
519 }
520 }
521}