1use std::collections::BTreeMap;
23use std::path::{Path, PathBuf};
24
25use serde::{Deserialize, Serialize};
26use sha2::{Digest, Sha256};
27
28use super::policy::{Grant, Hold, Mint, Policy, Tier};
29
30const VERSION: u32 = 1;
31const KEEP_CHANGES: usize = 200;
33pub const BASELINE_BY: &str = "baseline";
35pub const MAX_REASON: usize = 300;
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Summary {
41 pub tier: String,
42 pub agents: Vec<String>,
44 pub disabled: bool,
45 pub needs_reason: bool,
46 pub max_seconds: u64,
47 pub max_mints_per_hour: u32,
48 pub recipe: String,
51}
52
53impl Summary {
54 pub fn of(g: &Grant) -> Summary {
55 let mut agents = g.agents.clone();
56 agents.sort();
57 agents.dedup();
58 let mut hash = Sha256::new();
59 match &g.mint {
60 Mint::HostProfile { profile } => {
61 hash.update(b"profile\0");
62 hash.update(profile.as_bytes());
63 }
64 Mint::Command { argv } => {
65 hash.update(b"command\0");
66 for arg in argv {
67 hash.update(arg.as_bytes());
68 hash.update([0u8]);
69 }
70 }
71 }
72 if let Some(t) = &g.caller_tag {
75 hash.update(b"caller_tag\0");
76 hash.update(t.key.as_bytes());
77 hash.update([0u8]);
78 hash.update(t.prefix.as_bytes());
79 }
80 Summary {
81 tier: g.tier.as_str().to_string(),
82 agents,
83 disabled: g.disabled,
84 needs_reason: g.needs_reason,
85 max_seconds: g.max_seconds,
86 max_mints_per_hour: g.max_mints_per_hour,
87 recipe: hex::encode(&hash.finalize()[..8]),
88 }
89 }
90
91 fn is_write(&self) -> bool {
92 self.tier == Tier::Write.as_str()
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum Delta {
99 Same,
100 Narrower,
101 Wider(Vec<&'static str>),
103}
104
105pub fn compare(acknowledged: &Summary, now: &Summary) -> Delta {
106 if acknowledged == now {
107 return Delta::Same;
108 }
109 let mut wider = Vec::new();
110 if now.is_write() && !acknowledged.is_write() {
111 wider.push("tier");
112 }
113 let everyone = |s: &Summary| s.agents.iter().any(|a| a == "*");
114 if !everyone(acknowledged) && (everyone(now) || now.agents.iter().any(|a| !acknowledged.agents.contains(a))) {
115 wider.push("agents");
116 }
117 if now.recipe != acknowledged.recipe {
118 wider.push("recipe");
119 }
120 if acknowledged.disabled && !now.disabled {
121 wider.push("switched on");
122 }
123 if acknowledged.needs_reason && !now.needs_reason {
124 wider.push("no reason needed");
125 }
126 if now.max_seconds > acknowledged.max_seconds {
127 wider.push("session length");
128 }
129 if now.max_mints_per_hour > acknowledged.max_mints_per_hour {
130 wider.push("hourly cap");
131 }
132 if wider.is_empty() {
133 Delta::Narrower
134 } else {
135 Delta::Wider(wider)
136 }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum State {
142 Honoured,
143 Held,
145 Refused,
147}
148
149impl State {
150 pub fn as_str(self) -> &'static str {
151 match self {
152 State::Honoured => "honoured",
153 State::Held => "held",
154 State::Refused => "refused",
155 }
156 }
157}
158
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct Entry {
161 pub current: Summary,
163 pub acknowledged: Option<Summary>,
165 pub refused: Option<Summary>,
167 pub added_ms: i64,
168 pub added_change: String,
170 pub change: String,
171 pub allowed_by: Option<String>,
172 pub allowed_reason: Option<String>,
173 pub allowed_ms: Option<i64>,
174}
175
176impl Entry {
177 pub fn state(&self) -> State {
178 if self.acknowledged.as_ref() == Some(&self.current) {
179 State::Honoured
180 } else if self.refused.as_ref() == Some(&self.current) {
181 State::Refused
182 } else {
183 State::Held
184 }
185 }
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
190pub struct ChangeRow {
191 pub id: String,
192 pub at_ms: i64,
193 pub kind: String,
194 pub grant: Option<String>,
195 pub text: String,
196 pub by: Option<String>,
197}
198
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200pub struct Record {
201 pub version: u32,
202 pub file_sha256: String,
204 pub default_grant: Option<String>,
205 pub grants: BTreeMap<String, Entry>,
206 pub changes: Vec<ChangeRow>,
207}
208
209#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct Event {
212 pub id: String,
213 pub kind: &'static str,
214 pub grant: Option<String>,
215 pub text: String,
216 pub by: Option<String>,
217 pub held: bool,
219}
220
221pub fn sha256_hex(text: &str) -> String {
222 hex::encode(Sha256::digest(text.as_bytes()))
223}
224
225fn agents_text(s: &Summary) -> String {
226 match s.agents.as_slice() {
227 [] => "no agent".to_string(),
228 [one] if one == "*" => "every agent".to_string(),
229 [one] => format!("agent {one}"),
230 many => format!("{} agents ({})", many.len(), many.join(", ")),
231 }
232}
233
234struct Log {
236 now_ms: i64,
237 seq: usize,
238 events: Vec<Event>,
239}
240
241impl Log {
242 fn push(&mut self, kind: &'static str, grant: Option<&str>, text: String, held: bool) -> String {
244 self.seq += 1;
245 let id = format!("c{:x}-{}", self.now_ms, self.seq);
246 self.events.push(Event { id: id.clone(), kind, grant: grant.map(str::to_string), text, by: None, held });
247 id
248 }
249}
250
251pub fn sync(old: Option<Record>, policy: &Policy, file_sha256: &str, now_ms: i64) -> (Record, Vec<Event>) {
254 let mut log = Log { now_ms, seq: 0, events: Vec::new() };
255 let Some(mut rec) = old else {
256 let rec = baseline(policy, file_sha256, &mut log);
257 return finish(rec, log.events, now_ms);
258 };
259 if rec.file_sha256 == file_sha256 {
260 return (rec, log.events);
261 }
262 rec.file_sha256 = file_sha256.to_string();
263 for (name, g) in &policy.grants {
264 sync_grant(&mut rec, name, Summary::of(g), &mut log);
265 }
266 let gone: Vec<String> = rec.grants.keys().filter(|n| !policy.grants.contains_key(*n)).cloned().collect();
267 for name in gone {
268 rec.grants.remove(&name);
269 log.push("removed", Some(&name), format!("grant '{name}' was removed: it stopped working at once"), false);
270 }
271 if rec.default_grant != policy.default_grant {
272 rec.default_grant = policy.default_grant.clone();
273 let text = match &rec.default_grant {
274 Some(d) => format!("the default grant is now '{d}'"),
275 None => "the grants file no longer names a default grant".to_string(),
276 };
277 log.push("default", None, text, false);
278 }
279 finish(rec, log.events, now_ms)
280}
281
282fn baseline(policy: &Policy, file_sha256: &str, log: &mut Log) -> Record {
284 let mut grants = BTreeMap::new();
285 let mut writes = 0;
286 for (name, g) in &policy.grants {
287 let s = Summary::of(g);
288 writes += usize::from(s.is_write());
289 let entry = Entry {
290 current: s.clone(),
291 acknowledged: Some(s),
292 refused: None,
293 added_ms: log.now_ms,
294 added_change: String::new(),
295 change: String::new(),
296 allowed_by: Some(BASELINE_BY.to_string()),
297 allowed_reason: None,
298 allowed_ms: Some(log.now_ms),
299 };
300 grants.insert(name.clone(), entry);
301 }
302 let text = format!("no earlier record of the grants file: this version is the baseline, {} grants ({writes} write) counted as allowed", grants.len());
303 let id = log.push("baseline", None, text, false);
304 for e in grants.values_mut() {
305 e.added_change = id.clone();
306 e.change = id.clone();
307 }
308 Record { version: VERSION, file_sha256: file_sha256.to_string(), default_grant: policy.default_grant.clone(), grants, changes: Vec::new() }
309}
310
311fn sync_grant(rec: &mut Record, name: &str, now: Summary, log: &mut Log) {
313 let Some(entry) = rec.grants.get_mut(name) else {
314 add_grant(rec, name, now, log);
315 return;
316 };
317 if entry.current == now {
318 return;
319 }
320 let delta = entry.acknowledged.as_ref().map(|a| compare(a, &now));
321 let id = match delta {
322 Some(Delta::Same) => {
323 entry.refused = None;
324 log.push("reverted", Some(name), format!("grant '{name}' is back to what was allowed"), false)
325 }
326 Some(Delta::Narrower) => {
327 entry.acknowledged = Some(now.clone());
328 entry.refused = None;
329 entry.allowed_by = Some("narrowed".to_string());
330 entry.allowed_reason = None;
331 entry.allowed_ms = Some(log.now_ms);
332 let text = format!("grant '{name}' is narrower now ({} tier, {}): in force at once", now.tier, agents_text(&now));
333 log.push("narrowed", Some(name), text, false)
334 }
335 Some(Delta::Wider(dims)) => {
336 let text = format!("grant '{name}' is wider than what was allowed ({}): held until a native agent or a person allows it", dims.join(", "));
337 log.push("widened", Some(name), text, true)
338 }
339 None => {
341 let text = format!("grant '{name}' changed again before it was allowed ({} tier, {}): still held", now.tier, agents_text(&now));
342 log.push("widened", Some(name), text, true)
343 }
344 };
345 entry.current = now;
346 entry.change = id;
347}
348
349fn add_grant(rec: &mut Record, name: &str, now: Summary, log: &mut Log) {
352 let inert = now.disabled;
353 let tail = if inert { " (switched off)" } else { "; held until a native agent or a person allows it" };
354 let id = log.push("added", Some(name), format!("added {} grant '{name}' for {}{tail}", now.tier, agents_text(&now)), !inert);
355 let entry = Entry {
356 current: now.clone(),
357 acknowledged: inert.then(|| now.clone()),
358 refused: None,
359 added_ms: log.now_ms,
360 added_change: id.clone(),
361 change: id,
362 allowed_by: inert.then(|| "switched off".to_string()),
363 allowed_reason: None,
364 allowed_ms: inert.then_some(log.now_ms),
365 };
366 rec.grants.insert(name.to_string(), entry);
367}
368
369fn finish(mut rec: Record, events: Vec<Event>, now_ms: i64) -> (Record, Vec<Event>) {
370 for e in &events {
371 rec.changes.push(ChangeRow { id: e.id.clone(), at_ms: now_ms, kind: e.kind.to_string(), grant: e.grant.clone(), text: e.text.clone(), by: e.by.clone() });
372 }
373 let extra = rec.changes.len().saturating_sub(KEEP_CHANGES);
374 rec.changes.drain(..extra);
375 (rec, events)
376}
377
378pub fn effective(policy: &Policy, rec: &Record) -> Policy {
380 let mut out = policy.clone();
381 for (name, g) in out.grants.iter_mut() {
382 g.hold = match rec.grants.get(name).map(Entry::state) {
383 Some(State::Honoured) => None,
384 Some(State::Refused) => Some(Hold::Refused),
385 Some(State::Held) | None => Some(Hold::Awaiting),
387 };
388 }
389 out
390}
391
392pub fn hold_all(policy: &Policy) -> Policy {
394 let mut out = policy.clone();
395 for g in out.grants.values_mut() {
396 g.hold = Some(Hold::Awaiting);
397 }
398 out
399}
400
401pub struct Decision<'a> {
403 pub grant: &'a str,
404 pub change: &'a str,
406 pub allow: bool,
407 pub by: &'a str,
408 pub reason: &'a str,
409}
410
411pub fn decide(rec: &mut Record, d: &Decision<'_>, now_ms: i64) -> Result<Event, String> {
412 let reason: String = d.reason.chars().filter(|c| !c.is_control()).take(MAX_REASON).collect();
413 let reason = reason.trim().to_string();
414 if reason.is_empty() {
415 return Err("a reason is needed: what the grant is for and why it may be used".to_string());
416 }
417 let entry = rec.grants.get_mut(d.grant).ok_or_else(|| format!("no grant named '{}' in the record", d.grant))?;
418 if entry.change != d.change {
419 return Err(format!("grant '{}' has changed since you read it (now change {}): read the grants again", d.grant, entry.change));
420 }
421 let id = format!("c{now_ms:x}-d");
422 let state = entry.state();
423 if d.allow {
424 if state == State::Honoured {
425 return Err(format!("nothing waits on grant '{}': it is already allowed", d.grant));
426 }
427 entry.acknowledged = Some(entry.current.clone());
428 entry.refused = None;
429 entry.allowed_by = Some(d.by.to_string());
430 entry.allowed_reason = Some(reason.clone());
431 entry.allowed_ms = Some(now_ms);
432 } else {
433 if state == State::Refused {
434 return Err(format!("grant '{}' is already refused", d.grant));
435 }
436 if state == State::Honoured {
437 return Err(format!("grant '{}' is in force, not waiting: remove it from the grants file to stop it", d.grant));
438 }
439 entry.refused = Some(entry.current.clone());
440 }
441 entry.change = id.clone();
442 let (kind, verb) = if d.allow { ("allowed", "allowed") } else { ("refused", "refused") };
443 let event = Event { id, kind, grant: Some(d.grant.to_string()), text: format!("grant '{}' {verb} by {}: {reason}", d.grant, d.by), by: Some(d.by.to_string()), held: false };
444 rec.changes.push(ChangeRow { id: event.id.clone(), at_ms: now_ms, kind: kind.to_string(), grant: event.grant.clone(), text: event.text.clone(), by: event.by.clone() });
445 let extra = rec.changes.len().saturating_sub(KEEP_CHANGES);
446 rec.changes.drain(..extra);
447 Ok(event)
448}
449
450#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
452pub struct GrantView {
453 pub name: String,
454 pub tier: String,
455 pub agents: Vec<String>,
456 pub disabled: bool,
457 pub state: &'static str,
458 pub added_ms: i64,
459 pub added_change: String,
460 pub change: String,
461 pub allowed_by: Option<String>,
462 pub allowed_reason: Option<String>,
463 pub allowed_ms: Option<i64>,
464}
465
466#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
467pub struct View {
468 pub grants: Vec<GrantView>,
469 pub changes: Vec<ChangeRow>,
471}
472
473pub fn view(rec: &Record) -> View {
474 let grants = rec
475 .grants
476 .iter()
477 .map(|(name, e)| GrantView {
478 name: name.clone(),
479 tier: e.current.tier.clone(),
480 agents: e.current.agents.clone(),
481 disabled: e.current.disabled,
482 state: e.state().as_str(),
483 added_ms: e.added_ms,
484 added_change: e.added_change.clone(),
485 change: e.change.clone(),
486 allowed_by: e.allowed_by.clone(),
487 allowed_reason: e.allowed_reason.clone(),
488 allowed_ms: e.allowed_ms,
489 })
490 .collect();
491 View { grants, changes: rec.changes.iter().rev().take(50).cloned().collect() }
492}
493
494pub fn path_beside(policy_file: &Path) -> PathBuf {
496 let stem = policy_file.file_stem().and_then(|s| s.to_str()).unwrap_or("aws-grants");
497 policy_file.with_file_name(format!("{stem}.record.json"))
498}
499
500pub fn read(path: &Path) -> Result<Option<Record>, String> {
502 let text = match std::fs::read_to_string(path) {
503 Ok(t) => t,
504 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
505 Err(e) => return Err(format!("can't read {}: {e}", path.display())),
506 };
507 let rec: Record = serde_json::from_str(&text).map_err(|e| format!("{} doesn't parse: {e}", path.display()))?;
508 if rec.version != VERSION {
509 return Err(format!("{} is version {}: this AgentMux reads version {VERSION}", path.display(), rec.version));
510 }
511 Ok(Some(rec))
512}
513
514pub fn write(path: &Path, rec: &Record) -> Result<(), String> {
516 let text = serde_json::to_string_pretty(rec).map_err(|e| e.to_string())?;
517 let tmp = path.with_extension("json.tmp");
518 std::fs::write(&tmp, text).map_err(|e| format!("can't write {}: {e}", tmp.display()))?;
519 std::fs::rename(&tmp, path).map_err(|e| format!("can't replace {}: {e}", path.display()))
520}
521
522#[cfg(test)]
523#[path = "record_tests.rs"]
524mod tests;