返回 CodeWhale
managed_policy.rs
根目录 / crates / plugins / src / managed_policy.rs
1 //! Managed (organization/fleet) plugin policy: the Runtime-side enforcement primitive.
2 //!
3 //! An organization governs its members' Runtimes by delivering a policy document
4 //! to each machine; this module only defines the document and enforces it.
5 //! Delivery (network fetch, control-plane client, MDM deployment) is out of
6 //! scope: the policy arrives as a local file.
7 //!
8 //! Semantics, in order of importance:
9 //! - **Absent policy means today's exact behaviour.** Every plugin that enables
10 //! now must still enable when no policy file exists.
11 //! - **Local state can never defeat the policy.** Enforcement lives in the
12 //! registry's `apply_state` choke point, so a plugin enabled before the
13 //! policy arrived, or an `enabled: true` bit hand-edited into `state.json`,
14 //! comes back disabled. Execution boundaries re-read the trusted policy
15 //! source, and the existing MCP watcher cancels newly forbidden work on its
16 //! next poll. `PluginRegistry::enable` also re-reads the document.
17 //! - **A malformed policy fails closed.** An unreadable, unparseable, or
18 //! wrong-schema document refuses every enablement with a clear error; it
19 //! never silently degrades to "allow everything".
20 //!
21 //! The document is resolved to a single source: `managed-policy.json` next to
22 //! the plugin `state.json`, overridable by `CODEWHALE_MANAGED_POLICY_PATH` for
23 //! testing. The override is read from the pre-dotenv [`HostEnvironment`]
24 //! snapshot and frozen to an absolute source before dotenv, so a workspace
25 //! dotenv file or later working-directory change cannot redirect governance.
26 //!
27 //! This is deliberately a different concept from
28 //! [`PluginActivationPolicy`](super::activation::PluginActivationPolicy), which
29 //! describes which capability *kinds* this build will ever activate. The managed
30 //! policy describes which plugin *identities* this machine may enable.
31 //!
32 use std::collections::BTreeSet;
33 use std::fs;
34 use std::io::ErrorKind;
35 use std::path::{Path, PathBuf};
36
37 use serde::{Deserialize, Serialize};
38
39 use super::context::HostEnvironment;
40 use codewhale_config::PluginId;
41
42 /// Schema version of the managed policy document, versioned exactly like
43 /// `PluginStateFile`: a required `schema_version` field that must match.
44 pub const MANAGED_POLICY_SCHEMA_VERSION: u32 = 1;
45
46 /// File name resolved next to the plugin state file (e.g.
47 /// `~/.codewhale/plugins/managed-policy.json`).
48 pub const MANAGED_POLICY_FILE_NAME: &str = "managed-policy.json";
49
50 /// Process-environment override for the policy path. Read from the pre-dotenv
51 /// host snapshot, never from ambient process state after dotenv loads.
52 pub const MANAGED_POLICY_PATH_ENV: &str = "CODEWHALE_MANAGED_POLICY_PATH";
53
54 /// Organization-supplied allowlist of plugin identities permitted on this machine.
55 ///
56 /// Identities are full discovery [`PluginId`]s (`scope/hash/name`), matched
57 /// exactly: a renamed or relocated bundle has a different id and is not
58 /// covered by an entry written for another id.
59 #[derive(Debug, Clone, Serialize, Deserialize)]
60 #[serde(deny_unknown_fields)]
61 pub struct ManagedPluginPolicy {
62 pub schema_version: u32,
63 #[serde(default)]
64 pub allowed_plugins: BTreeSet<PluginId>,
65 #[serde(default)]
66 pub allow_unlisted: bool,
67 }
68
69 impl ManagedPluginPolicy {
70 /// True when `id` may be enabled under this policy: either it is
71 /// allowlisted, or the policy permits plugins outside the allowlist.
72 #[must_use]
73 pub fn allows(&self, id: &PluginId) -> bool {
74 self.allow_unlisted || self.allowed_plugins.contains(id)
75 }
76 }
77
78 /// Outcome of loading the managed policy document. There is no "ignore and
79 /// allow" outcome: anything other than absent-or-valid fails closed.
80 pub enum ManagedPolicyOutcome {
81 Absent,
82 Loaded(ManagedPluginPolicy),
83 Invalid(String),
84 }
85
86 /// Resolve the single policy source: the env override when set to a non-empty
87 /// value, otherwise `managed-policy.json` next to the plugin state file,
88 /// frozen as an absolute path while trusted discovery inputs are captured.
89 pub fn resolve_managed_policy_path(
90 state_path: &Path,
91 host_environment: Option<&HostEnvironment>,
92 ) -> Result<PathBuf, String> {
93 let override_path =
94 match host_environment.map(|environment| environment.var(MANAGED_POLICY_PATH_ENV)) {
95 Some(Ok(value)) if !value.trim().is_empty() => Some(value),
96 Some(Err(std::env::VarError::NotUnicode(_))) => {
97 return Err("Managed plugin policy override is not valid Unicode".to_string());
98 }
99 _ => None,
100 };
101 let path = override_path.map(PathBuf::from).unwrap_or_else(|| {
102 state_path
103 .parent()
104 .filter(|parent| !parent.as_os_str().is_empty())
105 .unwrap_or_else(|| Path::new("."))
106 .join(MANAGED_POLICY_FILE_NAME)
107 });
108 std::path::absolute(&path)
109 .map_err(|error| format!("Managed plugin policy source could not be resolved: {error}"))
110 }
111
112 /// Load the policy document. A missing file is [`ManagedPolicyOutcome::Absent`]
113 /// (today's behaviour); any other failure is [`ManagedPolicyOutcome::Invalid`].
114 pub fn load_managed_policy(path: &Path) -> ManagedPolicyOutcome {
115 let raw = match fs::read_to_string(path) {
116 Ok(raw) => raw,
117 Err(error) if error.kind() == ErrorKind::NotFound => {
118 return ManagedPolicyOutcome::Absent;
119 }
120 Err(error) => {
121 return ManagedPolicyOutcome::Invalid(format!(
122 "failed to read {}: {error}",
123 path.display()
124 ));
125 }
126 };
127 let policy: ManagedPluginPolicy = match serde_json::from_str(&raw) {
128 Ok(policy) => policy,
129 Err(error) => {
130 return ManagedPolicyOutcome::Invalid(format!(
131 "failed to parse {}: {error}",
132 path.display()
133 ));
134 }
135 };
136 if policy.schema_version != MANAGED_POLICY_SCHEMA_VERSION {
137 return ManagedPolicyOutcome::Invalid(format!(
138 "unsupported managed plugin policy schema {}; expected {MANAGED_POLICY_SCHEMA_VERSION}",
139 policy.schema_version
140 ));
141 }
142 ManagedPolicyOutcome::Loaded(policy)
143 }
144
144 lines RUST