Skip to main content

core_api/
plugin_publication.rs

1//! Platform-attested community releases. Parse only after verifying the enclosing
2//! release signature; a source manifest cannot grant this provenance to itself.
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
8pub enum PluginPublication {
9    Community {
10        #[serde(rename = "publisherId")]
11        publisher_id: String,
12        /// Published Integration IDs, acquired when this Plugin is enabled in a Space.
13        integrations: Vec<String>,
14    },
15}
16
17/// Account identity, not username or current Space, owns the runtime namespace.
18pub fn plugin_publisher_namespace(publisher_id: &str) -> String {
19    format!(
20        "u-{}",
21        &format!("{:x}", Sha256::digest(publisher_id.as_bytes()))[..32]
22    )
23}
24
25/// Syntactic routing hint only. The signed publisher attestation still owns authorization.
26pub fn is_community_plugin_id(id: &str) -> bool {
27    let Some(rest) = id.strip_prefix("u-") else {
28        return false;
29    };
30    let Some((namespace, slug)) = rest.split_once('-') else {
31        return false;
32    };
33    namespace.len() == 32
34        && namespace
35            .bytes()
36            .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
37        && id.len() <= 80
38        && slug.starts_with(|c: char| c.is_ascii_lowercase())
39        && slug
40            .bytes()
41            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
42}
43
44impl PluginPublication {
45    pub fn validate(&self, definition: &crate::PluginDefinition) -> Result<(), String> {
46        let Self::Community {
47            publisher_id,
48            integrations,
49        } = self;
50        if publisher_id.is_empty()
51            || publisher_id.len() > 256
52            || publisher_id.trim() != publisher_id
53            || definition.kind != crate::PluginKind::Extension
54        {
55            return Err("Invalid community Plugin publisher or kind".into());
56        }
57        let prefix = format!("{}-", plugin_publisher_namespace(publisher_id));
58        let slug = definition
59            .id
60            .strip_prefix(&prefix)
61            .filter(|v| !v.is_empty() && v.starts_with(|c: char| c.is_ascii_lowercase()))
62            .ok_or("Community Plugin does not belong to its publisher namespace")?;
63        if !slug
64            .bytes()
65            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
66        {
67            return Err("Invalid community Plugin name".into());
68        }
69        if integrations.len() > 100 {
70            return Err("Too many Plugin Integration packages".into());
71        }
72        let mut unique = std::collections::BTreeSet::new();
73        for id in integrations {
74            let Some((domain, entity)) = id.split_once('.') else {
75                return Err("Invalid Plugin Integration package ID".into());
76            };
77            if id.len() > 240
78                || domain.is_empty()
79                || entity.is_empty()
80                || ![domain, entity].iter().all(|part| {
81                    part.starts_with(|c: char| c.is_ascii_alphabetic())
82                        && part
83                            .bytes()
84                            .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
85                })
86                || !unique.insert(id)
87            {
88                return Err("Invalid or duplicate Plugin Integration package ID".into());
89            }
90        }
91        Ok(())
92    }
93
94    pub fn integrations(&self) -> &[String] {
95        match self {
96            Self::Community { integrations, .. } => integrations,
97        }
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    fn definition(publisher: &str) -> crate::PluginDefinition {
105        let id = format!("{}-garden", plugin_publisher_namespace(publisher));
106        crate::PluginDefinition {
107            node_type: id.clone(),
108            service_id: id.clone(),
109            component_id: format!("node-{id}"),
110            id,
111            kind: crate::PluginKind::Extension,
112            binding_cardinality: crate::NodeBindingCardinality::Single,
113            display_name: "Garden".into(),
114            description: "Example community service".into(),
115            contributions: None,
116        }
117    }
118    #[test]
119    fn account_namespace_and_extension_kind_are_enforced() {
120        let publication = PluginPublication::Community {
121            publisher_id: "publisher-a".into(),
122            integrations: vec!["garden.light".into()],
123        };
124        let mut plugin = definition("publisher-a");
125        plugin.validate().unwrap();
126        publication.validate(&plugin).unwrap();
127        assert!(publication.validate(&definition("publisher-b")).is_err());
128        plugin.kind = crate::PluginKind::Core;
129        assert!(publication.validate(&plugin).is_err());
130        plugin = definition("publisher-a");
131        plugin.id = "camera".into();
132        assert!(publication.validate(&plugin).is_err());
133    }
134    #[test]
135    fn duplicate_or_path_like_integration_references_are_rejected() {
136        for integrations in [
137            vec!["garden.light".into(), "garden.light".into()],
138            vec!["../garden".into()],
139            vec!["garden.light.extra".into()],
140        ] {
141            assert!(PluginPublication::Community {
142                publisher_id: "publisher-a".into(),
143                integrations
144            }
145            .validate(&definition("publisher-a"))
146            .is_err());
147        }
148    }
149}