| 1 | use std::collections::BTreeSet; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | use std::sync::{Arc, LazyLock}; |
| 4 | |
| 5 | use codewhale_config::extension_host::PluginSettings; |
| 6 | use codewhale_execpolicy::ApprovalMode; |
| 7 | use codewhale_runtime::config_persistence::{ |
| 8 | mutate_config_document, set_document_value, unset_document_value, |
| 9 | }; |
| 10 | use codewhale_sandbox::SandboxPolicy; |
| 11 | use serde::{Deserialize, Serialize}; |
| 12 | use serde_json::{Map, Value, json}; |
| 13 | use tokio_util::sync::CancellationToken; |
| 14 | |
| 15 | use super::dsh_broker::{ |
| 16 | BrokerCall, BrokerEffect, BrokerFuture, BrokerMethods, BrokerRefusal, decode, |
| 17 | }; |
| 18 | use super::plugin_config::{self, PluginConfig}; |
| 19 | use super::protocol::DshService; |
| 20 | use crate::tools::spec::ToolContext; |
| 21 | |
| 22 | const MAX_INPUT_BYTES: usize = 64 * 1024; |
| 23 | const MAX_OPS: usize = 64; |
| 24 | const MAX_PATH_DEPTH: usize = 16; |
| 25 | const MAX_KEY_CHARS: usize = 128; |
| 26 | const APPLIES: &str = "reload"; |
| 27 | const LOG: &str = "codewhale::dsh_settings"; |
| 28 | |
| 29 | static TURN: LazyLock<Arc<tokio::sync::Mutex<()>>> = |
| 30 | LazyLock::new(|| Arc::new(tokio::sync::Mutex::new(()))); |
| 31 | |
| 32 | #[derive(Deserialize)] |
| 33 | #[serde(tag = "method", content = "input", deny_unknown_fields)] |
| 34 | enum SettingsMethod { |
| 35 | #[serde(rename = "describe")] |
| 36 | Describe(NoInput), |
| 37 | #[serde(rename = "update")] |
| 38 | Update(PatchInput), |
| 39 | #[serde(rename = "replace")] |
| 40 | Replace(SectionInput), |
| 41 | #[serde(rename = "mutate")] |
| 42 | Mutate(OpsInput), |
| 43 | } |
| 44 | |
| 45 | impl BrokerMethods for SettingsMethod { |
| 46 | const NAMES: &'static [&'static str] = &["describe", "update", "replace", "mutate"]; |
| 47 | } |
| 48 | |
| 49 | #[derive(Deserialize)] |
| 50 | #[serde(deny_unknown_fields)] |
| 51 | struct NoInput {} |
| 52 | |
| 53 | #[derive(Deserialize)] |
| 54 | #[serde(deny_unknown_fields)] |
| 55 | struct PatchInput { |
| 56 | patch: Map<String, Value>, |
| 57 | #[serde(default)] |
| 58 | expected_revision: Option<String>, |
| 59 | } |
| 60 | |
| 61 | #[derive(Deserialize)] |
| 62 | #[serde(deny_unknown_fields)] |
| 63 | struct SectionInput { |
| 64 | value: Map<String, Value>, |
| 65 | #[serde(default)] |
| 66 | expected_revision: Option<String>, |
| 67 | } |
| 68 | |
| 69 | #[derive(Deserialize)] |
| 70 | #[serde(deny_unknown_fields)] |
| 71 | struct OpsInput { |
| 72 | ops: Vec<PathOp>, |
| 73 | #[serde(default)] |
| 74 | expected_revision: Option<String>, |
| 75 | } |
| 76 | |
| 77 | #[derive(Deserialize)] |
| 78 | #[serde(tag = "op", rename_all = "lowercase", deny_unknown_fields)] |
| 79 | enum PathOp { |
| 80 | Set { path: Vec<String>, value: Value }, |
| 81 | Unset { path: Vec<String> }, |
| 82 | } |
| 83 | |
| 84 | enum Change { |
| 85 | Update(Map<String, Value>), |
| 86 | Replace(Map<String, Value>), |
| 87 | Mutate(Vec<PathOp>), |
| 88 | } |
| 89 | |
| 90 | #[derive(Clone)] |
| 91 | pub(super) struct SettingsAuthority { |
| 92 | pub plugin_name: String, |
| 93 | pub roots: BTreeSet<String>, |
| 94 | pub source: Option<PathBuf>, |
| 95 | pub active_revision: Option<String>, |
| 96 | } |
| 97 | |
| 98 | enum Failure { |
| 99 | Invalid(&'static str), |
| 100 | Outside, |
| 101 | Store, |
| 102 | } |
| 103 | |
| 104 | struct Written { |
| 105 | written: bool, |
| 106 | conflict: bool, |
| 107 | revision: String, |
| 108 | roots: Vec<String>, |
| 109 | } |
| 110 | |
| 111 | pub(super) fn serve(call: BrokerCall) -> BrokerFuture { |
| 112 | serve_with(call, None) |
| 113 | } |
| 114 | |
| 115 | pub(super) fn serve_with(call: BrokerCall, authority: Option<SettingsAuthority>) -> BrokerFuture { |
| 116 | Box::pin(async move { |
| 117 | let Some((authority, source)) = authority.and_then(|authority| { |
| 118 | let source = authority.source.clone()?; |
| 119 | (!authority.plugin_name.is_empty() && !authority.roots.is_empty()) |
| 120 | .then_some((authority, source)) |
| 121 | }) else { |
| 122 | return Err(BrokerRefusal::NotAvailable(DshService::Settings)); |
| 123 | }; |
| 124 | if !fits(&call.input, &mut { MAX_INPUT_BYTES }) { |
| 125 | return Err(invalid("the settings input is too large")); |
| 126 | } |
| 127 | let (method_name, change, expected) = match decode::<SettingsMethod>(&call)? { |
| 128 | SettingsMethod::Describe(NoInput {}) => { |
| 129 | let writable = write_refusal(call.context.tool()).is_none(); |
| 130 | let plugin = call.owner.plugin_id.clone(); |
| 131 | let cancel = call.context.cancel().clone(); |
| 132 | call.context |
| 133 | .act("describe", BrokerEffect::Read, Some(&authority.plugin_name)) |
| 134 | .await?; |
| 135 | return describe(plugin, cancel, authority, source, writable).await; |
| 136 | } |
| 137 | SettingsMethod::Update(input) => ( |
| 138 | "update", |
| 139 | Change::Update(input.patch), |
| 140 | input.expected_revision, |
| 141 | ), |
| 142 | SettingsMethod::Replace(input) => ( |
| 143 | "replace", |
| 144 | Change::Replace(input.value), |
| 145 | input.expected_revision, |
| 146 | ), |
| 147 | SettingsMethod::Mutate(input) => { |
| 148 | ("mutate", Change::Mutate(input.ops), input.expected_revision) |
| 149 | } |
| 150 | }; |
| 151 | if let Some(reason) = write_refusal(call.context.tool()) { |
| 152 | tracing::info!(target: LOG, plugin = %call.owner.plugin_id, reason, "settings write refused by the session"); |
| 153 | return Err(refused("settings cannot be changed in this session")); |
| 154 | } |
| 155 | validate_change(&authority.roots, &change).map_err(failure_refusal)?; |
| 156 | call.context |
| 157 | .act( |
| 158 | method_name, |
| 159 | BrokerEffect::Write, |
| 160 | Some(&authority.plugin_name), |
| 161 | ) |
| 162 | .await?; |
| 163 | if let Some(reason) = write_refusal(call.context.tool()) { |
| 164 | tracing::info!(target: LOG, plugin = %call.owner.plugin_id, reason, "settings write refused by the session"); |
| 165 | return Err(refused("settings cannot be changed in this session")); |
| 166 | } |
| 167 | let turn = Arc::clone(&TURN).lock_owned().await; |
| 168 | if call.context.cancel().is_cancelled() { |
| 169 | return Err(refused("the settings call was withdrawn")); |
| 170 | } |
| 171 | let plugin = call.owner.plugin_id.clone(); |
| 172 | let name = authority.plugin_name.clone(); |
| 173 | let outcome = tokio::task::spawn_blocking(move || { |
| 174 | let _turn = turn; |
| 175 | write(&source, &authority, change, expected.as_deref()) |
| 176 | }) |
| 177 | .await; |
| 178 | match outcome { |
| 179 | Ok(Ok(done)) => { |
| 180 | tracing::info!(target: LOG, plugin = %plugin, name = %name, roots = ?done.roots, written = done.written, conflict = done.conflict, "plugin settings write"); |
| 181 | Ok(json!({ |
| 182 | "written": done.written, |
| 183 | "conflict": done.conflict, |
| 184 | "revision": done.revision, |
| 185 | "applies": APPLIES, |
| 186 | })) |
| 187 | } |
| 188 | Ok(Err(failure)) => Err(failure_refusal(failure)), |
| 189 | Err(_) => Err(refused("the settings could not be saved")), |
| 190 | } |
| 191 | }) |
| 192 | } |
| 193 | |
| 194 | async fn describe( |
| 195 | plugin: String, |
| 196 | cancel: CancellationToken, |
| 197 | authority: SettingsAuthority, |
| 198 | source: PathBuf, |
| 199 | writable: bool, |
| 200 | ) -> Result<Value, BrokerRefusal> { |
| 201 | let turn = Arc::clone(&TURN).lock_owned().await; |
| 202 | if cancel.is_cancelled() { |
| 203 | return Err(refused("the settings call was withdrawn")); |
| 204 | } |
| 205 | let name = authority.plugin_name.clone(); |
| 206 | let saved = tokio::task::spawn_blocking(move || { |
| 207 | let _turn = turn; |
| 208 | let settings = codewhale_runtime::config::read_plugin_settings(&source)?; |
| 209 | plugin_config::convert(&name, &settings.get(&name).cloned().unwrap_or_default()) |
| 210 | }) |
| 211 | .await; |
| 212 | let saved = match saved { |
| 213 | Ok(Ok(saved)) => saved, |
| 214 | Ok(Err(reason)) => { |
| 215 | tracing::warn!(target: LOG, plugin = %plugin, reason = %reason, "plugin settings could not be read"); |
| 216 | return Err(refused("the settings could not be read")); |
| 217 | } |
| 218 | Err(_) => return Err(refused("the settings could not be read")), |
| 219 | }; |
| 220 | let value: Map<String, Value> = saved |
| 221 | .value |
| 222 | .as_object() |
| 223 | .into_iter() |
| 224 | .flatten() |
| 225 | .filter(|(key, _)| authority.roots.contains(*key)) |
| 226 | .map(|(key, value)| (key.clone(), value.clone())) |
| 227 | .collect(); |
| 228 | Ok(json!({ |
| 229 | "ns": authority.plugin_name, |
| 230 | "writable": writable, |
| 231 | "roots": authority.roots, |
| 232 | "value": value, |
| 233 | "revision": saved.hash, |
| 234 | "applied": authority.active_revision.as_ref().map(|active| *active == saved.hash), |
| 235 | "applies": APPLIES, |
| 236 | })) |
| 237 | } |
| 238 | |
| 239 | fn invalid(message: &str) -> BrokerRefusal { |
| 240 | BrokerRefusal::InvalidInput { |
| 241 | service: DshService::Settings, |
| 242 | message: message.into(), |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | fn refused(message: &str) -> BrokerRefusal { |
| 247 | BrokerRefusal::Refused { |
| 248 | service: DshService::Settings, |
| 249 | message: message.into(), |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | fn failure_refusal(failure: Failure) -> BrokerRefusal { |
| 254 | match failure { |
| 255 | Failure::Invalid(message) => invalid(message), |
| 256 | Failure::Outside => refused("that setting is outside this plugin's reviewed settings"), |
| 257 | Failure::Store => refused("the settings could not be saved"), |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | fn write_refusal(context: &ToolContext) -> Option<&'static str> { |
| 262 | let mut tool = context.clone(); |
| 263 | let _ = tool.refresh_live_posture(); |
| 264 | if tool.child_host.is_some() || tool.owner_agent_id.is_some() { |
| 265 | return Some("the caller is a child agent"); |
| 266 | } |
| 267 | if tool.tool_authority.is_some() { |
| 268 | return Some("the caller is a worker under an authority envelope"); |
| 269 | } |
| 270 | if matches!(tool.approval_mode, ApprovalMode::Never | ApprovalMode::Auto) { |
| 271 | return Some("the approval posture refuses plugin writes"); |
| 272 | } |
| 273 | match tool.elevated_sandbox_policy { |
| 274 | None => Some("the session has no posture"), |
| 275 | Some(SandboxPolicy::ReadOnly { .. }) => Some("the session is read-only"), |
| 276 | Some(_) => None, |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | fn fits(value: &Value, budget: &mut usize) -> bool { |
| 281 | let cost = match value { |
| 282 | Value::String(text) => text.len() + 2, |
| 283 | Value::Array(items) => { |
| 284 | if !items.iter().all(|item| fits(item, budget)) { |
| 285 | return false; |
| 286 | } |
| 287 | 2 |
| 288 | } |
| 289 | Value::Object(map) => { |
| 290 | for (key, item) in map { |
| 291 | if !fits(item, budget) { |
| 292 | return false; |
| 293 | } |
| 294 | let Some(left) = budget.checked_sub(key.len() + 3) else { |
| 295 | return false; |
| 296 | }; |
| 297 | *budget = left; |
| 298 | } |
| 299 | 2 |
| 300 | } |
| 301 | _ => 8, |
| 302 | }; |
| 303 | match budget.checked_sub(cost) { |
| 304 | Some(left) => { |
| 305 | *budget = left; |
| 306 | true |
| 307 | } |
| 308 | None => false, |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | fn key_ok(key: &str) -> bool { |
| 313 | !key.is_empty() |
| 314 | && key.chars().count() <= MAX_KEY_CHARS |
| 315 | && !key.chars().any(char::is_control) |
| 316 | && key != plugin_config::TOML_DATETIME_KEY |
| 317 | } |
| 318 | |
| 319 | fn storable(value: &Value) -> bool { |
| 320 | match value { |
| 321 | Value::Null => false, |
| 322 | Value::Number(number) => number.is_i64() || number.is_f64(), |
| 323 | Value::Array(items) => items.iter().all(storable), |
| 324 | Value::Object(map) => map.iter().all(|(key, item)| key_ok(key) && storable(item)), |
| 325 | Value::Bool(_) | Value::String(_) => true, |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | fn merge(under: Option<Value>, over: Value) -> Value { |
| 330 | match (under, over) { |
| 331 | (Some(Value::Object(mut under)), Value::Object(over)) => { |
| 332 | for (key, value) in over { |
| 333 | let merged = merge(under.remove(&key), value); |
| 334 | under.insert(key, merged); |
| 335 | } |
| 336 | Value::Object(under) |
| 337 | } |
| 338 | (_, over) => over, |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | fn reviewed<'a>( |
| 343 | roots: &BTreeSet<String>, |
| 344 | mut keys: impl Iterator<Item = &'a String>, |
| 345 | ) -> Result<(), Failure> { |
| 346 | if keys.all(|key| roots.contains(key)) { |
| 347 | Ok(()) |
| 348 | } else { |
| 349 | Err(Failure::Outside) |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | fn set_at(section: &mut Map<String, Value>, path: &[String], value: Value) -> Result<(), Failure> { |
| 354 | let Some((key, rest)) = path.split_first() else { |
| 355 | return Err(Failure::Invalid("a settings path names at least one key")); |
| 356 | }; |
| 357 | if rest.is_empty() { |
| 358 | section.insert(key.clone(), value); |
| 359 | return Ok(()); |
| 360 | } |
| 361 | match section |
| 362 | .entry(key.clone()) |
| 363 | .or_insert_with(|| Value::Object(Map::new())) |
| 364 | { |
| 365 | Value::Object(inner) => set_at(inner, rest, value), |
| 366 | _ => Err(Failure::Invalid( |
| 367 | "a settings path may only pass through tables", |
| 368 | )), |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | fn unset_at(section: &mut Map<String, Value>, path: &[String]) { |
| 373 | match path { |
| 374 | [] => {} |
| 375 | [key] => { |
| 376 | section.remove(key); |
| 377 | } |
| 378 | [key, rest @ ..] => { |
| 379 | if let Some(Value::Object(inner)) = section.get_mut(key) { |
| 380 | unset_at(inner, rest); |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | fn validate_change(roots: &BTreeSet<String>, change: &Change) -> Result<(), Failure> { |
| 387 | let valid_map = |map: &Map<String, Value>| { |
| 388 | reviewed(roots, map.keys())?; |
| 389 | if map |
| 390 | .iter() |
| 391 | .all(|(key, value)| key_ok(key) && storable(value)) |
| 392 | { |
| 393 | Ok(()) |
| 394 | } else { |
| 395 | Err(Failure::Invalid( |
| 396 | "settings hold strings, finite numbers, booleans, arrays and tables under plain keys", |
| 397 | )) |
| 398 | } |
| 399 | }; |
| 400 | match change { |
| 401 | Change::Update(patch) => valid_map(patch), |
| 402 | Change::Replace(section) => valid_map(section), |
| 403 | Change::Mutate(ops) => { |
| 404 | if ops.len() > MAX_OPS { |
| 405 | return Err(Failure::Invalid("too many settings edits in one call")); |
| 406 | } |
| 407 | for op in ops { |
| 408 | let (PathOp::Set { path, .. } | PathOp::Unset { path }) = op; |
| 409 | if path.is_empty() || path.len() > MAX_PATH_DEPTH { |
| 410 | return Err(Failure::Invalid("a settings path names 1 to 16 keys")); |
| 411 | } |
| 412 | reviewed(roots, path.iter().take(1))?; |
| 413 | if !path.iter().all(|key| key_ok(key)) { |
| 414 | return Err(Failure::Invalid( |
| 415 | "settings hold strings, finite numbers, booleans, arrays and tables under plain keys", |
| 416 | )); |
| 417 | } |
| 418 | if let PathOp::Set { value, .. } = op |
| 419 | && !storable(value) |
| 420 | { |
| 421 | return Err(Failure::Invalid( |
| 422 | "settings hold strings, finite numbers, booleans, arrays and tables under plain keys", |
| 423 | )); |
| 424 | } |
| 425 | } |
| 426 | Ok(()) |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | fn next_config( |
| 432 | current: &Value, |
| 433 | roots: &BTreeSet<String>, |
| 434 | change: Change, |
| 435 | ) -> Result<Map<String, Value>, Failure> { |
| 436 | validate_change(roots, &change)?; |
| 437 | let mut next = current.as_object().cloned().unwrap_or_default(); |
| 438 | match change { |
| 439 | Change::Update(patch) => { |
| 440 | for (key, value) in patch { |
| 441 | let merged = merge(next.remove(&key), value); |
| 442 | next.insert(key, merged); |
| 443 | } |
| 444 | } |
| 445 | Change::Replace(section) => { |
| 446 | next.retain(|key, _| !roots.contains(key)); |
| 447 | next.extend(section); |
| 448 | } |
| 449 | Change::Mutate(ops) => { |
| 450 | for op in ops { |
| 451 | match op { |
| 452 | PathOp::Set { path, value } => set_at(&mut next, &path, value)?, |
| 453 | PathOp::Unset { path } => unset_at(&mut next, &path), |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | let touched = next |
| 459 | .iter() |
| 460 | .filter(|(key, value)| roots.contains(*key) && current.get(key.as_str()) != Some(*value)); |
| 461 | for (key, value) in touched { |
| 462 | if !key_ok(key) || !storable(value) { |
| 463 | return Err(Failure::Invalid( |
| 464 | "settings hold strings, finite numbers, booleans, arrays and tables under plain keys", |
| 465 | )); |
| 466 | } |
| 467 | } |
| 468 | Ok(next) |
| 469 | } |
| 470 | |
| 471 | fn edit_value(value: &Value) -> Option<toml_edit::Value> { |
| 472 | Some(match value { |
| 473 | Value::Null => return None, |
| 474 | Value::Bool(flag) => (*flag).into(), |
| 475 | Value::Number(number) => match number.as_i64() { |
| 476 | Some(integer) => integer.into(), |
| 477 | None if number.is_f64() => number.as_f64()?.into(), |
| 478 | None => return None, |
| 479 | }, |
| 480 | Value::String(text) => text.as_str().into(), |
| 481 | Value::Array(items) => toml_edit::Value::Array( |
| 482 | items |
| 483 | .iter() |
| 484 | .map(edit_value) |
| 485 | .collect::<Option<toml_edit::Array>>()?, |
| 486 | ), |
| 487 | Value::Object(map) => { |
| 488 | let mut table = toml_edit::InlineTable::new(); |
| 489 | for (key, item) in map { |
| 490 | table.insert(key.as_str(), edit_value(item)?); |
| 491 | } |
| 492 | toml_edit::Value::InlineTable(table) |
| 493 | } |
| 494 | }) |
| 495 | } |
| 496 | |
| 497 | fn store( |
| 498 | doc: &mut toml_edit::DocumentMut, |
| 499 | path: &mut Vec<String>, |
| 500 | before: Option<&Value>, |
| 501 | after: Option<&Value>, |
| 502 | ) -> anyhow::Result<()> { |
| 503 | match (before, after) { |
| 504 | (Some(before), Some(after)) if before == after => Ok(()), |
| 505 | (Some(Value::Object(before)), Some(Value::Object(after))) => { |
| 506 | let added = after.keys().filter(|key| !before.contains_key(*key)); |
| 507 | for key in before.keys().chain(added) { |
| 508 | path.push(key.clone()); |
| 509 | store(doc, path, before.get(key), after.get(key))?; |
| 510 | path.pop(); |
| 511 | } |
| 512 | Ok(()) |
| 513 | } |
| 514 | (_, Some(after)) => { |
| 515 | let value = edit_value(after) |
| 516 | .ok_or_else(|| anyhow::anyhow!("a settings value is not representable"))?; |
| 517 | let segments: Vec<&str> = path.iter().map(String::as_str).collect(); |
| 518 | set_document_value(doc, &segments, value) |
| 519 | } |
| 520 | (Some(_), None) => { |
| 521 | let segments: Vec<&str> = path.iter().map(String::as_str).collect(); |
| 522 | unset_document_value(doc, &segments).map(|_| ()) |
| 523 | } |
| 524 | (None, None) => Ok(()), |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | fn saved(doc: &toml_edit::DocumentMut, name: &str) -> Result<PluginConfig, String> { |
| 529 | let table: toml::Table = |
| 530 | toml::from_str(&doc.to_string()).map_err(|_| "the edited config does not parse")?; |
| 531 | let config = match table |
| 532 | .get("plugins") |
| 533 | .and_then(|plugins| plugins.get(name)) |
| 534 | .and_then(|plugin| plugin.get("config")) |
| 535 | { |
| 536 | None => None, |
| 537 | Some(toml::Value::Table(config)) => Some(config.clone()), |
| 538 | Some(_) => return Err(format!("plugin `{name}` config is not a table")), |
| 539 | }; |
| 540 | plugin_config::convert(name, &PluginSettings { config }) |
| 541 | } |
| 542 | |
| 543 | fn write( |
| 544 | source: &Path, |
| 545 | authority: &SettingsAuthority, |
| 546 | change: Change, |
| 547 | expected: Option<&str>, |
| 548 | ) -> Result<Written, Failure> { |
| 549 | let name = authority.plugin_name.as_str(); |
| 550 | let mut outcome: Result<Written, Failure> = Err(Failure::Store); |
| 551 | let stored = mutate_config_document(source, |doc| { |
| 552 | let current = saved(doc, name).map_err(anyhow::Error::msg)?; |
| 553 | if expected.is_some_and(|expected| expected != current.hash) { |
| 554 | outcome = Ok(Written { |
| 555 | written: false, |
| 556 | conflict: true, |
| 557 | revision: current.hash, |
| 558 | roots: Vec::new(), |
| 559 | }); |
| 560 | return Ok(()); |
| 561 | } |
| 562 | let next = match next_config(¤t.value, &authority.roots, change) { |
| 563 | Ok(next) => Value::Object(next), |
| 564 | Err(failure) => { |
| 565 | outcome = Err(failure); |
| 566 | anyhow::bail!("the settings change was refused"); |
| 567 | } |
| 568 | }; |
| 569 | let roots: Vec<String> = authority |
| 570 | .roots |
| 571 | .iter() |
| 572 | .filter(|root| current.value.get(root.as_str()) != next.get(root.as_str())) |
| 573 | .cloned() |
| 574 | .collect(); |
| 575 | if roots.is_empty() { |
| 576 | outcome = Ok(Written { |
| 577 | written: false, |
| 578 | conflict: false, |
| 579 | revision: current.hash, |
| 580 | roots, |
| 581 | }); |
| 582 | return Ok(()); |
| 583 | } |
| 584 | let mut path = vec!["plugins".to_string(), name.to_string(), "config".into()]; |
| 585 | store(doc, &mut path, Some(¤t.value), Some(&next))?; |
| 586 | match saved(doc, name) { |
| 587 | Ok(after) if after.value == next => { |
| 588 | outcome = Ok(Written { |
| 589 | written: true, |
| 590 | conflict: false, |
| 591 | revision: after.hash, |
| 592 | roots, |
| 593 | }); |
| 594 | Ok(()) |
| 595 | } |
| 596 | Ok(_) => anyhow::bail!("the stored settings differ from the requested ones"), |
| 597 | Err(reason) => { |
| 598 | outcome = Err(Failure::Invalid( |
| 599 | "the settings would not be a valid plugin configuration", |
| 600 | )); |
| 601 | anyhow::bail!(reason) |
| 602 | } |
| 603 | } |
| 604 | }); |
| 605 | match stored { |
| 606 | Ok(()) => outcome, |
| 607 | Err(error) => { |
| 608 | tracing::warn!(target: LOG, name = %name, error = %error, "plugin settings were not saved"); |
| 609 | Err(match outcome { |
| 610 | Err(failure) => failure, |
| 611 | Ok(_) => Failure::Store, |
| 612 | }) |
| 613 | } |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 618 | pub struct PluginSettingsSnapshot { |
| 619 | pub value: Map<String, Value>, |
| 620 | pub revision: String, |
| 621 | pub writable: bool, |
| 622 | } |
| 623 | |
| 624 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 625 | pub struct PluginSettingsWriteOutcome { |
| 626 | pub written: bool, |
| 627 | pub conflict: bool, |
| 628 | pub revision: String, |
| 629 | } |
| 630 | |
| 631 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 632 | pub enum PluginSettingsError { |
| 633 | Invalid(&'static str), |
| 634 | Store, |
| 635 | } |
| 636 | |
| 637 | fn depth_ok(value: &Value, depth: usize) -> bool { |
| 638 | if depth > MAX_PATH_DEPTH { |
| 639 | return false; |
| 640 | } |
| 641 | match value { |
| 642 | Value::Object(map) => map.values().all(|item| depth_ok(item, depth + 1)), |
| 643 | Value::Array(items) => items.iter().all(|item| depth_ok(item, depth + 1)), |
| 644 | _ => true, |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | pub async fn read_plugin_config_settings( |
| 649 | source: PathBuf, |
| 650 | plugin_name: String, |
| 651 | ) -> Result<PluginSettingsSnapshot, PluginSettingsError> { |
| 652 | if !key_ok(&plugin_name) { |
| 653 | return Err(PluginSettingsError::Invalid("invalid plugin name")); |
| 654 | } |
| 655 | let turn = Arc::clone(&TURN).lock_owned().await; |
| 656 | let saved = tokio::task::spawn_blocking(move || { |
| 657 | let _turn = turn; |
| 658 | let settings = codewhale_runtime::config::read_plugin_settings(&source)?; |
| 659 | plugin_config::convert( |
| 660 | &plugin_name, |
| 661 | &settings.get(&plugin_name).cloned().unwrap_or_default(), |
| 662 | ) |
| 663 | }) |
| 664 | .await |
| 665 | .map_err(|_| PluginSettingsError::Store)? |
| 666 | .map_err(|_| PluginSettingsError::Store)?; |
| 667 | let value = saved.value.as_object().cloned().unwrap_or_default(); |
| 668 | Ok(PluginSettingsSnapshot { |
| 669 | value, |
| 670 | revision: saved.hash, |
| 671 | writable: true, |
| 672 | }) |
| 673 | } |
| 674 | |
| 675 | pub async fn write_plugin_config_settings( |
| 676 | source: PathBuf, |
| 677 | plugin_name: String, |
| 678 | value: Map<String, Value>, |
| 679 | expected_revision: Option<String>, |
| 680 | ) -> Result<PluginSettingsWriteOutcome, PluginSettingsError> { |
| 681 | if !key_ok(&plugin_name) { |
| 682 | return Err(PluginSettingsError::Invalid("invalid plugin name")); |
| 683 | } |
| 684 | let next_value = Value::Object(value); |
| 685 | if !fits(&next_value, &mut { MAX_INPUT_BYTES }) { |
| 686 | return Err(PluginSettingsError::Invalid( |
| 687 | "the settings input is too large", |
| 688 | )); |
| 689 | } |
| 690 | if !storable(&next_value) { |
| 691 | return Err(PluginSettingsError::Invalid( |
| 692 | "settings hold strings, finite numbers, booleans, arrays and tables under plain keys", |
| 693 | )); |
| 694 | } |
| 695 | if !depth_ok(&next_value, 0) { |
| 696 | return Err(PluginSettingsError::Invalid( |
| 697 | "settings nesting exceeds the maximum depth of 16", |
| 698 | )); |
| 699 | } |
| 700 | let turn = Arc::clone(&TURN).lock_owned().await; |
| 701 | tokio::task::spawn_blocking(move || { |
| 702 | let _turn = turn; |
| 703 | let mut result: Result<PluginSettingsWriteOutcome, PluginSettingsError> = |
| 704 | Err(PluginSettingsError::Store); |
| 705 | let stored = mutate_config_document(&source, |doc| { |
| 706 | let current = saved(doc, &plugin_name).map_err(anyhow::Error::msg)?; |
| 707 | if expected_revision |
| 708 | .as_deref() |
| 709 | .is_some_and(|expected| expected != current.hash) |
| 710 | { |
| 711 | result = Ok(PluginSettingsWriteOutcome { |
| 712 | written: false, |
| 713 | conflict: true, |
| 714 | revision: current.hash, |
| 715 | }); |
| 716 | return Ok(()); |
| 717 | } |
| 718 | if current.value == next_value { |
| 719 | result = Ok(PluginSettingsWriteOutcome { |
| 720 | written: false, |
| 721 | conflict: false, |
| 722 | revision: current.hash, |
| 723 | }); |
| 724 | return Ok(()); |
| 725 | } |
| 726 | let mut path = vec!["plugins".to_string(), plugin_name.clone(), "config".into()]; |
| 727 | store(doc, &mut path, Some(¤t.value), Some(&next_value))?; |
| 728 | match saved(doc, &plugin_name) { |
| 729 | Ok(after) if after.value == next_value => { |
| 730 | result = Ok(PluginSettingsWriteOutcome { |
| 731 | written: true, |
| 732 | conflict: false, |
| 733 | revision: after.hash, |
| 734 | }); |
| 735 | Ok(()) |
| 736 | } |
| 737 | Ok(_) => anyhow::bail!("the stored settings differ from the requested ones"), |
| 738 | Err(reason) => { |
| 739 | result = Err(PluginSettingsError::Invalid( |
| 740 | "the settings would not be a valid plugin configuration", |
| 741 | )); |
| 742 | anyhow::bail!(reason) |
| 743 | } |
| 744 | } |
| 745 | }); |
| 746 | match stored { |
| 747 | Ok(()) => result, |
| 748 | Err(error) => { |
| 749 | tracing::warn!(target: LOG, error = %error, "plugin settings were not saved"); |
| 750 | Err(match result { |
| 751 | Err(err) => err, |
| 752 | Ok(_) => PluginSettingsError::Store, |
| 753 | }) |
| 754 | } |
| 755 | } |
| 756 | }) |
| 757 | .await |
| 758 | .map_err(|_| PluginSettingsError::Store)? |
| 759 | } |
| 760 | |
| 761 | #[cfg(test)] |
| 762 | mod tests { |
| 763 | use std::cell::RefCell; |
| 764 | |
| 765 | use codewhale_config::OwnerRef; |
| 766 | use codewhale_runtime::config::read_plugin_settings; |
| 767 | |
| 768 | use super::super::core_call::InvocationGuard; |
| 769 | use super::super::dsh_broker::{Arm, BrokerActTool, TABLE, TestGrants}; |
| 770 | use super::super::plugin_config::{PluginConfigs, activation_hash}; |
| 771 | use super::super::protocol::{DshBrokerParams, RpcErrorWire, error_code}; |
| 772 | use super::super::supervisor::HostRequestContext; |
| 773 | use super::super::test_support::fake_authority; |
| 774 | use super::super::{ExtensionHostManager, ExtensionHostOptions, HostCohort}; |
| 775 | use super::*; |
| 776 | use crate::core::engine::LivePosture; |
| 777 | use crate::tools::codemode::{ |
| 778 | ExtensionCaller, NestedCallGate, NestedCallVerdict, NestedDecision, |
| 779 | }; |
| 780 | use crate::tools::spec::{ |
| 781 | ToolAuthorityEnvelope, ToolError, ToolMutationAuthority, ToolShellAuthority, |
| 782 | ToolVerificationAuthority, |
| 783 | }; |
| 784 | |
| 785 | const NAME: &str = "fixture.plugin"; |
| 786 | const BEFORE: &str = r#"# the person's own notes stay |
| 787 | allow_shell = true |
| 788 | |
| 789 | [plugins."fixture.plugin".config] |
| 790 | model = "small" # chosen by hand |
| 791 | internal = "kept" |
| 792 | |
| 793 | [plugins."fixture.plugin".config.limits] |
| 794 | # a comment inside a reviewed table |
| 795 | max = 3 |
| 796 | burst = 9 |
| 797 | |
| 798 | [plugins.other.config] |
| 799 | model = "theirs" |
| 800 | "#; |
| 801 | |
| 802 | thread_local! { |
| 803 | static AUTHORITY: RefCell<Option<SettingsAuthority>> = const { RefCell::new(None) }; |
| 804 | } |
| 805 | |
| 806 | fn granted_arm(call: BrokerCall) -> BrokerFuture { |
| 807 | serve_with(call, AUTHORITY.with(|authority| authority.borrow().clone())) |
| 808 | } |
| 809 | |
| 810 | const GRANTED: &[(DshService, Arm)] = &[(DshService::Settings, granted_arm as Arm)]; |
| 811 | |
| 812 | struct Fixture { |
| 813 | manager: ExtensionHostManager, |
| 814 | owner: OwnerRef, |
| 815 | other: OwnerRef, |
| 816 | context: ToolContext, |
| 817 | gate: NestedCallGate, |
| 818 | posture: LivePosture, |
| 819 | dir: tempfile::TempDir, |
| 820 | _grants: TestGrants, |
| 821 | } |
| 822 | |
| 823 | impl Fixture { |
| 824 | fn new() -> Self { |
| 825 | let grants = TestGrants::only(&[DshService::Settings, DshService::Workspace]); |
| 826 | let manager = ExtensionHostManager::new(ExtensionHostOptions::default()); |
| 827 | let (owner, other) = { |
| 828 | let mut registry = manager.shared.registry.lock().unwrap(); |
| 829 | let mut begin = |id: &str| { |
| 830 | let owner = registry |
| 831 | .begin_owner( |
| 832 | HostCohort::reviewed(), |
| 833 | id, |
| 834 | id, |
| 835 | Some(fake_authority(id)), |
| 836 | "hash", |
| 837 | ) |
| 838 | .unwrap(); |
| 839 | registry.mark_active(&owner); |
| 840 | owner |
| 841 | }; |
| 842 | (begin("a"), begin("b")) |
| 843 | }; |
| 844 | let dir = tempfile::tempdir().unwrap(); |
| 845 | std::fs::write(dir.path().join("config.toml"), BEFORE).unwrap(); |
| 846 | let posture = LivePosture::for_tests(dir.path(), ApprovalMode::Suggest); |
| 847 | let mut fixture = Self { |
| 848 | manager, |
| 849 | owner, |
| 850 | other, |
| 851 | context: ToolContext::new(dir.path()), |
| 852 | gate: NestedCallGate::admitting_for_test().for_extension( |
| 853 | ExtensionCaller { |
| 854 | origin: "extension:a".to_string(), |
| 855 | tool: "a_tool".to_string(), |
| 856 | scope: "ext:a@hash".to_string(), |
| 857 | }, |
| 858 | BrokerActTool::all().to_vec(), |
| 859 | ), |
| 860 | posture, |
| 861 | dir, |
| 862 | _grants: grants, |
| 863 | }; |
| 864 | fixture.context.live_posture = Some(fixture.posture.clone()); |
| 865 | fixture.in_session("settings-session-a"); |
| 866 | fixture.authorize(&["model", "limits"]); |
| 867 | fixture |
| 868 | } |
| 869 | |
| 870 | fn path(&self) -> PathBuf { |
| 871 | self.dir.path().join("config.toml") |
| 872 | } |
| 873 | |
| 874 | fn text(&self) -> String { |
| 875 | std::fs::read_to_string(self.path()).unwrap() |
| 876 | } |
| 877 | |
| 878 | fn active(&self) -> PluginConfigs { |
| 879 | let mut configs = PluginConfigs::default(); |
| 880 | configs.replace(&read_plugin_settings(&self.path()).unwrap(), None); |
| 881 | configs |
| 882 | } |
| 883 | |
| 884 | fn authorize(&self, roots: &[&str]) { |
| 885 | let active = activation_hash(&self.active().select(NAME)); |
| 886 | AUTHORITY.with(|authority| { |
| 887 | *authority.borrow_mut() = Some(SettingsAuthority { |
| 888 | plugin_name: NAME.into(), |
| 889 | roots: roots.iter().map(|root| (*root).to_string()).collect(), |
| 890 | source: Some(self.path()), |
| 891 | active_revision: Some(active), |
| 892 | }); |
| 893 | }); |
| 894 | } |
| 895 | |
| 896 | fn in_session(&mut self, session: &str) { |
| 897 | self.context = self |
| 898 | .context |
| 899 | .clone() |
| 900 | .with_session_objects(crate::rlm::session::SessionObjectSnapshot::new( |
| 901 | session.into(), |
| 902 | "fixture-model".into(), |
| 903 | self.context.workspace.clone(), |
| 904 | None, |
| 905 | Arc::new(Vec::new()), |
| 906 | )) |
| 907 | .with_origin_turn_id("settings-turn"); |
| 908 | } |
| 909 | |
| 910 | fn begin(&self) -> InvocationGuard { |
| 911 | self.manager |
| 912 | .shared |
| 913 | .core_calls |
| 914 | .begin( |
| 915 | HostCohort::reviewed(), |
| 916 | 7, |
| 917 | &self.owner, |
| 918 | "call-1", |
| 919 | self.gate.extension().unwrap().0, |
| 920 | &self.context, |
| 921 | &self.gate, |
| 922 | ) |
| 923 | .expect("an invocation") |
| 924 | } |
| 925 | |
| 926 | async fn broker( |
| 927 | &self, |
| 928 | table: &[(DshService, Arm)], |
| 929 | owner: &OwnerRef, |
| 930 | ticket: &str, |
| 931 | method: &str, |
| 932 | input: Value, |
| 933 | ) -> Result<Value, RpcErrorWire> { |
| 934 | let (cx, _violations, _cancel) = HostRequestContext::for_test(40); |
| 935 | self.broker_in(cx, table, owner, ticket, method, input) |
| 936 | .await |
| 937 | } |
| 938 | |
| 939 | async fn broker_in( |
| 940 | &self, |
| 941 | cx: HostRequestContext, |
| 942 | table: &[(DshService, Arm)], |
| 943 | owner: &OwnerRef, |
| 944 | ticket: &str, |
| 945 | method: &str, |
| 946 | input: Value, |
| 947 | ) -> Result<Value, RpcErrorWire> { |
| 948 | self.manager |
| 949 | .shared |
| 950 | .core_calls |
| 951 | .serve_broker_in( |
| 952 | table, |
| 953 | &self.manager.shared, |
| 954 | HostCohort::reviewed(), |
| 955 | 7, |
| 956 | DshBrokerParams { |
| 957 | owner: owner.clone(), |
| 958 | ticket: ticket.to_string(), |
| 959 | service: "settings".to_string(), |
| 960 | method: method.to_string(), |
| 961 | input, |
| 962 | }, |
| 963 | cx, |
| 964 | ) |
| 965 | .await |
| 966 | } |
| 967 | |
| 968 | async fn call( |
| 969 | &self, |
| 970 | ticket: &str, |
| 971 | method: &str, |
| 972 | input: Value, |
| 973 | ) -> Result<Value, RpcErrorWire> { |
| 974 | self.broker(GRANTED, &self.owner, ticket, method, input) |
| 975 | .await |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | fn ticket(guard: &InvocationGuard, service: &str) -> String { |
| 980 | guard |
| 981 | .broker_tickets() |
| 982 | .unwrap() |
| 983 | .into_iter() |
| 984 | .find(|wire| wire.service == service) |
| 985 | .unwrap() |
| 986 | .ticket |
| 987 | } |
| 988 | |
| 989 | fn refusal(result: &Result<Value, RpcErrorWire>) -> (i64, String) { |
| 990 | let error = result.as_ref().expect_err("a refusal"); |
| 991 | let code = error |
| 992 | .data |
| 993 | .as_ref() |
| 994 | .and_then(|data| data["dsh_refusal"].as_str()) |
| 995 | .unwrap_or_else(|| panic!("untyped refusal: {error:?}")) |
| 996 | .to_string(); |
| 997 | (error.code, code) |
| 998 | } |
| 999 | |
| 1000 | fn ticket_refused() -> (i64, String) { |
| 1001 | (error_code::REFUSED, "ticket_refused".into()) |
| 1002 | } |
| 1003 | |
| 1004 | fn policy_refused() -> (i64, String) { |
| 1005 | (error_code::REFUSED, "refused".into()) |
| 1006 | } |
| 1007 | |
| 1008 | #[tokio::test] |
| 1009 | async fn settings_are_read_edited_applied_at_restart_and_refused_after_revocation() { |
| 1010 | let f = Fixture::new(); |
| 1011 | let guard = f.begin(); |
| 1012 | let settings = ticket(&guard, "settings"); |
| 1013 | let boot = f.active().select(NAME).unwrap(); |
| 1014 | |
| 1015 | let read = f.call(&settings, "describe", json!({})).await.unwrap(); |
| 1016 | assert_eq!(read["ns"], NAME); |
| 1017 | assert_eq!(read["roots"], json!(["limits", "model"])); |
| 1018 | assert_eq!( |
| 1019 | read["value"], |
| 1020 | json!({"model": "small", "limits": {"max": 3, "burst": 9}}), |
| 1021 | "only the reviewed roots are shown" |
| 1022 | ); |
| 1023 | assert_eq!(read["revision"], boot.hash.as_str()); |
| 1024 | assert_eq!(read["applied"], true); |
| 1025 | assert_eq!(read["applies"], "reload"); |
| 1026 | assert_eq!(read["writable"], true); |
| 1027 | |
| 1028 | let edit = f |
| 1029 | .call( |
| 1030 | &settings, |
| 1031 | "update", |
| 1032 | json!({ |
| 1033 | "patch": {"model": "large", "limits": {"max": 5}}, |
| 1034 | "expected_revision": boot.hash, |
| 1035 | }), |
| 1036 | ) |
| 1037 | .await |
| 1038 | .unwrap(); |
| 1039 | assert_eq!(edit["written"], true); |
| 1040 | assert_eq!(edit["conflict"], false); |
| 1041 | assert_eq!(edit["applies"], "reload"); |
| 1042 | let text = f.text(); |
| 1043 | for kept in [ |
| 1044 | "# the person's own notes stay", |
| 1045 | "allow_shell = true", |
| 1046 | "# chosen by hand", |
| 1047 | "internal = \"kept\"", |
| 1048 | "# a comment inside a reviewed table", |
| 1049 | "burst = 9", |
| 1050 | "[plugins.other.config]\nmodel = \"theirs\"", |
| 1051 | ] { |
| 1052 | assert!(text.contains(kept), "{kept:?} survives in:\n{text}"); |
| 1053 | } |
| 1054 | assert!(text.contains("model = \"large\""), "{text}"); |
| 1055 | assert!(text.contains("max = 5"), "{text}"); |
| 1056 | |
| 1057 | let pending = f.call(&settings, "describe", json!({})).await.unwrap(); |
| 1058 | assert_eq!(pending["revision"], edit["revision"]); |
| 1059 | assert_eq!( |
| 1060 | pending["applied"], false, |
| 1061 | "the running plugin still has the old config" |
| 1062 | ); |
| 1063 | assert_eq!(pending["value"]["model"], "large"); |
| 1064 | assert_eq!(pending["value"]["limits"], json!({"max": 5, "burst": 9})); |
| 1065 | |
| 1066 | let restarted = f.active().select(NAME); |
| 1067 | assert_ne!( |
| 1068 | activation_hash(&restarted), |
| 1069 | boot.hash, |
| 1070 | "a reload re-activates the plugin" |
| 1071 | ); |
| 1072 | let restarted = restarted.unwrap(); |
| 1073 | assert_eq!(restarted.hash, edit["revision"].as_str().unwrap()); |
| 1074 | assert_eq!(restarted.value["model"], "large"); |
| 1075 | assert_eq!(restarted.value["internal"], "kept"); |
| 1076 | f.authorize(&["model", "limits"]); |
| 1077 | let applied = f.call(&settings, "describe", json!({})).await.unwrap(); |
| 1078 | assert_eq!(applied["applied"], true); |
| 1079 | |
| 1080 | let stale = f |
| 1081 | .call( |
| 1082 | &settings, |
| 1083 | "update", |
| 1084 | json!({"patch": {"model": "stale"}, "expected_revision": boot.hash}), |
| 1085 | ) |
| 1086 | .await |
| 1087 | .unwrap(); |
| 1088 | assert_eq!(stale["written"], false); |
| 1089 | assert_eq!(stale["conflict"], true); |
| 1090 | assert_eq!(stale["revision"], edit["revision"]); |
| 1091 | assert_eq!(f.text(), text, "a stale edit writes nothing"); |
| 1092 | |
| 1093 | let ops = f |
| 1094 | .call( |
| 1095 | &settings, |
| 1096 | "mutate", |
| 1097 | json!({"ops": [ |
| 1098 | {"op": "set", "path": ["limits", "window", "seconds"], "value": 30}, |
| 1099 | {"op": "unset", "path": ["limits", "burst"]}, |
| 1100 | ]}), |
| 1101 | ) |
| 1102 | .await |
| 1103 | .unwrap(); |
| 1104 | assert_eq!(ops["written"], true); |
| 1105 | let replaced = f |
| 1106 | .call(&settings, "replace", json!({"value": {"model": "tiny"}})) |
| 1107 | .await |
| 1108 | .unwrap(); |
| 1109 | assert_eq!(replaced["written"], true); |
| 1110 | let last = f.active().select(NAME).unwrap(); |
| 1111 | assert_eq!( |
| 1112 | last.value, |
| 1113 | json!({"model": "tiny", "internal": "kept"}), |
| 1114 | "replace resets the reviewed roots and keeps the rest" |
| 1115 | ); |
| 1116 | let same = f |
| 1117 | .call(&settings, "replace", json!({"value": {"model": "tiny"}})) |
| 1118 | .await |
| 1119 | .unwrap(); |
| 1120 | assert_eq!(same["written"], false); |
| 1121 | assert_eq!(same["revision"], last.hash.as_str()); |
| 1122 | |
| 1123 | let text = f.text(); |
| 1124 | f.manager.shared.core_calls.revoke_owner("a"); |
| 1125 | let revoked = f |
| 1126 | .call(&settings, "update", json!({"patch": {"model": "after"}})) |
| 1127 | .await; |
| 1128 | assert_eq!(refusal(&revoked), ticket_refused()); |
| 1129 | let unread = f.call(&settings, "describe", json!({})).await; |
| 1130 | assert_eq!(refusal(&unread), ticket_refused()); |
| 1131 | assert_eq!(f.text(), text, "a revoked plugin writes nothing"); |
| 1132 | drop(guard); |
| 1133 | assert_eq!(f.manager.shared.core_calls.live_tickets(), 0); |
| 1134 | } |
| 1135 | |
| 1136 | #[tokio::test] |
| 1137 | async fn settings_arm_refuses_foreign_tickets_unknown_methods_and_keys_outside_review() { |
| 1138 | let mut f = Fixture::new(); |
| 1139 | let guard_a = f.begin(); |
| 1140 | let settings = ticket(&guard_a, "settings"); |
| 1141 | let before = f.text(); |
| 1142 | let patch = json!({"patch": {"model": "x"}}); |
| 1143 | |
| 1144 | for (owner, presented) in [ |
| 1145 | (&f.other, settings.clone()), |
| 1146 | (&f.owner, ticket(&guard_a, "workspace")), |
| 1147 | (&f.owner, guard_a.ticket().to_string()), |
| 1148 | ] { |
| 1149 | let result = f |
| 1150 | .broker(GRANTED, owner, &presented, "update", patch.clone()) |
| 1151 | .await; |
| 1152 | assert_eq!(refusal(&result), ticket_refused()); |
| 1153 | } |
| 1154 | |
| 1155 | for method in ["edit", "configuration", "entries", "set", "core/call", ""] { |
| 1156 | let unknown = f.call(&settings, method, json!({})).await; |
| 1157 | assert_eq!( |
| 1158 | refusal(&unknown), |
| 1159 | (error_code::INVALID_PARAMS, "unknown_method".into()), |
| 1160 | "{method:?}" |
| 1161 | ); |
| 1162 | } |
| 1163 | for (method, input) in [ |
| 1164 | ("describe", json!({"redactSecrets": false})), |
| 1165 | ("update", json!({"ns": "other", "patch": {"model": "x"}})), |
| 1166 | ("update", json!({"patch": {"model": null}})), |
| 1167 | ("update", json!({"patch": {"model": {"": 1}}})), |
| 1168 | ( |
| 1169 | "update", |
| 1170 | json!({"patch": {"model": 18446744073709551615u64}}), |
| 1171 | ), |
| 1172 | ( |
| 1173 | "update", |
| 1174 | json!({"patch": {"model": "x".repeat(MAX_INPUT_BYTES)}}), |
| 1175 | ), |
| 1176 | ("update", json!({"patch": {"model": "x".repeat(17 * 1024)}})), |
| 1177 | ( |
| 1178 | "mutate", |
| 1179 | json!({"ops": [{"op": "set", "path": [], "value": 1}]}), |
| 1180 | ), |
| 1181 | ( |
| 1182 | "mutate", |
| 1183 | json!({"ops": [{"op": "set", "path": ["model", "deeper"], "value": 1}]}), |
| 1184 | ), |
| 1185 | ( |
| 1186 | "mutate", |
| 1187 | json!({"ops": [{"op": "move", "path": ["model"]}]}), |
| 1188 | ), |
| 1189 | ("replace", json!({"value": "model"})), |
| 1190 | ] { |
| 1191 | let result = f.call(&settings, method, input.clone()).await; |
| 1192 | assert_eq!( |
| 1193 | refusal(&result), |
| 1194 | (error_code::INVALID_PARAMS, "invalid_input".into()), |
| 1195 | "{method} {}", |
| 1196 | input.to_string().chars().take(80).collect::<String>() |
| 1197 | ); |
| 1198 | } |
| 1199 | for (method, input) in [ |
| 1200 | ("update", json!({"patch": {"internal": "taken"}})), |
| 1201 | ( |
| 1202 | "update", |
| 1203 | json!({"patch": {"model": "x", "allow_shell": false}}), |
| 1204 | ), |
| 1205 | ( |
| 1206 | "replace", |
| 1207 | json!({"value": {"model": "x", "internal": "taken"}}), |
| 1208 | ), |
| 1209 | ( |
| 1210 | "mutate", |
| 1211 | json!({"ops": [{"op": "unset", "path": ["internal"]}]}), |
| 1212 | ), |
| 1213 | ( |
| 1214 | "mutate", |
| 1215 | json!({"ops": [ |
| 1216 | {"op": "set", "path": ["model"], "value": "x"}, |
| 1217 | {"op": "set", "path": ["plugins", "other", "config", "model"], "value": "mine"}, |
| 1218 | ]}), |
| 1219 | ), |
| 1220 | ] { |
| 1221 | let result = f.call(&settings, method, input).await; |
| 1222 | assert_eq!(refusal(&result), policy_refused(), "{method}"); |
| 1223 | assert_eq!( |
| 1224 | result.unwrap_err().message, |
| 1225 | "that setting is outside this plugin's reviewed settings" |
| 1226 | ); |
| 1227 | } |
| 1228 | assert_eq!(f.text(), before, "no refused call wrote anything"); |
| 1229 | |
| 1230 | for (method, input) in [ |
| 1231 | ("describe", json!({})), |
| 1232 | ("anything", json!({})), |
| 1233 | ("update", patch.clone()), |
| 1234 | ] { |
| 1235 | let withheld = f.broker(TABLE, &f.owner, &settings, method, input).await; |
| 1236 | assert_eq!( |
| 1237 | refusal(&withheld), |
| 1238 | (error_code::NOT_AVAILABLE, "not_available".into()), |
| 1239 | "the landed arm has no authority yet ({method})" |
| 1240 | ); |
| 1241 | } |
| 1242 | f.authorize(&[]); |
| 1243 | let unreviewed = f.call(&settings, "describe", json!({})).await; |
| 1244 | assert_eq!( |
| 1245 | refusal(&unreviewed), |
| 1246 | (error_code::NOT_AVAILABLE, "not_available".into()), |
| 1247 | "no reviewed roots is a refusal, not an open table" |
| 1248 | ); |
| 1249 | f.authorize(&["model", "limits"]); |
| 1250 | |
| 1251 | f.in_session("settings-session-b"); |
| 1252 | let guard_b = f.begin(); |
| 1253 | let settings_b = ticket(&guard_b, "settings"); |
| 1254 | drop(guard_a); |
| 1255 | let ended = f.call(&settings, "update", patch.clone()).await; |
| 1256 | assert_eq!(refusal(&ended), ticket_refused()); |
| 1257 | assert_eq!(f.text(), before); |
| 1258 | |
| 1259 | let (cx, _violations, cancel) = HostRequestContext::for_test(41); |
| 1260 | cancel.cancel(); |
| 1261 | let cancelled = f |
| 1262 | .broker_in(cx, GRANTED, &f.owner, &settings_b, "update", patch.clone()) |
| 1263 | .await; |
| 1264 | assert_eq!( |
| 1265 | refusal(&cancelled), |
| 1266 | (error_code::CANCELLED, "cancelled".into()) |
| 1267 | ); |
| 1268 | assert_eq!( |
| 1269 | f.text(), |
| 1270 | before, |
| 1271 | "a call cancelled before it starts writes nothing" |
| 1272 | ); |
| 1273 | |
| 1274 | let written = f.call(&settings_b, "update", patch).await.unwrap(); |
| 1275 | assert_eq!(written["written"], true); |
| 1276 | drop(guard_b); |
| 1277 | } |
| 1278 | |
| 1279 | #[tokio::test] |
| 1280 | async fn settings_writes_follow_the_callers_limits_and_the_live_posture() { |
| 1281 | let mut f = Fixture::new(); |
| 1282 | let before = f.text(); |
| 1283 | let patch = json!({"patch": {"model": "x"}}); |
| 1284 | let base = f.context.clone(); |
| 1285 | |
| 1286 | let mut refused_contexts: Vec<(&str, ToolContext)> = Vec::new(); |
| 1287 | refused_contexts.push(( |
| 1288 | "a child agent", |
| 1289 | base.clone().with_owner_agent("child-1", "child"), |
| 1290 | )); |
| 1291 | let mut worker = base.clone(); |
| 1292 | worker.tool_authority = Some(Arc::new(ToolAuthorityEnvelope { |
| 1293 | schema_version: 1, |
| 1294 | owner: "worker".into(), |
| 1295 | authority: ToolMutationAuthority::ScopedWrite, |
| 1296 | network_access: None, |
| 1297 | shell: ToolShellAuthority::default(), |
| 1298 | verification: ToolVerificationAuthority::default(), |
| 1299 | writable_roots: vec![".".into()], |
| 1300 | writable_files: Vec::new(), |
| 1301 | coordination_contracts: Vec::new(), |
| 1302 | })); |
| 1303 | refused_contexts.push(("a worker under an envelope", worker)); |
| 1304 | let mut unknown = base.clone(); |
| 1305 | unknown.live_posture = None; |
| 1306 | unknown.elevated_sandbox_policy = None; |
| 1307 | refused_contexts.push(("a session with no posture", unknown)); |
| 1308 | let mut plan = base.clone(); |
| 1309 | plan.live_posture = None; |
| 1310 | plan.elevated_sandbox_policy = Some(SandboxPolicy::read_only()); |
| 1311 | refused_contexts.push(("a read-only session", plan)); |
| 1312 | |
| 1313 | for (what, context) in refused_contexts { |
| 1314 | f.context = context; |
| 1315 | let guard = f.begin(); |
| 1316 | let settings = ticket(&guard, "settings"); |
| 1317 | let result = f.call(&settings, "update", patch.clone()).await; |
| 1318 | assert_eq!(refusal(&result), policy_refused(), "{what}"); |
| 1319 | assert_eq!( |
| 1320 | result.unwrap_err().message, |
| 1321 | "settings cannot be changed in this session", |
| 1322 | "{what}: the refusal says no more than that" |
| 1323 | ); |
| 1324 | let read = f.call(&settings, "describe", json!({})).await.unwrap(); |
| 1325 | assert_eq!(read["writable"], false, "{what}"); |
| 1326 | assert_eq!(f.text(), before, "{what}"); |
| 1327 | } |
| 1328 | |
| 1329 | f.context = base; |
| 1330 | let guard = f.begin(); |
| 1331 | let settings = ticket(&guard, "settings"); |
| 1332 | for mode in [ApprovalMode::Never, ApprovalMode::Auto] { |
| 1333 | f.posture.switch_for_tests(mode); |
| 1334 | let result = f.call(&settings, "update", patch.clone()).await; |
| 1335 | assert_eq!( |
| 1336 | refusal(&result), |
| 1337 | policy_refused(), |
| 1338 | "{mode:?} set after the tool call began" |
| 1339 | ); |
| 1340 | assert_eq!(f.text(), before); |
| 1341 | } |
| 1342 | f.posture.switch_for_tests(ApprovalMode::Suggest); |
| 1343 | let allowed = f.call(&settings, "update", patch).await.unwrap(); |
| 1344 | assert_eq!(allowed["written"], true); |
| 1345 | } |
| 1346 | |
| 1347 | #[tokio::test] |
| 1348 | async fn a_settings_write_the_config_writer_cannot_persist_is_refused_and_changes_nothing() { |
| 1349 | let f = Fixture::new(); |
| 1350 | let guard = f.begin(); |
| 1351 | let settings = ticket(&guard, "settings"); |
| 1352 | let before = f.text(); |
| 1353 | let patch = json!({"patch": {"model": "x"}}); |
| 1354 | |
| 1355 | let blocked = f.dir.path().join("not-a-directory"); |
| 1356 | std::fs::write(&blocked, "a file where the config directory would be").unwrap(); |
| 1357 | AUTHORITY.with(|authority| { |
| 1358 | authority.borrow_mut().as_mut().unwrap().source = Some(blocked.join("config.toml")); |
| 1359 | }); |
| 1360 | let failed = f.call(&settings, "update", patch.clone()).await; |
| 1361 | assert_eq!(refusal(&failed), policy_refused()); |
| 1362 | let message = failed.unwrap_err().message; |
| 1363 | assert_eq!(message, "the settings could not be saved"); |
| 1364 | assert!( |
| 1365 | !message.contains("not-a-directory"), |
| 1366 | "the refusal carries no path" |
| 1367 | ); |
| 1368 | assert!(!blocked.join("config.toml").exists()); |
| 1369 | assert_eq!( |
| 1370 | std::fs::read_to_string(&blocked).unwrap(), |
| 1371 | "a file where the config directory would be" |
| 1372 | ); |
| 1373 | |
| 1374 | f.authorize(&["model", "limits"]); |
| 1375 | std::fs::write(f.path(), "plugins = [unterminated").unwrap(); |
| 1376 | let unparsable = f.call(&settings, "update", patch.clone()).await; |
| 1377 | assert_eq!(refusal(&unparsable), policy_refused()); |
| 1378 | assert_eq!( |
| 1379 | f.text(), |
| 1380 | "plugins = [unterminated", |
| 1381 | "the file is left as it was" |
| 1382 | ); |
| 1383 | let unreadable = f.call(&settings, "describe", json!({})).await; |
| 1384 | assert_eq!(refusal(&unreadable), policy_refused()); |
| 1385 | assert_eq!( |
| 1386 | unreadable.unwrap_err().message, |
| 1387 | "the settings could not be read" |
| 1388 | ); |
| 1389 | |
| 1390 | std::fs::write(f.path(), &before).unwrap(); |
| 1391 | let recovered = f.call(&settings, "update", patch).await.unwrap(); |
| 1392 | assert_eq!(recovered["written"], true); |
| 1393 | |
| 1394 | std::fs::remove_file(f.path()).unwrap(); |
| 1395 | let created = f |
| 1396 | .call( |
| 1397 | &settings, |
| 1398 | "update", |
| 1399 | json!({"patch": {"limits": {"max": 1}}}), |
| 1400 | ) |
| 1401 | .await |
| 1402 | .unwrap(); |
| 1403 | assert_eq!(created["written"], true); |
| 1404 | assert_eq!( |
| 1405 | f.active().select(NAME).unwrap().value, |
| 1406 | json!({"limits": {"max": 1}}), |
| 1407 | "a first edit creates only the plugin's own table" |
| 1408 | ); |
| 1409 | } |
| 1410 | |
| 1411 | #[tokio::test] |
| 1412 | async fn settings_acts_pass_the_gate_and_record_receipts() { |
| 1413 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 1414 | |
| 1415 | let mut f = Fixture::new(); |
| 1416 | let asked = Arc::new(AtomicUsize::new(0)); |
| 1417 | let deny = Arc::new(AtomicBool::new(false)); |
| 1418 | let switch_to_never = Arc::new(AtomicBool::new(false)); |
| 1419 | let asked_in_gate = Arc::clone(&asked); |
| 1420 | let deny_in_gate = Arc::clone(&deny); |
| 1421 | let switch_in_gate = Arc::clone(&switch_to_never); |
| 1422 | let posture_in_gate = f.posture.clone(); |
| 1423 | f.gate = NestedCallGate::answering_for_test(move |name, input| { |
| 1424 | asked_in_gate.fetch_add(1, Ordering::SeqCst); |
| 1425 | if deny_in_gate.load(Ordering::SeqCst) { |
| 1426 | return NestedCallVerdict::Refused { |
| 1427 | error: ToolError::permission_denied("denied by the person"), |
| 1428 | decision: NestedDecision::Denied, |
| 1429 | }; |
| 1430 | } |
| 1431 | if switch_in_gate.load(Ordering::SeqCst) { |
| 1432 | posture_in_gate.switch_for_tests(ApprovalMode::Never); |
| 1433 | } |
| 1434 | NestedCallVerdict::Run { |
| 1435 | name: name.to_string(), |
| 1436 | input: input.clone(), |
| 1437 | supports_parallel: false, |
| 1438 | decision: NestedDecision::Auto, |
| 1439 | hook_context: None, |
| 1440 | } |
| 1441 | }) |
| 1442 | .for_extension( |
| 1443 | ExtensionCaller { |
| 1444 | origin: "extension:a".to_string(), |
| 1445 | tool: "a_tool".to_string(), |
| 1446 | scope: "ext:a@hash".to_string(), |
| 1447 | }, |
| 1448 | BrokerActTool::all().to_vec(), |
| 1449 | ); |
| 1450 | |
| 1451 | let guard = f.begin(); |
| 1452 | let settings = ticket(&guard, "settings"); |
| 1453 | |
| 1454 | let _ = f.call(&settings, "describe", json!({})).await.unwrap(); |
| 1455 | assert_eq!(asked.load(Ordering::SeqCst), 0); |
| 1456 | |
| 1457 | let outside = f |
| 1458 | .call(&settings, "update", json!({"patch": {"other": 1}})) |
| 1459 | .await; |
| 1460 | assert_eq!(refusal(&outside), policy_refused()); |
| 1461 | assert_eq!( |
| 1462 | asked.load(Ordering::SeqCst), |
| 1463 | 0, |
| 1464 | "out-of-scope edits are rejected before opening a gate prompt" |
| 1465 | ); |
| 1466 | |
| 1467 | let ok = f |
| 1468 | .call(&settings, "update", json!({"patch": {"model": "gated"}})) |
| 1469 | .await |
| 1470 | .unwrap(); |
| 1471 | assert_eq!(ok["written"], true); |
| 1472 | assert_eq!(asked.load(Ordering::SeqCst), 1); |
| 1473 | let after_ok = f.text(); |
| 1474 | |
| 1475 | deny.store(true, Ordering::SeqCst); |
| 1476 | let denied = f |
| 1477 | .call(&settings, "update", json!({"patch": {"model": "blocked"}})) |
| 1478 | .await; |
| 1479 | assert_eq!(refusal(&denied), (error_code::DENIED, "denied".into())); |
| 1480 | assert_eq!(asked.load(Ordering::SeqCst), 2); |
| 1481 | assert_eq!(f.text(), after_ok); |
| 1482 | |
| 1483 | deny.store(false, Ordering::SeqCst); |
| 1484 | switch_to_never.store(true, Ordering::SeqCst); |
| 1485 | let raced = f |
| 1486 | .call(&settings, "update", json!({"patch": {"model": "never"}})) |
| 1487 | .await; |
| 1488 | assert_eq!(refusal(&raced), policy_refused()); |
| 1489 | assert_eq!(asked.load(Ordering::SeqCst), 3); |
| 1490 | assert_eq!(f.text(), after_ok); |
| 1491 | |
| 1492 | let receipts = guard.receipts().expect("broker acts are recorded"); |
| 1493 | assert_eq!(receipts["broker_acts"]["total"], 4, "{receipts}"); |
| 1494 | assert_eq!( |
| 1495 | receipts["broker_acts"]["acts"] |
| 1496 | .as_array() |
| 1497 | .unwrap() |
| 1498 | .iter() |
| 1499 | .map(|act| ( |
| 1500 | act["service"].as_str().unwrap(), |
| 1501 | act["method"].as_str().unwrap(), |
| 1502 | act["outcome"].as_str().unwrap(), |
| 1503 | act["target"].as_str().unwrap(), |
| 1504 | )) |
| 1505 | .collect::<Vec<_>>(), |
| 1506 | vec![ |
| 1507 | ("settings", "describe", "read", NAME), |
| 1508 | ("settings", "update", "allowed", NAME), |
| 1509 | ("settings", "update", "denied", NAME), |
| 1510 | ("settings", "update", "allowed", NAME), |
| 1511 | ] |
| 1512 | ); |
| 1513 | } |
| 1514 | |
| 1515 | #[tokio::test] |
| 1516 | async fn shared_plugin_config_settings_round_trip_conflicts_and_bounds() { |
| 1517 | let dir = tempfile::tempdir().unwrap(); |
| 1518 | let config_path = dir.path().join("config.toml"); |
| 1519 | std::fs::write( |
| 1520 | &config_path, |
| 1521 | "api_key = \"sk-super-secret\"\n\n[plugins.sibling.config]\ntoken = \"sibling-secret\"\n", |
| 1522 | ) |
| 1523 | .unwrap(); |
| 1524 | |
| 1525 | let initial = read_plugin_config_settings(config_path.clone(), "demo".to_string()) |
| 1526 | .await |
| 1527 | .expect("read empty plugin config"); |
| 1528 | assert!(initial.value.is_empty()); |
| 1529 | assert!(initial.writable); |
| 1530 | assert!(!initial.value.contains_key("api_key")); |
| 1531 | assert!(!initial.value.contains_key("sibling")); |
| 1532 | |
| 1533 | let mut next = Map::new(); |
| 1534 | next.insert("theme".to_string(), json!("ocean")); |
| 1535 | next.insert("nested".to_string(), json!({ "count": 2 })); |
| 1536 | let saved = write_plugin_config_settings( |
| 1537 | config_path.clone(), |
| 1538 | "demo".to_string(), |
| 1539 | next.clone(), |
| 1540 | Some(initial.revision.clone()), |
| 1541 | ) |
| 1542 | .await |
| 1543 | .expect("write plugin config"); |
| 1544 | assert!(saved.written); |
| 1545 | assert!(!saved.conflict); |
| 1546 | assert_ne!(saved.revision, initial.revision); |
| 1547 | |
| 1548 | let reread = read_plugin_config_settings(config_path.clone(), "demo".to_string()) |
| 1549 | .await |
| 1550 | .expect("re-read plugin config"); |
| 1551 | assert_eq!(reread.value, next); |
| 1552 | assert_eq!(reread.revision, saved.revision); |
| 1553 | |
| 1554 | let mut stale = Map::new(); |
| 1555 | stale.insert("theme".to_string(), json!("forest")); |
| 1556 | let conflict = write_plugin_config_settings( |
| 1557 | config_path.clone(), |
| 1558 | "demo".to_string(), |
| 1559 | stale, |
| 1560 | Some(initial.revision), |
| 1561 | ) |
| 1562 | .await |
| 1563 | .expect("conflict returns outcome"); |
| 1564 | assert!(!conflict.written); |
| 1565 | assert!(conflict.conflict); |
| 1566 | assert_eq!(conflict.revision, saved.revision); |
| 1567 | |
| 1568 | let mut oversized = Map::new(); |
| 1569 | oversized.insert("blob".to_string(), json!("x".repeat(MAX_INPUT_BYTES + 1))); |
| 1570 | assert_eq!( |
| 1571 | write_plugin_config_settings(config_path.clone(), "demo".to_string(), oversized, None) |
| 1572 | .await, |
| 1573 | Err(PluginSettingsError::Invalid( |
| 1574 | "the settings input is too large" |
| 1575 | )) |
| 1576 | ); |
| 1577 | |
| 1578 | let mut bad_key = Map::new(); |
| 1579 | bad_key.insert("bad\nkey".to_string(), json!("v")); |
| 1580 | assert!(matches!( |
| 1581 | write_plugin_config_settings(config_path.clone(), "demo".to_string(), bad_key, None) |
| 1582 | .await, |
| 1583 | Err(PluginSettingsError::Invalid(_)) |
| 1584 | )); |
| 1585 | |
| 1586 | let mut deep = json!("leaf"); |
| 1587 | for _ in 0..=MAX_PATH_DEPTH { |
| 1588 | deep = json!({ "k": deep }); |
| 1589 | } |
| 1590 | let Value::Object(deep_map) = deep else { |
| 1591 | unreachable!() |
| 1592 | }; |
| 1593 | assert_eq!( |
| 1594 | write_plugin_config_settings(config_path.clone(), "demo".to_string(), deep_map, None) |
| 1595 | .await, |
| 1596 | Err(PluginSettingsError::Invalid( |
| 1597 | "settings nesting exceeds the maximum depth of 16" |
| 1598 | )) |
| 1599 | ); |
| 1600 | |
| 1601 | let sibling = read_plugin_config_settings(config_path, "sibling".to_string()) |
| 1602 | .await |
| 1603 | .expect("sibling untouched"); |
| 1604 | assert_eq!(sibling.value.get("token"), Some(&json!("sibling-secret"))); |
| 1605 | } |
| 1606 | } |
| 1607 |