1use std::collections::{HashMap, HashSet};
11use std::path::{Path, PathBuf};
12use std::sync::{Arc, Mutex, OnceLock};
13
14use adk_auth::signed_audit::{AuditLog, Ed25519Signer, json_sha256};
15use adk_auth::{AccessControl, ContextScopeResolver, ProtectedToolDyn, ScopeGuard, ScopeResolver};
16use adk_core::audit_log::{AuditRecordDraft, AuditRecorder, InMemoryAuditLogStore};
17use adk_core::{
18 AdkError, CredentialBroker, ErrorCategory, ErrorComponent, ReadonlyContext, Result,
19 RevocationScope, Tool, ToolContext, ToolEffect, Url,
20};
21use adk_devtools::{CommandLauncher, DevToolError, Workspace};
22use async_trait::async_trait;
23use serde_json::Value;
24
25use crate::policy::ToolKind;
26
27pub const HARNESS_AUDIT_REQUIRED_CODE: &str = "harness.audit_required";
35
36fn intern(permission: &str) -> &'static str {
41 static NAMES: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
42 let mut names = NAMES.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
43 if let Some(name) = names.get(permission) {
44 return name;
45 }
46 let name: &'static str = Box::leak(permission.to_string().into_boxed_str());
47 names.insert(name);
48 name
49}
50
51#[derive(Clone, Default)]
74pub struct RbacMap {
75 required: HashMap<ToolKind, &'static str>,
76 resolver: Option<Arc<dyn ScopeResolver>>,
77 access_control: Option<Arc<AccessControl>>,
78}
79
80impl std::fmt::Debug for RbacMap {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 f.debug_struct("RbacMap")
83 .field("required", &self.required)
84 .field("resolver", &self.resolver.is_some())
85 .field("access_control", &self.access_control.is_some())
86 .finish()
87 }
88}
89
90impl RbacMap {
91 pub fn new() -> Self {
93 Self::default()
94 }
95
96 pub fn harness_defaults() -> Self {
100 use crate::policy::Isolation;
101 Self::new()
102 .require(ToolKind::Shell(Isolation::Host), "harness:shell")
103 .require(ToolKind::Shell(Isolation::OsSandbox), "harness:shell")
104 .require(ToolKind::Shell(Isolation::Container), "harness:shell")
105 .require(ToolKind::ShellEscalation, "harness:shell")
106 .require(ToolKind::Edit, "harness:edit")
107 .require(ToolKind::MemoryWrite, "harness:memory")
108 .require(ToolKind::Payment, "harness:pay")
109 .require(ToolKind::ComputerUse, "harness:desktop")
110 }
111
112 #[must_use]
114 pub fn require(mut self, class: ToolKind, permission: impl AsRef<str>) -> Self {
115 self.required.insert(class, intern(permission.as_ref()));
116 self
117 }
118
119 #[must_use]
122 pub fn with_scope_resolver(mut self, resolver: Arc<dyn ScopeResolver>) -> Self {
123 self.resolver = Some(resolver);
124 self
125 }
126
127 #[must_use]
130 pub fn with_access_control(mut self, access_control: Arc<AccessControl>) -> Self {
131 self.access_control = Some(access_control);
132 self
133 }
134
135 pub fn permission_for(&self, class: &ToolKind) -> Option<&'static str> {
137 self.required.get(class).copied()
138 }
139
140 pub(crate) fn protect(&self, tool: Arc<dyn Tool>, class: &ToolKind) -> Arc<dyn Tool> {
142 let Some(permission) = self.permission_for(class) else {
143 return tool;
144 };
145 let required: Arc<dyn Tool> =
146 Arc::new(PermissionTool { inner: tool, role: PermissionRole::Declare([permission]) });
147 let guard = match &self.resolver {
148 Some(resolver) => ScopeGuard::new(SharedResolver(resolver.clone())),
149 None => ScopeGuard::new(ContextScopeResolver),
150 };
151 let mut guarded =
152 guard.protect_all(vec![required]).pop().expect("one tool in, one tool out");
153 if let Some(access_control) = &self.access_control {
154 guarded = Arc::new(ProtectedToolDyn::new(guarded, access_control.clone()));
155 }
156 let code = intern(&format!("harness.rbac.denied:{permission}"));
157 Arc::new(PermissionTool { inner: guarded, role: PermissionRole::Explain { code } })
158 }
159}
160
161struct SharedResolver(Arc<dyn ScopeResolver>);
162
163#[async_trait]
164impl ScopeResolver for SharedResolver {
165 async fn resolve(&self, ctx: &dyn ToolContext) -> Vec<String> {
166 self.0.resolve(ctx).await
167 }
168}
169
170enum PermissionRole {
172 Declare([&'static str; 1]),
174 Explain { code: &'static str },
177}
178
179struct PermissionTool {
182 inner: Arc<dyn Tool>,
183 role: PermissionRole,
184}
185
186#[async_trait]
187impl Tool for PermissionTool {
188 fn name(&self) -> &str {
189 self.inner.name()
190 }
191 fn description(&self) -> &str {
192 self.inner.description()
193 }
194 fn declaration(&self) -> Value {
195 self.inner.declaration()
196 }
197 fn enhanced_description(&self) -> String {
198 self.inner.enhanced_description()
199 }
200 fn is_long_running(&self) -> bool {
201 self.inner.is_long_running()
202 }
203 fn is_builtin(&self) -> bool {
204 self.inner.is_builtin()
205 }
206 fn parameters_schema(&self) -> Option<Value> {
207 self.inner.parameters_schema()
208 }
209 fn response_schema(&self) -> Option<Value> {
210 self.inner.response_schema()
211 }
212 fn annotations(&self) -> Option<&Value> {
213 self.inner.annotations()
214 }
215 fn origin(&self) -> &str {
216 self.inner.origin()
217 }
218 fn required_scopes(&self) -> &[&str] {
219 match &self.role {
220 PermissionRole::Declare(scopes) => scopes,
221 PermissionRole::Explain { .. } => self.inner.required_scopes(),
222 }
223 }
224 fn is_read_only(&self) -> bool {
225 self.inner.is_read_only()
226 }
227 fn effect(&self) -> ToolEffect {
228 self.inner.effect()
229 }
230
231 fn egress(&self, args: &serde_json::Value) -> adk_core::egress::ToolEgress {
232 self.inner.egress(args)
233 }
234
235 fn approval_evidence(&self, args: &serde_json::Value) -> Vec<adk_core::Evidence> {
236 self.inner.approval_evidence(args)
237 }
238
239 fn batch_group(&self) -> Option<adk_core::BatchGroup> {
240 self.inner.batch_group()
241 }
242 fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
243 self.inner.timeout_override()
244 }
245 fn is_concurrency_safe(&self) -> bool {
246 self.inner.is_concurrency_safe()
247 }
248 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
249 let result = self.inner.execute(ctx, args).await;
250 match (&self.role, result) {
251 (PermissionRole::Explain { code }, Err(error))
252 if error.message.starts_with("missing required scopes")
253 || error.message.starts_with("Access denied: user") =>
254 {
255 Err(AdkError::new(
256 ErrorComponent::Tool,
257 ErrorCategory::Forbidden,
258 code,
259 error.message,
260 ))
261 }
262 (_, result) => result,
263 }
264 }
265}
266
267#[derive(Clone, Debug, PartialEq, Eq)]
281pub struct ShellCredential {
282 pub resource: Url,
284 pub scopes: Vec<String>,
286 pub username: String,
288}
289
290impl ShellCredential {
291 pub fn new(resource: &str) -> Result<Self> {
297 Ok(Self {
298 resource: adk_core::resource_indicator(resource)?,
299 scopes: Vec::new(),
300 username: "x-access-token".to_string(),
301 })
302 }
303
304 #[must_use]
306 pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
307 where
308 I: IntoIterator<Item = S>,
309 S: Into<String>,
310 {
311 self.scopes = scopes.into_iter().map(Into::into).collect();
312 self
313 }
314
315 #[must_use]
317 pub fn with_username(mut self, username: impl Into<String>) -> Self {
318 self.username = username.into();
319 self
320 }
321}
322
323pub(crate) fn git_https_remotes(root: &Path) -> Vec<ShellCredential> {
325 let Ok(config) = std::fs::read_to_string(root.join(".git").join("config")) else {
326 return Vec::new();
327 };
328 let mut seen = HashSet::new();
329 config
330 .lines()
331 .filter_map(|line| line.trim().strip_prefix("url"))
332 .filter_map(|rest| rest.trim_start().strip_prefix('='))
333 .filter_map(|url| Url::parse(url.trim()).ok())
334 .filter(|url| url.scheme() == "https" && url.username().is_empty())
335 .filter_map(|url| {
336 let origin = format!("https://{}/", url.host_str()?);
337 seen.insert(origin.clone()).then(|| ShellCredential::new(&origin).ok()).flatten()
338 })
339 .collect()
340}
341
342#[derive(Debug, Default)]
344pub(crate) struct CallEnvironment {
345 calls: Mutex<HashMap<String, Vec<(String, String)>>>,
346}
347
348impl CallEnvironment {
349 fn set(&self, call_id: &str, env: Vec<(String, String)>) {
350 self.calls.lock().unwrap_or_else(|e| e.into_inner()).insert(call_id.to_string(), env);
351 }
352
353 fn clear(&self, call_id: &str) {
354 self.calls.lock().unwrap_or_else(|e| e.into_inner()).remove(call_id);
355 }
356
357 fn get(&self, call_id: &str) -> Vec<(String, String)> {
358 self.calls
359 .lock()
360 .unwrap_or_else(|e| e.into_inner())
361 .get(call_id)
362 .cloned()
363 .unwrap_or_default()
364 }
365}
366
367pub(crate) struct CredentialLauncher {
370 inner: Arc<dyn CommandLauncher>,
371 calls: Arc<CallEnvironment>,
372}
373
374impl CredentialLauncher {
375 pub(crate) fn new(inner: Arc<dyn CommandLauncher>, calls: Arc<CallEnvironment>) -> Self {
376 Self { inner, calls }
377 }
378}
379
380impl CommandLauncher for CredentialLauncher {
381 fn command(
382 &self,
383 ws: &Workspace,
384 script: &str,
385 ctx: &dyn ToolContext,
386 ) -> std::result::Result<tokio::process::Command, DevToolError> {
387 let mut command = self.inner.command(ws, script, ctx)?;
388 for (key, value) in self.calls.get(ctx.function_call_id()) {
389 command.env(key, value);
390 }
391 Ok(command)
392 }
393
394 fn isolation(&self) -> &str {
395 self.inner.isolation()
396 }
397
398 fn guarded_command(
399 &self,
400 ws: &Workspace,
401 script: &str,
402 ctx: &dyn ToolContext,
403 ) -> std::result::Result<
404 (tokio::process::Command, Option<adk_devtools::LaunchGuard>),
405 DevToolError,
406 > {
407 let (mut command, guard) = self.inner.guarded_command(ws, script, ctx)?;
408 for (key, value) in self.calls.get(ctx.function_call_id()) {
409 command.env(key, value);
410 }
411 Ok((command, guard))
412 }
413
414 fn egress(&self) -> adk_core::egress::ToolEgress {
415 self.inner.egress()
416 }
417
418 #[cfg(windows)]
421 fn spawn_contained(
422 &self,
423 ws: &Workspace,
424 script: &str,
425 env: &[(String, String)],
426 ctx: &dyn ToolContext,
427 ) -> Option<std::result::Result<adk_devtools::ContainedChild, DevToolError>> {
428 let mut all = env.to_vec();
429 all.extend(self.calls.get(ctx.function_call_id()));
430 self.inner.spawn_contained(ws, script, &all, ctx)
431 }
432}
433
434fn quote(text: &str) -> String {
436 format!("'{}'", text.replace('\'', "'\\''"))
437}
438
439fn helper_script(tokens: &[(String, String, String)]) -> String {
441 let mut get = String::new();
442 let mut ask = String::new();
443 for (host, username, secret) in tokens {
444 get.push_str(&format!(
445 " {}) printf 'username=%s\\npassword=%s\\n' {} {} ;;\n",
446 quote(host),
447 quote(username),
448 quote(secret)
449 ));
450 let pattern = host.replace('*', "");
451 ask.push_str(&format!(
452 " Username*{pattern}*) printf '%s\\n' {} ;;\n Password*{pattern}*) printf '%s\\n' {} ;;\n",
453 quote(username),
454 quote(secret)
455 ));
456 }
457 format!(
458 "#!/bin/sh\n# Credential helper for one harness bash call; deleted when the call ends.\ncase \"$1\" in\n get)\n host=''\n while IFS='=' read -r key value; do\n [ -z \"$key\" ] && break\n [ \"$key\" = host ] && host=\"$value\"\n done\n case \"$host\" in\n{get} esac ;;\n store|erase) ;;\n *)\n case \"$1\" in\n{ask} esac ;;\nesac\n"
459 )
460}
461
462pub(crate) struct CredentialedTool {
470 inner: Arc<dyn Tool>,
471 broker: Arc<dyn CredentialBroker>,
472 credentials: Vec<ShellCredential>,
473 calls: Arc<CallEnvironment>,
474 helper_dir: PathBuf,
475}
476
477impl CredentialedTool {
478 pub(crate) fn new(
479 inner: Arc<dyn Tool>,
480 broker: Arc<dyn CredentialBroker>,
481 credentials: Vec<ShellCredential>,
482 calls: Arc<CallEnvironment>,
483 ) -> Self {
484 Self { inner, broker, credentials, calls, helper_dir: std::env::temp_dir() }
485 }
486
487 async fn mint(&self, ctx: &dyn ToolContext) -> Vec<(ShellCredential, String)> {
488 let acting = ctx.acting_context();
489 let mut tokens = Vec::new();
490 for credential in &self.credentials {
491 match self.broker.token_for(&acting, &credential.resource, &credential.scopes).await {
492 Ok(token) => match token.authorize_for(&credential.resource) {
493 Ok(secret) => tokens.push((credential.clone(), secret.expose().to_string())),
494 Err(error) => {
495 tracing::warn!(error = %error, credential.resource = %credential.resource, "the broker's token does not cover the resource")
496 }
497 },
498 Err(error) => tracing::warn!(
499 error = %error,
500 credential.resource = %credential.resource,
501 "no token for the shell; the command runs without one"
502 ),
503 }
504 }
505 tokens
506 }
507
508 async fn revoke(&self, ctx: &dyn ToolContext, minted: &[(ShellCredential, String)]) {
509 let agent = ctx.acting_context().agent.id;
510 for (credential, _) in minted {
511 let scope = RevocationScope::AgentResource {
512 agent: agent.clone(),
513 resource: credential.resource.clone(),
514 };
515 if let Err(error) = self.broker.revoke(&scope).await {
516 tracing::warn!(error = %error, credential.resource = %credential.resource, "could not revoke the shell's token");
517 }
518 }
519 }
520
521 fn write_helper(&self, dir: &Path, minted: &[(ShellCredential, String)]) -> Result<PathBuf> {
522 let io = |error: std::io::Error| {
523 AdkError::new(
524 ErrorComponent::Tool,
525 ErrorCategory::Unavailable,
526 "harness.credentials.io",
527 format!("write the credential helper: {error}"),
528 )
529 };
530 std::fs::create_dir(dir).map_err(io)?;
531 let path = dir.join("credential-helper");
532 let tokens: Vec<(String, String, String)> = minted
533 .iter()
534 .filter_map(|(credential, secret)| {
535 let host = match credential.resource.port() {
536 Some(port) => format!("{}:{port}", credential.resource.host_str()?),
537 None => credential.resource.host_str()?.to_string(),
538 };
539 Some((host, credential.username.clone(), secret.clone()))
540 })
541 .collect();
542 #[cfg(unix)]
543 {
544 use std::io::Write as _;
545 use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
546 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err(io)?;
547 let mut file = std::fs::OpenOptions::new()
548 .write(true)
549 .create_new(true)
550 .mode(0o700)
551 .open(&path)
552 .map_err(io)?;
553 file.write_all(helper_script(&tokens).as_bytes()).map_err(io)?;
554 }
555 #[cfg(windows)]
558 {
559 use std::io::Write as _;
560 let mut file = crate::fsutil::owner_only::create_new(&path).map_err(io)?;
561 file.write_all(helper_script(&tokens).as_bytes()).map_err(io)?;
562 }
563 #[cfg(not(any(unix, windows)))]
564 std::fs::write(&path, helper_script(&tokens)).map_err(io)?;
565 Ok(path)
566 }
567}
568
569#[async_trait]
570impl Tool for CredentialedTool {
571 fn name(&self) -> &str {
572 self.inner.name()
573 }
574 fn description(&self) -> &str {
575 self.inner.description()
576 }
577 fn declaration(&self) -> Value {
578 self.inner.declaration()
579 }
580 fn enhanced_description(&self) -> String {
581 self.inner.enhanced_description()
582 }
583 fn is_long_running(&self) -> bool {
584 self.inner.is_long_running()
585 }
586 fn is_builtin(&self) -> bool {
587 self.inner.is_builtin()
588 }
589 fn parameters_schema(&self) -> Option<Value> {
590 self.inner.parameters_schema()
591 }
592 fn response_schema(&self) -> Option<Value> {
593 self.inner.response_schema()
594 }
595 fn annotations(&self) -> Option<&Value> {
596 self.inner.annotations()
597 }
598 fn origin(&self) -> &str {
599 self.inner.origin()
600 }
601 fn required_scopes(&self) -> &[&str] {
602 self.inner.required_scopes()
603 }
604 fn is_read_only(&self) -> bool {
605 self.inner.is_read_only()
606 }
607 fn effect(&self) -> ToolEffect {
608 self.inner.effect()
609 }
610
611 fn egress(&self, args: &serde_json::Value) -> adk_core::egress::ToolEgress {
612 self.inner.egress(args)
613 }
614
615 fn approval_evidence(&self, args: &serde_json::Value) -> Vec<adk_core::Evidence> {
616 self.inner.approval_evidence(args)
617 }
618
619 fn batch_group(&self) -> Option<adk_core::BatchGroup> {
620 self.inner.batch_group()
621 }
622 fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
623 self.inner.timeout_override()
624 }
625 fn is_concurrency_safe(&self) -> bool {
626 self.inner.is_concurrency_safe()
627 }
628
629 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
630 let minted = self.mint(ctx.as_ref()).await;
631 if minted.is_empty() {
632 return self.inner.execute(ctx, args).await;
633 }
634 let call_id = ctx.function_call_id().to_string();
635 let dir = self
636 .helper_dir
637 .join(format!("adk-harness-credentials-{}", uuid::Uuid::new_v4().simple()));
638 let result = match self.write_helper(&dir, &minted) {
639 Ok(helper) => {
640 let helper = helper.to_string_lossy().into_owned();
641 self.calls.set(
642 &call_id,
643 vec![
644 ("GIT_ASKPASS".to_string(), helper.clone()),
645 ("GIT_TERMINAL_PROMPT".to_string(), "0".to_string()),
646 ("GIT_CONFIG_COUNT".to_string(), "2".to_string()),
647 ("GIT_CONFIG_KEY_0".to_string(), "credential.helper".to_string()),
648 ("GIT_CONFIG_VALUE_0".to_string(), String::new()),
649 ("GIT_CONFIG_KEY_1".to_string(), "credential.helper".to_string()),
650 ("GIT_CONFIG_VALUE_1".to_string(), format!("!{}", quote(&helper))),
651 ("ADK_CREDENTIAL_HELPER".to_string(), helper),
652 ],
653 );
654 let result = self.inner.execute(ctx.clone(), args).await;
655 self.calls.clear(&call_id);
656 result
657 }
658 Err(error) => Err(error),
659 };
660 if let Err(error) = std::fs::remove_dir_all(&dir)
661 && error.kind() != std::io::ErrorKind::NotFound
662 {
663 tracing::warn!(error = %error, "could not delete the credential helper");
664 }
665 self.revoke(ctx.as_ref(), &minted).await;
666 result
667 }
668}
669
670#[derive(Debug, Default)]
675pub(crate) struct IdentityGate {
676 require_authenticated: bool,
677 seen: Mutex<HashMap<String, bool>>,
678}
679
680impl IdentityGate {
681 pub(crate) fn new(require_authenticated: bool) -> Self {
682 Self { require_authenticated, seen: Mutex::new(HashMap::new()) }
683 }
684
685 pub(crate) fn observe(&self, ctx: &dyn ReadonlyContext) {
687 if !self.require_authenticated {
688 return;
689 }
690 let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
691 if seen.len() > 8192 {
692 seen.clear();
693 }
694 seen.insert(ctx.invocation_id().to_string(), ctx.is_authenticated());
695 }
696
697 #[cfg(feature = "acp-server")]
700 pub(crate) fn requires_authentication(&self) -> bool {
701 self.require_authenticated
702 }
703
704 pub(crate) fn inert(&self, invocation_id: &str) -> bool {
707 self.require_authenticated
708 && !self
709 .seen
710 .lock()
711 .unwrap_or_else(|e| e.into_inner())
712 .get(invocation_id)
713 .copied()
714 .unwrap_or(false)
715 }
716}
717
718#[async_trait]
719impl crate::toolset::RequestObserver for IdentityGate {
720 async fn before_request(
721 &self,
722 ctx: &Arc<dyn ReadonlyContext>,
723 _request: &mut adk_core::LlmRequest,
724 ) -> Result<()> {
725 self.observe(ctx.as_ref());
726 Ok(())
727 }
728}
729
730pub struct EphemeralAuditLog {
752 store: Arc<InMemoryAuditLogStore>,
753 signer: Arc<Ed25519Signer>,
754 log: tokio::sync::OnceCell<AuditLog>,
755}
756
757impl std::fmt::Debug for EphemeralAuditLog {
758 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
759 f.debug_struct("EphemeralAuditLog").finish_non_exhaustive()
760 }
761}
762
763const EPHEMERAL_LOG_ID: &str = "adk-harness";
765
766impl EphemeralAuditLog {
767 pub fn new() -> Result<Self> {
773 let signer = Ed25519Signer::generate("adk-harness.local").map_err(|error| {
774 AdkError::config(format!("generate the harness audit signing key: {error}"))
775 })?;
776 Ok(Self {
777 store: Arc::new(InMemoryAuditLogStore::new()),
778 signer: Arc::new(signer),
779 log: tokio::sync::OnceCell::new(),
780 })
781 }
782
783 async fn log(&self) -> Result<&AuditLog> {
784 self.log
785 .get_or_try_init(|| async {
786 AuditLog::builder(self.store.clone(), EPHEMERAL_LOG_ID, self.signer.clone())
787 .open()
788 .await
789 })
790 .await
791 }
792
793 pub fn store(&self) -> &Arc<InMemoryAuditLogStore> {
795 &self.store
796 }
797
798 pub fn verifier_key(&self) -> String {
800 use adk_auth::signed_audit::AuditSigner as _;
801 self.signer.verifier_key()
802 }
803
804 pub async fn records(&self) -> Result<Vec<adk_core::audit_log::AuditRecord>> {
825 use adk_core::audit_log::AuditLogStore as _;
826 let size = self.store.size(EPHEMERAL_LOG_ID).await?;
827 self.store
828 .read(EPHEMERAL_LOG_ID, 0..size)
829 .await?
830 .into_iter()
831 .filter_map(|entry| entry.record)
832 .map(|text| {
833 serde_json::from_str(&text).map_err(|error| {
834 AdkError::config(format!("an audit record does not parse: {error}"))
835 })
836 })
837 .collect()
838 }
839
840 pub async fn verify(&self) -> Result<bool> {
847 let log = self.log().await?;
848 log.checkpoint().await?;
849 let export =
850 adk_auth::signed_audit::AuditExport::from_store(self.store.as_ref(), log.log_id())
851 .await?;
852 let trusted = self
853 .verifier_key()
854 .parse::<adk_auth::signed_audit::NoteVerifier>()
855 .map_err(|error| AdkError::config(format!("the log's verifier key: {error}")))?;
856 Ok(export.verify(&[trusted]).is_valid())
857 }
858}
859
860#[async_trait]
861impl AuditRecorder for EphemeralAuditLog {
862 fn digest(&self, value: &Value) -> String {
863 json_sha256(value).unwrap_or_else(|_| {
864 format!(
865 "sha256-json:{}",
866 crate::fsutil::hex_digest(
867 serde_json::to_string(value).unwrap_or_default().as_bytes()
868 )
869 )
870 })
871 }
872
873 async fn record(&self, draft: AuditRecordDraft) -> Result<()> {
874 self.log().await?.append(draft).await.map(drop)
875 }
876
877 async fn seal(&self) -> Result<()> {
880 match self.log.get() {
881 Some(log) => log.seal().await,
882 None => Ok(()),
883 }
884 }
885}
886
887pub(crate) fn audit_required(agent: &str) -> AdkError {
889 AdkError::new(
890 ErrorComponent::Agent,
891 ErrorCategory::Forbidden,
892 HARNESS_AUDIT_REQUIRED_CODE,
893 format!(
894 "harness '{agent}' runs only with an audit trail in Block mode (RunConfig::audit): \
895 set one with Runner::builder().audit_log(..) and the default \
896 AuditFailureMode::Block, or HarnessAgentBuilder::audit_log(..)"
897 ),
898 )
899}
900
901pub(crate) fn resolve_credentials(
904 configured: Vec<ShellCredential>,
905 root: &Path,
906) -> Vec<ShellCredential> {
907 if !configured.is_empty() {
908 return configured;
909 }
910 let remotes = git_https_remotes(root);
911 if remotes.is_empty() {
912 tracing::warn!(
913 "a credential broker is set but no shell credential is configured and the workspace \
914 has no HTTPS git remote; bash runs without tokens"
915 );
916 }
917 remotes
918}
919
920#[cfg(test)]
921mod tests {
922 use super::*;
923 use adk_core::ToolOrigin;
924 use serde_json::json;
925
926 #[derive(Debug)]
928 struct Declared;
929
930 #[async_trait]
931 impl Tool for Declared {
932 fn name(&self) -> &str {
933 "read"
934 }
935
936 fn description(&self) -> &str {
937 "reads"
938 }
939
940 fn declaration(&self) -> Value {
941 json!({
942 "name": "read",
943 "description": "reads",
944 "parameters": { "type": "object", "properties": { "path": { "type": "string" } } },
945 "x-server": "fs"
946 })
947 }
948
949 fn annotations(&self) -> Option<&Value> {
950 static HINTS: OnceLock<Value> = OnceLock::new();
951 Some(HINTS.get_or_init(|| json!({ "readOnlyHint": true })))
952 }
953
954 fn origin(&self) -> &str {
955 "mcp:fs"
956 }
957
958 fn effect(&self) -> ToolEffect {
959 ToolEffect::ReadOnly
960 }
961
962 async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
963 Ok(Value::Null)
964 }
965 }
966
967 #[derive(Debug)]
969 struct NoBroker;
970
971 #[async_trait]
972 impl CredentialBroker for NoBroker {
973 async fn token_for(
974 &self,
975 _acting: &adk_core::ActingContext,
976 resource: &Url,
977 _scopes: &[String],
978 ) -> Result<adk_core::ScopedToken> {
979 Err(AdkError::new(
980 ErrorComponent::Auth,
981 ErrorCategory::Unavailable,
982 "test.broker.none",
983 format!("no credential for {resource}"),
984 ))
985 }
986
987 async fn revoke(&self, _scope: &RevocationScope) -> Result<u64> {
988 Ok(0)
989 }
990 }
991
992 #[test]
993 fn the_wrappers_keep_the_wrapped_tools_origin_and_declaration_digest() {
994 let inner: Arc<dyn Tool> = Arc::new(Declared);
995 let expected = ToolOrigin::of(inner.as_ref());
996 assert_eq!(expected.source, "mcp:fs");
997
998 let permission = PermissionTool {
999 inner: inner.clone(),
1000 role: PermissionRole::Explain { code: "harness.rbac.denied:harness:shell" },
1001 };
1002 assert_eq!(ToolOrigin::of(&permission), expected, "PermissionTool");
1003 assert_eq!(permission.annotations(), inner.annotations());
1004
1005 let credentialed = CredentialedTool::new(
1006 inner.clone(),
1007 Arc::new(NoBroker),
1008 Vec::new(),
1009 Arc::new(CallEnvironment::default()),
1010 );
1011 assert_eq!(ToolOrigin::of(&credentialed), expected, "CredentialedTool");
1012 assert_eq!(credentialed.effect(), ToolEffect::ReadOnly);
1013 }
1014
1015 #[test]
1016 fn https_remotes_become_credentials_once_per_host() {
1017 let dir = tempfile::tempdir().unwrap();
1018 std::fs::create_dir(dir.path().join(".git")).unwrap();
1019 std::fs::write(
1020 dir.path().join(".git/config"),
1021 "[remote \"origin\"]\n\turl = https://github.com/acme/app.git\n[remote \"fork\"]\n\turl = https://github.com/me/app.git\n[remote \"ssh\"]\n\turl = git@gitlab.com:acme/app.git\n[remote \"x\"]\n\turl = https://user@example.com/x.git\n",
1022 )
1023 .unwrap();
1024 let credentials = git_https_remotes(dir.path());
1025 assert_eq!(credentials, vec![ShellCredential::new("https://github.com/").unwrap()]);
1026 }
1027
1028 #[test]
1029 fn the_helper_quotes_secrets() {
1030 let script = helper_script(&[("github.com".into(), "x-access-token".into(), "a'b".into())]);
1031 assert!(script.contains("'a'\\''b'"), "{script}");
1032 assert!(script.starts_with("#!/bin/sh\n"));
1033 }
1034
1035 #[test]
1036 fn the_gate_is_inert_only_when_identity_is_required() {
1037 let open = IdentityGate::new(false);
1038 assert!(!open.inert("inv"));
1039 let served = IdentityGate::new(true);
1040 assert!(served.inert("never-seen"));
1041 }
1042
1043 #[tokio::test]
1045 async fn sealing_the_ephemeral_log_signs_its_unsigned_records() {
1046 use adk_core::audit_log::{AuditLogStore as _, AuditRecordKind};
1047
1048 let log = EphemeralAuditLog::new().unwrap();
1049 let sizes = || async {
1050 let checkpoints = log.store().checkpoints(EPHEMERAL_LOG_ID).await.unwrap();
1051 checkpoints.into_iter().map(|checkpoint| checkpoint.size).collect::<Vec<_>>()
1052 };
1053 log.seal().await.unwrap();
1054 assert_eq!(sizes().await, Vec::<u64>::new(), "an empty log has nothing to sign");
1055 for action in ["search", "read"] {
1056 log.record(AuditRecordDraft::new(AuditRecordKind::ToolCall, action)).await.unwrap();
1057 }
1058 assert_eq!(sizes().await, Vec::<u64>::new(), "no checkpoint is due yet");
1059 log.seal().await.unwrap();
1060 log.seal().await.unwrap();
1061 assert_eq!(sizes().await, vec![2]);
1062 }
1063}