1use serde::{Deserialize, Serialize};
15use std::collections::BTreeMap;
16use std::path::PathBuf;
17
18use super::audit_trail::{self, AuditEntryData, AuditEventType};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum AgentStatus {
23 Active,
24 Suspended,
25 Decommissioned,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct Attestation {
30 pub binary_sha256: String,
32 pub config_sha256: String,
34 pub attested_at: String,
35 #[serde(skip_serializing_if = "Option::is_none", default)]
49 pub drift: Option<DriftMark>,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct DriftMark {
57 pub detected_at: String,
58 pub binary: bool,
60 pub config: bool,
62 pub evidence: String,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct HeartbeatOutcome {
75 pub drift: Option<DriftMark>,
76 pub newly_observed: bool,
77}
78
79#[cfg(test)]
80impl HeartbeatOutcome {
81 pub(crate) fn evidence(&self) -> Option<&str> {
83 self.drift.as_ref().map(|mark| mark.evidence.as_str())
84 }
85
86 pub(crate) fn is_none(&self) -> bool {
89 !self.newly_observed
90 }
91
92 pub(crate) fn expect(self, message: &str) -> String {
95 self.drift
96 .map(|mark| mark.evidence)
97 .unwrap_or_else(|| panic!("{message}"))
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct DriftAcknowledgement {
104 pub agent_id: String,
105 pub evidence: String,
107 pub detected_at: String,
108 pub acknowledged_at: String,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub(crate) struct DriftDimensions {
116 pub binary: bool,
117 pub config: bool,
118}
119
120impl DriftDimensions {
121 fn any(self) -> bool {
122 self.binary || self.config
123 }
124
125 fn label(self) -> &'static str {
127 match (self.binary, self.config) {
128 (true, true) => "binary+config",
129 (true, false) => "binary",
130 (false, true) => "config",
131 (false, false) => "none",
132 }
133 }
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
144pub(crate) struct DriftPolicy {
145 pub block_on_drift: bool,
146}
147
148impl DriftPolicy {
149 pub(crate) fn from_env() -> Self {
150 Self {
151 block_on_drift: std::env::var("LEAN_CTX_AGENT_BLOCK_ON_DRIFT")
152 .is_ok_and(|value| matches!(value.trim(), "1" | "true" | "yes")),
153 }
154 }
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct AgentRecord {
159 pub agent_id: String,
161 pub role: String,
163 pub owner: String,
165 pub status: AgentStatus,
166 pub created_at: String,
167 pub public_key: String,
169 #[serde(skip_serializing_if = "Option::is_none", default)]
170 pub attestation: Option<Attestation>,
171 #[serde(skip_serializing_if = "Option::is_none", default)]
172 pub last_heartbeat: Option<String>,
173 #[serde(skip_serializing_if = "Option::is_none", default)]
174 pub suspended_reason: Option<String>,
175 #[serde(skip_serializing_if = "Option::is_none", default)]
176 pub decommissioned_at: Option<String>,
177}
178
179#[derive(Debug, Clone, Serialize)]
182pub struct IdentityCheck {
183 pub agent_id: String,
184 pub registered: bool,
185 pub allowed: bool,
187 #[serde(skip_serializing_if = "Option::is_none")]
188 pub status: Option<AgentStatus>,
189 pub drifted: bool,
192 pub detail: String,
193}
194
195fn registry_path() -> Result<PathBuf, String> {
196 let dir = crate::core::data_dir::lean_ctx_data_dir()
197 .map_err(|e| format!("data dir: {e}"))?
198 .join("agents");
199 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
200 Ok(dir.join("identity-registry.json"))
201}
202
203fn legacy_registry_path() -> Result<PathBuf, String> {
204 registry_path().map(|path| path.with_file_name("registry.json"))
205}
206
207fn load_unlocked(path: &PathBuf) -> Result<BTreeMap<String, AgentRecord>, String> {
208 let contents = match std::fs::read_to_string(path) {
209 Ok(contents) => contents,
210 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
211 return Ok(BTreeMap::new());
212 }
213 Err(error) => return Err(format!("read registry {}: {error}", path.display())),
214 };
215 serde_json::from_str(&contents)
216 .map_err(|error| format!("parse registry {}: {error}", path.display()))
217}
218
219fn load_registry(path: &PathBuf) -> Result<BTreeMap<String, AgentRecord>, String> {
220 if path.exists() {
221 return load_unlocked(path);
222 }
223 let legacy = legacy_registry_path()?;
224 match load_unlocked(&legacy) {
225 Ok(registry) => Ok(registry),
226 Err(identity_error) => {
227 let is_presence_registry = std::fs::read_to_string(&legacy)
232 .ok()
233 .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
234 .and_then(|value| value.get("agents").cloned())
235 .is_some_and(|agents| agents.is_array());
236 if is_presence_registry {
237 Ok(BTreeMap::new())
238 } else {
239 Err(identity_error)
240 }
241 }
242 }
243}
244
245fn load_registry_strict() -> Result<BTreeMap<String, AgentRecord>, String> {
248 let path = registry_path()?;
249 let path = if path.exists() {
250 path
251 } else {
252 legacy_registry_path()?
253 };
254 if !path.exists() {
255 return Ok(BTreeMap::new());
256 }
257 let contents = std::fs::read_to_string(&path)
258 .map_err(|error| format!("read durable identity registry: {error}"))?;
259 serde_json::from_str(&contents)
260 .map_err(|error| format!("durable identity registry is corrupt: {error}"))
261}
262
263fn with_registry<T>(
266 f: impl FnOnce(&mut BTreeMap<String, AgentRecord>) -> Result<T, String>,
267) -> Result<T, String> {
268 use fs2::FileExt;
269 use std::time::{Duration, Instant};
270
271 const LOCK_TIMEOUT: Duration = Duration::from_millis(750);
272 const LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(25);
273 let path = registry_path()?;
274 let lock_path = path.with_extension("lock");
275 let lock = std::fs::OpenOptions::new()
276 .create(true)
277 .truncate(false)
278 .write(true)
279 .open(&lock_path)
280 .map_err(|e| format!("registry lock: {e}"))?;
281 let deadline = Instant::now() + LOCK_TIMEOUT;
282 let _lock = loop {
283 match lock.try_lock_exclusive() {
284 Ok(()) => break super::file_lock::FlockGuard::from_locked(lock),
285 Err(error) if super::file_lock::is_contended(&error) && Instant::now() < deadline => {
286 std::thread::sleep(LOCK_RETRY_INTERVAL);
287 }
288 Err(error) if super::file_lock::is_contended(&error) => {
289 return Err(format!(
290 "registry lock timed out after {}ms; another agent operation is still active",
291 LOCK_TIMEOUT.as_millis()
292 ));
293 }
294 Err(error) => return Err(format!("registry lock: {error}")),
295 }
296 };
297
298 let mut registry = load_registry(&path)?;
299 let result = f(&mut registry);
300 if result.is_ok() {
301 persist_registry(&path, ®istry)?;
302 }
303 result
304}
305
306fn persist_registry(
312 path: &PathBuf,
313 registry: &BTreeMap<String, AgentRecord>,
314) -> Result<(), String> {
315 use std::io::Write;
316
317 let json = serde_json::to_string_pretty(registry).map_err(|e| format!("serialize: {e}"))?;
318 let tmp = path.with_extension("json.tmp");
319 let written = (|| -> std::io::Result<()> {
320 let mut file = std::fs::File::create(&tmp)?;
321 file.write_all(json.as_bytes())?;
322 file.sync_all()
323 })();
324 if let Err(error) = written {
325 let _ = std::fs::remove_file(&tmp);
326 return Err(format!("persist registry: {error}"));
327 }
328 std::fs::rename(&tmp, path).map_err(|error| {
329 let _ = std::fs::remove_file(&tmp);
330 format!("persist registry: {error}")
331 })
332}
333
334#[cfg(test)]
336pub fn list() -> Vec<AgentRecord> {
337 try_list().unwrap_or_default()
338}
339
340pub fn try_list() -> Result<Vec<AgentRecord>, String> {
341 let path = registry_path()?;
342 Ok(load_registry(&path)?.into_values().collect())
343}
344
345#[cfg(test)]
348pub(crate) fn list_active() -> Vec<AgentRecord> {
349 list()
350 .into_iter()
351 .filter(|record| record.status == AgentStatus::Active)
352 .collect()
353}
354
355pub fn try_list_active() -> Result<Vec<AgentRecord>, String> {
356 Ok(try_list()?
357 .into_iter()
358 .filter(|record| record.status == AgentStatus::Active)
359 .collect())
360}
361
362#[cfg(test)]
363pub(crate) fn get(agent_id: &str) -> Option<AgentRecord> {
364 try_get(agent_id).ok().flatten()
365}
366
367pub fn try_get(agent_id: &str) -> Result<Option<AgentRecord>, String> {
368 let path = registry_path()?;
369 Ok(load_registry(&path)?.remove(agent_id))
370}
371
372pub(crate) fn require_active(agent_id: &str) -> Result<(), String> {
375 if agent_id.trim().is_empty() {
376 return Err("durable identity id must not be empty".to_string());
377 }
378 let registry = load_registry_strict()?;
379 let Some(record) = registry.get(agent_id) else {
380 return Err(format!("durable identity '{agent_id}' is not registered"));
381 };
382 match record.status {
383 AgentStatus::Active => Ok(()),
384 AgentStatus::Suspended => Err(format!("durable identity '{agent_id}' is suspended")),
385 AgentStatus::Decommissioned => {
386 Err(format!("durable identity '{agent_id}' is decommissioned"))
387 }
388 }
389}
390
391fn audit(event_type: AuditEventType, agent_id: &str, role: &str, detail: Option<String>) {
392 audit_trail::record(AuditEntryData {
393 agent_id: agent_id.to_string(),
394 tool: "agent_registry".to_string(),
395 action: detail,
396 input_hash: audit_trail::hash_input(&serde_json::Map::new()),
397 output_tokens: 0,
398 role: role.to_string(),
399 event_type,
400 });
401}
402
403fn binary_sha256() -> String {
414 use std::sync::{Mutex, OnceLock};
415 type HashCache = Mutex<Option<((u64, u64), String)>>;
417 static CACHE: OnceLock<HashCache> = OnceLock::new();
418
419 let Ok(exe) = std::env::current_exe() else {
420 return String::new();
421 };
422 let Ok(meta) = std::fs::metadata(&exe) else {
423 return String::new();
424 };
425 let mtime = meta
426 .modified()
427 .ok()
428 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
429 .map_or(0, |d| d.as_secs());
430 let key = (meta.len(), mtime);
431
432 let cache = CACHE.get_or_init(|| Mutex::new(None));
433 let mut slot = cache
434 .lock()
435 .unwrap_or_else(std::sync::PoisonError::into_inner);
436 if let Some((cached_key, hash)) = slot.as_ref()
437 && *cached_key == key
438 {
439 return hash.clone();
440 }
441 let hash = std::fs::read(&exe)
442 .map(|bytes| sha256_hex(&bytes))
443 .unwrap_or_default();
444 *slot = Some((key, hash.clone()));
445 hash
446}
447
448pub(crate) fn attest(role: &str) -> Attestation {
452 let binary_sha256 = binary_sha256();
453 let config_sha256 = role_file_path(role)
454 .and_then(|p| std::fs::read(p).ok())
455 .map(|bytes| sha256_hex(&bytes))
456 .unwrap_or_default();
457 Attestation {
458 binary_sha256,
459 config_sha256,
460 attested_at: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
461 drift: None,
462 }
463}
464
465fn diff_attestation(previous: &Attestation, fresh: &Attestation) -> DriftDimensions {
468 DriftDimensions {
469 binary: previous.binary_sha256 != fresh.binary_sha256,
470 config: previous.config_sha256 != fresh.config_sha256,
471 }
472}
473
474const EVIDENCE_DIGEST_PREFIX: usize = 12;
478
479fn digest_prefix(digest: &str) -> String {
483 if digest.is_empty() {
484 return "none".to_string();
485 }
486 digest
487 .chars()
488 .take(EVIDENCE_DIGEST_PREFIX)
489 .map(|c| if c.is_ascii_hexdigit() { c } else { '?' })
490 .collect()
491}
492
493fn drift_evidence(
498 previous: &Attestation,
499 fresh: &Attestation,
500 dimensions: DriftDimensions,
501) -> String {
502 use std::fmt::Write as _;
503
504 let mut evidence = format!("attestation drift dimensions={}", dimensions.label());
505 if dimensions.binary {
506 let _ = write!(
507 evidence,
508 " binary={}->{}",
509 digest_prefix(&previous.binary_sha256),
510 digest_prefix(&fresh.binary_sha256)
511 );
512 }
513 if dimensions.config {
514 let _ = write!(
515 evidence,
516 " config={}->{}",
517 digest_prefix(&previous.config_sha256),
518 digest_prefix(&fresh.config_sha256)
519 );
520 }
521 evidence
522}
523
524const EVIDENCE_MAX_CHARS: usize = 256;
528
529fn bounded_evidence(evidence: &str) -> String {
533 evidence
534 .chars()
535 .filter(|c| !c.is_control() && *c != '"' && *c != '\\')
536 .take(EVIDENCE_MAX_CHARS)
537 .collect()
538}
539
540fn validate_drift_mark(mark: DriftMark) -> Result<DriftMark, String> {
541 let validated = bounded_evidence(&mark.evidence);
542 if validated.is_empty() || validated != mark.evidence {
543 return Err("stored drift evidence is invalid or oversized".to_string());
544 }
545 Ok(mark)
546}
547
548fn audit_drift(agent_id: &str, role: &str, evidence: &str) -> Result<String, String> {
551 audit_trail::try_record(AuditEntryData {
552 agent_id: agent_id.to_string(),
553 tool: "agent_registry".to_string(),
554 action: Some(evidence.to_string()),
555 input_hash: audit_trail::hash_input(&serde_json::Map::new()),
556 output_tokens: 0,
557 role: role.to_string(),
558 event_type: AuditEventType::AgentDriftDetected,
559 })
560 .map(|entry| entry.entry_hash)
561 .map_err(|error| format!("drift audit failed, attestation not updated: {error}"))
562}
563
564fn audit_drift_ack(agent_id: &str, role: &str, mark: &DriftMark) -> Result<(), String> {
570 let chain = audit_trail::verify_chain();
571 if !chain.source_present {
572 return Err("acknowledgement audit failed, audit trail unavailable".to_string());
573 }
574 if !chain.valid {
575 return Err(format!(
576 "acknowledgement audit failed, audit chain invalid at entry {}",
577 chain.first_invalid_at.unwrap_or(chain.total_entries)
578 ));
579 }
580 let evidence = bounded_evidence(&mark.evidence);
581 if evidence.is_empty() || evidence != mark.evidence {
582 return Err("acknowledgement evidence on record is invalid or oversized".to_string());
583 }
584 audit_trail::try_record(AuditEntryData {
585 agent_id: agent_id.to_string(),
586 tool: "agent_registry".to_string(),
587 action: Some(evidence),
588 input_hash: audit_trail::hash_input(&serde_json::Map::new()),
589 output_tokens: 0,
590 role: role.to_string(),
591 event_type: AuditEventType::AgentDriftAcknowledged,
592 })
593 .map(|_| ())
594 .map_err(|error| format!("acknowledgement audit failed, drift not cleared: {error}"))
595}
596
597fn drift_from_audit(agent_id: &str) -> Result<Option<DriftMark>, String> {
598 let Some((detected_at, evidence)) = audit_trail::latest_unacknowledged_drift(agent_id)? else {
599 return Ok(None);
600 };
601 let validated = bounded_evidence(&evidence);
602 if validated.is_empty() || validated != evidence {
603 return Err("audit drift evidence is invalid or oversized".to_string());
604 }
605 let dimensions = evidence
606 .split_whitespace()
607 .find_map(|part| part.strip_prefix("dimensions="))
608 .unwrap_or("none");
609 Ok(Some(DriftMark {
610 detected_at,
611 binary: matches!(dimensions, "binary" | "binary+config"),
612 config: matches!(dimensions, "config" | "binary+config"),
613 evidence,
614 }))
615}
616
617fn role_file_path(role: &str) -> Option<PathBuf> {
618 let dir = crate::core::data_dir::lean_ctx_data_dir()
619 .ok()?
620 .join("roles");
621 let path = dir.join(format!("{role}.toml"));
622 path.exists().then_some(path)
623}
624
625fn sha256_hex(bytes: &[u8]) -> String {
626 use sha2::{Digest, Sha256};
627 let mut hasher = Sha256::new();
628 hasher.update(bytes);
629 crate::core::agent_identity::hex_encode(&hasher.finalize())
630}
631
632pub fn register(agent_id: &str, role: &str, owner: &str) -> Result<AgentRecord, String> {
636 if agent_id.trim().is_empty()
637 || !agent_id
638 .chars()
639 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
640 {
641 return Err("agent_id must be non-empty [A-Za-z0-9_-]".to_string());
642 }
643 if owner.trim().is_empty() {
644 return Err(
645 "owner is mandatory — every agent identity has a human accountable for it".to_string(),
646 );
647 }
648 if crate::core::roles::load_role(role).is_none() {
649 return Err(format!(
650 "role '{role}' does not exist (see `lean-ctx roles list`)"
651 ));
652 }
653
654 let public_key = crate::core::agent_identity::get_public_key(agent_id)
655 .map(|k| crate::core::agent_identity::hex_encode(k.as_bytes()))
656 .map_err(|e| format!("keypair: {e}"))?;
657
658 let record = AgentRecord {
659 agent_id: agent_id.to_string(),
660 role: role.to_string(),
661 owner: owner.trim().to_string(),
662 status: AgentStatus::Active,
663 created_at: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
664 public_key,
665 attestation: Some(attest(role)),
666 last_heartbeat: None,
667 suspended_reason: None,
668 decommissioned_at: None,
669 };
670
671 with_registry(|reg| {
672 if reg.contains_key(agent_id) {
673 return Err(format!("agent '{agent_id}' is already registered"));
674 }
675 reg.insert(agent_id.to_string(), record.clone());
676 Ok(())
677 })?;
678 audit(
679 AuditEventType::AgentRegistered,
680 agent_id,
681 role,
682 Some(format!("owner={}", record.owner)),
683 );
684 Ok(record)
685}
686
687pub fn heartbeat(agent_id: &str) -> Result<HeartbeatOutcome, String> {
714 with_registry(|reg| {
715 let record = reg
716 .get_mut(agent_id)
717 .ok_or_else(|| format!("agent '{agent_id}' is not registered"))?;
718 if record.status == AgentStatus::Decommissioned {
719 return Err(format!("agent '{agent_id}' is decommissioned"));
720 }
721 let stored_drift = record
722 .attestation
723 .as_ref()
724 .and_then(|attestation| attestation.drift.clone())
725 .map(validate_drift_mark)
726 .transpose()?;
727 let recovered_drift = match drift_from_audit(agent_id) {
733 Ok(drift) => drift,
734 Err(error)
735 if record.attestation.is_none()
736 && record.last_heartbeat.is_none()
737 && error == "audit trail unavailable" =>
738 {
739 None
740 }
741 Err(error) => return Err(error),
742 };
743 let mut fresh = attest(&record.role);
744 let observed = record.attestation.as_ref().and_then(|previous| {
745 let dimensions = diff_attestation(previous, &fresh);
746 dimensions
747 .any()
748 .then(|| (dimensions, drift_evidence(previous, &fresh, dimensions)))
749 });
750
751 match &observed {
752 Some((dimensions, evidence)) => {
753 let observation_id = audit_drift(agent_id, &record.role, evidence)?;
754 fresh.drift = Some(DriftMark {
755 detected_at: fresh.attested_at.clone(),
756 binary: dimensions.binary,
757 config: dimensions.config,
758 evidence: format!("{evidence} observation={observation_id}"),
759 });
760 }
761 None => {
763 fresh.drift = recovered_drift.or(stored_drift);
764 }
765 }
766
767 record.last_heartbeat = Some(fresh.attested_at.clone());
768 let outcome = HeartbeatOutcome {
769 drift: fresh.drift.clone(),
770 newly_observed: observed.is_some(),
771 };
772 record.attestation = Some(fresh);
773 Ok(outcome)
774 })
775}
776
777pub fn suspend(agent_id: &str, reason: &str) -> Result<(), String> {
778 let role = transition(agent_id, AgentStatus::Suspended, Some(reason.to_string()))?;
779 audit(
780 AuditEventType::AgentSuspended,
781 agent_id,
782 &role,
783 Some(reason.to_string()),
784 );
785 Ok(())
786}
787
788pub fn resume(agent_id: &str) -> Result<(), String> {
795 let role = transition(agent_id, AgentStatus::Active, None)?;
796 audit(AuditEventType::AgentResumed, agent_id, &role, None);
797 Ok(())
798}
799
800pub fn acknowledge_drift(
819 agent_id: &str,
820 observed_evidence: &str,
821) -> Result<DriftAcknowledgement, String> {
822 let observed = observed_evidence.to_string();
823 with_registry(|reg| {
824 let record = reg
825 .get_mut(agent_id)
826 .ok_or_else(|| format!("agent '{agent_id}' is not registered"))?;
827 if record.status == AgentStatus::Decommissioned {
828 return Err(format!(
829 "agent '{agent_id}' is decommissioned — identities are never reactivated"
830 ));
831 }
832 let role = record.role.clone();
833 let mark = drift_from_audit(agent_id)?.ok_or_else(|| {
834 format!("agent '{agent_id}' has no audited unacknowledged attestation drift")
835 })?;
836 if mark.evidence != observed {
837 return Err(format!(
838 "acknowledgement does not match the drift on record — \
839 you acknowledged: {observed} — current: {} (detected at {}). \
840 Re-review and acknowledge the current evidence.",
841 mark.evidence, mark.detected_at
842 ));
843 }
844
845 audit_drift_ack(agent_id, &role, &mark)?;
846 if let Some(attestation) = record.attestation.as_mut() {
847 attestation.drift = None;
848 }
849 Ok(DriftAcknowledgement {
850 agent_id: agent_id.to_string(),
851 evidence: mark.evidence,
852 detected_at: mark.detected_at,
853 acknowledged_at: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
854 })
855 })
856}
857
858pub fn decommission(agent_id: &str) -> Result<(), String> {
861 let role = with_registry(|reg| {
862 let record = reg
863 .get_mut(agent_id)
864 .ok_or_else(|| format!("agent '{agent_id}' is not registered"))?;
865 record.status = AgentStatus::Decommissioned;
866 record.decommissioned_at = Some(lean_ctx_time::UtcDateTime::now().to_rfc3339());
867 Ok(record.role.clone())
868 })?;
869 audit(
870 AuditEventType::AgentDecommissioned,
871 agent_id,
872 &role,
873 Some("audit-closing entry".to_string()),
874 );
875 Ok(())
876}
877
878fn transition(agent_id: &str, to: AgentStatus, reason: Option<String>) -> Result<String, String> {
879 with_registry(|reg| {
880 let record = reg
881 .get_mut(agent_id)
882 .ok_or_else(|| format!("agent '{agent_id}' is not registered"))?;
883 if record.status == AgentStatus::Decommissioned {
884 return Err(format!(
885 "agent '{agent_id}' is decommissioned — identities are never reactivated"
886 ));
887 }
888 record.status = to;
889 record.suspended_reason = reason;
890 Ok(record.role.clone())
891 })
892}
893
894pub fn suspend_agents_for_owner(owner: &str, reason: &str) -> Result<Vec<String>, String> {
897 let suspended = with_registry(|reg| {
898 let mut hit = Vec::new();
899 for record in reg.values_mut() {
900 if record.owner == owner && record.status == AgentStatus::Active {
901 record.status = AgentStatus::Suspended;
902 record.suspended_reason = Some(reason.to_string());
903 hit.push((record.agent_id.clone(), record.role.clone()));
904 }
905 }
906 Ok(hit)
907 })?;
908 for (agent_id, role) in &suspended {
909 audit(
910 AuditEventType::AgentSuspended,
911 agent_id,
912 role,
913 Some(format!("owner offboarded: {reason}")),
914 );
915 }
916 Ok(suspended.into_iter().map(|(id, _)| id).collect())
917}
918
919pub fn check(agent_id: &str) -> IdentityCheck {
926 check_with_policy(agent_id, DriftPolicy::from_env())
927}
928
929pub(crate) fn check_with_policy(agent_id: &str, policy: DriftPolicy) -> IdentityCheck {
933 let record = match try_get(agent_id) {
934 Ok(record) => record,
935 Err(error) => {
936 return IdentityCheck {
937 agent_id: agent_id.to_string(),
938 registered: false,
939 allowed: false,
940 status: None,
941 drifted: false,
942 detail: format!("denied, registry unavailable: {error}"),
943 };
944 }
945 };
946 match record {
947 None => IdentityCheck {
948 agent_id: agent_id.to_string(),
949 registered: false,
950 allowed: false,
951 status: None,
952 drifted: false,
953 detail: "not registered — register with `lean-ctx agent register`".to_string(),
954 },
955 Some(record) => {
956 let stored_drift = record
957 .attestation
958 .as_ref()
959 .and_then(|attestation| attestation.drift.clone())
960 .map(validate_drift_mark)
961 .transpose();
962 let (drift, audit_error) = match drift_from_audit(agent_id) {
963 Ok(audit_drift) => match stored_drift {
964 Ok(stored) => (audit_drift.or(stored), None),
965 Err(error) => (audit_drift, Some(error)),
966 },
967 Err(error) => (stored_drift.unwrap_or(None), Some(error)),
968 };
969 let blocked_by_drift = policy.block_on_drift && drift.is_some();
970 let allowed =
971 record.status == AgentStatus::Active && !blocked_by_drift && audit_error.is_none();
972 IdentityCheck {
973 agent_id: agent_id.to_string(),
974 registered: true,
975 allowed,
976 status: Some(record.status),
977 drifted: drift.is_some() || audit_error.is_some(),
979 detail: match record.status {
980 AgentStatus::Active => match (drift.as_ref(), audit_error.as_ref()) {
981 (_, Some(error)) => {
982 format!("denied, audit state unavailable: {error}")
983 }
984 (Some(mark), _) if policy.block_on_drift => {
985 format!("denied, unacknowledged {}", mark.evidence)
986 }
987 (Some(mark), _) => format!(
988 "active, owner {} (advisory: unacknowledged {})",
989 record.owner, mark.evidence
990 ),
991 (None, None) => format!("active, owner {}", record.owner),
992 },
993 AgentStatus::Suspended => format!(
994 "suspended: {}",
995 record.suspended_reason.as_deref().unwrap_or("no reason")
996 ),
997 AgentStatus::Decommissioned => "decommissioned".to_string(),
998 },
999 }
1000 }
1001 }
1002}
1003
1004pub fn spiffe_id(record: &AgentRecord, trust_domain: &str) -> String {
1007 format!(
1008 "spiffe://{}/agent/{}/{}",
1009 trust_domain.trim_matches('/'),
1010 record.role,
1011 record.agent_id
1012 )
1013}
1014
1015#[cfg(test)]
1016#[path = "agent_registry_tests.rs"]
1017mod tests;
1018
1019#[cfg(test)]
1021#[path = "agent_registry_drift_tests.rs"]
1022mod drift_tests;