返回 CodeWhale
native_presets.rs
根目录 / crates / plugins / src / native_presets.rs
1 //! Pure roster facts tied to existing Native entry receipts. No new profile,
2 //! session, filesystem root or writable catalog authority.
3 use super::{PluginRegistry, activation::PluginActivationCapability};
4 use crate::composition_scope::NativePresetRef;
5 use codewhale_config::EntryRef;
6 use serde::Deserialize;
7 use std::collections::{BTreeMap, BTreeSet};
8 use std::io::Read;
9 use std::path::Path;
10
11 const MARKER: &str = "// codewhale-native-preset-v1 ";
12 const MAX_ENTRY: u64 = 16 * 1024;
13
14 #[derive(Debug, Clone, Deserialize)]
15 #[serde(deny_unknown_fields)]
16 pub struct NativePresetMetadata {
17 pub id: String,
18 pub trust: String,
19 pub name: Option<String>,
20 pub description: Option<String>,
21 pub order: Option<f64>,
22 pub is_default: bool,
23 pub broken: Option<String>,
24 }
25
26 pub fn metadata_from_bytes(bytes: &[u8]) -> Option<NativePresetMetadata> {
27 let source = std::str::from_utf8(bytes).ok()?;
28 let first = source.lines().next()?.strip_prefix(MARKER)?;
29 let data: NativePresetMetadata = serde_json::from_str(first).ok()?;
30 if data.id.is_empty()
31 || data.id.len() > 64
32 || !data.id.as_bytes()[0].is_ascii_alphanumeric()
33 || !data
34 .id
35 .bytes()
36 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
37 || !matches!(data.trust.as_str(), "system" | "user")
38 || data.name.as_ref().is_some_and(|v| v.len() > 4096)
39 || data
40 .description
41 .as_ref()
42 .is_some_and(|v| v.len() > 16 * 1024)
43 || data.order.is_some_and(|v| !v.is_finite())
44 || data.broken.is_some()
45 {
46 return None;
47 }
48 Some(data)
49 }
50
51 pub fn metadata(
52 plugins: &PluginRegistry,
53 preset: &NativePresetRef,
54 ) -> Option<NativePresetMetadata> {
55 let plugin = plugins.get(&preset.plugin_id)?;
56 if plugin.content_hash != preset.content_hash
57 || !plugin.component_active(PluginActivationCapability::Native)
58 {
59 return None;
60 }
61 let root = plugin.staged_root.as_deref()?;
62 let finalized = super::registry::verify_finalized_stage_root(root, None).ok()?;
63 let path = Path::new(&preset.entry.path);
64 // Reuse the sole discovery-to-stage translator: it resolves both the
65 // root and entry, proves confinement and requires an actual Native entry.
66 if !plugin.components.native.iter().any(|source| {
67 super::runtime::staged_component_path(&plugin.canonical_root, root, source)
68 .is_ok_and(|admitted| admitted == path)
69 }) {
70 return None;
71 }
72 let mut file = codewhale_util::bundle_file::open_bundle_file(path).ok()?;
73 let mut bytes = Vec::new();
74 file.by_ref()
75 .take(MAX_ENTRY + 1)
76 .read_to_end(&mut bytes)
77 .ok()?;
78 if bytes.len() > MAX_ENTRY as usize
79 || codewhale_runtime::hashing::sha256_hex(&bytes) != preset.entry.sha256
80 {
81 return None;
82 }
83 super::registry::verify_finalized_stage_root(root, Some(&finalized)).ok()?;
84 metadata_from_bytes(&bytes)
85 }
86
87 fn reviewed_entry(
88 source: &super::runtime::PluginComponentSource,
89 checked: &mut BTreeMap<String, Option<super::manifest::ValidatedManifest>>,
90 ) -> Option<NativePresetRef> {
91 let id = source.authority.plugin_id.to_string();
92 let receipt = checked.entry(id.clone()).or_insert_with(|| {
93 let validated =
94 super::manifest::PluginManifest::validate_from_path(&source.authority.staged_manifest)
95 .ok()?;
96 (validated.content_hash == source.authority.content_hash
97 && validated.capability_hash == source.authority.capability_hash)
98 .then_some(validated)
99 });
100 let receipt = receipt.as_ref()?;
101 // Component paths and the validated receipt share canonical identity;
102 // the selected manifest's lexical alias is not a containment root.
103 let relative = source.path.strip_prefix(&receipt.canonical_root).ok()?;
104 Some(NativePresetRef {
105 plugin_id: id,
106 content_hash: source.authority.content_hash.clone(),
107 entry: EntryRef {
108 path: source.path.to_string_lossy().into_owned(),
109 sha256: receipt.native_entry_hashes.get(relative)?.clone(),
110 },
111 })
112 }
113
114 /// New roster choices come from a whole admitted bundle validation, not a
115 /// fresh hash of an unmounted mutable file mistaken for a reviewed receipt.
116 pub fn admitted_entries(
117 plugins: &PluginRegistry,
118 ) -> Vec<(
119 NativePresetRef,
120 NativePresetMetadata,
121 codewhale_config::PluginAuthority,
122 )> {
123 let (sources, _) =
124 super::runtime::active_component_sources(plugins, PluginActivationCapability::Native);
125 let mut checked = BTreeMap::new();
126 let mut result = Vec::new();
127 for source in sources {
128 // Ordinary Native modules have no catalog metadata; do not rehash
129 // their whole bundles just to rediscover their existing roster view.
130 // active_component_sources already validated the authority and used
131 // the shared translator to prove this canonical entry is confined.
132 let Ok(mut file) = codewhale_util::bundle_file::open_bundle_file(&source.path) else {
133 continue;
134 };
135 let mut header = Vec::new();
136 if file
137 .by_ref()
138 .take(MAX_ENTRY + 1)
139 .read_to_end(&mut header)
140 .is_err()
141 || header.len() > MAX_ENTRY as usize
142 || metadata_from_bytes(&header).is_none()
143 {
144 continue;
145 }
146 let Some(preset) = reviewed_entry(&source, &mut checked) else {
147 continue;
148 };
149 if let Some(data) = metadata(plugins, &preset) {
150 result.push((preset, data, source.authority));
151 }
152 }
153 result
154 }
155
156 /// One caller snapshot: each raw catalog chooses one default; ordinary Native
157 /// plugins keep their existing complete entry set. The manager may own a union
158 /// across callers but no caller receives a union of that catalog's presets.
159 pub fn default_selection(plugins: &PluginRegistry) -> (Vec<NativePresetRef>, BTreeSet<String>) {
160 let (sources, _) =
161 super::runtime::active_component_sources(plugins, PluginActivationCapability::Native);
162 let admitted = admitted_entries(plugins);
163 if admitted.is_empty() {
164 return (Vec::new(), BTreeSet::new());
165 }
166 let mut normal = Vec::new();
167 let mut catalogs: BTreeMap<String, Vec<(NativePresetRef, NativePresetMetadata)>> =
168 BTreeMap::new();
169 for (preset, data, _) in admitted {
170 catalogs
171 .entry(preset.plugin_id.clone())
172 .or_default()
173 .push((preset, data));
174 }
175 let mut checked = BTreeMap::new();
176 for source in sources {
177 if catalogs.contains_key(source.authority.plugin_id.as_str()) {
178 continue;
179 }
180 if let Some(entry) = reviewed_entry(&source, &mut checked) {
181 normal.push(entry);
182 }
183 }
184 if catalogs.is_empty() {
185 return (Vec::new(), BTreeSet::new());
186 }
187 let mut unselected = BTreeSet::new();
188 for (id, rows) in catalogs {
189 if let Some((preset, _)) = rows.into_iter().find(|(_, data)| data.is_default) {
190 normal.push(preset);
191 } else {
192 // Absence is upstream data, never permission to mount the first row.
193 unselected.insert(id);
194 }
195 }
196 (normal, unselected)
197 }
198
199 #[cfg(test)]
200 mod tests {
201 use super::*;
202 #[test]
203 fn native_preset_metadata_is_data_and_cannot_mint_trust_or_an_entry() {
204 let good = br#"// codewhale-native-preset-v1 {"id":"reviewer","trust":"user","name":"Repo reviewer","description":"bounded","is_default":true}
205 export function apply() {}"#;
206 assert_eq!(metadata_from_bytes(good).unwrap().id, "reviewer");
207 for source in [
208 r#"{"id":"../escape","trust":"user","is_default":true}"#,
209 r#"{"id":"ok","trust":"admin","is_default":true}"#,
210 r#"{"id":"ok","trust":"user","is_default":true,"entry":{"path":"outside"}}"#,
211 r#"{"id":"ok","trust":"user","is_default":true,"broken":"missing"}"#,
212 ] {
213 assert!(metadata_from_bytes(format!("{MARKER}{source}\n").as_bytes()).is_none());
214 }
215 }
216 }
217
217 lines RUST