返回 CodeWhale
registry.rs
根目录 / crates / plugins / src / registry.rs
1 use std::collections::{BTreeMap, BTreeSet};
2 use std::fs::{self, OpenOptions};
3 use std::io::{Read, Write};
4 use std::path::{Path, PathBuf};
5
6 use serde::{Deserialize, Serialize};
7 use sha2::{Digest, Sha256};
8
9 use super::activation::{PluginActivationCapability, PluginActivationPolicy};
10 use super::host_services::{
11 AgentPosture, HostService, HostServiceLine, HostServiceReview, PersonVia, PluginApprover,
12 PluginCohort, ReviewApproval, ReviewPeer, cohort_of,
13 };
14 use super::managed_policy::{
15 ManagedPluginPolicy, ManagedPolicyOutcome, load_managed_policy, resolve_managed_policy_path,
16 };
17 use super::manifest::PluginInventory;
18 use super::types::{
19 LoadedPlugin, PluginDiagnostic, PluginDiagnosticLevel, PluginReviewEntry, PluginScope,
20 PluginTrustStatus,
21 };
22 use codewhale_config::{PluginAuthority, PluginId};
23 use codewhale_util::path_identity::metadata_is_link_or_reparse;
24 #[cfg(windows)]
25 use codewhale_util::path_identity::windows_file_identity;
26
27 pub mod gc;
28 mod withdrawn;
29
30 const STATE_SCHEMA_VERSION: u32 = 1;
31 const MAX_REVIEW_HISTORY: usize = 32;
32 const RECEIPT_VERSION: u32 = 2;
33
34 #[derive(Debug, Clone, Serialize, Deserialize)]
35 #[serde(deny_unknown_fields)]
36 struct PluginStateFile {
37 schema_version: u32,
38 #[serde(default)]
39 plugins: BTreeMap<PluginId, PersistedPluginState>,
40 }
41
42 impl Default for PluginStateFile {
43 fn default() -> Self {
44 Self {
45 schema_version: STATE_SCHEMA_VERSION,
46 plugins: BTreeMap::new(),
47 }
48 }
49 }
50
51 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
52 #[serde(deny_unknown_fields)]
53 struct PersistedPluginState {
54 #[serde(default)]
55 generation: u64,
56 #[serde(default)]
57 enabled: bool,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 enabled_by: Option<PluginApprover>,
60 #[serde(default)]
61 trust: Option<TrustReceipt>,
62 #[serde(default)]
63 review_history: Vec<TrustReceipt>,
64 }
65
66 #[derive(Debug, Clone, Serialize, Deserialize)]
67 #[serde(deny_unknown_fields)]
68 struct TrustReceipt {
69 content_hash: String,
70 capability_hash: String,
71 reviewed_capabilities: PluginInventory,
72 reviewed_at: String,
73 #[serde(default, skip_serializing_if = "receipt_version_is_unset")]
74 version: u32,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 approved_by: Option<PluginApprover>,
77 #[serde(default, skip_serializing_if = "Vec::is_empty")]
78 host_services: Vec<HostService>,
79 }
80
81 fn receipt_version_is_unset(version: &u32) -> bool {
82 *version == 0
83 }
84
85 impl TrustReceipt {
86 fn granted(&self) -> Vec<HostService> {
87 if self.version != RECEIPT_VERSION
88 || self.host_services.is_empty()
89 || !self
90 .host_services
91 .iter()
92 .all(|service| self.reviewed_capabilities.host_services.contains(service))
93 || super::manifest::hash_inventory(&self.reviewed_capabilities) != self.capability_hash
94 {
95 return Vec::new();
96 }
97 let mut granted = self.host_services.clone();
98 granted.sort();
99 granted.dedup();
100 granted
101 }
102 }
103
104 fn trust_receipt_matches(expected: Option<&TrustReceipt>, current: Option<&TrustReceipt>) -> bool {
105 match (expected, current) {
106 (None, None) => true,
107 (Some(expected), Some(current)) => {
108 expected.content_hash == current.content_hash
109 && expected.capability_hash == current.capability_hash
110 && expected.approved_by == current.approved_by
111 }
112 _ => false,
113 }
114 }
115
116 fn peer_name(id: &PluginId, names: &BTreeMap<PluginId, String>) -> String {
117 names.get(id).cloned().unwrap_or_else(|| {
118 id.as_str()
119 .rsplit('/')
120 .next()
121 .unwrap_or_default()
122 .to_string()
123 })
124 }
125
126 fn host_service_review_in(
127 state: &PluginStateFile,
128 plugin: &LoadedPlugin,
129 names: &BTreeMap<PluginId, String>,
130 cohort: &PluginCohort,
131 ) -> HostServiceReview {
132 let peers = |holds: bool, service: HostService| -> Vec<ReviewPeer> {
133 state
134 .plugins
135 .iter()
136 .filter(|(id, _)| **id != plugin.id)
137 .filter(|(_, entry)| {
138 entry.trust.as_ref().is_some_and(|receipt| {
139 if cohort_of(receipt.approved_by.as_ref()) != *cohort {
140 return false;
141 }
142 if holds {
143 receipt.granted().contains(&service)
144 } else {
145 entry.enabled
146 && receipt.reviewed_capabilities.native > 0
147 && !receipt.granted().contains(&service)
148 }
149 })
150 })
151 .map(|(id, _)| ReviewPeer {
152 id: id.as_str().to_string(),
153 name: peer_name(id, names),
154 })
155 .collect()
156 };
157 let lines = plugin
158 .inventory
159 .host_services
160 .iter()
161 .map(|service| HostServiceLine {
162 service: *service,
163 offered: super::host_services::offered(*service),
164 shared_with: peers(true, *service),
165 withheld_by: peers(false, *service),
166 })
167 .collect();
168 HostServiceReview::new(
169 plugin.id.as_str(),
170 &plugin.content_hash,
171 &plugin.capability_hash,
172 cohort,
173 lines,
174 )
175 }
176
177 fn check_approver(
178 approver: &PluginApprover,
179 plugin: &LoadedPlugin,
180 workspace: &Path,
181 shown: bool,
182 ) -> Result<(), String> {
183 let agent = match approver {
184 PluginApprover::Agent(agent) => agent,
185 PluginApprover::CommandLine if shown => {
186 return Err(
187 "An approval from the command line shows no review, so it cannot grant host services"
188 .to_string(),
189 );
190 }
191 PluginApprover::Person { .. } | PluginApprover::CommandLine => return Ok(()),
192 };
193 if !shown {
194 return Err(
195 "An approval by the agent must carry the token of the review composed for the call"
196 .to_string(),
197 );
198 }
199 let identified = |value: &Option<String>| value.as_deref().is_some_and(|id| !id.is_empty());
200 if matches!(
201 agent.posture,
202 AgentPosture::FullAccess | AgentPosture::AutoReview
203 ) && !(identified(&agent.thread_id)
204 && identified(&agent.turn_id)
205 && identified(&agent.tool_call_id))
206 {
207 return Err(
208 "An approval by the agent must name the thread, turn and tool call that made it"
209 .to_string(),
210 );
211 }
212 let normalized_agent =
213 codewhale_config::normalize_project_workspace(Path::new(&agent.workspace));
214 let normalized_target = codewhale_config::normalize_project_workspace(workspace);
215 let workspaces_match = match (&normalized_agent, &normalized_target) {
216 (Ok(a), Ok(b)) => a == b,
217 _ => Path::new(&agent.workspace) == workspace,
218 };
219 if agent.workspace.is_empty() || !workspaces_match {
220 return Err(
221 "An approval by the agent is limited to its own project, and this is not that project"
222 .to_string(),
223 );
224 }
225 if plugin.scope == PluginScope::Builtin {
226 return Err(
227 "A built-in plugin ships with Codewhale, so the agent cannot approve it; ask the person"
228 .to_string(),
229 );
230 }
231 if plugin.trusted()
232 && plugin
233 .approved_by
234 .as_ref()
235 .and_then(PluginApprover::agent_workspace)
236 .is_none()
237 {
238 return Err(format!(
239 "Plugin bundle `{}` holds a review for every project, so the agent cannot replace it; ask the person",
240 plugin.name()
241 ));
242 }
243 if plugin.trusted() && plugin.outside_reach {
244 return Err(format!(
245 "Plugin bundle `{}` holds the review of the agent of another project, so this agent cannot replace it; ask the person",
246 plugin.name()
247 ));
248 }
249 if plugin.scope == PluginScope::Workspace {
250 let inside = fs::canonicalize(workspace)
251 .is_ok_and(|project| plugin.canonical_root.starts_with(project));
252 if !inside {
253 return Err(format!(
254 "Plugin bundle `{}` is in a project plugin folder that resolves outside this project, so the agent cannot approve it; ask the person",
255 plugin.name()
256 ));
257 }
258 }
259 Ok(())
260 }
261
262 fn outside_reach(approver: Option<&PluginApprover>, workspace: &Path) -> bool {
263 approver
264 .and_then(PluginApprover::agent_workspace)
265 .is_some_and(|recorded| {
266 if recorded.is_empty() {
267 return true;
268 }
269 let norm_recorded = codewhale_config::normalize_project_workspace(Path::new(recorded));
270 let norm_target = codewhale_config::normalize_project_workspace(workspace);
271 match (norm_recorded, norm_target) {
272 (Ok(a), Ok(b)) => a != b,
273 _ => Path::new(recorded) != workspace,
274 }
275 })
276 }
277
278 #[derive(Debug, Clone, Default)]
279 pub struct PluginRegistry {
280 plugins: BTreeMap<PluginId, LoadedPlugin>,
281 names: BTreeMap<String, PluginId>,
282 diagnostics: Vec<PluginDiagnostic>,
283 state: PluginStateFile,
284 state_path: Option<PathBuf>,
285 state_error: Option<String>,
286 managed_policy: Option<ManagedPluginPolicy>,
287 managed_policy_path: Option<PathBuf>,
288 managed_policy_error: Option<String>,
289 workspace: PathBuf,
290 discovery_context: Option<std::sync::Arc<super::context::PluginDiscoveryContext>>,
291 catalog_stamp: super::discovery::PluginCatalogStamp,
292 /// Ephemeral caller binding, never persisted in plugin state.
293 caller_selection: Option<crate::composition_scope::SelectionRevision>,
294 selected_native_entries: Vec<crate::composition_scope::NativePresetRef>,
295 /// Catalog-only Native owners with no upstream default. Ephemeral caller
296 /// selection data; an empty entry list must not broaden these owners.
297 unselected_native_catalogs: BTreeSet<String>,
298 }
299
300 impl PluginRegistry {
301 #[must_use]
302 pub fn new() -> Self {
303 Self::default()
304 }
305
306 pub fn caller_selection(&self) -> Option<crate::composition_scope::SelectionRevision> {
307 self.caller_selection
308 }
309 pub fn bind_caller(&self, revision: crate::composition_scope::SelectionRevision) -> Self {
310 let mut view = self.clone();
311 view.caller_selection = Some(revision);
312 view
313 }
314 pub fn selected_native_entries(&self) -> &[crate::composition_scope::NativePresetRef] {
315 &self.selected_native_entries
316 }
317 /// Keep a narrowed selector across rediscovery even when its receipt is now
318 /// invalid. Desired-owner admission then withdraws it; failure must never
319 /// widen this caller back to every Native entry.
320 pub fn retain_native_selection_from(&self, previous: &Self) -> Self {
321 let mut view = self.clone();
322 if !previous.selected_native_entries.is_empty()
323 || !previous.unselected_native_catalogs.is_empty()
324 {
325 view.selected_native_entries = previous.selected_native_entries.clone();
326 view.unselected_native_catalogs = previous.unselected_native_catalogs.clone();
327 }
328 view
329 }
330
331 pub fn sync_user_plugins_from(&self, updated: &Self) -> Option<Self> {
332 if self.workspace == updated.workspace
333 || self.user_plugins_dir().is_none()
334 || self.user_plugins_dir() != updated.user_plugins_dir()
335 || self.state_path.is_none()
336 || self.state_path != updated.state_path
337 {
338 return None;
339 }
340 let summary = |reg: &Self| {
341 reg.plugins
342 .iter()
343 .map(|(id, p)| {
344 (
345 id.clone(),
346 p.scope,
347 p.content_hash.clone(),
348 p.capability_hash.clone(),
349 p.state_generation,
350 p.enabled,
351 p.trust_status,
352 p.outside_reach,
353 )
354 })
355 .collect::<Vec<_>>()
356 };
357 let before = summary(self);
358 let mut candidates: Vec<LoadedPlugin> = self
359 .plugins
360 .values()
361 .filter(|p| p.scope != PluginScope::User)
362 .cloned()
363 .chain(
364 updated
365 .plugins
366 .values()
367 .filter(|p| p.scope == PluginScope::User)
368 .cloned(),
369 )
370 .collect();
371 candidates.sort_by(|left, right| {
372 left.scope
373 .cmp(&right.scope)
374 .then_with(|| left.name().cmp(right.name()))
375 .then_with(|| left.canonical_root.cmp(&right.canonical_root))
376 });
377
378 let mut view = self.clone();
379 view.plugins.clear();
380 view.names.clear();
381 let mut seen_roots = BTreeSet::new();
382 let mut seen_names = BTreeSet::new();
383 for plugin in candidates {
384 if !seen_roots.insert(plugin.canonical_root.clone()) {
385 continue;
386 }
387 if !seen_names.insert(plugin.name().to_string()) {
388 continue;
389 }
390 view.register_loaded(plugin);
391 }
392 view.state = updated.state.clone();
393 view.state_error = updated.state_error.clone();
394 view.managed_policy = updated.managed_policy.clone();
395 view.managed_policy_error = updated.managed_policy_error.clone();
396 view.apply_state();
397 let after = summary(&view);
398 if before == after
399 && view.state_error == self.state_error
400 && view.managed_policy_error == self.managed_policy_error
401 {
402 return None;
403 }
404 Some(view)
405 }
406
407 pub fn native_catalog_requires_selection(&self, plugin_id: &str) -> bool {
408 self.unselected_native_catalogs.contains(plugin_id)
409 }
410
411 pub fn native_entry_selected(&self, plugin_id: &str, path: &str, sha256: &str) -> bool {
412 if self.unselected_native_catalogs.contains(plugin_id) {
413 return false;
414 }
415 if self.selected_native_entries.is_empty() {
416 return true;
417 }
418 self.selected_native_entries.iter().any(|selected| {
419 selected.plugin_id == plugin_id
420 && selected.entry.path == path
421 && selected.entry.sha256 == sha256
422 && self
423 .get(plugin_id)
424 .is_some_and(|plugin| plugin.content_hash == selected.content_hash)
425 })
426 }
427
428 /// Select one reviewed Native inventory entry. No additional Agent capability.
429 pub fn with_native_preset(
430 &self,
431 selected: crate::composition_scope::NativePresetRef,
432 ) -> Result<Self, String> {
433 let (sources, _) =
434 super::runtime::active_component_sources(self, PluginActivationCapability::Native);
435 let source = sources
436 .into_iter()
437 .find(|source| {
438 source.authority.plugin_id.as_str() == selected.plugin_id
439 && source.authority.content_hash == selected.content_hash
440 && source.path.to_string_lossy() == selected.entry.path
441 })
442 .ok_or("Native preset is not in the current reviewed inventory")?;
443 if let Some(problem) = super::runtime::native_entry_problem(&source.path, true) {
444 return Err(problem.into());
445 }
446 let file = codewhale_util::bundle_file::open_bundle_file(&source.path)
447 .map_err(|_| "Native preset cannot be opened")?;
448 let mut bytes = Vec::new();
449 file.take(256 * 1024 * 1024 + 1)
450 .read_to_end(&mut bytes)
451 .map_err(|_| "Native preset cannot be read")?;
452 if bytes.len() > 256 * 1024 * 1024 {
453 return Err("Native preset entry exceeds the bundle limit".into());
454 }
455 if codewhale_runtime::hashing::sha256_hex(&bytes) != selected.entry.sha256 {
456 return Err("Native preset bytes changed".into());
457 }
458 let mut view = self.clone();
459 view.caller_selection = None;
460 view.unselected_native_catalogs.remove(&selected.plugin_id);
461 view.selected_native_entries
462 .retain(|entry| entry.plugin_id != selected.plugin_id);
463 view.selected_native_entries.push(selected);
464 Ok(view)
465 }
466
467 /// Construct a fail-closed registry for a workspace without consulting
468 /// process environment or filesystem discovery roots.
469 #[must_use]
470 pub fn empty(workspace: &Path) -> Self {
471 Self {
472 workspace: workspace.to_path_buf(),
473 ..Self::default()
474 }
475 }
476
477 pub fn from_discovery(
478 plugins: Vec<LoadedPlugin>,
479 mut diagnostics: Vec<PluginDiagnostic>,
480 state_path: PathBuf,
481 workspace: PathBuf,
482 discovery_context: Option<std::sync::Arc<super::context::PluginDiscoveryContext>>,
483 ) -> Self {
484 let (state, state_error) = match load_state(&state_path) {
485 Ok(state) => (state, None),
486 Err(error) => {
487 diagnostics.push(PluginDiagnostic::error(
488 "state-invalid",
489 format!("Plugin state is fail-closed and will not be overwritten: {error}"),
490 Some(state_path.clone()),
491 ));
492 (PluginStateFile::default(), Some(error))
493 }
494 };
495 let catalog_stamp = discovery_context
496 .as_ref()
497 .map(|context| context.catalog_stamp_for_workspace(&workspace))
498 .unwrap_or_default();
499 let source = discovery_context.as_ref().map_or_else(
500 || resolve_managed_policy_path(&state_path, None),
501 |context| context.managed_policy_source(),
502 );
503 let (policy_path, managed_policy, managed_policy_error) = match source {
504 Ok(path) => match load_managed_policy(&path) {
505 ManagedPolicyOutcome::Absent => (Some(path), None, None),
506 ManagedPolicyOutcome::Loaded(policy) => (Some(path), Some(policy), None),
507 ManagedPolicyOutcome::Invalid(error) => (Some(path), None, Some(error)),
508 },
509 Err(error) => (None, None, Some(error)),
510 };
511 if let Some(error) = managed_policy_error.as_ref() {
512 diagnostics.push(PluginDiagnostic::error(
513 "policy-invalid",
514 format!("Managed plugin policy is fail-closed; no plugin may stay enabled until it is repaired or removed: {error}"),
515 policy_path.clone(),
516 ));
517 }
518 let mut registry = Self {
519 plugins: BTreeMap::new(),
520 names: BTreeMap::new(),
521 diagnostics,
522 state,
523 state_path: Some(state_path),
524 state_error,
525 managed_policy,
526 managed_policy_path: policy_path,
527 managed_policy_error,
528 workspace,
529 discovery_context,
530 catalog_stamp,
531 caller_selection: None,
532 selected_native_entries: Vec::new(),
533 unselected_native_catalogs: BTreeSet::new(),
534 };
535 for plugin in plugins {
536 registry.register_loaded(plugin);
537 }
538 registry.apply_state();
539 registry
540 }
541
542 fn register_loaded(&mut self, plugin: LoadedPlugin) {
543 self.names
544 .insert(plugin.name().to_string(), plugin.id.clone());
545 self.plugins.insert(plugin.id.clone(), plugin);
546 }
547
548 fn apply_state(&mut self) {
549 let state_path = self.state_path.clone();
550 let recovery_policy_path = self.managed_policy_path.clone();
551 // Hoisted so the loop below can borrow `self.plugins` mutably: a
552 // malformed policy fails closed (nothing stays enabled), a valid one
553 // forbids whatever it does not allow, and an absent one forbids nothing.
554 let managed_policy_invalid = self.managed_policy_error.is_some();
555 let managed_policy = self.managed_policy.clone();
556 for (id, plugin) in &mut self.plugins {
557 let persisted = self.state.plugins.get(id);
558 let bundled_agent_teams =
559 super::builtin::is_bundled_agent_teams(plugin.scope, plugin.name());
560 plugin.state_generation = persisted.map_or(0, |state| state.generation);
561 plugin.enabled = match persisted {
562 Some(state) => state.enabled,
563 None if bundled_agent_teams => {
564 super::builtin::bundled_agent_teams_default_enabled()
565 }
566 None => false,
567 };
568 plugin.trust_status = match persisted.and_then(|state| state.trust.as_ref()) {
569 Some(receipt) if receipt.capability_hash != plugin.capability_hash => {
570 PluginTrustStatus::CapabilitiesChanged
571 }
572 Some(receipt) if receipt.content_hash != plugin.content_hash => {
573 PluginTrustStatus::ContentChanged
574 }
575 Some(_) => PluginTrustStatus::Trusted,
576 None if bundled_agent_teams => PluginTrustStatus::Trusted,
577 None => PluginTrustStatus::NeverReviewed,
578 };
579 let receipt = persisted
580 .and_then(|state| state.trust.as_ref())
581 .filter(|_| plugin.trust_status == PluginTrustStatus::Trusted);
582 plugin.approved_by = receipt.and_then(|receipt| receipt.approved_by.clone());
583 plugin.enabled_by = persisted
584 .filter(|state| state.enabled)
585 .and_then(|state| state.enabled_by.clone());
586 plugin.host_services = receipt.map(TrustReceipt::granted).unwrap_or_default();
587 plugin.outside_reach = outside_reach(plugin.approved_by.as_ref(), &self.workspace);
588 plugin.reviewed_at = receipt.map(|receipt| receipt.reviewed_at.clone());
589 plugin.review_history = persisted
590 .map(|state| {
591 state
592 .review_history
593 .iter()
594 .rev()
595 .take(MAX_REVIEW_HISTORY)
596 .map(|entry| PluginReviewEntry {
597 reviewed_at: entry.reviewed_at.clone(),
598 approved_by: entry.approved_by.clone(),
599 })
600 .collect()
601 })
602 .unwrap_or_default();
603 if self.state_error.is_some() {
604 plugin.enabled = false;
605 plugin.trust_status = PluginTrustStatus::NeverReviewed;
606 plugin.approved_by = None;
607 plugin.enabled_by = None;
608 plugin.host_services = Vec::new();
609 plugin.outside_reach = false;
610 plugin.reviewed_at = None;
611 plugin.review_history = Vec::new();
612 }
613 // The managed policy is enforced here — inside the single choke
614 // point that turns persisted state into live enablement — so a
615 // plugin enabled before the policy arrived, or hand-edited to
616 // `enabled: true`, never comes back enabled. There is no window
617 // in which a forbidden plugin is observably active.
618 let policy_forbids = managed_policy_invalid
619 || managed_policy
620 .as_ref()
621 .is_some_and(|policy| !policy.allows(id));
622 if policy_forbids {
623 plugin.enabled = false;
624 }
625 let staged_path = state_path
626 .as_deref()
627 .map(|state_path| runtime_stage_path(state_path, id, &plugin.content_hash));
628 let mut snapshot_rejection = None;
629 plugin.staged_root =
630 staged_path.as_ref().and_then(|root| {
631 match staged_bundle_rejection(
632 root,
633 &plugin.content_hash,
634 &plugin.capability_hash,
635 ) {
636 None => Some(root.clone()),
637 Some(reason) => {
638 snapshot_rejection = Some(reason);
639 None
640 }
641 }
642 });
643 if bundled_agent_teams && plugin.trusted() && plugin.staged_root.is_none() {
644 plugin.staged_root = Some(plugin.canonical_root.clone());
645 }
646 if plugin.staged_root.is_some() {
647 plugin
648 .diagnostics
649 .retain(|item| item.code != "runtime-snapshot-recovery-failed");
650 if let (Some(state_path), Some(policy_path)) =
651 (state_path.as_deref(), recovery_policy_path.as_deref())
652 {
653 let key = recovery_attempt_key(state_path, policy_path, plugin);
654 if let Ok(mut attempts) = recovery_attempts().lock() {
655 attempts.remove(&key);
656 }
657 }
658 }
659 plugin
660 .diagnostics
661 .retain(|diagnostic| diagnostic.code != "runtime-snapshot-unavailable");
662 if plugin.trusted() && plugin.staged_root.is_none() {
663 let message = match staged_path.as_deref().map(std::fs::symlink_metadata) {
664 Some(Ok(metadata))
665 if metadata.file_type().is_dir()
666 && !metadata_is_link_or_reparse(&metadata) =>
667 {
668 "Plugin runtime snapshot is present but could not be verified; inspect it and review the plugin again."
669 }
670 Some(Ok(_)) => {
671 "Plugin runtime snapshot entry is unsafe; inspect it and review the plugin again."
672 }
673 Some(Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {
674 "Plugin runtime snapshot path is unavailable or cannot be inspected; it may be missing or unsafe. Inspect the runtime snapshot path."
675 }
676 Some(Err(_)) | None => {
677 "Plugin runtime snapshot cannot be inspected; check access to the runtime snapshot path."
678 }
679 };
680 let message = match snapshot_rejection {
681 Some(reason) => format!("{message} Rejected: {reason}."),
682 None => message.to_string(),
683 };
684 plugin.diagnostics.push(PluginDiagnostic::warning(
685 "runtime-snapshot-unavailable",
686 message,
687 staged_path,
688 ));
689 }
690 if let Some(staged_root) = plugin.staged_root.clone()
691 && !(bundled_agent_teams
692 && staged_root == plugin.canonical_root
693 && plugin.inventory.skills == 0)
694 {
695 match super::discovery::load_staged_skill_snapshots(
696 &staged_root,
697 &plugin.content_hash,
698 &plugin.capability_hash,
699 ) {
700 Ok(snapshots) => plugin.skill_snapshots = snapshots,
701 Err(error) => {
702 plugin.staged_root = None;
703 plugin.enabled = false;
704 plugin.diagnostics.push(PluginDiagnostic::error(
705 "staged-skill-invalid",
706 format!("Plugin runtime Skill snapshot is fail-closed: {error}"),
707 Some(staged_root),
708 ));
709 }
710 }
711 }
712 }
713 if self.selected_native_entries.is_empty() && self.unselected_native_catalogs.is_empty() {
714 (
715 self.selected_native_entries,
716 self.unselected_native_catalogs,
717 ) = super::native_presets::default_selection(self);
718 }
719 }
720
721 #[must_use]
722 pub fn workspace(&self) -> &Path {
723 &self.workspace
724 }
725
726 /// Re-discover for a new workspace using the immutable pre-dotenv roots
727 /// and environment. Registries without a context are test/ad-hoc values
728 /// and remain fail-closed instead of consulting ambient process state.
729 #[must_use]
730 pub fn catalog_stamp(&self) -> &super::discovery::PluginCatalogStamp {
731 &self.catalog_stamp
732 }
733
734 #[must_use]
735 pub fn live_catalog_stamp(&self) -> super::discovery::PluginCatalogStamp {
736 self.discovery_context
737 .as_ref()
738 .map_or_else(super::discovery::PluginCatalogStamp::default, |context| {
739 context.catalog_stamp_for_workspace(&self.workspace)
740 })
741 }
742
743 /// True when a plugin bundle directory has appeared, vanished, or been
744 /// rewritten since this registry was last discovered. Does not auto-reload.
745 #[must_use]
746 pub fn on_disk_catalog_changed(&self) -> bool {
747 self.discovery_context.is_some() && self.live_catalog_stamp() != self.catalog_stamp
748 }
749
750 #[must_use]
751 pub fn rediscover_for_workspace(&self, workspace: &Path) -> std::sync::Arc<Self> {
752 self.discovery_context.as_ref().map_or_else(
753 || std::sync::Arc::new(Self::empty(workspace)),
754 |context| context.registry_for_workspace(workspace),
755 )
756 }
757
758 #[must_use]
759 pub fn host_environment(&self) -> Option<std::sync::Arc<super::context::HostEnvironment>> {
760 self.discovery_context
761 .as_ref()
762 .map(|context| context.host_environment())
763 }
764
765 #[cfg(any(test, feature = "test-support"))]
766 pub fn replace_skill_snapshots_for_test(
767 &mut self,
768 selector: &str,
769 snapshots: Vec<super::types::PluginSkillSnapshot>,
770 ) {
771 let id = self
772 .resolve_id(selector)
773 .cloned()
774 .expect("test plugin exists");
775 self.plugins
776 .get_mut(&id)
777 .expect("test plugin exists")
778 .skill_snapshots = snapshots;
779 }
780
781 #[must_use]
782 pub fn authority_for(&self, selector: &str) -> Option<PluginAuthority> {
783 self.get(selector).and_then(|plugin| {
784 plugin.authority(
785 self.state_path.clone()?,
786 self.workspace.clone(),
787 self.managed_policy_path.clone()?,
788 )
789 })
790 }
791
792 #[must_use]
793 pub fn list(&self) -> Vec<&LoadedPlugin> {
794 let mut plugins = self.plugins.values().collect::<Vec<_>>();
795 plugins.sort_by(|left, right| {
796 left.scope
797 .cmp(&right.scope)
798 .then_with(|| left.name().cmp(right.name()))
799 .then_with(|| left.id.cmp(&right.id))
800 });
801 plugins
802 }
803
804 #[must_use]
805 pub fn get(&self, selector: &str) -> Option<&LoadedPlugin> {
806 let id = self.resolve_id(selector)?;
807 self.plugins.get(id)
808 }
809
810 #[must_use]
811 pub fn active_plugins(&self) -> Vec<&LoadedPlugin> {
812 self.list()
813 .into_iter()
814 .filter(|plugin| plugin.active())
815 .collect()
816 }
817
818 #[must_use]
819 pub fn is_enabled(&self, selector: &str) -> bool {
820 self.get(selector).is_some_and(|plugin| plugin.enabled)
821 }
822
823 #[must_use]
824 pub fn is_active(&self, selector: &str) -> bool {
825 self.get(selector).is_some_and(LoadedPlugin::active)
826 }
827
828 #[must_use]
829 pub fn diagnostics(&self) -> &[PluginDiagnostic] {
830 &self.diagnostics
831 }
832
833 #[must_use]
834 pub fn validation_is_clean(&self) -> bool {
835 !self
836 .diagnostics
837 .iter()
838 .any(|diagnostic| diagnostic.level == PluginDiagnosticLevel::Error)
839 && self.plugins.values().all(|plugin| {
840 !plugin
841 .diagnostics
842 .iter()
843 .any(|diagnostic| diagnostic.level == PluginDiagnosticLevel::Error)
844 })
845 }
846
847 #[must_use]
848 pub fn state_error(&self) -> Option<&str> {
849 self.state_error.as_deref()
850 }
851
852 #[must_use]
853 pub fn state_path(&self) -> Option<&Path> {
854 self.state_path.as_deref()
855 }
856
857 /// The fail-closed load error for the managed plugin policy, if the
858 /// document exists but could not be used. `None` means no policy file was
859 /// found or the loaded policy is valid.
860 #[must_use]
861 pub fn managed_policy_error(&self) -> Option<&str> {
862 self.managed_policy_error.as_deref()
863 }
864
865 /// The resolved managed policy source: the env override when set,
866 /// otherwise `managed-policy.json` next to the plugin state file.
867 #[must_use]
868 pub fn managed_policy_path(&self) -> Option<&Path> {
869 self.managed_policy_path.as_deref()
870 }
871
872 /// The pre-dotenv user plugins root, when this registry was built from a
873 /// discovery context. Registries without one (tests, fail-closed ad-hoc
874 /// values) return `None`, and the mutation controller refuses to write.
875 #[must_use]
876 pub fn user_plugins_dir(&self) -> Option<&Path> {
877 self.discovery_context
878 .as_ref()
879 .map(|context| context.user_plugins_dir())
880 }
881
882 /// Remove the persisted state entry for a bundle. This is the uninstall
883 /// hook (#5182): the caller deletes the bundle bits first, then prunes
884 /// the entry through the same locked, fail-closed state transaction used
885 /// by trust/enable/disable/revoke.
886 pub fn prune_state_entry(&mut self, selector: &str) -> Result<(), String> {
887 let id = self
888 .resolve_id(selector)
889 .cloned()
890 .ok_or_else(|| format!("Plugin bundle `{selector}` was not found"))?;
891 self.commit_state_change(|state| {
892 state.plugins.remove(&id);
893 Ok(())
894 })
895 }
896
897 pub fn restage(&mut self, selector: &str) -> Result<(), String> {
898 self.restage_inner(selector, false).map(drop)
899 }
900
901 fn restage_inner(&mut self, selector: &str, automatic: bool) -> Result<bool, String> {
902 if let Some(error) = &self.state_error {
903 return Err(format!("Plugin state is fail-closed: {error}"));
904 }
905 let plugin = self
906 .get(selector)
907 .cloned()
908 .ok_or_else(|| format!("Plugin bundle `{selector}` was not found"))?;
909 if !plugin.enabled
910 || !plugin.trusted()
911 || !plugin.applicable
912 || !plugin.inventory.can_activate_supported_components()
913 || plugin
914 .diagnostics
915 .iter()
916 .any(|item| item.level == PluginDiagnosticLevel::Error)
917 {
918 return Err("Recovery requires an enabled, reviewed, applicable plugin".to_string());
919 }
920 let state_path = self
921 .state_path
922 .clone()
923 .ok_or("Plugin state is unavailable")?;
924 let policy_path = self
925 .managed_policy_path
926 .clone()
927 .filter(|path| path.is_absolute())
928 .ok_or("Managed plugin policy source is unavailable")?;
929 let key = recovery_attempt_key(&state_path, &policy_path, &plugin);
930 validate_existing_plugin_state_parent(&state_path)?;
931 let lock_file = open_state_lock(&state_lock_path(&state_path), false)?;
932 let mut lock = fd_lock::RwLock::new(lock_file);
933 let guard = lock
934 .write()
935 .map_err(|error| format!("failed to lock plugin state: {error}"))?;
936 if automatic {
937 let previous = match recovery_attempts().lock() {
938 Ok(attempts) => attempts.get(&key).cloned(),
939 Err(_) => Some("Recovery attempt status is unavailable".to_string()),
940 };
941 if let Some(reason) = previous {
942 drop(guard);
943 self.set_recovery_diagnostic(&plugin.id, &reason);
944 return Ok(false);
945 }
946 }
947 let result = (|| {
948 let current = load_state_unlocked(&state_path)?;
949 let approved = current.plugins.get(&plugin.id).is_some_and(|entry| {
950 entry.enabled
951 && entry.generation == plugin.state_generation
952 && entry.trust.as_ref().is_some_and(|receipt| {
953 receipt.content_hash == plugin.content_hash
954 && receipt.capability_hash == plugin.capability_hash
955 })
956 });
957 if !approved {
958 return Err("Plugin state or review changed before recovery".to_string());
959 }
960 verify_recovery_policy(&policy_path, &plugin.id)?;
961 if !staged_bundle_content_matches(
962 &plugin.canonical_root,
963 &plugin.content_hash,
964 &plugin.capability_hash,
965 ) {
966 return Err("Reviewed plugin source no longer matches its receipt".to_string());
967 }
968 let staged = stage_bundle(&state_path, &plugin, StageIntent::Recovery)?;
969 if !staged_bundle_content_matches(
970 &plugin.canonical_root,
971 &plugin.content_hash,
972 &plugin.capability_hash,
973 ) || !staged_bundle_matches(&staged, &plugin.content_hash, &plugin.capability_hash)
974 {
975 return Err(
976 "Plugin source or recovered snapshot changed during recovery".to_string(),
977 );
978 }
979 verify_recovery_policy(&policy_path, &plugin.id)?;
980 Ok(())
981 })();
982 if let Ok(mut attempts) = recovery_attempts().lock() {
983 if result.is_ok() {
984 attempts.remove(&key);
985 } else if automatic && let Err(error) = &result {
986 attempts.insert(key, error.clone());
987 }
988 }
989 drop(guard);
990 result?;
991 self.state = load_state(&state_path)?;
992 self.refresh_managed_policy();
993 if let Some(plugin) = self.plugins.get_mut(&plugin.id) {
994 plugin
995 .diagnostics
996 .retain(|item| item.code != "runtime-snapshot-recovery-failed");
997 }
998 self.apply_state();
999 if !self.get(selector).is_some_and(LoadedPlugin::active) {
1000 return Err("Recovered snapshot is not active; refresh plugin state".to_string());
1001 }
1002 Ok(true)
1003 }
1004
1005 fn set_recovery_diagnostic(&mut self, id: &PluginId, reason: &str) {
1006 let Some(plugin) = self.plugins.get_mut(id) else {
1007 return;
1008 };
1009 plugin
1010 .diagnostics
1011 .retain(|item| item.code != "runtime-snapshot-recovery-failed");
1012 let path = self
1013 .state_path
1014 .as_deref()
1015 .map(|state| runtime_stage_path(state, id, &plugin.content_hash));
1016 plugin.diagnostics.push(PluginDiagnostic::warning(
1017 "runtime-snapshot-recovery-failed",
1018 format!("Plugin runtime snapshot could not be restored: {reason}"),
1019 path,
1020 ));
1021 }
1022
1023 #[cfg(not(any(test, feature = "test-support")))]
1024 pub(super) fn reconcile_missing_stages(&mut self) {
1025 if self.state_error.is_some() {
1026 return;
1027 }
1028 let Some(state_path) = self.state_path.clone() else {
1029 return;
1030 };
1031 let candidates = self
1032 .plugins
1033 .values()
1034 .filter_map(|plugin| {
1035 if !plugin.enabled
1036 || !plugin.trusted()
1037 || !plugin.applicable
1038 || !plugin.inventory.can_activate_supported_components()
1039 || plugin
1040 .diagnostics
1041 .iter()
1042 .any(|item| item.level == PluginDiagnosticLevel::Error)
1043 {
1044 return None;
1045 }
1046 let destination = runtime_stage_path(&state_path, &plugin.id, &plugin.content_hash);
1047 match fs::symlink_metadata(&destination) {
1048 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1049 Some(plugin.id.as_str().to_string())
1050 }
1051 Ok(_) if plugin.staged_root.is_none() => Some(plugin.id.as_str().to_string()),
1052 _ => None,
1053 }
1054 })
1055 .collect::<Vec<_>>();
1056 for selector in candidates {
1057 if let Err(error) = self.restage_inner(&selector, true) {
1058 tracing::warn!(plugin = %selector, %error, "reviewed plugin runtime snapshot was not restored");
1059 if let Some(id) = self.resolve_id(&selector).cloned() {
1060 self.set_recovery_diagnostic(&id, &error);
1061 }
1062 }
1063 }
1064 }
1065
1066 fn peer_names(&self) -> BTreeMap<PluginId, String> {
1067 self.plugins
1068 .iter()
1069 .map(|(id, plugin)| (id.clone(), plugin.name().to_string()))
1070 .collect()
1071 }
1072
1073 #[must_use]
1074 pub fn host_service_review(&self, selector: &str) -> Option<HostServiceReview> {
1075 self.host_service_review_for(selector, &PluginApprover::person(PersonVia::Terminal))
1076 }
1077
1078 #[must_use]
1079 pub fn host_service_review_for(
1080 &self,
1081 selector: &str,
1082 approver: &PluginApprover,
1083 ) -> Option<HostServiceReview> {
1084 if self.state_error.is_some() {
1085 return None;
1086 }
1087 Some(host_service_review_in(
1088 &self.state,
1089 self.get(selector)?,
1090 &self.peer_names(),
1091 &approver.cohort(),
1092 ))
1093 }
1094
1095 pub fn trust(&mut self, selector: &str) -> Result<(), String> {
1096 self.trust_reviewed(
1097 selector,
1098 ReviewApproval {
1099 approved_by: PluginApprover::person(PersonVia::Terminal),
1100 host_services: None,
1101 },
1102 )
1103 }
1104
1105 pub fn trust_reviewed(
1106 &mut self,
1107 selector: &str,
1108 approval: ReviewApproval,
1109 ) -> Result<(), String> {
1110 let plugin = self
1111 .get(selector)
1112 .ok_or_else(|| format!("Plugin bundle `{selector}` was not found"))?
1113 .clone();
1114 self.commit_trust_transaction(&plugin, approval, None)
1115 }
1116
1117 pub fn trust_and_enable_by(
1118 &mut self,
1119 selector: &str,
1120 approval: ReviewApproval,
1121 enabled_by: PluginApprover,
1122 ) -> Result<(), String> {
1123 let plugin = self
1124 .get(selector)
1125 .ok_or_else(|| format!("Plugin bundle `{selector}` was not found"))?
1126 .clone();
1127 self.check_managed_policy_for_enable(&plugin)?;
1128 self.check_enable_approver(
1129 &plugin,
1130 Some(&approval.approved_by),
1131 outside_reach(Some(&approval.approved_by), &self.workspace),
1132 &enabled_by,
1133 )?;
1134 self.check_activation_preconditions(&plugin)?;
1135 self.commit_trust_transaction(&plugin, approval, Some(enabled_by))
1136 }
1137
1138 fn commit_trust_transaction(
1139 &mut self,
1140 plugin: &LoadedPlugin,
1141 approval: ReviewApproval,
1142 also_enable_by: Option<PluginApprover>,
1143 ) -> Result<(), String> {
1144 let id = plugin.id.clone();
1145 check_approver(
1146 &approval.approved_by,
1147 plugin,
1148 &self.workspace,
1149 approval.host_services.is_some(),
1150 )?;
1151 let state_path = self
1152 .state_path
1153 .as_deref()
1154 .ok_or_else(|| "Plugin registry has no persistence store".to_string())?;
1155 let staged_path = stage_bundle(state_path, plugin, StageIntent::Review)?;
1156 if also_enable_by.is_some()
1157 && let Some(reason) =
1158 staged_bundle_rejection(&staged_path, &plugin.content_hash, &plugin.capability_hash)
1159 {
1160 return Err(format!(
1161 "Plugin bundle `{}` has no verified Codewhale runtime snapshot ({reason}); review and trust it again before enablement",
1162 plugin.name()
1163 ));
1164 }
1165 let names = self.peer_names();
1166 let cohort = approval.approved_by.cohort();
1167 let expected_entry = self.state.plugins.get(&id).cloned();
1168 let expected_install_nonce = plugin.install_nonce.clone();
1169 let mut receipt = TrustReceipt {
1170 content_hash: plugin.content_hash.clone(),
1171 capability_hash: plugin.capability_hash.clone(),
1172 reviewed_capabilities: plugin.inventory.clone(),
1173 reviewed_at: chrono::Utc::now().to_rfc3339(),
1174 version: RECEIPT_VERSION,
1175 approved_by: Some(approval.approved_by),
1176 host_services: Vec::new(),
1177 };
1178 self.commit_state_change(|state| {
1179 let current_entry = state.plugins.get(&id);
1180 if current_entry.map_or(0, |entry| entry.generation) != plugin.state_generation
1181 || !trust_receipt_matches(
1182 expected_entry.as_ref().and_then(|entry| entry.trust.as_ref()),
1183 current_entry.and_then(|entry| entry.trust.as_ref()),
1184 )
1185 || (plugin.trusted()
1186 && !current_entry
1187 .and_then(|entry| entry.trust.as_ref())
1188 .is_some_and(|current| {
1189 current.content_hash == plugin.content_hash
1190 && current.capability_hash == plugin.capability_hash
1191 && current.approved_by == plugin.approved_by
1192 }))
1193 || super::discovery::read_install_nonce(&plugin.canonical_root)?
1194 != expected_install_nonce
1195 {
1196 return Err(format!(
1197 "Plugin bundle `{}` state or review changed; refresh plugin state and review it again",
1198 plugin.name()
1199 ));
1200 }
1201 if let Some(shown) = approval.host_services.as_deref() {
1202 let review = host_service_review_in(state, plugin, &names, &cohort);
1203 if review.token != shown {
1204 return Err(format!(
1205 "The host service review for plugin bundle `{}` changed since it was shown; read it again before approving",
1206 plugin.name()
1207 ));
1208 }
1209 receipt.host_services = review.grants();
1210 }
1211 let entry = state.plugins.entry(id).or_default();
1212 entry.generation = entry
1213 .generation
1214 .checked_add(1)
1215 .ok_or_else(|| "Plugin authority generation is exhausted".to_string())?;
1216 match also_enable_by {
1217 Some(enabled_by) => {
1218 entry.enabled = true;
1219 entry.enabled_by = Some(enabled_by);
1220 }
1221 None => {
1222 entry.enabled = false;
1223 entry.enabled_by = None;
1224 }
1225 }
1226 entry.trust = Some(receipt.clone());
1227 entry.review_history.push(receipt);
1228 if entry.review_history.len() > MAX_REVIEW_HISTORY {
1229 let remove = entry.review_history.len() - MAX_REVIEW_HISTORY;
1230 entry.review_history.drain(..remove);
1231 }
1232 Ok(())
1233 })
1234 }
1235
1236 pub fn revoke_trust(&mut self, selector: &str) -> Result<(), String> {
1237 let id = self
1238 .resolve_id(selector)
1239 .cloned()
1240 .ok_or_else(|| format!("Plugin bundle `{selector}` was not found"))?;
1241 self.commit_state_change(|state| {
1242 let entry = state.plugins.entry(id).or_default();
1243 entry.generation = entry
1244 .generation
1245 .checked_add(1)
1246 .ok_or_else(|| "Plugin authority generation is exhausted".to_string())?;
1247 entry.trust = None;
1248 Ok(())
1249 })
1250 }
1251
1252 pub fn enable(&mut self, selector: &str) -> Result<(), String> {
1253 self.enable_by(selector, PluginApprover::person(PersonVia::Terminal))
1254 }
1255
1256 fn check_managed_policy_for_enable(&mut self, plugin: &LoadedPlugin) -> Result<(), String> {
1257 self.refresh_managed_policy();
1258 if let Some(error) = self.managed_policy_error.as_deref() {
1259 let path = self.managed_policy_path.as_deref().map_or_else(
1260 || "(unknown path)".to_string(),
1261 |path| path.display().to_string(),
1262 );
1263 return Err(format!(
1264 "Managed plugin policy at {path} is invalid, so no plugin may be enabled: {error}"
1265 ));
1266 }
1267 if self
1268 .managed_policy
1269 .as_ref()
1270 .is_some_and(|policy| !policy.allows(&plugin.id))
1271 {
1272 return Err(format!(
1273 "Plugin bundle `{}` is forbidden by the managed plugin policy: `{}` is not on the plugin allowlist",
1274 plugin.name(),
1275 plugin.id.as_str()
1276 ));
1277 }
1278 Ok(())
1279 }
1280
1281 fn check_enable_approver(
1282 &self,
1283 plugin: &LoadedPlugin,
1284 approved_by: Option<&PluginApprover>,
1285 is_outside_reach: bool,
1286 enabled_by: &PluginApprover,
1287 ) -> Result<(), String> {
1288 if matches!(enabled_by, PluginApprover::Agent(_)) {
1289 if approved_by
1290 .and_then(PluginApprover::agent_workspace)
1291 .is_none()
1292 {
1293 return Err(format!(
1294 "Plugin bundle `{}` is approved for every project, so the agent cannot turn it on; ask the person",
1295 plugin.name()
1296 ));
1297 }
1298 if is_outside_reach {
1299 return Err(format!(
1300 "Plugin bundle `{}` was approved by the agent of another project, so it cannot be turned on here",
1301 plugin.name()
1302 ));
1303 }
1304 check_approver(enabled_by, plugin, &self.workspace, true)?;
1305 }
1306 Ok(())
1307 }
1308
1309 fn check_activation_preconditions(&self, plugin: &LoadedPlugin) -> Result<(), String> {
1310 if !plugin.applicable {
1311 return Err(format!(
1312 "Plugin bundle `{}` does not apply to this host",
1313 plugin.name()
1314 ));
1315 }
1316 if !plugin.inventory.can_activate_supported_components() {
1317 let unsupported = plugin.inventory.unsupported_labels();
1318 return Err(format!(
1319 "Plugin bundle `{}` has no supported declarative components to activate; inactive: {}",
1320 plugin.name(),
1321 unsupported.join(", ")
1322 ));
1323 }
1324 Ok(())
1325 }
1326
1327 pub fn enable_by(&mut self, selector: &str, enabled_by: PluginApprover) -> Result<(), String> {
1328 let plugin = self
1329 .get(selector)
1330 .ok_or_else(|| format!("Plugin bundle `{selector}` was not found"))?
1331 .clone();
1332 self.check_managed_policy_for_enable(&plugin)?;
1333 if !plugin.trusted() {
1334 return Err(format!(
1335 "Plugin bundle `{}` requires capability review before enablement (trust: {})",
1336 plugin.name(),
1337 plugin.trust_status.as_str()
1338 ));
1339 }
1340 self.check_enable_approver(
1341 &plugin,
1342 plugin.approved_by.as_ref(),
1343 plugin.outside_reach,
1344 &enabled_by,
1345 )?;
1346 let snapshot_rejection = match plugin.staged_root.as_deref() {
1347 None => Some(
1348 plugin
1349 .diagnostics
1350 .iter()
1351 .find(|diagnostic| diagnostic.code == "runtime-snapshot-unavailable")
1352 .map_or_else(
1353 || "no staged snapshot".to_string(),
1354 |diagnostic| diagnostic.message.clone(),
1355 ),
1356 ),
1357 Some(root) => {
1358 staged_bundle_rejection(root, &plugin.content_hash, &plugin.capability_hash)
1359 }
1360 };
1361 if let Some(reason) = snapshot_rejection {
1362 return Err(format!(
1363 "Plugin bundle `{}` has no verified Codewhale runtime snapshot ({reason}); review and trust it again before enablement",
1364 plugin.name()
1365 ));
1366 }
1367 self.check_activation_preconditions(&plugin)?;
1368 let id = plugin.id.clone();
1369 let expected_install_nonce = plugin.install_nonce.clone();
1370 self.commit_state_change(|state| {
1371 if super::discovery::read_install_nonce(&plugin.canonical_root)?
1372 != expected_install_nonce
1373 {
1374 return Err(format!(
1375 "Plugin bundle `{}` state or review changed; refresh plugin state and review it if needed before enabling again",
1376 plugin.name()
1377 ));
1378 }
1379 let entry = state
1380 .plugins
1381 .get_mut(&id)
1382 .filter(|entry| {
1383 entry.generation == plugin.state_generation
1384 && entry.trust.as_ref().is_some_and(|receipt| {
1385 receipt.content_hash == plugin.content_hash
1386 && receipt.capability_hash == plugin.capability_hash
1387 && receipt.approved_by == plugin.approved_by
1388 })
1389 })
1390 .ok_or_else(|| {
1391 format!(
1392 "Plugin bundle `{}` state or review changed; refresh plugin state and review it if needed before enabling again",
1393 plugin.name()
1394 )
1395 })?;
1396 entry.generation = entry
1397 .generation
1398 .checked_add(1)
1399 .ok_or_else(|| "Plugin authority generation is exhausted".to_string())?;
1400 entry.enabled = true;
1401 entry.enabled_by = Some(enabled_by);
1402 Ok(())
1403 })
1404 }
1405
1406 pub fn disable(&mut self, selector: &str) -> Result<(), String> {
1407 let id = self
1408 .resolve_id(selector)
1409 .cloned()
1410 .ok_or_else(|| format!("Plugin bundle `{selector}` was not found"))?;
1411 self.commit_state_change(|state| {
1412 let entry = state.plugins.entry(id).or_default();
1413 entry.generation = entry
1414 .generation
1415 .checked_add(1)
1416 .ok_or_else(|| "Plugin authority generation is exhausted".to_string())?;
1417 entry.enabled = false;
1418 entry.enabled_by = None;
1419 Ok(())
1420 })
1421 }
1422
1423 /// Carry a built-in bundle's review across Codewhale upgrades (K4).
1424 ///
1425 /// Each build materializes its built-ins under a digest-named snapshot
1426 /// root and a plugin id is bound to its root, so an upgrade presents the
1427 /// same built-in under a new id with no persisted state. Left alone it is
1428 /// `NeverReviewed` and disabled, which turns Computer Use off for every
1429 /// user who had enabled it. Once per new id, the newest review of a
1430 /// same-named built-in is carried forward:
1431 ///
1432 /// * capability hash unchanged: the review stands for the new bytes. The
1433 /// bundle is staged and re-receipted under its new id and keeps its
1434 /// prior enablement.
1435 /// * capability hash changed: the prior receipt is recorded as is, so the
1436 /// bundle reports `capabilities-changed` and stays disabled until the
1437 /// user reviews the changes.
1438 ///
1439 /// Fail-closed: nothing is carried when the new id already has state,
1440 /// when the most recently reviewed same-named predecessor has since been
1441 /// revoked, or when the state file is invalid. Older ids are left
1442 /// untouched, so a still-running older binary keeps its own authority.
1443 /// Only the built-in scope is ever carried; user and workspace bundles
1444 /// still require review of the exact bytes on disk.
1445 pub fn carry_forward_builtin_trust(&mut self) {
1446 if self.state_error.is_some() || self.state_path.is_none() {
1447 return;
1448 }
1449 let candidates: Vec<LoadedPlugin> = self
1450 .plugins
1451 .values()
1452 .filter(|plugin| plugin.scope == super::types::PluginScope::Builtin)
1453 .filter(|plugin| builtin_predecessor(&self.state, &plugin.id, plugin.name()).is_some())
1454 .cloned()
1455 .collect();
1456 for plugin in candidates {
1457 if let Err(error) = self.carry_forward_one_builtin(&plugin) {
1458 tracing::warn!(
1459 target: "plugins",
1460 plugin = plugin.name(),
1461 %error,
1462 "built-in plugin review could not be carried across the upgrade; it needs review again"
1463 );
1464 }
1465 }
1466 }
1467
1468 fn carry_forward_one_builtin(&mut self, plugin: &LoadedPlugin) -> Result<(), String> {
1469 let state_path = self
1470 .state_path
1471 .clone()
1472 .ok_or_else(|| "Plugin registry has no persistence store".to_string())?;
1473 let same_capabilities = builtin_predecessor(&self.state, &plugin.id, plugin.name())
1474 .and_then(|entry| entry.trust.as_ref())
1475 .is_some_and(|receipt| receipt.capability_hash == plugin.capability_hash);
1476 // Staging is content-addressed and idempotent, so it runs before the
1477 // state lock; the decision is re-derived from the locked state below.
1478 if same_capabilities {
1479 stage_bundle(&state_path, plugin, StageIntent::Review)?;
1480 }
1481 let id = plugin.id.clone();
1482 let name = plugin.name().to_string();
1483 let applicable = plugin.applicable;
1484 let mut carried = TrustReceipt {
1485 content_hash: plugin.content_hash.clone(),
1486 capability_hash: plugin.capability_hash.clone(),
1487 reviewed_capabilities: plugin.inventory.clone(),
1488 reviewed_at: chrono::Utc::now().to_rfc3339(),
1489 version: 0,
1490 approved_by: None,
1491 host_services: Vec::new(),
1492 };
1493 self.commit_state_change(|state| {
1494 let Some(predecessor) = builtin_predecessor(state, &id, &name).cloned() else {
1495 return Ok(());
1496 };
1497 let Some(prior) = predecessor.trust else {
1498 return Ok(());
1499 };
1500 carried.approved_by.clone_from(&prior.approved_by);
1501 if carried.approved_by.is_some() {
1502 carried.version = RECEIPT_VERSION;
1503 }
1504 let mut entry = PersistedPluginState {
1505 generation: 1,
1506 enabled: false,
1507 enabled_by: None,
1508 trust: None,
1509 review_history: predecessor.review_history,
1510 };
1511 if prior.capability_hash == carried.capability_hash {
1512 if !same_capabilities {
1513 // Changed under us to a state that needs a staged copy we
1514 // did not make; the next discovery carries it.
1515 return Ok(());
1516 }
1517 entry.enabled = predecessor.enabled && applicable;
1518 if entry.enabled {
1519 entry.enabled_by = predecessor.enabled_by;
1520 }
1521 entry.trust = Some(carried.clone());
1522 entry.review_history.push(carried);
1523 if entry.review_history.len() > MAX_REVIEW_HISTORY {
1524 let remove = entry.review_history.len() - MAX_REVIEW_HISTORY;
1525 entry.review_history.drain(..remove);
1526 }
1527 } else {
1528 entry.trust = Some(prior);
1529 }
1530 state.plugins.insert(id, entry);
1531 Ok(())
1532 })
1533 }
1534
1535 fn commit_state_change(
1536 &mut self,
1537 mutate: impl FnOnce(&mut PluginStateFile) -> Result<(), String>,
1538 ) -> Result<(), String> {
1539 if let Some(error) = &self.state_error {
1540 return Err(format!(
1541 "Plugin state is fail-closed; repair or move the malformed state file before mutating it: {error}"
1542 ));
1543 }
1544 let Some(path) = self.state_path.as_deref() else {
1545 return Err("Plugin registry has no persistence store".to_string());
1546 };
1547 let lock_path = state_lock_path(path);
1548 if let Some(parent) = lock_path.parent() {
1549 ensure_private_plugin_state_directory(parent)?;
1550 }
1551 let lock_file = open_state_lock(&lock_path, true)?;
1552 let mut lock = fd_lock::RwLock::new(lock_file);
1553 let _guard = lock
1554 .write()
1555 .map_err(|e| format!("failed to lock plugin state for update: {e}"))?;
1556 let mut next = load_state_unlocked(path)?;
1557 mutate(&mut next)?;
1558 save_state(path, &next)?;
1559 self.catalog_stamp.refresh_state(path);
1560 self.state = next;
1561 // Runtime selection rechecks the persisted review through its own
1562 // read lock. Publish the completed state transaction before deriving
1563 // that view; retaining the writer here would deadlock on enable.
1564 drop(_guard);
1565 self.apply_state();
1566 Ok(())
1567 }
1568
1569 /// Re-read the policy document from its resolved path so `enable`
1570 /// enforces the on-disk document even when it landed or changed after
1571 /// discovery. Refreshing never touches diagnostics: the discovery-time
1572 /// `policy-invalid` diagnostic and the `enable` refusal carry the error.
1573 fn refresh_managed_policy(&mut self) {
1574 let Some(path) = self.managed_policy_path.clone() else {
1575 return;
1576 };
1577 match load_managed_policy(&path) {
1578 ManagedPolicyOutcome::Absent => {
1579 self.managed_policy = None;
1580 self.managed_policy_error = None;
1581 }
1582 ManagedPolicyOutcome::Loaded(policy) => {
1583 self.managed_policy = Some(policy);
1584 self.managed_policy_error = None;
1585 }
1586 ManagedPolicyOutcome::Invalid(error) => {
1587 self.managed_policy = None;
1588 self.managed_policy_error = Some(error);
1589 }
1590 }
1591 }
1592
1593 fn resolve_id(&self, selector: &str) -> Option<&PluginId> {
1594 self.plugins
1595 .keys()
1596 .find(|id| id.as_str() == selector)
1597 .or_else(|| self.names.get(selector))
1598 }
1599
1600 #[must_use]
1601 pub fn len(&self) -> usize {
1602 self.plugins.len()
1603 }
1604
1605 #[must_use]
1606 pub fn is_empty(&self) -> bool {
1607 self.plugins.is_empty()
1608 }
1609 }
1610
1611 fn load_state(path: &Path) -> Result<PluginStateFile, String> {
1612 validate_existing_plugin_state_parent(path)?;
1613 let lock_path = state_lock_path(path);
1614 let lock_exists = path_entry_exists(&lock_path)?;
1615 if lock_exists {
1616 let lock_file = open_state_lock(&lock_path, false)?;
1617 let lock = fd_lock::RwLock::new(lock_file);
1618 let _guard = lock
1619 .read()
1620 .map_err(|e| format!("failed to read-lock plugin state: {e}"))?;
1621 return load_state_unlocked(path);
1622 }
1623 load_state_unlocked(path)
1624 }
1625
1626 /// Maximum bytes read from the plugin state file.
1627 const MAX_PLUGIN_STATE_BYTES: u64 = 16 * 1024 * 1024;
1628
1629 fn load_state_unlocked(path: &Path) -> Result<PluginStateFile, String> {
1630 let Some(file) = open_existing_regular_file(path, false)? else {
1631 return Ok(PluginStateFile::default());
1632 };
1633 load_state_from_file(path, file)
1634 }
1635
1636 fn load_state_from_file(path: &Path, file: fs::File) -> Result<PluginStateFile, String> {
1637 let mut raw = String::new();
1638 file.take(MAX_PLUGIN_STATE_BYTES + 1)
1639 .read_to_string(&mut raw)
1640 .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
1641 if raw.len() as u64 > MAX_PLUGIN_STATE_BYTES {
1642 return Err(format!(
1643 "plugin state {} exceeds the {} MiB limit",
1644 path.display(),
1645 MAX_PLUGIN_STATE_BYTES / (1024 * 1024)
1646 ));
1647 }
1648 let state: PluginStateFile = serde_json::from_str(&raw)
1649 .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
1650 if state.schema_version != STATE_SCHEMA_VERSION {
1651 return Err(format!(
1652 "unsupported plugin state schema {}; expected {STATE_SCHEMA_VERSION}",
1653 state.schema_version
1654 ));
1655 }
1656 Ok(state)
1657 }
1658
1659 fn save_state(path: &Path, state: &PluginStateFile) -> Result<(), String> {
1660 save_state_with_hardener(path, state, harden_plugin_state_file)
1661 }
1662
1663 /// Publish a hardened JSON document atomically. Generic over the schema so
1664 /// sibling Codewhale-owned stores (e.g. the marketplace catalog store) share
1665 /// the exact durability and no-follow path this registry was audited for.
1666 pub fn save_state_with_hardener<T: serde::Serialize>(
1667 path: &Path,
1668 state: &T,
1669 harden_temporary: impl FnOnce(&Path) -> Result<(), String>,
1670 ) -> Result<(), String> {
1671 let parent = path
1672 .parent()
1673 .filter(|parent| !parent.as_os_str().is_empty())
1674 .ok_or_else(|| "Plugin state path must have a private parent directory".to_string())?;
1675 ensure_private_plugin_state_directory(parent)?;
1676
1677 let mut body = serde_json::to_string_pretty(state)
1678 .map_err(|error| format!("failed to serialize {}: {error}", path.display()))?;
1679 body.push('\n');
1680 let mut temporary = tempfile::NamedTempFile::new_in(parent)
1681 .map_err(|error| format!("failed to create private plugin state temp file: {error}"))?;
1682 temporary
1683 .write_all(body.as_bytes())
1684 .map_err(|error| format!("failed to write private plugin state temp file: {error}"))?;
1685 temporary
1686 .flush()
1687 .and_then(|()| temporary.as_file().sync_all())
1688 .map_err(|error| format!("failed to flush private plugin state temp file: {error}"))?;
1689
1690 // Restrict the exact temporary object before its atomic rename publishes
1691 // it under the stable state path. Post-publish hardening leaves a Windows
1692 // race in which another local principal can open the inherited DACL.
1693 #[cfg(windows)]
1694 {
1695 // `NamedTempFile` keeps a writer handle open. The ACL hardener
1696 // intentionally opens its target with FILE_SHARE_READ only, so close
1697 // that writer before safely reopening the name for ACL mutation. Its
1698 // parent was hardened above, which prevents another principal from
1699 // replacing the temporary entry between those operations.
1700 let temporary = temporary.into_temp_path();
1701 harden_temporary(temporary.as_ref())?;
1702 persist_plugin_state(temporary, path)
1703 }
1704 #[cfg(not(windows))]
1705 {
1706 harden_temporary(temporary.path())?;
1707 persist_plugin_state(temporary, path)
1708 }
1709 }
1710
1711 #[cfg(unix)]
1712 fn persist_plugin_state(temporary: tempfile::NamedTempFile, path: &Path) -> Result<(), String> {
1713 persist_plugin_state_with_directory_sync(temporary, path, fs::File::sync_all)
1714 }
1715
1716 #[cfg(unix)]
1717 fn persist_plugin_state_with_directory_sync(
1718 temporary: tempfile::NamedTempFile,
1719 path: &Path,
1720 sync_directory: impl FnOnce(&fs::File) -> std::io::Result<()>,
1721 ) -> Result<(), String> {
1722 use std::os::unix::fs::OpenOptionsExt as _;
1723
1724 temporary
1725 .persist(path)
1726 .map_err(|error| error.error)
1727 .map_err(|error| format!("failed to atomically persist {}: {error}", path.display()))?;
1728 let parent = path
1729 .parent()
1730 .filter(|parent| !parent.as_os_str().is_empty())
1731 .ok_or_else(|| "Plugin state path must have a private parent directory".to_string())?;
1732 let directory = OpenOptions::new()
1733 .read(true)
1734 .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
1735 .open(parent)
1736 .map_err(|error| {
1737 format!("failed to open plugin state directory for durability sync: {error}")
1738 })?;
1739 sync_directory(&directory).map_err(|error| {
1740 format!(
1741 "plugin state was published but its directory durability could not be confirmed: {error}"
1742 )
1743 })
1744 }
1745
1746 #[cfg(windows)]
1747 fn persist_plugin_state(mut temporary: tempfile::TempPath, path: &Path) -> Result<(), String> {
1748 use std::os::windows::ffi::OsStrExt as _;
1749 use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, WIN32_ERROR};
1750 use windows::Win32::Storage::FileSystem::{
1751 FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_TEMPORARY, MOVEFILE_REPLACE_EXISTING,
1752 MOVEFILE_WRITE_THROUGH, MoveFileExW, SetFileAttributesW,
1753 };
1754 use windows::core::PCWSTR;
1755
1756 fn wide_path(path: &Path) -> Vec<u16> {
1757 path.as_os_str().encode_wide().chain(Some(0)).collect()
1758 }
1759
1760 let temporary_path = temporary.to_path_buf();
1761 let temporary_wide = wide_path(&temporary_path);
1762 let destination_wide = wide_path(path);
1763 // NamedTempFile marks the source as temporary. Clear only that temporary
1764 // caching hint before publication, matching tempfile's own persistence
1765 // contract while retaining the owner-only DACL applied above.
1766 // SAFETY: `temporary_wide` is NUL-terminated and live.
1767 unsafe {
1768 SetFileAttributesW(
1769 PCWSTR::from_raw(temporary_wide.as_ptr()),
1770 FILE_ATTRIBUTE_NORMAL,
1771 )
1772 }
1773 .map_err(|error| {
1774 format!("failed to prepare private plugin state temp file for publication: {error}")
1775 })?;
1776
1777 // The state lock serializes writers, but not everything that opens the
1778 // stable file. Another registry re-applies the state directory's
1779 // inheritable ACL before it takes that lock, and Defender or the indexer
1780 // can scan the file; each holds it only briefly. A plugin UI grant holds
1781 // it for up to an hour. MoveFileExW refuses to replace a destination that
1782 // any handle has open, so on access denied publish with std::fs::rename,
1783 // which replaces a destination whose holders share delete access (POSIX
1784 // rename: NTFS, Windows 10 1709 or later), and flush through a handle
1785 // opened beforehand because that rename does not write through. When that
1786 // is refused too, re-attempt on the schedule the other atomic writers
1787 // share; a failed attempt leaves the hardened temporary and the stable
1788 // file untouched.
1789 let mut attempt = 0;
1790 // SAFETY: both paths are NUL-terminated and live.
1791 while let Err(error) = unsafe {
1792 MoveFileExW(
1793 PCWSTR::from_raw(temporary_wide.as_ptr()),
1794 PCWSTR::from_raw(destination_wide.as_ptr()),
1795 MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
1796 )
1797 } {
1798 // MoveFileExW reports an HRESULT; the shared classifier reads the
1799 // Win32 code it wraps.
1800 let code = WIN32_ERROR::from_error(&error);
1801 if code == Some(ERROR_ACCESS_DENIED)
1802 && let Ok(Some(source)) = open_existing_regular_file(&temporary_path, true)
1803 && fs::rename(&temporary_path, path).is_ok()
1804 {
1805 temporary.disable_cleanup(true);
1806 return source.sync_all().map_err(|error| {
1807 format!(
1808 "plugin state was published but its durability could not be confirmed: {error}"
1809 )
1810 });
1811 }
1812 let backoff = code.and_then(|code| {
1813 codewhale_util::utils::windows_publish_retry_delay(
1814 &std::io::Error::from_raw_os_error(code.0 as i32),
1815 attempt,
1816 )
1817 });
1818 if let Some(backoff) = backoff {
1819 std::thread::sleep(backoff);
1820 attempt += 1;
1821 continue;
1822 }
1823 // Restore tempfile's cleanup hint on the still-private source. The
1824 // stable state path remains untouched when MoveFileExW fails.
1825 // SAFETY: `temporary_wide` is NUL-terminated and live.
1826 let _ = unsafe {
1827 SetFileAttributesW(
1828 PCWSTR::from_raw(temporary_wide.as_ptr()),
1829 FILE_ATTRIBUTE_TEMPORARY,
1830 )
1831 };
1832 return Err(format!(
1833 "failed to atomically and durably persist {}: {error}",
1834 path.display()
1835 ));
1836 }
1837
1838 // The old temporary pathname no longer exists. Disarm TempPath cleanup.
1839 temporary.disable_cleanup(true);
1840 Ok(())
1841 }
1842
1843 #[cfg(all(not(unix), not(windows)))]
1844 fn persist_plugin_state(temporary: tempfile::NamedTempFile, path: &Path) -> Result<(), String> {
1845 temporary
1846 .persist(path)
1847 .map_err(|error| error.error)
1848 .map(|_| ())
1849 .map_err(|error| format!("failed to atomically persist {}: {error}", path.display()))
1850 }
1851
1852 pub fn state_lock_path(path: &Path) -> PathBuf {
1853 let mut name = path
1854 .file_name()
1855 .map(|name| name.to_os_string())
1856 .unwrap_or_else(|| "state.json".into());
1857 name.push(".lock");
1858 path.with_file_name(name)
1859 }
1860
1861 #[cfg(not(windows))]
1862 pub fn open_state_lock(path: &Path, create: bool) -> Result<fs::File, String> {
1863 let mut options = OpenOptions::new();
1864 options
1865 .read(true)
1866 .write(true)
1867 .create(create)
1868 .truncate(false);
1869 #[cfg(unix)]
1870 {
1871 use std::os::unix::fs::OpenOptionsExt;
1872 options
1873 .mode(0o600)
1874 .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);
1875 }
1876 let file = options
1877 .open(path)
1878 .map_err(|e| format!("failed to open plugin state lock: {e}"))?;
1879 validate_opened_regular_file(path, &file)?;
1880 // Discovery/doctor opens existing locks with `create=false` and must be
1881 // byte-for-byte and descriptor-for-descriptor non-mutating. ACL/mode
1882 // hardening belongs only to trust/enable/disable/revoke updates.
1883 if create {
1884 harden_plugin_state_file(path)?;
1885 }
1886 Ok(file)
1887 }
1888
1889 #[cfg(windows)]
1890 pub fn open_state_lock(path: &Path, create: bool) -> Result<fs::File, String> {
1891 use std::os::windows::fs::OpenOptionsExt as _;
1892
1893 const LOCK_ACCESS_WITH_OWNER: u32 = 0x001e_019f;
1894 const LOCK_ACCESS_WITHOUT_OWNER: u32 = 0x0016_019f;
1895
1896 let (file, owner_mode) = if create {
1897 match open_windows_state_lock(path, true, LOCK_ACCESS_WITH_OWNER) {
1898 Ok(file) => (file, WindowsAclOwnerMode::NormalizeCurrentUser),
1899 Err(error) if is_windows_access_denied(&error) => {
1900 // The first attempt can only be retried when Windows denied
1901 // WRITE_OWNER. Do not recreate the entry here: a disappeared
1902 // lock is a concurrent mutation that must fail closed instead
1903 // of turning into a fresh object with an unchecked owner.
1904 let file = open_windows_state_lock(path, false, LOCK_ACCESS_WITHOUT_OWNER)
1905 .map_err(|error| format!("failed to open plugin state lock: {error}"))?;
1906 (file, WindowsAclOwnerMode::VerifyCurrentUser)
1907 }
1908 Err(error) => {
1909 return Err(format!("failed to open plugin state lock: {error}"));
1910 }
1911 }
1912 } else {
1913 let mut options = OpenOptions::new();
1914 options
1915 .read(true)
1916 .write(true)
1917 .truncate(false)
1918 // Open the reparse point itself. `validate_opened_regular_file`
1919 // then rejects it instead of following it to an unrelated target.
1920 .custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
1921 let file = options
1922 .open(path)
1923 .map_err(|error| format!("failed to open plugin state lock: {error}"))?;
1924 (file, WindowsAclOwnerMode::VerifyCurrentUser)
1925 };
1926
1927 validate_opened_regular_file(path, &file)?;
1928 // Discovery/doctor opens existing locks with `create=false` and must be
1929 // byte-for-byte and descriptor-for-descriptor non-mutating. ACL/mode
1930 // hardening belongs only to trust/enable/disable/revoke updates.
1931 if create {
1932 harden_opened_plugin_state_file(path, &file, owner_mode)?;
1933 }
1934 Ok(file)
1935 }
1936
1937 #[cfg(windows)]
1938 fn open_windows_state_lock(
1939 path: &Path,
1940 create: bool,
1941 access_mode: u32,
1942 ) -> std::io::Result<fs::File> {
1943 use std::os::windows::fs::OpenOptionsExt as _;
1944
1945 let mut options = OpenOptions::new();
1946 options
1947 .read(true)
1948 .write(true)
1949 .create(create)
1950 .truncate(false)
1951 // Open the reparse point itself. `validate_opened_regular_file` then
1952 // rejects it instead of following it to an unrelated ACL target.
1953 .custom_flags(0x0020_0000) // FILE_FLAG_OPEN_REPARSE_POINT
1954 .access_mode(access_mode)
1955 .open(path)
1956 }
1957
1958 pub fn path_entry_exists(path: &Path) -> Result<bool, String> {
1959 match fs::symlink_metadata(path) {
1960 Ok(_) => Ok(true),
1961 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1962 Err(error) => Err(format!("failed to inspect {}: {error}", path.display())),
1963 }
1964 }
1965
1966 /// Open an existing state file without following its final link/reparse point.
1967 /// `None` is returned only for a genuinely absent entry; an existing unsafe
1968 /// object always fails closed.
1969 pub fn open_existing_regular_file(path: &Path, write: bool) -> Result<Option<fs::File>, String> {
1970 if !path_entry_exists(path)? {
1971 return Ok(None);
1972 }
1973 let mut options = OpenOptions::new();
1974 options.read(true).write(write);
1975 #[cfg(unix)]
1976 {
1977 use std::os::unix::fs::OpenOptionsExt as _;
1978 // A swapped FIFO must not block before the handle can be validated.
1979 options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK);
1980 }
1981 #[cfg(windows)]
1982 {
1983 use std::os::windows::fs::OpenOptionsExt as _;
1984 options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
1985 }
1986 let file = options
1987 .open(path)
1988 .map_err(|e| format!("failed to open {} safely: {e}", path.display()))?;
1989 validate_opened_regular_file(path, &file)?;
1990 Ok(Some(file))
1991 }
1992
1993 #[cfg(unix)]
1994 fn validate_opened_regular_file(path: &Path, file: &fs::File) -> Result<(), String> {
1995 use std::os::unix::fs::MetadataExt as _;
1996
1997 let metadata = file
1998 .metadata()
1999 .map_err(|e| format!("failed to inspect opened {}: {e}", path.display()))?;
2000 if !metadata.is_file() || metadata.nlink() != 1 {
2001 return Err(format!(
2002 "{} must be one regular, non-hard-linked file",
2003 path.display()
2004 ));
2005 }
2006 Ok(())
2007 }
2008
2009 #[cfg(windows)]
2010 fn validate_opened_regular_file(path: &Path, file: &fs::File) -> Result<(), String> {
2011 const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
2012 let metadata = file
2013 .metadata()
2014 .map_err(|e| format!("failed to inspect opened {}: {e}", path.display()))?;
2015 let identity = windows_file_identity(file)
2016 .map_err(|e| format!("failed to identify opened {}: {e}", path.display()))?;
2017 if !metadata.is_file()
2018 || identity.attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
2019 || identity.links != 1
2020 {
2021 return Err(format!(
2022 "{} must be one regular, non-reparse, non-hard-linked file",
2023 path.display()
2024 ));
2025 }
2026 Ok(())
2027 }
2028
2029 #[cfg(all(not(unix), not(windows)))]
2030 fn validate_opened_regular_file(path: &Path, file: &fs::File) -> Result<(), String> {
2031 let metadata = file
2032 .metadata()
2033 .map_err(|e| format!("failed to inspect opened {}: {e}", path.display()))?;
2034 if !metadata.is_file() {
2035 return Err(format!("{} must be a regular file", path.display()));
2036 }
2037 Ok(())
2038 }
2039
2040 pub fn validate_existing_plugin_state_parent(path: &Path) -> Result<(), String> {
2041 let Some(parent) = path
2042 .parent()
2043 .filter(|parent| !parent.as_os_str().is_empty())
2044 else {
2045 return Ok(());
2046 };
2047 match fs::symlink_metadata(parent) {
2048 Ok(_) => validate_plugin_state_directory_for_read(parent),
2049 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
2050 Err(error) => Err(format!(
2051 "failed to inspect plugin state directory {}: {error}",
2052 parent.display()
2053 )),
2054 }
2055 }
2056
2057 #[cfg(unix)]
2058 fn validate_plugin_state_directory_for_read(path: &Path) -> Result<(), String> {
2059 use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _, PermissionsExt as _};
2060
2061 let directory = OpenOptions::new()
2062 .read(true)
2063 .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
2064 .open(path)
2065 .map_err(|error| {
2066 format!("failed to open plugin state directory without following links: {error}")
2067 })?;
2068 let metadata = directory
2069 .metadata()
2070 .map_err(|error| format!("failed to inspect opened plugin state directory: {error}"))?;
2071 // SAFETY: geteuid has no pointer or lifetime preconditions.
2072 let effective_uid = unsafe { libc::geteuid() };
2073 let is_directory = metadata.is_dir();
2074 let public = metadata.uid() != effective_uid || metadata.permissions().mode() & 0o077 != 0;
2075 // Only a directory that fails the fields asks the filesystem whether it can
2076 // express them at all: on a mount that stores ownership this costs nothing,
2077 // and on one that does not the answer — with its warning — is remembered
2078 // per directory, so repeated reads do not repeat the probe or the log line.
2079 let synthesised = is_directory
2080 && public
2081 && matches!(
2082 codewhale_config::private_directory::mount_footing(path),
2083 codewhale_config::private_directory::PrivateFooting::Synthesised { .. }
2084 );
2085 validate_unix_plugin_state_directory_fields(
2086 is_directory,
2087 metadata.uid(),
2088 metadata.permissions().mode(),
2089 effective_uid,
2090 synthesised,
2091 )
2092 }
2093
2094 /// Whether a directory satisfies the private-state guard.
2095 ///
2096 /// `mount_cannot_express_ownership` names a filesystem that reports its own
2097 /// owner and mode for every object (HarmonyOS hmdfs), so neither field can
2098 /// prove anything there. Refusing on such a mount makes plugin state
2099 /// unusable for every app on that platform; accepting keeps the real guards —
2100 /// no-follow, single link, atomic publication — and relies on the mount's own
2101 /// access control for ownership, which is the same tradeoff the credential
2102 /// store makes on the same mount.
2103 #[cfg(unix)]
2104 fn validate_unix_plugin_state_directory_fields(
2105 is_directory: bool,
2106 owner_uid: u32,
2107 mode: u32,
2108 effective_uid: u32,
2109 mount_cannot_express_ownership: bool,
2110 ) -> Result<(), String> {
2111 if !is_directory {
2112 return Err("Plugin state path must be a directory".to_string());
2113 }
2114 if mount_cannot_express_ownership {
2115 return Ok(());
2116 }
2117 if owner_uid != effective_uid || mode & 0o077 != 0 {
2118 return Err(
2119 "Plugin state directory must be current-user-owned and inaccessible to group or other users"
2120 .to_string(),
2121 );
2122 }
2123 Ok(())
2124 }
2125
2126 #[cfg(not(unix))]
2127 fn validate_plugin_state_directory_for_read(_path: &Path) -> Result<(), String> {
2128 Ok(())
2129 }
2130
2131 #[cfg(unix)]
2132 pub fn ensure_private_plugin_state_directory(path: &Path) -> Result<(), String> {
2133 use std::os::unix::fs::DirBuilderExt as _;
2134
2135 if !path_entry_exists(path)? {
2136 let mut builder = fs::DirBuilder::new();
2137 builder.recursive(true).mode(0o700);
2138 builder
2139 .create(path)
2140 .map_err(|error| format!("failed to create plugin state directory: {error}"))?;
2141 }
2142 validate_plugin_state_directory_for_read(path)
2143 }
2144
2145 #[cfg(windows)]
2146 pub fn ensure_private_plugin_state_directory(path: &Path) -> Result<(), String> {
2147 fs::create_dir_all(path)
2148 .map_err(|error| format!("failed to create plugin state directory: {error}"))?;
2149 set_windows_owner_only_acl(path)
2150 }
2151
2152 #[cfg(all(not(unix), not(windows)))]
2153 pub fn ensure_private_plugin_state_directory(path: &Path) -> Result<(), String> {
2154 fs::create_dir_all(path)
2155 .map_err(|error| format!("failed to create plugin state directory: {error}"))
2156 }
2157
2158 #[cfg(windows)]
2159 pub fn harden_plugin_state_file(path: &Path) -> Result<(), String> {
2160 set_windows_owner_only_acl(path)
2161 }
2162
2163 #[cfg(windows)]
2164 fn harden_opened_plugin_state_file(
2165 path: &Path,
2166 file: &fs::File,
2167 owner_mode: WindowsAclOwnerMode,
2168 ) -> Result<(), String> {
2169 validate_opened_regular_file(path, file)?;
2170 ensure_windows_registry_path_still_opened(path, file)?;
2171 apply_windows_owner_only_acl(file, 0x001f_01ff, owner_mode)
2172 }
2173
2174 #[cfg(unix)]
2175 pub fn harden_plugin_state_file(path: &Path) -> Result<(), String> {
2176 // `tighten_mode` keeps the refusal for a filesystem that stores modes and
2177 // tolerates one that assigns its own (HarmonyOS hmdfs), which is the same
2178 // rule the state directory is admitted under. Refusing here would make a
2179 // plugin state file unwritable after a successful write.
2180 codewhale_config::private_directory::tighten_mode(path, 0o600).map_err(|error| {
2181 format!(
2182 "failed to restrict plugin state file permissions for {}: {error}",
2183 path.display()
2184 )
2185 })
2186 }
2187
2188 #[cfg(all(not(unix), not(windows)))]
2189 pub fn harden_plugin_state_file(_path: &Path) -> Result<(), String> {
2190 Ok(())
2191 }
2192
2193 /// The newest persisted review of another built-in with this name, when it
2194 /// may be carried to `id`: `id` has no state yet, and the same-named built-in
2195 /// entry with the most recent review still holds its receipt. A revoked entry
2196 /// is dated by its last review, so revoking blocks carrying until the user
2197 /// reviews a build again; ties go to the revocation. Entries that were never
2198 /// reviewed (for example, disabled before any review) granted nothing and are
2199 /// ignored.
2200 fn builtin_predecessor<'a>(
2201 state: &'a PluginStateFile,
2202 id: &PluginId,
2203 name: &str,
2204 ) -> Option<&'a PersistedPluginState> {
2205 if state.plugins.contains_key(id) {
2206 return None;
2207 }
2208 let builtin = super::types::PluginScope::Builtin.as_str();
2209 let mut newest: Option<(&PersistedPluginState, i64)> = None;
2210 for (other, entry) in &state.plugins {
2211 let mut parts = other.as_str().splitn(3, '/');
2212 if parts.next() != Some(builtin) || parts.nth(1) != Some(name) {
2213 continue;
2214 }
2215 let Some(last_review) = entry.trust.as_ref().or(entry.review_history.last()) else {
2216 continue;
2217 };
2218 let reviewed = chrono::DateTime::parse_from_rfc3339(&last_review.reviewed_at)
2219 .map_or(i64::MIN, |at| at.timestamp_micros());
2220 let revoked = entry.trust.is_none();
2221 if newest.is_none_or(|(_, at)| reviewed > at || (reviewed == at && revoked)) {
2222 newest = Some((entry, reviewed));
2223 }
2224 }
2225 newest
2226 .map(|(entry, _)| entry)
2227 .filter(|entry| entry.trust.is_some())
2228 }
2229
2230 /// Directory name of a plugin id's runtime snapshots under `.runtime/v2`.
2231 fn runtime_stage_key(id: &PluginId) -> String {
2232 let mut hasher = Sha256::new();
2233 hasher.update(b"codewhale-plugin-stage-v2\0");
2234 hasher.update(id.as_str().as_bytes());
2235 hasher
2236 .finalize()
2237 .iter()
2238 .map(|byte| format!("{byte:02x}"))
2239 .collect::<String>()
2240 }
2241
2242 fn runtime_stage_path(state_path: &Path, id: &PluginId, content_hash: &str) -> PathBuf {
2243 let key = runtime_stage_key(id);
2244 let state_parent = state_path.parent().unwrap_or_else(|| Path::new("."));
2245 let state_parent = state_parent
2246 .canonicalize()
2247 .unwrap_or_else(|_| state_parent.to_path_buf());
2248 state_parent
2249 .join(".runtime")
2250 .join("v2")
2251 .join(key)
2252 .join(content_hash)
2253 }
2254
2255 fn staged_bundle_rejection(
2256 root: &Path,
2257 content_hash: &str,
2258 capability_hash: &str,
2259 ) -> Option<String> {
2260 let finalized = match verify_finalized_stage_root(root, None) {
2261 Ok(finalized) => finalized,
2262 Err(reason) => return Some(format!("stage root: {reason}")),
2263 };
2264 if !staged_bundle_content_matches(root, content_hash, capability_hash) {
2265 return Some("content or capability identity differs".to_string());
2266 }
2267 verify_finalized_stage_root(root, Some(&finalized))
2268 .err()
2269 .map(|reason| format!("final root check: {reason}"))
2270 }
2271
2272 fn staged_bundle_matches(root: &Path, content_hash: &str, capability_hash: &str) -> bool {
2273 staged_bundle_rejection(root, content_hash, capability_hash).is_none()
2274 }
2275
2276 pub(super) fn verify_finalized_stage_root(
2277 root: &Path,
2278 expected: Option<&fs::File>,
2279 ) -> Result<fs::File, String> {
2280 let metadata = fs::symlink_metadata(root)
2281 .map_err(|error| format!("failed to inspect plugin runtime root: {error}"))?;
2282 if !metadata.is_dir() || metadata_is_link_or_reparse(&metadata) {
2283 return Err("Plugin runtime root is not an ordinary directory".to_string());
2284 }
2285 let (_, held) = codewhale_util::workspace_dir::open_workspace_directory(root)
2286 .map_err(|error| format!("failed to retain plugin runtime root: {error}"))?;
2287 if let Some(expected) = expected
2288 && !codewhale_util::files::same_file(expected, &held)
2289 .map_err(|error| format!("failed to identify plugin runtime root: {error}"))?
2290 {
2291 return Err("Plugin runtime root changed while it was read".to_string());
2292 }
2293 #[cfg(unix)]
2294 {
2295 use std::os::unix::fs::PermissionsExt as _;
2296 let metadata = held
2297 .metadata()
2298 .map_err(|error| format!("failed to inspect retained plugin runtime root: {error}"))?;
2299 if metadata.permissions().mode() & 0o7777 != 0o500 {
2300 return Err("Plugin runtime root has not been finalized read-only".to_string());
2301 }
2302 }
2303 #[cfg(windows)]
2304 codewhale_config::private_directory::verify_windows_finalized_read_only_handle(&held).map_err(
2305 |error| format!("Plugin runtime root has not been finalized read-only: {error:#}"),
2306 )?;
2307 #[cfg(not(any(unix, windows)))]
2308 {
2309 Err("Plugin runtime root finalization cannot be verified on this platform".to_string())
2310 }
2311 #[cfg(any(unix, windows))]
2312 {
2313 Ok(held)
2314 }
2315 }
2316
2317 fn staged_bundle_content_matches(root: &Path, content_hash: &str, capability_hash: &str) -> bool {
2318 let Some(manifest_path) = super::agent_plugin::resolve_manifest_path(root) else {
2319 return false;
2320 };
2321 super::manifest::PluginManifest::validate_from_path(&manifest_path).is_ok_and(|validated| {
2322 validated.content_hash == content_hash
2323 && validated.capability_hash == capability_hash
2324 && root
2325 .canonicalize()
2326 .is_ok_and(|root| validated.canonical_root == root)
2327 })
2328 }
2329
2330 type RecoveryAttemptKey = (PathBuf, PathBuf, String, String, String, u64);
2331
2332 fn recovery_attempt_key(
2333 state_path: &Path,
2334 policy_path: &Path,
2335 plugin: &LoadedPlugin,
2336 ) -> RecoveryAttemptKey {
2337 (
2338 state_path.to_path_buf(),
2339 policy_path.to_path_buf(),
2340 plugin.id.as_str().to_string(),
2341 plugin.content_hash.clone(),
2342 plugin.capability_hash.clone(),
2343 plugin.state_generation,
2344 )
2345 }
2346
2347 fn recovery_attempts() -> &'static std::sync::Mutex<BTreeMap<RecoveryAttemptKey, String>> {
2348 static ATTEMPTS: std::sync::Mutex<BTreeMap<RecoveryAttemptKey, String>> =
2349 std::sync::Mutex::new(BTreeMap::new());
2350 &ATTEMPTS
2351 }
2352
2353 fn verify_recovery_policy(policy_path: &Path, id: &PluginId) -> Result<(), String> {
2354 match load_managed_policy(policy_path) {
2355 ManagedPolicyOutcome::Absent => Ok(()),
2356 ManagedPolicyOutcome::Loaded(policy) if policy.allows(id) => Ok(()),
2357 ManagedPolicyOutcome::Loaded(_) => {
2358 Err("Managed plugin policy forbids recovery".to_string())
2359 }
2360 ManagedPolicyOutcome::Invalid(_) => Err("Managed plugin policy is invalid".to_string()),
2361 }
2362 }
2363
2364 fn verify_recovery_path(state_path: &Path, destination: &Path) -> Result<(), String> {
2365 let base = state_path
2366 .parent()
2367 .ok_or("Plugin state path has no parent")?;
2368 let metadata = fs::symlink_metadata(base)
2369 .map_err(|error| format!("Failed to inspect plugin state parent: {error}"))?;
2370 if !metadata.is_dir() || metadata_is_link_or_reparse(&metadata) {
2371 return Err("Plugin state parent is not an ordinary directory".to_string());
2372 }
2373 let base = base
2374 .canonicalize()
2375 .map_err(|error| format!("Failed to resolve plugin state parent: {error}"))?;
2376 codewhale_util::files::reject_linked_path(&base, destination)
2377 .map_err(|error| format!("Unsafe plugin runtime snapshot path: {error}"))
2378 }
2379
2380 #[cfg(unix)]
2381 fn open_recovery_directory(path: &Path) -> Result<fs::File, String> {
2382 use std::os::unix::fs::OpenOptionsExt as _;
2383 let file = OpenOptions::new()
2384 .read(true)
2385 .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
2386 .open(path)
2387 .map_err(|error| format!("Failed to retain recovery directory: {error}"))?;
2388 if !file
2389 .metadata()
2390 .map_err(|error| format!("Failed to inspect recovery directory: {error}"))?
2391 .is_dir()
2392 {
2393 return Err("Recovery directory changed type".to_string());
2394 }
2395 Ok(file)
2396 }
2397
2398 #[derive(Clone, Copy, PartialEq, Eq)]
2399 enum StageIntent {
2400 Review,
2401 Recovery,
2402 }
2403
2404 fn stage_bundle(
2405 state_path: &Path,
2406 plugin: &LoadedPlugin,
2407 intent: StageIntent,
2408 ) -> Result<PathBuf, String> {
2409 // Resolve the state directory before deriving the content-addressed path.
2410 // On macOS an existing ancestor such as `/var` canonicalizes to
2411 // `/private/var`; when the final `state/` directory does not exist yet,
2412 // deriving the destination first would preserve the non-canonical prefix
2413 // and the subsequent containment proof would correctly reject it as an
2414 // escape. Trust is already the mutating boundary, so creating this private
2415 // parent here is both safe and necessary for a stable path identity.
2416 let state_parent = state_path
2417 .parent()
2418 .ok_or_else(|| "plugin state path has no parent directory".to_string())?;
2419 ensure_private_plugin_state_directory(state_parent)?;
2420 let destination = runtime_stage_path(state_path, &plugin.id, &plugin.content_hash);
2421 if intent == StageIntent::Recovery {
2422 verify_recovery_path(state_path, &destination)?;
2423 }
2424 match fs::symlink_metadata(&destination) {
2425 Ok(metadata) => {
2426 if !metadata.is_dir()
2427 || metadata_is_link_or_reparse(&metadata)
2428 || !staged_bundle_content_matches(
2429 &destination,
2430 &plugin.content_hash,
2431 &plugin.capability_hash,
2432 )
2433 {
2434 return Err(
2435 "Existing Codewhale plugin runtime snapshot failed content validation; remove the exact .runtime entry and review again"
2436 .to_string(),
2437 );
2438 }
2439 if intent == StageIntent::Review {
2440 // Trust is a mutating boundary, so it may upgrade an older verified
2441 // snapshot to the finalized non-writable permission contract.
2442 harden_staged_tree(&destination)?;
2443 } else if !staged_bundle_matches(
2444 &destination,
2445 &plugin.content_hash,
2446 &plugin.capability_hash,
2447 ) {
2448 return Err("Existing plugin runtime snapshot is not finalized".to_string());
2449 }
2450 return Ok(destination.canonicalize().unwrap_or(destination));
2451 }
2452 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
2453 Err(error) => {
2454 return Err(format!(
2455 "failed to inspect plugin runtime snapshot: {error}"
2456 ));
2457 }
2458 }
2459
2460 let parent = destination
2461 .parent()
2462 .ok_or_else(|| "plugin runtime snapshot has no parent".to_string())?;
2463 ensure_private_runtime_parent(state_path, parent)?;
2464 if intent == StageIntent::Recovery {
2465 verify_recovery_path(state_path, &destination)?;
2466 }
2467 let temporary = parent.join(format!(".staging-{}", uuid::Uuid::new_v4().simple()));
2468 fs::create_dir(&temporary)
2469 .map_err(|e| format!("failed to create temporary plugin runtime snapshot: {e}"))?;
2470 set_owner_only_directory(&temporary)?;
2471
2472 let staged = (|| {
2473 copy_bundle_tree(&plugin.canonical_root, &temporary)?;
2474 if !staged_bundle_content_matches(&temporary, &plugin.content_hash, &plugin.capability_hash)
2475 {
2476 return Err(
2477 "Plugin bundle changed while Codewhale was staging it; no runtime authority was granted"
2478 .to_string(),
2479 );
2480 }
2481 // Finalize descendants before activation, but keep the temporary root
2482 // owner-writable through the atomic rename. macOS rejects renaming a
2483 // directory whose own mode is already 0500 even when both parents are
2484 // writable. The destination root is hardened immediately after the
2485 // rename, before its path is returned or persisted as authority.
2486 harden_staged_tree_contents(&temporary)?;
2487 if intent == StageIntent::Recovery {
2488 verify_recovery_path(state_path, &destination)?;
2489 }
2490 #[cfg(unix)]
2491 let recovery_root = if intent == StageIntent::Recovery {
2492 Some(open_recovery_directory(&temporary)?)
2493 } else {
2494 None
2495 };
2496 if let Err(error) = super::builtin::publish_snapshot(&temporary, &destination) {
2497 // Another process may have won the same content-addressed race.
2498 // Reuse only after exact validation and hardening at this explicit
2499 // mutation boundary; every other rename failure remains fatal.
2500 if fs::symlink_metadata(&destination)
2501 .is_ok_and(|metadata| metadata.is_dir() && !metadata_is_link_or_reparse(&metadata))
2502 && staged_bundle_content_matches(
2503 &destination,
2504 &plugin.content_hash,
2505 &plugin.capability_hash,
2506 )
2507 {
2508 if intent == StageIntent::Review {
2509 harden_staged_tree(&destination)?;
2510 } else if !staged_bundle_matches(
2511 &destination,
2512 &plugin.content_hash,
2513 &plugin.capability_hash,
2514 ) {
2515 return Err("Raced plugin runtime snapshot is not finalized".to_string());
2516 }
2517 return destination.canonicalize().map_err(|e| {
2518 format!("failed to finalize raced plugin runtime snapshot path: {e}")
2519 });
2520 }
2521 return Err(format!(
2522 "failed to activate content-addressed plugin runtime snapshot: {error}"
2523 ));
2524 }
2525 if intent == StageIntent::Recovery {
2526 verify_recovery_path(state_path, &destination)?;
2527 }
2528 #[cfg(unix)]
2529 if let Some(root) = recovery_root {
2530 use std::os::unix::fs::PermissionsExt as _;
2531 let published = open_recovery_directory(&destination)?;
2532 if !codewhale_util::files::same_file(&root, &published)
2533 .map_err(|error| format!("Failed to identify recovered snapshot: {error}"))?
2534 {
2535 return Err("Recovered snapshot changed before finalization".to_string());
2536 }
2537 root.set_permissions(fs::Permissions::from_mode(0o500))
2538 .map_err(|error| format!("Failed to finalize recovered snapshot: {error}"))?;
2539 verify_finalized_stage_root(&destination, Some(&root))?;
2540 } else {
2541 set_staged_read_only_directory(&destination)?;
2542 }
2543 #[cfg(not(unix))]
2544 set_staged_read_only_directory(&destination)?;
2545 destination
2546 .canonicalize()
2547 .map_err(|e| format!("failed to finalize plugin runtime snapshot path: {e}"))
2548 })();
2549 if intent == StageIntent::Review && staged.is_err() && temporary.exists() {
2550 let _ = fs::remove_dir_all(&temporary);
2551 }
2552 staged
2553 }
2554
2555 fn ensure_private_runtime_parent(state_path: &Path, parent: &Path) -> Result<(), String> {
2556 let configured_base = state_path
2557 .parent()
2558 .ok_or_else(|| "plugin state path has no parent directory".to_string())?;
2559 ensure_private_plugin_state_directory(configured_base)?;
2560 let base_metadata = fs::symlink_metadata(configured_base)
2561 .map_err(|e| format!("failed to inspect plugin state directory: {e}"))?;
2562 if metadata_is_link_or_reparse(&base_metadata) || !base_metadata.is_dir() {
2563 return Err(
2564 "plugin state directory must not be a symbolic link or reparse point".to_string(),
2565 );
2566 }
2567 // `runtime_stage_path` canonicalizes the same parent. Match that identity
2568 // here as well (notably `/var` -> `/private/var` on macOS) before proving
2569 // that every runtime component stays beneath the state directory.
2570 let base = configured_base
2571 .canonicalize()
2572 .map_err(|e| format!("failed to canonicalize plugin state directory: {e}"))?;
2573 let relative = parent
2574 .strip_prefix(&base)
2575 .or_else(|_| parent.strip_prefix(configured_base))
2576 .map_err(|_| "plugin runtime snapshot escaped the state directory".to_string())?;
2577 let mut cursor = base;
2578 for component in relative.components() {
2579 use std::path::Component;
2580 let Component::Normal(component) = component else {
2581 return Err("plugin runtime snapshot contains an invalid path component".to_string());
2582 };
2583 cursor.push(component);
2584 match fs::symlink_metadata(&cursor) {
2585 Ok(metadata) if metadata_is_link_or_reparse(&metadata) => {
2586 return Err(
2587 "plugin runtime snapshot directory may not traverse symbolic links or reparse points"
2588 .to_string(),
2589 );
2590 }
2591 Ok(metadata) if !metadata.is_dir() => {
2592 return Err("plugin runtime snapshot parent is not a directory".to_string());
2593 }
2594 Ok(_) => {}
2595 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
2596 match fs::create_dir(&cursor) {
2597 Ok(()) => {}
2598 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
2599 let metadata = fs::symlink_metadata(&cursor).map_err(|e| {
2600 format!(
2601 "failed to inspect concurrently created plugin runtime snapshot directory: {e}"
2602 )
2603 })?;
2604 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
2605 return Err(
2606 "concurrently created plugin runtime snapshot parent is not a safe directory"
2607 .to_string(),
2608 );
2609 }
2610 }
2611 Err(error) => {
2612 return Err(format!(
2613 "failed to create plugin runtime snapshot directory: {error}"
2614 ));
2615 }
2616 }
2617 }
2618 Err(error) => {
2619 return Err(format!(
2620 "failed to inspect plugin runtime snapshot directory: {error}"
2621 ));
2622 }
2623 }
2624 set_owner_only_directory(&cursor)?;
2625 }
2626 Ok(())
2627 }
2628
2629 #[derive(Default)]
2630 struct StageBudget {
2631 files: usize,
2632 bytes: u64,
2633 }
2634
2635 fn copy_bundle_tree(source: &Path, destination: &Path) -> Result<(), String> {
2636 let mut budget = StageBudget::default();
2637 copy_bundle_tree_bounded(source, destination, &mut budget)
2638 }
2639
2640 #[cfg(not(unix))]
2641 fn copy_bundle_tree_bounded(
2642 source: &Path,
2643 destination: &Path,
2644 budget: &mut StageBudget,
2645 ) -> Result<(), String> {
2646 use std::io::Read as _;
2647 let metadata = fs::symlink_metadata(source)
2648 .map_err(|e| format!("failed to inspect plugin content during staging: {e}"))?;
2649 if metadata_is_link_or_reparse(&metadata) {
2650 return Err("Plugin content changed into a symbolic link during staging".to_string());
2651 }
2652 if !metadata.is_dir() {
2653 return Err("Plugin runtime source is not a directory".to_string());
2654 }
2655 #[cfg(windows)]
2656 let source_guard = open_windows_bundle_directory(source)?;
2657 #[cfg(windows)]
2658 ensure_windows_registry_path_still_opened(source, &source_guard)?;
2659 let mut entries = fs::read_dir(source)
2660 .map_err(|e| format!("failed to read plugin content during staging: {e}"))?
2661 .collect::<Result<Vec<_>, _>>()
2662 .map_err(|e| format!("failed to enumerate plugin content during staging: {e}"))?;
2663 entries.sort_by_key(fs::DirEntry::file_name);
2664 for entry in entries {
2665 let source_path = entry.path();
2666 let destination_path = destination.join(entry.file_name());
2667 let metadata = fs::symlink_metadata(&source_path)
2668 .map_err(|e| format!("failed to inspect plugin entry during staging: {e}"))?;
2669 if metadata_is_link_or_reparse(&metadata) {
2670 return Err("Plugin content may not contain symbolic links".to_string());
2671 }
2672 if metadata.is_dir() {
2673 fs::create_dir(&destination_path)
2674 .map_err(|e| format!("failed to create staged plugin directory: {e}"))?;
2675 set_owner_only_directory(&destination_path)?;
2676 copy_bundle_tree_bounded(&source_path, &destination_path, budget)?;
2677 } else if metadata.is_file() {
2678 budget.files = budget.files.saturating_add(1);
2679 if budget.files > 16_384 {
2680 return Err("Plugin content exceeded the staging file limit".to_string());
2681 }
2682 let mut source_file = codewhale_util::bundle_file::open_bundle_file(&source_path)
2683 .map_err(|e| format!("failed to open plugin file without following links: {e}"))?;
2684 #[cfg(windows)]
2685 ensure_windows_registry_path_still_opened(&source_path, &source_file)?;
2686 let mut destination_file = OpenOptions::new()
2687 .create_new(true)
2688 .write(true)
2689 .open(&destination_path)
2690 .map_err(|e| format!("failed to create staged plugin file: {e}"))?;
2691 let mut buffer = [0_u8; 64 * 1024];
2692 loop {
2693 let read = source_file
2694 .read(&mut buffer)
2695 .map_err(|e| format!("failed to read plugin file during staging: {e}"))?;
2696 if read == 0 {
2697 break;
2698 }
2699 budget.bytes = budget.bytes.saturating_add(read as u64);
2700 if budget.bytes > 256 * 1024 * 1024 {
2701 return Err("Plugin content exceeded the staging byte limit".to_string());
2702 }
2703 destination_file
2704 .write_all(&buffer[..read])
2705 .map_err(|e| format!("failed to write staged plugin file: {e}"))?;
2706 }
2707 destination_file
2708 .sync_all()
2709 .map_err(|e| format!("failed to sync staged plugin file: {e}"))?;
2710 #[cfg(windows)]
2711 // The containing staging directory is already owner-only. Close
2712 // the writer before reopening this path with the ACL hardener's
2713 // deliberately restrictive share mode.
2714 drop(destination_file);
2715 preserve_owner_only_file_mode(&destination_path, &metadata)?;
2716 #[cfg(windows)]
2717 ensure_windows_registry_path_still_opened(&source_path, &source_file)?;
2718 } else {
2719 return Err(
2720 "Plugin content must contain only regular files and directories".to_string(),
2721 );
2722 }
2723 }
2724 #[cfg(windows)]
2725 ensure_windows_registry_path_still_opened(source, &source_guard)?;
2726 Ok(())
2727 }
2728
2729 #[cfg(windows)]
2730 fn open_windows_bundle_directory(path: &Path) -> Result<fs::File, String> {
2731 use std::os::windows::fs::OpenOptionsExt as _;
2732
2733 let file = OpenOptions::new()
2734 .read(true)
2735 .share_mode(0x0000_0001)
2736 .custom_flags(0x0220_0000) // BACKUP_SEMANTICS | OPEN_REPARSE_POINT
2737 .open(path)
2738 .map_err(|e| format!("failed to open plugin directory safely: {e}"))?;
2739 let metadata = file
2740 .metadata()
2741 .map_err(|e| format!("failed to inspect opened plugin directory: {e}"))?;
2742 let identity = windows_file_identity(&file)
2743 .map_err(|e| format!("failed to identify opened plugin directory: {e}"))?;
2744 if !metadata.is_dir() || identity.attributes & 0x0000_0400 != 0 {
2745 return Err("Plugin directory changed into a reparse point during staging".to_string());
2746 }
2747 Ok(file)
2748 }
2749
2750 #[cfg(windows)]
2751 fn ensure_windows_registry_path_still_opened(path: &Path, opened: &fs::File) -> Result<(), String> {
2752 let after = fs::symlink_metadata(path)
2753 .map_err(|e| format!("failed to re-inspect staged source path: {e}"))?;
2754 if metadata_is_link_or_reparse(&after) {
2755 return Err("Plugin path changed into a reparse point during staging".to_string());
2756 }
2757 let expect_directory = if after.is_dir() {
2758 true
2759 } else if after.is_file() {
2760 false
2761 } else {
2762 return Err("Plugin path changed into an unsupported object during staging".to_string());
2763 };
2764 let current = codewhale_util::bundle_file::open_bundle_identity_probe(path, expect_directory)
2765 .map_err(|e| format!("failed to reopen staged source path safely: {e}"))?;
2766 let opened = windows_file_identity(opened)
2767 .map_err(|e| format!("failed to identify retained plugin handle: {e}"))?;
2768 let current = windows_file_identity(&current)
2769 .map_err(|e| format!("failed to identify current plugin path: {e}"))?;
2770 if opened.volume != current.volume || opened.index != current.index {
2771 return Err("Plugin path identity changed while staging".to_string());
2772 }
2773 if opened.links != 1 && after.is_file() {
2774 return Err("Plugin content may not contain hard-linked files".to_string());
2775 }
2776 Ok(())
2777 }
2778
2779 #[cfg(unix)]
2780 fn copy_bundle_tree_bounded(
2781 source: &Path,
2782 destination: &Path,
2783 budget: &mut StageBudget,
2784 ) -> Result<(), String> {
2785 use std::ffi::CString;
2786 use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
2787 use std::os::unix::ffi::OsStrExt;
2788
2789 let source = CString::new(source.as_os_str().as_bytes())
2790 .map_err(|_| "plugin runtime source path contains an invalid byte".to_string())?;
2791 // SAFETY: `source` is a NUL-terminated path and successful descriptors
2792 // are immediately owned by `OwnedFd`.
2793 let fd = unsafe {
2794 libc::open(
2795 source.as_ptr(),
2796 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
2797 )
2798 };
2799 if fd < 0 {
2800 return Err(format!(
2801 "failed to open plugin root without following links: {}",
2802 std::io::Error::last_os_error()
2803 ));
2804 }
2805 // SAFETY: `fd` is a unique successful result from `open` above.
2806 let fd = unsafe { OwnedFd::from_raw_fd(fd) };
2807 copy_bundle_directory_fd(fd.as_raw_fd(), destination, budget)
2808 }
2809
2810 #[cfg(unix)]
2811 fn copy_bundle_directory_fd(
2812 source_fd: std::os::fd::RawFd,
2813 destination: &Path,
2814 budget: &mut StageBudget,
2815 ) -> Result<(), String> {
2816 use std::ffi::{CStr, CString, OsString};
2817 use std::io::Read as _;
2818 use std::mem::MaybeUninit;
2819 use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
2820 use std::os::unix::ffi::OsStringExt;
2821
2822 // `fdopendir` owns its descriptor, so duplicate the directory fd retained
2823 // by this stack frame for subsequent `openat` calls.
2824 // SAFETY: `source_fd` is an open directory descriptor.
2825 let iter_fd = unsafe { libc::dup(source_fd) };
2826 if iter_fd < 0 {
2827 return Err(format!(
2828 "failed to duplicate plugin directory descriptor: {}",
2829 std::io::Error::last_os_error()
2830 ));
2831 }
2832 // SAFETY: `iter_fd` is a fresh descriptor and ownership transfers to DIR.
2833 let directory = unsafe { libc::fdopendir(iter_fd) };
2834 if directory.is_null() {
2835 // SAFETY: fdopendir failed, so ownership did not transfer.
2836 unsafe { libc::close(iter_fd) };
2837 return Err(format!(
2838 "failed to enumerate plugin directory safely: {}",
2839 std::io::Error::last_os_error()
2840 ));
2841 }
2842 let mut names = Vec::new();
2843 loop {
2844 // SAFETY: `directory` remains valid until closed below.
2845 let entry = unsafe { libc::readdir(directory) };
2846 if entry.is_null() {
2847 break;
2848 }
2849 // SAFETY: POSIX dirent d_name is NUL-terminated for returned entries.
2850 let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }.to_bytes();
2851 if name == b"." || name == b".." {
2852 continue;
2853 }
2854 names.push(OsString::from_vec(name.to_vec()));
2855 }
2856 // SAFETY: closes DIR and its duplicated descriptor exactly once.
2857 unsafe { libc::closedir(directory) };
2858 names.sort();
2859
2860 for name in names {
2861 let name_c = CString::new(name.clone().into_vec())
2862 .map_err(|_| "plugin entry name contains an invalid byte".to_string())?;
2863 let mut stat = MaybeUninit::<libc::stat>::zeroed();
2864 // SAFETY: source_fd and name are valid; stat points to writable memory.
2865 if unsafe {
2866 libc::fstatat(
2867 source_fd,
2868 name_c.as_ptr(),
2869 stat.as_mut_ptr(),
2870 libc::AT_SYMLINK_NOFOLLOW,
2871 )
2872 } != 0
2873 {
2874 return Err(format!(
2875 "failed to inspect plugin entry safely: {}",
2876 std::io::Error::last_os_error()
2877 ));
2878 }
2879 // SAFETY: fstatat initialized stat after returning success.
2880 let stat = unsafe { stat.assume_init() };
2881 let kind = stat.st_mode & libc::S_IFMT;
2882 let destination_path = destination.join(&name);
2883 if kind == libc::S_IFDIR {
2884 // SAFETY: openat is anchored to the already-open parent and
2885 // O_NOFOLLOW prevents a concurrent directory-to-symlink swap.
2886 let child_fd = unsafe {
2887 libc::openat(
2888 source_fd,
2889 name_c.as_ptr(),
2890 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
2891 )
2892 };
2893 if child_fd < 0 {
2894 return Err(format!(
2895 "failed to open plugin directory safely: {}",
2896 std::io::Error::last_os_error()
2897 ));
2898 }
2899 // SAFETY: unique descriptor returned by openat.
2900 let child_fd = unsafe { OwnedFd::from_raw_fd(child_fd) };
2901 fs::create_dir(&destination_path)
2902 .map_err(|e| format!("failed to create staged plugin directory: {e}"))?;
2903 set_owner_only_directory(&destination_path)?;
2904 copy_bundle_directory_fd(child_fd.as_raw_fd(), &destination_path, budget)?;
2905 } else if kind == libc::S_IFREG {
2906 if stat.st_nlink != 1 {
2907 return Err("Plugin content may not contain hard-linked files".to_string());
2908 }
2909 budget.files = budget.files.saturating_add(1);
2910 if budget.files > 16_384 {
2911 return Err("Plugin content exceeded the staging file limit".to_string());
2912 }
2913 // SAFETY: openat is anchored and O_NOFOLLOW prevents a file swap
2914 // to a symbolic link between metadata inspection and open.
2915 let file_fd = unsafe {
2916 libc::openat(
2917 source_fd,
2918 name_c.as_ptr(),
2919 libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
2920 )
2921 };
2922 if file_fd < 0 {
2923 return Err(format!(
2924 "failed to open plugin file safely: {}",
2925 std::io::Error::last_os_error()
2926 ));
2927 }
2928 // SAFETY: unique descriptor returned by openat.
2929 let mut source_file = unsafe { fs::File::from_raw_fd(file_fd) };
2930 let opened = source_file
2931 .metadata()
2932 .map_err(|e| format!("failed to inspect opened plugin file: {e}"))?;
2933 if !opened.is_file() {
2934 return Err("Plugin entry changed type during staging".to_string());
2935 }
2936 let mut destination_file = OpenOptions::new()
2937 .create_new(true)
2938 .write(true)
2939 .open(&destination_path)
2940 .map_err(|e| format!("failed to create staged plugin file: {e}"))?;
2941 let mut buffer = [0_u8; 64 * 1024];
2942 loop {
2943 let read = source_file
2944 .read(&mut buffer)
2945 .map_err(|e| format!("failed to read plugin file during staging: {e}"))?;
2946 if read == 0 {
2947 break;
2948 }
2949 budget.bytes = budget.bytes.saturating_add(read as u64);
2950 if budget.bytes > 256 * 1024 * 1024 {
2951 return Err("Plugin content exceeded the staging byte limit".to_string());
2952 }
2953 destination_file
2954 .write_all(&buffer[..read])
2955 .map_err(|e| format!("failed to write staged plugin file: {e}"))?;
2956 }
2957 destination_file
2958 .sync_all()
2959 .map_err(|e| format!("failed to sync staged plugin file: {e}"))?;
2960 preserve_owner_only_file_mode(&destination_path, &opened)?;
2961 } else if kind == libc::S_IFLNK {
2962 return Err("Plugin content may not contain symbolic links".to_string());
2963 } else {
2964 return Err(
2965 "Plugin content must contain only regular files and directories".to_string(),
2966 );
2967 }
2968 }
2969 Ok(())
2970 }
2971
2972 pub(super) fn harden_staged_tree(path: &Path) -> Result<(), String> {
2973 let metadata = fs::symlink_metadata(path)
2974 .map_err(|e| format!("failed to harden staged plugin content: {e}"))?;
2975 if metadata_is_link_or_reparse(&metadata) {
2976 return Err(
2977 "Staged plugin content changed into a symbolic link or reparse point before hardening"
2978 .to_string(),
2979 );
2980 }
2981 if metadata.is_dir() {
2982 let entries = fs::read_dir(path)
2983 .map_err(|e| format!("failed to read staged plugin content: {e}"))?
2984 .collect::<Result<Vec<_>, _>>()
2985 .map_err(|e| format!("failed to enumerate staged plugin content: {e}"))?;
2986 for entry in entries {
2987 harden_staged_tree(&entry.path())?;
2988 }
2989 set_staged_read_only_directory(path)?;
2990 } else if metadata.is_file() {
2991 set_staged_read_only_file(path, &metadata)?;
2992 } else {
2993 return Err("Staged plugin content changed type before activation".to_string());
2994 }
2995 Ok(())
2996 }
2997
2998 #[cfg(all(unix, any(test, feature = "test-support")))]
2999 pub(super) fn open_staged_fixture_target(path: &Path) -> Result<fs::File, String> {
3000 use std::os::unix::fs::OpenOptionsExt as _;
3001
3002 OpenOptions::new()
3003 .read(true)
3004 .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
3005 .open(path)
3006 .map_err(|error| format!("failed to retain staged fixture object: {error}"))
3007 }
3008
3009 #[cfg(all(windows, any(test, feature = "test-support")))]
3010 pub(super) fn open_staged_fixture_target(path: &Path) -> Result<fs::File, String> {
3011 open_windows_acl_target(path, 0x0006_0081).map_err(WindowsAclTargetOpenError::into_message)
3012 }
3013
3014 #[cfg(all(not(any(unix, windows)), any(test, feature = "test-support")))]
3015 pub(super) fn open_staged_fixture_target(_path: &Path) -> Result<fs::File, String> {
3016 Err("staged fixture permissions cannot be retained on this platform".to_string())
3017 }
3018
3019 #[cfg(all(unix, any(test, feature = "test-support")))]
3020 pub(super) fn restore_staged_fixture_target(
3021 file: &fs::File,
3022 permissions: &fs::Permissions,
3023 ) -> Result<(), String> {
3024 file.set_permissions(permissions.clone())
3025 .map_err(|error| format!("failed to restore staged fixture permissions: {error}"))
3026 }
3027
3028 #[cfg(all(windows, any(test, feature = "test-support")))]
3029 pub(super) fn restore_staged_fixture_target(
3030 file: &fs::File,
3031 _permissions: &fs::Permissions,
3032 ) -> Result<(), String> {
3033 apply_windows_owner_only_acl(file, 0x001f_01ff, WindowsAclOwnerMode::VerifyCurrentUser)
3034 }
3035
3036 #[cfg(all(not(any(unix, windows)), any(test, feature = "test-support")))]
3037 pub(super) fn restore_staged_fixture_target(
3038 _file: &fs::File,
3039 _permissions: &fs::Permissions,
3040 ) -> Result<(), String> {
3041 Err("staged fixture permissions cannot be restored on this platform".to_string())
3042 }
3043
3044 fn harden_staged_tree_contents(path: &Path) -> Result<(), String> {
3045 let metadata = fs::symlink_metadata(path)
3046 .map_err(|e| format!("failed to harden staged plugin root: {e}"))?;
3047 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
3048 return Err("Staged plugin root changed type before activation".to_string());
3049 }
3050 let entries = fs::read_dir(path)
3051 .map_err(|e| format!("failed to read staged plugin root: {e}"))?
3052 .collect::<Result<Vec<_>, _>>()
3053 .map_err(|e| format!("failed to enumerate staged plugin root: {e}"))?;
3054 for entry in entries {
3055 harden_staged_tree(&entry.path())?;
3056 }
3057 Ok(())
3058 }
3059
3060 #[cfg(unix)]
3061 fn set_staged_read_only_directory(path: &Path) -> Result<(), String> {
3062 use std::os::unix::fs::PermissionsExt as _;
3063 fs::set_permissions(path, fs::Permissions::from_mode(0o500))
3064 .map_err(|e| format!("failed to make staged plugin directory non-writable: {e}"))
3065 }
3066
3067 #[cfg(windows)]
3068 fn set_staged_read_only_directory(path: &Path) -> Result<(), String> {
3069 // GENERIC_READ | GENERIC_EXECUTE. Descendants are hardened explicitly, so
3070 // the root needs no inheriting ACE; an inheritable generic-rights ACE is
3071 // stored as more than one explicit ACE on a directory.
3072 set_windows_owner_only_acl_with_mask_and_inheritance(path, 0xa000_0000, false)
3073 }
3074
3075 #[cfg(all(not(unix), not(windows)))]
3076 fn set_staged_read_only_directory(_path: &Path) -> Result<(), String> {
3077 Err("Plugin runtime staging cannot make directories non-writable on this platform".to_string())
3078 }
3079
3080 #[cfg(unix)]
3081 fn set_staged_read_only_file(path: &Path, source: &fs::Metadata) -> Result<(), String> {
3082 preserve_owner_only_file_mode(path, source)
3083 }
3084
3085 #[cfg(windows)]
3086 fn set_staged_read_only_file(path: &Path, source: &fs::Metadata) -> Result<(), String> {
3087 preserve_owner_only_file_mode(path, source)
3088 }
3089
3090 #[cfg(all(not(unix), not(windows)))]
3091 fn set_staged_read_only_file(path: &Path, source: &fs::Metadata) -> Result<(), String> {
3092 preserve_owner_only_file_mode(path, source)
3093 }
3094
3095 #[cfg(unix)]
3096 fn set_owner_only_directory(path: &Path) -> Result<(), String> {
3097 codewhale_config::private_directory::tighten_mode(path, 0o700).map_err(|error| {
3098 format!(
3099 "failed to restrict plugin runtime directory permissions for {}: {error}",
3100 path.display()
3101 )
3102 })
3103 }
3104
3105 #[cfg(windows)]
3106 fn set_owner_only_directory(path: &Path) -> Result<(), String> {
3107 set_windows_owner_only_acl(path)
3108 }
3109
3110 #[cfg(windows)]
3111 fn set_windows_owner_only_acl(path: &Path) -> Result<(), String> {
3112 set_windows_owner_only_acl_with_mask(path, 0x001f_01ff)
3113 }
3114
3115 #[cfg(windows)]
3116 #[derive(Clone, Copy)]
3117 enum WindowsAclOwnerMode {
3118 // The handle has WRITE_OWNER, so restoring the current-user ownership and
3119 // DACL together keeps the authority boundary atomic.
3120 NormalizeCurrentUser,
3121 // A previously hardened current-user-owned object may deliberately deny
3122 // WRITE_OWNER. Re-hardening may replace its DACL only after proving the
3123 // existing owner is still the current user.
3124 VerifyCurrentUser,
3125 }
3126
3127 #[cfg(windows)]
3128 enum WindowsAclTargetOpenError {
3129 Io(std::io::Error),
3130 Validation(String),
3131 }
3132
3133 #[cfg(windows)]
3134 impl WindowsAclTargetOpenError {
3135 fn should_retry_without_write_owner(&self) -> bool {
3136 matches!(self, Self::Io(error) if is_windows_access_denied(error))
3137 }
3138
3139 fn into_message(self) -> String {
3140 match self {
3141 Self::Io(error) => format!("failed to open Windows plugin ACL target safely: {error}"),
3142 Self::Validation(message) => message,
3143 }
3144 }
3145 }
3146
3147 #[cfg(windows)]
3148 fn is_windows_access_denied(error: &std::io::Error) -> bool {
3149 // Only retry the expected access denial from a missing WRITE_OWNER grant.
3150 // A sharing violation, missing path, reparse validation failure, or any
3151 // other open failure must remain fail-closed without opening a new handle.
3152 error.raw_os_error() == Some(5) // ERROR_ACCESS_DENIED
3153 }
3154
3155 #[cfg(windows)]
3156 fn open_windows_acl_target(
3157 path: &Path,
3158 access_mode: u32,
3159 ) -> Result<fs::File, WindowsAclTargetOpenError> {
3160 use std::os::windows::fs::OpenOptionsExt as _;
3161
3162 let target = OpenOptions::new()
3163 .access_mode(access_mode)
3164 .share_mode(0x0000_0001) // FILE_SHARE_READ
3165 .custom_flags(0x0220_0000) // BACKUP_SEMANTICS | OPEN_REPARSE_POINT
3166 .open(path)
3167 .map_err(WindowsAclTargetOpenError::Io)?;
3168 let opened = target.metadata().map_err(|error| {
3169 WindowsAclTargetOpenError::Validation(format!(
3170 "failed to inspect opened Windows plugin ACL target: {error}"
3171 ))
3172 })?;
3173 let opened_identity = windows_file_identity(&target).map_err(|error| {
3174 WindowsAclTargetOpenError::Validation(format!(
3175 "failed to identify opened Windows plugin ACL target: {error}"
3176 ))
3177 })?;
3178 if opened_identity.attributes & 0x0000_0400 != 0 || !(opened.is_file() || opened.is_dir()) {
3179 return Err(WindowsAclTargetOpenError::Validation(
3180 "Windows plugin ACL target changed into a reparse point or unsupported object"
3181 .to_string(),
3182 ));
3183 }
3184 ensure_windows_registry_path_still_opened(path, &target)
3185 .map_err(WindowsAclTargetOpenError::Validation)?;
3186 Ok(target)
3187 }
3188
3189 #[cfg(windows)]
3190 fn set_windows_owner_only_acl_with_mask(path: &Path, access_mask: u32) -> Result<(), String> {
3191 set_windows_owner_only_acl_with_mask_and_inheritance(path, access_mask, true)
3192 }
3193
3194 #[cfg(windows)]
3195 fn set_windows_owner_only_acl_with_mask_and_inheritance(
3196 path: &Path,
3197 access_mask: u32,
3198 inherit_to_children: bool,
3199 ) -> Result<(), String> {
3200 const ACL_ACCESS_WITH_OWNER: u32 = 0x0002_0000 | 0x0004_0000 | 0x0008_0000;
3201 const ACL_ACCESS_WITHOUT_OWNER: u32 = 0x0002_0000 | 0x0004_0000;
3202
3203 // Bind ACL mutation to the exact object opened without following a
3204 // reparse point. A pathname-only SetNamedSecurityInfoW call could inspect
3205 // a safe entry and then follow a junction substituted before the update.
3206 let before = fs::symlink_metadata(path)
3207 .map_err(|error| format!("failed to inspect Windows plugin ACL target: {error}"))?;
3208 if metadata_is_link_or_reparse(&before) || !(before.is_file() || before.is_dir()) {
3209 return Err(
3210 "Windows plugin ACL target must be a regular non-reparse file or directory".to_string(),
3211 );
3212 }
3213 let (target, owner_mode) = match open_windows_acl_target(path, ACL_ACCESS_WITH_OWNER) {
3214 Ok(target) => (target, WindowsAclOwnerMode::NormalizeCurrentUser),
3215 Err(error) if error.should_retry_without_write_owner() => {
3216 let target = open_windows_acl_target(path, ACL_ACCESS_WITHOUT_OWNER)
3217 .map_err(WindowsAclTargetOpenError::into_message)?;
3218 (target, WindowsAclOwnerMode::VerifyCurrentUser)
3219 }
3220 Err(error) => return Err(error.into_message()),
3221 };
3222
3223 apply_windows_owner_only_acl_with_inheritance(
3224 &target,
3225 access_mask,
3226 owner_mode,
3227 inherit_to_children,
3228 )
3229 }
3230
3231 #[cfg(windows)]
3232 fn apply_windows_owner_only_acl(
3233 target: &fs::File,
3234 access_mask: u32,
3235 owner_mode: WindowsAclOwnerMode,
3236 ) -> Result<(), String> {
3237 apply_windows_owner_only_acl_with_inheritance(target, access_mask, owner_mode, true)
3238 }
3239
3240 #[cfg(windows)]
3241 fn apply_windows_owner_only_acl_with_inheritance(
3242 target: &fs::File,
3243 access_mask: u32,
3244 owner_mode: WindowsAclOwnerMode,
3245 inherit_to_children: bool,
3246 ) -> Result<(), String> {
3247 use std::mem::{MaybeUninit, size_of};
3248 use std::os::windows::io::AsRawHandle as _;
3249 use windows::Win32::Foundation::{CloseHandle, HANDLE, WIN32_ERROR};
3250 use windows::Win32::Security::Authorization::{SE_FILE_OBJECT, SetSecurityInfo};
3251 use windows::Win32::Security::{
3252 ACCESS_ALLOWED_ACE, ACL, ACL_REVISION, CONTAINER_INHERIT_ACE, DACL_SECURITY_INFORMATION,
3253 GetLengthSid, GetTokenInformation, InitializeAcl, NO_INHERITANCE, OBJECT_INHERIT_ACE,
3254 OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, TOKEN_QUERY, TOKEN_USER,
3255 TokenUser,
3256 };
3257 use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
3258
3259 let mut token = HANDLE::default();
3260 // SAFETY: output handle points to valid storage and the pseudo process
3261 // handle is valid for the current process.
3262 unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }
3263 .map_err(|error| format!("failed to open the current Windows security token: {error}"))?;
3264 let result = (|| {
3265 let mut required = 0_u32;
3266 // The first call intentionally obtains the required byte count.
3267 // SAFETY: null buffer queries size; `required` is live.
3268 let _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, &mut required) };
3269 if required < size_of::<TOKEN_USER>() as u32 {
3270 return Err("Windows token did not expose a current-user SID".to_string());
3271 }
3272 let words = (required as usize).div_ceil(size_of::<usize>());
3273 let mut token_buffer = vec![MaybeUninit::<usize>::zeroed(); words];
3274 // SAFETY: aligned buffer is at least `required` bytes and remains alive
3275 // for every SID/ACL operation below.
3276 unsafe {
3277 GetTokenInformation(
3278 token,
3279 TokenUser,
3280 Some(token_buffer.as_mut_ptr().cast()),
3281 required,
3282 &mut required,
3283 )
3284 }
3285 .map_err(|error| format!("failed to read the current Windows user SID: {error}"))?;
3286 // SAFETY: successful TokenUser query initialized a TOKEN_USER at the
3287 // beginning of the aligned buffer.
3288 let token_user = unsafe { &*token_buffer.as_ptr().cast::<TOKEN_USER>() };
3289 let sid = token_user.User.Sid;
3290 // SAFETY: SID comes from the successful token query above.
3291 let sid_len = unsafe { GetLengthSid(sid) } as usize;
3292 if sid_len == 0 {
3293 return Err("Windows current-user SID is invalid".to_string());
3294 }
3295 let acl_bytes =
3296 size_of::<ACL>() + size_of::<ACCESS_ALLOWED_ACE>() - size_of::<u32>() + sid_len;
3297 let acl_words = acl_bytes.div_ceil(size_of::<usize>());
3298 let mut acl_buffer = vec![MaybeUninit::<usize>::zeroed(); acl_words];
3299 let acl = acl_buffer.as_mut_ptr().cast::<ACL>();
3300 // SAFETY: aligned ACL buffer is large enough for one full-access ACE
3301 // containing the current user SID.
3302 unsafe { InitializeAcl(acl, acl_bytes as u32, ACL_REVISION) }
3303 .map_err(|error| format!("failed to initialize a private Windows ACL: {error}"))?;
3304 let inheritance = if inherit_to_children {
3305 CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE
3306 } else {
3307 NO_INHERITANCE
3308 };
3309 unsafe {
3310 windows::Win32::Security::AddAccessAllowedAceEx(
3311 acl,
3312 ACL_REVISION,
3313 inheritance,
3314 access_mask,
3315 sid,
3316 )
3317 }
3318 .map_err(|error| format!("failed to grant the current Windows user access: {error}"))?;
3319
3320 let (security_information, owner) = match owner_mode {
3321 WindowsAclOwnerMode::NormalizeCurrentUser => (
3322 OWNER_SECURITY_INFORMATION
3323 | DACL_SECURITY_INFORMATION
3324 | PROTECTED_DACL_SECURITY_INFORMATION,
3325 Some(sid),
3326 ),
3327 WindowsAclOwnerMode::VerifyCurrentUser => {
3328 // The caller could not obtain WRITE_OWNER. Mutate only an
3329 // exact handle whose current owner is already the token user.
3330 ensure_windows_plugin_target_owner(target, sid)?;
3331 (
3332 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
3333 None,
3334 )
3335 }
3336 };
3337
3338 // SAFETY: `target` retains the exact validated non-reparse object and
3339 // the ACL/SID buffers remain alive through the call. The normalization
3340 // path writes owner and DACL together; the fallback path has already
3341 // verified the owner through this retained handle.
3342 let status = unsafe {
3343 SetSecurityInfo(
3344 HANDLE(target.as_raw_handle()),
3345 SE_FILE_OBJECT,
3346 security_information,
3347 owner,
3348 None,
3349 Some(acl),
3350 None,
3351 )
3352 };
3353 if status != WIN32_ERROR(0) {
3354 return Err(format!(
3355 "failed to restrict Windows plugin runtime ACL: error {}",
3356 status.0
3357 ));
3358 }
3359 if let WindowsAclOwnerMode::VerifyCurrentUser = owner_mode {
3360 // A handle that predated our restrictive share barrier may still
3361 // mutate the descriptor. Do not hand out authority if it changed
3362 // ownership around the DACL-only fallback.
3363 ensure_windows_plugin_target_owner(target, sid)?;
3364 }
3365 Ok(())
3366 })();
3367 // SAFETY: token is the unique real handle returned by OpenProcessToken.
3368 let _ = unsafe { CloseHandle(token) };
3369 result
3370 }
3371
3372 /// Require a current-user-owned target before changing its DACL. The caller
3373 /// has already opened the exact non-reparse object with a restrictive sharing
3374 /// barrier, so this does not reintroduce a path-following race.
3375 #[cfg(windows)]
3376 fn ensure_windows_plugin_target_owner(
3377 target: &fs::File,
3378 expected_owner: windows::Win32::Security::PSID,
3379 ) -> Result<(), String> {
3380 use std::os::windows::io::AsRawHandle as _;
3381 use windows::Win32::Foundation::{HANDLE, HLOCAL, LocalFree, WIN32_ERROR};
3382 use windows::Win32::Security::Authorization::{GetSecurityInfo, SE_FILE_OBJECT};
3383 use windows::Win32::Security::{
3384 EqualSid, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID,
3385 };
3386
3387 let mut owner = PSID::default();
3388 let mut descriptor = PSECURITY_DESCRIPTOR(std::ptr::null_mut());
3389 // SAFETY: `target` remains open for the complete call, all requested
3390 // output locations are valid, and Windows allocates `descriptor` for the
3391 // caller to free with LocalFree below.
3392 let status = unsafe {
3393 GetSecurityInfo(
3394 HANDLE(target.as_raw_handle()),
3395 SE_FILE_OBJECT,
3396 OWNER_SECURITY_INFORMATION,
3397 Some(&mut owner),
3398 None,
3399 None,
3400 None,
3401 Some(&mut descriptor),
3402 )
3403 };
3404 if status != WIN32_ERROR(0) {
3405 if !descriptor.0.is_null() {
3406 // SAFETY: a non-null descriptor came from GetSecurityInfo and is
3407 // documented to be released by LocalFree exactly once.
3408 let _ = unsafe { LocalFree(Some(HLOCAL(descriptor.0))) };
3409 }
3410 return Err(format!(
3411 "failed to inspect Windows plugin ACL target owner: error {}",
3412 status.0
3413 ));
3414 }
3415 // SAFETY: `owner` is non-null from GetSecurityInfo; `expected_owner` is the caller's SID.
3416 let owner_matches = !owner.0.is_null() && unsafe { EqualSid(owner, expected_owner) }.is_ok();
3417 if !descriptor.0.is_null() {
3418 // SAFETY: the successful GetSecurityInfo allocation is released only
3419 // after the owner SID comparison above completes.
3420 let _ = unsafe { LocalFree(Some(HLOCAL(descriptor.0))) };
3421 }
3422 if !owner_matches {
3423 return Err(
3424 "Windows plugin ACL target owner is not the current user; refusing to harden a foreign-owned object"
3425 .to_string(),
3426 );
3427 }
3428 Ok(())
3429 }
3430
3431 #[cfg(all(not(unix), not(windows)))]
3432 fn set_owner_only_directory(_path: &Path) -> Result<(), String> {
3433 Err("Plugin runtime staging is unavailable on this platform because owner-only filesystem permissions cannot be enforced".to_string())
3434 }
3435
3436 #[cfg(unix)]
3437 fn preserve_owner_only_file_mode(path: &Path, source: &fs::Metadata) -> Result<(), String> {
3438 use std::os::unix::fs::PermissionsExt;
3439 let executable = source.permissions().mode() & 0o111 != 0;
3440 let mode = if executable { 0o500 } else { 0o400 };
3441 fs::set_permissions(path, fs::Permissions::from_mode(mode))
3442 .map_err(|e| format!("failed to restrict staged plugin file permissions: {e}"))
3443 }
3444
3445 #[cfg(windows)]
3446 fn preserve_owner_only_file_mode(path: &Path, _source: &fs::Metadata) -> Result<(), String> {
3447 // The protected handle-relative DACL is the Windows non-writable
3448 // authority. Avoid `set_permissions(path)`, which can follow a reparse
3449 // point substituted after metadata inspection.
3450 set_windows_owner_only_acl_with_mask_and_inheritance(path, 0xa000_0000, false)
3451 }
3452
3453 #[cfg(all(not(unix), not(windows)))]
3454 fn preserve_owner_only_file_mode(path: &Path, _source: &fs::Metadata) -> Result<(), String> {
3455 let mut permissions = fs::metadata(path)
3456 .map_err(|e| format!("failed to inspect staged plugin file permissions: {e}"))?
3457 .permissions();
3458 permissions.set_readonly(true);
3459 fs::set_permissions(path, permissions)
3460 .map_err(|e| format!("failed to restrict staged plugin file permissions: {e}"))
3461 }
3462
3463 /// Recheck a persisted plugin receipt, the mutable reviewed source, and the
3464 /// Codewhale-owned immutable runtime copy, then require the named adapter to
3465 /// be in this build's activation policy. Every adapter must call this with its
3466 /// specific capability rather than treating bundle-wide activity as authority
3467 /// to run every inventoried surface.
3468 pub fn verify_plugin_component_authority(
3469 authority: &PluginAuthority,
3470 capability: PluginActivationCapability,
3471 ) -> Result<(), String> {
3472 verify_plugin_authority(authority)?;
3473 if !PluginActivationPolicy::current().is_supported(capability) {
3474 return Err(format!(
3475 "Plugin bundle `{}` capability `{}` is inactive in this Codewhale build",
3476 authority.plugin_name,
3477 capability.as_str()
3478 ));
3479 }
3480 Ok(())
3481 }
3482
3483 /// Recheck a persisted plugin receipt, the mutable reviewed source, and the
3484 /// Codewhale-owned immutable runtime copy. This function performs no writes.
3485 ///
3486 /// Known limitation, deliberate: this is **not** memoized on `(path, mtime,
3487 /// len)`, even though re-walking both trees is the dominant cost of an MCP
3488 /// dispatch (#6209). The reviewed source tree is user-writable, and
3489 /// `utimensat(2)` lets any same-uid process restore an mtime after an
3490 /// equal-length in-place rewrite. A stat-keyed cache would then hand back the
3491 /// pre-tamper digest, `content_hash` would still match, and a modified bundle
3492 /// would dispatch as reviewed — turning the one check that stands between a
3493 /// reviewed bundle and an altered one into a check of whether someone
3494 /// remembered to reset a timestamp. The cost is paid per dispatch on purpose.
3495 /// Reduce the *number* of calls instead; see `McpConnection::is_transport_ready`.
3496 pub fn verify_plugin_authority(authority: &PluginAuthority) -> Result<(), String> {
3497 verify_plugin_state_authority(authority)?;
3498 let staged_root = super::agent_plugin::plugin_root_for_manifest(&authority.staged_manifest)
3499 .ok_or_else(|| "Plugin authority has no staged runtime root".to_string())?;
3500 let finalized = verify_finalized_stage_root(staged_root, None)?;
3501 for (label, manifest_path) in [
3502 ("reviewed source", &authority.source_manifest),
3503 ("Codewhale runtime snapshot", &authority.staged_manifest),
3504 ] {
3505 let current =
3506 super::manifest::PluginManifest::validate_from_path(manifest_path).map_err(|_| {
3507 format!(
3508 "Plugin bundle `{}` {label} could not be revalidated",
3509 authority.plugin_name
3510 )
3511 })?;
3512 if current.content_hash != authority.content_hash
3513 || current.capability_hash != authority.capability_hash
3514 {
3515 return Err(format!(
3516 "Plugin bundle `{}` {label} changed after review",
3517 authority.plugin_name
3518 ));
3519 }
3520 }
3521 verify_finalized_stage_root(staged_root, Some(&finalized)).map(drop)
3522 }
3523
3524 /// Cheap cross-process revocation probe used while an established MCP request
3525 /// is in flight. Full source/stage hashing is intentionally done before each
3526 /// dispatch; the watcher rechecks the trusted policy source and locked state.
3527 pub fn verify_plugin_state_authority(authority: &PluginAuthority) -> Result<(), String> {
3528 capture_plugin_state_authority(authority, None).map(drop)
3529 }
3530
3531 pub fn capture_plugin_state_authority(
3532 authority: &PluginAuthority,
3533 expected: Option<&fs::File>,
3534 ) -> Result<fs::File, String> {
3535 read_active_receipt(authority, expected).map(|(state_file, _)| state_file)
3536 }
3537
3538 pub fn granted_host_services(authority: &PluginAuthority) -> Result<Vec<HostService>, String> {
3539 reviewed_record(authority).map(|record| record.host_services)
3540 }
3541
3542 #[derive(Debug, Clone, PartialEq, Eq)]
3543 pub struct ReviewedRecord {
3544 pub approved_by: Option<PluginApprover>,
3545 pub host_services: Vec<HostService>,
3546 }
3547
3548 pub fn reviewed_record(authority: &PluginAuthority) -> Result<ReviewedRecord, String> {
3549 read_active_receipt(authority, None).map(|(_, receipt)| ReviewedRecord {
3550 host_services: receipt.granted(),
3551 approved_by: receipt.approved_by,
3552 })
3553 }
3554
3555 fn read_active_receipt(
3556 authority: &PluginAuthority,
3557 expected: Option<&fs::File>,
3558 ) -> Result<(fs::File, TrustReceipt), String> {
3559 let policy_path = authority
3560 .managed_policy_source
3561 .as_deref()
3562 .filter(|path| path.is_absolute())
3563 .ok_or_else(|| {
3564 "Plugin authority has no managed policy source; reload the plugin before executing it"
3565 .to_string()
3566 })?;
3567 if authority.managed_policy_path.as_deref() != Some(policy_path) {
3568 return Err("Plugin authority does not match its trusted managed policy source; reload the plugin before executing it".to_string());
3569 }
3570 match load_managed_policy(policy_path) {
3571 ManagedPolicyOutcome::Absent => {}
3572 ManagedPolicyOutcome::Loaded(policy) if policy.allows(&authority.plugin_id) => {}
3573 ManagedPolicyOutcome::Loaded(_) => {
3574 return Err(format!(
3575 "Plugin bundle `{}` is blocked by managed plugin policy",
3576 authority.plugin_name
3577 ));
3578 }
3579 ManagedPolicyOutcome::Invalid(_) => {
3580 return Err(
3581 "Managed plugin policy is invalid; the bundle is disabled fail-closed".to_string(),
3582 );
3583 }
3584 }
3585 let state_parent = authority
3586 .state_path
3587 .parent()
3588 .filter(|parent| !parent.as_os_str().is_empty())
3589 .ok_or_else(|| "Plugin authority state has no private parent directory".to_string())?;
3590 validate_plugin_state_directory_for_read(state_parent).map_err(|_| {
3591 "Plugin authority state directory is not private; the bundle is disabled fail-closed"
3592 .to_string()
3593 })?;
3594 let lock_path = state_lock_path(&authority.state_path);
3595 let lock_file = open_state_lock(&lock_path, false).map_err(|_| {
3596 "Plugin authority state lock is missing; review and enable the bundle again".to_string()
3597 })?;
3598 let lock = fd_lock::RwLock::new(lock_file);
3599 let _guard = lock
3600 .read()
3601 .map_err(|_| "Plugin authority state could not be read safely".to_string())?;
3602 let state_file = open_existing_regular_file(&authority.state_path, false)
3603 .map_err(|_| "Plugin authority state could not be opened safely".to_string())?
3604 .ok_or_else(|| "Plugin authority state is missing".to_string())?;
3605 if let Some(expected) = expected
3606 && !codewhale_util::files::same_file(expected, &state_file)
3607 .map_err(|_| "Plugin authority state identity could not be checked".to_string())?
3608 {
3609 return Err("Plugin authority state changed after UI authorization".to_string());
3610 }
3611 let state = load_state_from_file(
3612 &authority.state_path,
3613 state_file
3614 .try_clone()
3615 .map_err(|_| "Plugin authority state could not be read safely".to_string())?,
3616 )
3617 .map_err(|_| {
3618 "Plugin authority state is invalid; the bundle is disabled fail-closed".to_string()
3619 })?;
3620 let receipt = state
3621 .plugins
3622 .get(&authority.plugin_id)
3623 .filter(|entry| entry.generation == authority.state_generation && entry.enabled)
3624 .and_then(|entry| entry.trust.as_ref())
3625 .filter(|receipt| {
3626 receipt.content_hash == authority.content_hash
3627 && receipt.capability_hash == authority.capability_hash
3628 })
3629 .cloned()
3630 .ok_or_else(|| {
3631 format!(
3632 "Plugin bundle `{}` is disabled, revoked, or no longer matches its review receipt",
3633 authority.plugin_name
3634 )
3635 })?;
3636 Ok((state_file, receipt))
3637 }
3638
3639 #[cfg(test)]
3640 mod state_publication_tests {
3641 use super::{
3642 PluginStateFile, harden_plugin_state_file, open_existing_regular_file,
3643 save_state_with_hardener,
3644 };
3645
3646 fn prepare_private_directory(_path: &std::path::Path) {
3647 #[cfg(unix)]
3648 {
3649 use std::os::unix::fs::PermissionsExt as _;
3650 std::fs::set_permissions(_path, std::fs::Permissions::from_mode(0o700)).unwrap();
3651 }
3652 }
3653
3654 #[test]
3655 fn successful_state_publication_replaces_the_stable_file_without_temp_debris() {
3656 let directory = tempfile::tempdir().unwrap();
3657 prepare_private_directory(directory.path());
3658 let state_path = directory.path().join("state-鲸.json");
3659 std::fs::write(&state_path, b"old-authoritative-state").unwrap();
3660
3661 save_state_with_hardener(
3662 &state_path,
3663 &PluginStateFile::default(),
3664 harden_plugin_state_file,
3665 )
3666 .unwrap();
3667
3668 let published = std::fs::read_to_string(&state_path).unwrap();
3669 assert!(published.contains("\"schema_version\": 1"));
3670 let entries = std::fs::read_dir(directory.path())
3671 .unwrap()
3672 .map(|entry| entry.unwrap().file_name())
3673 .collect::<Vec<_>>();
3674 assert_eq!(entries, [std::ffi::OsString::from("state-鲸.json")]);
3675 }
3676
3677 #[test]
3678 fn state_publication_replaces_a_stable_file_that_a_reader_still_holds_open() {
3679 use std::io::Read as _;
3680
3681 let directory = tempfile::tempdir().unwrap();
3682 prepare_private_directory(directory.path());
3683 let state_path = directory.path().join("state.json");
3684 std::fs::write(&state_path, b"old-authoritative-state").unwrap();
3685 let mut held = open_existing_regular_file(&state_path, false)
3686 .unwrap()
3687 .unwrap();
3688
3689 save_state_with_hardener(
3690 &state_path,
3691 &PluginStateFile::default(),
3692 harden_plugin_state_file,
3693 )
3694 .unwrap();
3695
3696 let mut published = open_existing_regular_file(&state_path, false)
3697 .unwrap()
3698 .unwrap();
3699 assert!(!codewhale_util::files::same_file(&held, &published).unwrap());
3700 let mut superseded = String::new();
3701 held.read_to_string(&mut superseded).unwrap();
3702 assert_eq!(superseded, "old-authoritative-state");
3703 let mut current = String::new();
3704 published.read_to_string(&mut current).unwrap();
3705 assert!(current.contains("\"schema_version\": 1"));
3706 let entries = std::fs::read_dir(directory.path())
3707 .unwrap()
3708 .map(|entry| entry.unwrap().file_name())
3709 .collect::<Vec<_>>();
3710 assert_eq!(entries, [std::ffi::OsString::from("state.json")]);
3711 }
3712
3713 #[test]
3714 fn failed_temp_hardening_never_publishes_new_plugin_state() {
3715 let directory = tempfile::tempdir().unwrap();
3716 prepare_private_directory(directory.path());
3717 let state_path = directory.path().join("state.json");
3718 std::fs::write(&state_path, b"old-authoritative-state").unwrap();
3719
3720 let error =
3721 save_state_with_hardener(&state_path, &PluginStateFile::default(), |temporary_path| {
3722 assert!(temporary_path.is_file());
3723 assert!(
3724 std::fs::read_to_string(temporary_path)
3725 .unwrap()
3726 .contains("\"schema_version\": 1")
3727 );
3728 assert_eq!(
3729 std::fs::read(&state_path).unwrap(),
3730 b"old-authoritative-state",
3731 "the stable path must still hold the old state while hardening runs"
3732 );
3733 Err("injected pre-publication ACL failure".to_string())
3734 })
3735 .unwrap_err();
3736
3737 assert!(error.contains("injected pre-publication ACL failure"));
3738 assert_eq!(
3739 std::fs::read(&state_path).unwrap(),
3740 b"old-authoritative-state"
3741 );
3742 let entries = std::fs::read_dir(directory.path())
3743 .unwrap()
3744 .map(|entry| entry.unwrap().file_name())
3745 .collect::<Vec<_>>();
3746 assert_eq!(entries, [std::ffi::OsString::from("state.json")]);
3747 }
3748
3749 #[cfg(unix)]
3750 #[test]
3751 fn directory_sync_failure_reports_that_the_new_state_was_published() {
3752 use super::persist_plugin_state_with_directory_sync;
3753 use std::io::Write as _;
3754
3755 let directory = tempfile::tempdir().unwrap();
3756 prepare_private_directory(directory.path());
3757 let state_path = directory.path().join("state.json");
3758 std::fs::write(&state_path, b"old-authoritative-state").unwrap();
3759 let mut temporary = tempfile::NamedTempFile::new_in(directory.path()).unwrap();
3760 temporary.write_all(b"new-authoritative-state").unwrap();
3761 temporary.flush().unwrap();
3762 temporary.as_file().sync_all().unwrap();
3763
3764 let error = persist_plugin_state_with_directory_sync(temporary, &state_path, |_| {
3765 Err(std::io::Error::other(
3766 "injected post-publication directory sync failure",
3767 ))
3768 })
3769 .unwrap_err();
3770
3771 assert!(error.contains("published but its directory durability could not be confirmed"));
3772 assert_eq!(
3773 std::fs::read(&state_path).unwrap(),
3774 b"new-authoritative-state"
3775 );
3776 let entries = std::fs::read_dir(directory.path())
3777 .unwrap()
3778 .map(|entry| entry.unwrap().file_name())
3779 .collect::<Vec<_>>();
3780 assert_eq!(entries, [std::ffi::OsString::from("state.json")]);
3781 }
3782 }
3783
3784 #[cfg(all(test, unix))]
3785 mod unix_state_directory_tests {
3786 use super::validate_unix_plugin_state_directory_fields;
3787
3788 #[test]
3789 fn state_directory_validation_rejects_an_owner_mismatch() {
3790 let error =
3791 validate_unix_plugin_state_directory_fields(true, 41, 0o700, 42, false).unwrap_err();
3792 assert!(error.contains("current-user-owned"));
3793 }
3794
3795 /// A mount that reports its own owner and mode cannot prove either, so the
3796 /// fields are not evidence there. The refusal above must still apply on a
3797 /// filesystem that stores them — this pins that the tolerance is a property
3798 /// of the mount, not a weakening of the check.
3799 #[test]
3800 fn state_directory_validation_accepts_a_mount_that_cannot_express_ownership() {
3801 validate_unix_plugin_state_directory_fields(true, 41, 0o2771, 42, true)
3802 .expect("a synthesising mount is not an owner mismatch");
3803 assert!(
3804 validate_unix_plugin_state_directory_fields(true, 41, 0o2771, 42, false).is_err(),
3805 "the same values are a refusal where the mount stores them"
3806 );
3807 assert!(
3808 validate_unix_plugin_state_directory_fields(false, 42, 0o700, 42, true).is_err(),
3809 "a non-directory is refused whatever the mount does"
3810 );
3811 }
3812 }
3813
3814 #[cfg(all(test, windows))]
3815 mod windows_acl_tests {
3816 use super::{
3817 PluginStateFile, WindowsAclOwnerMode, apply_windows_owner_only_acl,
3818 ensure_private_runtime_parent, ensure_windows_plugin_target_owner,
3819 harden_plugin_state_file, harden_staged_tree_contents, open_state_lock,
3820 save_state_with_hardener, set_windows_owner_only_acl, state_lock_path,
3821 };
3822 use std::ffi::c_void;
3823 use std::mem::{MaybeUninit, size_of};
3824 use std::os::windows::ffi::OsStrExt;
3825 use windows::Win32::Foundation::{CloseHandle, HANDLE};
3826 use windows::Win32::Security::{
3827 ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION, AclSizeInformation, AdjustTokenPrivileges,
3828 CONTAINER_INHERIT_ACE, DACL_SECURITY_INFORMATION, DuplicateTokenEx, EqualSid, GetAce,
3829 GetAclInformation, GetFileSecurityW, GetSecurityDescriptorControl,
3830 GetSecurityDescriptorDacl, GetSecurityDescriptorOwner, OBJECT_INHERIT_ACE,
3831 OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, RevertToSelf, SE_DACL_PROTECTED,
3832 SecurityImpersonation, TOKEN_ADJUST_PRIVILEGES, TOKEN_DUPLICATE, TOKEN_IMPERSONATE,
3833 TOKEN_QUERY, TokenImpersonation,
3834 };
3835 use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken, SetThreadToken};
3836 use windows::core::{BOOL, PCWSTR};
3837
3838 /// Pin the fixture to a thread token with privileges disabled. Hosted
3839 /// runners can hold backup/restore/take-ownership privileges that bypass
3840 /// the DACL, making a WRITE_OWNER denial depend on the host identity.
3841 /// The process token is unchanged, and dropping the guard reverts the thread.
3842 struct UnprivilegedThreadToken {
3843 process_token: HANDLE,
3844 restricted: HANDLE,
3845 }
3846
3847 impl UnprivilegedThreadToken {
3848 fn adopt() -> windows::core::Result<Self> {
3849 let mut process_token = HANDLE::default();
3850 // SAFETY: the pseudo process handle is valid for the current
3851 // process and the output location is live across the call.
3852 unsafe {
3853 OpenProcessToken(
3854 GetCurrentProcess(),
3855 TOKEN_DUPLICATE | TOKEN_QUERY,
3856 &mut process_token,
3857 )
3858 }?;
3859 let mut restricted = HANDLE::default();
3860 // SAFETY: `process_token` stays open for the call and `restricted`
3861 // receives a new handle ownership of which passes to the guard.
3862 let duplicated = unsafe {
3863 DuplicateTokenEx(
3864 process_token,
3865 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_IMPERSONATE,
3866 None,
3867 SecurityImpersonation,
3868 TokenImpersonation,
3869 &mut restricted,
3870 )
3871 };
3872 if let Err(error) = duplicated {
3873 // SAFETY: closing the only handle opened above.
3874 unsafe {
3875 let _ = CloseHandle(process_token);
3876 }
3877 return Err(error);
3878 }
3879 // Own both handles before the fallible calls below, so a failure
3880 // still reverts and closes through `Drop`.
3881 let guard = Self {
3882 process_token,
3883 restricted,
3884 };
3885 // DisableAllPrivileges leaves the duplicate holding none, so the
3886 // DACL becomes the only thing that can grant WRITE_OWNER.
3887 // SAFETY: `restricted` is owned by `guard` for the whole call.
3888 unsafe { AdjustTokenPrivileges(guard.restricted, true, None, 0, None, None) }?;
3889 // SAFETY: impersonation is scoped to this thread and undone in Drop.
3890 unsafe { SetThreadToken(None, Some(guard.restricted)) }?;
3891 Ok(guard)
3892 }
3893 }
3894
3895 impl Drop for UnprivilegedThreadToken {
3896 fn drop(&mut self) {
3897 // SAFETY: reverts this thread's identity and closes the two handles
3898 // this guard opened, each exactly once.
3899 unsafe {
3900 let _ = RevertToSelf();
3901 let _ = CloseHandle(self.restricted);
3902 let _ = CloseHandle(self.process_token);
3903 }
3904 }
3905 }
3906
3907 fn create_junction(link: &std::path::Path, target: &std::path::Path) {
3908 let output = std::process::Command::new("cmd")
3909 .args(["/C", "mklink", "/J"])
3910 .arg(link)
3911 .arg(target)
3912 .output()
3913 .expect("invoke Windows junction creation");
3914 assert!(
3915 output.status.success(),
3916 "failed to create junction: stdout={} stderr={}",
3917 String::from_utf8_lossy(&output.stdout),
3918 String::from_utf8_lossy(&output.stderr)
3919 );
3920 }
3921
3922 #[test]
3923 fn acl_hardening_rejects_junction_targets() {
3924 let directory = tempfile::tempdir().unwrap();
3925 let target = directory.path().join("target");
3926 let junction = directory.path().join("junction");
3927 std::fs::create_dir(&target).unwrap();
3928 create_junction(&junction, &target);
3929
3930 let error = set_windows_owner_only_acl(&junction).unwrap_err();
3931 assert!(error.contains("non-reparse"), "unexpected error: {error}");
3932 }
3933
3934 #[test]
3935 fn runtime_parent_creation_rejects_junction_components() {
3936 let directory = tempfile::tempdir().unwrap();
3937 let state_root = directory.path().join("state");
3938 let outside = directory.path().join("outside");
3939 std::fs::create_dir(&state_root).unwrap();
3940 std::fs::create_dir(&outside).unwrap();
3941 create_junction(&state_root.join(".runtime"), &outside);
3942 let state_path = state_root.join("state.json");
3943 let expected_parent = state_root.join(".runtime/v2/plugin");
3944
3945 let error = ensure_private_runtime_parent(&state_path, &expected_parent).unwrap_err();
3946 assert!(
3947 error.contains("reparse points"),
3948 "unexpected error: {error}"
3949 );
3950 }
3951
3952 #[test]
3953 fn staged_tree_hardening_rejects_junction_entries() {
3954 let directory = tempfile::tempdir().unwrap();
3955 let stage = directory.path().join("stage");
3956 let outside = directory.path().join("outside");
3957 std::fs::create_dir(&stage).unwrap();
3958 std::fs::create_dir(&outside).unwrap();
3959 create_junction(&stage.join("linked"), &outside);
3960
3961 let error = harden_staged_tree_contents(&stage).unwrap_err();
3962 assert!(error.contains("reparse point"), "unexpected error: {error}");
3963 }
3964
3965 #[test]
3966 fn state_lock_hardening_keeps_its_writer_handle() {
3967 let directory = tempfile::tempdir().unwrap();
3968 let state_directory = directory.path().join("state");
3969 std::fs::create_dir(&state_directory).unwrap();
3970 set_windows_owner_only_acl(&state_directory).unwrap();
3971 let lock_path = state_lock_path(&state_directory.join("state.json"));
3972
3973 let lock = open_state_lock(&lock_path, true)
3974 .expect("state lock ACL hardening must not conflict with its writer handle");
3975 assert!(lock.metadata().unwrap().is_file());
3976 }
3977
3978 #[test]
3979 fn owner_only_acl_rehardens_without_write_owner_access() {
3980 use std::os::windows::fs::OpenOptionsExt as _;
3981
3982 let directory = tempfile::tempdir().unwrap();
3983 let target = directory.path().join("state");
3984 std::fs::create_dir(&target).unwrap();
3985 set_windows_owner_only_acl(&target).unwrap();
3986
3987 // Simulate an already-private Codewhale object whose owner is still
3988 // the current user, but whose DACL intentionally does not grant
3989 // WRITE_OWNER. Rehardening must restore the full owner-only ACL
3990 // rather than assuming it may take ownership again.
3991 let reduced = std::fs::OpenOptions::new()
3992 .access_mode(0x001f_01ff) // FILE_ALL_ACCESS for this setup only
3993 .share_mode(0x0000_0001)
3994 .custom_flags(0x0220_0000) // BACKUP_SEMANTICS | OPEN_REPARSE_POINT
3995 .open(&target)
3996 .unwrap();
3997 apply_windows_owner_only_acl(
3998 &reduced,
3999 0x0017_01ff,
4000 WindowsAclOwnerMode::VerifyCurrentUser,
4001 )
4002 .expect("current owner may restrict its DACL without changing ownership");
4003 drop(reduced);
4004
4005 // From here the DACL must be the only authority. Held to the end of the
4006 // test so the fallback and the restored ACL are both observed through
4007 // an identity that cannot bypass the descriptor.
4008 let _unprivileged = UnprivilegedThreadToken::adopt()
4009 .expect("restricted thread identity for the WRITE_OWNER denial");
4010
4011 let denied = std::fs::OpenOptions::new()
4012 .access_mode(0x0002_0000 | 0x0004_0000 | 0x0008_0000)
4013 .share_mode(0x0000_0001)
4014 .custom_flags(0x0220_0000) // BACKUP_SEMANTICS | OPEN_REPARSE_POINT
4015 .open(&target)
4016 .unwrap_err();
4017 assert_eq!(
4018 denied.raw_os_error(),
4019 Some(5),
4020 "the full-owner path must be unavailable before exercising the fallback"
4021 );
4022
4023 set_windows_owner_only_acl(&target)
4024 .expect("rehardening must verify the current owner without requesting WRITE_OWNER");
4025 let restored = std::fs::OpenOptions::new()
4026 .access_mode(0x001f_01ff)
4027 .share_mode(0x0000_0001)
4028 .custom_flags(0x0220_0000)
4029 .open(&target);
4030 assert!(
4031 restored.is_ok(),
4032 "rehardening must restore the current user's full owner-only ACL"
4033 );
4034 }
4035
4036 #[test]
4037 fn state_lock_rehardens_without_write_owner_access() {
4038 use std::os::windows::fs::OpenOptionsExt as _;
4039
4040 let directory = tempfile::tempdir().unwrap();
4041 let state_directory = directory.path().join("state");
4042 std::fs::create_dir(&state_directory).unwrap();
4043 set_windows_owner_only_acl(&state_directory).unwrap();
4044 let lock_path = state_lock_path(&state_directory.join("state.json"));
4045 drop(open_state_lock(&lock_path, true).unwrap());
4046
4047 let reduced = std::fs::OpenOptions::new()
4048 .access_mode(0x001f_01ff) // FILE_ALL_ACCESS for this setup only
4049 .share_mode(0x0000_0001)
4050 .custom_flags(0x0220_0000) // BACKUP_SEMANTICS | OPEN_REPARSE_POINT
4051 .open(&lock_path)
4052 .unwrap();
4053 apply_windows_owner_only_acl(
4054 &reduced,
4055 0x0016_019f, // FILE_GENERIC_READ | FILE_GENERIC_WRITE | WRITE_DAC
4056 WindowsAclOwnerMode::VerifyCurrentUser,
4057 )
4058 .expect("current owner may remove WRITE_OWNER from an existing state lock");
4059 drop(reduced);
4060
4061 // This sibling passed on the hosted runner only because its denial open
4062 // omits FILE_FLAG_BACKUP_SEMANTICS, which is what engages the
4063 // descriptor-bypassing privileges. That is an accident of the flags, not
4064 // a guarantee, so pin the identity here too.
4065 let _unprivileged = UnprivilegedThreadToken::adopt()
4066 .expect("restricted thread identity for the WRITE_OWNER denial");
4067
4068 let denied = std::fs::OpenOptions::new()
4069 .access_mode(0x001e_019f) // FILE_GENERIC_READ | FILE_GENERIC_WRITE | WRITE_DAC | WRITE_OWNER
4070 .share_mode(0x0000_0001)
4071 .custom_flags(0x0020_0000) // FILE_FLAG_OPEN_REPARSE_POINT
4072 .open(&lock_path)
4073 .unwrap_err();
4074 assert_eq!(
4075 denied.raw_os_error(),
4076 Some(5),
4077 "the state-lock fallback must run only after WRITE_OWNER is denied"
4078 );
4079
4080 let lock = open_state_lock(&lock_path, true)
4081 .expect("state-lock hardening must fall back to DACL-only rehardening");
4082 assert!(lock.metadata().unwrap().is_file());
4083 }
4084
4085 #[test]
4086 fn owner_only_acl_rejects_an_owner_identity_mismatch() {
4087 use std::os::windows::fs::OpenOptionsExt as _;
4088 use windows::Win32::Security::{CreateWellKnownSid, WinWorldSid};
4089
4090 let directory = tempfile::tempdir().unwrap();
4091 let path = directory.path().join("state");
4092 std::fs::create_dir(&path).unwrap();
4093 set_windows_owner_only_acl(&path).unwrap();
4094 let target = std::fs::OpenOptions::new()
4095 .access_mode(0x0002_0000) // READ_CONTROL
4096 .share_mode(0x0000_0001)
4097 .custom_flags(0x0220_0000) // BACKUP_SEMANTICS | OPEN_REPARSE_POINT
4098 .open(&path)
4099 .unwrap();
4100
4101 // World is a valid SID that cannot match this user's object owner.
4102 // Supply it directly to the exact-handle verifier without changing
4103 // the fixture's real owner or relying on privileged owner mutation.
4104 let mut required = 0_u32;
4105 let _ = unsafe { CreateWellKnownSid(WinWorldSid, None, None, &mut required) };
4106 assert!(required > 0, "Windows did not report the world SID size");
4107 let words = (required as usize).div_ceil(size_of::<usize>());
4108 let mut sid_buffer = vec![MaybeUninit::<usize>::zeroed(); words];
4109 let world = PSID(sid_buffer.as_mut_ptr().cast());
4110 unsafe { CreateWellKnownSid(WinWorldSid, None, Some(world), &mut required) }.unwrap();
4111
4112 let error = ensure_windows_plugin_target_owner(&target, world).unwrap_err();
4113 assert!(
4114 error.contains("not the current user"),
4115 "unexpected error: {error}"
4116 );
4117 }
4118
4119 #[test]
4120 fn blocked_state_replacement_preserves_the_stable_authority_file() {
4121 use std::os::windows::fs::OpenOptionsExt as _;
4122
4123 let directory = tempfile::tempdir().unwrap();
4124 let state_path = directory.path().join("state.json");
4125 std::fs::write(&state_path, b"old-authoritative-state").unwrap();
4126 let retained = std::fs::OpenOptions::new()
4127 .read(true)
4128 .share_mode(0x0000_0001)
4129 .open(&state_path)
4130 .unwrap();
4131
4132 let error = save_state_with_hardener(
4133 &state_path,
4134 &PluginStateFile::default(),
4135 harden_plugin_state_file,
4136 )
4137 .unwrap_err();
4138
4139 assert!(
4140 error.contains("durably persist"),
4141 "unexpected error: {error}"
4142 );
4143 assert_eq!(
4144 std::fs::read(&state_path).unwrap(),
4145 b"old-authoritative-state"
4146 );
4147 drop(retained);
4148 }
4149
4150 #[test]
4151 fn transient_state_replacement_contention_is_retried() {
4152 use std::os::windows::fs::OpenOptionsExt as _;
4153
4154 let directory = tempfile::tempdir().unwrap();
4155 let state_path = directory.path().join("state.json");
4156 std::fs::write(&state_path, b"old-authoritative-state").unwrap();
4157 // FILE_SHARE_READ alone omits delete sharing: the short-lived handle a
4158 // concurrent ACL pass or scanner holds on the stable file.
4159 let retained = std::fs::OpenOptions::new()
4160 .read(true)
4161 .share_mode(0x0000_0001)
4162 .open(&state_path)
4163 .unwrap();
4164 let release = std::thread::spawn(move || {
4165 std::thread::sleep(std::time::Duration::from_millis(50));
4166 drop(retained);
4167 });
4168
4169 save_state_with_hardener(
4170 &state_path,
4171 &PluginStateFile::default(),
4172 harden_plugin_state_file,
4173 )
4174 .expect("retry contended plugin state replacement");
4175
4176 release.join().unwrap();
4177 let published = std::fs::read_to_string(&state_path).unwrap();
4178 assert!(published.contains("\"schema_version\": 1"));
4179 let entries = std::fs::read_dir(directory.path())
4180 .unwrap()
4181 .map(|entry| entry.unwrap().file_name())
4182 .collect::<Vec<_>>();
4183 assert_eq!(entries, [std::ffi::OsString::from("state.json")]);
4184 }
4185
4186 #[test]
4187 fn owner_only_runtime_acl_is_protected_and_has_one_full_access_ace() {
4188 let directory = tempfile::tempdir().unwrap();
4189 let runtime = directory.path().join("runtime");
4190 std::fs::create_dir(&runtime).unwrap();
4191 set_windows_owner_only_acl(&runtime).unwrap();
4192
4193 let mut wide = runtime.as_os_str().encode_wide().collect::<Vec<_>>();
4194 wide.push(0);
4195 let mut required = 0_u32;
4196 // SAFETY: this size-probe intentionally supplies no destination buffer.
4197 let _ = unsafe {
4198 GetFileSecurityW(
4199 PCWSTR(wide.as_ptr()),
4200 (DACL_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION).0,
4201 None,
4202 0,
4203 &mut required,
4204 )
4205 };
4206 assert!(
4207 required > 0,
4208 "Windows did not report a security descriptor size"
4209 );
4210 let words = (required as usize).div_ceil(size_of::<usize>());
4211 let mut descriptor = vec![MaybeUninit::<usize>::zeroed(); words];
4212 let descriptor = PSECURITY_DESCRIPTOR(descriptor.as_mut_ptr().cast::<c_void>());
4213 // SAFETY: the aligned destination is at least `required` bytes and the
4214 // UTF-16 path remains NUL terminated for the call.
4215 assert!(
4216 unsafe {
4217 GetFileSecurityW(
4218 PCWSTR(wide.as_ptr()),
4219 (DACL_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION).0,
4220 Some(descriptor),
4221 required,
4222 &mut required,
4223 )
4224 }
4225 .as_bool()
4226 );
4227
4228 let mut present = BOOL::default();
4229 let mut defaulted = BOOL::default();
4230 let mut acl = std::ptr::null_mut::<ACL>();
4231 // SAFETY: `descriptor` contains the successful GetFileSecurityW result.
4232 unsafe { GetSecurityDescriptorDacl(descriptor, &mut present, &mut acl, &mut defaulted) }
4233 .unwrap();
4234 assert!(present.as_bool());
4235 assert!(!acl.is_null());
4236
4237 let mut info = ACL_SIZE_INFORMATION::default();
4238 // SAFETY: `acl` is owned by the live descriptor buffer above.
4239 unsafe {
4240 GetAclInformation(
4241 acl,
4242 (&mut info as *mut ACL_SIZE_INFORMATION).cast(),
4243 size_of::<ACL_SIZE_INFORMATION>() as u32,
4244 AclSizeInformation,
4245 )
4246 }
4247 .unwrap();
4248 assert_eq!(info.AceCount, 1, "runtime DACL must name only the owner");
4249
4250 let mut ace = std::ptr::null_mut::<c_void>();
4251 // SAFETY: the ACL contains exactly one ACE.
4252 unsafe { GetAce(acl, 0, &mut ace) }.unwrap();
4253 let ace = unsafe { &*ace.cast::<ACCESS_ALLOWED_ACE>() };
4254 assert_eq!(ace.Header.AceType, 0, "owner entry must be an allow ACE");
4255 assert_eq!(ace.Mask, 0x001f_01ff, "owner entry must grant full access");
4256 let ace_sid = PSID(std::ptr::addr_of!(ace.SidStart).cast_mut().cast());
4257 let mut owner = PSID::default();
4258 let mut owner_defaulted = BOOL::default();
4259 // SAFETY: `descriptor` contains the live security descriptor and both
4260 // output pointers reference initialized storage.
4261 unsafe { GetSecurityDescriptorOwner(descriptor, &mut owner, &mut owner_defaulted) }
4262 .unwrap();
4263 assert!(
4264 !owner.0.is_null(),
4265 "runtime object must have an explicit owner"
4266 );
4267 assert!(
4268 !owner_defaulted.as_bool(),
4269 "runtime object owner must be explicitly assigned"
4270 );
4271 // SAFETY: both SIDs are owned by the live descriptor/ACL buffers.
4272 unsafe { EqualSid(owner, ace_sid) }
4273 .expect("runtime object owner must equal its sole current-user ACE");
4274 let inheritance = (CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE).0 as u8;
4275 assert_eq!(ace.Header.AceFlags & inheritance, inheritance);
4276
4277 let mut control = 0_u16;
4278 let mut revision = 0_u32;
4279 // SAFETY: the descriptor buffer remains alive for this inspection.
4280 unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) }.unwrap();
4281 assert_ne!(
4282 control & SE_DACL_PROTECTED.0,
4283 0,
4284 "runtime DACL must not inherit broader parent permissions"
4285 );
4286 }
4287 }
4288
4288 lines RUST