adk-auth 3.0.0

Access control and authentication for Rust Agent Development Kit (ADK-Rust)
Documentation
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Scope-based access control for tools.
//!
//! Scopes provide a declarative security model where tools declare what scopes
//! they require, and the framework automatically enforces them before execution.
//!
//! # Overview
//!
//! Unlike role-based access control (which maps users → roles → permissions),
//! scope-based access works at the tool level:
//!
//! 1. Tools declare required scopes via [`Tool::required_scopes()`]
//! 2. User scopes are resolved from session state, JWT claims, or a custom provider
//! 3. The [`ScopeGuard`] checks that the user has **all** required scopes
//!
//! # Example
//!
//! ```rust,ignore
//! use adk_auth::{ScopeGuard, ContextScopeResolver};
//!
//! // Tools declare their requirements
//! let transfer = FunctionTool::new("transfer", "Transfer funds", handler)
//!     .with_scopes(&["finance:write", "verified"]);
//!
//! // Guard enforces scopes automatically
//! let guard = ScopeGuard::new(ContextScopeResolver);
//! let protected = guard.protect(transfer);
//! ```

use crate::audit::{AuditEvent, AuditFailureMode, AuditOutcome, AuditSink, record_decision};
use adk_core::{Result, Tool, ToolContext};
use async_trait::async_trait;
use serde_json::Value;
use std::collections::HashSet;
use std::sync::Arc;

macro_rules! impl_scoped_tool {
    ($wrapper:ident<$generic:ident>, $self_ident:ident => $inner:expr) => {
        #[async_trait]
        impl<$generic: Tool + Send + Sync> Tool for $wrapper<$generic> {
            fn name(&self) -> &str {
                let $self_ident = self;
                ($inner).name()
            }

            fn description(&self) -> &str {
                let $self_ident = self;
                ($inner).description()
            }

            fn enhanced_description(&self) -> String {
                let $self_ident = self;
                ($inner).enhanced_description()
            }

            fn is_long_running(&self) -> bool {
                let $self_ident = self;
                ($inner).is_long_running()
            }

            fn parameters_schema(&self) -> Option<Value> {
                let $self_ident = self;
                ($inner).parameters_schema()
            }

            fn response_schema(&self) -> Option<Value> {
                let $self_ident = self;
                ($inner).response_schema()
            }

            fn required_scopes(&self) -> &[&str] {
                let $self_ident = self;
                ($inner).required_scopes()
            }

            fn effect(&self) -> adk_core::ToolEffect {
                let $self_ident = self;
                ($inner).effect()
            }

            fn egress(&self, args: &Value) -> adk_core::egress::ToolEgress {
                let $self_ident = self;
                ($inner).egress(args)
            }

            fn approval_evidence(&self, args: &Value) -> Vec<adk_core::Evidence> {
                let $self_ident = self;
                ($inner).approval_evidence(args)
            }

            fn batch_group(&self) -> Option<adk_core::BatchGroup> {
                let $self_ident = self;
                ($inner).batch_group()
            }

            fn annotations(&self) -> Option<&Value> {
                let $self_ident = self;
                ($inner).annotations()
            }

            fn origin(&self) -> &str {
                let $self_ident = self;
                ($inner).origin()
            }

            fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
                let $self_ident = self;
                ($inner).timeout_override()
            }

            fn declaration(&self) -> Value {
                let $self_ident = self;
                ($inner).declaration()
            }

            fn is_builtin(&self) -> bool {
                let $self_ident = self;
                ($inner).is_builtin()
            }

            fn is_read_only(&self) -> bool {
                let $self_ident = self;
                ($inner).is_read_only()
            }

            fn is_concurrency_safe(&self) -> bool {
                let $self_ident = self;
                ($inner).is_concurrency_safe()
            }

            fn is_agent_delegation(&self) -> bool {
                let $self_ident = self;
                ($inner).is_agent_delegation()
            }

            async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
                let $self_ident = self;
                execute_scoped_tool(
                    ($inner),
                    self.resolver.as_ref(),
                    self.audit_sink.as_ref(),
                    self.audit_failure_mode,
                    ctx,
                    args,
                )
                .await
            }
        }
    };
    ($wrapper:ty, $self_ident:ident => $inner:expr) => {
        #[async_trait]
        impl Tool for $wrapper {
            fn name(&self) -> &str {
                let $self_ident = self;
                ($inner).name()
            }

            fn description(&self) -> &str {
                let $self_ident = self;
                ($inner).description()
            }

            fn enhanced_description(&self) -> String {
                let $self_ident = self;
                ($inner).enhanced_description()
            }

            fn is_long_running(&self) -> bool {
                let $self_ident = self;
                ($inner).is_long_running()
            }

            fn parameters_schema(&self) -> Option<Value> {
                let $self_ident = self;
                ($inner).parameters_schema()
            }

            fn response_schema(&self) -> Option<Value> {
                let $self_ident = self;
                ($inner).response_schema()
            }

            fn required_scopes(&self) -> &[&str] {
                let $self_ident = self;
                ($inner).required_scopes()
            }

            fn effect(&self) -> adk_core::ToolEffect {
                let $self_ident = self;
                ($inner).effect()
            }

            fn egress(&self, args: &Value) -> adk_core::egress::ToolEgress {
                let $self_ident = self;
                ($inner).egress(args)
            }

            fn approval_evidence(&self, args: &Value) -> Vec<adk_core::Evidence> {
                let $self_ident = self;
                ($inner).approval_evidence(args)
            }

            fn batch_group(&self) -> Option<adk_core::BatchGroup> {
                let $self_ident = self;
                ($inner).batch_group()
            }

            fn annotations(&self) -> Option<&Value> {
                let $self_ident = self;
                ($inner).annotations()
            }

            fn origin(&self) -> &str {
                let $self_ident = self;
                ($inner).origin()
            }

            fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
                let $self_ident = self;
                ($inner).timeout_override()
            }

            fn declaration(&self) -> Value {
                let $self_ident = self;
                ($inner).declaration()
            }

            fn is_builtin(&self) -> bool {
                let $self_ident = self;
                ($inner).is_builtin()
            }

            fn is_read_only(&self) -> bool {
                let $self_ident = self;
                ($inner).is_read_only()
            }

            fn is_concurrency_safe(&self) -> bool {
                let $self_ident = self;
                ($inner).is_concurrency_safe()
            }

            fn is_agent_delegation(&self) -> bool {
                let $self_ident = self;
                ($inner).is_agent_delegation()
            }

            async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
                let $self_ident = self;
                execute_scoped_tool(
                    ($inner),
                    self.resolver.as_ref(),
                    self.audit_sink.as_ref(),
                    self.audit_failure_mode,
                    ctx,
                    args,
                )
                .await
            }
        }
    };
}

