Skip to main content

aidaemon_core/
authority.rs

1//! Explicit authority: how much a run may do, and the hook that enforces it.
2//!
3//! An [`Authority`] is a value, not a mood. A child's authority is derived
4//! with [`Authority::narrow`], which can only shrink it.
5
6use std::collections::BTreeSet;
7use std::sync::Arc;
8
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11
12use crate::approval::AUTHORITY_BLOCKED;
13use crate::hook::{Hook, HookContext, ToolDecision};
14use crate::message::ToolCall;
15use crate::safeguard::Safeguard;
16use crate::tool::{ToolAnnotations, ToolInfo};
17
18/// How much a run may change. `ReadOnly < Write`.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "lowercase")]
21pub enum AccessLevel {
22    ReadOnly,
23    Write,
24}
25
26/// What a run is allowed to do: a level plus an optional tool allow-list.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct Authority {
29    pub level: AccessLevel,
30    /// `None` means every tool.
31    pub tools: Option<BTreeSet<String>>,
32}
33
34impl Authority {
35    /// Every tool, writes allowed.
36    pub fn full() -> Self {
37        Self {
38            level: AccessLevel::Write,
39            tools: None,
40        }
41    }
42
43    /// Every tool, but only calls that do not change anything.
44    pub fn read_only() -> Self {
45        Self {
46            level: AccessLevel::ReadOnly,
47            tools: None,
48        }
49    }
50
51    /// No tool at all.
52    pub fn no_tools() -> Self {
53        Self {
54            level: AccessLevel::ReadOnly,
55            tools: Some(BTreeSet::new()),
56        }
57    }
58
59    /// The most that both `self` and `requested` allow. Never wider than
60    /// either: lowest level, tool intersection (`None` is every tool).
61    pub fn narrow(&self, requested: &Authority) -> Authority {
62        let tools = match (&self.tools, &requested.tools) {
63            (None, None) => None,
64            (Some(t), None) | (None, Some(t)) => Some(t.clone()),
65            (Some(a), Some(b)) => Some(a.intersection(b).cloned().collect()),
66        };
67        Authority {
68            level: self.level.min(requested.level),
69            tools,
70        }
71    }
72
73    /// Whether a call to `tool` with these (per-call) annotations is allowed.
74    /// The error is the reason, as short text.
75    pub fn permits(&self, tool: &str, annotations: ToolAnnotations) -> Result<(), String> {
76        if let Some(tools) = &self.tools
77            && !tools.contains(tool)
78        {
79            return Err("tool not available".into());
80        }
81        if self.level == AccessLevel::ReadOnly && !annotations.read_only {
82            return Err("read-only".into());
83        }
84        Ok(())
85    }
86}
87
88/// Enforces the granted [`Authority`] (level and tool set) on every call, and
89/// declares [`Safeguard::Authority`] so the agent builder accepts it. It
90/// never prompts: a composition root that wants approvals for some calls adds
91/// its own hook.
92#[derive(Clone)]
93pub struct AuthorityHook {
94    authority: Authority,
95    ceiling: Option<Arc<dyn AuthorityCeiling>>,
96    delegated: bool,
97    /// How the person in charge can lift this hook's own limit, added to
98    /// its refusals (see [`Self::with_limit_note`]).
99    limit_note: Option<String>,
100}
101
102impl AuthorityHook {
103    pub fn new(authority: Authority) -> Self {
104        Self {
105            authority,
106            ceiling: None,
107            delegated: false,
108            limit_note: None,
109        }
110    }
111
112    /// Add `note` to every refusal this hook's own authority makes: what
113    /// set the limit and how it can be lifted, so the run tells the person
114    /// that instead of asking them to do the work by hand.
115    pub fn with_limit_note(mut self, note: impl Into<String>) -> Self {
116        self.limit_note = Some(note.into());
117        self
118    }
119
120    /// This run's authority was set by the agent that started it (a
121    /// sub-agent's): a refusal by that authority says so, so the run reports
122    /// the limit to its parent instead of to the session's owner. A refusal
123    /// by the ceiling still names the session.
124    pub fn delegated(mut self) -> Self {
125        self.delegated = true;
126        self
127    }
128
129    /// Read `ceiling` on every call and judge with the narrower of this
130    /// hook's authority and the ceiling's. A ceiling can narrow a running
131    /// turn; it can never widen it.
132    pub fn with_ceiling(mut self, ceiling: Arc<dyn AuthorityCeiling>) -> Self {
133        self.ceiling = Some(ceiling);
134        self
135    }
136}
137
138impl std::fmt::Debug for AuthorityHook {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        f.debug_struct("AuthorityHook")
141            .field("authority", &self.authority)
142            .field("ceiling", &self.ceiling.is_some())
143            .field("delegated", &self.delegated)
144            .finish()
145    }
146}
147
148/// A limit on what a run may do that can tighten while the run is in flight,
149/// read before every call. `None` means no extra limit right now.
150#[async_trait]
151pub trait AuthorityCeiling: Send + Sync {
152    async fn ceiling(&self) -> Option<Authority>;
153
154    /// What set the ceiling and how it can be lifted, added to a refusal
155    /// the ceiling (and not the run's own authority) made.
156    fn limit_note(&self) -> Option<&str> {
157        None
158    }
159}
160
161#[async_trait]
162impl Hook for AuthorityHook {
163    fn safeguards(&self) -> &'static [Safeguard] {
164        &[Safeguard::Authority]
165    }
166
167    fn authority(&self) -> Option<Authority> {
168        Some(self.authority.clone())
169    }
170
171    async fn before_tool(
172        &self,
173        _ctx: &HookContext<'_>,
174        call: &ToolCall,
175        tool: &ToolInfo,
176    ) -> ToolDecision {
177        if self.delegated
178            && let Err(reason) = self.authority.permits(&call.name, tool.annotations)
179        {
180            return ToolDecision::Deny {
181                reason: format!(
182                    "{AUTHORITY_BLOCKED} `{}` is outside the access this sub-agent was \
183                         given ({reason}). Use a permitted tool or report the limitation: the \
184                         agent that started this one chose that access, and only it can start \
185                         a sub-agent with more (never more than its own).",
186                    call.name
187                ),
188            };
189        }
190        let narrowed = match &self.ceiling {
191            Some(ceiling) => ceiling.ceiling().await.map(|c| self.authority.narrow(&c)),
192            None => None,
193        };
194        let judged = narrowed.as_ref().unwrap_or(&self.authority);
195        match judged.permits(&call.name, tool.annotations) {
196            Ok(()) => ToolDecision::Allow,
197            Err(reason) => {
198                // Whose limit refused it: the run's own authority, or only
199                // the ceiling narrowing it now.
200                let note = if self.authority.permits(&call.name, tool.annotations).is_ok() {
201                    self.ceiling.as_ref().and_then(|c| c.limit_note())
202                } else {
203                    self.limit_note.as_deref()
204                };
205                let mut reason = format!(
206                    "{AUTHORITY_BLOCKED} `{}` is outside what this session allows ({reason}). \
207                     Use a permitted tool or report the limitation.",
208                    call.name
209                );
210                if let Some(note) = note {
211                    reason.push(' ');
212                    reason.push_str(note);
213                }
214                ToolDecision::Deny { reason }
215            }
216        }
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use crate::testing::{ScriptedProvider, call, spec, text, tool_calls};
224    use crate::tool::{FnTool, Tool, ToolContext, ToolOutput, ToolResult};
225    use crate::{Agent, ReceiptStatus};
226    use serde_json::{Value, json};
227
228    fn set(names: &[&str]) -> BTreeSet<String> {
229        names.iter().map(|s| s.to_string()).collect()
230    }
231
232    fn samples() -> Vec<Authority> {
233        vec![
234            Authority::full(),
235            Authority::read_only(),
236            Authority::no_tools(),
237            Authority {
238                level: AccessLevel::Write,
239                tools: Some(set(&["read_file", "write_file"])),
240            },
241        ]
242    }
243
244    fn within(tools: &Option<BTreeSet<String>>, outer: &Option<BTreeSet<String>>) -> bool {
245        match (tools, outer) {
246            (_, None) => true,
247            (None, Some(_)) => false,
248            (Some(t), Some(o)) => t.is_subset(o),
249        }
250    }
251
252    #[test]
253    fn narrow_never_widens() {
254        for a in samples() {
255            for b in samples() {
256                let n = a.narrow(&b);
257                assert_eq!(n.level, a.level.min(b.level));
258                assert!(within(&n.tools, &a.tools), "{a:?} {b:?}");
259                assert!(within(&n.tools, &b.tools), "{a:?} {b:?}");
260            }
261        }
262    }
263
264    #[test]
265    fn narrow_intersects_tool_sets() {
266        let ab = Authority {
267            level: AccessLevel::Write,
268            tools: Some(set(&["a", "b"])),
269        };
270        let bc = Authority {
271            level: AccessLevel::Write,
272            tools: Some(set(&["b", "c"])),
273        };
274        assert_eq!(ab.narrow(&bc).tools, Some(set(&["b"])));
275        let b = Authority {
276            level: AccessLevel::Write,
277            tools: Some(set(&["b"])),
278        };
279        assert_eq!(Authority::full().narrow(&b).tools, Some(set(&["b"])));
280        assert_eq!(b.narrow(&Authority::full()).tools, Some(set(&["b"])));
281        assert_eq!(Authority::full().narrow(&Authority::full()).tools, None);
282    }
283
284    #[test]
285    fn read_only_denies_non_read_only_calls() {
286        let a = Authority::read_only();
287        assert!(a.permits("write_file", ToolAnnotations::WRITE).is_err());
288        assert!(a.permits("read_file", ToolAnnotations::READ_ONLY).is_ok());
289    }
290
291    #[test]
292    fn tool_set_denies_unlisted_tools() {
293        let a = Authority {
294            level: AccessLevel::Write,
295            tools: Some(set(&["read_file"])),
296        };
297        assert!(a.permits("terminal", ToolAnnotations::READ_ONLY).is_err());
298        assert!(a.permits("read_file", ToolAnnotations::READ_ONLY).is_ok());
299    }
300
301    struct FlagCeiling(std::sync::Arc<std::sync::atomic::AtomicBool>);
302    #[async_trait]
303    impl AuthorityCeiling for FlagCeiling {
304        async fn ceiling(&self) -> Option<Authority> {
305            self.0
306                .load(std::sync::atomic::Ordering::SeqCst)
307                .then(Authority::read_only)
308        }
309    }
310
311    fn writer_tool() -> impl Tool {
312        FnTool::new(
313            spec("write_file", "writes", &[]),
314            ToolAnnotations::WRITE,
315            |_: Value| async { Ok(ToolOutput::text("wrote")) },
316        )
317    }
318
319    #[tokio::test]
320    async fn ceiling_narrows_mid_run() {
321        let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
322        let flipper = {
323            let flag = flag.clone();
324            FnTool::new(
325                spec("flip", "flips the ceiling", &[]),
326                ToolAnnotations::READ_ONLY,
327                move |_: Value| {
328                    let flag = flag.clone();
329                    async move {
330                        flag.store(true, std::sync::atomic::Ordering::SeqCst);
331                        Ok(ToolOutput::text("flipped"))
332                    }
333                },
334            )
335        };
336        let agent = Agent::builder("a")
337            .model("m")
338            .provider(ScriptedProvider::new([
339                tool_calls([call("c1", "write_file", json!({}))]),
340                tool_calls([call("c2", "flip", json!({}))]),
341                tool_calls([call("c3", "write_file", json!({}))]),
342                text("done"),
343            ]))
344            .tool(writer_tool())
345            .tool(flipper)
346            .hook(
347                AuthorityHook::new(Authority::full())
348                    .with_ceiling(std::sync::Arc::new(FlagCeiling(flag))),
349            )
350            .attest(Safeguard::Scope)
351            .attest(Safeguard::Approval)
352            .attest(Safeguard::Egress)
353            .attest(Safeguard::UntrustedOutput)
354            .build()
355            .unwrap();
356        let out = agent.run("s", "go").await.unwrap();
357        let r = out.receipts();
358        assert_eq!(r[0].status, ReceiptStatus::Succeeded);
359        assert_eq!(r[2].status, ReceiptStatus::Denied);
360    }
361
362    struct FullCeiling;
363    #[async_trait]
364    impl AuthorityCeiling for FullCeiling {
365        async fn ceiling(&self) -> Option<Authority> {
366            Some(Authority::full())
367        }
368    }
369
370    #[tokio::test]
371    async fn ceiling_never_widens() {
372        let agent = Agent::builder("a")
373            .model("m")
374            .provider(ScriptedProvider::new([
375                tool_calls([call("c1", "write_file", json!({}))]),
376                text("done"),
377            ]))
378            .tool(writer_tool())
379            .hook(
380                AuthorityHook::new(Authority::read_only())
381                    .with_ceiling(std::sync::Arc::new(FullCeiling)),
382            )
383            .attest(Safeguard::Scope)
384            .attest(Safeguard::Approval)
385            .attest(Safeguard::Egress)
386            .attest(Safeguard::UntrustedOutput)
387            .build()
388            .unwrap();
389        let out = agent.run("s", "go").await.unwrap();
390        assert_eq!(out.receipts()[0].status, ReceiptStatus::Denied);
391    }
392
393    #[tokio::test]
394    async fn hook_declares_authority_and_denies() {
395        let writer = FnTool::new(
396            spec("write_file", "writes", &[]),
397            ToolAnnotations::WRITE,
398            |_: Value| async { Ok(ToolOutput::text("wrote")) },
399        );
400        let agent = Agent::builder("a")
401            .model("m")
402            .provider(ScriptedProvider::new([
403                tool_calls([call("c1", "write_file", json!({}))]),
404                text("done"),
405            ]))
406            .tool(writer)
407            .hook(AuthorityHook::new(Authority::read_only()))
408            .attest(Safeguard::Scope)
409            .attest(Safeguard::Approval)
410            .attest(Safeguard::Egress)
411            .attest(Safeguard::UntrustedOutput)
412            .build()
413            .unwrap();
414        let out = agent.run("s", "go").await.unwrap();
415        assert_eq!(out.receipts()[0].status, ReceiptStatus::Denied);
416        let reason = out.receipts()[0].reason.as_deref().unwrap_or_default();
417        assert!(
418            reason.starts_with("[AUTHORITY BLOCKED] `write_file`"),
419            "{reason}"
420        );
421    }
422
423    /// A sub-agent refused by the access its parent gave it is told so (the
424    /// parent can start it again with more); a refusal by the session's
425    /// ceiling still names the session.
426    #[tokio::test]
427    async fn a_delegated_refusal_names_the_parent_not_the_session() {
428        let run = |hook: AuthorityHook| async move {
429            let agent = Agent::builder("a")
430                .model("m")
431                .provider(ScriptedProvider::new([
432                    tool_calls([call("c1", "write_file", json!({}))]),
433                    text("done"),
434                ]))
435                .tool(writer_tool())
436                .hook(hook)
437                .attest(Safeguard::Scope)
438                .attest(Safeguard::Approval)
439                .attest(Safeguard::Egress)
440                .attest(Safeguard::UntrustedOutput)
441                .build()
442                .unwrap();
443            let out = agent.run("s", "go").await.unwrap();
444            assert_eq!(out.receipts()[0].status, ReceiptStatus::Denied);
445            out.receipts()[0].reason.clone().unwrap_or_default()
446        };
447        let given = run(AuthorityHook::new(Authority::read_only()).delegated()).await;
448        assert!(
449            given.contains("this sub-agent was given (read-only)"),
450            "{given}"
451        );
452        assert!(!given.contains("session"), "{given}");
453
454        let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
455        let session = run(AuthorityHook::new(Authority::full())
456            .with_ceiling(std::sync::Arc::new(FlagCeiling(flag)))
457            .delegated())
458        .await;
459        assert!(
460            session.contains("this session allows (read-only)"),
461            "{session}"
462        );
463    }
464
465    struct NotedCeiling;
466    #[async_trait]
467    impl AuthorityCeiling for NotedCeiling {
468        async fn ceiling(&self) -> Option<Authority> {
469            Some(Authority::read_only())
470        }
471        fn limit_note(&self) -> Option<&str> {
472            Some("ceiling-note")
473        }
474    }
475
476    /// A refusal carries the note of whichever limit made it: the run's own
477    /// authority, or the ceiling narrowing a run that could otherwise write.
478    #[tokio::test]
479    async fn a_refusal_says_how_its_own_limit_is_lifted() {
480        let run = |hook: AuthorityHook| async move {
481            let agent = Agent::builder("a")
482                .model("m")
483                .provider(ScriptedProvider::new([
484                    tool_calls([call("c1", "write_file", json!({}))]),
485                    text("done"),
486                ]))
487                .tool(writer_tool())
488                .hook(hook)
489                .attest(Safeguard::Scope)
490                .attest(Safeguard::Approval)
491                .attest(Safeguard::Egress)
492                .attest(Safeguard::UntrustedOutput)
493                .build()
494                .unwrap();
495            let out = agent.run("s", "go").await.unwrap();
496            assert_eq!(out.receipts()[0].status, ReceiptStatus::Denied);
497            out.receipts()[0].reason.clone().unwrap_or_default()
498        };
499        let own = run(AuthorityHook::new(Authority::read_only())
500            .with_limit_note("own-note")
501            .with_ceiling(std::sync::Arc::new(NotedCeiling)))
502        .await;
503        assert!(own.ends_with(" own-note"), "{own}");
504        let ceiling = run(AuthorityHook::new(Authority::full())
505            .with_limit_note("own-note")
506            .with_ceiling(std::sync::Arc::new(NotedCeiling)))
507        .await;
508        assert!(ceiling.ends_with(" ceiling-note"), "{ceiling}");
509        let plain = run(AuthorityHook::new(Authority::read_only())).await;
510        assert!(plain.ends_with("report the limitation."), "{plain}");
511    }
512
513    struct Mixed;
514    #[async_trait]
515    impl Tool for Mixed {
516        fn spec(&self) -> crate::ToolSpec {
517            spec("mixed", "read or write", &[])
518        }
519        fn annotations(&self) -> ToolAnnotations {
520            ToolAnnotations::DESTRUCTIVE
521        }
522        fn annotations_for(&self, arguments: &Value) -> ToolAnnotations {
523            if arguments["op"] == "read" {
524                ToolAnnotations::READ_ONLY
525            } else {
526                self.annotations()
527            }
528        }
529        async fn call(&self, _args: Value, _ctx: &ToolContext) -> ToolResult {
530            Ok(ToolOutput::text("ok"))
531        }
532    }
533
534    #[tokio::test]
535    async fn annotations_for_overrides_per_call() {
536        let agent = Agent::builder("a")
537            .model("m")
538            .provider(ScriptedProvider::new([
539                tool_calls([
540                    call("c1", "mixed", json!({"op": "read"})),
541                    call("c2", "mixed", json!({"op": "write"})),
542                ]),
543                text("done"),
544            ]))
545            .tool(Mixed)
546            .hook(AuthorityHook::new(Authority::read_only()))
547            .attest(Safeguard::Scope)
548            .attest(Safeguard::Approval)
549            .attest(Safeguard::Egress)
550            .attest(Safeguard::UntrustedOutput)
551            .build()
552            .unwrap();
553        let out = agent.run("s", "go").await.unwrap();
554        let r = out.receipts();
555        assert_eq!(r[0].status, ReceiptStatus::Succeeded);
556        assert_eq!(r[1].status, ReceiptStatus::Denied);
557    }
558
559    #[test]
560    fn an_empty_tool_set_permits_nothing() {
561        assert_eq!(
562            Authority::no_tools().permits("read_file", ToolAnnotations::READ_ONLY),
563            Err("tool not available".to_string())
564        );
565    }
566}