agentmux_srv_core/backend/
agent_grants.rs1use std::path::{Path, PathBuf};
16use std::sync::Mutex;
17
18use serde::{Deserialize, Serialize};
19
20const FILE_NAME: &str = "agent-grants.json";
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum Topic {
26 Spawn,
28 Google,
30 Memory,
32}
33
34#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
37struct Grants {
38 #[serde(default)]
39 always: Vec<serde_json::Value>,
40 #[serde(flatten)]
41 other: serde_json::Map<String, serde_json::Value>,
42}
43
44impl Grants {
45 fn known(&self) -> impl Iterator<Item = Grant> + '_ {
47 self.always.iter().filter_map(|v| serde_json::from_value::<Grant>(v.clone()).ok())
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52struct Grant {
53 topic: Topic,
54 agent: String,
55}
56
57static LOCK: Mutex<()> = Mutex::new(());
59
60fn path_in(config_home: &Path) -> PathBuf {
61 config_home.join(FILE_NAME)
62}
63
64fn read(path: &Path) -> Option<Grants> {
67 match std::fs::read_to_string(path) {
68 Ok(text) => serde_json::from_str(&text).ok(),
69 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(Grants::default()),
70 Err(_) => None,
71 }
72}
73
74fn unreadable() -> std::io::Error {
75 std::io::Error::new(std::io::ErrorKind::InvalidData, "agent-grants.json cannot be read, so it is left as it is")
76}
77
78fn write(config_home: &Path, grants: &Grants) -> std::io::Result<()> {
79 std::fs::create_dir_all(config_home)?;
80 let path = path_in(config_home);
81 let tmp = path.with_extension("json.tmp");
82 std::fs::write(&tmp, serde_json::to_vec_pretty(grants).unwrap_or_default())?;
83 std::fs::rename(&tmp, &path)
84}
85
86pub fn allowed_in(config_home: &Path, topic: Topic, agent: &str) -> bool {
88 let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
89 read(&path_in(config_home)).is_some_and(|g| g.known().any(|g| g.topic == topic && g.agent.eq_ignore_ascii_case(agent)))
90}
91
92pub fn allow_in(config_home: &Path, topic: Topic, agent: &str) -> std::io::Result<()> {
94 let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
95 let mut grants = read(&path_in(config_home)).ok_or_else(unreadable)?;
96 let grant = Grant { topic, agent: agent.to_ascii_lowercase() };
97 if grants.known().any(|g| g == grant) {
98 return Ok(());
99 }
100 grants.always.push(serde_json::to_value(&grant).unwrap_or_default());
101 write(config_home, &grants)
102}
103
104pub fn revoke_in(config_home: &Path, topic: Topic, agent: &str) -> std::io::Result<bool> {
106 let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
107 let mut grants = read(&path_in(config_home)).ok_or_else(unreadable)?;
108 let before = grants.always.len();
109 grants.always.retain(|v| !serde_json::from_value::<Grant>(v.clone()).is_ok_and(|g| g.topic == topic && g.agent.eq_ignore_ascii_case(agent)));
111 if grants.always.len() == before {
112 return Ok(false);
113 }
114 write(config_home, &grants)?;
115 Ok(true)
116}
117
118pub fn all_in(config_home: &Path, topic: Topic) -> Vec<String> {
120 let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
121 read(&path_in(config_home)).map(|g| g.known().filter(|g| g.topic == topic).map(|g| g.agent).collect()).unwrap_or_default()
122}
123
124fn home() -> PathBuf {
126 #[cfg(any(test, feature = "test-support"))]
127 {
128 static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
129 DIR.get_or_init(|| tempfile::tempdir().expect("a temporary config dir")).path().to_path_buf()
130 }
131 #[cfg(not(any(test, feature = "test-support")))]
132 crate::backend::base::get_mux_config_dir()
133}
134
135pub fn allowed(topic: Topic, agent: &str) -> bool {
137 allowed_in(&home(), topic, agent)
138}
139
140pub fn allow(topic: Topic, agent: &str) -> std::io::Result<()> {
142 allow_in(&home(), topic, agent)
143}
144
145pub fn revoke(topic: Topic, agent: &str) -> std::io::Result<bool> {
147 revoke_in(&home(), topic, agent)
148}
149
150pub fn all(topic: Topic) -> Vec<String> {
152 all_in(&home(), topic)
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[test]
160 fn always_is_per_agent_and_topic() {
161 let dir = tempfile::tempdir().unwrap();
162 let home = dir.path();
163 assert!(!allowed_in(home, Topic::Spawn, "korp"), "nothing until the person says so");
164 allow_in(home, Topic::Spawn, "Korp").unwrap();
165 allow_in(home, Topic::Spawn, "korp").unwrap();
166 assert!(allowed_in(home, Topic::Spawn, "KORP"), "agent ids ignore case");
167 assert!(!allowed_in(home, Topic::Google, "korp"), "another topic asks");
168 assert!(!allowed_in(home, Topic::Spawn, "agentx"), "another agent asks");
169 assert_eq!(std::fs::read_to_string(home.join(FILE_NAME)).unwrap().matches("korp").count(), 1, "stored once");
170 assert_eq!(all_in(home, Topic::Spawn), vec!["korp".to_string()]);
171 }
172
173 #[test]
174 fn a_grant_for_a_topic_this_build_does_not_know_and_any_other_key_survive_a_change() {
175 let dir = tempfile::tempdir().unwrap();
176 let home = dir.path();
177 std::fs::write(
178 home.join(FILE_NAME),
179 r#"{ "always": [ { "topic": "browser", "agent": "korp", "scope": "all" }, { "topic": "spawn", "agent": "agentx" } ], "added_later": { "x": 1 } }"#,
180 )
181 .unwrap();
182 assert!(allowed_in(home, Topic::Spawn, "agentx"));
183 allow_in(home, Topic::Google, "korp").unwrap();
184 assert!(revoke_in(home, Topic::Spawn, "agentx").unwrap());
185 let after: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(home.join(FILE_NAME)).unwrap()).unwrap();
186 assert_eq!(after["added_later"], serde_json::json!({ "x": 1 }), "a key this build does not know is kept");
187 let kept = after["always"].as_array().unwrap();
188 assert!(kept.contains(&serde_json::json!({ "topic": "browser", "agent": "korp", "scope": "all" })), "a grant of an unknown topic is kept as it was: {kept:?}");
189 assert!(kept.contains(&serde_json::json!({ "topic": "google", "agent": "korp" })));
190 assert_eq!(kept.len(), 2, "the revoked one is gone: {kept:?}");
191 }
192
193 #[test]
194 fn a_file_that_cannot_be_read_is_not_replaced_by_a_save_and_grants_nothing() {
195 let dir = tempfile::tempdir().unwrap();
196 let home = dir.path();
197 std::fs::write(home.join(FILE_NAME), "{ \"always\": [ { \"topic\": \"spawn\", ").unwrap();
198 assert!(!allowed_in(home, Topic::Spawn, "korp"), "an unreadable file grants nothing");
199 assert!(allow_in(home, Topic::Spawn, "korp").is_err());
200 assert!(revoke_in(home, Topic::Spawn, "korp").is_err());
201 assert_eq!(std::fs::read_to_string(home.join(FILE_NAME)).unwrap(), "{ \"always\": [ { \"topic\": \"spawn\", ", "left as it was");
202 }
203
204 #[test]
205 fn revoking_asks_again_and_leaves_the_others() {
206 let dir = tempfile::tempdir().unwrap();
207 let home = dir.path();
208 allow_in(home, Topic::Spawn, "korp").unwrap();
209 allow_in(home, Topic::Google, "korp").unwrap();
210 allow_in(home, Topic::Spawn, "agentx").unwrap();
211 assert!(revoke_in(home, Topic::Spawn, "KORP").unwrap());
212 assert!(!allowed_in(home, Topic::Spawn, "korp"));
213 assert!(allowed_in(home, Topic::Google, "korp"), "another topic keeps its grant");
214 assert!(allowed_in(home, Topic::Spawn, "agentx"), "another agent keeps its grant");
215 assert!(!revoke_in(home, Topic::Spawn, "korp").unwrap(), "nothing left to revoke");
216 }
217
218 #[test]
219 fn an_unreadable_file_grants_nothing() {
220 let dir = tempfile::tempdir().unwrap();
221 std::fs::write(dir.path().join(FILE_NAME), "not json").unwrap();
222 assert!(!allowed_in(dir.path(), Topic::Spawn, "korp"));
223 }
224}