/// Resolves the set of scopes granted to the current user.
///
/// Implementations can pull scopes from session state, JWT claims,
/// an external identity provider, or any other source.
#[async_trait]
pub trait ScopeResolver: Send + Sync {
    /// Returns the scopes granted to the user in the given tool context.
    async fn resolve(&self, ctx: &dyn ToolContext) -> Vec<String>;
}

/// Resolves user scopes from the `user_scopes()` method on [`ToolContext`].
///
/// This is the default resolver — it delegates directly to the context,
/// which may pull scopes from JWT claims, session state, or any other source
/// configured at the context level.
pub struct ContextScopeResolver;

#[async_trait]
impl ScopeResolver for ContextScopeResolver {
    async fn resolve(&self, ctx: &dyn ToolContext) -> Vec<String> {
        ctx.user_scopes()
    }
}

/// A static resolver that always returns a fixed set of scopes.
///
/// Useful for testing or when scopes are known at configuration time.
///
/// # Example
///
/// ```rust,ignore
/// let resolver = StaticScopeResolver::new(vec!["admin", "finance:write"]);
/// ```
pub struct StaticScopeResolver {
    scopes: Vec<String>,
}

impl StaticScopeResolver {
    /// Create a resolver with a fixed set of scopes.
    pub fn new(scopes: Vec<impl Into<String>>) -> Self {
        Self { scopes: scopes.into_iter().map(Into::into).collect() }
    }
}

#[async_trait]
impl ScopeResolver for StaticScopeResolver {
    async fn resolve(&self, _ctx: &dyn ToolContext) -> Vec<String> {
        self.scopes.clone()
    }
}

/// Checks whether a user's scopes satisfy a tool's requirements.
///
/// Returns `Ok(())` if the user has all required scopes, or an error
/// listing the missing scopes.
pub fn check_scopes(required: &[&str], granted: &[String]) -> std::result::Result<(), ScopeDenied> {
    if required.is_empty() {
        return Ok(());
    }

    let granted_set: HashSet<&str> = granted.iter().map(String::as_str).collect();
    let missing: Vec<String> =
        required.iter().filter(|s| !granted_set.contains(**s)).map(|s| s.to_string()).collect();

    if missing.is_empty() {
        Ok(())
    } else {
        Err(ScopeDenied { required: required.iter().map(|s| s.to_string()).collect(), missing })
    }
}

/// Error returned when a user lacks required scopes.
#[derive(Debug, Clone)]
pub struct ScopeDenied {
    /// All scopes the tool requires.
    pub required: Vec<String>,
    /// Scopes the user is missing.
    pub missing: Vec<String>,
}

impl std::fmt::Display for ScopeDenied {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "missing required scopes: [{}] (tool requires: [{}])",
            self.missing.join(", "),
            self.required.join(", ")
        )
    }
}

