1use std::io;
26use std::path::{Path, PathBuf};
27
28use crate::identity::{ChainOptions, RotationAttestation, verify_chain};
29
30pub const IDENTITY_PINS_DIR: &str = "identity-pins";
32
33pub const PUBKEY_FILE: &str = "identity.pub";
35pub const CHAIN_FILE: &str = "rotations.jsonl";
36
37const PIN_EXT: &str = "json";
38const PIN_VERSION: u32 = 1;
39
40#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
43pub struct IdentityPin {
44 pub version: u32,
45 pub pubkey: String,
46 pub key_version: u32,
47 pub chain: Vec<RotationAttestation>,
48 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
53 pub fail_closed: bool,
54}
55
56#[derive(Debug, thiserror::Error)]
57pub enum IdentityPinError {
58 #[error("io error on {path}: {source}")]
59 Io { path: PathBuf, source: io::Error },
60 #[error("invalid identity pin {path}: {msg}")]
61 Invalid { path: PathBuf, msg: String },
62 #[error("identity of '{agent}' is inconsistent: {msg}")]
63 Inconsistent { agent: String, msg: String },
64 #[error("invalid agent name '{0}'")]
65 Name(String),
66 #[error("rotation of '{agent}' does not extend its pinned identity: {msg}")]
67 NotAnExtension { agent: String, msg: String },
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct TrustedIdentity {
73 pub head_pubkey: String,
75 pub head_key_version: u32,
76 pub chain: Option<Vec<RotationAttestation>>,
80}
81
82pub fn pin_path(mur_home: &Path, agent: &str) -> PathBuf {
84 mur_home
85 .join(IDENTITY_PINS_DIR)
86 .join(format!("{agent}.{PIN_EXT}"))
87}
88
89fn checked_name(agent: &str) -> Result<(), IdentityPinError> {
90 crate::agent_name::validate_agent_name(agent)
91 .map_err(|_| IdentityPinError::Name(agent.to_string()))
92}
93
94pub fn split_agent_home(agent_home: &Path) -> Option<(&Path, &str)> {
98 let parent = agent_home.parent()?;
99 if parent.file_name()? != "agents" {
100 return None;
101 }
102 let name = agent_home.file_name()?.to_str()?;
103 crate::agent_name::validate_agent_name(name).ok()?;
104 Some((parent.parent()?, name))
105}
106
107pub fn parse_chain(text: &str) -> Option<Vec<RotationAttestation>> {
109 text.lines()
110 .filter(|l| !l.trim().is_empty())
111 .map(serde_json::from_str)
112 .collect::<Result<_, _>>()
113 .ok()
114}
115
116pub fn pin_from_disk(mur_home: &Path, agent: &str) -> Result<IdentityPin, IdentityPinError> {
122 checked_name(agent)?;
123 let home = mur_home.join("agents").join(agent);
124 let pub_path = home.join(PUBKEY_FILE);
125 let pubkey = std::fs::read_to_string(&pub_path)
126 .map_err(|source| IdentityPinError::Io {
127 path: pub_path.clone(),
128 source,
129 })?
130 .trim()
131 .to_string();
132 let chain_path = home.join(CHAIN_FILE);
133 let chain = match std::fs::read_to_string(&chain_path) {
134 Ok(text) => parse_chain(&text).ok_or_else(|| IdentityPinError::Invalid {
135 path: chain_path.clone(),
136 msg: "unparseable rotation attestation".into(),
137 })?,
138 Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
139 Err(source) => {
140 return Err(IdentityPinError::Io {
141 path: chain_path,
142 source,
143 });
144 }
145 };
146 let key_version = match chain.last() {
147 Some(head) if head.new_pubkey != pubkey => {
148 return Err(IdentityPinError::Inconsistent {
149 agent: agent.to_string(),
150 msg: format!("{CHAIN_FILE} head is not {PUBKEY_FILE}"),
151 });
152 }
153 Some(head) => head.new_key_version,
154 None => 0,
155 };
156 let pin = IdentityPin {
157 version: PIN_VERSION,
158 pubkey,
159 key_version,
160 chain,
161 fail_closed: false,
162 };
163 write_pin(mur_home, agent, &pin)?;
164 Ok(pin)
165}
166
167fn pin_head_only(
169 mur_home: &Path,
170 agent: &str,
171 rotation: &RotationAttestation,
172) -> Result<IdentityPin, IdentityPinError> {
173 let pin = IdentityPin {
174 version: PIN_VERSION,
175 pubkey: rotation.new_pubkey.clone(),
176 key_version: rotation.new_key_version,
177 chain: Vec::new(),
178 fail_closed: false,
179 };
180 write_pin(mur_home, agent, &pin)?;
181 Ok(pin)
182}
183
184pub fn write_fail_closed(mur_home: &Path, agent: &str) -> Result<(), IdentityPinError> {
188 checked_name(agent)?;
189 let pin = IdentityPin {
190 version: PIN_VERSION,
191 pubkey: String::new(),
192 key_version: 0,
193 chain: Vec::new(),
194 fail_closed: true,
195 };
196 write_pin(mur_home, agent, &pin)
197}
198
199pub fn extend_pin(
207 mur_home: &Path,
208 agent: &str,
209 rotation: &RotationAttestation,
210) -> Result<IdentityPin, IdentityPinError> {
211 let Some(mut pin) = load_pin(mur_home, agent)? else {
212 return pin_head_only(mur_home, agent, rotation);
216 };
217 let refuse = |msg: String| IdentityPinError::NotAnExtension {
218 agent: agent.to_string(),
219 msg,
220 };
221 let emergency = rotation.reason == crate::identity::RotationReason::Emergency;
222 if pin.fail_closed {
223 if !emergency {
224 return Err(refuse(
225 "the pin is fail-closed; only an emergency rekey resets it".into(),
226 ));
227 }
228 return pin_head_only(mur_home, agent, rotation);
229 }
230 if rotation.bootstrap {
231 return Err(refuse("a bootstrap cannot extend a pin".into()));
232 }
233 if rotation.old_pubkey != pin.pubkey {
234 return Err(refuse("old key is not the pinned key".into()));
235 }
236 if rotation.old_key_version != pin.key_version
237 || Some(rotation.new_key_version) != pin.key_version.checked_add(1)
238 {
239 return Err(refuse(format!(
240 "version {} -> {} does not follow pinned version {}",
241 rotation.old_key_version, rotation.new_key_version, pin.key_version
242 )));
243 }
244 rotation
245 .verify_or_emergency(&pin.pubkey)
246 .map_err(|e| refuse(format!("not signed by the pinned key: {e}")))?;
247 pin.pubkey = rotation.new_pubkey.clone();
248 pin.key_version = rotation.new_key_version;
249 pin.chain.push(rotation.clone());
250 write_pin(mur_home, agent, &pin)?;
251 Ok(pin)
252}
253
254fn write_pin(mur_home: &Path, agent: &str, pin: &IdentityPin) -> Result<(), IdentityPinError> {
256 let dir = mur_home.join(IDENTITY_PINS_DIR);
257 let path = pin_path(mur_home, agent);
258 let io_err = |source| IdentityPinError::Io {
259 path: path.clone(),
260 source,
261 };
262 std::fs::create_dir_all(&dir).map_err(io_err)?;
263 let bytes = crate::jcs::to_jcs_for(pin);
264 let mut tmp = tempfile::NamedTempFile::new_in(&dir).map_err(io_err)?;
265 io::Write::write_all(&mut tmp, &bytes).map_err(io_err)?;
266 tmp.persist(&path).map_err(|e| io_err(e.error))?;
267 Ok(())
268}
269
270pub fn load_pin(mur_home: &Path, agent: &str) -> Result<Option<IdentityPin>, IdentityPinError> {
272 checked_name(agent)?;
273 let path = pin_path(mur_home, agent);
274 let raw = match std::fs::read(&path) {
275 Ok(b) => b,
276 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
277 Err(source) => return Err(IdentityPinError::Io { path, source }),
278 };
279 let invalid = |msg: String| IdentityPinError::Invalid {
280 path: path.clone(),
281 msg,
282 };
283 let pin: IdentityPin = serde_json::from_slice(&raw).map_err(|e| invalid(e.to_string()))?;
284 if pin.version != PIN_VERSION {
285 return Err(invalid(format!("unsupported version {}", pin.version)));
286 }
287 Ok(Some(pin))
288}
289
290pub fn remove_pin(mur_home: &Path, agent: &str) -> Result<(), IdentityPinError> {
292 checked_name(agent)?;
293 let path = pin_path(mur_home, agent);
294 match std::fs::remove_file(&path) {
295 Ok(()) => Ok(()),
296 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
297 Err(source) => Err(IdentityPinError::Io { path, source }),
298 }
299}
300
301pub fn rename_pin(mur_home: &Path, old: &str, new: &str) -> Result<(), IdentityPinError> {
303 checked_name(old)?;
304 checked_name(new)?;
305 let (from, to) = (pin_path(mur_home, old), pin_path(mur_home, new));
306 match std::fs::rename(&from, &to) {
307 Ok(()) => Ok(()),
308 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
309 Err(source) => Err(IdentityPinError::Io { path: from, source }),
310 }
311}
312
313fn strict() -> ChainOptions {
314 ChainOptions {
315 allow_emergency: false,
316 }
317}
318
319pub fn resolve(agent_home: &Path) -> Option<Option<TrustedIdentity>> {
332 let (mur_home, name) = split_agent_home(agent_home)?;
333 let pin = match load_pin(mur_home, name) {
334 Ok(Some(pin)) => pin,
335 Ok(None) => return None,
336 Err(e) => {
337 tracing::warn!(agent = name, error = %e, "identity pin unusable; trusting no key");
338 return Some(None);
339 }
340 };
341 if pin.fail_closed {
342 return Some(None);
343 }
344 let chain = (!pin.chain.is_empty() && verify_chain(&pin.chain, strict()).is_ok())
345 .then(|| pin.chain.clone());
346 Some(Some(TrustedIdentity {
347 head_pubkey: pin.pubkey,
348 head_key_version: pin.key_version,
349 chain,
350 }))
351}
352
353#[cfg(test)]
354mod tests;