Skip to main content

adk_kernel/drivers/
policy.rs

1//! The kernel's policy layer for driver tools (spec 3.2 §7.7, K-I6, K-I9, K-I13, K-I14).
2
3use adk_core::{PolicyCall, PolicyDecision, ToolPolicy, ToolPolicyRequest};
4use async_trait::async_trait;
5
6use super::driver_of;
7use super::supervisor::DriverSupervisor;
8
9/// The policy reference of [`DriverPolicy`] in audit records: `tool_policy:adk-kernel/drivers`.
10pub const DRIVER_POLICY_REF: &str = "adk-kernel/drivers";
11
12/// Decides calls to driver tools by the approved manifests (spec 3.2 §7.7).
13///
14/// It composes with the harness's policy through `StrictestPolicy` and never loosens it
15/// (K-I6): a call it does not concern, or that it allows, is decided by the other layers.
16///
17/// | Call | Decision |
18/// |---|---|
19/// | A tool whose source is not a driver's | Allow (not this layer's call) |
20/// | A tool of a driver that is not mounted | Deny (K-I13) |
21/// | A tool whose declaration differs from its pin, or that was not there at approval | RequireApproval until the driver is re-approved (K-I14) |
22/// | A tool of class `publish_public` or `financial` | RequireApproval, every call (K-I9) |
23/// | Any other driver tool | Allow |
24///
25/// # Example
26///
27/// ```rust
28/// use std::sync::Arc;
29/// use adk_core::PolicyDecision;
30/// use adk_kernel::drivers::DriverSupervisor;
31/// use adk_kernel::stores::InMemoryDriverStore;
32///
33/// let drivers = DriverSupervisor::builder(Arc::new(InMemoryDriverStore::new())).build();
34/// let policy = adk_kernel::drivers::DriverPolicy::new(drivers);
35/// assert!(matches!(policy.decide("email", "send_draft", "sha256:x"), PolicyDecision::Deny { .. }));
36/// ```
37#[derive(Debug, Clone)]
38pub struct DriverPolicy {
39    drivers: DriverSupervisor,
40}
41
42impl DriverPolicy {
43    /// The policy over `drivers`' mounted manifests.
44    pub fn new(drivers: DriverSupervisor) -> Self {
45        Self { drivers }
46    }
47
48    /// The decision for a call to `tool` of driver `id`, whose declaration digest is
49    /// `digest`.
50    pub fn decide(&self, id: &str, tool: &str, digest: &str) -> PolicyDecision {
51        let Some(record) = self.drivers.record(id) else {
52            return PolicyDecision::deny(format!(
53                "driver `{id}` is not mounted; a driver runs only with a manifest the user \
54                 approved (adk-rust drivers mount <file>)"
55            ));
56        };
57        let pins = &record.manifest.declaration_digests;
58        // A coordinator's crossing renames the tool it reaches and so its declaration; it is
59        // judged as that tool, whose declaration the listing that offered it compared with
60        // its pin (spec 3.2 §7.8).
61        let (tool, stale) = match self.drivers.wrapped_tool(id, tool) {
62            Some(wrapped) => {
63                let stale = record.stale.contains_key(&wrapped)
64                    || (!pins.is_empty() && !pins.contains_key(&wrapped));
65                (wrapped, stale)
66            }
67            None => {
68                let pinned = pins.get(tool);
69                let stale = record.stale.contains_key(tool)
70                    || pinned.is_some_and(|pinned| pinned != digest)
71                    || (pinned.is_none() && !pins.is_empty());
72                (tool.to_string(), stale)
73            }
74        };
75        let tool = tool.as_str();
76        if stale {
77            return PolicyDecision::require_approval(format!(
78                "`{tool}` of driver `{id}` declares something other than what was approved, so \
79                 its standing rules do not apply and every call needs approval until the driver \
80                 is re-approved (adk-rust drivers reapprove {id})"
81            ));
82        }
83        let class = record.manifest.class_of(tool);
84        if class.is_never_auto_allowed() {
85            return PolicyDecision::require_approval(format!(
86                "`{tool}` of driver `{id}` is `{class}`, which runs only when a person approves \
87                 the call"
88            ));
89        }
90        PolicyDecision::Allow
91    }
92}
93
94#[async_trait]
95impl ToolPolicy for DriverPolicy {
96    async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
97        PolicyDecision::Allow
98    }
99
100    async fn evaluate_call(
101        &self,
102        request: &ToolPolicyRequest,
103        call: &PolicyCall<'_>,
104    ) -> PolicyDecision {
105        match call.origin {
106            Some(origin) => match driver_of(&origin.source) {
107                Some(id) => self.decide(id, &request.tool_name, &origin.declaration_digest),
108                None => PolicyDecision::Allow,
109            },
110            None => PolicyDecision::Allow,
111        }
112    }
113
114    fn policy_ref(&self) -> Option<String> {
115        Some(DRIVER_POLICY_REF.to_string())
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use std::sync::Arc;
122
123    use super::*;
124    use crate::drivers::{DriverManifest, DriverRecord, DriverStore};
125    use crate::stores::InMemoryDriverStore;
126
127    /// A supervisor whose store holds `calendar`, with `list_events` pinned, `stale` marked
128    /// stale and `pay` classed financial.
129    async fn supervisor(stale: bool) -> DriverSupervisor {
130        let manifest = DriverManifest::from_toml(
131            "id = \"calendar\"\ncommand = \"mcp-calendar\"\npartitions = [\"work\"]\n\
132             [tools]\nlist_events = \"read\"\npay = \"financial\"\n",
133        )
134        .unwrap();
135        let mut record = DriverRecord::new(manifest, "alice", chrono::Utc::now());
136        for tool in ["list_events", "pay"] {
137            record.manifest.declaration_digests.insert(tool.into(), format!("sha256:{tool}"));
138        }
139        if stale {
140            record.stale.insert("list_events".into(), "sha256:changed".into());
141        }
142        let store = Arc::new(InMemoryDriverStore::new());
143        store.put(record).await.unwrap();
144        let drivers = DriverSupervisor::builder(store).build();
145        drivers.load().await.unwrap();
146        drivers.register_crossing("calendar", "work__list_events", "list_events");
147        drivers.register_crossing("calendar", "work__pay", "pay");
148        drivers
149    }
150
151    /// A coordinator's crossing is judged as the driver tool it wraps: allowed while that
152    /// tool's declaration is the approved one, asked once it is stale (K-I14), and asked
153    /// every call for a class never auto-allowed (K-I9).
154    #[tokio::test]
155    async fn a_crossing_is_judged_as_the_driver_tool_it_wraps() {
156        let fresh = DriverPolicy::new(supervisor(false).await);
157        assert_eq!(
158            fresh.decide("calendar", "work__list_events", "sha256:renamed"),
159            PolicyDecision::Allow
160        );
161        assert_eq!(
162            fresh.drivers.class_of("driver:calendar", "work__list_events"),
163            Some(crate::drivers::EffectClass::Read)
164        );
165        assert!(matches!(
166            fresh.decide("calendar", "work__pay", "sha256:renamed"),
167            PolicyDecision::RequireApproval { .. }
168        ));
169        let stale = DriverPolicy::new(supervisor(true).await);
170        assert!(matches!(
171            stale.decide("calendar", "work__list_events", "sha256:renamed"),
172            PolicyDecision::RequireApproval { .. }
173        ));
174        // A name no crossing registered is judged as itself: not there at approval.
175        assert!(matches!(
176            fresh.decide("calendar", "home__list_events", "sha256:x"),
177            PolicyDecision::RequireApproval { .. }
178        ));
179    }
180}