Skip to main content

adk_auth/sso/
sso_access.rs

1//! SSO access control integration.
2
3use super::{ClaimsMapper, TokenClaims, TokenError, TokenValidator};
4use crate::{AccessControl, AuditEvent, AuditFailureMode, AuditOutcome, AuditSink, Permission};
5use std::sync::Arc;
6
7/// Combines SSO token validation with adk-auth access control.
8///
9/// With an audit sink, a grant whose decision the sink fails to record is refused with
10/// [`SsoError::AuditFailed`] ([`AuditFailureMode::Block`], the default), as
11/// [`ProtectedTool`](crate::ProtectedTool) and [`ScopeGuard`](crate::ScopeGuard) refuse
12/// the call; see [`SsoAccessControlBuilder::audit_failure_mode`].
13///
14/// # Example
15///
16/// ```rust,ignore
17/// let sso = SsoAccessControl::builder()
18///     .validator(GoogleProvider::new("client-id"))
19///     .mapper(ClaimsMapper::builder()
20///         .map_group("Admin", "admin")
21///         .default_role("user")
22///         .build())
23///     .access_control(ac)
24///     .build()?;
25///
26/// let claims = sso.check_token(token, &Permission::Tool("search".into())).await?;
27/// ```
28pub struct SsoAccessControl {
29    validator: Arc<dyn TokenValidator>,
30    mapper: ClaimsMapper,
31    access_control: AccessControl,
32    audit_sink: Option<Arc<dyn AuditSink>>,
33    audit_failure_mode: AuditFailureMode,
34}
35
36impl SsoAccessControl {
37    /// Create a new builder.
38    pub fn builder() -> SsoAccessControlBuilder {
39        SsoAccessControlBuilder::default()
40    }
41
42    /// Validate token and check permission.
43    ///
44    /// Returns the token claims if access is granted. With an audit sink, the decision is
45    /// recorded before it is returned.
46    ///
47    /// # Errors
48    ///
49    /// Returns [`SsoError::TokenError`] when the token does not validate,
50    /// [`SsoError::AccessDenied`] when no mapped role grants `permission`, and
51    /// [`SsoError::AuditFailed`] when access would be granted but the audit sink failed to
52    /// record it under [`AuditFailureMode::Block`].
53    pub async fn check_token(
54        &self,
55        token: &str,
56        permission: &Permission,
57    ) -> Result<TokenClaims, SsoError> {
58        let claims = self.validator.validate(token).await?;
59        let user_id = self.mapper.get_user_id(&claims);
60        let roles = self.mapper.map_to_roles(&claims);
61        let result = self.check_with_roles(&user_id, &roles, permission);
62
63        let recorded = match &self.audit_sink {
64            Some(sink) => {
65                let outcome =
66                    if result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied };
67                let event = AuditEvent::tool_access(&user_id, &permission.to_string(), outcome);
68                self.record(sink.as_ref(), event, &user_id, permission).await
69            }
70            None => Ok(()),
71        };
72
73        // A denial stays a denial when its record also failed.
74        result?;
75        recorded?;
76        Ok(claims)
77    }
78
79    /// Records one decision, refusing access when the sink fails in `Block` mode.
80    async fn record(
81        &self,
82        sink: &dyn AuditSink,
83        event: AuditEvent,
84        user_id: &str,
85        permission: &Permission,
86    ) -> Result<(), SsoError> {
87        let Err(error) = sink.log(event).await else {
88            return Ok(());
89        };
90        match self.audit_failure_mode {
91            AuditFailureMode::Block => {
92                tracing::error!(
93                    user.id = %user_id,
94                    permission = %permission,
95                    error = %error,
96                    "audit sink failed to record the access decision; access is not granted"
97                );
98                Err(SsoError::AuditFailed {
99                    user: user_id.to_string(),
100                    permission: permission.to_string(),
101                    reason: error.to_string(),
102                })
103            }
104            AuditFailureMode::Warn => {
105                tracing::warn!(
106                    user.id = %user_id,
107                    permission = %permission,
108                    error = %error,
109                    "audit sink failed; continuing without a record"
110                );
111                Ok(())
112            }
113        }
114    }
115
116    /// Check permission with pre-mapped roles.
117    fn check_with_roles(
118        &self,
119        user_id: &str,
120        roles: &[String],
121        permission: &Permission,
122    ) -> Result<(), SsoError> {
123        if self.access_control.check_roles(roles, permission) {
124            Ok(())
125        } else {
126            Err(SsoError::AccessDenied {
127                user: user_id.to_string(),
128                permission: permission.to_string(),
129            })
130        }
131    }
132
133    /// Get the underlying access control.
134    pub fn access_control(&self) -> &AccessControl {
135        &self.access_control
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::Role;
143    use async_trait::async_trait;
144
145    struct DummyValidator;
146
147    #[async_trait]
148    impl TokenValidator for DummyValidator {
149        async fn validate(&self, _token: &str) -> Result<TokenClaims, TokenError> {
150            Err(TokenError::ValidationError("not used in unit test".into()))
151        }
152
153        fn issuer(&self) -> &str {
154            "test-issuer"
155        }
156    }
157
158    #[test]
159    fn test_check_with_roles_honors_deny_precedence() {
160        let access_control = AccessControl::builder()
161            .role(Role::new("editor").allow(Permission::AllTools))
162            .role(Role::new("restricted").deny(Permission::Tool("code_exec".into())))
163            .build()
164            .unwrap();
165
166        let sso = SsoAccessControl {
167            validator: Arc::new(DummyValidator),
168            mapper: ClaimsMapper::builder().build(),
169            access_control,
170            audit_sink: None,
171            audit_failure_mode: AuditFailureMode::default(),
172        };
173
174        assert!(
175            sso.check_with_roles(
176                "bob",
177                &["editor".to_string(), "restricted".to_string()],
178                &Permission::Tool("code_exec".into())
179            )
180            .is_err()
181        );
182        assert!(
183            sso.check_with_roles(
184                "bob",
185                &["restricted".to_string(), "editor".to_string()],
186                &Permission::Tool("code_exec".into())
187            )
188            .is_err()
189        );
190        assert!(
191            sso.check_with_roles(
192                "bob",
193                &["editor".to_string(), "restricted".to_string()],
194                &Permission::Tool("search".into())
195            )
196            .is_ok()
197        );
198    }
199
200    /// Accepts every token as `alice` in the `Engineering` group.
201    struct AcceptingValidator;
202
203    #[async_trait]
204    impl TokenValidator for AcceptingValidator {
205        async fn validate(&self, _token: &str) -> Result<TokenClaims, TokenError> {
206            Ok(TokenClaims {
207                sub: "alice".to_string(),
208                groups: vec!["Engineering".to_string()],
209                ..TokenClaims::default()
210            })
211        }
212
213        fn issuer(&self) -> &str {
214            "test-issuer"
215        }
216    }
217
218    /// A sink whose store is down.
219    struct FailingSink;
220
221    #[async_trait]
222    impl AuditSink for FailingSink {
223        async fn log(&self, _event: AuditEvent) -> Result<(), crate::AuthError> {
224            Err(crate::AuthError::AuditError("audit store unavailable".into()))
225        }
226    }
227
228    fn engineers_deploy(sink: impl AuditSink + 'static) -> SsoAccessControlBuilder {
229        SsoAccessControl::builder()
230            .validator(AcceptingValidator)
231            .mapper(ClaimsMapper::builder().map_group("Engineering", "engineer").build())
232            .access_control(
233                AccessControl::builder()
234                    .role(Role::new("engineer").allow(Permission::Tool("deploy".into())))
235                    .build()
236                    .unwrap(),
237            )
238            .audit_sink(sink)
239    }
240
241    #[tokio::test]
242    async fn a_grant_the_sink_cannot_record_is_refused_by_default() {
243        let sso = engineers_deploy(FailingSink).build().unwrap();
244        let error = sso.check_token("token", &Permission::Tool("deploy".into())).await.unwrap_err();
245        assert!(
246            matches!(&error, SsoError::AuditFailed { user, permission, .. }
247                if user == "alice" && permission == "tool:deploy"),
248            "{error}"
249        );
250    }
251
252    #[tokio::test]
253    async fn warn_mode_grants_access_without_a_record() {
254        let sso = engineers_deploy(FailingSink)
255            .audit_failure_mode(AuditFailureMode::Warn)
256            .build()
257            .unwrap();
258        let claims = sso.check_token("token", &Permission::Tool("deploy".into())).await.unwrap();
259        assert_eq!(claims.sub, "alice");
260    }
261
262    #[tokio::test]
263    async fn a_denial_stays_a_denial_when_its_record_fails() {
264        let sso = engineers_deploy(FailingSink).build().unwrap();
265        let error =
266            sso.check_token("token", &Permission::Tool("drop_database".into())).await.unwrap_err();
267        assert!(matches!(error, SsoError::AccessDenied { .. }), "{error}");
268    }
269
270    #[tokio::test]
271    async fn a_recorded_grant_is_returned() {
272        let sink = Arc::new(crate::InMemoryAuditSink::new());
273        let sso = engineers_deploy(sink.clone()).build().unwrap();
274        let claims = sso.check_token("token", &Permission::Tool("deploy".into())).await.unwrap();
275        assert_eq!(claims.sub, "alice");
276        assert_eq!(sink.len().await, 1);
277    }
278}
279
280/// Errors from SSO access control.
281#[derive(Debug, thiserror::Error)]
282pub enum SsoError {
283    /// Token validation failed.
284    #[error("Token error: {0}")]
285    TokenError(#[from] TokenError),
286
287    /// Access denied.
288    #[error("Access denied for user '{user}' to '{permission}'")]
289    AccessDenied { user: String, permission: String },
290
291    /// Access would be granted, but the audit sink failed to record the decision.
292    #[error(
293        "access for user '{user}' to '{permission}' refused: the decision could not be audited \
294         ({reason}). Restore the audit sink, or set AuditFailureMode::Warn to grant access \
295         without a record"
296    )]
297    AuditFailed { user: String, permission: String, reason: String },
298}
299
300/// Builder for SsoAccessControl.
301#[derive(Default)]
302pub struct SsoAccessControlBuilder {
303    validator: Option<Arc<dyn TokenValidator>>,
304    mapper: Option<ClaimsMapper>,
305    access_control: Option<AccessControl>,
306    audit_sink: Option<Arc<dyn AuditSink>>,
307    audit_failure_mode: AuditFailureMode,
308}
309
310impl SsoAccessControlBuilder {
311    /// Set the token validator.
312    pub fn validator(mut self, v: impl TokenValidator + 'static) -> Self {
313        self.validator = Some(Arc::new(v));
314        self
315    }
316
317    /// Set the claims mapper.
318    pub fn mapper(mut self, m: ClaimsMapper) -> Self {
319        self.mapper = Some(m);
320        self
321    }
322
323    /// Set the access control.
324    pub fn access_control(mut self, ac: AccessControl) -> Self {
325        self.access_control = Some(ac);
326        self
327    }
328
329    /// Set the audit sink.
330    ///
331    /// A grant whose decision `sink` fails to record is refused; use
332    /// [`audit_failure_mode`](Self::audit_failure_mode) to change that.
333    pub fn audit_sink(mut self, sink: impl AuditSink + 'static) -> Self {
334        self.audit_sink = Some(Arc::new(sink));
335        self
336    }
337
338    /// Sets what happens when the audit sink fails to record a decision:
339    /// [`AuditFailureMode::Block`] (the default) refuses the grant with
340    /// [`SsoError::AuditFailed`], [`AuditFailureMode::Warn`] logs the failure and grants
341    /// access without a record.
342    ///
343    /// # Example
344    ///
345    /// ```rust,ignore
346    /// use adk_auth::AuditFailureMode;
347    /// use adk_auth::sso::SsoAccessControl;
348    ///
349    /// let sso = SsoAccessControl::builder()
350    ///     .validator(provider)
351    ///     .access_control(ac)
352    ///     .audit_sink(audit)
353    ///     .audit_failure_mode(AuditFailureMode::Warn)
354    ///     .build()?;
355    /// ```
356    pub fn audit_failure_mode(mut self, mode: AuditFailureMode) -> Self {
357        self.audit_failure_mode = mode;
358        self
359    }
360
361    /// Build the SsoAccessControl.
362    pub fn build(self) -> Result<SsoAccessControl, &'static str> {
363        Ok(SsoAccessControl {
364            validator: self.validator.ok_or("validator is required")?,
365            mapper: self.mapper.unwrap_or_else(|| ClaimsMapper::builder().build()),
366            access_control: self.access_control.ok_or("access_control is required")?,
367            audit_sink: self.audit_sink,
368            audit_failure_mode: self.audit_failure_mode,
369        })
370    }
371}