| 1 | use std::cell::RefCell; |
| 2 | use std::path::Path; |
| 3 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 4 | |
| 5 | use codewhale_config::OwnerRef; |
| 6 | use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 7 | use codewhale_secrets::InMemoryKeyringStore; |
| 8 | use tokio::sync::mpsc; |
| 9 | use wiremock::matchers::{header, method, path}; |
| 10 | use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; |
| 11 | |
| 12 | use super::super::core_call::InvocationGuard; |
| 13 | use super::super::dsh_broker::{Arm, BrokerActTool, BrokerContext, REACH_TOOL, TestGrants}; |
| 14 | use super::super::protocol::{DshBrokerParams, RpcErrorWire}; |
| 15 | use super::super::supervisor::HostRequestContext; |
| 16 | use super::super::test_support::fake_authority; |
| 17 | use super::super::{ExtensionHostManager, ExtensionHostOptions, HostCohort}; |
| 18 | use super::*; |
| 19 | use crate::tools::codemode::{ |
| 20 | ExtensionCaller, NestedCallGate, NestedCallRequest, NestedCallVerdict, NestedDecision, |
| 21 | }; |
| 22 | |
| 23 | const SECRET: &str = "sk-live-0123456789abcdef"; |
| 24 | const BUILD: &str = "build-1"; |
| 25 | |
| 26 | thread_local! { |
| 27 | static AUTHORITY: RefCell<Option<NetworkAuthority>> = const { RefCell::new(None) }; |
| 28 | } |
| 29 | |
| 30 | fn arm(call: BrokerCall) -> BrokerFuture { |
| 31 | serve_with( |
| 32 | call, |
| 33 | AUTHORITY.with(|authority| authority.borrow().clone().expect("a test authority")), |
| 34 | ) |
| 35 | } |
| 36 | |
| 37 | const TABLE: &[(DshService, Arm)] = &[(DshService::Network, arm as Arm)]; |
| 38 | |
| 39 | #[derive(Default)] |
| 40 | struct Person { |
| 41 | cards: Mutex<Vec<(Value, String)>>, |
| 42 | says_no: AtomicBool, |
| 43 | absent: AtomicBool, |
| 44 | act_denied: AtomicBool, |
| 45 | } |
| 46 | |
| 47 | impl Person { |
| 48 | fn cards(&self) -> Vec<(Value, String)> { |
| 49 | self.cards.lock().unwrap().clone() |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | fn serve_gate(mut requests: mpsc::Receiver<NestedCallRequest>, person: Arc<Person>) { |
| 54 | tokio::spawn(async move { |
| 55 | while let Some(request) = requests.recv().await { |
| 56 | let NestedCallRequest::Tool(request) = request else { |
| 57 | continue; |
| 58 | }; |
| 59 | if request.is_stale() { |
| 60 | continue; |
| 61 | } |
| 62 | let refuse = |decision| NestedCallVerdict::Refused { |
| 63 | error: ToolError::permission_denied("the gate said no"), |
| 64 | decision, |
| 65 | }; |
| 66 | let verdict = if request.name == SEND_TOOL { |
| 67 | let planned = |
| 68 | SendConsent.prepare(request.input.clone(), &ToolContext::new(Path::new("."))); |
| 69 | match planned { |
| 70 | Err(_) => refuse(NestedDecision::Refused), |
| 71 | Ok(_) if person.absent.load(Ordering::SeqCst) => { |
| 72 | refuse(NestedDecision::Refused) |
| 73 | } |
| 74 | Ok(planned) => { |
| 75 | person |
| 76 | .cards |
| 77 | .lock() |
| 78 | .unwrap() |
| 79 | .push((request.input.clone(), planned.description)); |
| 80 | if person.says_no.load(Ordering::SeqCst) { |
| 81 | refuse(NestedDecision::Denied) |
| 82 | } else { |
| 83 | NestedCallVerdict::Run { |
| 84 | name: request.name.clone(), |
| 85 | input: request.input.clone(), |
| 86 | supports_parallel: true, |
| 87 | decision: NestedDecision::Approved, |
| 88 | hook_context: None, |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | } else { |
| 94 | let gate = if request.name == REACH_TOOL { |
| 95 | BrokerActTool::REACH |
| 96 | } else { |
| 97 | BrokerActTool::ACT |
| 98 | }; |
| 99 | match gate.prepare(request.input.clone(), &ToolContext::new(Path::new("."))) { |
| 100 | Err(_) => refuse(NestedDecision::Refused), |
| 101 | Ok(_) if person.act_denied.load(Ordering::SeqCst) => { |
| 102 | refuse(NestedDecision::Denied) |
| 103 | } |
| 104 | Ok(_) => NestedCallVerdict::Run { |
| 105 | name: request.name.clone(), |
| 106 | input: request.input.clone(), |
| 107 | supports_parallel: true, |
| 108 | decision: NestedDecision::Approved, |
| 109 | hook_context: None, |
| 110 | }, |
| 111 | } |
| 112 | }; |
| 113 | let _ = request.reply.send(verdict); |
| 114 | } |
| 115 | }); |
| 116 | } |
| 117 | |
| 118 | struct Rig { |
| 119 | manager: ExtensionHostManager, |
| 120 | owner: OwnerRef, |
| 121 | context: ToolContext, |
| 122 | gate: NestedCallGate, |
| 123 | person: Arc<Person>, |
| 124 | } |
| 125 | |
| 126 | fn allowing(hosts: &[&str]) -> NetworkPolicyDecider { |
| 127 | NetworkPolicyDecider::new( |
| 128 | NetworkPolicy { |
| 129 | default: Decision::Deny.into(), |
| 130 | allow: hosts.iter().map(|host| (*host).to_string()).collect(), |
| 131 | deny: Vec::new(), |
| 132 | proxy: Vec::new(), |
| 133 | proxy_fake_ip_cidrs: Vec::new(), |
| 134 | audit: false, |
| 135 | }, |
| 136 | None, |
| 137 | ) |
| 138 | } |
| 139 | |
| 140 | fn loopback() -> NetworkPolicyDecider { |
| 141 | allowing(&["127.0.0.1"]) |
| 142 | } |
| 143 | |
| 144 | impl Rig { |
| 145 | fn new(session: &str, shape: impl FnOnce(ToolContext) -> ToolContext) -> Self { |
| 146 | let manager = ExtensionHostManager::new(ExtensionHostOptions::default()); |
| 147 | let owner = { |
| 148 | let mut registry = manager.shared.registry.lock().unwrap(); |
| 149 | let owner = registry |
| 150 | .begin_owner( |
| 151 | HostCohort::reviewed(), |
| 152 | "a", |
| 153 | "a", |
| 154 | Some(fake_authority("a")), |
| 155 | "hash", |
| 156 | ) |
| 157 | .unwrap(); |
| 158 | registry.mark_active(&owner); |
| 159 | owner |
| 160 | }; |
| 161 | let workspace = std::env::temp_dir(); |
| 162 | let context = ToolContext::new(&workspace) |
| 163 | .with_session_objects(crate::rlm::session::SessionObjectSnapshot::new( |
| 164 | session.to_string(), |
| 165 | "fixture-model".to_string(), |
| 166 | workspace.clone(), |
| 167 | None, |
| 168 | Arc::new(Vec::new()), |
| 169 | )) |
| 170 | .with_origin_turn_id("turn"); |
| 171 | let (tx_event, mut rx_event) = mpsc::channel(8); |
| 172 | tokio::spawn(async move { while rx_event.recv().await.is_some() {} }); |
| 173 | let (gate, requests) = NestedCallGate::new(None, tx_event, Duration::from_secs(60)); |
| 174 | let person = Arc::new(Person::default()); |
| 175 | serve_gate(requests, Arc::clone(&person)); |
| 176 | let mut specs: Vec<Arc<dyn ToolSpec>> = BrokerActTool::all().to_vec(); |
| 177 | specs.push(Arc::new(SendConsent)); |
| 178 | Self { |
| 179 | manager, |
| 180 | owner, |
| 181 | context: shape(context), |
| 182 | person, |
| 183 | gate: gate.for_extension( |
| 184 | ExtensionCaller { |
| 185 | origin: "extension:a".to_string(), |
| 186 | tool: "a_tool".to_string(), |
| 187 | scope: "ext:a@hash".to_string(), |
| 188 | }, |
| 189 | specs, |
| 190 | ), |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | fn begin(&self) -> InvocationGuard { |
| 195 | let caller = self.gate.extension().unwrap().0.clone(); |
| 196 | self.manager |
| 197 | .shared |
| 198 | .core_calls |
| 199 | .begin( |
| 200 | HostCohort::reviewed(), |
| 201 | 7, |
| 202 | &self.owner, |
| 203 | "call-1", |
| 204 | &caller, |
| 205 | &self.context, |
| 206 | &self.gate, |
| 207 | ) |
| 208 | .expect("an invocation") |
| 209 | } |
| 210 | |
| 211 | async fn call( |
| 212 | &self, |
| 213 | guard: &InvocationGuard, |
| 214 | authority: &NetworkAuthority, |
| 215 | method: &str, |
| 216 | input: Value, |
| 217 | ) -> Result<Value, RpcErrorWire> { |
| 218 | let ticket = guard |
| 219 | .broker_tickets() |
| 220 | .expect("broker tickets") |
| 221 | .into_iter() |
| 222 | .find(|wire| wire.service == "network") |
| 223 | .expect("a network ticket") |
| 224 | .ticket; |
| 225 | AUTHORITY.with(|slot| *slot.borrow_mut() = Some(authority.clone())); |
| 226 | let (cx, _violations, _cancel) = HostRequestContext::for_test(1); |
| 227 | self.manager |
| 228 | .shared |
| 229 | .core_calls |
| 230 | .serve_broker_in( |
| 231 | TABLE, |
| 232 | &self.manager.shared, |
| 233 | HostCohort::reviewed(), |
| 234 | 7, |
| 235 | DshBrokerParams { |
| 236 | owner: self.owner.clone(), |
| 237 | ticket, |
| 238 | service: "network".to_string(), |
| 239 | method: method.to_string(), |
| 240 | input, |
| 241 | }, |
| 242 | cx, |
| 243 | ) |
| 244 | .await |
| 245 | } |
| 246 | |
| 247 | async fn fetch( |
| 248 | &self, |
| 249 | guard: &InvocationGuard, |
| 250 | authority: &NetworkAuthority, |
| 251 | input: Value, |
| 252 | ) -> Result<Value, RpcErrorWire> { |
| 253 | self.call(guard, authority, "fetch", input).await |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | fn vault() -> Vault { |
| 258 | Vault { |
| 259 | store: Secrets::new(Arc::new(InMemoryKeyringStore::new())), |
| 260 | plaintext_for_test: true, |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | fn authority(sites: &[String], vault: &Vault) -> NetworkAuthority { |
| 265 | NetworkAuthority { |
| 266 | build: BUILD.to_string(), |
| 267 | sites: sites |
| 268 | .iter() |
| 269 | .map(|site| Origin::parse(site).expect("a site")) |
| 270 | .collect(), |
| 271 | vault: vault.clone(), |
| 272 | test_dns_pins: BTreeMap::new(), |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | fn site_for(host: &str, server: &MockServer) -> String { |
| 277 | format!("http://{host}:{}", server.address().port()) |
| 278 | } |
| 279 | |
| 280 | fn authority_pinned(servers: &[(&str, &MockServer)], vault: &Vault) -> NetworkAuthority { |
| 281 | let sites: Vec<String> = servers |
| 282 | .iter() |
| 283 | .map(|(host, server)| site_for(host, server)) |
| 284 | .collect(); |
| 285 | let mut out = authority(&sites, vault); |
| 286 | out.test_dns_pins = servers |
| 287 | .iter() |
| 288 | .map(|(host, server)| ((*host).to_string(), server.address().ip())) |
| 289 | .collect(); |
| 290 | out |
| 291 | } |
| 292 | |
| 293 | fn keep(vault: &Vault, plugin: &str, name: &str, site: &str, value: &str) { |
| 294 | assert!( |
| 295 | vault |
| 296 | .write_blocking( |
| 297 | plugin, |
| 298 | BUILD, |
| 299 | name, |
| 300 | Stored { |
| 301 | site: site.to_string(), |
| 302 | value: value.to_string(), |
| 303 | }, |
| 304 | ) |
| 305 | .is_ok() |
| 306 | ); |
| 307 | } |
| 308 | |
| 309 | fn kind(result: &Result<Value, RpcErrorWire>) -> (String, String) { |
| 310 | let error = result.as_ref().expect_err("a refusal"); |
| 311 | ( |
| 312 | error |
| 313 | .data |
| 314 | .as_ref() |
| 315 | .and_then(|data| data["dsh_refusal"].as_str()) |
| 316 | .unwrap_or("untyped") |
| 317 | .to_string(), |
| 318 | error.message.clone(), |
| 319 | ) |
| 320 | } |
| 321 | |
| 322 | fn body(result: &Value) -> String { |
| 323 | String::from_utf8( |
| 324 | STANDARD |
| 325 | .decode(result["body_base64"].as_str().unwrap()) |
| 326 | .unwrap(), |
| 327 | ) |
| 328 | .unwrap() |
| 329 | } |
| 330 | |
| 331 | fn detached(plugin: &str, method: &str, input: Value) -> BrokerCall { |
| 332 | let owner = OwnerRef { |
| 333 | plugin_id: plugin.into(), |
| 334 | generation: 1, |
| 335 | owner_token: "t".into(), |
| 336 | }; |
| 337 | BrokerCall { |
| 338 | context: BrokerContext::detached_for_test(&owner, DshService::Network), |
| 339 | owner, |
| 340 | session_id: "detached".into(), |
| 341 | service: DshService::Network, |
| 342 | method: method.into(), |
| 343 | input, |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | fn code(result: &Result<Value, BrokerRefusal>) -> &'static str { |
| 348 | result.as_ref().expect_err("a refusal").code() |
| 349 | } |
| 350 | |
| 351 | async fn ok_server() -> MockServer { |
| 352 | let server = MockServer::start().await; |
| 353 | Mock::given(wiremock::matchers::any()) |
| 354 | .respond_with(ResponseTemplate::new(200).set_body_string("ok")) |
| 355 | .mount(&server) |
| 356 | .await; |
| 357 | server |
| 358 | } |
| 359 | |
| 360 | async fn quiet_server() -> MockServer { |
| 361 | let server = MockServer::start().await; |
| 362 | Mock::given(wiremock::matchers::any()) |
| 363 | .respond_with(ResponseTemplate::new(200)) |
| 364 | .expect(0) |
| 365 | .mount(&server) |
| 366 | .await; |
| 367 | server |
| 368 | } |
| 369 | |
| 370 | struct Echo; |
| 371 | impl Respond for Echo { |
| 372 | fn respond(&self, request: &Request) -> ResponseTemplate { |
| 373 | let auth = request |
| 374 | .headers |
| 375 | .get("authorization") |
| 376 | .and_then(|value| value.to_str().ok()) |
| 377 | .unwrap_or_default() |
| 378 | .to_string(); |
| 379 | ResponseTemplate::new(200) |
| 380 | .insert_header("x-echo", auth.as_str()) |
| 381 | .set_body_string(format!("you sent {auth}")) |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | type SeenRequests = Arc<Mutex<Vec<Vec<(String, String)>>>>; |
| 386 | |
| 387 | #[derive(Clone, Default)] |
| 388 | struct Seen(SeenRequests); |
| 389 | impl Respond for Seen { |
| 390 | fn respond(&self, request: &Request) -> ResponseTemplate { |
| 391 | self.0.lock().unwrap().push( |
| 392 | request |
| 393 | .headers |
| 394 | .iter() |
| 395 | .map(|(name, value)| { |
| 396 | ( |
| 397 | name.as_str().to_string(), |
| 398 | String::from_utf8_lossy(value.as_bytes()).into_owned(), |
| 399 | ) |
| 400 | }) |
| 401 | .collect(), |
| 402 | ); |
| 403 | ResponseTemplate::new(200).set_body_string("landed") |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | #[test] |
| 408 | fn a_site_name_is_ascii_and_derived_from_the_url() { |
| 409 | let site = |url: &str| Origin::parse(url).map(|site| site.to_string()); |
| 410 | assert_eq!( |
| 411 | site("https://API.Example.com").as_deref(), |
| 412 | Some("https://api.example.com") |
| 413 | ); |
| 414 | assert_eq!( |
| 415 | site("https://api.example.com:443/").as_deref(), |
| 416 | Some("https://api.example.com") |
| 417 | ); |
| 418 | assert_eq!( |
| 419 | site("https://api.example.com:8443").as_deref(), |
| 420 | Some("https://api.example.com:8443") |
| 421 | ); |
| 422 | let named = site("https://b\u{fc}cher.example").expect("an IDN site"); |
| 423 | assert!(named.is_ascii() && named.contains("xn--"), "{named}"); |
| 424 | for refused in [ |
| 425 | "https://user:pw@api.example.com", |
| 426 | "https://api.example.com/v1", |
| 427 | "https://api.example.com?x=1", |
| 428 | "https://api.example.com.", |
| 429 | "ftp://api.example.com", |
| 430 | "api.example.com", |
| 431 | ] { |
| 432 | assert_eq!(site(refused), None, "{refused}"); |
| 433 | } |
| 434 | assert_ne!( |
| 435 | Origin::parse("https://api.example.com"), |
| 436 | Origin::parse("http://api.example.com") |
| 437 | ); |
| 438 | } |
| 439 | |
| 440 | #[tokio::test] |
| 441 | async fn withheld_authority_refuses_typed_and_unknown_methods_are_named() { |
| 442 | let unknown = serve(detached("a", "connect", json!({}))).await; |
| 443 | assert_eq!(code(&unknown), "unknown_method"); |
| 444 | let bad = serve(detached("a", "fetch", json!({"url": 1}))).await; |
| 445 | assert_eq!(code(&bad), "invalid_input"); |
| 446 | for (method, input) in [ |
| 447 | ("fetch", json!({"url": "https://example.com/"})), |
| 448 | ("credentials.resolve", json!({"ref": "K"})), |
| 449 | ("credentials.describe", json!({"ref": "K"})), |
| 450 | ( |
| 451 | "credentials.set", |
| 452 | json!({"ref": "K", "value": "v", "site": "https://example.com"}), |
| 453 | ), |
| 454 | ] { |
| 455 | assert_eq!( |
| 456 | code(&serve(detached("a", method, input)).await), |
| 457 | "not_available", |
| 458 | "{method}" |
| 459 | ); |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | #[tokio::test] |
| 464 | async fn credentials_never_leave_rust_and_are_scoped_to_their_plugin() { |
| 465 | let vault = vault(); |
| 466 | let site = "https://api.example.com".to_string(); |
| 467 | let authority = authority(std::slice::from_ref(&site), &vault); |
| 468 | let set = serve_with( |
| 469 | detached( |
| 470 | "a", |
| 471 | "credentials.set", |
| 472 | json!({"ref": "OPENAI_API_KEY", "value": SECRET, "site": site}), |
| 473 | ), |
| 474 | authority.clone(), |
| 475 | ) |
| 476 | .await |
| 477 | .unwrap(); |
| 478 | assert!(!set.to_string().contains(SECRET)); |
| 479 | assert_eq!(set["site"], "https://api.example.com"); |
| 480 | for method in ["credentials.resolve", "credentials.describe"] { |
| 481 | let answer = serve_with( |
| 482 | detached("a", method, json!({"ref": "OPENAI_API_KEY"})), |
| 483 | authority.clone(), |
| 484 | ) |
| 485 | .await |
| 486 | .unwrap(); |
| 487 | assert!(!answer.to_string().contains(SECRET), "{method}"); |
| 488 | assert!( |
| 489 | answer |
| 490 | .to_string() |
| 491 | .contains("codewhale-credential:OPENAI_API_KEY"), |
| 492 | "{method}" |
| 493 | ); |
| 494 | } |
| 495 | let foreign = serve_with( |
| 496 | detached("b", "credentials.resolve", json!({"ref": "OPENAI_API_KEY"})), |
| 497 | authority.clone(), |
| 498 | ) |
| 499 | .await |
| 500 | .unwrap(); |
| 501 | assert_eq!(foreign["value"], Value::Null); |
| 502 | let traversal = serve_with( |
| 503 | detached( |
| 504 | "b", |
| 505 | "credentials.describe", |
| 506 | json!({"ref": "../a:OPENAI_API_KEY"}), |
| 507 | ), |
| 508 | authority.clone(), |
| 509 | ) |
| 510 | .await; |
| 511 | assert_eq!(code(&traversal), "invalid_input"); |
| 512 | let elsewhere = serve_with( |
| 513 | detached( |
| 514 | "a", |
| 515 | "credentials.set", |
| 516 | json!({"ref": "K", "value": SECRET, "site": "https://other.example.com"}), |
| 517 | ), |
| 518 | authority, |
| 519 | ) |
| 520 | .await; |
| 521 | assert_eq!(code(&elsewhere), "refused"); |
| 522 | } |
| 523 | |
| 524 | #[tokio::test] |
| 525 | async fn an_arm_whose_cancel_has_fired_has_no_effect() { |
| 526 | let vault = vault(); |
| 527 | let site = "https://api.example.com".to_string(); |
| 528 | let authority = authority(std::slice::from_ref(&site), &vault); |
| 529 | let call = detached( |
| 530 | "a", |
| 531 | "credentials.set", |
| 532 | json!({"ref": "K", "value": SECRET, "site": site}), |
| 533 | ); |
| 534 | call.context.cancel().cancel(); |
| 535 | assert_eq!(code(&serve_with(call, authority.clone()).await), "refused"); |
| 536 | assert!(vault.store.get(VAULT_ENTRY).unwrap().is_none()); |
| 537 | let call = detached("a", "fetch", json!({"url": "https://api.example.com/"})); |
| 538 | call.context.cancel().cancel(); |
| 539 | assert_eq!(code(&serve_with(call, authority).await), "refused"); |
| 540 | } |
| 541 | |
| 542 | #[tokio::test] |
| 543 | async fn a_forged_consent_request_never_reaches_a_card() { |
| 544 | let context = ToolContext::new(Path::new(".")); |
| 545 | let forged = json!({"request": "guess", "plugin": "a", "url": "https://bank.example/"}); |
| 546 | assert!(SendConsent.prepare(forged.clone(), &context).is_err()); |
| 547 | assert!(SendConsent.execute(forged, &context).await.is_err()); |
| 548 | assert!( |
| 549 | SendConsent |
| 550 | .prepare(json!({"url": "https://bank.example/"}), &context) |
| 551 | .is_err() |
| 552 | ); |
| 553 | assert!(!SendConsent.model_visible()); |
| 554 | assert!( |
| 555 | SendConsent |
| 556 | .capabilities() |
| 557 | .contains(&ToolCapability::Network) |
| 558 | ); |
| 559 | let request = PendingRequest::open(); |
| 560 | let live = json!({"request": request.0, "plugin": "a", "url": "https://bank.example/"}); |
| 561 | let planned = SendConsent.prepare(live.clone(), &context).unwrap(); |
| 562 | assert_eq!(planned.approval, ApprovalRequirement::Required); |
| 563 | assert!(planned.description.contains("`a`")); |
| 564 | assert!(planned.description.contains("https://bank.example")); |
| 565 | drop(request); |
| 566 | assert!(SendConsent.prepare(live, &context).is_err()); |
| 567 | } |
| 568 | |
| 569 | #[tokio::test] |
| 570 | async fn a_fetch_is_refused_when_the_session_has_no_network_policy() { |
| 571 | let _grants = TestGrants::only(&[DshService::Network]); |
| 572 | let server = quiet_server().await; |
| 573 | let vault = vault(); |
| 574 | let authority = authority(&[server.uri()], &vault); |
| 575 | let url = json!({"url": format!("{}/x", server.uri())}); |
| 576 | let prompt = NetworkPolicyDecider::new( |
| 577 | NetworkPolicy { |
| 578 | audit: false, |
| 579 | ..NetworkPolicy::default() |
| 580 | }, |
| 581 | None, |
| 582 | ); |
| 583 | let denied = NetworkPolicyDecider::new( |
| 584 | NetworkPolicy { |
| 585 | default: Decision::Allow.into(), |
| 586 | allow: Vec::new(), |
| 587 | deny: vec!["127.0.0.1".to_string()], |
| 588 | proxy: Vec::new(), |
| 589 | proxy_fake_ip_cidrs: Vec::new(), |
| 590 | audit: false, |
| 591 | }, |
| 592 | None, |
| 593 | ); |
| 594 | for (name, policy) in [ |
| 595 | ("none", None), |
| 596 | ("prompt", Some(prompt)), |
| 597 | ("deny", Some(denied)), |
| 598 | ] { |
| 599 | let rig = Rig::new(&format!("no-policy-{name}"), |context| match policy { |
| 600 | Some(policy) => context.with_network_policy(policy), |
| 601 | None => context, |
| 602 | }); |
| 603 | let guard = rig.begin(); |
| 604 | let result = rig.fetch(&guard, &authority, url.clone()).await; |
| 605 | assert_eq!( |
| 606 | kind(&result), |
| 607 | ("refused".to_string(), NOT_ALLOWED_HERE.to_string()), |
| 608 | "{name}" |
| 609 | ); |
| 610 | assert!(rig.person.cards().is_empty(), "{name}: no card is raised"); |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | #[tokio::test] |
| 615 | async fn the_first_send_to_a_site_raises_one_card_and_later_sends_go_through() { |
| 616 | let _grants = TestGrants::only(&[DshService::Network]); |
| 617 | let server = ok_server().await; |
| 618 | let second = ok_server().await; |
| 619 | let site = site_for("api.example.com", &server); |
| 620 | let second_site = site_for("other.example.com", &second); |
| 621 | let vault = vault(); |
| 622 | let authority = authority_pinned( |
| 623 | &[("api.example.com", &server), ("other.example.com", &second)], |
| 624 | &vault, |
| 625 | ); |
| 626 | let rig = Rig::new("one-card", |context| { |
| 627 | context.with_network_policy(allowing(&["api.example.com", "other.example.com"])) |
| 628 | }); |
| 629 | let guard = rig.begin(); |
| 630 | for _ in 0..3 { |
| 631 | let result = rig |
| 632 | .fetch(&guard, &authority, json!({"url": format!("{site}/x")})) |
| 633 | .await |
| 634 | .unwrap(); |
| 635 | assert_eq!(result["status"], 200); |
| 636 | } |
| 637 | let cards = rig.person.cards(); |
| 638 | assert_eq!(cards.len(), 1, "{cards:?}"); |
| 639 | let (input, text) = &cards[0]; |
| 640 | assert_eq!(input["plugin"], "a"); |
| 641 | assert_eq!(input["url"], format!("{site}/")); |
| 642 | assert!(text.contains("`a`") && text.contains(&site), "{text}"); |
| 643 | assert!(text.is_ascii()); |
| 644 | let receipts = guard.receipts().expect("the card is in the tool result"); |
| 645 | let send_calls = receipts["calls"] |
| 646 | .as_array() |
| 647 | .unwrap() |
| 648 | .iter() |
| 649 | .filter(|entry| entry["tool"] == SEND_TOOL) |
| 650 | .count(); |
| 651 | assert_eq!(send_calls, 1, "{receipts}"); |
| 652 | assert_eq!(receipts["broker_acts"]["total"], 3, "{receipts}"); |
| 653 | |
| 654 | let url = json!({"url": format!("{second_site}/y")}); |
| 655 | let (one, two) = tokio::join!( |
| 656 | rig.fetch(&guard, &authority, url.clone()), |
| 657 | rig.fetch(&guard, &authority, url.clone()) |
| 658 | ); |
| 659 | assert_eq!(one.unwrap()["status"], 200); |
| 660 | assert_eq!(two.unwrap()["status"], 200); |
| 661 | assert_eq!(rig.person.cards().len(), 2, "one card for the second site"); |
| 662 | assert_eq!(server.received_requests().await.unwrap().len(), 3); |
| 663 | assert_eq!(second.received_requests().await.unwrap().len(), 2); |
| 664 | } |
| 665 | |
| 666 | #[tokio::test] |
| 667 | async fn a_no_on_the_card_is_remembered_for_the_session() { |
| 668 | let _grants = TestGrants::only(&[DshService::Network]); |
| 669 | let server = ok_server().await; |
| 670 | let site = site_for("api.example.com", &server); |
| 671 | let vault = vault(); |
| 672 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 673 | let url = json!({"url": format!("{site}/x")}); |
| 674 | let rig = Rig::new("said-no", |context| { |
| 675 | context.with_network_policy(allowing(&["api.example.com"])) |
| 676 | }); |
| 677 | let guard = rig.begin(); |
| 678 | rig.person.says_no.store(true, Ordering::SeqCst); |
| 679 | let first = rig.fetch(&guard, &authority, url.clone()).await; |
| 680 | assert_eq!(kind(&first), ("denied".to_string(), DECLINED.to_string())); |
| 681 | rig.person.says_no.store(false, Ordering::SeqCst); |
| 682 | let again = rig.fetch(&guard, &authority, url.clone()).await; |
| 683 | assert_eq!(kind(&again).0, "denied"); |
| 684 | assert_eq!(rig.person.cards().len(), 1, "a no is not asked twice"); |
| 685 | assert!(server.received_requests().await.unwrap().is_empty()); |
| 686 | |
| 687 | let absent = Rig::new("nobody-there", |context| { |
| 688 | context.with_network_policy(allowing(&["api.example.com"])) |
| 689 | }); |
| 690 | let absent_guard = absent.begin(); |
| 691 | absent.person.absent.store(true, Ordering::SeqCst); |
| 692 | let unanswered = absent.fetch(&absent_guard, &authority, url.clone()).await; |
| 693 | assert_eq!( |
| 694 | kind(&unanswered), |
| 695 | ("refused".to_string(), NOT_ALLOWED_HERE.to_string()) |
| 696 | ); |
| 697 | absent.person.absent.store(false, Ordering::SeqCst); |
| 698 | assert_eq!( |
| 699 | absent |
| 700 | .fetch(&absent_guard, &authority, url.clone()) |
| 701 | .await |
| 702 | .unwrap()["status"], |
| 703 | 200, |
| 704 | "a card nobody answered is asked again" |
| 705 | ); |
| 706 | |
| 707 | let other = Rig::new("another-session", |context| { |
| 708 | context.with_network_policy(allowing(&["api.example.com"])) |
| 709 | }); |
| 710 | let other_guard = other.begin(); |
| 711 | assert_eq!( |
| 712 | other.fetch(&other_guard, &authority, url).await.unwrap()["status"], |
| 713 | 200 |
| 714 | ); |
| 715 | assert_eq!(other.person.cards().len(), 1, "another session asks again"); |
| 716 | } |
| 717 | |
| 718 | #[tokio::test] |
| 719 | async fn every_send_leaves_an_audit_receipt_without_body_or_credential() { |
| 720 | let _grants = TestGrants::only(&[DshService::Network]); |
| 721 | let server = MockServer::start().await; |
| 722 | Mock::given(method("POST")) |
| 723 | .respond_with(ResponseTemplate::new(201).set_body_string("stored")) |
| 724 | .mount(&server) |
| 725 | .await; |
| 726 | let site = site_for("api.example.com", &server); |
| 727 | let vault = vault(); |
| 728 | keep(&vault, "a", "KEY", &site, SECRET); |
| 729 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 730 | let session = format!("receipt-{}", uuid::Uuid::new_v4().simple()); |
| 731 | let rig = Rig::new(&session, |context| { |
| 732 | context.with_network_policy(allowing(&["api.example.com"])) |
| 733 | }); |
| 734 | let guard = rig.begin(); |
| 735 | let sent = "WORKSPACE-FILE-CONTENTS"; |
| 736 | let result = rig |
| 737 | .fetch( |
| 738 | &guard, |
| 739 | &authority, |
| 740 | json!({ |
| 741 | "url": format!("{site}/upload"), |
| 742 | "method": "post", |
| 743 | "headers": [["authorization", "Bearer codewhale-credential:KEY"]], |
| 744 | "body_base64": STANDARD.encode(sent), |
| 745 | }), |
| 746 | ) |
| 747 | .await |
| 748 | .unwrap(); |
| 749 | assert_eq!(result["status"], 201); |
| 750 | let log = std::fs::read_to_string( |
| 751 | codewhale_runtime::audit::audit_log_path().expect("an audit log path"), |
| 752 | ) |
| 753 | .expect("the audit log"); |
| 754 | let lines: Vec<&str> = log.lines().filter(|line| line.contains(&session)).collect(); |
| 755 | assert_eq!(lines.len(), 1, "{lines:?}"); |
| 756 | let record: Value = serde_json::from_str(lines[0]).unwrap(); |
| 757 | assert_eq!(record["event"], AUDIT_EVENT); |
| 758 | assert_eq!( |
| 759 | record["details"], |
| 760 | json!({ |
| 761 | "plugin": "a", |
| 762 | "session": session, |
| 763 | "site": site, |
| 764 | "method": "POST", |
| 765 | "bytes_out": sent.len(), |
| 766 | "bytes_in": "stored".len(), |
| 767 | "status": 201, |
| 768 | "outcome": "ok", |
| 769 | }) |
| 770 | ); |
| 771 | assert!(!lines[0].contains(SECRET) && !lines[0].contains(sent)); |
| 772 | } |
| 773 | |
| 774 | fn child_without_network(workspace: &Path) -> Arc<crate::tools::subagent::engine::ChildAuthority> { |
| 775 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 776 | let config = codewhale_runtime::config::Config::default() |
| 777 | .with_legacy_root(Some("test-key".to_string()), None); |
| 778 | let client = crate::client::CodewhaleClient::new(&config).expect("a stub client"); |
| 779 | let manager = crate::tools::subagent::new_shared_subagent_manager(workspace.to_path_buf(), 2); |
| 780 | let mut runtime = crate::tools::subagent::SubAgentRuntime::new( |
| 781 | client, |
| 782 | "deepseek-v4-flash".to_string(), |
| 783 | ToolContext::new(workspace), |
| 784 | true, |
| 785 | None, |
| 786 | manager, |
| 787 | ); |
| 788 | runtime.worker_profile.permissions.network = false; |
| 789 | crate::tools::subagent::engine::ChildAuthority::capture( |
| 790 | runtime, |
| 791 | Default::default(), |
| 792 | "child".to_string(), |
| 793 | "child".to_string(), |
| 794 | None, |
| 795 | ) |
| 796 | } |
| 797 | |
| 798 | #[tokio::test] |
| 799 | async fn a_fetch_is_refused_for_a_sub_agent_without_network() { |
| 800 | let _grants = TestGrants::only(&[DshService::Network]); |
| 801 | let server = quiet_server().await; |
| 802 | let vault = vault(); |
| 803 | let authority = authority(&[server.uri()], &vault); |
| 804 | let child = child_without_network(&std::env::temp_dir()); |
| 805 | assert!(child.network_is_denied()); |
| 806 | let rig = Rig::new("child-no-network", |mut context| { |
| 807 | context.execution.child_host = Some(child); |
| 808 | context.with_network_policy(loopback()) |
| 809 | }); |
| 810 | let guard = rig.begin(); |
| 811 | let result = rig |
| 812 | .fetch( |
| 813 | &guard, |
| 814 | &authority, |
| 815 | json!({"url": format!("{}/x", server.uri())}), |
| 816 | ) |
| 817 | .await; |
| 818 | assert_eq!( |
| 819 | kind(&result), |
| 820 | ("refused".to_string(), NOT_ALLOWED_HERE.to_string()) |
| 821 | ); |
| 822 | assert!(rig.person.cards().is_empty()); |
| 823 | } |
| 824 | |
| 825 | #[tokio::test] |
| 826 | async fn a_fetch_is_refused_for_a_worker_whose_envelope_denies_network() { |
| 827 | let _grants = TestGrants::only(&[DshService::Network]); |
| 828 | let server = quiet_server().await; |
| 829 | let vault = vault(); |
| 830 | let authority = authority(&[server.uri()], &vault); |
| 831 | let rig = Rig::new("envelope-no-network", |mut context| { |
| 832 | context.execution.tool_authority = |
| 833 | Some(Arc::new(crate::tools::spec::ToolAuthorityEnvelope { |
| 834 | schema_version: 1, |
| 835 | owner: "worker".to_string(), |
| 836 | authority: crate::tools::spec::ToolMutationAuthority::ReadOnly, |
| 837 | network_access: Some(false), |
| 838 | shell: crate::tools::spec::ToolShellAuthority::ReadOnly, |
| 839 | verification: crate::tools::spec::ToolVerificationAuthority::None, |
| 840 | writable_roots: Vec::new(), |
| 841 | writable_files: Vec::new(), |
| 842 | coordination_contracts: Vec::new(), |
| 843 | })); |
| 844 | context.with_network_policy(loopback()) |
| 845 | }); |
| 846 | let guard = rig.begin(); |
| 847 | let result = rig |
| 848 | .fetch( |
| 849 | &guard, |
| 850 | &authority, |
| 851 | json!({"url": format!("{}/x", server.uri())}), |
| 852 | ) |
| 853 | .await; |
| 854 | assert_eq!( |
| 855 | kind(&result), |
| 856 | ("refused".to_string(), NOT_ALLOWED_HERE.to_string()) |
| 857 | ); |
| 858 | assert!(rig.person.cards().is_empty()); |
| 859 | } |
| 860 | |
| 861 | #[tokio::test] |
| 862 | async fn a_fetch_follows_the_sessions_posture() { |
| 863 | let _grants = TestGrants::only(&[DshService::Network]); |
| 864 | let quiet = quiet_server().await; |
| 865 | let vault = vault(); |
| 866 | let refused_authority = authority(&[quiet.uri()], &vault); |
| 867 | type Shape = Box<dyn FnOnce(ToolContext) -> ToolContext>; |
| 868 | fn shaped(shape: impl FnOnce(ToolContext) -> ToolContext + 'static) -> Shape { |
| 869 | Box::new(shape) |
| 870 | } |
| 871 | let shapes: Vec<(&str, Shape)> = vec![ |
| 872 | ( |
| 873 | "never", |
| 874 | shaped(|mut context| { |
| 875 | context.execution.approval_mode = ApprovalMode::Never; |
| 876 | context |
| 877 | }), |
| 878 | ), |
| 879 | ( |
| 880 | "auto-review", |
| 881 | shaped(|mut context| { |
| 882 | context.execution.approval_mode = ApprovalMode::Auto; |
| 883 | context |
| 884 | }), |
| 885 | ), |
| 886 | ( |
| 887 | "plan", |
| 888 | shaped(|context| context.with_shell_network_denied_hint("plan mode")), |
| 889 | ), |
| 890 | ( |
| 891 | "deny-list", |
| 892 | shaped(|mut context| { |
| 893 | context.execution.disallowed_tools = vec!["fetch_url".to_string()]; |
| 894 | context |
| 895 | }), |
| 896 | ), |
| 897 | ( |
| 898 | "deny-list-of-the-send-itself", |
| 899 | shaped(|mut context| { |
| 900 | context.execution.disallowed_tools = vec![SEND_TOOL.to_string()]; |
| 901 | context |
| 902 | }), |
| 903 | ), |
| 904 | ]; |
| 905 | for (name, shape) in shapes { |
| 906 | let rig = Rig::new(&format!("posture-{name}"), |context| { |
| 907 | shape(context.with_network_policy(loopback())) |
| 908 | }); |
| 909 | let guard = rig.begin(); |
| 910 | let result = rig |
| 911 | .fetch( |
| 912 | &guard, |
| 913 | &refused_authority, |
| 914 | json!({"url": format!("{}/x", quiet.uri())}), |
| 915 | ) |
| 916 | .await; |
| 917 | assert_eq!( |
| 918 | kind(&result), |
| 919 | ("refused".to_string(), NOT_ALLOWED_HERE.to_string()), |
| 920 | "{name}" |
| 921 | ); |
| 922 | assert!(rig.person.cards().is_empty(), "{name}"); |
| 923 | } |
| 924 | let open = ok_server().await; |
| 925 | let open_site = site_for("api.example.com", &open); |
| 926 | let allowed_authority = authority_pinned(&[("api.example.com", &open)], &vault); |
| 927 | for (name, mode) in [ |
| 928 | ("ask", ApprovalMode::Suggest), |
| 929 | ("accept-edits", ApprovalMode::AcceptEdits), |
| 930 | ("full-access", ApprovalMode::Bypass), |
| 931 | ] { |
| 932 | let rig = Rig::new(&format!("posture-{name}"), |mut context| { |
| 933 | context.execution.approval_mode = mode; |
| 934 | context.with_network_policy(allowing(&["api.example.com"])) |
| 935 | }); |
| 936 | let guard = rig.begin(); |
| 937 | let result = rig |
| 938 | .fetch( |
| 939 | &guard, |
| 940 | &allowed_authority, |
| 941 | json!({"url": format!("{open_site}/x")}), |
| 942 | ) |
| 943 | .await |
| 944 | .unwrap(); |
| 945 | assert_eq!(result["status"], 200, "{name}"); |
| 946 | assert_eq!( |
| 947 | rig.person.cards().len(), |
| 948 | 1, |
| 949 | "{name}: the card is still raised" |
| 950 | ); |
| 951 | } |
| 952 | } |
| 953 | |
| 954 | #[tokio::test] |
| 955 | async fn a_posture_narrowed_during_the_call_stops_later_fetches() { |
| 956 | let _grants = TestGrants::only(&[DshService::Network]); |
| 957 | let server = ok_server().await; |
| 958 | let site = site_for("api.example.com", &server); |
| 959 | let vault = vault(); |
| 960 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 961 | let workspace = std::env::temp_dir(); |
| 962 | let posture = crate::core::engine::LivePosture::for_tests(&workspace, ApprovalMode::Suggest); |
| 963 | let live = posture.clone(); |
| 964 | let rig = Rig::new("narrowed", move |mut context| { |
| 965 | context.execution.live_posture = Some(live); |
| 966 | context.with_network_policy(allowing(&["api.example.com"])) |
| 967 | }); |
| 968 | let guard = rig.begin(); |
| 969 | let url = json!({"url": format!("{site}/x")}); |
| 970 | assert_eq!( |
| 971 | rig.fetch(&guard, &authority, url.clone()).await.unwrap()["status"], |
| 972 | 200 |
| 973 | ); |
| 974 | posture.switch_for_tests(ApprovalMode::Never); |
| 975 | let later = rig.fetch(&guard, &authority, url.clone()).await; |
| 976 | assert_eq!( |
| 977 | kind(&later), |
| 978 | ("refused".to_string(), NOT_ALLOWED_HERE.to_string()) |
| 979 | ); |
| 980 | posture.switch_for_tests(ApprovalMode::Suggest); |
| 981 | assert_eq!( |
| 982 | rig.fetch(&guard, &authority, url).await.unwrap()["status"], |
| 983 | 200 |
| 984 | ); |
| 985 | assert_eq!(server.received_requests().await.unwrap().len(), 2); |
| 986 | } |
| 987 | |
| 988 | #[tokio::test] |
| 989 | async fn an_oversized_credential_is_refused_and_the_store_stays_bounded() { |
| 990 | let vault = vault(); |
| 991 | let site = "https://api.example.com".to_string(); |
| 992 | let authority = authority(std::slice::from_ref(&site), &vault); |
| 993 | for (name, value) in [ |
| 994 | ("too long", "x".repeat(MAX_SECRET_BYTES + 1)), |
| 995 | ("too short", "x".repeat(MIN_SECRET_BYTES - 1)), |
| 996 | ("a megabyte", "x".repeat(1024 * 1024)), |
| 997 | ("a line break", format!("{SECRET}\r\nx-injected: 1")), |
| 998 | ("a handle", format!("{CREDENTIAL_HANDLE_PREFIX}OTHER-KEY")), |
| 999 | ] { |
| 1000 | let result = serve_with( |
| 1001 | detached( |
| 1002 | "a", |
| 1003 | "credentials.set", |
| 1004 | json!({"ref": "K", "value": value, "site": site}), |
| 1005 | ), |
| 1006 | authority.clone(), |
| 1007 | ) |
| 1008 | .await; |
| 1009 | assert_eq!(code(&result), "invalid_input", "{name}"); |
| 1010 | } |
| 1011 | assert!(vault.store.get(VAULT_ENTRY).unwrap().is_none()); |
| 1012 | let longest = serve_with( |
| 1013 | detached( |
| 1014 | "a", |
| 1015 | "credentials.set", |
| 1016 | json!({"ref": "K", "value": "x".repeat(MAX_SECRET_BYTES), "site": site}), |
| 1017 | ), |
| 1018 | authority, |
| 1019 | ) |
| 1020 | .await; |
| 1021 | assert!(longest.is_ok()); |
| 1022 | let stored = vault.store.get(VAULT_ENTRY).unwrap().unwrap(); |
| 1023 | assert!(stored.len() < MAX_SECRET_BYTES + 512, "{}", stored.len()); |
| 1024 | } |
| 1025 | |
| 1026 | #[tokio::test] |
| 1027 | async fn a_plugin_cannot_store_more_than_n_credentials() { |
| 1028 | let vault = vault(); |
| 1029 | let site = "https://api.example.com".to_string(); |
| 1030 | let authority = authority(std::slice::from_ref(&site), &vault); |
| 1031 | let set = |name: String| { |
| 1032 | serve_with( |
| 1033 | detached( |
| 1034 | "a", |
| 1035 | "credentials.set", |
| 1036 | json!({"ref": name, "value": SECRET, "site": site}), |
| 1037 | ), |
| 1038 | authority.clone(), |
| 1039 | ) |
| 1040 | }; |
| 1041 | for index in 0..MAX_REFS_PER_PLUGIN { |
| 1042 | assert!(set(format!("K{index}")).await.is_ok(), "{index}"); |
| 1043 | } |
| 1044 | let one_more = set("ONE_MORE".to_string()).await; |
| 1045 | assert_eq!(code(&one_more), "refused"); |
| 1046 | assert!(format!("{one_more:?}").contains(VAULT_FULL)); |
| 1047 | assert!( |
| 1048 | set("K0".to_string()).await.is_ok(), |
| 1049 | "an existing ref is rewritten" |
| 1050 | ); |
| 1051 | |
| 1052 | let total = self::vault(); |
| 1053 | let value = "x".repeat(512); |
| 1054 | for index in 0..MAX_REFS_TOTAL { |
| 1055 | keep( |
| 1056 | &total, |
| 1057 | &format!("plugin-{}", index / MAX_REFS_PER_PLUGIN), |
| 1058 | &format!("K{}", index % MAX_REFS_PER_PLUGIN), |
| 1059 | &site, |
| 1060 | &value, |
| 1061 | ); |
| 1062 | } |
| 1063 | let full = total.write_blocking( |
| 1064 | "one-plugin-too-many", |
| 1065 | BUILD, |
| 1066 | "K", |
| 1067 | Stored { |
| 1068 | site: site.clone(), |
| 1069 | value: value.clone(), |
| 1070 | }, |
| 1071 | ); |
| 1072 | assert!(matches!(full, Err(VaultError::Full))); |
| 1073 | let stored = total.store.get(VAULT_ENTRY).unwrap().unwrap(); |
| 1074 | assert!( |
| 1075 | stored.len() < MAX_REFS_TOTAL * (512 + 256), |
| 1076 | "{}", |
| 1077 | stored.len() |
| 1078 | ); |
| 1079 | } |
| 1080 | |
| 1081 | #[tokio::test] |
| 1082 | async fn headers_are_capped_after_substitution() { |
| 1083 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1084 | let server = quiet_server().await; |
| 1085 | let site = site_for("api.example.com", &server); |
| 1086 | let vault = vault(); |
| 1087 | keep(&vault, "a", "BIG", &site, &"x".repeat(MAX_SECRET_BYTES)); |
| 1088 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 1089 | let rig = Rig::new("header-cap", |context| { |
| 1090 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1091 | }); |
| 1092 | let guard = rig.begin(); |
| 1093 | let url = format!("{site}/x"); |
| 1094 | let handles = |count: usize| -> Vec<Value> { |
| 1095 | (0..count) |
| 1096 | .map(|index| json!([format!("x-key-{index}"), "codewhale-credential:BIG"])) |
| 1097 | .collect() |
| 1098 | }; |
| 1099 | let filled = rig |
| 1100 | .fetch( |
| 1101 | &guard, |
| 1102 | &authority, |
| 1103 | json!({"url": url, "headers": handles(5)}), |
| 1104 | ) |
| 1105 | .await; |
| 1106 | let (code, message) = kind(&filled); |
| 1107 | assert_eq!(code, "invalid_input"); |
| 1108 | assert!( |
| 1109 | message.contains("once credentials are filled in"), |
| 1110 | "{message}" |
| 1111 | ); |
| 1112 | let many = rig |
| 1113 | .fetch( |
| 1114 | &guard, |
| 1115 | &authority, |
| 1116 | json!({"url": url, "headers": handles(MAX_HANDLES_PER_REQUEST + 1)}), |
| 1117 | ) |
| 1118 | .await; |
| 1119 | let (code, message) = kind(&many); |
| 1120 | assert_eq!(code, "invalid_input"); |
| 1121 | assert!(message.contains("credential handles"), "{message}"); |
| 1122 | } |
| 1123 | |
| 1124 | #[test] |
| 1125 | fn scrubbing_is_linear_and_bounded() { |
| 1126 | let names: Vec<String> = (0..MAX_HANDLES_PER_REQUEST) |
| 1127 | .map(|index| handle(&format!("K{index}"))) |
| 1128 | .collect(); |
| 1129 | let near: Vec<(String, String)> = names |
| 1130 | .iter() |
| 1131 | .enumerate() |
| 1132 | .map(|(index, name)| { |
| 1133 | let mut secret = "a".repeat(MAX_SECRET_BYTES - 1); |
| 1134 | secret.push(char::from(b'b' + index as u8)); |
| 1135 | (name.clone(), secret) |
| 1136 | }) |
| 1137 | .collect(); |
| 1138 | let haystack = vec![b'a'; MAX_RESPONSE_BYTES]; |
| 1139 | let started = Instant::now(); |
| 1140 | let clean = scrub(&haystack, &near, MAX_RESPONSE_BYTES).expect("within the cap"); |
| 1141 | assert!( |
| 1142 | started.elapsed() < Duration::from_secs(60), |
| 1143 | "{:?}", |
| 1144 | started.elapsed() |
| 1145 | ); |
| 1146 | assert_eq!(clean.len(), haystack.len()); |
| 1147 | |
| 1148 | let short = vec![("codewhale-credential:S".to_string(), "aaaaaaaa".to_string())]; |
| 1149 | let run = scrub(&vec![b'a'; 1024 * 1024], &short, 64).expect("one run is one handle"); |
| 1150 | assert_eq!(run, b"codewhale-credential:S"); |
| 1151 | let spaced = "aaaaaaaa-".repeat(1000); |
| 1152 | assert!(scrub(spaced.as_bytes(), &short, spaced.len()).is_none()); |
| 1153 | let within = scrub(spaced.as_bytes(), &short, 1024 * 1024).unwrap(); |
| 1154 | assert_eq!( |
| 1155 | String::from_utf8(within).unwrap(), |
| 1156 | "codewhale-credential:S-".repeat(1000) |
| 1157 | ); |
| 1158 | |
| 1159 | let nested = vec![ |
| 1160 | ( |
| 1161 | "codewhale-credential:INNER".to_string(), |
| 1162 | "secretBBBB".to_string(), |
| 1163 | ), |
| 1164 | ( |
| 1165 | "codewhale-credential:OUTER".to_string(), |
| 1166 | "XXXXXXXXsecretBBBBYYYY".to_string(), |
| 1167 | ), |
| 1168 | ]; |
| 1169 | let both = scrub(b"a XXXXXXXXsecretBBBBYYYY b secretBBBB c", &nested, 1024).unwrap(); |
| 1170 | assert_eq!( |
| 1171 | String::from_utf8(both).unwrap(), |
| 1172 | "a codewhale-credential:OUTER b codewhale-credential:INNER c" |
| 1173 | ); |
| 1174 | let overlapping = vec![("codewhale-credential:O".to_string(), "abababab".to_string())]; |
| 1175 | let folded = scrub(b"<ababababab>", &overlapping, 1024).unwrap(); |
| 1176 | assert_eq!(folded, b"<codewhale-credential:O>"); |
| 1177 | assert_eq!(scrub(b"plain", &[], 1024).unwrap(), b"plain"); |
| 1178 | } |
| 1179 | |
| 1180 | #[tokio::test] |
| 1181 | async fn the_runtime_stays_responsive_while_a_fetch_scrubs() { |
| 1182 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1183 | let server = MockServer::start().await; |
| 1184 | Mock::given(method("GET")) |
| 1185 | .and(path("/v1/models")) |
| 1186 | .and(header("authorization", format!("Bearer {SECRET}").as_str())) |
| 1187 | .respond_with(Echo) |
| 1188 | .expect(1) |
| 1189 | .mount(&server) |
| 1190 | .await; |
| 1191 | let site = site_for("api.example.com", &server); |
| 1192 | let vault = vault(); |
| 1193 | keep(&vault, "a", "KEY", &site, SECRET); |
| 1194 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 1195 | let rig = Rig::new("scrub-thread", |context| { |
| 1196 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1197 | }); |
| 1198 | let guard = rig.begin(); |
| 1199 | *SCRUBBED_ON.lock().unwrap() = None; |
| 1200 | let result = rig |
| 1201 | .fetch( |
| 1202 | &guard, |
| 1203 | &authority, |
| 1204 | json!({ |
| 1205 | "url": format!("{site}/v1/models"), |
| 1206 | "headers": [["authorization", "Bearer codewhale-credential:KEY"]], |
| 1207 | }), |
| 1208 | ) |
| 1209 | .await |
| 1210 | .unwrap(); |
| 1211 | assert!(!result.to_string().contains(SECRET)); |
| 1212 | assert_eq!(body(&result), "you sent Bearer codewhale-credential:KEY"); |
| 1213 | assert!( |
| 1214 | result["headers"] |
| 1215 | .as_array() |
| 1216 | .unwrap() |
| 1217 | .iter() |
| 1218 | .any(|pair| pair[0] == "x-echo" && pair[1] == "Bearer codewhale-credential:KEY") |
| 1219 | ); |
| 1220 | let scrubbed_on = SCRUBBED_ON.lock().unwrap().expect("the scrub ran"); |
| 1221 | assert_ne!( |
| 1222 | scrubbed_on, |
| 1223 | std::thread::current().id(), |
| 1224 | "the scrub runs off the thread that drives this single-threaded runtime" |
| 1225 | ); |
| 1226 | } |
| 1227 | |
| 1228 | #[tokio::test] |
| 1229 | async fn at_most_n_fetches_run_at_once_per_invocation() { |
| 1230 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1231 | let server = MockServer::start().await; |
| 1232 | let delay = Duration::from_millis(400); |
| 1233 | Mock::given(path("/slow")) |
| 1234 | .respond_with(ResponseTemplate::new(200).set_delay(delay)) |
| 1235 | .mount(&server) |
| 1236 | .await; |
| 1237 | Mock::given(path("/first")) |
| 1238 | .respond_with(ResponseTemplate::new(200)) |
| 1239 | .mount(&server) |
| 1240 | .await; |
| 1241 | let site = site_for("api.example.com", &server); |
| 1242 | let vault = vault(); |
| 1243 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 1244 | let rig = Rig::new("four-at-once", |context| { |
| 1245 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1246 | }); |
| 1247 | let guard = rig.begin(); |
| 1248 | rig.fetch(&guard, &authority, json!({"url": format!("{site}/first")})) |
| 1249 | .await |
| 1250 | .unwrap(); |
| 1251 | let started = Instant::now(); |
| 1252 | let results = futures_util::future::join_all( |
| 1253 | (0..MAX_FETCHES_AT_ONCE * 2) |
| 1254 | .map(|_| rig.fetch(&guard, &authority, json!({"url": format!("{site}/slow")}))), |
| 1255 | ) |
| 1256 | .await; |
| 1257 | assert!(results.iter().all(Result::is_ok)); |
| 1258 | assert!( |
| 1259 | started.elapsed() >= delay * 2 - Duration::from_millis(50), |
| 1260 | "eight fetches, four at once, take two rounds: {:?}", |
| 1261 | started.elapsed() |
| 1262 | ); |
| 1263 | } |
| 1264 | |
| 1265 | #[tokio::test] |
| 1266 | async fn a_credential_is_sent_only_to_the_origin_it_was_bound_to() { |
| 1267 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1268 | let home = MockServer::start().await; |
| 1269 | Mock::given(header("authorization", SECRET)) |
| 1270 | .respond_with(ResponseTemplate::new(200).set_body_string("ok")) |
| 1271 | .expect(1) |
| 1272 | .mount(&home) |
| 1273 | .await; |
| 1274 | let other = quiet_server().await; |
| 1275 | let home_site = site_for("api.example.com", &home); |
| 1276 | let other_site = site_for("other.example.com", &other); |
| 1277 | let vault = vault(); |
| 1278 | let authority = authority_pinned( |
| 1279 | &[("api.example.com", &home), ("other.example.com", &other)], |
| 1280 | &vault, |
| 1281 | ); |
| 1282 | let rig = Rig::new("bound-origin", |context| { |
| 1283 | context.with_network_policy(allowing(&["api.example.com", "other.example.com"])) |
| 1284 | }); |
| 1285 | let guard = rig.begin(); |
| 1286 | rig.call( |
| 1287 | &guard, |
| 1288 | &authority, |
| 1289 | "credentials.set", |
| 1290 | json!({"ref": "KEY", "value": SECRET, "site": home_site}), |
| 1291 | ) |
| 1292 | .await |
| 1293 | .unwrap(); |
| 1294 | let headers = json!([["authorization", "codewhale-credential:KEY"]]); |
| 1295 | let at_home = rig |
| 1296 | .fetch( |
| 1297 | &guard, |
| 1298 | &authority, |
| 1299 | json!({"url": format!("{home_site}/x"), "headers": headers}), |
| 1300 | ) |
| 1301 | .await |
| 1302 | .unwrap(); |
| 1303 | assert_eq!(at_home["status"], 200); |
| 1304 | let elsewhere = rig |
| 1305 | .fetch( |
| 1306 | &guard, |
| 1307 | &authority, |
| 1308 | json!({"url": format!("{other_site}/x"), "headers": headers}), |
| 1309 | ) |
| 1310 | .await; |
| 1311 | assert_eq!( |
| 1312 | kind(&elsewhere), |
| 1313 | ("refused".to_string(), NOT_FOR_THIS_SITE.to_string()) |
| 1314 | ); |
| 1315 | assert_eq!( |
| 1316 | rig.person.cards().len(), |
| 1317 | 1, |
| 1318 | "no card for a send that is refused" |
| 1319 | ); |
| 1320 | } |
| 1321 | |
| 1322 | #[tokio::test] |
| 1323 | async fn a_credential_is_never_sent_over_plain_http() { |
| 1324 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1325 | let server = quiet_server().await; |
| 1326 | let site = site_for("api.example.com", &server); |
| 1327 | let strict = Vault { |
| 1328 | plaintext_for_test: false, |
| 1329 | ..vault() |
| 1330 | }; |
| 1331 | let authority = authority_pinned(&[("api.example.com", &server)], &strict); |
| 1332 | let rig = Rig::new("https-only", |context| { |
| 1333 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1334 | }); |
| 1335 | let guard = rig.begin(); |
| 1336 | let stored = rig |
| 1337 | .call( |
| 1338 | &guard, |
| 1339 | &authority, |
| 1340 | "credentials.set", |
| 1341 | json!({"ref": "KEY", "value": SECRET, "site": site}), |
| 1342 | ) |
| 1343 | .await; |
| 1344 | assert_eq!(kind(&stored).0, "invalid_input"); |
| 1345 | keep(&strict, "a", "KEY", &site, SECRET); |
| 1346 | let sent = rig |
| 1347 | .fetch( |
| 1348 | &guard, |
| 1349 | &authority, |
| 1350 | json!({ |
| 1351 | "url": format!("{site}/x"), |
| 1352 | "headers": [["authorization", "codewhale-credential:KEY"]], |
| 1353 | }), |
| 1354 | ) |
| 1355 | .await; |
| 1356 | assert_eq!( |
| 1357 | kind(&sent), |
| 1358 | ("refused".to_string(), NOT_FOR_THIS_SITE.to_string()) |
| 1359 | ); |
| 1360 | } |
| 1361 | |
| 1362 | #[tokio::test] |
| 1363 | async fn another_port_of_a_reviewed_host_is_refused() { |
| 1364 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1365 | let reviewed = quiet_server().await; |
| 1366 | let other_port = quiet_server().await; |
| 1367 | let reviewed_site = site_for("api.example.com", &reviewed); |
| 1368 | let other_site = site_for("api.example.com", &other_port); |
| 1369 | let vault = vault(); |
| 1370 | let authority = authority_pinned(&[("api.example.com", &reviewed)], &vault); |
| 1371 | let rig = Rig::new("other-port", |context| { |
| 1372 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1373 | }); |
| 1374 | let guard = rig.begin(); |
| 1375 | for url in [ |
| 1376 | format!("{other_site}/x"), |
| 1377 | reviewed_site.replace("http://", "https://"), |
| 1378 | reviewed_site.replace("api.example.com", "localhost"), |
| 1379 | "https://unreviewed.example.com/".to_string(), |
| 1380 | ] { |
| 1381 | let result = rig.fetch(&guard, &authority, json!({"url": url})).await; |
| 1382 | assert_eq!( |
| 1383 | kind(&result), |
| 1384 | ("refused".to_string(), NOT_REVIEWED.to_string()), |
| 1385 | "{url}" |
| 1386 | ); |
| 1387 | } |
| 1388 | assert!(rig.person.cards().is_empty()); |
| 1389 | } |
| 1390 | |
| 1391 | #[tokio::test] |
| 1392 | async fn a_compressed_or_partial_echo_never_returns_the_secret() { |
| 1393 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1394 | let server = ok_server().await; |
| 1395 | let site = site_for("api.example.com", &server); |
| 1396 | let vault = vault(); |
| 1397 | keep(&vault, "a", "KEY", &site, SECRET); |
| 1398 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 1399 | let rig = Rig::new("echo-shapes", |context| { |
| 1400 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1401 | }); |
| 1402 | let guard = rig.begin(); |
| 1403 | let url = format!("{site}/x"); |
| 1404 | for (name, value) in [ |
| 1405 | ("Accept-Encoding", "gzip"), |
| 1406 | ("Range", "bytes=0-10"), |
| 1407 | ("If-Range", "\"etag\""), |
| 1408 | ] { |
| 1409 | let result = rig |
| 1410 | .fetch( |
| 1411 | &guard, |
| 1412 | &authority, |
| 1413 | json!({ |
| 1414 | "url": url, |
| 1415 | "headers": [["authorization", "codewhale-credential:KEY"], [name, value]], |
| 1416 | }), |
| 1417 | ) |
| 1418 | .await; |
| 1419 | let (code, message) = kind(&result); |
| 1420 | assert_eq!(code, "invalid_input", "{name}"); |
| 1421 | assert!(message.contains("together with a credential"), "{message}"); |
| 1422 | } |
| 1423 | assert!(server.received_requests().await.unwrap().is_empty()); |
| 1424 | let plain = rig |
| 1425 | .fetch( |
| 1426 | &guard, |
| 1427 | &authority, |
| 1428 | json!({"url": url, "headers": [["Accept-Encoding", "gzip"], ["Range", "bytes=0-1"]]}), |
| 1429 | ) |
| 1430 | .await |
| 1431 | .unwrap(); |
| 1432 | assert_eq!(plain["status"], 200, "without a credential they are sent"); |
| 1433 | } |
| 1434 | |
| 1435 | #[tokio::test] |
| 1436 | async fn the_final_url_is_scrubbed() { |
| 1437 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1438 | let server = MockServer::start().await; |
| 1439 | Mock::given(path("/start")) |
| 1440 | .respond_with( |
| 1441 | ResponseTemplate::new(307) |
| 1442 | .insert_header("location", format!("/landing?token={SECRET}").as_str()), |
| 1443 | ) |
| 1444 | .mount(&server) |
| 1445 | .await; |
| 1446 | Mock::given(path("/landing")) |
| 1447 | .and(header("authorization", SECRET)) |
| 1448 | .respond_with(ResponseTemplate::new(200).set_body_string("ok")) |
| 1449 | .expect(1) |
| 1450 | .mount(&server) |
| 1451 | .await; |
| 1452 | let site = site_for("api.example.com", &server); |
| 1453 | let vault = vault(); |
| 1454 | keep(&vault, "a", "KEY", &site, SECRET); |
| 1455 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 1456 | let rig = Rig::new("final-url", |context| { |
| 1457 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1458 | }); |
| 1459 | let guard = rig.begin(); |
| 1460 | let result = rig |
| 1461 | .fetch( |
| 1462 | &guard, |
| 1463 | &authority, |
| 1464 | json!({ |
| 1465 | "url": format!("{site}/start"), |
| 1466 | "headers": [["authorization", "codewhale-credential:KEY"]], |
| 1467 | }), |
| 1468 | ) |
| 1469 | .await |
| 1470 | .unwrap(); |
| 1471 | assert_eq!(result["redirected"], true); |
| 1472 | assert!(!result.to_string().contains(SECRET), "{result}"); |
| 1473 | assert_eq!( |
| 1474 | result["url"], |
| 1475 | format!("{site}/landing?token=codewhale-credential:KEY") |
| 1476 | ); |
| 1477 | assert_eq!( |
| 1478 | rig.person.cards().len(), |
| 1479 | 1, |
| 1480 | "a redirect on the same site asks once" |
| 1481 | ); |
| 1482 | } |
| 1483 | |
| 1484 | #[tokio::test] |
| 1485 | async fn a_reinstalled_plugin_does_not_inherit_credentials() { |
| 1486 | let vault = vault(); |
| 1487 | let site = "https://api.example.com".to_string(); |
| 1488 | keep(&vault, "a", "OLD", &site, SECRET); |
| 1489 | let reinstalled = NetworkAuthority { |
| 1490 | build: "build-2".to_string(), |
| 1491 | ..authority(std::slice::from_ref(&site), &vault) |
| 1492 | }; |
| 1493 | let resolved = serve_with( |
| 1494 | detached("a", "credentials.resolve", json!({"ref": "OLD"})), |
| 1495 | reinstalled.clone(), |
| 1496 | ) |
| 1497 | .await |
| 1498 | .unwrap(); |
| 1499 | assert_eq!(resolved["value"], Value::Null); |
| 1500 | let described = serve_with( |
| 1501 | detached("a", "credentials.describe", json!({"ref": "OLD"})), |
| 1502 | reinstalled.clone(), |
| 1503 | ) |
| 1504 | .await |
| 1505 | .unwrap(); |
| 1506 | assert_eq!(described["set"], false); |
| 1507 | assert!( |
| 1508 | vault |
| 1509 | .read_blocking("a", "build-2") |
| 1510 | .is_ok_and(|slots| slots.is_empty()) |
| 1511 | ); |
| 1512 | serve_with( |
| 1513 | detached( |
| 1514 | "a", |
| 1515 | "credentials.set", |
| 1516 | json!({"ref": "NEW", "value": "another-secret-value", "site": site}), |
| 1517 | ), |
| 1518 | reinstalled, |
| 1519 | ) |
| 1520 | .await |
| 1521 | .unwrap(); |
| 1522 | assert!( |
| 1523 | !vault |
| 1524 | .store |
| 1525 | .get(VAULT_ENTRY) |
| 1526 | .unwrap() |
| 1527 | .unwrap() |
| 1528 | .contains(SECRET), |
| 1529 | "the first build's slots are gone once the new build writes" |
| 1530 | ); |
| 1531 | assert!( |
| 1532 | vault |
| 1533 | .read_blocking("a", BUILD) |
| 1534 | .is_ok_and(|slots| slots.is_empty()) |
| 1535 | ); |
| 1536 | } |
| 1537 | |
| 1538 | #[test] |
| 1539 | fn uninstall_deletes_a_plugins_credentials() { |
| 1540 | let vault = vault(); |
| 1541 | keep(&vault, "a", "KEY", "https://api.example.com", SECRET); |
| 1542 | keep( |
| 1543 | &vault, |
| 1544 | "b", |
| 1545 | "KEY", |
| 1546 | "https://api.example.com", |
| 1547 | "the-other-plugins-key", |
| 1548 | ); |
| 1549 | assert!(vault.forget_blocking("a").is_ok()); |
| 1550 | assert!( |
| 1551 | vault |
| 1552 | .read_blocking("a", BUILD) |
| 1553 | .is_ok_and(|slots| slots.is_empty()) |
| 1554 | ); |
| 1555 | assert!( |
| 1556 | vault |
| 1557 | .read_blocking("b", BUILD) |
| 1558 | .is_ok_and(|slots| slots.contains_key("KEY")) |
| 1559 | ); |
| 1560 | assert!( |
| 1561 | !vault |
| 1562 | .store |
| 1563 | .get(VAULT_ENTRY) |
| 1564 | .unwrap() |
| 1565 | .unwrap() |
| 1566 | .contains(SECRET) |
| 1567 | ); |
| 1568 | assert!(vault.forget_blocking("never-installed").is_ok()); |
| 1569 | } |
| 1570 | |
| 1571 | #[test] |
| 1572 | fn the_vault_is_its_own_private_file() { |
| 1573 | let home = tempfile::tempdir().unwrap(); |
| 1574 | let file = vault_path(home.path()); |
| 1575 | assert_eq!( |
| 1576 | file, |
| 1577 | home.path().join("secrets").join("plugin-credentials.json") |
| 1578 | ); |
| 1579 | let vault = Vault::at(file.clone()); |
| 1580 | keep(&vault, "a", "KEY", "https://api.example.com", SECRET); |
| 1581 | assert!(file.is_file()); |
| 1582 | assert!( |
| 1583 | !home.path().join("secrets").join("secrets.json").exists(), |
| 1584 | "the provider key file is not touched" |
| 1585 | ); |
| 1586 | #[cfg(unix)] |
| 1587 | { |
| 1588 | use std::os::unix::fs::PermissionsExt; |
| 1589 | let mode = std::fs::metadata(&file).unwrap().permissions().mode(); |
| 1590 | assert_eq!(mode & 0o077, 0, "{mode:o}"); |
| 1591 | } |
| 1592 | let reopened = Vault::at(file); |
| 1593 | assert!( |
| 1594 | reopened |
| 1595 | .read_blocking("a", BUILD) |
| 1596 | .is_ok_and(|slots| slots["KEY"].value == SECRET) |
| 1597 | ); |
| 1598 | } |
| 1599 | |
| 1600 | #[tokio::test] |
| 1601 | async fn an_unreadable_vault_refuses_the_send() { |
| 1602 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1603 | let server = quiet_server().await; |
| 1604 | let site = site_for("api.example.com", &server); |
| 1605 | let vault = vault(); |
| 1606 | vault.store.set(VAULT_ENTRY, "{ not json").unwrap(); |
| 1607 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 1608 | let rig = Rig::new("bad-vault", |context| { |
| 1609 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1610 | }); |
| 1611 | let guard = rig.begin(); |
| 1612 | let sent = rig |
| 1613 | .fetch( |
| 1614 | &guard, |
| 1615 | &authority, |
| 1616 | json!({ |
| 1617 | "url": format!("{site}/x"), |
| 1618 | "headers": [["authorization", "codewhale-credential:KEY"]], |
| 1619 | }), |
| 1620 | ) |
| 1621 | .await; |
| 1622 | assert_eq!( |
| 1623 | kind(&sent), |
| 1624 | ("refused".to_string(), VAULT_UNREADABLE.to_string()) |
| 1625 | ); |
| 1626 | let stored = rig |
| 1627 | .call( |
| 1628 | &guard, |
| 1629 | &authority, |
| 1630 | "credentials.set", |
| 1631 | json!({"ref": "KEY", "value": SECRET, "site": site}), |
| 1632 | ) |
| 1633 | .await; |
| 1634 | assert_eq!(kind(&stored).0, "refused"); |
| 1635 | assert_eq!( |
| 1636 | vault.store.get(VAULT_ENTRY).unwrap().as_deref(), |
| 1637 | Some("{ not json"), |
| 1638 | "a store that cannot be read is not overwritten" |
| 1639 | ); |
| 1640 | } |
| 1641 | |
| 1642 | #[tokio::test] |
| 1643 | async fn a_redirect_to_another_site_is_a_new_site_with_its_own_card() { |
| 1644 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1645 | let landing = Seen::default(); |
| 1646 | let second = MockServer::start().await; |
| 1647 | Mock::given(path("/landing")) |
| 1648 | .respond_with(landing.clone()) |
| 1649 | .mount(&second) |
| 1650 | .await; |
| 1651 | let first = MockServer::start().await; |
| 1652 | let first_site = site_for("api.example.com", &first); |
| 1653 | let second_site = site_for("other.example.com", &second); |
| 1654 | Mock::given(path("/away")) |
| 1655 | .respond_with( |
| 1656 | ResponseTemplate::new(307) |
| 1657 | .insert_header("location", format!("{second_site}/landing").as_str()), |
| 1658 | ) |
| 1659 | .mount(&first) |
| 1660 | .await; |
| 1661 | let vault = vault(); |
| 1662 | keep(&vault, "a", "KEY", &first_site, SECRET); |
| 1663 | let authority = authority_pinned( |
| 1664 | &[("api.example.com", &first), ("other.example.com", &second)], |
| 1665 | &vault, |
| 1666 | ); |
| 1667 | let rig = Rig::new("redirect-new-site", |context| { |
| 1668 | context.with_network_policy(allowing(&["api.example.com", "other.example.com"])) |
| 1669 | }); |
| 1670 | let guard = rig.begin(); |
| 1671 | let result = rig |
| 1672 | .fetch( |
| 1673 | &guard, |
| 1674 | &authority, |
| 1675 | json!({ |
| 1676 | "url": format!("{first_site}/away"), |
| 1677 | "headers": [ |
| 1678 | ["authorization", "Bearer codewhale-credential:KEY"], |
| 1679 | ["x-key", "codewhale-credential:KEY"], |
| 1680 | ["cookie", "typed-by-the-plugin"], |
| 1681 | ["x-plain", "1"], |
| 1682 | ], |
| 1683 | }), |
| 1684 | ) |
| 1685 | .await |
| 1686 | .unwrap(); |
| 1687 | assert_eq!(result["status"], 200); |
| 1688 | assert_eq!(result["redirected"], true); |
| 1689 | assert_eq!(body(&result), "landed"); |
| 1690 | let cards = rig.person.cards(); |
| 1691 | assert_eq!(cards.len(), 2, "{cards:?}"); |
| 1692 | assert_eq!(cards[0].0["url"], format!("{first_site}/")); |
| 1693 | assert_eq!(cards[1].0["url"], format!("{second_site}/")); |
| 1694 | let seen = landing.0.lock().unwrap().clone(); |
| 1695 | assert_eq!(seen.len(), 1); |
| 1696 | let names: Vec<&str> = seen[0].iter().map(|(name, _)| name.as_str()).collect(); |
| 1697 | assert!(names.contains(&"x-plain"), "{names:?}"); |
| 1698 | for dropped in ["authorization", "x-key", "cookie"] { |
| 1699 | assert!(!names.contains(&dropped), "{dropped} followed the redirect"); |
| 1700 | } |
| 1701 | assert!(seen[0].iter().all(|(_, value)| !value.contains(SECRET))); |
| 1702 | } |
| 1703 | |
| 1704 | #[tokio::test] |
| 1705 | async fn a_redirect_never_reaches_a_site_the_person_declined() { |
| 1706 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1707 | let second = quiet_server().await; |
| 1708 | let first = MockServer::start().await; |
| 1709 | let first_site = site_for("api.example.com", &first); |
| 1710 | let second_site = site_for("other.example.com", &second); |
| 1711 | Mock::given(path("/away")) |
| 1712 | .respond_with( |
| 1713 | ResponseTemplate::new(302) |
| 1714 | .insert_header("location", format!("{second_site}/landing").as_str()), |
| 1715 | ) |
| 1716 | .mount(&first) |
| 1717 | .await; |
| 1718 | let vault = vault(); |
| 1719 | let authority = authority_pinned( |
| 1720 | &[("api.example.com", &first), ("other.example.com", &second)], |
| 1721 | &vault, |
| 1722 | ); |
| 1723 | let rig = Rig::new("redirect-declined", |context| { |
| 1724 | context.with_network_policy(allowing(&["api.example.com", "other.example.com"])) |
| 1725 | }); |
| 1726 | let guard = rig.begin(); |
| 1727 | let landing = rig |
| 1728 | .fetch( |
| 1729 | &guard, |
| 1730 | &authority, |
| 1731 | json!({"url": format!("{first_site}/landing")}), |
| 1732 | ) |
| 1733 | .await; |
| 1734 | assert!(landing.is_ok(), "the first site is approved"); |
| 1735 | rig.person.says_no.store(true, Ordering::SeqCst); |
| 1736 | let result = rig |
| 1737 | .fetch( |
| 1738 | &guard, |
| 1739 | &authority, |
| 1740 | json!({"url": format!("{first_site}/away")}), |
| 1741 | ) |
| 1742 | .await; |
| 1743 | assert_eq!(kind(&result), ("denied".to_string(), DECLINED.to_string())); |
| 1744 | } |
| 1745 | |
| 1746 | #[tokio::test] |
| 1747 | async fn a_redirect_to_an_unreviewed_site_is_refused() { |
| 1748 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1749 | let unreviewed = quiet_server().await; |
| 1750 | let first = MockServer::start().await; |
| 1751 | let first_site = site_for("api.example.com", &first); |
| 1752 | Mock::given(path("/away")) |
| 1753 | .respond_with( |
| 1754 | ResponseTemplate::new(302) |
| 1755 | .insert_header("location", format!("{}/steal", unreviewed.uri()).as_str()), |
| 1756 | ) |
| 1757 | .mount(&first) |
| 1758 | .await; |
| 1759 | Mock::given(path("/rename")) |
| 1760 | .respond_with(ResponseTemplate::new(302).insert_header( |
| 1761 | "location", |
| 1762 | first_site.replace("api.example.com", "localhost").as_str(), |
| 1763 | )) |
| 1764 | .mount(&first) |
| 1765 | .await; |
| 1766 | let vault = vault(); |
| 1767 | let authority = authority_pinned(&[("api.example.com", &first)], &vault); |
| 1768 | let rig = Rig::new("redirect-unreviewed", |context| { |
| 1769 | context.with_network_policy(allowing(&["api.example.com", "127.0.0.1", "localhost"])) |
| 1770 | }); |
| 1771 | let guard = rig.begin(); |
| 1772 | for route in ["away", "rename"] { |
| 1773 | let result = rig |
| 1774 | .fetch( |
| 1775 | &guard, |
| 1776 | &authority, |
| 1777 | json!({"url": format!("{first_site}/{route}")}), |
| 1778 | ) |
| 1779 | .await; |
| 1780 | assert_eq!( |
| 1781 | kind(&result), |
| 1782 | ("refused".to_string(), NOT_REVIEWED.to_string()), |
| 1783 | "{route}" |
| 1784 | ); |
| 1785 | } |
| 1786 | assert_eq!(rig.person.cards().len(), 1); |
| 1787 | } |
| 1788 | |
| 1789 | #[tokio::test] |
| 1790 | async fn an_egress_refusal_reports_no_resolved_address() { |
| 1791 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1792 | let local = quiet_server().await; |
| 1793 | let localhost_site = local.uri().replace("127.0.0.1", "localhost"); |
| 1794 | let vault = vault(); |
| 1795 | let metadata = "http://169.254.169.254".to_string(); |
| 1796 | let authority = authority( |
| 1797 | &[metadata.clone(), local.uri(), localhost_site.clone()], |
| 1798 | &vault, |
| 1799 | ); |
| 1800 | let rig = Rig::new("no-address", |context| { |
| 1801 | context.with_network_policy(allowing(&["169.254.169.254", "127.0.0.1", "localhost"])) |
| 1802 | }); |
| 1803 | let guard = rig.begin(); |
| 1804 | for target in [metadata, local.uri(), localhost_site] { |
| 1805 | let result = rig |
| 1806 | .fetch( |
| 1807 | &guard, |
| 1808 | &authority, |
| 1809 | json!({"url": format!("{target}/latest")}), |
| 1810 | ) |
| 1811 | .await; |
| 1812 | let (code, message) = kind(&result); |
| 1813 | assert_eq!(code, "refused", "{target}"); |
| 1814 | assert_eq!(message, NOT_ALLOWED_HERE, "{target}"); |
| 1815 | for leak in [ |
| 1816 | "169.254", |
| 1817 | "127.0.0.1", |
| 1818 | "localhost", |
| 1819 | "restricted", |
| 1820 | "resolved", |
| 1821 | "/network", |
| 1822 | "policy", |
| 1823 | ] { |
| 1824 | assert!(!message.contains(leak), "{message}"); |
| 1825 | } |
| 1826 | } |
| 1827 | assert!(rig.person.cards().is_empty()); |
| 1828 | } |
| 1829 | |
| 1830 | #[tokio::test] |
| 1831 | async fn a_host_with_a_trailing_dot_is_refused_before_any_lookup() { |
| 1832 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1833 | let vault = vault(); |
| 1834 | let authority = authority(&["http://example.com".to_string()], &vault); |
| 1835 | let rig = Rig::new("trailing-dot", |context| { |
| 1836 | context.with_network_policy(allowing(&["example.com"])) |
| 1837 | }); |
| 1838 | let guard = rig.begin(); |
| 1839 | for url in [ |
| 1840 | "http://example.com./", |
| 1841 | "http://user:pw@example.com/", |
| 1842 | "ftp://example.com/", |
| 1843 | ] { |
| 1844 | let result = rig.fetch(&guard, &authority, json!({"url": url})).await; |
| 1845 | assert_eq!(kind(&result).0, "invalid_input", "{url}"); |
| 1846 | } |
| 1847 | let in_url = rig |
| 1848 | .fetch( |
| 1849 | &guard, |
| 1850 | &authority, |
| 1851 | json!({"url": "http://example.com/?k=codewhale-credential:KEY"}), |
| 1852 | ) |
| 1853 | .await; |
| 1854 | assert_eq!(kind(&in_url).0, "invalid_input"); |
| 1855 | let host_header = rig |
| 1856 | .fetch( |
| 1857 | &guard, |
| 1858 | &authority, |
| 1859 | json!({"url": "http://example.com/", "headers": [["Host", "evil.example"]]}), |
| 1860 | ) |
| 1861 | .await; |
| 1862 | assert_eq!(kind(&host_header).0, "invalid_input"); |
| 1863 | assert!(rig.person.cards().is_empty()); |
| 1864 | } |
| 1865 | |
| 1866 | #[tokio::test] |
| 1867 | async fn the_client_connects_only_to_the_pinned_address() { |
| 1868 | let server = MockServer::start().await; |
| 1869 | Mock::given(path("/pin")) |
| 1870 | .and(header( |
| 1871 | "host", |
| 1872 | format!("pinned.invalid:{}", server.address().port()).as_str(), |
| 1873 | )) |
| 1874 | .respond_with(ResponseTemplate::new(204)) |
| 1875 | .expect(1) |
| 1876 | .mount(&server) |
| 1877 | .await; |
| 1878 | let client = pinned_client( |
| 1879 | Some(("pinned.invalid".to_string(), server.address().ip())), |
| 1880 | Duration::from_secs(10), |
| 1881 | ) |
| 1882 | .unwrap(); |
| 1883 | let response = client |
| 1884 | .get(format!( |
| 1885 | "http://pinned.invalid:{}/pin", |
| 1886 | server.address().port() |
| 1887 | )) |
| 1888 | .send() |
| 1889 | .await |
| 1890 | .expect("the pinned address answers for a name no resolver knows"); |
| 1891 | assert_eq!(response.status().as_u16(), 204); |
| 1892 | } |
| 1893 | |
| 1894 | #[test] |
| 1895 | fn the_first_send_card_cannot_be_skipped_by_a_grant_or_a_posture() { |
| 1896 | use super::super::core_call::{OriginApproval, origin_approval, refusal}; |
| 1897 | use crate::core::authority::{ |
| 1898 | ApprovalRequestDisposition as D, RunOrigin, TurnAuthority, |
| 1899 | resolve_approval_request_disposition, |
| 1900 | }; |
| 1901 | use codewhale_config::AppMode; |
| 1902 | |
| 1903 | let input = json!({"request": "r", "plugin": "a", "url": "https://api.example.com/"}); |
| 1904 | let spec: Arc<dyn ToolSpec> = Arc::new(SendConsent); |
| 1905 | assert_eq!( |
| 1906 | origin_approval(SEND_TOOL, &input, true, Some(spec.as_ref())), |
| 1907 | OriginApproval::ForcePrompt |
| 1908 | ); |
| 1909 | assert_eq!( |
| 1910 | refusal(std::slice::from_ref(&spec), SEND_TOOL, &input), |
| 1911 | None |
| 1912 | ); |
| 1913 | let posture = |auto_approve: bool, mode: ApprovalMode, granted: bool, owner_present: bool| { |
| 1914 | let mut authority = |
| 1915 | TurnAuthority::from_effective_fields(AppMode::Agent, true, false, auto_approve, mode); |
| 1916 | if owner_present { |
| 1917 | authority = authority.with_rust_origin(RunOrigin::Interactive, true); |
| 1918 | } |
| 1919 | resolve_approval_request_disposition(&authority, granted, false, true, "extcall:ext:test") |
| 1920 | }; |
| 1921 | for granted in [false, true] { |
| 1922 | assert_eq!( |
| 1923 | posture(false, ApprovalMode::Suggest, granted, true), |
| 1924 | D::Prompt |
| 1925 | ); |
| 1926 | assert_eq!( |
| 1927 | posture(true, ApprovalMode::Bypass, granted, true), |
| 1928 | D::Prompt |
| 1929 | ); |
| 1930 | assert_eq!(posture(false, ApprovalMode::Auto, granted, true), D::Prompt); |
| 1931 | assert_eq!( |
| 1932 | posture(false, ApprovalMode::Auto, granted, false), |
| 1933 | D::AutoDenyAutoReview |
| 1934 | ); |
| 1935 | assert_eq!( |
| 1936 | posture(false, ApprovalMode::Never, granted, true), |
| 1937 | D::AutoDenyNeverPosture |
| 1938 | ); |
| 1939 | } |
| 1940 | } |
| 1941 | |
| 1942 | #[tokio::test] |
| 1943 | async fn a_denied_service_act_leaves_credentials_and_network_uncalled_and_records_the_act() { |
| 1944 | let _grants = TestGrants::only(&[DshService::Network]); |
| 1945 | let server = quiet_server().await; |
| 1946 | let site = site_for("api.example.com", &server); |
| 1947 | let vault = vault(); |
| 1948 | let authority = authority_pinned(&[("api.example.com", &server)], &vault); |
| 1949 | let rig = Rig::new("denied-act", |context| { |
| 1950 | context.with_network_policy(allowing(&["api.example.com"])) |
| 1951 | }); |
| 1952 | rig.person.act_denied.store(true, Ordering::SeqCst); |
| 1953 | let guard = rig.begin(); |
| 1954 | |
| 1955 | let write = rig |
| 1956 | .call( |
| 1957 | &guard, |
| 1958 | &authority, |
| 1959 | "credentials.set", |
| 1960 | json!({"ref": "KEY", "value": SECRET, "site": site}), |
| 1961 | ) |
| 1962 | .await; |
| 1963 | assert_eq!(kind(&write).0, "denied"); |
| 1964 | assert!(vault.store.get(VAULT_ENTRY).unwrap().is_none()); |
| 1965 | |
| 1966 | let reach = rig |
| 1967 | .fetch(&guard, &authority, json!({"url": format!("{site}/x")})) |
| 1968 | .await; |
| 1969 | assert_eq!(kind(&reach).0, "denied"); |
| 1970 | assert!(rig.person.cards().is_empty()); |
| 1971 | assert!(server.received_requests().await.unwrap().is_empty()); |
| 1972 | |
| 1973 | let described = rig |
| 1974 | .call( |
| 1975 | &guard, |
| 1976 | &authority, |
| 1977 | "credentials.describe", |
| 1978 | json!({"ref": "KEY"}), |
| 1979 | ) |
| 1980 | .await |
| 1981 | .unwrap(); |
| 1982 | assert_eq!(described["set"], false); |
| 1983 | |
| 1984 | let receipts = guard.receipts().expect("acts recorded"); |
| 1985 | let acts = &receipts["broker_acts"]; |
| 1986 | assert_eq!(acts["total"], 3, "{receipts}"); |
| 1987 | assert_eq!( |
| 1988 | acts["acts"] |
| 1989 | .as_array() |
| 1990 | .unwrap() |
| 1991 | .iter() |
| 1992 | .map(|entry| ( |
| 1993 | entry["service"].as_str().unwrap(), |
| 1994 | entry["method"].as_str().unwrap(), |
| 1995 | entry["effect"].as_str().unwrap(), |
| 1996 | entry["outcome"].as_str().unwrap(), |
| 1997 | entry["target"].as_str().unwrap(), |
| 1998 | )) |
| 1999 | .collect::<Vec<_>>(), |
| 2000 | vec![ |
| 2001 | ("network", "credentials.set", "write", "denied", "KEY"), |
| 2002 | ("network", "fetch", "reach", "denied", "api.example.com"), |
| 2003 | ("network", "credentials.describe", "read", "read", "KEY"), |
| 2004 | ] |
| 2005 | ); |
| 2006 | } |
| 2007 |