1use crate::audit::{AuditEvent, AuditFailureMode, AuditOutcome, AuditSink, record_decision};
7use crate::{AccessControl, Permission};
8use adk_core::{Result, Tool, ToolContext};
9use async_trait::async_trait;
10use serde_json::Value;
11use std::sync::Arc;
12
13macro_rules! impl_protected_tool {
14 ($wrapper:ident<$generic:ident>, $self_ident:ident => $inner:expr) => {
15 #[async_trait]
16 impl<$generic: Tool + Send + Sync> Tool for $wrapper<$generic> {
17 fn name(&self) -> &str {
18 let $self_ident = self;
19 ($inner).name()
20 }
21
22 fn description(&self) -> &str {
23 let $self_ident = self;
24 ($inner).description()
25 }
26
27 fn enhanced_description(&self) -> String {
28 let $self_ident = self;
29 ($inner).enhanced_description()
30 }
31
32 fn is_long_running(&self) -> bool {
33 let $self_ident = self;
34 ($inner).is_long_running()
35 }
36
37 fn parameters_schema(&self) -> Option<Value> {
38 let $self_ident = self;
39 ($inner).parameters_schema()
40 }
41
42 fn response_schema(&self) -> Option<Value> {
43 let $self_ident = self;
44 ($inner).response_schema()
45 }
46
47 fn required_scopes(&self) -> &[&str] {
48 let $self_ident = self;
49 ($inner).required_scopes()
50 }
51
52 fn effect(&self) -> adk_core::ToolEffect {
53 let $self_ident = self;
54 ($inner).effect()
55 }
56
57 fn egress(&self, args: &Value) -> adk_core::egress::ToolEgress {
58 let $self_ident = self;
59 ($inner).egress(args)
60 }
61
62 fn approval_evidence(&self, args: &Value) -> Vec<adk_core::Evidence> {
63 let $self_ident = self;
64 ($inner).approval_evidence(args)
65 }
66
67 fn batch_group(&self) -> Option<adk_core::BatchGroup> {
68 let $self_ident = self;
69 ($inner).batch_group()
70 }
71
72 fn annotations(&self) -> Option<&Value> {
73 let $self_ident = self;
74 ($inner).annotations()
75 }
76
77 fn origin(&self) -> &str {
78 let $self_ident = self;
79 ($inner).origin()
80 }
81
82 fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
83 let $self_ident = self;
84 ($inner).timeout_override()
85 }
86
87 fn declaration(&self) -> Value {
88 let $self_ident = self;
89 ($inner).declaration()
90 }
91
92 fn is_builtin(&self) -> bool {
93 let $self_ident = self;
94 ($inner).is_builtin()
95 }
96
97 fn is_read_only(&self) -> bool {
98 let $self_ident = self;
99 ($inner).is_read_only()
100 }
101
102 fn is_concurrency_safe(&self) -> bool {
103 let $self_ident = self;
104 ($inner).is_concurrency_safe()
105 }
106
107 fn is_agent_delegation(&self) -> bool {
108 let $self_ident = self;
109 ($inner).is_agent_delegation()
110 }
111
112 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
113 let $self_ident = self;
114 execute_protected_tool(
115 ($inner),
116 self.access_control.as_ref(),
117 self.audit_sink.as_ref(),
118 self.audit_failure_mode,
119 ctx,
120 args,
121 )
122 .await
123 }
124 }
125 };
126 ($wrapper:ty, $self_ident:ident => $inner:expr) => {
127 #[async_trait]
128 impl Tool for $wrapper {
129 fn name(&self) -> &str {
130 let $self_ident = self;
131 ($inner).name()
132 }
133
134 fn description(&self) -> &str {
135 let $self_ident = self;
136 ($inner).description()
137 }
138
139 fn enhanced_description(&self) -> String {
140 let $self_ident = self;
141 ($inner).enhanced_description()
142 }
143
144 fn is_long_running(&self) -> bool {
145 let $self_ident = self;
146 ($inner).is_long_running()
147 }
148
149 fn parameters_schema(&self) -> Option<Value> {
150 let $self_ident = self;
151 ($inner).parameters_schema()
152 }
153
154 fn response_schema(&self) -> Option<Value> {
155 let $self_ident = self;
156 ($inner).response_schema()
157 }
158
159 fn required_scopes(&self) -> &[&str] {
160 let $self_ident = self;
161 ($inner).required_scopes()
162 }
163
164 fn effect(&self) -> adk_core::ToolEffect {
165 let $self_ident = self;
166 ($inner).effect()
167 }
168
169 fn egress(&self, args: &Value) -> adk_core::egress::ToolEgress {
170 let $self_ident = self;
171 ($inner).egress(args)
172 }
173
174 fn approval_evidence(&self, args: &Value) -> Vec<adk_core::Evidence> {
175 let $self_ident = self;
176 ($inner).approval_evidence(args)
177 }
178
179 fn batch_group(&self) -> Option<adk_core::BatchGroup> {
180 let $self_ident = self;
181 ($inner).batch_group()
182 }
183
184 fn annotations(&self) -> Option<&Value> {
185 let $self_ident = self;
186 ($inner).annotations()
187 }
188
189 fn origin(&self) -> &str {
190 let $self_ident = self;
191 ($inner).origin()
192 }
193
194 fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
195 let $self_ident = self;
196 ($inner).timeout_override()
197 }
198
199 fn declaration(&self) -> Value {
200 let $self_ident = self;
201 ($inner).declaration()
202 }
203
204 fn is_builtin(&self) -> bool {
205 let $self_ident = self;
206 ($inner).is_builtin()
207 }
208
209 fn is_read_only(&self) -> bool {
210 let $self_ident = self;
211 ($inner).is_read_only()
212 }
213
214 fn is_concurrency_safe(&self) -> bool {
215 let $self_ident = self;
216 ($inner).is_concurrency_safe()
217 }
218
219 fn is_agent_delegation(&self) -> bool {
220 let $self_ident = self;
221 ($inner).is_agent_delegation()
222 }
223
224 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
225 let $self_ident = self;
226 execute_protected_tool(
227 ($inner),
228 self.access_control.as_ref(),
229 self.audit_sink.as_ref(),
230 self.audit_failure_mode,
231 ctx,
232 args,
233 )
234 .await
235 }
236 }
237 };
238}
239
240pub struct ProtectedTool<T: Tool> {
260 inner: T,
261 access_control: Arc<AccessControl>,
262 audit_sink: Option<Arc<dyn AuditSink>>,
263 audit_failure_mode: AuditFailureMode,
264}
265
266async fn authorize_tool_access(
267 tool_name: &str,
268 access_control: &AccessControl,
269 audit_sink: Option<&Arc<dyn AuditSink>>,
270 audit_failure_mode: AuditFailureMode,
271 ctx: &Arc<dyn ToolContext>,
272) -> Result<()> {
273 let permission = Permission::Tool(tool_name.to_string());
274 let check_result = access_control.check(ctx.user_id(), &permission);
275
276 let recorded = match audit_sink {
277 Some(sink) => {
278 let outcome =
279 if check_result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied };
280 let event = AuditEvent::tool_access(ctx.user_id(), tool_name, outcome)
281 .with_session(ctx.session_id())
282 .with_acting_context(&ctx.acting_context());
283 record_decision(sink.as_ref(), event, audit_failure_mode, tool_name).await
284 }
285 None => Ok(()),
286 };
287
288 check_result.map_err(|err| {
289 let mut details = adk_core::ErrorDetails::default();
291 details.metadata.insert("permission".to_string(), Value::String(err.permission.clone()));
292 adk_core::AdkError::new(
293 adk_core::ErrorComponent::Tool,
294 adk_core::ErrorCategory::Forbidden,
295 adk_core::TOOL_PERMISSION_DENIED_CODE,
296 err.to_string(),
297 )
298 .with_details(details)
299 })?;
300 recorded
301}
302
303async fn execute_protected_tool(
304 inner: &dyn Tool,
305 access_control: &AccessControl,
306 audit_sink: Option<&Arc<dyn AuditSink>>,
307 audit_failure_mode: AuditFailureMode,
308 ctx: Arc<dyn ToolContext>,
309 args: Value,
310) -> Result<Value> {
311 authorize_tool_access(inner.name(), access_control, audit_sink, audit_failure_mode, &ctx)
312 .await?;
313 inner.execute(ctx, args).await
314}
315
316impl<T: Tool> ProtectedTool<T> {
317 pub fn new(tool: T, access_control: Arc<AccessControl>) -> Self {
319 Self {
320 inner: tool,
321 access_control,
322 audit_sink: None,
323 audit_failure_mode: AuditFailureMode::default(),
324 }
325 }
326
327 pub fn with_audit(
332 tool: T,
333 access_control: Arc<AccessControl>,
334 audit_sink: Arc<dyn AuditSink>,
335 ) -> Self {
336 Self {
337 inner: tool,
338 access_control,
339 audit_sink: Some(audit_sink),
340 audit_failure_mode: AuditFailureMode::default(),
341 }
342 }
343
344 pub fn with_audit_failure_mode(mut self, mode: AuditFailureMode) -> Self {
355 self.audit_failure_mode = mode;
356 self
357 }
358}
359
360impl_protected_tool!(ProtectedTool<T>, wrapper => &wrapper.inner);
361
362pub trait ToolExt: Tool + Sized {
364 fn with_access_control(self, ac: Arc<AccessControl>) -> ProtectedTool<Self> {
366 ProtectedTool::new(self, ac)
367 }
368
369 fn with_access_control_and_audit(
371 self,
372 ac: Arc<AccessControl>,
373 audit: Arc<dyn AuditSink>,
374 ) -> ProtectedTool<Self> {
375 ProtectedTool::with_audit(self, ac, audit)
376 }
377}
378
379impl<T: Tool> ToolExt for T {}
380
381pub struct AuthMiddleware {
383 access_control: Arc<AccessControl>,
384 audit_sink: Option<Arc<dyn AuditSink>>,
385 audit_failure_mode: AuditFailureMode,
386}
387
388impl AuthMiddleware {
389 pub fn new(access_control: AccessControl) -> Self {
391 Self {
392 access_control: Arc::new(access_control),
393 audit_sink: None,
394 audit_failure_mode: AuditFailureMode::default(),
395 }
396 }
397
398 pub fn with_audit(access_control: AccessControl, audit_sink: impl AuditSink + 'static) -> Self {
403 Self {
404 access_control: Arc::new(access_control),
405 audit_sink: Some(Arc::new(audit_sink)),
406 audit_failure_mode: AuditFailureMode::default(),
407 }
408 }
409
410 pub fn with_audit_failure_mode(mut self, mode: AuditFailureMode) -> Self {
412 self.audit_failure_mode = mode;
413 self
414 }
415
416 pub fn access_control(&self) -> &AccessControl {
418 &self.access_control
419 }
420
421 pub fn protect<T: Tool>(&self, tool: T) -> ProtectedTool<T> {
423 match &self.audit_sink {
424 Some(sink) => {
425 ProtectedTool::with_audit(tool, self.access_control.clone(), sink.clone())
426 }
427 None => ProtectedTool::new(tool, self.access_control.clone()),
428 }
429 .with_audit_failure_mode(self.audit_failure_mode)
430 }
431
432 pub fn protect_all(&self, tools: Vec<Arc<dyn Tool>>) -> Vec<Arc<dyn Tool>> {
434 tools
435 .into_iter()
436 .map(|t| {
437 let protected = match &self.audit_sink {
438 Some(sink) => {
439 ProtectedToolDyn::with_audit(t, self.access_control.clone(), sink.clone())
440 }
441 None => ProtectedToolDyn::new(t, self.access_control.clone()),
442 }
443 .with_audit_failure_mode(self.audit_failure_mode);
444 Arc::new(protected) as Arc<dyn Tool>
445 })
446 .collect()
447 }
448}
449
450pub struct ProtectedToolDyn {
452 inner: Arc<dyn Tool>,
453 access_control: Arc<AccessControl>,
454 audit_sink: Option<Arc<dyn AuditSink>>,
455 audit_failure_mode: AuditFailureMode,
456}
457
458impl ProtectedToolDyn {
459 pub fn new(tool: Arc<dyn Tool>, access_control: Arc<AccessControl>) -> Self {
461 Self {
462 inner: tool,
463 access_control,
464 audit_sink: None,
465 audit_failure_mode: AuditFailureMode::default(),
466 }
467 }
468
469 pub fn with_audit(
474 tool: Arc<dyn Tool>,
475 access_control: Arc<AccessControl>,
476 audit_sink: Arc<dyn AuditSink>,
477 ) -> Self {
478 Self {
479 inner: tool,
480 access_control,
481 audit_sink: Some(audit_sink),
482 audit_failure_mode: AuditFailureMode::default(),
483 }
484 }
485
486 pub fn with_audit_failure_mode(mut self, mode: AuditFailureMode) -> Self {
488 self.audit_failure_mode = mode;
489 self
490 }
491}
492
493impl_protected_tool!(ProtectedToolDyn, wrapper => wrapper.inner.as_ref());
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498 use crate::Role;
499
500 struct MockTool {
502 name: String,
503 }
504
505 impl MockTool {
506 fn new(name: &str) -> Self {
507 Self { name: name.to_string() }
508 }
509 }
510
511 #[async_trait]
512 impl Tool for MockTool {
513 fn name(&self) -> &str {
514 &self.name
515 }
516
517 fn description(&self) -> &str {
518 "Mock tool"
519 }
520
521 async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
522 Ok(serde_json::json!({"result": "success"}))
523 }
524 }
525
526 #[test]
527 fn test_tool_ext() {
528 let ac = AccessControl::builder()
529 .role(Role::new("user").allow(Permission::Tool("mock".into())))
530 .build()
531 .unwrap();
532
533 let tool = MockTool::new("mock");
534 let protected = tool.with_access_control(Arc::new(ac));
535
536 assert_eq!(protected.name(), "mock");
537 assert_eq!(protected.description(), "Mock tool");
538 }
539}