1use std::io;
20use std::path::{Path, PathBuf};
21
22use crate::agent::{AgentProfile, Entitlements};
23
24mod lock;
25pub use lock::{ProfileLock, lock_path, lock_profile};
26
27pub const PINS_DIR: &str = "entitlement-pins";
29
30const PIN_EXT: &str = "json";
31
32const PIN_VERSION: u32 = 1;
34
35#[derive(serde::Serialize, serde::Deserialize)]
36struct PinFile {
37 version: u32,
38 entitlements: serde_json::Value,
39}
40
41pub fn pin_path(mur_home: &Path, agent: &str) -> PathBuf {
43 mur_home.join(PINS_DIR).join(format!("{agent}.{PIN_EXT}"))
44}
45
46#[derive(Debug, PartialEq, Eq)]
48pub enum PinCheck {
49 Match,
51 Missing,
53 Mismatch { changed: Vec<String> },
55}
56
57#[derive(Debug, thiserror::Error)]
58pub enum PinError {
59 #[error("io error on {path}: {source}")]
60 Io { path: PathBuf, source: io::Error },
61 #[error("invalid pin file {path}: {msg}")]
62 Invalid { path: PathBuf, msg: String },
63 #[error("invalid profile {path}: {msg}")]
64 Profile { path: PathBuf, msg: String },
65 #[error("invalid agent name '{0}'")]
66 Name(String),
67}
68
69fn canonical(ent: &Entitlements) -> serde_json::Value {
70 serde_json::to_value(ent).expect("Entitlements serializes to JSON")
72}
73
74fn checked_name(agent: &str) -> Result<(), PinError> {
75 crate::agent_name::validate_agent_name(agent).map_err(|_| PinError::Name(agent.to_string()))
76}
77
78pub fn write_pin(mur_home: &Path, agent: &str, ent: &Entitlements) -> Result<(), PinError> {
81 checked_name(agent)?;
82 let path = pin_path(mur_home, agent);
83 let io_err = |source| PinError::Io {
84 path: path.clone(),
85 source,
86 };
87 let dir = mur_home.join(PINS_DIR);
88 std::fs::create_dir_all(&dir).map_err(io_err)?;
89 let body = PinFile {
90 version: PIN_VERSION,
91 entitlements: canonical(ent),
92 };
93 let bytes = crate::jcs::to_jcs_for(&body);
94 let mut tmp = tempfile::NamedTempFile::new_in(&dir).map_err(io_err)?;
95 io::Write::write_all(&mut tmp, &bytes).map_err(io_err)?;
96 tmp.persist(&path).map_err(|e| io_err(e.error))?;
97 Ok(())
98}
99
100pub fn entitlements_from_yaml(yaml: &str, path: &Path) -> Result<Entitlements, PinError> {
105 serde_yaml_ng::from_str::<AgentProfile>(yaml)
106 .map(|p| p.entitlements)
107 .map_err(|e| PinError::Profile {
108 path: path.to_path_buf(),
109 msg: e.to_string(),
110 })
111}
112
113pub fn repin_from_profile(mur_home: &Path, agent: &str) -> Result<(), PinError> {
117 checked_name(agent)?;
118 let path = mur_home.join("agents").join(agent).join("profile.yaml");
119 let yaml = std::fs::read_to_string(&path).map_err(|source| PinError::Io {
120 path: path.clone(),
121 source,
122 })?;
123 let ent = entitlements_from_yaml(&yaml, &path)?;
124 write_pin(mur_home, agent, &ent)
125}
126
127pub fn advance_pin(
136 mur_home: &Path,
137 agent: &str,
138 prior: Option<&Entitlements>,
139 new: &Entitlements,
140) -> Result<bool, PinError> {
141 let trusted = match prior {
142 None => true,
144 Some(p) => matches!(
145 check(mur_home, agent, p)?,
146 PinCheck::Match | PinCheck::Missing
147 ),
148 };
149 if trusted {
150 write_pin(mur_home, agent, new)?;
151 }
152 Ok(trusted)
153}
154
155pub fn remove_pin(mur_home: &Path, agent: &str) -> Result<(), PinError> {
158 checked_name(agent)?;
159 let path = pin_path(mur_home, agent);
160 match std::fs::remove_file(&path) {
161 Ok(()) => Ok(()),
162 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
163 Err(source) => Err(PinError::Io { path, source }),
164 }
165}
166
167pub fn rename_pin(mur_home: &Path, old: &str, new: &str) -> Result<(), PinError> {
169 checked_name(old)?;
170 checked_name(new)?;
171 let (from, to) = (pin_path(mur_home, old), pin_path(mur_home, new));
172 match std::fs::rename(&from, &to) {
173 Ok(()) => Ok(()),
174 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
175 Err(source) => Err(PinError::Io { path: from, source }),
176 }
177}
178
179pub fn check(mur_home: &Path, agent: &str, ent: &Entitlements) -> Result<PinCheck, PinError> {
181 checked_name(agent)?;
182 let path = pin_path(mur_home, agent);
183 let raw = match std::fs::read(&path) {
184 Ok(b) => b,
185 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(PinCheck::Missing),
186 Err(source) => return Err(PinError::Io { path, source }),
187 };
188 let invalid = |msg: String| PinError::Invalid {
189 path: path.clone(),
190 msg,
191 };
192 let file: PinFile = serde_json::from_slice(&raw).map_err(|e| invalid(e.to_string()))?;
193 if file.version != PIN_VERSION {
194 return Err(invalid(format!("unsupported version {}", file.version)));
195 }
196 let pinned: Entitlements =
199 serde_json::from_value(file.entitlements).map_err(|e| invalid(e.to_string()))?;
200 let (a, b) = (canonical(&pinned), canonical(ent));
201 if a == b {
202 return Ok(PinCheck::Match);
203 }
204 Ok(PinCheck::Mismatch {
205 changed: changed_keys(&a, &b),
206 })
207}
208
209pub fn changed_entitlements(a: &Entitlements, b: &Entitlements) -> Vec<String> {
211 let (a, b) = (canonical(a), canonical(b));
212 if a == b {
213 return Vec::new();
214 }
215 changed_keys(&a, &b)
216}
217
218fn changed_keys(a: &serde_json::Value, b: &serde_json::Value) -> Vec<String> {
219 let (Some(a), Some(b)) = (a.as_object(), b.as_object()) else {
220 return vec!["entitlements".to_string()];
221 };
222 let mut keys: Vec<String> = a
223 .keys()
224 .chain(b.keys())
225 .filter(|k| a.get(*k) != b.get(*k))
226 .cloned()
227 .collect();
228 keys.sort();
229 keys.dedup();
230 keys
231}
232
233#[cfg(test)]
234mod tests;