| 1 | use super::*; |
| 2 | use crate::core::authority::grants::{GrantEffect, GrantScope, GrantState}; |
| 3 | use crate::core::authority::persistent_rules::persistent_rule_candidates; |
| 4 | use crate::tools::subagent::SubAgentManager; |
| 5 | use codewhale_execpolicy::{PermissionAction, Ruleset, RulesetLayer, ToolAskRule}; |
| 6 | |
| 7 | static PERMISSION_RULES_WRITE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); |
| 8 | |
| 9 | #[derive(Debug, Clone)] |
| 10 | pub(crate) enum StandingRuleState { |
| 11 | Claimed, |
| 12 | Saved(Vec<ToolAskRule>), |
| 13 | } |
| 14 | |
| 15 | #[derive(Debug, thiserror::Error)] |
| 16 | #[error("{reason}")] |
| 17 | pub struct StandingRuleIneligible { |
| 18 | pub reason: &'static str, |
| 19 | } |
| 20 | |
| 21 | #[derive(Debug, thiserror::Error)] |
| 22 | #[error("permission rules are unavailable: {0}")] |
| 23 | pub struct PermissionRulesUnavailable(pub String); |
| 24 | |
| 25 | #[derive(Debug, thiserror::Error)] |
| 26 | #[error("permission rules changed after they were listed; list them again")] |
| 27 | pub struct StalePermissionToken; |
| 28 | |
| 29 | #[derive(Debug, Clone, Serialize, PartialEq, Eq)] |
| 30 | pub struct PermissionRuleView { |
| 31 | pub index: usize, |
| 32 | pub tool: String, |
| 33 | pub command: Option<String>, |
| 34 | pub command_exact: bool, |
| 35 | pub path: Option<String>, |
| 36 | pub workspace: Option<String>, |
| 37 | pub action: PermissionAction, |
| 38 | pub layer: RulesetLayer, |
| 39 | pub removal_token: String, |
| 40 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 41 | pub warning: Option<String>, |
| 42 | } |
| 43 | |
| 44 | #[derive(Debug, Clone, Serialize)] |
| 45 | #[serde(tag = "status", rename_all = "snake_case")] |
| 46 | pub enum PermissionRulesListing { |
| 47 | Ok { |
| 48 | path: String, |
| 49 | exists: bool, |
| 50 | rules: Vec<PermissionRuleView>, |
| 51 | }, |
| 52 | Unavailable { |
| 53 | reason: String, |
| 54 | }, |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, Serialize)] |
| 58 | pub struct StandingGrantView { |
| 59 | pub grant_id: String, |
| 60 | pub scope_kind: &'static str, |
| 61 | pub thread_id: Option<String>, |
| 62 | pub workspace_id: Option<String>, |
| 63 | pub effect: GrantEffect, |
| 64 | pub tool_name: String, |
| 65 | pub label: String, |
| 66 | pub summary: String, |
| 67 | pub created_at: DateTime<Utc>, |
| 68 | pub last_used_at: Option<DateTime<Utc>>, |
| 69 | pub uses: u32, |
| 70 | pub state: GrantState, |
| 71 | pub suspended_reason: Option<String>, |
| 72 | } |
| 73 | |
| 74 | #[derive(Debug, Clone, Serialize)] |
| 75 | #[serde(tag = "status", rename_all = "snake_case")] |
| 76 | pub enum StandingGrantsListing { |
| 77 | Ok { grants: Vec<StandingGrantView> }, |
| 78 | Unavailable { reason: String }, |
| 79 | } |
| 80 | |
| 81 | impl RuntimeThreadManager { |
| 82 | fn permissions_config_path(&self) -> Result<PathBuf, PermissionRulesUnavailable> { |
| 83 | self.read_config() |
| 84 | .loaded_config_path |
| 85 | .clone() |
| 86 | .ok_or_else(|| { |
| 87 | PermissionRulesUnavailable( |
| 88 | "the Runtime loaded no user config, so no permissions.toml is in effect" |
| 89 | .to_string(), |
| 90 | ) |
| 91 | }) |
| 92 | } |
| 93 | |
| 94 | fn require_owner_responder(&self, responder: Option<ApprovalResponder>) -> Result<()> { |
| 95 | if self.owner_surface_attached && responder.is_some_and(ApprovalResponder::is_owner_surface) |
| 96 | { |
| 97 | Ok(()) |
| 98 | } else { |
| 99 | Err(ApprovalOwnerRequired.into()) |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | pub async fn list_permission_rules(&self) -> PermissionRulesListing { |
| 104 | let path = match self.permissions_config_path() { |
| 105 | Ok(path) => path, |
| 106 | Err(error) => return PermissionRulesListing::Unavailable { reason: error.0 }, |
| 107 | }; |
| 108 | let snapshot = tokio::task::spawn_blocking(move || { |
| 109 | codewhale_config::load_permissions_snapshot(Some(path)) |
| 110 | }) |
| 111 | .await; |
| 112 | let snapshot = match snapshot { |
| 113 | Ok(Ok(snapshot)) => snapshot, |
| 114 | Ok(Err(error)) => { |
| 115 | return PermissionRulesListing::Unavailable { |
| 116 | reason: format!("{error:#}"), |
| 117 | }; |
| 118 | } |
| 119 | Err(error) => { |
| 120 | return PermissionRulesListing::Unavailable { |
| 121 | reason: format!("permission read task failed: {error}"), |
| 122 | }; |
| 123 | } |
| 124 | }; |
| 125 | let rules = snapshot |
| 126 | .rules() |
| 127 | .iter() |
| 128 | .enumerate() |
| 129 | .map(|(index, rule)| PermissionRuleView { |
| 130 | index, |
| 131 | tool: rule.tool.clone(), |
| 132 | command: rule.command.clone(), |
| 133 | command_exact: rule.command_exact, |
| 134 | path: rule.path.clone(), |
| 135 | workspace: rule.workspace.clone(), |
| 136 | action: rule.action, |
| 137 | layer: RulesetLayer::User, |
| 138 | removal_token: snapshot |
| 139 | .removal_token(index) |
| 140 | .unwrap_or_default() |
| 141 | .to_string(), |
| 142 | warning: snapshot.rule_warning(index).map(str::to_owned), |
| 143 | }) |
| 144 | .collect(); |
| 145 | PermissionRulesListing::Ok { |
| 146 | path: snapshot.path().display().to_string(), |
| 147 | exists: snapshot.file_exists(), |
| 148 | rules, |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | #[must_use] |
| 153 | pub fn list_standing_grants(&self) -> StandingGrantsListing { |
| 154 | match self.grants.standing_grants() { |
| 155 | Ok(grants) => StandingGrantsListing::Ok { |
| 156 | grants: grants |
| 157 | .into_iter() |
| 158 | .map(|grant| { |
| 159 | let (scope_kind, thread_id, workspace_id) = match grant.scope { |
| 160 | GrantScope::Thread { thread_id } => ("thread", Some(thread_id), None), |
| 161 | GrantScope::Workspace { workspace_id } => { |
| 162 | ("workspace", None, Some(workspace_id)) |
| 163 | } |
| 164 | }; |
| 165 | StandingGrantView { |
| 166 | grant_id: grant.grant_id, |
| 167 | scope_kind, |
| 168 | thread_id, |
| 169 | workspace_id, |
| 170 | effect: grant.effect, |
| 171 | tool_name: grant.display.tool_name, |
| 172 | label: grant.display.label, |
| 173 | summary: grant.display.redacted_summary, |
| 174 | created_at: grant.created.at, |
| 175 | last_used_at: grant.limits.last_used_at, |
| 176 | uses: grant.limits.uses, |
| 177 | state: grant.state, |
| 178 | suspended_reason: grant.suspended_reason, |
| 179 | } |
| 180 | }) |
| 181 | .collect(), |
| 182 | }, |
| 183 | Err(reason) => StandingGrantsListing::Unavailable { reason }, |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | pub async fn remove_permission_rule_by_token( |
| 188 | &self, |
| 189 | token: &str, |
| 190 | responder: Option<ApprovalResponder>, |
| 191 | ) -> Result<ToolAskRule> { |
| 192 | self.require_owner_responder(responder)?; |
| 193 | let path = self.permissions_config_path()?; |
| 194 | let token = token.to_string(); |
| 195 | let _write = PERMISSION_RULES_WRITE.lock().await; |
| 196 | let (removed, ruleset) = tokio::task::spawn_blocking(move || -> Result<_> { |
| 197 | let snapshot = codewhale_config::load_permissions_snapshot(Some(path.clone())) |
| 198 | .map_err(|error| PermissionRulesUnavailable(format!("{error:#}")))?; |
| 199 | let index = (0..snapshot.rules().len()) |
| 200 | .find(|index| snapshot.removal_token(*index) == Some(token.as_str())) |
| 201 | .ok_or(StalePermissionToken)?; |
| 202 | let removed = codewhale_config::remove_permission_rule(Some(path), index, &token) |
| 203 | .map_err(|error| -> anyhow::Error { |
| 204 | if error |
| 205 | .downcast_ref::<codewhale_config::StalePermissionSnapshot>() |
| 206 | .is_some() |
| 207 | { |
| 208 | StalePermissionToken.into() |
| 209 | } else { |
| 210 | PermissionRulesUnavailable(format!("{error:#}")).into() |
| 211 | } |
| 212 | })?; |
| 213 | let mut remaining = snapshot.permissions().clone(); |
| 214 | remaining.rules.remove(index); |
| 215 | Ok((removed, remaining.ruleset())) |
| 216 | }) |
| 217 | .await |
| 218 | .context("permission removal task failed")??; |
| 219 | self.apply_user_permission_ruleset(ruleset).await; |
| 220 | Ok(removed) |
| 221 | } |
| 222 | |
| 223 | pub async fn deliver_approval_with_standing_rule( |
| 224 | &self, |
| 225 | approval_id: &str, |
| 226 | responder: Option<ApprovalResponder>, |
| 227 | ) -> Result<Option<(bool, Vec<ToolAskRule>)>> { |
| 228 | self.require_owner_responder(responder)?; |
| 229 | let decision = ExternalApprovalDecision::Allow { remember: false }; |
| 230 | let lookup = { |
| 231 | let pending = self.pending_approvals.lock(); |
| 232 | let Some(entry) = pending.get(approval_id) else { |
| 233 | return Ok(None); |
| 234 | }; |
| 235 | if entry.agent_settled.is_some() { |
| 236 | return Err(StandingRuleIneligible { |
| 237 | reason: "an external agent's approval cannot create a standing rule", |
| 238 | } |
| 239 | .into()); |
| 240 | } |
| 241 | match &entry.standing_rules { |
| 242 | Some(StandingRuleState::Saved(rules)) => { |
| 243 | Err((rules.clone(), entry.publication.clone())) |
| 244 | } |
| 245 | _ => Ok((entry.thread_id.clone(), entry.request.clone())), |
| 246 | } |
| 247 | }; |
| 248 | let (thread_id, request) = match lookup { |
| 249 | Ok(found) => found, |
| 250 | Err((rules, publication)) => { |
| 251 | let delivered = match self |
| 252 | .await_delivered_approval(approval_id, decision, publication, None) |
| 253 | .await |
| 254 | { |
| 255 | Ok(delivered) => delivered, |
| 256 | Err(error) => { |
| 257 | tracing::warn!( |
| 258 | approval_id, |
| 259 | "standing rule re-delivery was not confirmed: {error:#}" |
| 260 | ); |
| 261 | false |
| 262 | } |
| 263 | }; |
| 264 | return Ok(Some((delivered, rules))); |
| 265 | } |
| 266 | }; |
| 267 | let rules = self.standing_allow_rules_for(&thread_id, &request)?; |
| 268 | let path = self.permissions_config_path()?; |
| 269 | { |
| 270 | let mut pending = self.pending_approvals.lock(); |
| 271 | let Some(entry) = pending.get_mut(approval_id) else { |
| 272 | return Ok(None); |
| 273 | }; |
| 274 | if entry.standing_rules.is_some() || entry.proposed.is_some() || entry.sender.is_none() |
| 275 | { |
| 276 | return Err(io::Error::new( |
| 277 | io::ErrorKind::AlreadyExists, |
| 278 | "approval already has a proposed answer", |
| 279 | ) |
| 280 | .into()); |
| 281 | } |
| 282 | entry.standing_rules = Some(StandingRuleState::Claimed); |
| 283 | } |
| 284 | let _claim = StandingRuleClaim { |
| 285 | manager: self, |
| 286 | approval_id, |
| 287 | }; |
| 288 | { |
| 289 | let _write = PERMISSION_RULES_WRITE.lock().await; |
| 290 | let appended = rules.clone(); |
| 291 | let ruleset = tokio::task::spawn_blocking(move || -> Result<Ruleset> { |
| 292 | let mut store = codewhale_config::ConfigStore::load(Some(path)) |
| 293 | .map_err(|error| PermissionRulesUnavailable(format!("{error:#}")))?; |
| 294 | store |
| 295 | .append_allow_rules(&appended) |
| 296 | .map_err(|error| PermissionRulesUnavailable(format!("{error:#}")))?; |
| 297 | Ok(store.permissions().ruleset()) |
| 298 | }) |
| 299 | .await |
| 300 | .context("permission write task failed")??; |
| 301 | self.apply_user_permission_ruleset(ruleset).await; |
| 302 | } |
| 303 | if let Err(error) = self |
| 304 | .emit_event( |
| 305 | &thread_id, |
| 306 | Some(&request.turn_id), |
| 307 | None, |
| 308 | "permission.rules_saved", |
| 309 | json!({ |
| 310 | "approval_id": approval_id, |
| 311 | "tool_call_id": request.tool_call_id, |
| 312 | "tool_name": request.tool_name, |
| 313 | "standing_rules": rules, |
| 314 | }), |
| 315 | ) |
| 316 | .await |
| 317 | { |
| 318 | tracing::warn!(thread_id = %thread_id, approval_id, "failed to record saved permission rules: {error:#}"); |
| 319 | } |
| 320 | let (publication, agent_settled) = { |
| 321 | let mut pending = self.pending_approvals.lock(); |
| 322 | let Some(entry) = pending.get_mut(approval_id) else { |
| 323 | return Ok(Some((false, rules))); |
| 324 | }; |
| 325 | if !matches!(entry.standing_rules, Some(StandingRuleState::Claimed)) { |
| 326 | return Ok(Some((false, rules))); |
| 327 | } |
| 328 | entry.standing_rules = Some(StandingRuleState::Saved(rules.clone())); |
| 329 | let Some(sender) = entry.sender.take() else { |
| 330 | return Ok(Some((false, rules))); |
| 331 | }; |
| 332 | entry.responder = responder; |
| 333 | if sender.send(decision).is_err() { |
| 334 | return Ok(Some((false, rules))); |
| 335 | } |
| 336 | entry.proposed = Some(decision); |
| 337 | (entry.publication.clone(), entry.agent_settled.clone()) |
| 338 | }; |
| 339 | let delivered = match self |
| 340 | .await_delivered_approval(approval_id, decision, publication, agent_settled) |
| 341 | .await |
| 342 | { |
| 343 | Ok(delivered) => delivered, |
| 344 | Err(error) => { |
| 345 | tracing::warn!( |
| 346 | approval_id, |
| 347 | "standing rule saved but delivery was not confirmed: {error:#}" |
| 348 | ); |
| 349 | false |
| 350 | } |
| 351 | }; |
| 352 | Ok(Some((delivered, rules))) |
| 353 | } |
| 354 | |
| 355 | fn standing_allow_rules_for( |
| 356 | &self, |
| 357 | thread_id: &str, |
| 358 | request: &PendingApprovalRequest, |
| 359 | ) -> Result<Vec<ToolAskRule>> { |
| 360 | if request |
| 361 | .tool_call_id |
| 362 | .as_deref() |
| 363 | .is_some_and(SubAgentManager::is_child_approval_id) |
| 364 | { |
| 365 | return Err(StandingRuleIneligible { |
| 366 | reason: "a sub-agent's approval cannot create a standing rule", |
| 367 | } |
| 368 | .into()); |
| 369 | } |
| 370 | let Some(input) = request.input.as_ref() else { |
| 371 | return Err(StandingRuleIneligible { |
| 372 | reason: "this approval carries no captured tool input to build a rule from", |
| 373 | } |
| 374 | .into()); |
| 375 | }; |
| 376 | let thread = self |
| 377 | .store |
| 378 | .load_thread(thread_id) |
| 379 | .with_context(|| format!("Thread not found: {thread_id}"))?; |
| 380 | if thread.archived { |
| 381 | return Err(StandingRuleIneligible { |
| 382 | reason: "an archived thread cannot create a standing rule", |
| 383 | } |
| 384 | .into()); |
| 385 | } |
| 386 | if thread.executor.is_some() { |
| 387 | return Err(StandingRuleIneligible { |
| 388 | reason: "an external agent's approval cannot create a standing rule", |
| 389 | } |
| 390 | .into()); |
| 391 | } |
| 392 | let allow = standing_rule_candidates( |
| 393 | request.tool_call_id.as_deref(), |
| 394 | &request.tool_name, |
| 395 | input, |
| 396 | &request.description, |
| 397 | &thread.workspace, |
| 398 | ); |
| 399 | if allow.is_empty() { |
| 400 | return Err(StandingRuleIneligible { |
| 401 | reason: "only a safe shell command, or a write_file, edit_file or apply_patch inside the thread's workspace, can become a standing allow rule", |
| 402 | } |
| 403 | .into()); |
| 404 | } |
| 405 | Ok(allow) |
| 406 | } |
| 407 | |
| 408 | pub(super) async fn resync_user_permission_ruleset(&self) { |
| 409 | let Ok(path) = self.permissions_config_path() else { |
| 410 | return; |
| 411 | }; |
| 412 | let _write = PERMISSION_RULES_WRITE.lock().await; |
| 413 | let snapshot = tokio::task::spawn_blocking(move || { |
| 414 | codewhale_config::load_permissions_snapshot(Some(path)) |
| 415 | }) |
| 416 | .await; |
| 417 | match snapshot { |
| 418 | Ok(Ok(snapshot)) => { |
| 419 | self.apply_user_permission_ruleset(snapshot.permissions().ruleset()) |
| 420 | .await; |
| 421 | } |
| 422 | Ok(Err(error)) => { |
| 423 | tracing::warn!( |
| 424 | "permission rules were not re-read after a config reload: {error:#}" |
| 425 | ); |
| 426 | } |
| 427 | Err(error) => { |
| 428 | tracing::warn!("permission rules re-read task failed: {error}"); |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | async fn apply_user_permission_ruleset(&self, ruleset: Ruleset) { |
| 434 | self.read_config() |
| 435 | .exec_policy_engine |
| 436 | .clone() |
| 437 | .set_ruleset(ruleset.clone()); |
| 438 | let engines: Vec<EngineHandle> = { |
| 439 | let active = self.active.lock().await; |
| 440 | active |
| 441 | .engines |
| 442 | .values() |
| 443 | .map(|state| state.engine.clone()) |
| 444 | .collect() |
| 445 | }; |
| 446 | for engine in engines { |
| 447 | engine.replace_user_permission_ruleset(ruleset.clone()); |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | #[must_use] |
| 453 | pub(super) fn standing_rule_candidates( |
| 454 | tool_call_id: Option<&str>, |
| 455 | tool_name: &str, |
| 456 | input: &Value, |
| 457 | description: &str, |
| 458 | workspace: &Path, |
| 459 | ) -> Vec<ToolAskRule> { |
| 460 | if tool_call_id.is_some_and(SubAgentManager::is_child_approval_id) { |
| 461 | return Vec::new(); |
| 462 | } |
| 463 | persistent_rule_candidates(tool_name, input, description, workspace).allow |
| 464 | } |
| 465 | |
| 466 | struct StandingRuleClaim<'a> { |
| 467 | manager: &'a RuntimeThreadManager, |
| 468 | approval_id: &'a str, |
| 469 | } |
| 470 | |
| 471 | impl Drop for StandingRuleClaim<'_> { |
| 472 | fn drop(&mut self) { |
| 473 | if let Some(entry) = self |
| 474 | .manager |
| 475 | .pending_approvals |
| 476 | .lock() |
| 477 | .get_mut(self.approval_id) |
| 478 | && matches!(entry.standing_rules, Some(StandingRuleState::Claimed)) |
| 479 | { |
| 480 | entry.standing_rules = None; |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | #[cfg(any(test, feature = "test-support"))] |
| 486 | impl RuntimeThreadManager { |
| 487 | pub fn register_pending_tool_approval_for_thread_for_test( |
| 488 | &self, |
| 489 | thread_id: &str, |
| 490 | tool_name: &str, |
| 491 | input: Value, |
| 492 | ) -> (String, oneshot::Receiver<ExternalApprovalDecision>) { |
| 493 | self.register_pending_tool_call_approval_for_test( |
| 494 | thread_id, |
| 495 | &format!("call-{tool_name}"), |
| 496 | tool_name, |
| 497 | input, |
| 498 | ) |
| 499 | } |
| 500 | |
| 501 | pub fn register_pending_tool_call_approval_for_test( |
| 502 | &self, |
| 503 | thread_id: &str, |
| 504 | tool_call_id: &str, |
| 505 | tool_name: &str, |
| 506 | input: Value, |
| 507 | ) -> (String, oneshot::Receiver<ExternalApprovalDecision>) { |
| 508 | self.register_pending_approval_with_policy( |
| 509 | thread_id, |
| 510 | PendingApprovalRequest { |
| 511 | id: String::new(), |
| 512 | turn_id: "test-turn".to_string(), |
| 513 | tool_name: tool_name.to_string(), |
| 514 | input: Some(input), |
| 515 | description: format!("test approval for {tool_name}"), |
| 516 | intent_summary: None, |
| 517 | tool_call_id: Some(tool_call_id.to_string()), |
| 518 | summary: None, |
| 519 | approval_kind: None, |
| 520 | }, |
| 521 | None, |
| 522 | false, |
| 523 | ) |
| 524 | } |
| 525 | |
| 526 | pub fn register_pending_search_consent_approval_for_test( |
| 527 | &self, |
| 528 | thread_id: &str, |
| 529 | input: Value, |
| 530 | owner_only: bool, |
| 531 | ) -> (String, oneshot::Receiver<ExternalApprovalDecision>) { |
| 532 | self.register_pending_approval_with_policy( |
| 533 | thread_id, |
| 534 | PendingApprovalRequest { |
| 535 | id: String::new(), |
| 536 | turn_id: "test-turn".to_string(), |
| 537 | tool_name: "Web".to_string(), |
| 538 | input: Some(input), |
| 539 | description: "test search consent".to_string(), |
| 540 | intent_summary: None, |
| 541 | tool_call_id: Some("call-Web".to_string()), |
| 542 | summary: None, |
| 543 | approval_kind: Some( |
| 544 | codewhale_app_server_protocol::runtime::ApprovalKind::ThirdPartySearch, |
| 545 | ), |
| 546 | }, |
| 547 | None, |
| 548 | owner_only, |
| 549 | ) |
| 550 | } |
| 551 | |
| 552 | pub fn standing_rule_claimed_for_test(&self, approval_id: &str, claimed: bool) { |
| 553 | if let Some(entry) = self.pending_approvals.lock().get_mut(approval_id) { |
| 554 | entry.standing_rules = claimed.then_some(StandingRuleState::Claimed); |
| 555 | } |
| 556 | } |
| 557 | } |
| 558 |