1use serde::{Deserialize, Serialize};
19use std::collections::HashMap;
20use std::path::{Path, PathBuf};
21
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
23pub struct ScopeKey {
24 pub agent_id: String,
25 pub tool_name: String,
26 pub input_schema_hash: String,
28}
29
30#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
31pub enum GrantDecision {
32 Allow,
33 Deny,
34}
35
36#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
37pub enum GrantSource {
38 Ui,
39 Headless,
40 Default,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct Grant {
45 pub scope_key: ScopeKey,
46 pub decision: GrantDecision,
47 pub granted_at: chrono::DateTime<chrono::Utc>,
48 pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
49 pub last_used_at: Option<chrono::DateTime<chrono::Utc>>,
50 pub source: GrantSource,
51 pub source_audit_id: Option<String>,
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
55#[serde(tag = "type", rename_all = "snake_case")]
56pub enum AuditEvent {
57 AskedUser {
58 ts: chrono::DateTime<chrono::Utc>,
59 scope_key: ScopeKey,
60 prompt_hash: String,
61 ttl_ms: u64,
62 },
63 GrantWritten {
64 ts: chrono::DateTime<chrono::Utc>,
65 scope_key: ScopeKey,
66 decision: GrantDecision,
67 source: GrantSource,
68 },
69 GrantUsed {
70 ts: chrono::DateTime<chrono::Utc>,
71 scope_key: ScopeKey,
72 },
73 HeadlessDenied {
74 ts: chrono::DateTime<chrono::Utc>,
75 scope_key: ScopeKey,
76 },
77 Revoked {
78 ts: chrono::DateTime<chrono::Utc>,
79 scope_key: ScopeKey,
80 },
81 StartupOverrideApplied {
83 ts: chrono::DateTime<chrono::Utc>,
84 nonce: String,
85 flags: crate::agent::OverrideFlags,
86 confirmed_by: crate::startup_override::ConfirmedBy,
87 #[serde(default, skip_serializing_if = "Vec::is_empty")]
91 changes: Vec<String>,
92 },
93 StartupOverrideRejected {
96 ts: chrono::DateTime<chrono::Utc>,
97 nonce: Option<String>,
98 reason: String,
99 },
100 StartupOverrideNotReapplied { ts: chrono::DateTime<chrono::Utc> },
103 StartupOverrideRefused {
108 ts: chrono::DateTime<chrono::Utc>,
109 reason: String,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
111 window: Option<String>,
112 },
113 StartupOverrideDeclined {
115 ts: chrono::DateTime<chrono::Utc>,
116 flags: crate::agent::OverrideFlags,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
118 window: Option<String>,
119 },
120 StartupOverrideIssued {
122 ts: chrono::DateTime<chrono::Utc>,
123 nonce: String,
124 flags: crate::agent::OverrideFlags,
125 issued_by: crate::startup_override::IssuedBy,
126 confirmed_by: crate::startup_override::ConfirmedBy,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
128 window: Option<String>,
129 },
130 StartupOverrideDiscarded {
132 ts: chrono::DateTime<chrono::Utc>,
133 nonce: Option<String>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
135 window: Option<String>,
136 },
137 StartupOverrideWithdrawn {
139 ts: chrono::DateTime<chrono::Utc>,
140 nonce: String,
141 reason: String,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
143 window: Option<String>,
144 },
145 StartupOverrideUnacknowledged {
147 ts: chrono::DateTime<chrono::Utc>,
148 nonce: String,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 window: Option<String>,
151 },
152 StartupOverrideWithdrawFailed {
154 ts: chrono::DateTime<chrono::Utc>,
155 nonce: Option<String>,
156 error: String,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
158 window: Option<String>,
159 },
160}
161
162#[derive(Debug, Default, Serialize, Deserialize)]
163pub struct GrantsFile {
164 pub version: u32,
165 pub grants: Vec<Grant>,
166}
167
168pub struct GrantStore {
171 grants_path: PathBuf,
172 audit_path: PathBuf,
173 cache: HashMap<ScopeKey, Grant>,
174}
175
176impl GrantStore {
177 pub fn new<P: AsRef<Path>>(agent_dir: P) -> Self {
180 let dir = agent_dir.as_ref().join("permissions");
181 Self {
182 grants_path: dir.join("grants.yaml"),
183 audit_path: dir.join("audit.jsonl"),
184 cache: HashMap::new(),
185 }
186 }
187
188 pub fn load(&mut self) -> std::io::Result<()> {
189 if !self.grants_path.exists() {
190 return Ok(());
191 }
192 let bytes = std::fs::read(&self.grants_path)?;
193 let file: GrantsFile = serde_yaml_ng::from_slice(&bytes)
194 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
195 self.cache.clear();
196 for g in file.grants {
197 self.cache.insert(g.scope_key.clone(), g);
198 }
199 Ok(())
200 }
201
202 pub fn lookup(
205 &self,
206 key: &ScopeKey,
207 now: chrono::DateTime<chrono::Utc>,
208 ) -> Option<GrantDecision> {
209 self.cache.get(key).and_then(|g| {
210 if let Some(expires) = g.expires_at
211 && now > expires
212 {
213 return None;
214 }
215 Some(g.decision)
216 })
217 }
218
219 pub fn insert(&mut self, grant: Grant) -> std::io::Result<()> {
220 self.cache.insert(grant.scope_key.clone(), grant);
221 self.persist()
222 }
223
224 pub fn revoke(
225 &mut self,
226 key: &ScopeKey,
227 now: chrono::DateTime<chrono::Utc>,
228 ) -> std::io::Result<()> {
229 if self.cache.remove(key).is_none() {
230 return Ok(()); }
232 self.append_audit(&AuditEvent::Revoked {
233 ts: now,
234 scope_key: key.clone(),
235 })?;
236 self.persist()
237 }
238
239 pub fn append_audit(&self, event: &AuditEvent) -> std::io::Result<()> {
240 if let Some(parent) = self.audit_path.parent() {
241 std::fs::create_dir_all(parent)?;
242 }
243 let mut line = serde_json::to_string(event)
244 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
245 line.push('\n');
246 use std::io::Write;
247 let mut f = std::fs::OpenOptions::new()
248 .create(true)
249 .append(true)
250 .open(&self.audit_path)?;
251 f.write_all(line.as_bytes())?;
252 Ok(())
253 }
254
255 fn persist(&self) -> std::io::Result<()> {
256 if let Some(parent) = self.grants_path.parent() {
257 std::fs::create_dir_all(parent)?;
258 }
259 let file = GrantsFile {
260 version: 1,
261 grants: self.cache.values().cloned().collect(),
262 };
263 let bytes = serde_yaml_ng::to_string(&file)
264 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
265 let tmp = self.grants_path.with_extension("yaml.tmp");
266 std::fs::write(&tmp, bytes)?;
267 #[cfg(unix)]
268 {
269 use std::os::unix::fs::PermissionsExt;
270 let perms = std::fs::Permissions::from_mode(0o600);
271 std::fs::set_permissions(&tmp, perms)?;
272 }
273 std::fs::rename(&tmp, &self.grants_path)?;
274 Ok(())
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use tempfile::tempdir;
282
283 fn key(tool: &str) -> ScopeKey {
284 ScopeKey {
285 agent_id: "coach".into(),
286 tool_name: tool.into(),
287 input_schema_hash: "sha".into(),
288 }
289 }
290
291 #[test]
292 fn insert_and_lookup_round_trip() {
293 let dir = tempdir().unwrap();
294 let mut store = GrantStore::new(dir.path());
295 let now = chrono::Utc::now();
296 let k = key("fs.write");
297 store
298 .insert(Grant {
299 scope_key: k.clone(),
300 decision: GrantDecision::Allow,
301 granted_at: now,
302 expires_at: Some(now + chrono::Duration::days(30)),
303 last_used_at: None,
304 source: GrantSource::Ui,
305 source_audit_id: None,
306 })
307 .unwrap();
308
309 let mut store2 = GrantStore::new(dir.path());
310 store2.load().unwrap();
311 assert_eq!(store2.lookup(&k, now), Some(GrantDecision::Allow));
312 }
313
314 #[test]
315 fn lookup_returns_none_for_expired_grant() {
316 let dir = tempdir().unwrap();
317 let mut store = GrantStore::new(dir.path());
318 let now = chrono::Utc::now();
319 let k = key("fs.write");
320 store
321 .insert(Grant {
322 scope_key: k.clone(),
323 decision: GrantDecision::Allow,
324 granted_at: now,
325 expires_at: Some(now - chrono::Duration::seconds(1)),
326 last_used_at: None,
327 source: GrantSource::Ui,
328 source_audit_id: None,
329 })
330 .unwrap();
331 assert_eq!(store.lookup(&k, now), None);
332 }
333
334 #[test]
335 fn audit_log_appends_and_persists() {
336 let dir = tempdir().unwrap();
337 let store = GrantStore::new(dir.path());
338 let now = chrono::Utc::now();
339 store
340 .append_audit(&AuditEvent::AskedUser {
341 ts: now,
342 scope_key: key("bash"),
343 prompt_hash: "abc".into(),
344 ttl_ms: 120_000,
345 })
346 .unwrap();
347 store
348 .append_audit(&AuditEvent::HeadlessDenied {
349 ts: now,
350 scope_key: key("net.connect"),
351 })
352 .unwrap();
353
354 let body = std::fs::read_to_string(dir.path().join("permissions/audit.jsonl")).unwrap();
355 let lines: Vec<_> = body.lines().collect();
356 assert_eq!(lines.len(), 2);
357 assert!(lines[0].contains("asked_user"));
358 assert!(lines[1].contains("headless_denied"));
359 }
360
361 #[test]
362 fn revoke_drops_grant_and_writes_audit() {
363 let dir = tempdir().unwrap();
364 let mut store = GrantStore::new(dir.path());
365 let now = chrono::Utc::now();
366 let k = key("fs.write");
367 store
368 .insert(Grant {
369 scope_key: k.clone(),
370 decision: GrantDecision::Allow,
371 granted_at: now,
372 expires_at: None,
373 last_used_at: None,
374 source: GrantSource::Ui,
375 source_audit_id: None,
376 })
377 .unwrap();
378 store.revoke(&k, now).unwrap();
379 assert_eq!(store.lookup(&k, now), None);
380 let body = std::fs::read_to_string(dir.path().join("permissions/audit.jsonl")).unwrap();
381 assert!(body.contains("revoked"));
382 }
383}
384
385#[cfg(test)]
386#[path = "permissions_override_audit_tests.rs"]
387mod override_audit_tests;