impl std::error::Error for ScopeDenied {}

/// A scope denial as the tool error a scope-guarded call fails with: component `Tool`,
/// category `Forbidden`, code [`TOOL_PERMISSION_DENIED_CODE`](adk_core::TOOL_PERMISSION_DENIED_CODE),
/// and the missing and required scopes in the details' `missingScopes` and `requiredScopes`.
/// The model is told the call was refused and which scopes were missing (spec 3.1 §7.14).
///
/// # Example
///
/// ```rust
/// use adk_auth::check_scopes;
/// use adk_core::{AdkError, ErrorCategory, TOOL_PERMISSION_DENIED_CODE};
///
/// let denied = check_scopes(&["finance:write"], &[]).unwrap_err();
/// let error = AdkError::from(denied);
/// assert_eq!((error.category, error.code), (ErrorCategory::Forbidden, TOOL_PERMISSION_DENIED_CODE));
/// assert_eq!(error.details.metadata["missingScopes"], serde_json::json!(["finance:write"]));
/// ```
impl From<ScopeDenied> for adk_core::AdkError {
    fn from(denied: ScopeDenied) -> Self {
        let mut details = adk_core::ErrorDetails::default();
        details.metadata.insert("missingScopes".to_string(), Value::from(denied.missing.clone()));
        details.metadata.insert("requiredScopes".to_string(), Value::from(denied.required.clone()));
        adk_core::AdkError::new(
            adk_core::ErrorComponent::Tool,
            adk_core::ErrorCategory::Forbidden,
            adk_core::TOOL_PERMISSION_DENIED_CODE,
            denied.to_string(),
        )
        .with_details(details)
    }
}

/// Declarative scope enforcement for tools.
///
/// Wraps tools and automatically checks that the user has all scopes
/// declared by [`Tool::required_scopes()`] before allowing execution.
///
/// # Example
///
/// ```rust,ignore
/// use adk_auth::{ScopeGuard, ContextScopeResolver};
///
/// let guard = ScopeGuard::new(ContextScopeResolver);
///
/// // Wrap a single tool
/// let protected = guard.protect(my_tool);
///
/// // Wrap all tools in a vec
/// let protected_tools = guard.protect_all(tools);
/// ```
pub struct ScopeGuard {
    resolver: Arc<dyn ScopeResolver>,
    audit_sink: Option<Arc<dyn AuditSink>>,
    audit_failure_mode: AuditFailureMode,
}

impl ScopeGuard {
    /// Create a scope guard with the given resolver.
    pub fn new(resolver: impl ScopeResolver + 'static) -> Self {
        Self {
            resolver: Arc::new(resolver),
            audit_sink: None,
            audit_failure_mode: AuditFailureMode::default(),
        }
    }

    /// Create a scope guard with audit logging.
    ///
    /// Guarded tools refuse a call whose decision the sink fails to record; use
    /// [`with_audit_failure_mode`](Self::with_audit_failure_mode) to change that.
    pub fn with_audit(
        resolver: impl ScopeResolver + 'static,
        audit_sink: impl AuditSink + 'static,
    ) -> Self {
        Self {
            resolver: Arc::new(resolver),
            audit_sink: Some(Arc::new(audit_sink)),
            audit_failure_mode: AuditFailureMode::default(),
        }
    }

    /// Sets what tools guarded from now on do when the audit sink fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_auth::{AuditFailureMode, ContextScopeResolver, InMemoryAuditSink, ScopeGuard};
    ///
    /// let guard = ScopeGuard::with_audit(ContextScopeResolver, InMemoryAuditSink::new())
    ///     .with_audit_failure_mode(AuditFailureMode::Warn);
    /// # let _ = guard;
    /// ```
    pub fn with_audit_failure_mode(mut self, mode: AuditFailureMode) -> Self {
        self.audit_failure_mode = mode;
        self
    }

    /// Wrap a tool with scope enforcement.
    ///
    /// If the tool declares no required scopes, the wrapper is a no-op passthrough.
    pub fn protect<T: Tool + 'static>(&self, tool: T) -> ScopedTool<T> {
        ScopedTool {
            inner: tool,
            resolver: self.resolver.clone(),
            audit_sink: self.audit_sink.clone(),
            audit_failure_mode: self.audit_failure_mode,
        }
    }

    /// Wrap all tools in a vec with scope enforcement.
    pub fn protect_all(&self, tools: Vec<Arc<dyn Tool>>) -> Vec<Arc<dyn Tool>> {
        tools
            .into_iter()
            .map(|t| {
                let wrapped = ScopedToolDyn {
                    inner: t,
                    resolver: self.resolver.clone(),
                    audit_sink: self.audit_sink.clone(),
                    audit_failure_mode: self.audit_failure_mode,
                };
                Arc::new(wrapped) as Arc<dyn Tool>
            })
            .collect()
    }
}

