1use std::path::{Path, PathBuf};
4
5use graphrt_core::catalog::NodeDescriptor;
6use graphrt_core::tool::ToolSpec;
7use indexmap::IndexMap;
8use serde::{Deserialize, Serialize};
9
10use crate::error::PluginError;
11
12pub const PROTOCOL_VERSION: u32 = 1;
14
15pub const MANIFEST_FILES: &[&str] = &["graphrt-plugin.json", "graphrt-plugin.yaml", "graphrt-plugin.yml"];
17
18pub const DEFAULT_TIMEOUT_MS: u64 = 60_000;
20pub const DEFAULT_MAX_CONCURRENCY: usize = 16;
22pub const DEFAULT_MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024;
24
25#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
27#[serde(try_from = "RawManifest")]
28pub struct PluginManifest {
29 pub name: String,
30 #[serde(default)]
31 pub version: String,
32 #[serde(default)]
33 pub description: String,
34 #[serde(default)]
35 pub author: Option<String>,
36 #[serde(default)]
37 pub license: Option<String>,
38 #[serde(default)]
39 pub homepage: Option<String>,
40 #[serde(default = "default_protocol")]
41 pub protocol_version: u32,
42 #[serde(flatten)]
43 pub runtime: Runtime,
44 #[serde(default)]
45 pub permissions: Permissions,
46 #[serde(default)]
47 pub limits: Limits,
48 #[serde(default)]
50 pub checksums: IndexMap<String, String>,
51 #[serde(default)]
52 pub nodes: Vec<NodeDescriptor>,
53 #[serde(default)]
54 pub tools: Vec<ToolSpec>,
55 #[serde(default)]
57 pub allow_unprefixed_kinds: bool,
58}
59
60fn default_protocol() -> u32 {
61 PROTOCOL_VERSION
62}
63
64#[derive(Deserialize)]
67#[serde(deny_unknown_fields)]
68struct RawManifest {
69 name: String,
70 #[serde(default)]
71 version: String,
72 #[serde(default)]
73 description: String,
74 #[serde(default)]
75 author: Option<String>,
76 #[serde(default)]
77 license: Option<String>,
78 #[serde(default)]
79 homepage: Option<String>,
80 #[serde(default = "default_protocol")]
81 protocol_version: u32,
82 runtime: String,
83 #[serde(default)]
85 command: Option<String>,
86 #[serde(default)]
87 args: Vec<String>,
88 #[serde(default)]
89 env: IndexMap<String, String>,
90 #[serde(default)]
91 inherit_env: bool,
92 #[serde(default)]
93 cwd: Option<String>,
94 #[serde(default)]
96 url: Option<String>,
97 #[serde(default)]
98 headers: IndexMap<String, String>,
99 #[serde(default)]
100 bearer_token_env: Option<String>,
101 #[serde(default)]
103 module: Option<String>,
104 #[serde(default)]
105 permissions: Permissions,
106 #[serde(default)]
107 limits: Limits,
108 #[serde(default)]
109 checksums: IndexMap<String, String>,
110 #[serde(default)]
111 nodes: Vec<NodeDescriptor>,
112 #[serde(default)]
113 tools: Vec<ToolSpec>,
114 #[serde(default)]
115 allow_unprefixed_kinds: bool,
116}
117
118impl TryFrom<RawManifest> for PluginManifest {
119 type Error = String;
120
121 fn try_from(raw: RawManifest) -> Result<Self, String> {
122 let misplaced = |runtime: &str, fields: &[(&str, bool)]| -> Result<(), String> {
123 match fields.iter().find(|(_, present)| *present) {
124 Some((field, _)) => Err(format!("`{field}` is not valid for runtime `{runtime}`")),
125 None => Ok(()),
126 }
127 };
128 let process_fields = [
129 ("command", raw.command.is_some()),
130 ("args", !raw.args.is_empty()),
131 ("env", !raw.env.is_empty()),
132 ("inherit_env", raw.inherit_env),
133 ("cwd", raw.cwd.is_some()),
134 ];
135 let http_fields = [
136 ("url", raw.url.is_some()),
137 ("headers", !raw.headers.is_empty()),
138 ("bearer_token_env", raw.bearer_token_env.is_some()),
139 ];
140 let wasm_fields = [("module", raw.module.is_some())];
141 let runtime = match raw.runtime.as_str() {
142 "process" => {
143 misplaced("process", &http_fields)?;
144 misplaced("process", &wasm_fields)?;
145 Runtime::Process(ProcessRuntime {
146 command: raw.command.ok_or("runtime `process` requires `command`")?,
147 args: raw.args,
148 env: raw.env,
149 inherit_env: raw.inherit_env,
150 cwd: raw.cwd,
151 })
152 }
153 "http" => {
154 misplaced("http", &process_fields)?;
155 misplaced("http", &wasm_fields)?;
156 Runtime::Http(HttpRuntime {
157 url: raw.url.ok_or("runtime `http` requires `url`")?,
158 headers: raw.headers,
159 bearer_token_env: raw.bearer_token_env,
160 })
161 }
162 "wasm" => {
163 misplaced("wasm", &process_fields)?;
164 misplaced("wasm", &http_fields)?;
165 Runtime::Wasm(WasmRuntime { module: raw.module.ok_or("runtime `wasm` requires `module`")? })
166 }
167 other => return Err(format!("unknown runtime `{other}` (expected process, http or wasm)")),
168 };
169 Ok(Self {
170 name: raw.name,
171 version: raw.version,
172 description: raw.description,
173 author: raw.author,
174 license: raw.license,
175 homepage: raw.homepage,
176 protocol_version: raw.protocol_version,
177 runtime,
178 permissions: raw.permissions,
179 limits: raw.limits,
180 checksums: raw.checksums,
181 nodes: raw.nodes,
182 tools: raw.tools,
183 allow_unprefixed_kinds: raw.allow_unprefixed_kinds,
184 })
185 }
186}
187
188#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
190#[serde(tag = "runtime", rename_all = "lowercase")]
191#[non_exhaustive]
192pub enum Runtime {
193 Process(ProcessRuntime),
195 Http(HttpRuntime),
197 Wasm(WasmRuntime),
199}
200
201impl Runtime {
202 pub fn name(&self) -> &'static str {
204 match self {
205 Runtime::Process(_) => "process",
206 Runtime::Http(_) => "http",
207 Runtime::Wasm(_) => "wasm",
208 }
209 }
210}
211
212#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
214pub struct ProcessRuntime {
215 pub command: String,
216 #[serde(default)]
217 pub args: Vec<String>,
218 #[serde(default)]
220 pub env: IndexMap<String, String>,
221 #[serde(default)]
223 pub inherit_env: bool,
224 #[serde(default)]
226 pub cwd: Option<String>,
227}
228
229#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
231pub struct HttpRuntime {
232 pub url: String,
233 #[serde(default)]
234 pub headers: IndexMap<String, String>,
235 #[serde(default)]
237 pub bearer_token_env: Option<String>,
238}
239
240#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
242pub struct WasmRuntime {
243 pub module: String,
245}
246
247#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
249#[serde(deny_unknown_fields)]
250pub struct Permissions {
251 #[serde(default)]
253 pub network: bool,
254 #[serde(default)]
256 pub env: Vec<String>,
257 #[serde(default)]
259 pub secrets: bool,
260}
261
262#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
264#[serde(deny_unknown_fields)]
265pub struct Limits {
266 #[serde(default = "default_timeout")]
267 pub timeout_ms: u64,
268 #[serde(default = "default_concurrency")]
269 pub max_concurrency: usize,
270 #[serde(default = "default_message_bytes")]
271 pub max_message_bytes: usize,
272}
273
274fn default_timeout() -> u64 {
275 DEFAULT_TIMEOUT_MS
276}
277fn default_concurrency() -> usize {
278 DEFAULT_MAX_CONCURRENCY
279}
280fn default_message_bytes() -> usize {
281 DEFAULT_MAX_MESSAGE_BYTES
282}
283
284impl Default for Limits {
285 fn default() -> Self {
286 Self {
287 timeout_ms: DEFAULT_TIMEOUT_MS,
288 max_concurrency: DEFAULT_MAX_CONCURRENCY,
289 max_message_bytes: DEFAULT_MAX_MESSAGE_BYTES,
290 }
291 }
292}
293
294impl PluginManifest {
295 pub fn from_json(text: &str) -> Result<Self, PluginError> {
297 let manifest: Self = serde_json::from_str(text).map_err(|e| PluginError::Manifest(e.to_string()))?;
298 manifest.validate()?;
299 Ok(manifest)
300 }
301
302 #[cfg(feature = "yaml")]
304 pub fn from_yaml(text: &str) -> Result<Self, PluginError> {
305 let options = serde_saphyr::options! { strict_booleans: true };
306 let raw: serde_json::Value =
307 serde_saphyr::from_str_with_options(text, options).map_err(|e| PluginError::Manifest(e.to_string()))?;
308 let manifest: Self = serde_json::from_value(raw).map_err(|e| PluginError::Manifest(e.to_string()))?;
309 manifest.validate()?;
310 Ok(manifest)
311 }
312
313 pub fn from_file(path: &Path) -> Result<Self, PluginError> {
315 let text = std::fs::read_to_string(path)
316 .map_err(|e| PluginError::Io { path: path.to_path_buf(), message: e.to_string() })?;
317 let is_yaml = matches!(path.extension().and_then(|e| e.to_str()), Some("yaml" | "yml"));
318 let parsed = if is_yaml { Self::parse_yaml(&text) } else { Self::from_json(&text) };
319 parsed.map_err(|e| match e {
320 PluginError::Manifest(m) => PluginError::Manifest(format!("{}: {m}", path.display())),
321 other => other,
322 })
323 }
324
325 #[cfg(feature = "yaml")]
326 fn parse_yaml(text: &str) -> Result<Self, PluginError> {
327 Self::from_yaml(text)
328 }
329
330 #[cfg(not(feature = "yaml"))]
331 fn parse_yaml(_text: &str) -> Result<Self, PluginError> {
332 Err(PluginError::Manifest("YAML manifests need the `yaml` feature".into()))
333 }
334
335 pub fn validate(&self) -> Result<(), PluginError> {
337 let bad = |m: String| Err(PluginError::Manifest(format!("plugin `{}`: {m}", self.name)));
338 if !is_valid_name(&self.name) {
339 return bad("name must be 1-64 characters of lowercase letters, digits, `-` or `_`".into());
340 }
341 if self.protocol_version != PROTOCOL_VERSION {
342 return bad(format!(
343 "protocol_version {} is not supported (this host speaks {PROTOCOL_VERSION})",
344 self.protocol_version
345 ));
346 }
347 if self.limits.max_concurrency == 0 {
348 return bad("limits.max_concurrency must be at least 1".into());
349 }
350 if self.limits.timeout_ms == 0 {
351 return bad("limits.timeout_ms must be positive".into());
352 }
353 if self.limits.max_message_bytes < 1024 {
354 return bad("limits.max_message_bytes must be at least 1024".into());
355 }
356 let prefix = format!("{}.", self.name);
357 let mut seen = std::collections::HashSet::new();
358 for node in &self.nodes {
359 if node.kind.trim().is_empty() || node.kind.chars().any(char::is_whitespace) {
360 return bad(format!("invalid node kind `{}`", node.kind));
361 }
362 if !node.kind.starts_with(&prefix) {
363 if !self.allow_unprefixed_kinds {
364 return bad(format!("node kind `{}` must start with `{prefix}`", node.kind));
365 }
366 if node.kind.contains('.') {
369 return bad(format!(
370 "node kind `{}` uses another namespace; unprefixed kinds must not contain `.`",
371 node.kind
372 ));
373 }
374 }
375 if node.container {
376 return bad(format!("node kind `{}`: container nodes are not supported by plugins", node.kind));
377 }
378 if !seen.insert(node.kind.as_str()) {
379 return bad(format!("duplicate node kind `{}`", node.kind));
380 }
381 }
382 let mut tool_names = std::collections::HashSet::new();
383 for tool in &self.tools {
384 if tool.name.trim().is_empty() || !tool_names.insert(tool.name.as_str()) {
385 return bad(format!("invalid or duplicate tool name `{}`", tool.name));
386 }
387 }
388 match &self.runtime {
389 Runtime::Process(p) if p.command.trim().is_empty() => bad("`command` must not be empty".into()),
390 Runtime::Http(h) if !(h.url.starts_with("http://") || h.url.starts_with("https://")) => {
391 bad(format!("`url` must be an http(s) URL, got `{}`", h.url))
392 }
393 Runtime::Http(h) => self.validate_http(h),
394 Runtime::Wasm(w) if w.module.trim().is_empty() => bad("`module` must not be empty".into()),
395 Runtime::Wasm(w) if !is_inside(&w.module) => {
396 bad(format!("`module` `{}` must be relative and inside the plugin directory", w.module))
397 }
398 _ => Ok(()),
399 }?;
400 for path in self.checksums.keys() {
401 if !is_inside(path) {
402 return bad(format!("checksum path `{path}` must be relative and inside the plugin directory"));
403 }
404 }
405 if !self.checksums.is_empty() {
407 let entrypoint = match &self.runtime {
408 Runtime::Process(p) if Path::new(&p.command).components().count() > 1 && is_inside(&p.command) => {
409 Some(p.command.trim_start_matches("./"))
410 }
411 Runtime::Wasm(w) => Some(w.module.trim_start_matches("./")),
412 _ => None,
413 };
414 if let Some(entry) = entrypoint {
415 let pinned = self.checksums.keys().any(|k| k.trim_start_matches("./") == entry);
416 if !pinned {
417 return bad(format!("`checksums` must include the entrypoint `{entry}`"));
418 }
419 }
420 }
421 Ok(())
422 }
423
424 fn validate_http(&self, h: &HttpRuntime) -> Result<(), PluginError> {
428 let bad = |m: String| Err(PluginError::Manifest(format!("plugin `{}`: {m}", self.name)));
429 let sensitive = h.bearer_token_env.is_some() || self.permissions.secrets;
430 if sensitive && !h.url.starts_with("https://") && !is_loopback_url(&h.url) {
431 return bad(format!(
432 "`url` `{}` must use https:// when `bearer_token_env` or `permissions.secrets` is set",
433 h.url
434 ));
435 }
436 if let Some(var) = &h.bearer_token_env {
437 if !self.permissions.env.iter().any(|e| e == var) {
438 return bad(format!("`bearer_token_env` `{var}` must also be listed in `permissions.env`"));
439 }
440 }
441 Ok(())
442 }
443}
444
445fn is_inside(path: &str) -> bool {
447 !path.trim().is_empty() && !Path::new(path).is_absolute() && !path.split(['/', '\\']).any(|seg| seg == "..")
448}
449
450fn is_loopback_url(url: &str) -> bool {
452 let rest = url.split_once("://").map_or(url, |(_, r)| r);
453 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
454 let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
455 let host = if let Some(stripped) = host.strip_prefix('[') {
456 stripped.split(']').next().unwrap_or_default()
457 } else {
458 host.split(':').next().unwrap_or_default()
459 };
460 host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
461}
462
463pub fn is_valid_name(name: &str) -> bool {
465 !name.is_empty()
466 && name.len() <= 64
467 && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
468}
469
470#[derive(Clone, Debug, PartialEq)]
472pub struct LoadedManifest {
473 pub manifest: PluginManifest,
474 pub dir: PathBuf,
476}
477
478impl LoadedManifest {
479 pub fn from_dir(dir: &Path) -> Result<Self, PluginError> {
481 let path = manifest_in(dir)
482 .ok_or_else(|| PluginError::Manifest(format!("no plugin manifest found in {}", dir.display())))?;
483 Self::from_path(&path)
484 }
485
486 pub fn from_path(path: &Path) -> Result<Self, PluginError> {
488 let manifest = PluginManifest::from_file(path)?;
489 let dir = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
490 Ok(Self { manifest, dir })
491 }
492
493 pub fn resolve(&self, relative: &str) -> PathBuf {
495 self.dir.join(relative)
496 }
497}
498
499pub fn manifest_in(dir: &Path) -> Option<PathBuf> {
501 MANIFEST_FILES.iter().map(|f| dir.join(f)).find(|p| p.is_file())
502}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507
508 fn base() -> serde_json::Value {
509 serde_json::json!({
510 "name": "acme",
511 "runtime": "process",
512 "command": "python3",
513 "args": ["plugin.py"],
514 "nodes": [{"kind": "acme.x", "title": "X"}]
515 })
516 }
517
518 #[test]
519 fn parses_process_manifest() {
520 let m = PluginManifest::from_json(&base().to_string()).unwrap();
521 assert_eq!(m.runtime.name(), "process");
522 assert_eq!(m.limits.max_concurrency, DEFAULT_MAX_CONCURRENCY);
523 assert_eq!(m.nodes[0].kind, "acme.x");
524 }
525
526 #[test]
527 fn rejects_unprefixed_kind_and_bad_name() {
528 let mut v = base();
529 v["nodes"][0]["kind"] = "other.x".into();
530 assert!(PluginManifest::from_json(&v.to_string()).is_err());
531 v["allow_unprefixed_kinds"] = true.into();
533 assert!(PluginManifest::from_json(&v.to_string()).is_err());
534 v["nodes"][0]["kind"] = "plain".into();
535 assert!(PluginManifest::from_json(&v.to_string()).is_ok());
536 let mut v = base();
537 v["name"] = "Acme Corp".into();
538 assert!(PluginManifest::from_json(&v.to_string()).is_err());
539 }
540
541 #[test]
542 fn http_credentials_need_tls_and_declared_env() {
543 let http = |url: &str, extra: serde_json::Value| {
544 let mut v = serde_json::json!({
545 "name": "acme", "runtime": "http", "url": url,
546 "nodes": [{"kind": "acme.x", "title": "X"}]
547 });
548 if let (Some(obj), Some(more)) = (v.as_object_mut(), extra.as_object()) {
549 for (k, val) in more {
550 obj.insert(k.clone(), val.clone());
551 }
552 }
553 PluginManifest::from_json(&v.to_string())
554 };
555 let token = serde_json::json!({"bearer_token_env": "TOKEN", "permissions": {"env": ["TOKEN"]}});
557 assert!(http("http://evil.example/rpc", token.clone()).is_err());
558 assert!(http("https://plugins.example/rpc", token.clone()).is_ok());
559 assert!(http("http://127.0.0.1:9000/rpc", token.clone()).is_ok());
560 assert!(http("http://localhost/rpc", token).is_ok());
561 let undeclared = serde_json::json!({"bearer_token_env": "AWS_SECRET_ACCESS_KEY"});
562 assert!(http("https://plugins.example/rpc", undeclared).is_err());
563 let secrets = serde_json::json!({"permissions": {"secrets": true}});
564 assert!(http("http://evil.example/rpc", secrets).is_err());
565 assert!(http("http://evil.example/rpc", serde_json::json!({})).is_ok());
566 }
567
568 #[test]
569 fn wasm_module_and_entrypoint_checksums() {
570 let mut v = serde_json::json!({
571 "name": "acme", "runtime": "wasm", "module": "../escape.wasm",
572 "nodes": [{"kind": "acme.x", "title": "X"}]
573 });
574 assert!(PluginManifest::from_json(&v.to_string()).is_err());
575 v["module"] = "plugin.wasm".into();
576 assert!(PluginManifest::from_json(&v.to_string()).is_ok());
577 v["checksums"] = serde_json::json!({"other.txt": "00"});
579 assert!(PluginManifest::from_json(&v.to_string()).is_err());
580 v["checksums"] = serde_json::json!({"plugin.wasm": "00"});
581 assert!(PluginManifest::from_json(&v.to_string()).is_ok());
582 }
583
584 #[test]
585 fn loopback_detection() {
586 assert!(is_loopback_url("http://localhost:8080/x"));
587 assert!(is_loopback_url("http://[::1]:80/"));
588 assert!(is_loopback_url("http://user@127.0.0.2/"));
589 assert!(!is_loopback_url("http://localhost.evil.example/"));
590 assert!(!is_loopback_url("http://10.0.0.1/"));
591 }
592
593 #[test]
594 fn rejects_unknown_fields_and_bad_paths() {
595 let mut v = base();
596 v["comand"] = "x".into();
597 assert!(PluginManifest::from_json(&v.to_string()).is_err());
598 let mut v = base();
599 v["checksums"] = serde_json::json!({"../evil": "00"});
600 assert!(PluginManifest::from_json(&v.to_string()).is_err());
601 let mut v = base();
602 v["protocol_version"] = 99.into();
603 assert!(PluginManifest::from_json(&v.to_string()).is_err());
604 }
605
606 #[test]
607 fn parses_http_and_wasm() {
608 let http = serde_json::json!({"name": "h", "runtime": "http", "url": "https://p.example.com/rpc"});
609 assert!(matches!(PluginManifest::from_json(&http.to_string()).unwrap().runtime, Runtime::Http(_)));
610 let bad = serde_json::json!({"name": "h", "runtime": "http", "url": "ftp://x"});
611 assert!(PluginManifest::from_json(&bad.to_string()).is_err());
612 let wasm = serde_json::json!({"name": "w", "runtime": "wasm", "module": "plugin.wasm"});
613 assert!(matches!(PluginManifest::from_json(&wasm.to_string()).unwrap().runtime, Runtime::Wasm(_)));
614 }
615
616 #[cfg(feature = "yaml")]
617 #[test]
618 fn parses_yaml() {
619 let m = PluginManifest::from_yaml("name: acme\nruntime: process\ncommand: node\nargs: [p.mjs]\n").unwrap();
620 assert_eq!(m.name, "acme");
621 }
622}