1use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::fmt;
5use std::path::{Path, PathBuf};
6
7use adk_tool::mcp::McpTaskConfig;
8use adk_tool::mcp::manager::{McpLifecycleMode, McpServerConfig, RestartPolicy};
9use serde::{Deserialize, Serialize};
10
11use super::EffectClass;
12use crate::error::{KernelError, Result};
13use crate::partition::PartitionId;
14
15pub const SECRET_SCHEME: &str = "secret";
17
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35#[non_exhaustive]
36pub enum DriverSandbox {
37 #[default]
39 Os,
40 Container,
43 Unsandboxed,
45}
46
47impl DriverSandbox {
48 pub fn as_str(self) -> &'static str {
50 match self {
51 Self::Os => "os",
52 Self::Container => "container",
53 Self::Unsandboxed => "unsandboxed",
54 }
55 }
56}
57
58#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69#[non_exhaustive]
70pub enum DriverLifecycle {
71 #[default]
73 Lazy,
74 Eager,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95#[non_exhaustive]
96pub struct DriverAccess {
97 #[serde(default, skip_serializing_if = "Vec::is_empty")]
99 pub allow_read: Vec<PathBuf>,
100 #[serde(default, skip_serializing_if = "Vec::is_empty")]
102 pub allow_write: Vec<PathBuf>,
103 #[serde(default = "default_true")]
105 pub allow_network: bool,
106 #[serde(default, skip_serializing_if = "Vec::is_empty")]
110 pub network_hosts: Vec<adk_core::egress::EgressRule>,
111}
112
113impl Default for DriverAccess {
114 fn default() -> Self {
115 Self {
116 allow_read: Vec::new(),
117 allow_write: Vec::new(),
118 allow_network: true,
119 network_hosts: Vec::new(),
120 }
121 }
122}
123
124impl DriverAccess {
125 pub fn egress_policy(&self) -> Option<adk_core::egress::EgressPolicy> {
127 (self.allow_network && !self.network_hosts.is_empty()).then(|| {
128 self.network_hosts.iter().cloned().fold(
129 adk_core::egress::EgressPolicy::deny_all(),
130 adk_core::egress::EgressPolicy::allow,
131 )
132 })
133 }
134}
135
136fn default_true() -> bool {
137 true
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193#[serde(rename_all = "camelCase")]
194#[non_exhaustive]
195pub struct DriverManifest {
196 pub id: String,
198 pub server: McpServerConfig,
201 pub partitions: Vec<PartitionId>,
203 pub sandbox: DriverSandbox,
205 #[serde(default)]
207 pub tools: BTreeMap<String, EffectClass>,
208 #[serde(default, skip_serializing_if = "Vec::is_empty")]
210 pub data_classes: Vec<String>,
211 #[serde(default)]
214 pub declaration_digests: BTreeMap<String, String>,
215 #[serde(default)]
217 pub lifecycle: DriverLifecycle,
218 #[serde(default)]
220 pub access: DriverAccess,
221 #[serde(default)]
223 pub sampling: bool,
224}
225
226#[derive(Debug, Deserialize)]
228#[serde(deny_unknown_fields)]
229struct ManifestFile {
230 id: String,
231 command: String,
232 #[serde(default)]
233 args: Vec<String>,
234 #[serde(default)]
235 env: HashMap<String, String>,
236 #[serde(default)]
237 partitions: Option<Vec<String>>,
238 #[serde(default)]
239 lifecycle: DriverLifecycle,
240 #[serde(default)]
241 protocol: McpLifecycleMode,
242 #[serde(default)]
243 sandbox: DriverSandbox,
244 #[serde(default)]
245 allow_read: Vec<PathBuf>,
246 #[serde(default)]
247 allow_write: Vec<PathBuf>,
248 #[serde(default = "default_true")]
249 allow_network: bool,
250 #[serde(default)]
251 network: Option<NetworkFile>,
252 #[serde(default)]
253 restart: Option<RestartFile>,
254 #[serde(default)]
255 sampling: bool,
256 #[serde(default)]
257 data_classes: Vec<String>,
258 #[serde(default)]
259 tools: BTreeMap<String, String>,
260}
261
262#[derive(Debug, Deserialize)]
264#[serde(deny_unknown_fields)]
265struct NetworkFile {
266 #[serde(default)]
267 hosts: Vec<adk_core::egress::EgressRule>,
268}
269
270#[derive(Debug, Deserialize)]
272#[serde(deny_unknown_fields)]
273struct RestartFile {
274 #[serde(default)]
275 max_attempts: Option<u32>,
276 #[serde(default)]
277 initial_delay_ms: Option<u64>,
278 #[serde(default)]
279 max_delay_ms: Option<u64>,
280 #[serde(default)]
281 backoff_multiplier: Option<f64>,
282}
283
284const CREDENTIAL_NAMES: &[&str] = &[
286 "TOKEN",
287 "SECRET",
288 "PASSWORD",
289 "PASSWD",
290 "API_KEY",
291 "APIKEY",
292 "ACCESS_KEY",
293 "PRIVATE_KEY",
294 "CREDENTIAL",
295 "CREDENTIALS",
296];
297
298fn names_a_credential(name: &str) -> bool {
300 let upper = name.to_ascii_uppercase();
301 CREDENTIAL_NAMES.iter().any(|suffix| {
302 upper == *suffix || upper.strip_suffix(suffix).is_some_and(|rest| rest.ends_with('_'))
303 })
304}
305
306fn invalid(id: &str, reason: impl fmt::Display) -> KernelError {
307 KernelError::Config { reason: format!("driver manifest `{id}`: {reason}") }
308}
309
310impl DriverManifest {
311 pub fn new(id: impl Into<String>, mut server: McpServerConfig) -> Result<Self> {
322 server.task_config.enable_tasks = true;
323 server.restart_policy.get_or_insert_with(RestartPolicy::default);
325 let manifest = Self {
326 id: id.into(),
327 server,
328 partitions: vec![PartitionId::default()],
329 sandbox: DriverSandbox::default(),
330 tools: BTreeMap::new(),
331 data_classes: Vec::new(),
332 declaration_digests: BTreeMap::new(),
333 lifecycle: DriverLifecycle::default(),
334 access: DriverAccess::default(),
335 sampling: false,
336 };
337 manifest.validate()?;
338 Ok(manifest)
339 }
340
341 pub fn from_toml(text: &str) -> Result<Self> {
348 let file: ManifestFile = toml::from_str(text).map_err(|error| KernelError::Config {
349 reason: format!("not a driver manifest: {error}"),
350 })?;
351 let mut restart = None;
352 if let Some(table) = file.restart {
353 let defaults = RestartPolicy::default();
354 restart = Some(RestartPolicy {
355 initial_delay_ms: table.initial_delay_ms.unwrap_or(defaults.initial_delay_ms),
356 max_delay_ms: table.max_delay_ms.unwrap_or(defaults.max_delay_ms),
357 backoff_multiplier: table.backoff_multiplier.unwrap_or(defaults.backoff_multiplier),
358 max_restart_attempts: table.max_attempts.unwrap_or(defaults.max_restart_attempts),
359 });
360 }
361 let server = McpServerConfig {
362 command: file.command,
363 args: file.args,
364 env: file.env,
365 restart_policy: restart,
366 lifecycle: file.protocol,
367 task_config: McpTaskConfig::enabled(),
368 ..McpServerConfig::default()
369 };
370 let mut tools = BTreeMap::new();
371 for (tool, class) in file.tools {
372 let class = class
373 .parse::<EffectClass>()
374 .map_err(|error| invalid(&file.id, format!("tool `{tool}`: {error}")))?;
375 tools.insert(tool, class);
376 }
377 let mut manifest = Self::new(file.id, server)?;
378 if let Some(partitions) = file.partitions {
379 manifest.partitions = partitions.into_iter().map(PartitionId::new).collect();
380 }
381 manifest.sandbox = file.sandbox;
382 manifest.tools = tools;
383 manifest.data_classes = file.data_classes;
384 manifest.lifecycle = file.lifecycle;
385 manifest.access = DriverAccess {
386 allow_read: file.allow_read,
387 allow_write: file.allow_write,
388 allow_network: file.allow_network,
389 network_hosts: file.network.map(|network| network.hosts).unwrap_or_default(),
390 };
391 manifest.sampling = file.sampling;
392 manifest.validate()?;
393 Ok(manifest)
394 }
395
396 pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
403 let path = path.as_ref();
404 let text = std::fs::read_to_string(path)?;
405 Self::from_toml(&text)
406 .map_err(|error| KernelError::Config { reason: format!("{}: {error}", path.display()) })
407 }
408
409 pub fn validate(&self) -> Result<()> {
415 if self.id.is_empty()
416 || !self.id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
417 {
418 return Err(invalid(
419 &self.id,
420 "the id must be ASCII letters, digits, `-` or `_`, as MCP server ids are",
421 ));
422 }
423 if self.server.command.trim().is_empty() {
424 return Err(invalid(&self.id, "the command is empty"));
425 }
426 if !self.access.network_hosts.is_empty()
427 && (!self.access.allow_network || self.sandbox != DriverSandbox::Os)
428 {
429 return Err(invalid(
430 &self.id,
431 "network hosts are enforced only by the OS sandbox's egress proxy: set \
432 sandbox = \"os\" and leave allow_network on, or drop the hosts",
433 ));
434 }
435 if self.partitions.is_empty() {
436 return Err(invalid(&self.id, "it serves no partition; list at least one"));
437 }
438 for (name, value) in &self.server.env {
439 match secret_reference(value) {
440 Some(Err(reason)) => {
441 return Err(invalid(&self.id, format!("env `{name}`: {reason}")));
442 }
443 Some(Ok(_)) => {}
444 None if names_a_credential(name) && !value.is_empty() => {
445 return Err(invalid(
446 &self.id,
447 format!(
448 "env `{name}` holds a plain value under a credential's name; write \
449 `secret://<path>` and bind the secret in the credential broker"
450 ),
451 ));
452 }
453 None => {}
454 }
455 }
456 Ok(())
457 }
458
459 pub fn class_of(&self, tool: &str) -> EffectClass {
461 self.tools.get(tool).copied().unwrap_or(EffectClass::Other)
462 }
463
464 #[must_use]
466 pub fn with_tool(mut self, tool: impl Into<String>, class: EffectClass) -> Self {
467 self.tools.insert(tool.into(), class);
468 self
469 }
470
471 #[must_use]
473 pub fn with_partitions(mut self, partitions: impl IntoIterator<Item = PartitionId>) -> Self {
474 self.partitions = partitions.into_iter().collect();
475 self
476 }
477
478 #[must_use]
480 pub fn with_sandbox(mut self, sandbox: DriverSandbox) -> Self {
481 self.sandbox = sandbox;
482 self
483 }
484
485 #[must_use]
487 pub fn with_access(mut self, access: DriverAccess) -> Self {
488 self.access = access;
489 self
490 }
491
492 #[must_use]
494 pub fn with_lifecycle(mut self, lifecycle: DriverLifecycle) -> Self {
495 self.lifecycle = lifecycle;
496 self
497 }
498
499 #[must_use]
501 pub fn with_sampling(mut self, sampling: bool) -> Self {
502 self.sampling = sampling;
503 self
504 }
505
506 pub fn command_line(&self) -> String {
509 std::iter::once(&self.server.command)
510 .chain(&self.server.args)
511 .map(|word| shell_word(word))
512 .collect::<Vec<_>>()
513 .join(" ")
514 }
515
516 pub fn command_digest(&self) -> String {
519 let env: BTreeMap<&String, &String> = self.server.env.iter().collect();
520 adk_core::json_digest(&serde_json::json!({
521 "command": self.server.command,
522 "args": self.server.args,
523 "env": env,
524 "protocol": self.server.lifecycle,
525 "sandbox": self.sandbox,
526 "access": self.access,
527 }))
528 }
529
530 pub fn secret_references(&self) -> BTreeMap<String, url::Url> {
532 self.server
533 .env
534 .iter()
535 .filter_map(|(name, value)| match secret_reference(value) {
536 Some(Ok(reference)) => Some((name.clone(), reference)),
537 _ => None,
538 })
539 .collect()
540 }
541
542 pub fn restrict_with(&self, project: &DriverManifest) -> Result<DriverManifest> {
582 let refuse = |what: &str| {
583 Err(invalid(
584 &self.id,
585 format!("a project manifest may only restrict a driver; it {what}"),
586 ))
587 };
588 if project.id != self.id {
589 return refuse(&format!("names driver `{}` instead", project.id));
590 }
591 let (mine, theirs) = (&self.server, &project.server);
592 if mine.command != theirs.command
593 || mine.args != theirs.args
594 || mine.env != theirs.env
595 || mine.lifecycle != theirs.lifecycle
596 || mine.restart_policy != theirs.restart_policy
597 {
598 return refuse(
599 "changes what runs: the command, arguments, environment, protocol or restart",
600 );
601 }
602 let allowed: BTreeSet<&PartitionId> = self.partitions.iter().collect();
603 if let Some(extra) = project.partitions.iter().find(|p| !allowed.contains(p)) {
604 return refuse(&format!("adds partition `{extra}`"));
605 }
606 if project.sandbox != self.sandbox && self.sandbox != DriverSandbox::Unsandboxed {
607 return refuse(&format!(
608 "changes the sandbox from `{}` to `{}`",
609 self.sandbox.as_str(),
610 project.sandbox.as_str()
611 ));
612 }
613 if let Some(path) =
614 project.access.allow_read.iter().find(|p| !self.access.allow_read.contains(p))
615 {
616 return refuse(&format!("grants read access to {}", path.display()));
617 }
618 if let Some(path) =
619 project.access.allow_write.iter().find(|p| !self.access.allow_write.contains(p))
620 {
621 return refuse(&format!("grants write access to {}", path.display()));
622 }
623 if project.access.allow_network && !self.access.allow_network {
624 return refuse("grants network access");
625 }
626 if project.access.allow_network
629 && let Some(mine) = self.access.egress_policy()
630 {
631 if project.access.network_hosts.is_empty() {
632 return refuse("opens the network the user's manifest limits to its hosts");
633 }
634 if let Some(host) = project.access.network_hosts.iter().find(|host| !mine.covers(host))
635 {
636 return refuse(&format!("grants network access to {host}"));
637 }
638 }
639 if project.sampling && !self.sampling {
640 return refuse("lets the server sample");
641 }
642 if project.lifecycle == DriverLifecycle::Eager && self.lifecycle == DriverLifecycle::Lazy {
643 return refuse("starts the driver eagerly");
644 }
645 let mut tools = self.tools.clone();
646 for (tool, class) in &project.tools {
647 let current = self.class_of(tool);
648 if class.strictness() < current.strictness() {
649 return refuse(&format!("loosens tool `{tool}` from `{current}` to `{class}`"));
650 }
651 tools.insert(tool.clone(), *class);
652 }
653 let mut effective = self.clone();
654 effective.partitions = project.partitions.clone();
655 effective.sandbox = project.sandbox;
656 effective.access = project.access.clone();
657 effective.sampling = project.sampling;
658 effective.lifecycle = project.lifecycle;
659 effective.tools = tools;
660 Ok(effective)
661 }
662}
663
664fn secret_reference(value: &str) -> Option<std::result::Result<url::Url, String>> {
667 let rest = value.strip_prefix(SECRET_SCHEME)?.strip_prefix("://")?;
668 Some(match url::Url::parse(value) {
669 Ok(url) if !rest.is_empty() && url.host_str().is_some_and(|host| !host.is_empty()) => {
670 Ok(url)
671 }
672 Ok(_) => Err(format!("`{value}` names no secret; write secret://<scope>/<name>")),
673 Err(error) => Err(format!("`{value}` is not a secret reference: {error}")),
674 })
675}
676
677fn shell_word(word: &str) -> String {
679 let plain = !word.is_empty()
680 && word.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%".contains(c));
681 if plain { word.to_string() } else { format!("'{}'", word.replace('\'', "'\\''")) }
682}
683
684pub fn load_dir(dir: impl AsRef<Path>) -> Result<Vec<DriverManifest>> {
691 let dir = dir.as_ref();
692 let entries = match std::fs::read_dir(dir) {
693 Ok(entries) => entries,
694 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
695 Err(error) => return Err(error.into()),
696 };
697 let mut paths: Vec<PathBuf> = entries
698 .filter_map(|entry| entry.ok().map(|entry| entry.path()))
699 .filter(|path| path.extension().is_some_and(|ext| ext == "toml") && path.is_file())
700 .collect();
701 paths.sort();
702 let mut manifests: Vec<DriverManifest> = Vec::with_capacity(paths.len());
703 for path in paths {
704 let manifest = DriverManifest::from_file(&path)?;
705 if manifests.iter().any(|known| known.id == manifest.id) {
706 return Err(KernelError::Config {
707 reason: format!(
708 "{}: driver `{}` is declared twice in {}",
709 path.display(),
710 manifest.id,
711 dir.display()
712 ),
713 });
714 }
715 manifests.push(manifest);
716 }
717 Ok(manifests)
718}
719
720pub fn load_manifests(
737 user_dir: impl AsRef<Path>,
738 project_dir: Option<&Path>,
739) -> Result<Vec<DriverManifest>> {
740 let mut manifests = load_dir(user_dir)?;
741 let Some(project_dir) = project_dir else {
742 return Ok(manifests);
743 };
744 for project in load_dir(project_dir)? {
745 let Some(user) = manifests.iter_mut().find(|user| user.id == project.id) else {
746 return Err(KernelError::Config {
747 reason: format!(
748 "{}: driver `{}` is not in the user's drivers; a workspace may only \
749 restrict drivers the user declared",
750 project_dir.display(),
751 project.id
752 ),
753 });
754 };
755 *user = user.restrict_with(&project)?;
756 }
757 Ok(manifests)
758}
759
760#[cfg(test)]
761mod tests {
762 use adk_core::ToolEffect;
763
764 use super::*;
765
766 #[test]
767 fn network_hosts_limit_the_driver_and_a_project_can_only_narrow_them() {
768 let base = "id = \"mail\"\ncommand = \"mcp-mail\"\nsandbox = \"os\"\n";
769 let user = DriverManifest::from_toml(&format!(
770 "{base}network = {{ hosts = [\"imap.example.com:993\", \"*.example.com:443\"] }}\n"
771 ))
772 .unwrap();
773 let policy = user.access.egress_policy().expect("hosts make an egress policy");
774 assert!(policy.check_url("https://api.example.com/").is_ok());
775 assert!(policy.check_url("https://evil.test/").is_err());
776
777 let narrower = DriverManifest::from_toml(&format!(
778 "{base}network = {{ hosts = [\"api.example.com:443\"] }}\n"
779 ))
780 .unwrap();
781 let effective = user.restrict_with(&narrower).unwrap();
782 assert_eq!(effective.access.network_hosts, narrower.access.network_hosts);
783 for wider in
784 [format!("{base}network = {{ hosts = [\"evil.test:443\"] }}\n"), base.to_string()]
785 {
786 let project = DriverManifest::from_toml(&wider).unwrap();
787 assert!(user.restrict_with(&project).is_err(), "{wider}");
788 }
789 let denied = DriverManifest::from_toml(&format!("{base}allow_network = false\n")).unwrap();
790 assert!(user.restrict_with(&denied).is_ok());
791 assert_eq!(denied.access.egress_policy(), None);
792 for refused in [
793 format!("{base}network = {{ hosts = [\"https://x\"] }}\n"),
794 format!("{base}allow_network = false\nnetwork = {{ hosts = [\"x.example.com\"] }}\n"),
795 "id = \"mail\"\ncommand = \"mcp-mail\"\nsandbox = \"unsandboxed\"\n\
796 network = { hosts = [\"x.example.com\"] }\n"
797 .to_string(),
798 ] {
799 assert!(DriverManifest::from_toml(&refused).is_err(), "{refused}");
800 }
801 }
802
803 const EMAIL: &str = r#"
804 id = "email"
805 command = "mcp-email"
806 args = ["--imap"]
807 env = { EMAIL_TOKEN = "secret://email/token", LOG_LEVEL = "info" }
808 partitions = ["work"]
809 lifecycle = "lazy"
810 sandbox = "os"
811 restart = { max_attempts = 5, initial_delay_ms = 500, max_delay_ms = 30000, backoff_multiplier = 2.0 }
812
813 [tools]
814 list_inbox = "read"
815 get_email = "read"
816 create_draft = "write_local"
817 send_draft = "send_external"
818 "#;
819
820 #[test]
821 fn the_spec_manifest_parses() {
822 let manifest = DriverManifest::from_toml(EMAIL).unwrap();
823 assert_eq!(manifest.id, "email");
824 assert_eq!(manifest.server.command, "mcp-email");
825 assert_eq!(manifest.server.args, ["--imap"]);
826 assert_eq!(manifest.partitions, [PartitionId::new("work")]);
827 assert_eq!(manifest.lifecycle, DriverLifecycle::Lazy);
828 assert_eq!(manifest.sandbox, DriverSandbox::Os);
829 assert_eq!(
830 manifest.server.restart_policy,
831 Some(RestartPolicy {
832 initial_delay_ms: 500,
833 max_delay_ms: 30_000,
834 backoff_multiplier: 2.0,
835 max_restart_attempts: 5,
836 })
837 );
838 assert!(manifest.server.task_config.enable_tasks);
839 assert_eq!(manifest.class_of("list_inbox"), EffectClass::Read);
840 assert_eq!(manifest.class_of("create_draft"), EffectClass::WriteLocal);
841 assert_eq!(manifest.class_of("send_draft"), EffectClass::SendExternal);
842 assert_eq!(manifest.class_of("unknown_tool"), EffectClass::Other);
843 assert!(manifest.declaration_digests.is_empty());
844 let secrets = manifest.secret_references();
845 assert_eq!(secrets["EMAIL_TOKEN"].as_str(), "secret://email/token");
846 assert!(!secrets.contains_key("LOG_LEVEL"));
847 assert_eq!(manifest.command_line(), "mcp-email --imap");
848 }
849
850 #[test]
851 fn every_effect_class_parses_and_prints_as_itself() {
852 for class in EffectClass::ALL {
853 assert_eq!(class.as_str().parse::<EffectClass>().unwrap(), class);
854 assert_eq!(serde_json::to_value(class).unwrap(), class.as_str());
855 }
856 assert_eq!("Send-External".parse::<EffectClass>().unwrap(), EffectClass::SendExternal);
857 assert!("teleport".parse::<EffectClass>().is_err());
858 let manifest =
859 DriverManifest::from_toml("id = \"x\"\ncommand = \"x\"\n[tools]\na = \"teleport\"\n");
860 assert!(manifest.unwrap_err().to_string().contains("teleport"));
861 }
862
863 #[test]
864 fn only_publish_public_and_financial_are_never_auto_allowed() {
865 let never: Vec<_> =
866 EffectClass::ALL.into_iter().filter(|class| class.is_never_auto_allowed()).collect();
867 assert_eq!(never, [EffectClass::PublishPublic, EffectClass::Financial]);
868 for class in EffectClass::ALL {
869 let effect = class.tool_effect();
870 assert_eq!(effect == ToolEffect::ReadOnly, class == EffectClass::Read, "{class}");
871 }
872 }
873
874 #[test]
875 fn defaults_are_sandboxed_lazy_and_in_the_default_partition() {
876 let manifest = DriverManifest::from_toml("id = \"fs\"\ncommand = \"mcp-fs\"\n").unwrap();
877 assert_eq!(manifest.partitions, [PartitionId::default()]);
878 assert_eq!(manifest.sandbox, DriverSandbox::Os);
879 assert_eq!(manifest.lifecycle, DriverLifecycle::Lazy);
880 assert!(manifest.access.allow_network);
881 assert!(!manifest.sampling);
882 assert_eq!(manifest.server.lifecycle, McpLifecycleMode::Initialize);
883 assert_eq!(manifest.server.restart_policy, Some(RestartPolicy::default()));
884 }
885
886 #[test]
887 fn bad_manifests_are_refused_with_the_reason() {
888 let cases = [
889 ("id = \"a b\"\ncommand = \"x\"\n", "the id must be"),
890 ("id = \"a\"\ncommand = \" \"\n", "command is empty"),
891 ("id = \"a\"\ncommand = \"x\"\npartitions = []\n", "serves no partition"),
892 ("id = \"a\"\ncommand = \"x\"\nenv = { API_TOKEN = \"abc\" }\n", "credential"),
893 ("id = \"a\"\ncommand = \"x\"\nenv = { GH_PASSWORD = \"abc\" }\n", "credential"),
894 ("id = \"a\"\ncommand = \"x\"\nenv = { TOKEN = \"secret://\" }\n", "secret"),
895 ("id = \"a\"\ncommand = \"x\"\nsurprise = 1\n", "unknown field"),
896 ("id = \"a\"\ncommand = \"x\"\nsandbox = \"vm\"\n", "unknown variant"),
897 ];
898 for (text, expected) in cases {
899 let error = DriverManifest::from_toml(text).unwrap_err().to_string();
900 assert!(error.contains(expected), "{text}: {error}");
901 }
902 DriverManifest::from_toml(
904 "id = \"a\"\ncommand = \"x\"\nenv = { API_TOKEN = \"secret://a/t\", TOKENIZER = \"bpe\" }\n",
905 )
906 .unwrap();
907 }
908
909 #[test]
910 fn a_project_manifest_may_only_restrict() {
911 let user = DriverManifest::from_toml(
912 r#"
913 id = "email"
914 command = "mcp-email"
915 partitions = ["work", "home"]
916 sandbox = "unsandboxed"
917 allow_read = ["/srv/mail"]
918 lifecycle = "eager"
919 sampling = true
920 [tools]
921 send_draft = "send_external"
922 list_inbox = "read"
923 "#,
924 )
925 .unwrap();
926 let narrow = |extra: &str| {
927 DriverManifest::from_toml(&format!(
928 "id = \"email\"\ncommand = \"mcp-email\"\npartitions = [\"work\"]\n{extra}"
929 ))
930 .unwrap()
931 };
932
933 let effective = user
934 .restrict_with(&narrow(
935 "sandbox = \"os\"\nallow_network = false\n[tools]\nlist_inbox = \"delete\"\n",
936 ))
937 .unwrap();
938 assert_eq!(effective.partitions, [PartitionId::new("work")]);
939 assert_eq!(effective.sandbox, DriverSandbox::Os);
940 assert!(!effective.access.allow_network);
941 assert!(!effective.sampling);
942 assert_eq!(effective.lifecycle, DriverLifecycle::Lazy);
943 assert_eq!(effective.class_of("list_inbox"), EffectClass::Delete);
944 assert_eq!(effective.class_of("send_draft"), EffectClass::SendExternal);
945
946 let error = user
947 .restrict_with(
948 &DriverManifest::from_toml(
949 "id = \"email\"\ncommand = \"mcp-email\"\npartitions = [\"work\", \"play\"]\n",
950 )
951 .unwrap(),
952 )
953 .unwrap_err()
954 .to_string();
955 assert!(error.contains("adds partition"), "{error}");
956 for (project, loosens) in [
957 ("[tools]\nsend_draft = \"read\"\n", "loosens tool"),
958 ("allow_write = [\"/\"]\n", "write access"),
959 ("allow_read = [\"/etc\"]\n", "read access"),
960 ] {
961 let error = user.restrict_with(&narrow(project)).unwrap_err().to_string();
962 assert!(error.contains(loosens), "{error}");
963 }
964 let other_command = DriverManifest::from_toml(
965 "id = \"email\"\ncommand = \"evil\"\npartitions = [\"work\"]\n",
966 )
967 .unwrap();
968 assert!(user.restrict_with(&other_command).unwrap_err().to_string().contains("what runs"));
969
970 let sandboxed = narrow("");
972 let unsandboxed = narrow("sandbox = \"unsandboxed\"\n");
973 assert!(sandboxed.restrict_with(&unsandboxed).is_err());
974 }
975
976 #[test]
977 fn load_manifests_restricts_by_the_workspace_and_refuses_new_drivers() {
978 let user = tempfile::tempdir().unwrap();
979 let project = tempfile::tempdir().unwrap();
980 std::fs::write(user.path().join("email.toml"), EMAIL).unwrap();
981 std::fs::write(user.path().join("notes.txt"), "not a manifest").unwrap();
982 std::fs::write(
983 project.path().join("email.toml"),
984 EMAIL.replace("send_external", "publish_public"),
985 )
986 .unwrap();
987 let manifests = load_manifests(user.path(), Some(project.path())).unwrap();
988 assert_eq!(manifests.len(), 1);
989 assert_eq!(manifests[0].class_of("send_draft"), EffectClass::PublishPublic);
990
991 std::fs::write(
992 project.path().join("calendar.toml"),
993 "id = \"calendar\"\ncommand = \"c\"\n",
994 )
995 .unwrap();
996 let error = load_manifests(user.path(), Some(project.path())).unwrap_err().to_string();
997 assert!(error.contains("may only restrict drivers the user declared"), "{error}");
998 assert!(load_dir(user.path().join("missing")).unwrap().is_empty());
999 }
1000
1001 #[test]
1002 fn the_command_digest_changes_with_what_runs() {
1003 let manifest = DriverManifest::from_toml(EMAIL).unwrap();
1004 let mut other = manifest.clone();
1005 other.server.args.push("--debug".into());
1006 assert_ne!(manifest.command_digest(), other.command_digest());
1007 let mut reclassed = manifest.clone();
1008 reclassed.tools.clear();
1009 assert_eq!(manifest.command_digest(), reclassed.command_digest());
1010 let quoted = DriverManifest::new(
1011 "q",
1012 McpServerConfig {
1013 command: "/opt/my tools/srv".into(),
1014 args: vec!["it's".into()],
1015 ..Default::default()
1016 },
1017 )
1018 .unwrap();
1019 assert_eq!(quoted.command_line(), "'/opt/my tools/srv' 'it'\\''s'");
1020 }
1021
1022 #[test]
1023 fn a_manifest_round_trips_through_json() {
1024 let mut manifest = DriverManifest::from_toml(EMAIL).unwrap();
1025 manifest.declaration_digests.insert("list_inbox".into(), "sha256:ab".into());
1026 let json = serde_json::to_value(&manifest).unwrap();
1027 assert_eq!(json["sandbox"], "os");
1028 assert_eq!(json["tools"]["send_draft"], "send_external");
1029 let back: DriverManifest = serde_json::from_value(json).unwrap();
1030 assert_eq!(back, manifest);
1031 }
1032}