返回 CodeWhale
tier.rs
1 //! Trust tiers of the extension host.
2 //!
3 //! One process is one trust domain (design §1.5), so the host runs as two
4 //! processes that never share code, state or a data directory:
5 //!
6 //! * **Plugin** (tier 1): reviewed third-party plugins. Owner ids are the
7 //! plugin ids discovery builds (`<scope>/<12 hex>/<name>`). This is the only
8 //! tier serves reviewed third-party code independently of the selected
9 //! builtin MCP protocol backend.
10 //! * **Builtin** (tier 0): Codewhale's own host code, so that it never shares
11 //! a process with third-party code. Owner ids are `host:<module>`. A module
12 //! is admitted by a row of [`BUILTIN_MODULES`], which pins the SHA-256 of its
13 //! source and names each of its tools with the approval the core gives it
14 //! (`Auto` or `Required`). The table is Rust data: nothing a module says
15 //! about itself can lower its approval, and a tool the table does not list is
16 //! `Required`.
17 //!
18 //! The two id spaces cannot meet. A plugin id starts with a scope name and a
19 //! manifest name cannot hold `:`, so discovery never builds a `host:` id;
20 //! [`HostTier::check_owner_id`] is the one place that says so, and the owner
21 //! registry refuses a `host:` id on the plugin tier and any other id on the
22 //! builtin tier (`OwnerRegistry::begin_owner`).
23 //!
24 //! Production pins the MCP SDK module, activated only when a selected Host
25 //! stdio connection asks for it. Plugin-tier frames cannot use proc/* or mcp/*.
26 //! Rust owns launch, exact operation tickets, credentials and decision keys;
27 //! the builtin is a protocol owner, not an execution or approval authority.
28 //! The pinned digest detects changed bytes; it does not sandbox code already
29 //! executing as the current OS user. Sources are embedded and materialized at
30 //! `<bundle dir>/builtin/<module>.mjs` with the host's notices.
31
32 use std::path::{Path, PathBuf};
33
34 pub use codewhale_plugins::host_services::PluginCohort;
35
36 use super::protocol::DshService;
37 use crate::tools::spec::ApprovalRequirement;
38
39 /// Every tier-0 owner id starts with this: `host:<module>`.
40 pub const HOST_OWNER_PREFIX: &str = "host:";
41
42 /// Which of the two host processes something belongs to. Also the wire value
43 /// of `host/hello.tier` and of a method's tier allow-list
44 /// (`protocol::MethodSpec::tiers`).
45 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
46 #[cfg_attr(test, derive(schemars::JsonSchema))]
47 #[serde(rename_all = "lowercase")]
48 pub enum HostTier {
49 /// Codewhale's own host code (tier 0).
50 Builtin,
51 /// Reviewed third-party plugins (tier 1).
52 Plugin,
53 }
54
55 impl HostTier {
56 /// Plugin first for ordinary extension discovery; builtin stays separate.
57 pub const ALL: [Self; 2] = [Self::Plugin, Self::Builtin];
58
59 /// The value of `--tier=` and of the data directory's name.
60 #[must_use]
61 pub fn name(self) -> &'static str {
62 match self {
63 Self::Builtin => "builtin",
64 Self::Plugin => "plugin",
65 }
66 }
67
68 /// The argument the core launches this tier's host with.
69 #[must_use]
70 pub fn argv_flag(self) -> String {
71 format!("--tier={}", self.name())
72 }
73
74 /// How diagnostics and errors name this tier's host process.
75 #[must_use]
76 pub fn host_label(self) -> &'static str {
77 match self {
78 Self::Builtin => "built-in plugin host",
79 Self::Plugin => "plugin host",
80 }
81 }
82
83 /// The tier an owner id belongs to. Total: the id decides.
84 #[must_use]
85 pub fn of_owner_id(owner_id: &str) -> Self {
86 if owner_id.starts_with(HOST_OWNER_PREFIX) {
87 Self::Builtin
88 } else {
89 Self::Plugin
90 }
91 }
92
93 /// Whether `owner_id` may be an owner on this tier, or why not.
94 pub fn check_owner_id(self, owner_id: &str) -> Result<(), String> {
95 match self {
96 Self::Plugin if owner_id.starts_with(HOST_OWNER_PREFIX) => Err(format!(
97 "`{owner_id}` is in the built-in host namespace (`{HOST_OWNER_PREFIX}<module>`); a plugin id can never use it"
98 )),
99 Self::Plugin => Ok(()),
100 Self::Builtin => match owner_id.strip_prefix(HOST_OWNER_PREFIX) {
101 Some(module) if valid_module_id(module) => Ok(()),
102 _ => Err(format!(
103 "`{owner_id}` is not a built-in host module id: the built-in tier takes only `{HOST_OWNER_PREFIX}<module>` (a lower-case module name of letters, digits and `-`)"
104 )),
105 },
106 }
107 }
108 }
109
110 #[derive(Debug, Clone, serde::Serialize)]
111 #[serde(tag = "kind", rename_all = "snake_case")]
112 pub enum HostCohort {
113 Builtin,
114 Plugin(PluginCohort),
115 }
116
117 impl PartialEq for HostCohort {
118 fn eq(&self, other: &Self) -> bool {
119 match (self, other) {
120 (Self::Builtin, Self::Builtin) => true,
121 (Self::Plugin(a), Self::Plugin(b)) => a == b,
122 _ => false,
123 }
124 }
125 }
126
127 impl Eq for HostCohort {}
128
129 impl Ord for HostCohort {
130 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
131 self.sort_key().cmp(&other.sort_key())
132 }
133 }
134
135 impl PartialOrd for HostCohort {
136 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
137 Some(self.cmp(other))
138 }
139 }
140
141 impl std::hash::Hash for HostCohort {
142 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
143 match self {
144 Self::Builtin => 0u8.hash(state),
145 Self::Plugin(p) => {
146 1u8.hash(state);
147 p.hash(state);
148 }
149 }
150 }
151 }
152
153 impl HostCohort {
154 pub const BUILTIN: Self = Self::Builtin;
155
156 fn sort_key(&self) -> (u8, Option<&PluginCohort>) {
157 match self {
158 Self::Builtin => (0u8, None),
159 Self::Plugin(p) => (1u8, Some(p)),
160 }
161 }
162
163 #[must_use]
164 pub fn reviewed() -> Self {
165 Self::Plugin(PluginCohort::Reviewed)
166 }
167
168 #[must_use]
169 pub fn agent(workspace: impl AsRef<Path>) -> Self {
170 Self::Plugin(PluginCohort::agent(workspace))
171 }
172
173 #[must_use]
174 pub fn from_plugin_cohort(cohort: PluginCohort) -> Self {
175 match cohort {
176 PluginCohort::Reviewed => Self::Plugin(PluginCohort::Reviewed),
177 PluginCohort::Agent { workspace } => Self::agent(workspace),
178 }
179 }
180
181 #[must_use]
182 pub fn tier(&self) -> HostTier {
183 match self {
184 Self::Builtin => HostTier::Builtin,
185 Self::Plugin(_) => HostTier::Plugin,
186 }
187 }
188
189 #[must_use]
190 pub fn is_builtin(&self) -> bool {
191 matches!(self, Self::Builtin)
192 }
193
194 #[must_use]
195 pub fn is_reviewed(&self) -> bool {
196 matches!(self, Self::Plugin(PluginCohort::Reviewed))
197 }
198
199 #[must_use]
200 pub fn host_label(&self) -> &'static str {
201 self.tier().host_label()
202 }
203
204 #[must_use]
205 pub fn plugin_cohort(&self) -> Option<&PluginCohort> {
206 match self {
207 Self::Plugin(cohort) => Some(cohort),
208 Self::Builtin => None,
209 }
210 }
211
212 #[must_use]
213 pub fn agent_workspace(&self) -> Option<&str> {
214 match self {
215 Self::Plugin(PluginCohort::Agent { workspace }) => Some(workspace.as_str()),
216 _ => None,
217 }
218 }
219
220 #[must_use]
221 pub fn agent_project_path(&self) -> Option<PathBuf> {
222 match self {
223 Self::Plugin(PluginCohort::Agent { workspace }) => Some(
224 codewhale_config::normalize_project_workspace(Path::new(workspace))
225 .unwrap_or_else(|_| Path::new(workspace).components().collect()),
226 ),
227 _ => None,
228 }
229 }
230 }
231
232 impl From<PluginCohort> for HostCohort {
233 fn from(cohort: PluginCohort) -> Self {
234 Self::from_plugin_cohort(cohort)
235 }
236 }
237
238 impl From<&HostCohort> for HostCohort {
239 fn from(cohort: &HostCohort) -> Self {
240 cohort.clone()
241 }
242 }
243
244 impl std::fmt::Display for HostCohort {
245 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246 match self {
247 Self::Builtin => write!(f, "builtin"),
248 Self::Plugin(PluginCohort::Reviewed) => write!(f, "reviewed"),
249 Self::Plugin(PluginCohort::Agent { workspace }) => {
250 write!(f, "agent:{workspace}")
251 }
252 }
253 }
254 }
255
256 /// `^[a-z][a-z0-9-]{0,63}$`: a module name is also a file name and a
257 /// directory name, so it is as plain as one.
258 fn valid_module_id(module: &str) -> bool {
259 let mut chars = module.chars();
260 matches!(chars.next(), Some(first) if first.is_ascii_lowercase())
261 && module.len() <= 64
262 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
263 }
264
265 /// One tool of a built-in module and the approval the core gives it: `Auto` or
266 /// `Required` (the core's own [`ApprovalRequirement`]; [`tool_approval`] reads
267 /// anything but `Auto` as `Required`). Only this table can say `Auto`.
268 #[derive(Debug)]
269 pub struct Tier0Tool {
270 pub name: &'static str,
271 pub approval: ApprovalRequirement,
272 }
273
274 /// One built-in host module: Codewhale's own code, pinned.
275 #[derive(Debug)]
276 pub struct BuiltinModule {
277 /// The module name; its owner id is `host:<id>`.
278 pub id: &'static str,
279 /// SHA-256 (lower-case hex) of the module's source file, as the host
280 /// build records it in `dist/builtin-modules.json`. The core refuses to
281 /// activate a file with any other digest.
282 pub source_sha256: &'static str,
283 pub tools: &'static [Tier0Tool],
284 pub services: &'static [DshService],
285 }
286
287 impl BuiltinModule {
288 /// The owner id this module activates under.
289 #[must_use]
290 pub fn owner_id(&self) -> String {
291 format!("{HOST_OWNER_PREFIX}{}", self.id)
292 }
293 }
294
295 /// The built-in modules the core pins. MCP is started only by the explicit
296 /// Host SDK backend. The host build records the same digest; the drift
297 /// test refuses any row/file mismatch.
298 pub static BUILTIN_MODULES: &[BuiltinModule] = &[
299 BuiltinModule {
300 id: "harness",
301 source_sha256: "752ee45d5233098b7acfd960358ac9a87b9275b7d3a27ab08d0e5ffb989575e1",
302 tools: &[],
303 services: &[],
304 },
305 BuiltinModule {
306 id: "mcp",
307 source_sha256: "f9735707e49e349ee38f791fa3c6f3379fde43cad5044f381f8e313286ea3d39",
308 tools: &[],
309 services: &[],
310 },
311 BuiltinModule {
312 id: "creator",
313 source_sha256: "6035ac7b20b16f39d671d9f136cd291e3613f320bc8e71344e524727287ea61e",
314 tools: &[
315 Tier0Tool {
316 name: "cordis_inspect_list",
317 approval: ApprovalRequirement::Auto,
318 },
319 Tier0Tool {
320 name: "cordis_inspect_query",
321 approval: ApprovalRequirement::Auto,
322 },
323 Tier0Tool {
324 name: "plugin_manager",
325 approval: ApprovalRequirement::Required,
326 },
327 ],
328 services: &[DshService::Plugins],
329 },
330 ];
331
332 /// The approval for `tool` of the module that owns `owner_id`, from `modules`
333 /// and nowhere else: `Auto` only where a row says so, `Required` for a module
334 /// or tool the table does not list and for any row that says anything else.
335 #[must_use]
336 pub fn tool_approval(modules: &[BuiltinModule], owner_id: &str, tool: &str) -> ApprovalRequirement {
337 let listed = owner_id
338 .strip_prefix(HOST_OWNER_PREFIX)
339 .and_then(|module_id| modules.iter().find(|module| module.id == module_id))
340 .and_then(|module| module.tools.iter().find(|listed| listed.name == tool));
341 match listed {
342 Some(Tier0Tool {
343 approval: ApprovalRequirement::Auto,
344 ..
345 }) => ApprovalRequirement::Auto,
346 _ => ApprovalRequirement::Required,
347 }
348 }
349
350 #[cfg(test)]
351 mod tests {
352 use std::collections::BTreeMap;
353
354 use super::*;
355
356 /// The host build (`extension-host/build.mjs`) writes the digest of every
357 /// built-in module's source to `dist/builtin-modules.json`; the Rust table
358 /// must say exactly the same, both ways: a module with no row, a row with
359 /// no module and a changed source all fail here. Same pattern as the
360 /// generated-protocol drift test in `protocol/tests.rs`, except the build
361 /// is the source of truth, so the fix is to update the table.
362 #[test]
363 fn table_matches_the_host_build() {
364 let built: serde_json::Value = serde_json::from_str(include_str!(
365 "../../extension-host/dist/builtin-modules.json"
366 ))
367 .expect("dist/builtin-modules.json is JSON");
368 let built: BTreeMap<String, String> = built["modules"]
369 .as_object()
370 .expect("`modules` is an object")
371 .iter()
372 .map(|(id, digest)| (id.clone(), digest.as_str().expect("a digest").to_string()))
373 .collect();
374 let table: BTreeMap<String, String> = BUILTIN_MODULES
375 .iter()
376 .map(|module| (module.id.to_string(), module.source_sha256.to_string()))
377 .collect();
378 assert_eq!(
379 table.len(),
380 BUILTIN_MODULES.len(),
381 "BUILTIN_MODULES lists a module twice"
382 );
383 assert_eq!(
384 table, built,
385 "BUILTIN_MODULES and crates/engine/extension-host/dist/builtin-modules.json disagree. \
386 Rebuild the host (`npm run build` in crates/engine/extension-host) and make the table \
387 list exactly the modules and digests the build recorded."
388 );
389 }
390
391 #[test]
392 fn every_row_is_well_formed() {
393 for module in BUILTIN_MODULES {
394 assert!(valid_module_id(module.id), "{}", module.id);
395 assert!(
396 module.source_sha256.len() == 64
397 && module
398 .source_sha256
399 .bytes()
400 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
401 "{}: not a lower-case SHA-256",
402 module.id
403 );
404 assert_eq!(HostTier::of_owner_id(&module.owner_id()), HostTier::Builtin);
405 }
406 }
407
408 #[test]
409 fn the_two_id_spaces_cannot_meet() {
410 assert!(
411 HostTier::Plugin
412 .check_owner_id("user/0123456789ab/demo")
413 .is_ok()
414 );
415 assert!(HostTier::Plugin.check_owner_id("a").is_ok());
416 assert!(HostTier::Builtin.check_owner_id("host:mcp").is_ok());
417 for host_id in ["host:mcp", "host:", "host:evil name"] {
418 let refused = HostTier::Plugin.check_owner_id(host_id).unwrap_err();
419 assert!(
420 refused.contains("a plugin id can never use it"),
421 "{refused}"
422 );
423 }
424 for id in [
425 "user/0123456789ab/demo",
426 "mcp",
427 "host",
428 "host:",
429 "host:UPPER",
430 "host:../x",
431 "host:a/b",
432 "HOST:mcp",
433 ] {
434 let refused = HostTier::Builtin.check_owner_id(id).unwrap_err();
435 assert!(
436 refused.contains("not a built-in host module id"),
437 "{id}: {refused}"
438 );
439 }
440 assert_eq!(HostTier::of_owner_id("host:mcp"), HostTier::Builtin);
441 assert_eq!(
442 HostTier::of_owner_id("user/0123456789ab/demo"),
443 HostTier::Plugin
444 );
445 }
446
447 #[test]
448 fn a_tier_zero_tool_is_required_unless_the_table_says_otherwise() {
449 const TOOLS: &[Tier0Tool] = &[
450 Tier0Tool {
451 name: "open",
452 approval: ApprovalRequirement::Auto,
453 },
454 Tier0Tool {
455 name: "write",
456 approval: ApprovalRequirement::Required,
457 },
458 Tier0Tool {
459 name: "suggest",
460 approval: ApprovalRequirement::Suggest,
461 },
462 ];
463 let table = [BuiltinModule {
464 id: "demo",
465 source_sha256: "0000000000000000000000000000000000000000000000000000000000000000",
466 tools: TOOLS,
467 services: &[],
468 }];
469 assert_eq!(
470 tool_approval(&table, "host:demo", "open"),
471 ApprovalRequirement::Auto
472 );
473 assert_eq!(
474 tool_approval(&table, "host:demo", "write"),
475 ApprovalRequirement::Required
476 );
477 // Only `Auto` lowers anything: any other row reads as `Required`.
478 assert_eq!(
479 tool_approval(&table, "host:demo", "suggest"),
480 ApprovalRequirement::Required
481 );
482 // Unlisted tool, unlisted module, and an id that is not tier 0 at all.
483 assert_eq!(
484 tool_approval(&table, "host:demo", "other"),
485 ApprovalRequirement::Required
486 );
487 assert_eq!(
488 tool_approval(&table, "host:other", "open"),
489 ApprovalRequirement::Required
490 );
491 assert_eq!(
492 tool_approval(&table, "demo", "open"),
493 ApprovalRequirement::Required
494 );
495 assert_eq!(
496 tool_approval(&[], "host:demo", "open"),
497 ApprovalRequirement::Required
498 );
499 }
500
501 #[test]
502 fn only_the_creator_row_names_a_service() {
503 let with_services: Vec<&str> = BUILTIN_MODULES
504 .iter()
505 .filter(|module| !module.services.is_empty())
506 .map(|module| module.id)
507 .collect();
508 assert_eq!(with_services, ["creator"]);
509 assert_eq!(
510 BUILTIN_MODULES
511 .iter()
512 .find(|module| module.id == "creator")
513 .map(|module| module.services),
514 Some(&[DshService::Plugins][..])
515 );
516 }
517 }
518
519 #[cfg(test)]
520 #[path = "creator_tests.rs"]
521 mod creator_tests;
522
522 lines RUST