| 1 | use std::fs::{self, OpenOptions}; |
| 2 | use std::io::Write as _; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::sync::Arc; |
| 5 | |
| 6 | use chrono::{DateTime, Duration, Utc}; |
| 7 | use parking_lot::Mutex; |
| 8 | use serde::{Deserialize, Serialize}; |
| 9 | use sha2::{Digest, Sha256}; |
| 10 | |
| 11 | const GRANT_SCHEMA_VERSION: u32 = 1; |
| 12 | const GRANTS_FILE: &str = "approval_grants.json"; |
| 13 | const GRANT_LOG_FILE: &str = "approval_grants.jsonl"; |
| 14 | pub const DEFAULT_WORKSPACE_IDLE_TTL_SECS: u64 = 30 * 24 * 60 * 60; |
| 15 | const CLOCK_SKEW_TOLERANCE_SECS: i64 = 300; |
| 16 | |
| 17 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 18 | #[serde(rename_all = "snake_case")] |
| 19 | pub enum GrantEffect { |
| 20 | Allow, |
| 21 | Deny, |
| 22 | } |
| 23 | |
| 24 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 25 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 26 | pub enum GrantScope { |
| 27 | Thread { thread_id: String }, |
| 28 | Workspace { workspace_id: String }, |
| 29 | } |
| 30 | |
| 31 | impl GrantScope { |
| 32 | fn narrowness(&self) -> u8 { |
| 33 | match self { |
| 34 | Self::Thread { .. } => 2, |
| 35 | Self::Workspace { .. } => 1, |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 41 | #[serde(rename_all = "snake_case")] |
| 42 | pub enum GrantOrigin { |
| 43 | Interactive, |
| 44 | ChildAgent, |
| 45 | Automation, |
| 46 | Acp, |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 50 | #[serde(rename_all = "snake_case")] |
| 51 | pub enum PostureCeiling { |
| 52 | Ask, |
| 53 | AutoReview, |
| 54 | } |
| 55 | |
| 56 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 57 | pub enum GrantPosture { |
| 58 | Ask, |
| 59 | AutoReview, |
| 60 | FullAccess, |
| 61 | Never, |
| 62 | } |
| 63 | |
| 64 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 65 | #[serde(rename_all = "snake_case")] |
| 66 | pub enum GrantState { |
| 67 | Active, |
| 68 | Revoked, |
| 69 | Expired, |
| 70 | Exhausted, |
| 71 | Suspended, |
| 72 | } |
| 73 | |
| 74 | /// Who answered. There is deliberately no variant for model output, tool |
| 75 | /// text, a bot, or a hosted gate: a grant can only be minted from an |
| 76 | /// authenticated human channel. |
| 77 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 78 | #[serde(rename_all = "snake_case")] |
| 79 | pub enum GrantDecider { |
| 80 | HumanCard, |
| 81 | HumanSettings, |
| 82 | } |
| 83 | |
| 84 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 85 | #[serde(rename_all = "snake_case")] |
| 86 | pub enum GrantSurface { |
| 87 | Tui, |
| 88 | App, |
| 89 | Web, |
| 90 | Runtime, |
| 91 | Cli, |
| 92 | } |
| 93 | |
| 94 | #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] |
| 95 | pub struct GrantMatcher { |
| 96 | pub tool_class: String, |
| 97 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 98 | pub exact_digest: Option<String>, |
| 99 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 100 | pub grouping_key: Option<String>, |
| 101 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 102 | pub argv_prefix: Vec<String>, |
| 103 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 104 | pub net_host: Option<String>, |
| 105 | } |
| 106 | |
| 107 | impl GrantMatcher { |
| 108 | fn narrows_beyond_class(&self) -> bool { |
| 109 | self.exact_digest.is_some() |
| 110 | || self.grouping_key.is_some() |
| 111 | || !self.argv_prefix.is_empty() |
| 112 | || self.net_host.is_some() |
| 113 | } |
| 114 | |
| 115 | fn matches(&self, query: &GrantQuery<'_>) -> bool { |
| 116 | self.tool_class == query.tool_class |
| 117 | && self |
| 118 | .exact_digest |
| 119 | .as_deref() |
| 120 | .is_none_or(|digest| digest == query.exact_digest) |
| 121 | && self |
| 122 | .grouping_key |
| 123 | .as_deref() |
| 124 | .is_none_or(|key| key == query.grouping_key) |
| 125 | && (self.argv_prefix.is_empty() || query.argv.starts_with(&self.argv_prefix)) |
| 126 | && self.net_host.as_deref().is_none_or(|host| { |
| 127 | query |
| 128 | .net_host |
| 129 | .is_some_and(|candidate| candidate.eq_ignore_ascii_case(host)) |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | fn specificity(&self) -> (u8, usize) { |
| 134 | if self.exact_digest.is_some() { |
| 135 | (3, 0) |
| 136 | } else if !self.argv_prefix.is_empty() { |
| 137 | (2, self.argv_prefix.len()) |
| 138 | } else if self.grouping_key.is_some() || self.net_host.is_some() { |
| 139 | (1, 0) |
| 140 | } else { |
| 141 | (0, 0) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn digest(&self) -> String { |
| 146 | let canonical = serde_json::to_vec(self).unwrap_or_default(); |
| 147 | hex_digest(&canonical) |
| 148 | } |
| 149 | |
| 150 | fn label(&self) -> String { |
| 151 | if let Some(key) = &self.grouping_key { |
| 152 | return format!("{}: {key}", self.tool_class); |
| 153 | } |
| 154 | if !self.argv_prefix.is_empty() { |
| 155 | return format!("{}: {} ...", self.tool_class, self.argv_prefix.join(" ")); |
| 156 | } |
| 157 | if let Some(host) = &self.net_host { |
| 158 | return format!("{}: {host}", self.tool_class); |
| 159 | } |
| 160 | if self.exact_digest.is_some() { |
| 161 | return format!("{}: this exact call", self.tool_class); |
| 162 | } |
| 163 | format!("any {} call", self.tool_class) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] |
| 168 | pub struct GrantDisplay { |
| 169 | pub label: String, |
| 170 | #[serde(default)] |
| 171 | pub tool_name: String, |
| 172 | pub redacted_summary: String, |
| 173 | } |
| 174 | |
| 175 | #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] |
| 176 | pub struct GrantLimits { |
| 177 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 178 | pub expires_at: Option<DateTime<Utc>>, |
| 179 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 180 | pub idle_ttl_secs: Option<u64>, |
| 181 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 182 | pub max_uses: Option<u32>, |
| 183 | #[serde(default)] |
| 184 | pub uses: u32, |
| 185 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 186 | pub last_used_at: Option<DateTime<Utc>>, |
| 187 | } |
| 188 | |
| 189 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 190 | pub struct GrantAppliesTo { |
| 191 | pub origins: Vec<GrantOrigin>, |
| 192 | pub posture_ceiling: PostureCeiling, |
| 193 | } |
| 194 | |
| 195 | impl Default for GrantAppliesTo { |
| 196 | fn default() -> Self { |
| 197 | Self { |
| 198 | origins: vec![GrantOrigin::Interactive], |
| 199 | posture_ceiling: PostureCeiling::Ask, |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 205 | pub struct GrantCreated { |
| 206 | pub at: DateTime<Utc>, |
| 207 | pub principal: String, |
| 208 | pub surface: GrantSurface, |
| 209 | pub decider: GrantDecider, |
| 210 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 211 | pub source_approval_id: Option<String>, |
| 212 | pub engine_version: String, |
| 213 | } |
| 214 | |
| 215 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 216 | pub struct GrantRevoked { |
| 217 | pub at: DateTime<Utc>, |
| 218 | pub by: String, |
| 219 | pub reason: String, |
| 220 | } |
| 221 | |
| 222 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 223 | pub struct Grant { |
| 224 | pub grant_id: String, |
| 225 | pub schema_v: u32, |
| 226 | pub effect: GrantEffect, |
| 227 | pub scope: GrantScope, |
| 228 | pub matcher: GrantMatcher, |
| 229 | pub matcher_digest: String, |
| 230 | pub display: GrantDisplay, |
| 231 | pub limits: GrantLimits, |
| 232 | pub applies_to: GrantAppliesTo, |
| 233 | pub created: GrantCreated, |
| 234 | pub state: GrantState, |
| 235 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 236 | pub revoked: Option<GrantRevoked>, |
| 237 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 238 | pub suspended_reason: Option<String>, |
| 239 | } |
| 240 | |
| 241 | impl Grant { |
| 242 | fn lapse_reason(&self, now: DateTime<Utc>) -> Option<GrantState> { |
| 243 | if self.limits.expires_at.is_some_and(|at| at <= now) { |
| 244 | return Some(GrantState::Expired); |
| 245 | } |
| 246 | if self.effect == GrantEffect::Deny { |
| 247 | return None; |
| 248 | } |
| 249 | if let Some(ttl) = self.limits.idle_ttl_secs { |
| 250 | let base = self.limits.last_used_at.unwrap_or(self.created.at); |
| 251 | let ttl = Duration::seconds(i64::try_from(ttl).unwrap_or(i64::MAX / 2)); |
| 252 | let skewed = base - now > Duration::seconds(CLOCK_SKEW_TOLERANCE_SECS); |
| 253 | if skewed || base.checked_add_signed(ttl).is_none_or(|end| end <= now) { |
| 254 | return Some(GrantState::Expired); |
| 255 | } |
| 256 | } |
| 257 | if self |
| 258 | .limits |
| 259 | .max_uses |
| 260 | .is_some_and(|max| self.limits.uses >= max) |
| 261 | { |
| 262 | return Some(GrantState::Exhausted); |
| 263 | } |
| 264 | None |
| 265 | } |
| 266 | |
| 267 | fn reference(&self) -> GrantRef { |
| 268 | GrantRef { |
| 269 | grant_id: self.grant_id.clone(), |
| 270 | label: self.display.label.clone(), |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | /// What a decision receipt names: the grant that answered and its label. |
| 276 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 277 | pub struct GrantRef { |
| 278 | pub grant_id: String, |
| 279 | pub label: String, |
| 280 | } |
| 281 | |
| 282 | pub struct NewGrant { |
| 283 | pub effect: GrantEffect, |
| 284 | pub scope: GrantScope, |
| 285 | pub matcher: GrantMatcher, |
| 286 | pub tool_name: String, |
| 287 | pub redacted_summary: String, |
| 288 | pub limits: GrantLimits, |
| 289 | pub applies_to: GrantAppliesTo, |
| 290 | pub principal: String, |
| 291 | pub surface: GrantSurface, |
| 292 | pub decider: GrantDecider, |
| 293 | pub source_approval_id: Option<String>, |
| 294 | } |
| 295 | |
| 296 | pub struct GrantQuery<'a> { |
| 297 | pub thread_id: &'a str, |
| 298 | pub workspace_id: &'a str, |
| 299 | pub origin: GrantOrigin, |
| 300 | pub posture: GrantPosture, |
| 301 | pub tool_class: &'a str, |
| 302 | pub exact_digest: &'a str, |
| 303 | pub grouping_key: &'a str, |
| 304 | pub argv: &'a [String], |
| 305 | pub net_host: Option<&'a str>, |
| 306 | } |
| 307 | |
| 308 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 309 | pub enum GrantVerdict { |
| 310 | Deny(GrantRef), |
| 311 | Allow(GrantRef), |
| 312 | NoMatch, |
| 313 | } |
| 314 | |
| 315 | #[derive(Debug, thiserror::Error)] |
| 316 | pub enum GrantError { |
| 317 | #[error("an allow grant must narrow beyond the tool class")] |
| 318 | TooBroad, |
| 319 | #[error("grant store is degraded: {0}")] |
| 320 | Degraded(String), |
| 321 | #[error("a grant needs a non-empty thread or workspace id")] |
| 322 | InvalidScope, |
| 323 | #[error("grant is exhausted, expired or no longer active")] |
| 324 | NotUsable, |
| 325 | #[error("grant evidence could not be written: {0}")] |
| 326 | Io(#[from] std::io::Error), |
| 327 | } |
| 328 | |
| 329 | #[derive(Debug, Serialize)] |
| 330 | struct GrantEvent { |
| 331 | at: DateTime<Utc>, |
| 332 | event: &'static str, |
| 333 | grant_id: String, |
| 334 | effect: GrantEffect, |
| 335 | scope: GrantScope, |
| 336 | label: String, |
| 337 | #[serde(skip_serializing_if = "Option::is_none")] |
| 338 | by: Option<String>, |
| 339 | #[serde(skip_serializing_if = "Option::is_none")] |
| 340 | reason: Option<String>, |
| 341 | #[serde(skip_serializing_if = "Option::is_none")] |
| 342 | uses: Option<u32>, |
| 343 | #[serde(skip_serializing_if = "Option::is_none")] |
| 344 | grant: Option<Grant>, |
| 345 | } |
| 346 | |
| 347 | impl GrantEvent { |
| 348 | fn new(event: &'static str, grant: &Grant) -> Self { |
| 349 | Self { |
| 350 | at: Utc::now(), |
| 351 | event, |
| 352 | grant_id: grant.grant_id.clone(), |
| 353 | effect: grant.effect, |
| 354 | scope: grant.scope.clone(), |
| 355 | label: grant.display.label.clone(), |
| 356 | by: None, |
| 357 | reason: None, |
| 358 | uses: None, |
| 359 | grant: None, |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | #[derive(Serialize, Deserialize)] |
| 365 | struct GrantFile { |
| 366 | schema_v: u32, |
| 367 | grants: Vec<Grant>, |
| 368 | } |
| 369 | |
| 370 | struct Inner { |
| 371 | dir: Option<PathBuf>, |
| 372 | grants: Vec<Grant>, |
| 373 | degraded: Option<String>, |
| 374 | persist_failed: bool, |
| 375 | stamp: Option<(std::time::SystemTime, u64)>, |
| 376 | } |
| 377 | |
| 378 | impl Inner { |
| 379 | fn file_stamp(&self) -> Option<(std::time::SystemTime, u64)> { |
| 380 | let meta = fs::metadata(self.dir.as_ref()?.join(GRANTS_FILE)).ok()?; |
| 381 | Some((meta.modified().ok()?, meta.len())) |
| 382 | } |
| 383 | |
| 384 | fn refresh(&mut self) { |
| 385 | if self.persist_failed || self.degraded.is_some() { |
| 386 | return; |
| 387 | } |
| 388 | let Some(dir) = &self.dir else { |
| 389 | return; |
| 390 | }; |
| 391 | let stamp = self.file_stamp(); |
| 392 | if stamp.is_none() || stamp == self.stamp { |
| 393 | return; |
| 394 | } |
| 395 | let Ok(bytes) = fs::read(dir.join(GRANTS_FILE)) else { |
| 396 | return; |
| 397 | }; |
| 398 | if let Ok(file) = serde_json::from_slice::<GrantFile>(&bytes) |
| 399 | && file.schema_v <= GRANT_SCHEMA_VERSION |
| 400 | { |
| 401 | self.grants = file.grants; |
| 402 | self.stamp = stamp; |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | fn persist(&self, grants: &[Grant], events: &[GrantEvent]) -> std::io::Result<()> { |
| 407 | let Some(dir) = &self.dir else { |
| 408 | return Ok(()); |
| 409 | }; |
| 410 | if !events.is_empty() { |
| 411 | let mut log = OpenOptions::new() |
| 412 | .create(true) |
| 413 | .append(true) |
| 414 | .open(dir.join(GRANT_LOG_FILE))?; |
| 415 | let mut buf = Vec::new(); |
| 416 | for event in events { |
| 417 | serde_json::to_writer(&mut buf, event).map_err(std::io::Error::other)?; |
| 418 | buf.push(b'\n'); |
| 419 | } |
| 420 | log.write_all(&buf)?; |
| 421 | log.sync_data()?; |
| 422 | } |
| 423 | let file = GrantFile { |
| 424 | schema_v: GRANT_SCHEMA_VERSION, |
| 425 | grants: grants.to_vec(), |
| 426 | }; |
| 427 | let bytes = serde_json::to_vec_pretty(&file).map_err(std::io::Error::other)?; |
| 428 | codewhale_util::utils::write_atomic(&dir.join(GRANTS_FILE), &bytes) |
| 429 | } |
| 430 | |
| 431 | fn commit(&mut self, grants: Vec<Grant>, events: Vec<GrantEvent>) -> std::io::Result<()> { |
| 432 | self.persist(&grants, &events)?; |
| 433 | self.grants = grants; |
| 434 | self.stamp = self.file_stamp(); |
| 435 | Ok(()) |
| 436 | } |
| 437 | |
| 438 | fn commit_tightening( |
| 439 | &mut self, |
| 440 | grants: Vec<Grant>, |
| 441 | events: Vec<GrantEvent>, |
| 442 | ) -> std::io::Result<()> { |
| 443 | self.grants = grants; |
| 444 | match self.persist(&self.grants, &events) { |
| 445 | Ok(()) => { |
| 446 | self.stamp = self.file_stamp(); |
| 447 | Ok(()) |
| 448 | } |
| 449 | Err(error) => { |
| 450 | self.persist_failed = true; |
| 451 | self.degraded = Some(format!( |
| 452 | "grant revocation evidence could not be persisted: {error}" |
| 453 | )); |
| 454 | tracing::error!( |
| 455 | target: "approval", |
| 456 | %error, |
| 457 | "grant tightening could not be persisted; store degraded and failing closed" |
| 458 | ); |
| 459 | Err(error) |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | fn sweep(&mut self, now: DateTime<Utc>) { |
| 465 | self.refresh(); |
| 466 | let mut grants = self.grants.clone(); |
| 467 | let mut events = Vec::new(); |
| 468 | for grant in &mut grants { |
| 469 | if grant.state != GrantState::Active { |
| 470 | continue; |
| 471 | } |
| 472 | if let Some(state) = grant.lapse_reason(now) { |
| 473 | grant.state = state; |
| 474 | let name = if state == GrantState::Expired { |
| 475 | "expired" |
| 476 | } else { |
| 477 | "exhausted" |
| 478 | }; |
| 479 | events.push(GrantEvent::new(name, grant)); |
| 480 | } |
| 481 | } |
| 482 | if !events.is_empty() { |
| 483 | let _ = self.commit_tightening(grants, events); |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | fn transition( |
| 488 | &mut self, |
| 489 | select: impl Fn(&Grant) -> bool, |
| 490 | from: GrantState, |
| 491 | to: GrantState, |
| 492 | event: &'static str, |
| 493 | by: &str, |
| 494 | reason: &str, |
| 495 | tighten: bool, |
| 496 | ) -> Result<Vec<Grant>, GrantError> { |
| 497 | self.refresh(); |
| 498 | let mut grants = self.grants.clone(); |
| 499 | let mut events = Vec::new(); |
| 500 | let mut changed = Vec::new(); |
| 501 | for grant in &mut grants { |
| 502 | if grant.state != from || !select(grant) { |
| 503 | continue; |
| 504 | } |
| 505 | grant.state = to; |
| 506 | match to { |
| 507 | GrantState::Revoked => { |
| 508 | grant.revoked = Some(GrantRevoked { |
| 509 | at: Utc::now(), |
| 510 | by: by.to_string(), |
| 511 | reason: reason.to_string(), |
| 512 | }); |
| 513 | } |
| 514 | GrantState::Suspended => grant.suspended_reason = Some(reason.to_string()), |
| 515 | _ => grant.suspended_reason = None, |
| 516 | } |
| 517 | let mut record = GrantEvent::new(event, grant); |
| 518 | record.by = Some(by.to_string()); |
| 519 | record.reason = Some(reason.to_string()); |
| 520 | events.push(record); |
| 521 | changed.push(grant.clone()); |
| 522 | } |
| 523 | if changed.is_empty() { |
| 524 | return Ok(changed); |
| 525 | } |
| 526 | if tighten { |
| 527 | self.commit_tightening(grants, events)?; |
| 528 | Ok(changed) |
| 529 | } else { |
| 530 | if let Some(degraded) = &self.degraded { |
| 531 | return Err(GrantError::Degraded(degraded.clone())); |
| 532 | } |
| 533 | self.commit(grants, events)?; |
| 534 | Ok(changed) |
| 535 | } |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | /// The single grant authority: records, matching, precedence, expiry, |
| 540 | /// revocation and receipts. Cloning shares the same store. |
| 541 | #[derive(Clone)] |
| 542 | pub struct GrantStore { |
| 543 | inner: Arc<Mutex<Inner>>, |
| 544 | } |
| 545 | |
| 546 | impl GrantStore { |
| 547 | /// Open the file-backed store under `dir`. An unreadable or corrupt store |
| 548 | /// is left untouched on disk and the store runs degraded (no grants, no |
| 549 | /// writes, see [`Self::degraded_reason`]): it never allows from a file it |
| 550 | /// cannot read, and it never overwrites standing denies it could not parse. |
| 551 | #[must_use] |
| 552 | pub fn open(dir: &Path) -> Self { |
| 553 | let mut inner = Inner { |
| 554 | dir: Some(dir.to_path_buf()), |
| 555 | grants: Vec::new(), |
| 556 | degraded: None, |
| 557 | persist_failed: false, |
| 558 | stamp: None, |
| 559 | }; |
| 560 | let path = dir.join(GRANTS_FILE); |
| 561 | match fs::read(&path) { |
| 562 | Ok(bytes) => match serde_json::from_slice::<GrantFile>(&bytes) { |
| 563 | Ok(file) if file.schema_v <= GRANT_SCHEMA_VERSION => { |
| 564 | inner.grants = file.grants; |
| 565 | inner.stamp = inner.file_stamp(); |
| 566 | } |
| 567 | Ok(file) => { |
| 568 | inner.degraded = Some(format!("grant store schema {} is newer", file.schema_v)); |
| 569 | inner.dir = None; |
| 570 | } |
| 571 | Err(error) => { |
| 572 | inner.degraded = Some(format!("grant store was unreadable: {error}")); |
| 573 | inner.dir = None; |
| 574 | } |
| 575 | }, |
| 576 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} |
| 577 | Err(error) => { |
| 578 | inner.degraded = Some(format!("grant store could not be read: {error}")); |
| 579 | inner.dir = None; |
| 580 | } |
| 581 | } |
| 582 | if let Some(reason) = &inner.degraded { |
| 583 | tracing::warn!(target: "approval", %reason, "standing grants are unavailable; every call asks"); |
| 584 | } |
| 585 | let _ = inner.transition( |
| 586 | |grant| { |
| 587 | grant.effect == GrantEffect::Allow |
| 588 | && matches!(grant.scope, GrantScope::Thread { .. }) |
| 589 | }, |
| 590 | GrantState::Active, |
| 591 | GrantState::Suspended, |
| 592 | "suspended", |
| 593 | "engine", |
| 594 | "restart: awaiting authenticated resume", |
| 595 | true, |
| 596 | ); |
| 597 | Self { |
| 598 | inner: Arc::new(Mutex::new(inner)), |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | #[must_use] |
| 603 | pub fn degraded_reason(&self) -> Option<String> { |
| 604 | self.inner.lock().degraded.clone() |
| 605 | } |
| 606 | |
| 607 | /// Create a grant. Allow grants cannot cover a whole tool class, and an |
| 608 | /// identical live grant is returned instead of duplicated. |
| 609 | pub fn create(&self, new: NewGrant) -> Result<Grant, GrantError> { |
| 610 | if new.effect == GrantEffect::Allow && !new.matcher.narrows_beyond_class() { |
| 611 | return Err(GrantError::TooBroad); |
| 612 | } |
| 613 | let empty_id = match &new.scope { |
| 614 | GrantScope::Thread { thread_id } => thread_id.is_empty(), |
| 615 | GrantScope::Workspace { workspace_id } => workspace_id.is_empty(), |
| 616 | }; |
| 617 | if empty_id { |
| 618 | return Err(GrantError::InvalidScope); |
| 619 | } |
| 620 | let mut inner = self.inner.lock(); |
| 621 | if let Some(reason) = &inner.degraded { |
| 622 | return Err(GrantError::Degraded(reason.clone())); |
| 623 | } |
| 624 | let now = Utc::now(); |
| 625 | inner.sweep(now); |
| 626 | if let Some(reason) = &inner.degraded { |
| 627 | return Err(GrantError::Degraded(reason.clone())); |
| 628 | } |
| 629 | let matcher_digest = new.matcher.digest(); |
| 630 | if let Some(existing) = inner.grants.iter().find(|grant| { |
| 631 | matches!(grant.state, GrantState::Active | GrantState::Suspended) |
| 632 | && grant.effect == new.effect |
| 633 | && grant.scope == new.scope |
| 634 | && grant.matcher_digest == matcher_digest |
| 635 | }) { |
| 636 | return Ok(existing.clone()); |
| 637 | } |
| 638 | let mut limits = new.limits; |
| 639 | if limits.idle_ttl_secs.is_none() |
| 640 | && new.effect == GrantEffect::Allow |
| 641 | && matches!(new.scope, GrantScope::Workspace { .. }) |
| 642 | { |
| 643 | limits.idle_ttl_secs = Some(DEFAULT_WORKSPACE_IDLE_TTL_SECS); |
| 644 | } |
| 645 | let grant = Grant { |
| 646 | grant_id: format!("grt_{}", uuid::Uuid::new_v4().simple()), |
| 647 | schema_v: GRANT_SCHEMA_VERSION, |
| 648 | effect: new.effect, |
| 649 | scope: new.scope, |
| 650 | display: GrantDisplay { |
| 651 | label: new.matcher.label(), |
| 652 | tool_name: new.tool_name, |
| 653 | redacted_summary: new.redacted_summary, |
| 654 | }, |
| 655 | matcher: new.matcher, |
| 656 | matcher_digest, |
| 657 | limits, |
| 658 | applies_to: new.applies_to, |
| 659 | created: GrantCreated { |
| 660 | at: now, |
| 661 | principal: new.principal, |
| 662 | surface: new.surface, |
| 663 | decider: new.decider, |
| 664 | source_approval_id: new.source_approval_id, |
| 665 | engine_version: env!("CARGO_PKG_VERSION").to_string(), |
| 666 | }, |
| 667 | state: GrantState::Active, |
| 668 | revoked: None, |
| 669 | suspended_reason: None, |
| 670 | }; |
| 671 | let mut event = GrantEvent::new("created", &grant); |
| 672 | event.by = Some(grant.created.principal.clone()); |
| 673 | event.grant = Some(grant.clone()); |
| 674 | let mut grants = inner.grants.clone(); |
| 675 | grants.push(grant.clone()); |
| 676 | inner.commit(grants, vec![event])?; |
| 677 | Ok(grant) |
| 678 | } |
| 679 | |
| 680 | /// Decide a call against the live grants. Deny beats allow in every |
| 681 | /// posture and for every origin; an allow needs a live posture at or |
| 682 | /// under its ceiling and an origin it lists. Among allows the most |
| 683 | /// specific matcher wins, then the narrower scope, then the newest. |
| 684 | /// This only reads; call [`Self::record_use`] when the allow is applied. |
| 685 | #[must_use] |
| 686 | pub fn evaluate(&self, query: &GrantQuery<'_>) -> GrantVerdict { |
| 687 | let mut inner = self.inner.lock(); |
| 688 | inner.sweep(Utc::now()); |
| 689 | let in_scope = |grant: &&Grant| { |
| 690 | grant.state == GrantState::Active |
| 691 | && match &grant.scope { |
| 692 | GrantScope::Thread { thread_id } => thread_id == query.thread_id, |
| 693 | GrantScope::Workspace { workspace_id } => { |
| 694 | !workspace_id.is_empty() && workspace_id == query.workspace_id |
| 695 | } |
| 696 | } |
| 697 | && grant.matcher.matches(query) |
| 698 | }; |
| 699 | let best = |effect: GrantEffect, usable: &dyn Fn(&Grant) -> bool| { |
| 700 | inner |
| 701 | .grants |
| 702 | .iter() |
| 703 | .filter(in_scope) |
| 704 | .filter(|grant| grant.effect == effect && usable(grant)) |
| 705 | .max_by_key(|grant| { |
| 706 | ( |
| 707 | grant.matcher.specificity(), |
| 708 | grant.scope.narrowness(), |
| 709 | grant.created.at, |
| 710 | ) |
| 711 | }) |
| 712 | .map(Grant::reference) |
| 713 | }; |
| 714 | if let Some(deny) = best(GrantEffect::Deny, &|_| true) { |
| 715 | return GrantVerdict::Deny(deny); |
| 716 | } |
| 717 | if inner.persist_failed || inner.degraded.is_some() { |
| 718 | return GrantVerdict::NoMatch; |
| 719 | } |
| 720 | let allow = best(GrantEffect::Allow, &|grant| { |
| 721 | grant.applies_to.origins.contains(&query.origin) |
| 722 | && match query.posture { |
| 723 | GrantPosture::Ask => true, |
| 724 | GrantPosture::AutoReview => { |
| 725 | grant.applies_to.posture_ceiling == PostureCeiling::AutoReview |
| 726 | } |
| 727 | GrantPosture::FullAccess | GrantPosture::Never => false, |
| 728 | } |
| 729 | }); |
| 730 | allow.map_or(GrantVerdict::NoMatch, GrantVerdict::Allow) |
| 731 | } |
| 732 | |
| 733 | /// Count one use of an allow grant under the store lock. Fails closed: |
| 734 | /// an exhausted, lapsed or unwritable grant is not usable and the caller |
| 735 | /// must ask instead. |
| 736 | pub fn record_use(&self, grant_id: &str) -> Result<(), GrantError> { |
| 737 | let mut inner = self.inner.lock(); |
| 738 | if let Some(reason) = &inner.degraded { |
| 739 | return Err(GrantError::Degraded(reason.clone())); |
| 740 | } |
| 741 | let now = Utc::now(); |
| 742 | inner.sweep(now); |
| 743 | if let Some(reason) = &inner.degraded { |
| 744 | return Err(GrantError::Degraded(reason.clone())); |
| 745 | } |
| 746 | let mut grants = inner.grants.clone(); |
| 747 | let Some(grant) = grants |
| 748 | .iter_mut() |
| 749 | .find(|grant| grant.grant_id == grant_id && grant.state == GrantState::Active) |
| 750 | else { |
| 751 | return Err(GrantError::NotUsable); |
| 752 | }; |
| 753 | grant.limits.uses = grant.limits.uses.saturating_add(1); |
| 754 | grant.limits.last_used_at = Some(now); |
| 755 | let mut events = Vec::new(); |
| 756 | if grant.limits.uses == 1 { |
| 757 | let mut used = GrantEvent::new("used", grant); |
| 758 | used.uses = Some(1); |
| 759 | events.push(used); |
| 760 | } |
| 761 | if grant |
| 762 | .limits |
| 763 | .max_uses |
| 764 | .is_some_and(|max| grant.limits.uses >= max) |
| 765 | { |
| 766 | grant.state = GrantState::Exhausted; |
| 767 | let mut done = GrantEvent::new("exhausted", grant); |
| 768 | done.uses = Some(grant.limits.uses); |
| 769 | events.push(done); |
| 770 | } |
| 771 | inner.commit(grants, events)?; |
| 772 | Ok(()) |
| 773 | } |
| 774 | |
| 775 | /// Revoke one active or suspended grant, optionally only inside `scope`. |
| 776 | pub fn revoke( |
| 777 | &self, |
| 778 | grant_id: &str, |
| 779 | scope: Option<&GrantScope>, |
| 780 | by: &str, |
| 781 | reason: &str, |
| 782 | ) -> Result<Option<Grant>, GrantError> { |
| 783 | let mut inner = self.inner.lock(); |
| 784 | let select = |grant: &Grant| { |
| 785 | grant.grant_id == grant_id && scope.is_none_or(|scope| &grant.scope == scope) |
| 786 | }; |
| 787 | let mut done = inner.transition( |
| 788 | select, |
| 789 | GrantState::Active, |
| 790 | GrantState::Revoked, |
| 791 | "revoked", |
| 792 | by, |
| 793 | reason, |
| 794 | true, |
| 795 | )?; |
| 796 | if done.is_empty() { |
| 797 | done = inner.transition( |
| 798 | select, |
| 799 | GrantState::Suspended, |
| 800 | GrantState::Revoked, |
| 801 | "revoked", |
| 802 | by, |
| 803 | reason, |
| 804 | true, |
| 805 | )?; |
| 806 | } |
| 807 | Ok(done.pop()) |
| 808 | } |
| 809 | |
| 810 | /// End every grant of a thread (archive or delete). |
| 811 | pub fn revoke_thread( |
| 812 | &self, |
| 813 | thread_id: &str, |
| 814 | by: &str, |
| 815 | reason: &str, |
| 816 | ) -> Result<Vec<Grant>, GrantError> { |
| 817 | let mut inner = self.inner.lock(); |
| 818 | let select = |grant: &Grant| matches!(&grant.scope, GrantScope::Thread { thread_id: id } if id == thread_id); |
| 819 | let mut done = inner.transition( |
| 820 | select, |
| 821 | GrantState::Active, |
| 822 | GrantState::Revoked, |
| 823 | "revoked", |
| 824 | by, |
| 825 | reason, |
| 826 | true, |
| 827 | )?; |
| 828 | done.extend(inner.transition( |
| 829 | select, |
| 830 | GrantState::Suspended, |
| 831 | GrantState::Revoked, |
| 832 | "revoked", |
| 833 | by, |
| 834 | reason, |
| 835 | true, |
| 836 | )?); |
| 837 | Ok(done) |
| 838 | } |
| 839 | |
| 840 | /// Reactivate a thread's grants suspended by a restart. Call only from an |
| 841 | /// authenticated resume; rehydrating a wait never restores authority. |
| 842 | pub fn resume_thread(&self, thread_id: &str) -> Vec<Grant> { |
| 843 | self.inner |
| 844 | .lock() |
| 845 | .transition( |
| 846 | |grant| matches!(&grant.scope, GrantScope::Thread { thread_id: id } if id == thread_id), |
| 847 | GrantState::Suspended, |
| 848 | GrantState::Active, |
| 849 | "resumed", |
| 850 | "authenticated_resume", |
| 851 | "thread resumed by an authenticated client", |
| 852 | false, |
| 853 | ) |
| 854 | .unwrap_or_default() |
| 855 | } |
| 856 | |
| 857 | pub fn standing_grants(&self) -> Result<Vec<Grant>, String> { |
| 858 | let mut inner = self.inner.lock(); |
| 859 | if let Some(reason) = &inner.degraded { |
| 860 | return Err(reason.clone()); |
| 861 | } |
| 862 | inner.sweep(Utc::now()); |
| 863 | if let Some(reason) = &inner.degraded { |
| 864 | return Err(reason.clone()); |
| 865 | } |
| 866 | Ok(inner |
| 867 | .grants |
| 868 | .iter() |
| 869 | .filter(|grant| matches!(grant.state, GrantState::Active | GrantState::Suspended)) |
| 870 | .cloned() |
| 871 | .collect()) |
| 872 | } |
| 873 | |
| 874 | /// Live (active) grants of one thread, oldest first. |
| 875 | #[must_use] |
| 876 | pub fn thread_grants(&self, thread_id: &str) -> Vec<Grant> { |
| 877 | let mut inner = self.inner.lock(); |
| 878 | inner.sweep(Utc::now()); |
| 879 | if inner.persist_failed || inner.degraded.is_some() { |
| 880 | return Vec::new(); |
| 881 | } |
| 882 | inner |
| 883 | .grants |
| 884 | .iter() |
| 885 | .filter(|grant| { |
| 886 | grant.state == GrantState::Active |
| 887 | && matches!(&grant.scope, GrantScope::Thread { thread_id: id } if id == thread_id) |
| 888 | }) |
| 889 | .cloned() |
| 890 | .collect() |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | /// Stable id for a workspace: the git root (or the directory itself) as a |
| 895 | /// canonical real path, never the path string a client supplied. |
| 896 | #[must_use] |
| 897 | pub fn workspace_id(workspace: &Path) -> String { |
| 898 | let real = fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf()); |
| 899 | let root = real |
| 900 | .ancestors() |
| 901 | .find(|dir| dir.join(".git").exists()) |
| 902 | .unwrap_or(&real); |
| 903 | format!( |
| 904 | "ws_{}", |
| 905 | &hex_digest(root.to_string_lossy().as_bytes())[..24] |
| 906 | ) |
| 907 | } |
| 908 | |
| 909 | fn hex_digest(bytes: &[u8]) -> String { |
| 910 | Sha256::digest(bytes) |
| 911 | .iter() |
| 912 | .map(|byte| format!("{byte:02x}")) |
| 913 | .collect() |
| 914 | } |
| 915 | |
| 916 | #[cfg(all(test, unix))] |
| 917 | mod tests { |
| 918 | #[cfg(unix)] |
| 919 | use super::*; |
| 920 | |
| 921 | #[cfg(unix)] |
| 922 | fn sample_workspace_grant(effect: GrantEffect, grouping_key: &str) -> NewGrant { |
| 923 | NewGrant { |
| 924 | effect, |
| 925 | scope: GrantScope::Workspace { |
| 926 | workspace_id: "ws_test".to_string(), |
| 927 | }, |
| 928 | matcher: GrantMatcher { |
| 929 | tool_class: "shell".to_string(), |
| 930 | grouping_key: Some(grouping_key.to_string()), |
| 931 | ..GrantMatcher::default() |
| 932 | }, |
| 933 | tool_name: "exec_shell".to_string(), |
| 934 | redacted_summary: format!("run {grouping_key}"), |
| 935 | limits: GrantLimits::default(), |
| 936 | applies_to: GrantAppliesTo::default(), |
| 937 | principal: "user".to_string(), |
| 938 | surface: GrantSurface::Tui, |
| 939 | decider: GrantDecider::HumanCard, |
| 940 | source_approval_id: None, |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | #[cfg(unix)] |
| 945 | fn query_for(grouping_key: &str) -> GrantQuery<'_> { |
| 946 | GrantQuery { |
| 947 | thread_id: "thr_1", |
| 948 | workspace_id: "ws_test", |
| 949 | origin: GrantOrigin::Interactive, |
| 950 | posture: GrantPosture::Ask, |
| 951 | tool_class: "shell", |
| 952 | exact_digest: "dig_1", |
| 953 | grouping_key, |
| 954 | argv: &[], |
| 955 | net_host: None, |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | #[cfg(unix)] |
| 960 | #[test] |
| 961 | fn revoke_persist_failure_returns_error_marks_degraded_and_fails_closed() { |
| 962 | use std::os::unix::fs::PermissionsExt as _; |
| 963 | |
| 964 | if unsafe { libc::geteuid() } == 0 { |
| 965 | return; |
| 966 | } |
| 967 | |
| 968 | let tmp = tempfile::tempdir().unwrap(); |
| 969 | let store = GrantStore::open(tmp.path()); |
| 970 | let allow = store |
| 971 | .create(sample_workspace_grant(GrantEffect::Allow, "cargo test")) |
| 972 | .unwrap(); |
| 973 | let deny = store |
| 974 | .create(sample_workspace_grant(GrantEffect::Deny, "rm -rf")) |
| 975 | .unwrap(); |
| 976 | let _ = deny; |
| 977 | assert!(matches!( |
| 978 | store.evaluate(&query_for("cargo test")), |
| 979 | GrantVerdict::Allow(_) |
| 980 | )); |
| 981 | assert!(matches!( |
| 982 | store.evaluate(&query_for("rm -rf")), |
| 983 | GrantVerdict::Deny(_) |
| 984 | )); |
| 985 | |
| 986 | fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o500)).unwrap(); |
| 987 | let revoke_result = store.revoke(&allow.grant_id, None, "user", "revoke test"); |
| 988 | assert!( |
| 989 | matches!(revoke_result, Err(GrantError::Io(_))), |
| 990 | "expected Io error on read-only grants dir, got {revoke_result:?}" |
| 991 | ); |
| 992 | assert!(store.degraded_reason().is_some()); |
| 993 | assert!(store.standing_grants().is_err()); |
| 994 | assert_eq!( |
| 995 | store.evaluate(&query_for("cargo test")), |
| 996 | GrantVerdict::NoMatch, |
| 997 | "degraded store must fail closed for standing allows" |
| 998 | ); |
| 999 | assert!( |
| 1000 | matches!(store.evaluate(&query_for("rm -rf")), GrantVerdict::Deny(_)), |
| 1001 | "standing denies must remain enforced while degraded" |
| 1002 | ); |
| 1003 | assert!(matches!( |
| 1004 | store.record_use(&allow.grant_id), |
| 1005 | Err(GrantError::Degraded(_)) |
| 1006 | )); |
| 1007 | assert!(matches!( |
| 1008 | store.create(sample_workspace_grant(GrantEffect::Allow, "cargo clippy")), |
| 1009 | Err(GrantError::Degraded(_)) |
| 1010 | )); |
| 1011 | |
| 1012 | fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o700)).unwrap(); |
| 1013 | } |
| 1014 | } |
| 1015 |