/// A tool wrapper that enforces scope requirements before execution.
///
/// With an audit sink, a call whose decision the sink fails to record is refused unless
/// the guard was built with [`AuditFailureMode::Warn`].
pub struct ScopedTool<T: Tool> {
    inner: T,
    resolver: Arc<dyn ScopeResolver>,
    audit_sink: Option<Arc<dyn AuditSink>>,
    audit_failure_mode: AuditFailureMode,
}

async fn authorize_tool_scopes(
    tool: &dyn Tool,
    resolver: &dyn ScopeResolver,
    audit_sink: Option<&Arc<dyn AuditSink>>,
    audit_failure_mode: AuditFailureMode,
    ctx: &Arc<dyn ToolContext>,
) -> Result<()> {
    let required = tool.required_scopes();
    if required.is_empty() {
        return Ok(());
    }

    let granted = resolver.resolve(ctx.as_ref()).await;
    let result = check_scopes(required, &granted);

    let recorded = match audit_sink {
        Some(sink) => {
            let outcome = if result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied };
            let event = AuditEvent::tool_access(ctx.user_id(), tool.name(), outcome)
                .with_session(ctx.session_id())
                .with_acting_context(&ctx.acting_context());
            record_decision(sink.as_ref(), event, audit_failure_mode, tool.name()).await
        }
        None => Ok(()),
    };

    if let Err(denied) = result {
        tracing::warn!(
            tool.name = %tool.name(),
            user.id = %ctx.user_id(),
            missing_scopes = ?denied.missing,
            "scope check failed"
        );
        return Err(denied.into());
    }

    recorded
}

async fn execute_scoped_tool(
    inner: &dyn Tool,
    resolver: &dyn ScopeResolver,
    audit_sink: Option<&Arc<dyn AuditSink>>,
    audit_failure_mode: AuditFailureMode,
    ctx: Arc<dyn ToolContext>,
    args: Value,
) -> Result<Value> {
    authorize_tool_scopes(inner, resolver, audit_sink, audit_failure_mode, &ctx).await?;
    inner.execute(ctx, args).await
}

impl_scoped_tool!(ScopedTool<T>, wrapper => &wrapper.inner);

/// Dynamic version of [`ScopedTool`] for `Arc<dyn Tool>`.
pub struct ScopedToolDyn {
    inner: Arc<dyn Tool>,
    resolver: Arc<dyn ScopeResolver>,
    audit_sink: Option<Arc<dyn AuditSink>>,
    audit_failure_mode: AuditFailureMode,
}

impl_scoped_tool!(ScopedToolDyn, wrapper => wrapper.inner.as_ref());

/// Extension trait for easily wrapping tools with scope enforcement.
pub trait ScopeToolExt: Tool + Sized {
    /// Wrap this tool with scope enforcement using the given resolver.
    fn with_scope_guard(self, resolver: impl ScopeResolver + 'static) -> ScopedTool<Self> {
        ScopedTool {
            inner: self,
            resolver: Arc::new(resolver),
            audit_sink: None,
            audit_failure_mode: AuditFailureMode::default(),
        }
    }
}

impl<T: Tool> ScopeToolExt for T {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_check_scopes_empty_required() {
        assert!(check_scopes(&[], &[]).is_ok());
        assert!(check_scopes(&[], &["admin".to_string()]).is_ok());
    }

    #[test]
    fn test_check_scopes_all_granted() {
        let granted = vec!["finance:read".to_string(), "finance:write".to_string()];
        assert!(check_scopes(&["finance:read", "finance:write"], &granted).is_ok());
    }

    #[test]
    fn test_check_scopes_subset_granted() {
        let granted =
            vec!["finance:read".to_string(), "finance:write".to_string(), "admin".to_string()];
        assert!(check_scopes(&["finance:write"], &granted).is_ok());
    }

    #[test]
    fn test_check_scopes_missing() {
        let granted = vec!["finance:read".to_string()];
        let err = check_scopes(&["finance:read", "finance:write"], &granted).unwrap_err();
        assert_eq!(err.missing, vec!["finance:write"]);
    }

    #[test]
    fn test_check_scopes_none_granted() {
        let err = check_scopes(&["admin"], &[]).unwrap_err();
        assert_eq!(err.missing, vec!["admin"]);
    }

    #[test]
    fn test_scope_denied_display() {
        let denied =
            ScopeDenied { required: vec!["a".into(), "b".into()], missing: vec!["b".into()] };
        let msg = denied.to_string();
        assert!(msg.contains("missing required scopes"));
        assert!(msg.contains("b"));
    }

    #[test]
    fn test_static_scope_resolver() {
        let resolver = StaticScopeResolver::new(vec!["admin", "finance:write"]);
        assert_eq!(resolver.scopes, vec!["admin", "finance:write"]);
    }
}