Skip to main content

adk_harness/
identity.rs

1//! Identity and credentials (spec 3.1 §7.14, §9.2 I5–I7, I39; feature `auth`).
2//!
3//! | Need | Item |
4//! |---|---|
5//! | Roles on a shared server | [`RbacMap`]: a harness tool class needs a permission, checked by `adk-auth`'s `ScopeGuard` (and `ProtectedTool` with an `AccessControl`) when the tool executes |
6//! | Credentials for `git` and HTTPS tools | [`ShellCredential`]: tokens minted per call by a `CredentialBroker` for the subject the run acts for, handed to `bash` through a helper script that exists only for that call, revoked after it |
7//! | Authenticated identity | `HarnessAgentBuilder::require_authenticated_identity`: on a served harness, standing rules and Auto apply only to a run whose user the server authenticated (I6) |
8//! | Tamper-evident record | the signed `adk_auth::signed_audit::AuditLog`; [`EphemeralAuditLog`] when none is configured, so every run records in Block mode (I39) |
9
10use 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
27/// Error code of a harness run without an audit trail in Block mode (spec 3.1 §9.2 I39).
28///
29/// # Example
30///
31/// ```rust
32/// assert_eq!(adk_harness::HARNESS_AUDIT_REQUIRED_CODE, "harness.audit_required");
33/// ```
34pub const HARNESS_AUDIT_REQUIRED_CODE: &str = "harness.audit_required";
35
36// ── RBAC ───────────────────────────────────────────────────────────────────────────
37
38/// Permission names, interned once each, so a wrapper can return `&[&str]` from
39/// `Tool::required_scopes`.
40fn 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/// The permission each harness tool class requires (spec 3.1 §7.14).
52///
53/// The harness wraps every tool whose class the map names in `adk-auth`'s `ScopeGuard`,
54/// with the permission as the required scope; with an
55/// [`AccessControl`](RbacMap::with_access_control) it is also wrapped in `ProtectedTool`,
56/// which checks the user's roles for the tool. The check runs when the tool executes,
57/// after the governed path allowed the call, so a denial is a tool error naming the
58/// missing permission. Scopes come from the run's authenticated request
59/// (`ToolContext::user_scopes`) unless a [`ScopeResolver`] is set.
60///
61/// # Example
62///
63/// ```rust
64/// use adk_harness::{Isolation, RbacMap, ToolKind};
65///
66/// let map = RbacMap::harness_defaults();
67/// assert_eq!(map.permission_for(&ToolKind::Shell(Isolation::Host)), Some("harness:shell"));
68/// assert_eq!(map.permission_for(&ToolKind::Payment), Some("harness:pay"));
69/// assert_eq!(map.permission_for(&ToolKind::Read), None);
70/// let custom = RbacMap::new().require(ToolKind::Edit, "repo:write");
71/// assert_eq!(custom.permission_for(&ToolKind::Edit), Some("repo:write"));
72/// ```
73#[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    /// An empty map: no class needs a permission.
92    pub fn new() -> Self {
93        Self::default()
94    }
95
96    /// `harness:shell` for every shell class and the unsandboxed retry, `harness:edit` for
97    /// edits, `harness:memory` for memory writes, `harness:pay` for payments, `harness:desktop`
98    /// for desktop actions (spec 3.1 §7.24).
99    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    /// Requires `permission` for tools of `class`.
113    #[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    /// Resolves the caller's permissions with `resolver` instead of the run's
120    /// authenticated scopes.
121    #[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    /// Also checks the user's roles in `access_control` for each wrapped tool
128    /// (`adk_auth::ProtectedTool`).
129    #[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    /// The permission a call of `class` needs.
136    pub fn permission_for(&self, class: &ToolKind) -> Option<&'static str> {
137        self.required.get(class).copied()
138    }
139
140    /// `tool` wrapped for `class`, or `tool` itself when the class needs no permission.
141    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
170/// What a [`PermissionTool`] adds to the tool it wraps.
171enum PermissionRole {
172    /// Declares the permission as the tool's required scope, for `ScopeGuard`.
173    Declare([&'static str; 1]),
174    /// Turns a denial by the `adk-auth` wrappers inside into a `Forbidden` error whose code
175    /// names the permission, which is the part of a tool error the model sees.
176    Explain { code: &'static str },
177}
178
179/// A forwarding wrapper: every method is the wrapped tool's, so the declaration digest and
180/// the tool's class are unchanged.
181struct 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// ── Credentials ────────────────────────────────────────────────────────────────────
268
269/// A resource `bash` gets a token for, through the credential helper (spec 3.1 §7.14).
270///
271/// # Example
272///
273/// ```rust
274/// use adk_harness::ShellCredential;
275///
276/// let github = ShellCredential::new("https://github.com/").unwrap().with_scopes(["repo"]);
277/// assert_eq!(github.resource.host_str(), Some("github.com"));
278/// assert_eq!(github.username, "x-access-token");
279/// ```
280#[derive(Clone, Debug, PartialEq, Eq)]
281pub struct ShellCredential {
282    /// The RFC 8707 resource the token is minted for; its host is what git asks about.
283    pub resource: Url,
284    /// Scopes requested for the token.
285    pub scopes: Vec<String>,
286    /// The user name git presents with the token.
287    pub username: String,
288}
289
290impl ShellCredential {
291    /// A credential for `resource` with no scopes and the user name `x-access-token`.
292    ///
293    /// # Errors
294    ///
295    /// `credential.resource.invalid` when `resource` is not an absolute HTTP(S) URI.
296    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    /// Requests `scopes`.
305    #[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    /// Presents the token with `username`.
316    #[must_use]
317    pub fn with_username(mut self, username: impl Into<String>) -> Self {
318        self.username = username.into();
319        self
320    }
321}
322
323/// The HTTPS remotes of the git repository at `root`, as credentials for their hosts.
324pub(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/// Environment of the calls that run with a credential helper, by function call id.
343#[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
367/// A [`CommandLauncher`] that adds the credential helper's environment to the command of
368/// a call that has one (spec 3.1 §7.14).
369pub(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    /// The Windows restricted-token sandbox starts the process itself, so the helper's
419    /// environment travels with the call (spec 3.2 §10 W5).
420    #[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
434/// Shell single-quoting.
435fn quote(text: &str) -> String {
436    format!("'{}'", text.replace('\'', "'\\''"))
437}
438
439/// The helper script: a git credential helper (`get`) and a `GIT_ASKPASS` program in one.
440fn 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
462/// Mints subject-scoped tokens around each call of the wrapped tool and hands them to
463/// the shell through a helper script that exists only for that call (spec 3.1 §7.14).
464///
465/// Tokens never enter the harness process's environment or the shell's: the shell gets
466/// `GIT_ASKPASS` and a git credential helper pointing at the script, which prints the
467/// token for the host git asks about. After the call the script is deleted and the
468/// tokens are revoked.
469pub(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        // A DACL granting the owner alone access stands in for the Unix modes (spec 3.2 §10
556        // W4).
557        #[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// ── Authenticated identity (I6) ────────────────────────────────────────────────────
671
672/// Which invocations ran for a user the server authenticated, for the policy
673/// (spec 3.1 §9.2 I6).
674#[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    /// Records whether `ctx`'s invocation is authenticated.
686    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    /// Whether rules and Auto apply only to authenticated runs
698    /// (`HarnessAgentBuilder::require_authenticated_identity`).
699    #[cfg(feature = "acp-server")]
700    pub(crate) fn requires_authentication(&self) -> bool {
701        self.require_authenticated
702    }
703
704    /// Whether standing rules and Auto are inert for `invocation_id`: the harness requires
705    /// authenticated identity and the invocation was not authenticated, or was never seen.
706    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
730// ── Signed audit (I39) ─────────────────────────────────────────────────────────────
731
732/// A signed, Merkle-hashed `AuditLog` kept in memory with a key generated at start-up:
733/// the harness's audit log when none is configured (spec 3.1 §9.2 I39).
734///
735/// Records are lost when the process exits and the key is never persisted, so a
736/// deployment passes its own `AuditLog` over a durable `AuditLogStore` to
737/// `HarnessAgentBuilder::audit_log`.
738///
739/// # Example
740///
741/// ```rust
742/// use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind, AuditRecorder};
743/// use adk_harness::EphemeralAuditLog;
744///
745/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
746/// let log = EphemeralAuditLog::new().unwrap();
747/// log.record(AuditRecordDraft::new(AuditRecordKind::ToolCall, "search")).await.unwrap();
748/// assert!(log.verify().await.unwrap());
749/// # });
750/// ```
751pub 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
763/// Log id of an [`EphemeralAuditLog`].
764const EPHEMERAL_LOG_ID: &str = "adk-harness";
765
766impl EphemeralAuditLog {
767    /// A new log with a freshly generated Ed25519 key.
768    ///
769    /// # Errors
770    ///
771    /// Returns an error when the system random number generator fails.
772    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    /// The store the records are in.
794    pub fn store(&self) -> &Arc<InMemoryAuditLogStore> {
795        &self.store
796    }
797
798    /// The signed-note verifier key of the log's checkpoints.
799    pub fn verifier_key(&self) -> String {
800        use adk_auth::signed_audit::AuditSigner as _;
801        self.signer.verifier_key()
802    }
803
804    /// The records in the log, in order (spec 3.1 §9.3).
805    ///
806    /// # Errors
807    ///
808    /// Returns the store's error, or a configuration error for a record that does not
809    /// parse.
810    ///
811    /// # Example
812    ///
813    /// ```rust
814    /// use adk_core::audit_log::{AuditRecordDraft, AuditRecordKind, AuditRecorder};
815    /// use adk_harness::EphemeralAuditLog;
816    ///
817    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
818    /// let log = EphemeralAuditLog::new().unwrap();
819    /// log.record(AuditRecordDraft::new(AuditRecordKind::ToolCall, "search")).await.unwrap();
820    /// let records = log.records().await.unwrap();
821    /// assert_eq!(records[0].action, "search");
822    /// # });
823    /// ```
824    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    /// Signs a checkpoint and verifies the whole log against it: hash chain, Merkle tree
841    /// and signature.
842    ///
843    /// # Errors
844    ///
845    /// Returns the store's error.
846    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    /// Signs a checkpoint over the records not yet signed; a log that has recorded
878    /// nothing is left unopened.
879    async fn seal(&self) -> Result<()> {
880        match self.log.get() {
881            Some(log) => log.seal().await,
882            None => Ok(()),
883        }
884    }
885}
886
887/// The refusal of a run whose audit trail is missing or does not block (spec 3.1 §9.2 I39).
888pub(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
901/// The credential resources of a harness: the configured ones, else the workspace's HTTPS
902/// git remotes.
903pub(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    /// A tool with its own origin, annotations and declaration, as an MCP tool has.
927    #[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    /// A broker that mints nothing.
968    #[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    /// Sealing signs one checkpoint over the records not yet signed, and none twice.
1044    #[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}