| 1 | use std::io::Cursor; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use base64::Engine as _; |
| 6 | use base64::engine::general_purpose::STANDARD; |
| 7 | use codewhale_config::OwnerRef; |
| 8 | use codewhale_models::{ContentBlock, ImageUrlContent, Message, Role}; |
| 9 | use codewhale_plugins::activation::TestPolicyGuard; |
| 10 | use codewhale_plugins::discovery::{DiscoveryConfig, discover_with_config}; |
| 11 | use codewhale_plugins::host_services::{ |
| 12 | HostService, PersonVia, PluginApprover, ReviewApproval, TestOffer, |
| 13 | }; |
| 14 | use codewhale_plugins::registry::granted_host_services; |
| 15 | use codewhale_runtime::hashing::sha256_hex; |
| 16 | use codewhale_tools::ToolResultContentBlock; |
| 17 | use image::{DynamicImage, ImageFormat, Rgba, RgbaImage}; |
| 18 | use serde_json::{Value, json}; |
| 19 | use tokio::sync::mpsc; |
| 20 | |
| 21 | use super::super::core_call::InvocationGuard; |
| 22 | use super::super::dsh_broker::{BrokerActTool, BrokerCall, BrokerContext, TABLE, TestGrants}; |
| 23 | use super::super::protocol::{ |
| 24 | ContentBlockWire, DshBrokerParams, DshService, RpcErrorWire, ToolResultWire, error_code, |
| 25 | }; |
| 26 | use super::super::supervisor::HostRequestContext; |
| 27 | use super::super::test_support::{FixturePlugins, fake_authority, host_tool, plugin_id}; |
| 28 | use super::super::tool::{resolve_held_image, wire_to_result}; |
| 29 | use super::super::{ |
| 30 | ExtensionHostManager, ExtensionHostOptions, HostCohort, OwnerState, TestManagerGuard, |
| 31 | }; |
| 32 | use crate::image_attach::test_support::PNG_1X1; |
| 33 | use crate::image_attach::{ |
| 34 | MAX_IMAGE_BYTES, MAX_IMAGE_DIMENSION, bound_rich_tool_result, encode_image_bytes, |
| 35 | }; |
| 36 | use crate::rlm::session::SessionObjectSnapshot; |
| 37 | use crate::tools::codemode::{ |
| 38 | ExtensionCaller, NestedCallGate, NestedCallRequest, NestedCallVerdict, NestedDecision, |
| 39 | }; |
| 40 | use crate::tools::spec::{RichToolResult, ToolContext, ToolError}; |
| 41 | |
| 42 | const HOST_GENERATION: u64 = 7; |
| 43 | |
| 44 | fn serve_acts(mut requests: mpsc::Receiver<NestedCallRequest>) { |
| 45 | tokio::spawn(async move { |
| 46 | while let Some(request) = requests.recv().await { |
| 47 | if let NestedCallRequest::Tool(tool_request) = request { |
| 48 | let _ = tool_request.reply.send(NestedCallVerdict::Run { |
| 49 | name: tool_request.name, |
| 50 | input: tool_request.input, |
| 51 | supports_parallel: true, |
| 52 | decision: NestedDecision::Auto, |
| 53 | hook_context: None, |
| 54 | }); |
| 55 | } |
| 56 | } |
| 57 | }); |
| 58 | } |
| 59 | |
| 60 | struct Seam { |
| 61 | manager: Arc<ExtensionHostManager>, |
| 62 | owner: OwnerRef, |
| 63 | gate: NestedCallGate, |
| 64 | _grants: TestGrants, |
| 65 | } |
| 66 | |
| 67 | fn seam(plugin: &str) -> Seam { |
| 68 | let manager = ExtensionHostManager::new(ExtensionHostOptions::default()); |
| 69 | let owner = { |
| 70 | let mut registry = manager.shared.registry.lock().unwrap(); |
| 71 | let owner = registry |
| 72 | .begin_owner( |
| 73 | HostCohort::reviewed(), |
| 74 | plugin, |
| 75 | "Attachments Fixture", |
| 76 | Some(fake_authority(plugin)), |
| 77 | "hash", |
| 78 | ) |
| 79 | .unwrap(); |
| 80 | registry.mark_active(&owner); |
| 81 | owner |
| 82 | }; |
| 83 | let (tx_event, mut rx_event) = mpsc::channel(8); |
| 84 | tokio::spawn(async move { while rx_event.recv().await.is_some() {} }); |
| 85 | let (gate, requests) = NestedCallGate::new(None, tx_event, Duration::from_secs(60)); |
| 86 | serve_acts(requests); |
| 87 | Seam { |
| 88 | manager: Arc::new(manager), |
| 89 | owner, |
| 90 | gate: gate.for_extension( |
| 91 | ExtensionCaller { |
| 92 | origin: format!("extension:{plugin}"), |
| 93 | tool: "attach_tool".to_string(), |
| 94 | scope: format!("ext:{plugin}@hash"), |
| 95 | }, |
| 96 | BrokerActTool::all().to_vec(), |
| 97 | ), |
| 98 | _grants: TestGrants::only(&[DshService::Attachments]), |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | impl Seam { |
| 103 | fn context_with_messages(&self, session: &str, messages: Vec<Message>) -> ToolContext { |
| 104 | ToolContext::new(std::env::temp_dir()) |
| 105 | .with_session_objects(SessionObjectSnapshot::new( |
| 106 | session.into(), |
| 107 | "fixture-model".into(), |
| 108 | std::env::temp_dir(), |
| 109 | None, |
| 110 | Arc::new(messages), |
| 111 | )) |
| 112 | .with_origin_turn_id("attach-turn") |
| 113 | } |
| 114 | |
| 115 | fn context(&self, session: &str) -> ToolContext { |
| 116 | self.context_with_messages(session, Vec::new()) |
| 117 | } |
| 118 | |
| 119 | fn begin(&self, context: &ToolContext, call_id: &str) -> InvocationGuard { |
| 120 | self.manager |
| 121 | .shared |
| 122 | .core_calls |
| 123 | .begin( |
| 124 | HostCohort::reviewed(), |
| 125 | HOST_GENERATION, |
| 126 | &self.owner, |
| 127 | call_id, |
| 128 | self.gate.extension().unwrap().0, |
| 129 | context, |
| 130 | &self.gate, |
| 131 | ) |
| 132 | .expect("an invocation") |
| 133 | } |
| 134 | |
| 135 | async fn call_in( |
| 136 | &self, |
| 137 | cx: HostRequestContext, |
| 138 | guard: &InvocationGuard, |
| 139 | method: &str, |
| 140 | input: Value, |
| 141 | ) -> Result<Value, RpcErrorWire> { |
| 142 | let ticket = guard |
| 143 | .broker_tickets() |
| 144 | .unwrap() |
| 145 | .into_iter() |
| 146 | .find(|wire| wire.service == "attachments") |
| 147 | .unwrap() |
| 148 | .ticket; |
| 149 | self.manager |
| 150 | .shared |
| 151 | .core_calls |
| 152 | .serve_broker_in( |
| 153 | TABLE, |
| 154 | &self.manager.shared, |
| 155 | HostCohort::reviewed(), |
| 156 | HOST_GENERATION, |
| 157 | DshBrokerParams { |
| 158 | owner: self.owner.clone(), |
| 159 | ticket, |
| 160 | service: "attachments".to_string(), |
| 161 | method: method.to_string(), |
| 162 | input, |
| 163 | }, |
| 164 | cx, |
| 165 | ) |
| 166 | .await |
| 167 | } |
| 168 | |
| 169 | async fn call( |
| 170 | &self, |
| 171 | guard: &InvocationGuard, |
| 172 | method: &str, |
| 173 | input: Value, |
| 174 | ) -> Result<Value, RpcErrorWire> { |
| 175 | let (cx, _violations, _cancel) = HostRequestContext::for_test(40); |
| 176 | self.call_in(cx, guard, method, input).await |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | fn wire_refusal(result: &Result<Value, RpcErrorWire>) -> (i64, String, String) { |
| 181 | let error = result.as_ref().expect_err("a refusal"); |
| 182 | let code = error |
| 183 | .data |
| 184 | .as_ref() |
| 185 | .and_then(|data| data["dsh_refusal"].as_str()) |
| 186 | .unwrap_or_else(|| panic!("untyped refusal: {error:?}")) |
| 187 | .to_string(); |
| 188 | (error.code, code, error.message.clone()) |
| 189 | } |
| 190 | |
| 191 | fn sample_rgba_png(width: u32, height: u32, r: u8, g: u8, b: u8) -> Vec<u8> { |
| 192 | let image = |
| 193 | DynamicImage::ImageRgba8(RgbaImage::from_pixel(width, height, Rgba([r, g, b, 255]))); |
| 194 | let mut out = Cursor::new(Vec::new()); |
| 195 | image.write_to(&mut out, ImageFormat::Png).unwrap(); |
| 196 | out.into_inner() |
| 197 | } |
| 198 | |
| 199 | fn crc32(bytes: &[u8]) -> u32 { |
| 200 | let mut crc = 0xffff_ffffu32; |
| 201 | for &byte in bytes { |
| 202 | crc ^= u32::from(byte); |
| 203 | for _ in 0..8 { |
| 204 | let mask = (crc & 1).wrapping_neg(); |
| 205 | crc = (crc >> 1) ^ (0xedb8_8320 & mask); |
| 206 | } |
| 207 | } |
| 208 | !crc |
| 209 | } |
| 210 | |
| 211 | fn png_with_ihdr_dimensions(width: u32, height: u32) -> Vec<u8> { |
| 212 | let mut ihdr = Vec::with_capacity(17); |
| 213 | ihdr.extend_from_slice(b"IHDR"); |
| 214 | ihdr.extend_from_slice(&width.to_be_bytes()); |
| 215 | ihdr.extend_from_slice(&height.to_be_bytes()); |
| 216 | ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); |
| 217 | let crc = crc32(&ihdr); |
| 218 | |
| 219 | let mut out = Vec::new(); |
| 220 | out.extend_from_slice(&PNG_1X1[..8]); |
| 221 | out.extend_from_slice(&13u32.to_be_bytes()); |
| 222 | out.extend_from_slice(&ihdr); |
| 223 | out.extend_from_slice(&crc.to_be_bytes()); |
| 224 | out.extend_from_slice(&PNG_1X1[33..]); |
| 225 | out |
| 226 | } |
| 227 | |
| 228 | fn user_message_with_png(bytes: &[u8]) -> (Message, String) { |
| 229 | let attached = encode_image_bytes(bytes, "user.png").unwrap(); |
| 230 | let b64 = STANDARD.encode(bytes); |
| 231 | let id = format!("sha256:{}", sha256_hex(bytes)); |
| 232 | let message = Message { |
| 233 | role: Role::User, |
| 234 | content: vec![ContentBlock::ImageUrl { |
| 235 | image_url: ImageUrlContent { |
| 236 | url: attached.data_url, |
| 237 | }, |
| 238 | }], |
| 239 | }; |
| 240 | let _ = b64; |
| 241 | (message, id) |
| 242 | } |
| 243 | |
| 244 | #[tokio::test] |
| 245 | async fn an_image_saved_by_a_plugin_lands_on_its_own_tool_result_and_reads_back_by_id() { |
| 246 | let s = seam("att-save-read"); |
| 247 | let png = sample_rgba_png(8, 6, 12, 180, 90); |
| 248 | let (user_msg, user_id) = user_message_with_png(&png); |
| 249 | let ctx = s.context_with_messages("att-s1", vec![user_msg]); |
| 250 | let guard = s.begin(&ctx, "call-save"); |
| 251 | |
| 252 | let valid = s |
| 253 | .call( |
| 254 | &guard, |
| 255 | "validate", |
| 256 | json!({ |
| 257 | "data_base64": STANDARD.encode(PNG_1X1), |
| 258 | "media_type": "image/png", |
| 259 | "name": "studio-image", |
| 260 | }), |
| 261 | ) |
| 262 | .await |
| 263 | .unwrap(); |
| 264 | assert_eq!(valid["ok"], true); |
| 265 | assert_eq!(valid["media_type"], "image/png"); |
| 266 | |
| 267 | let saved = s |
| 268 | .call( |
| 269 | &guard, |
| 270 | "save", |
| 271 | json!({ |
| 272 | "data_base64": STANDARD.encode(PNG_1X1), |
| 273 | "media_type": "image/png", |
| 274 | "name": "studio-image", |
| 275 | }), |
| 276 | ) |
| 277 | .await |
| 278 | .unwrap(); |
| 279 | let attachment = saved["attachment"].clone(); |
| 280 | let id = attachment["attachment_id"].as_str().unwrap().to_string(); |
| 281 | assert_eq!(id.len(), 71); |
| 282 | assert!(id.starts_with("sha256:")); |
| 283 | |
| 284 | let read_saved = s |
| 285 | .call(&guard, "read", json!({ "attachment": attachment.clone() })) |
| 286 | .await |
| 287 | .unwrap(); |
| 288 | let stored_bytes = STANDARD |
| 289 | .decode(read_saved["data_base64"].as_str().unwrap()) |
| 290 | .unwrap(); |
| 291 | assert_eq!(format!("sha256:{}", sha256_hex(&stored_bytes)), id); |
| 292 | assert_eq!(read_saved["attachment"]["bytes"], stored_bytes.len()); |
| 293 | |
| 294 | let read_user = s |
| 295 | .call( |
| 296 | &guard, |
| 297 | "read", |
| 298 | json!({ |
| 299 | "attachment": { |
| 300 | "attachment_id": user_id, |
| 301 | "media_type": "image/png", |
| 302 | "bytes": png.len(), |
| 303 | "width": 8, |
| 304 | "height": 6, |
| 305 | } |
| 306 | }), |
| 307 | ) |
| 308 | .await |
| 309 | .unwrap(); |
| 310 | let user_roundtrip = STANDARD |
| 311 | .decode(read_user["data_base64"].as_str().unwrap()) |
| 312 | .unwrap(); |
| 313 | assert_eq!(user_roundtrip, png); |
| 314 | |
| 315 | let thumb = s |
| 316 | .call( |
| 317 | &guard, |
| 318 | "read_request", |
| 319 | json!({ |
| 320 | "attachment": { "attachment_id": user_id }, |
| 321 | "width": 4, |
| 322 | "height": 4, |
| 323 | "max_bytes": 98_304, |
| 324 | }), |
| 325 | ) |
| 326 | .await |
| 327 | .unwrap(); |
| 328 | let thumb_bytes = STANDARD |
| 329 | .decode(thumb["data_base64"].as_str().unwrap()) |
| 330 | .unwrap(); |
| 331 | assert_eq!( |
| 332 | thumb["variant_id"], |
| 333 | format!("sha256:{}", sha256_hex(&thumb_bytes)) |
| 334 | ); |
| 335 | assert!(thumb_bytes.len() <= 98_304); |
| 336 | |
| 337 | let held = guard.seal_held_image(); |
| 338 | let mut settled = Ok(ToolResultWire { |
| 339 | content: vec![ |
| 340 | ContentBlockWire::Text { |
| 341 | text: "saved".to_string(), |
| 342 | }, |
| 343 | ContentBlockWire::ImageRef { |
| 344 | attachment_id: id.clone(), |
| 345 | }, |
| 346 | ], |
| 347 | is_error: false, |
| 348 | structured: None, |
| 349 | }); |
| 350 | let blocks = resolve_held_image(held, true, &mut settled, Some(&guard)); |
| 351 | let wire = settled.unwrap(); |
| 352 | let rich = bound_rich_tool_result(RichToolResult::with_content_blocks( |
| 353 | wire_to_result(wire, "extension:att-save-read"), |
| 354 | blocks, |
| 355 | )); |
| 356 | assert_eq!(rich.content_blocks.len(), 1); |
| 357 | let ToolResultContentBlock::Image { mime_type, data } = &rich.content_blocks[0]; |
| 358 | assert_eq!( |
| 359 | mime_type, |
| 360 | read_saved["attachment"]["media_type"].as_str().unwrap() |
| 361 | ); |
| 362 | assert_eq!(STANDARD.decode(data).unwrap(), stored_bytes); |
| 363 | |
| 364 | let receipts = guard.seal_receipts().unwrap(); |
| 365 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 366 | assert_eq!(acts.len(), 11); |
| 367 | assert!(acts.iter().all(|act| act["service"] == "attachments")); |
| 368 | assert_eq!( |
| 369 | acts.iter() |
| 370 | .filter(|act| act.get("effect").is_some()) |
| 371 | .count(), |
| 372 | 5 |
| 373 | ); |
| 374 | let last = acts.last().unwrap(); |
| 375 | assert_eq!(last["method"], "result"); |
| 376 | assert_eq!(last["outcome"], "delivered"); |
| 377 | let serialized = receipts.to_string(); |
| 378 | assert!(!serialized.contains("data:image/")); |
| 379 | assert!(!serialized.contains(STANDARD.encode(PNG_1X1).as_str())); |
| 380 | } |
| 381 | |
| 382 | #[tokio::test] |
| 383 | async fn an_image_block_naming_an_id_the_call_did_not_save_fails_the_tool() { |
| 384 | let s = seam("att-unheld-ref"); |
| 385 | let ctx = s.context("att-s2"); |
| 386 | |
| 387 | let unheld_guard = s.begin(&ctx, "call-none"); |
| 388 | let mut settled_none = Ok(ToolResultWire { |
| 389 | content: vec![ContentBlockWire::ImageRef { |
| 390 | attachment_id: format!("sha256:{}", "a".repeat(64)), |
| 391 | }], |
| 392 | is_error: false, |
| 393 | structured: None, |
| 394 | }); |
| 395 | let blocks_none = resolve_held_image( |
| 396 | unheld_guard.seal_held_image(), |
| 397 | true, |
| 398 | &mut settled_none, |
| 399 | Some(&unheld_guard), |
| 400 | ); |
| 401 | assert!(blocks_none.is_empty()); |
| 402 | let err = settled_none.unwrap_err(); |
| 403 | assert!(err.to_string().contains("not held by this call"), "{err}"); |
| 404 | |
| 405 | let wrong_guard = s.begin(&ctx, "call-wrong"); |
| 406 | let _saved = wrong_guard_save(&s, &wrong_guard).await; |
| 407 | let mut settled_wrong = Ok(ToolResultWire { |
| 408 | content: vec![ContentBlockWire::ImageRef { |
| 409 | attachment_id: format!("sha256:{}", "b".repeat(64)), |
| 410 | }], |
| 411 | is_error: false, |
| 412 | structured: None, |
| 413 | }); |
| 414 | let blocks_wrong = resolve_held_image( |
| 415 | wrong_guard.seal_held_image(), |
| 416 | true, |
| 417 | &mut settled_wrong, |
| 418 | Some(&wrong_guard), |
| 419 | ); |
| 420 | assert!(blocks_wrong.is_empty()); |
| 421 | assert!(settled_wrong.is_err()); |
| 422 | let receipts = wrong_guard.seal_receipts().unwrap(); |
| 423 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 424 | assert_eq!(acts.last().unwrap()["outcome"], "dropped"); |
| 425 | assert_eq!(acts.last().unwrap()["reason"], "unheld_reference"); |
| 426 | } |
| 427 | |
| 428 | async fn wrong_guard_save(s: &Seam, guard: &InvocationGuard) -> Value { |
| 429 | s.call( |
| 430 | guard, |
| 431 | "save", |
| 432 | json!({ |
| 433 | "data_base64": STANDARD.encode(PNG_1X1), |
| 434 | "media_type": "image/png", |
| 435 | }), |
| 436 | ) |
| 437 | .await |
| 438 | .unwrap() |
| 439 | } |
| 440 | |
| 441 | #[tokio::test] |
| 442 | async fn a_held_image_the_result_does_not_name_is_dropped_and_recorded() { |
| 443 | let s = seam("att-drop-unreferenced"); |
| 444 | let ctx = s.context("att-s3"); |
| 445 | let guard = s.begin(&ctx, "call-unref"); |
| 446 | let _ = wrong_guard_save(&s, &guard).await; |
| 447 | |
| 448 | let mut settled = Ok(ToolResultWire { |
| 449 | content: vec![ContentBlockWire::Text { |
| 450 | text: "forgot image".to_string(), |
| 451 | }], |
| 452 | is_error: false, |
| 453 | structured: None, |
| 454 | }); |
| 455 | let blocks = resolve_held_image(guard.seal_held_image(), true, &mut settled, Some(&guard)); |
| 456 | assert!(blocks.is_empty()); |
| 457 | assert!(settled.is_ok()); |
| 458 | let receipts = guard.seal_receipts().unwrap(); |
| 459 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 460 | assert_eq!(acts.len(), 3); |
| 461 | assert_eq!(acts[2]["outcome"], "dropped"); |
| 462 | assert_eq!(acts[2]["reason"], "not_referenced"); |
| 463 | |
| 464 | let failed_guard = s.begin(&ctx, "call-fail"); |
| 465 | let _ = wrong_guard_save(&s, &failed_guard).await; |
| 466 | let mut failed: Result<ToolResultWire, ToolError> = Err(ToolError::execution_failed("boom")); |
| 467 | let failed_blocks = resolve_held_image( |
| 468 | failed_guard.seal_held_image(), |
| 469 | true, |
| 470 | &mut failed, |
| 471 | Some(&failed_guard), |
| 472 | ); |
| 473 | assert!(failed_blocks.is_empty()); |
| 474 | let fail_receipts = failed_guard.seal_receipts().unwrap(); |
| 475 | let fail_acts = fail_receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 476 | assert_eq!(fail_acts.len(), 3); |
| 477 | assert_eq!(fail_acts[2]["outcome"], "dropped"); |
| 478 | assert_eq!(fail_acts[2]["reason"], "tool_failed"); |
| 479 | } |
| 480 | |
| 481 | #[tokio::test] |
| 482 | async fn a_second_save_in_one_tool_call_is_refused_with_a_reason() { |
| 483 | let s = seam("att-second-save"); |
| 484 | let ctx = s.context("att-s4"); |
| 485 | let guard = s.begin(&ctx, "call-two"); |
| 486 | let _first = wrong_guard_save(&s, &guard).await; |
| 487 | |
| 488 | let second = s |
| 489 | .call( |
| 490 | &guard, |
| 491 | "save", |
| 492 | json!({ |
| 493 | "data_base64": STANDARD.encode(PNG_1X1), |
| 494 | "media_type": "image/png", |
| 495 | }), |
| 496 | ) |
| 497 | .await; |
| 498 | let (rpc, refusal, msg) = wire_refusal(&second); |
| 499 | assert_eq!(rpc, error_code::REFUSED); |
| 500 | assert_eq!(refusal, "refused"); |
| 501 | assert!(msg.contains("TOO_MANY_IMAGES"), "{msg}"); |
| 502 | assert!( |
| 503 | msg.contains("this Codewhale keeps one image per tool result"), |
| 504 | "{msg}" |
| 505 | ); |
| 506 | let _ = resolve_held_image( |
| 507 | guard.seal_held_image(), |
| 508 | true, |
| 509 | &mut Ok(ToolResultWire { |
| 510 | content: Vec::new(), |
| 511 | is_error: false, |
| 512 | structured: None, |
| 513 | }), |
| 514 | Some(&guard), |
| 515 | ); |
| 516 | let receipts = guard.seal_receipts().unwrap(); |
| 517 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 518 | let refused_record = acts |
| 519 | .iter() |
| 520 | .find(|act| act["method"] == "save" && act["outcome"] == "refused") |
| 521 | .expect("refused save detail record"); |
| 522 | assert_eq!(refused_record["reason"], "TOO_MANY_IMAGES"); |
| 523 | } |
| 524 | |
| 525 | #[tokio::test] |
| 526 | async fn an_id_from_another_conversation_is_refused_like_an_unknown_id() { |
| 527 | let s = seam("att-foreign-conv"); |
| 528 | let png = sample_rgba_png(4, 4, 200, 10, 10); |
| 529 | let (user_msg, conv_a_id) = user_message_with_png(&png); |
| 530 | let _ctx_a = s.context_with_messages("conv-a", vec![user_msg]); |
| 531 | let ctx_b = s.context_with_messages("conv-b", Vec::new()); |
| 532 | let guard_b = s.begin(&ctx_b, "call-b"); |
| 533 | |
| 534 | let foreign = s |
| 535 | .call( |
| 536 | &guard_b, |
| 537 | "read", |
| 538 | json!({ "attachment": { "attachment_id": conv_a_id } }), |
| 539 | ) |
| 540 | .await; |
| 541 | let unknown = s |
| 542 | .call( |
| 543 | &guard_b, |
| 544 | "read", |
| 545 | json!({ "attachment": { "attachment_id": format!("sha256:{}", "0".repeat(64)) } }), |
| 546 | ) |
| 547 | .await; |
| 548 | assert_eq!(wire_refusal(&foreign), wire_refusal(&unknown)); |
| 549 | assert_eq!(wire_refusal(&foreign).0, error_code::REFUSED); |
| 550 | assert!(wire_refusal(&foreign).2.contains("ATTACHMENT_NOT_FOUND")); |
| 551 | } |
| 552 | |
| 553 | #[tokio::test] |
| 554 | async fn a_declared_type_that_differs_from_the_bytes_is_refused() { |
| 555 | let s = seam("att-bad-type"); |
| 556 | let ctx = s.context("att-s6"); |
| 557 | let guard = s.begin(&ctx, "call-type"); |
| 558 | |
| 559 | let mismatch = s |
| 560 | .call( |
| 561 | &guard, |
| 562 | "validate", |
| 563 | json!({ |
| 564 | "data_base64": STANDARD.encode(PNG_1X1), |
| 565 | "media_type": "image/jpeg", |
| 566 | }), |
| 567 | ) |
| 568 | .await; |
| 569 | assert!(wire_refusal(&mismatch).2.contains("IMAGE_TYPE_MISMATCH")); |
| 570 | |
| 571 | let mut bmp = b"BM".to_vec(); |
| 572 | bmp.extend_from_slice(&[0u8; 32]); |
| 573 | let bmp_res = s |
| 574 | .call( |
| 575 | &guard, |
| 576 | "save", |
| 577 | json!({ |
| 578 | "data_base64": STANDARD.encode(&bmp), |
| 579 | "media_type": "image/png", |
| 580 | }), |
| 581 | ) |
| 582 | .await; |
| 583 | assert!(wire_refusal(&bmp_res).2.contains("UNSUPPORTED_IMAGE_TYPE")); |
| 584 | |
| 585 | let truncated = s |
| 586 | .call( |
| 587 | &guard, |
| 588 | "save", |
| 589 | json!({ |
| 590 | "data_base64": STANDARD.encode(&PNG_1X1[..20]), |
| 591 | "media_type": "image/png", |
| 592 | }), |
| 593 | ) |
| 594 | .await; |
| 595 | assert!(wire_refusal(&truncated).2.contains("INVALID_IMAGE")); |
| 596 | |
| 597 | let bad_b64 = s |
| 598 | .call( |
| 599 | &guard, |
| 600 | "validate", |
| 601 | json!({ |
| 602 | "data_base64": "!!!not-base64!!!", |
| 603 | "media_type": "image/png", |
| 604 | }), |
| 605 | ) |
| 606 | .await; |
| 607 | assert!(wire_refusal(&bad_b64).2.contains("INVALID_IMAGE_BASE64")); |
| 608 | } |
| 609 | |
| 610 | #[tokio::test] |
| 611 | async fn an_image_over_the_byte_pixel_or_dimension_limit_is_refused_before_decoding_finishes() { |
| 612 | let s = seam("att-limits"); |
| 613 | let ctx = s.context("att-s7"); |
| 614 | let guard = s.begin(&ctx, "call-limits"); |
| 615 | |
| 616 | let mut too_many_bytes = PNG_1X1.to_vec(); |
| 617 | too_many_bytes.resize(MAX_IMAGE_BYTES + 1, 0); |
| 618 | let over_bytes = s |
| 619 | .call( |
| 620 | &guard, |
| 621 | "validate", |
| 622 | json!({ |
| 623 | "data_base64": STANDARD.encode(&too_many_bytes), |
| 624 | "media_type": "image/png", |
| 625 | }), |
| 626 | ) |
| 627 | .await; |
| 628 | assert!(wire_refusal(&over_bytes).2.contains("IMAGE_TOO_LARGE")); |
| 629 | |
| 630 | let wide_header = png_with_ihdr_dimensions(MAX_IMAGE_DIMENSION + 1, 1); |
| 631 | let over_dim = s |
| 632 | .call( |
| 633 | &guard, |
| 634 | "save", |
| 635 | json!({ |
| 636 | "data_base64": STANDARD.encode(&wide_header), |
| 637 | "media_type": "image/png", |
| 638 | }), |
| 639 | ) |
| 640 | .await; |
| 641 | assert!( |
| 642 | wire_refusal(&over_dim) |
| 643 | .2 |
| 644 | .contains("IMAGE_DIMENSION_TOO_LARGE") |
| 645 | ); |
| 646 | |
| 647 | let pixel_bomb = png_with_ihdr_dimensions(6000, 6000); |
| 648 | let over_pixels = s |
| 649 | .call( |
| 650 | &guard, |
| 651 | "save", |
| 652 | json!({ |
| 653 | "data_base64": STANDARD.encode(&pixel_bomb), |
| 654 | "media_type": "image/png", |
| 655 | }), |
| 656 | ) |
| 657 | .await; |
| 658 | assert!( |
| 659 | wire_refusal(&over_pixels) |
| 660 | .2 |
| 661 | .contains("IMAGE_TOO_MANY_PIXELS") |
| 662 | ); |
| 663 | } |
| 664 | |
| 665 | #[tokio::test] |
| 666 | async fn a_revoked_or_disabled_owner_cannot_read_or_save() { |
| 667 | let s = seam("att-revoked"); |
| 668 | let ctx = s.context("att-s8"); |
| 669 | let guard = s.begin(&ctx, "call-revoke"); |
| 670 | let _saved = wrong_guard_save(&s, &guard).await; |
| 671 | |
| 672 | s.manager.shared.core_calls.revoke_owner("att-revoked"); |
| 673 | let after_revoke = s |
| 674 | .call( |
| 675 | &guard, |
| 676 | "save", |
| 677 | json!({ |
| 678 | "data_base64": STANDARD.encode(PNG_1X1), |
| 679 | "media_type": "image/png", |
| 680 | }), |
| 681 | ) |
| 682 | .await; |
| 683 | assert_eq!(wire_refusal(&after_revoke).0, error_code::REFUSED); |
| 684 | assert_eq!(wire_refusal(&after_revoke).1, "ticket_refused"); |
| 685 | |
| 686 | let _policy = TestPolicyGuard::extension_host(true); |
| 687 | let _offer = TestOffer::only(&[HostService::Attachments]); |
| 688 | let temp = codewhale_plugins::test_fixture::PluginTempDir::new().unwrap(); |
| 689 | let root = temp.path(); |
| 690 | let config = DiscoveryConfig { |
| 691 | workspace: root.join("project"), |
| 692 | user_plugins_dir: root.join("user"), |
| 693 | workspace_plugins_dir: root.join("workspace"), |
| 694 | builtin_plugin_dirs: Vec::new(), |
| 695 | state_path: root.join("state/plugin-state.json"), |
| 696 | }; |
| 697 | std::fs::create_dir_all(&config.workspace).unwrap(); |
| 698 | let write_plugin = |name: &str, with_service: bool| { |
| 699 | let dir = config.user_plugins_dir.join(name); |
| 700 | std::fs::create_dir_all(dir.join("native")).unwrap(); |
| 701 | std::fs::write(dir.join("native/index.mjs"), "export function apply() {}\n").unwrap(); |
| 702 | let cap = if with_service { |
| 703 | "[capabilities]\nhost_services = [\"attachments\"]\n" |
| 704 | } else { |
| 705 | "" |
| 706 | }; |
| 707 | std::fs::write( |
| 708 | dir.join("plugin.toml"), |
| 709 | format!( |
| 710 | "schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n[native]\npath = \"native/index.mjs\"\n{cap}" |
| 711 | ), |
| 712 | ) |
| 713 | .unwrap(); |
| 714 | }; |
| 715 | write_plugin("alpha", true); |
| 716 | let mut reg = discover_with_config(&config); |
| 717 | let token = reg.host_service_review("alpha").unwrap().token; |
| 718 | reg.trust_reviewed( |
| 719 | "alpha", |
| 720 | ReviewApproval { |
| 721 | approved_by: PluginApprover::person(PersonVia::Terminal), |
| 722 | host_services: Some(token), |
| 723 | }, |
| 724 | ) |
| 725 | .unwrap(); |
| 726 | reg.enable("alpha").unwrap(); |
| 727 | let reg = discover_with_config(&config); |
| 728 | let alpha_auth = reg.authority_for("alpha").unwrap(); |
| 729 | assert!( |
| 730 | granted_host_services(&alpha_auth) |
| 731 | .unwrap() |
| 732 | .contains(&HostService::Attachments) |
| 733 | ); |
| 734 | |
| 735 | write_plugin("beta", false); |
| 736 | let mut reg = discover_with_config(&config); |
| 737 | reg.trust_reviewed( |
| 738 | "beta", |
| 739 | ReviewApproval { |
| 740 | approved_by: PluginApprover::person(PersonVia::Terminal), |
| 741 | host_services: None, |
| 742 | }, |
| 743 | ) |
| 744 | .unwrap(); |
| 745 | reg.enable("beta").unwrap(); |
| 746 | let reg = discover_with_config(&config); |
| 747 | let beta_auth = reg.authority_for("beta").unwrap(); |
| 748 | assert!( |
| 749 | !granted_host_services(&beta_auth) |
| 750 | .unwrap() |
| 751 | .contains(&HostService::Attachments) |
| 752 | ); |
| 753 | } |
| 754 | |
| 755 | #[tokio::test] |
| 756 | async fn no_attachments_method_takes_a_path() { |
| 757 | let s = seam("att-no-paths"); |
| 758 | let ctx = s.context("att-s9"); |
| 759 | let guard = s.begin(&ctx, "call-path"); |
| 760 | let b64 = STANDARD.encode(PNG_1X1); |
| 761 | let valid_id = format!("sha256:{}", sha256_hex(PNG_1X1)); |
| 762 | |
| 763 | for field in ["path", "url", "hostPath", "host_path"] { |
| 764 | let mut validate_input = json!({ "data_base64": b64, "media_type": "image/png" }); |
| 765 | validate_input[field] = json!("/etc/passwd"); |
| 766 | let res = s.call(&guard, "validate", validate_input).await; |
| 767 | assert_eq!(wire_refusal(&res).1, "invalid_input", "{field}"); |
| 768 | |
| 769 | let mut save_input = json!({ "data_base64": b64, "media_type": "image/png" }); |
| 770 | save_input[field] = json!("/etc/passwd"); |
| 771 | let res = s.call(&guard, "save", save_input).await; |
| 772 | assert_eq!(wire_refusal(&res).1, "invalid_input", "{field}"); |
| 773 | |
| 774 | let mut read_input = json!({ "attachment": { "attachment_id": valid_id } }); |
| 775 | read_input[field] = json!("/etc/passwd"); |
| 776 | let res = s.call(&guard, "read", read_input).await; |
| 777 | assert_eq!(wire_refusal(&res).1, "invalid_input", "{field}"); |
| 778 | |
| 779 | let mut req_input = json!({ "attachment": { "attachment_id": valid_id }, "width": 32, "height": 32, "max_bytes": 4096 }); |
| 780 | req_input[field] = json!("/etc/passwd"); |
| 781 | let res = s.call(&guard, "read_request", req_input).await; |
| 782 | assert_eq!(wire_refusal(&res).1, "invalid_input", "{field}"); |
| 783 | } |
| 784 | |
| 785 | for bad_name in ["../escape.png", "a/b.png", "a\\b.png", "C:file", ".hidden"] { |
| 786 | let res = s |
| 787 | .call( |
| 788 | &guard, |
| 789 | "save", |
| 790 | json!({ |
| 791 | "data_base64": b64, |
| 792 | "media_type": "image/png", |
| 793 | "name": bad_name, |
| 794 | }), |
| 795 | ) |
| 796 | .await; |
| 797 | assert_eq!(wire_refusal(&res).1, "invalid_input", "{bad_name}"); |
| 798 | } |
| 799 | |
| 800 | for bad_id in [ |
| 801 | "/etc/passwd", |
| 802 | "https://evil.example/x.png", |
| 803 | "C:\\tmp\\x.png", |
| 804 | "sha256:ZZZZ", |
| 805 | "not-sha", |
| 806 | ] { |
| 807 | let res = s |
| 808 | .call( |
| 809 | &guard, |
| 810 | "read", |
| 811 | json!({ "attachment": { "attachment_id": bad_id } }), |
| 812 | ) |
| 813 | .await; |
| 814 | assert!(wire_refusal(&res).2.contains("INVALID_ATTACHMENT_REF")); |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | #[tokio::test] |
| 819 | async fn a_read_with_no_conversation_snapshot_is_refused() { |
| 820 | let s = seam("att-no-snap"); |
| 821 | let ctx = ToolContext::new(std::env::temp_dir()).with_origin_turn_id("no-snap"); |
| 822 | let id = format!("sha256:{}", sha256_hex(PNG_1X1)); |
| 823 | let guard = s.manager.shared.core_calls.begin_scoped( |
| 824 | HostCohort::reviewed(), |
| 825 | HOST_GENERATION, |
| 826 | &s.owner, |
| 827 | "call-no-snap", |
| 828 | s.gate.extension().unwrap().0, |
| 829 | &ctx, |
| 830 | &s.gate, |
| 831 | None, |
| 832 | String::new(), |
| 833 | &[DshService::Attachments], |
| 834 | ); |
| 835 | assert!( |
| 836 | guard |
| 837 | .as_ref() |
| 838 | .and_then(|g| g.broker_tickets()) |
| 839 | .is_none_or(|tickets| tickets.is_empty()), |
| 840 | "no session_objects yields no broker ticket" |
| 841 | ); |
| 842 | |
| 843 | let mut call_ctx = BrokerContext::detached_for_test(&s.owner, DshService::Attachments); |
| 844 | let _ = &mut call_ctx; |
| 845 | let res = super::serve(BrokerCall { |
| 846 | owner: s.owner.clone(), |
| 847 | session_id: "missing-snap".into(), |
| 848 | service: DshService::Attachments, |
| 849 | method: "read".into(), |
| 850 | input: json!({ "attachment": { "attachment_id": id } }), |
| 851 | context: call_ctx, |
| 852 | }) |
| 853 | .await; |
| 854 | let err = res.unwrap_err(); |
| 855 | assert_eq!(err.code(), "refused"); |
| 856 | } |
| 857 | |
| 858 | #[tokio::test] |
| 859 | async fn an_arm_whose_cancel_has_fired_has_no_effect() { |
| 860 | let s = seam("att-cancel"); |
| 861 | let ctx = s.context("att-s11"); |
| 862 | let guard = s.begin(&ctx, "call-cancel"); |
| 863 | |
| 864 | let (cx, _violations, host_cancel) = HostRequestContext::for_test(1); |
| 865 | host_cancel.cancel(); |
| 866 | let cancelled = s |
| 867 | .call_in( |
| 868 | cx, |
| 869 | &guard, |
| 870 | "save", |
| 871 | json!({ |
| 872 | "data_base64": STANDARD.encode(PNG_1X1), |
| 873 | "media_type": "image/png", |
| 874 | }), |
| 875 | ) |
| 876 | .await; |
| 877 | assert_eq!( |
| 878 | (wire_refusal(&cancelled).0, wire_refusal(&cancelled).1), |
| 879 | (error_code::CANCELLED, "cancelled".to_string()) |
| 880 | ); |
| 881 | assert!(guard.seal_held_image().is_none()); |
| 882 | |
| 883 | let detached = BrokerContext::detached_for_test(&s.owner, DshService::Attachments); |
| 884 | detached.cancel().cancel(); |
| 885 | let direct = super::serve(BrokerCall { |
| 886 | owner: s.owner.clone(), |
| 887 | session_id: "att-s11".into(), |
| 888 | service: DshService::Attachments, |
| 889 | method: "save".into(), |
| 890 | input: json!({ |
| 891 | "data_base64": STANDARD.encode(PNG_1X1), |
| 892 | "media_type": "image/png", |
| 893 | }), |
| 894 | context: detached, |
| 895 | }) |
| 896 | .await; |
| 897 | assert_eq!(direct.unwrap_err().code(), "refused"); |
| 898 | } |
| 899 | |
| 900 | #[test] |
| 901 | fn a_state_file_without_attachments_or_with_unrecognized_grant_reads_as_before() { |
| 902 | assert_eq!( |
| 903 | HostService::parse("attachments"), |
| 904 | Some(HostService::Attachments) |
| 905 | ); |
| 906 | assert!(codewhale_plugins::host_services::offered( |
| 907 | HostService::Attachments |
| 908 | )); |
| 909 | |
| 910 | let temp = tempfile::tempdir().unwrap(); |
| 911 | let root = temp.path(); |
| 912 | let state_path = root.join("plugin-state.json"); |
| 913 | std::fs::write( |
| 914 | &state_path, |
| 915 | json!({ |
| 916 | "version": 1, |
| 917 | "plugins": { |
| 918 | "legacy-plugin": { |
| 919 | "trusted": true, |
| 920 | "enabled": true, |
| 921 | "content_hash": "abc", |
| 922 | "host_services": ["network"] |
| 923 | } |
| 924 | } |
| 925 | }) |
| 926 | .to_string(), |
| 927 | ) |
| 928 | .unwrap(); |
| 929 | let cfg = DiscoveryConfig { |
| 930 | workspace: root.join("workspace"), |
| 931 | user_plugins_dir: root.join("user"), |
| 932 | workspace_plugins_dir: root.join("workspace/.codewhale/plugins"), |
| 933 | builtin_plugin_dirs: Vec::new(), |
| 934 | state_path, |
| 935 | }; |
| 936 | let registry = discover_with_config(&cfg); |
| 937 | assert!(registry.list().is_empty()); |
| 938 | } |
| 939 | |
| 940 | #[tokio::test] |
| 941 | async fn a_real_node_host_enforces_attachments_registration_and_projects_image_ref_blocks() { |
| 942 | let resolution = codewhale_dependencies::resolve_extension_host_runtime( |
| 943 | codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 944 | None, |
| 945 | None, |
| 946 | super::super::bundle_sha256(), |
| 947 | ); |
| 948 | let failure = resolution.failure(); |
| 949 | let node = resolution |
| 950 | .selected |
| 951 | .unwrap_or_else(|| panic!("Node runtime is required: {failure}")) |
| 952 | .path; |
| 953 | |
| 954 | let _policy = TestPolicyGuard::extension_host(true); |
| 955 | let _offer = TestOffer::only(&[HostService::Attachments]); |
| 956 | let _grants = TestGrants::only(&[DshService::Attachments]); |
| 957 | |
| 958 | let unreg_fixture = FixturePlugins::new(&["dsh-attachments"]).await; |
| 959 | let unreg_id = plugin_id(&unreg_fixture, "dsh-attachments"); |
| 960 | let unreg_manager = unreg_fixture.manager(node.clone()); |
| 961 | let unreg_engine = unreg_manager.attach(unreg_fixture.registry()); |
| 962 | unreg_engine.sync().await.unwrap(); |
| 963 | assert!(matches!( |
| 964 | unreg_manager.owner_state(&unreg_id), |
| 965 | Some(OwnerState::Active) |
| 966 | )); |
| 967 | unreg_manager.shutdown().await; |
| 968 | |
| 969 | let fixture = FixturePlugins::new(&["dsh-attachments-render"]).await; |
| 970 | let manager = fixture.manager(node); |
| 971 | let engine = manager.attach(fixture.registry()); |
| 972 | engine.sync().await.unwrap(); |
| 973 | let _manager_guard = TestManagerGuard::install(Arc::clone(&manager)); |
| 974 | |
| 975 | let tool = host_tool(&engine, fixture.workspace(), "render_attachment_result"); |
| 976 | let (tx_event, mut rx_event) = mpsc::channel(16); |
| 977 | tokio::spawn(async move { while rx_event.recv().await.is_some() {} }); |
| 978 | let (gate, requests) = NestedCallGate::new(None, tx_event, Duration::from_secs(60)); |
| 979 | serve_acts(requests); |
| 980 | |
| 981 | let mut registry = crate::tools::registry::ToolRegistryBuilder::new() |
| 982 | .build(ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view())); |
| 983 | engine.install_tools(&mut registry); |
| 984 | |
| 985 | let mut context = ToolContext::new(fixture.workspace()) |
| 986 | .with_plugin_registry(engine.plugin_view()) |
| 987 | .with_session_objects(SessionObjectSnapshot::new( |
| 988 | "real-host-attach".into(), |
| 989 | "fixture-model".into(), |
| 990 | fixture.workspace().to_path_buf(), |
| 991 | None, |
| 992 | Arc::new(Vec::new()), |
| 993 | )) |
| 994 | .with_origin_turn_id("real-host-turn"); |
| 995 | context.execution.nested_call_gate = Some(gate.for_extension( |
| 996 | tool.extension_caller().expect("extension caller"), |
| 997 | registry.all(), |
| 998 | )); |
| 999 | |
| 1000 | let wanted_id = format!("sha256:{}", sha256_hex(PNG_1X1)); |
| 1001 | let unheld_err = tool |
| 1002 | .execute_rich(json!({ "attachmentId": wanted_id }), &context) |
| 1003 | .await |
| 1004 | .expect_err("real Node renderResult image block must fail closed when unheld"); |
| 1005 | assert!( |
| 1006 | unheld_err.to_string().contains("not held by this call"), |
| 1007 | "{unheld_err}" |
| 1008 | ); |
| 1009 | |
| 1010 | let dropped_text = tool |
| 1011 | .execute_rich(json!({ "textOnly": "plain reply" }), &context) |
| 1012 | .await |
| 1013 | .expect("text-only renderResult succeeds"); |
| 1014 | assert!(dropped_text.content_blocks.is_empty()); |
| 1015 | assert!(dropped_text.result.content.contains("plain reply")); |
| 1016 | |
| 1017 | { |
| 1018 | let _revoked = TestGrants::only(&[]); |
| 1019 | let revoked_err = tool |
| 1020 | .execute_rich(json!({ "attachmentId": wanted_id }), &context) |
| 1021 | .await |
| 1022 | .expect_err( |
| 1023 | "real Node renderResult image block must fail closed when grant is revoked", |
| 1024 | ); |
| 1025 | assert!( |
| 1026 | revoked_err.to_string().contains("grant was revoked"), |
| 1027 | "{revoked_err}" |
| 1028 | ); |
| 1029 | let text_when_revoked = tool |
| 1030 | .execute_rich(json!({ "textOnly": "plain still works" }), &context) |
| 1031 | .await |
| 1032 | .expect("text-only renderResult succeeds when attachments grant is absent"); |
| 1033 | assert!(text_when_revoked.content_blocks.is_empty()); |
| 1034 | } |
| 1035 | |
| 1036 | manager.shutdown().await; |
| 1037 | } |
| 1038 | |
| 1039 | static LATE_REVOKE_MANAGERS: std::sync::OnceLock< |
| 1040 | std::sync::Mutex<std::collections::HashMap<String, Arc<ExtensionHostManager>>>, |
| 1041 | > = std::sync::OnceLock::new(); |
| 1042 | |
| 1043 | fn revoke_owner_after_arm(call: BrokerCall) -> super::BrokerFuture { |
| 1044 | Box::pin(async move { |
| 1045 | let plugin_id = call.owner.plugin_id.clone(); |
| 1046 | let result = super::serve(call).await; |
| 1047 | let manager = LATE_REVOKE_MANAGERS |
| 1048 | .get() |
| 1049 | .and_then(|map| map.lock().unwrap().get(&plugin_id).cloned()); |
| 1050 | if let Some(manager) = manager { |
| 1051 | manager |
| 1052 | .shared |
| 1053 | .registry |
| 1054 | .lock() |
| 1055 | .unwrap() |
| 1056 | .revoke_owner(&plugin_id); |
| 1057 | } |
| 1058 | result |
| 1059 | }) |
| 1060 | } |
| 1061 | |
| 1062 | #[tokio::test] |
| 1063 | async fn late_refusal_after_save_rolls_back_held_image_without_touching_prior_valid_save() { |
| 1064 | let s = seam("att-late-revoke"); |
| 1065 | let ctx = s.context("att-late-1"); |
| 1066 | let guard = s.begin(&ctx, "call-late-1"); |
| 1067 | let managers = LATE_REVOKE_MANAGERS.get_or_init(|| std::sync::Mutex::new(Default::default())); |
| 1068 | managers |
| 1069 | .lock() |
| 1070 | .unwrap() |
| 1071 | .insert(s.owner.plugin_id.clone(), Arc::clone(&s.manager)); |
| 1072 | |
| 1073 | let ticket = guard |
| 1074 | .broker_tickets() |
| 1075 | .unwrap() |
| 1076 | .into_iter() |
| 1077 | .find(|wire| wire.service == "attachments") |
| 1078 | .unwrap() |
| 1079 | .ticket; |
| 1080 | let (cx, _violations, _cancel) = HostRequestContext::for_test(40); |
| 1081 | let err = s |
| 1082 | .manager |
| 1083 | .shared |
| 1084 | .core_calls |
| 1085 | .serve_broker_in( |
| 1086 | &[(DshService::Attachments, revoke_owner_after_arm)], |
| 1087 | &s.manager.shared, |
| 1088 | HostCohort::reviewed(), |
| 1089 | HOST_GENERATION, |
| 1090 | DshBrokerParams { |
| 1091 | owner: s.owner.clone(), |
| 1092 | ticket, |
| 1093 | service: "attachments".to_string(), |
| 1094 | method: "save".to_string(), |
| 1095 | input: json!({ |
| 1096 | "data_base64": STANDARD.encode(PNG_1X1), |
| 1097 | "media_type": "image/png", |
| 1098 | }), |
| 1099 | }, |
| 1100 | cx, |
| 1101 | ) |
| 1102 | .await |
| 1103 | .expect_err("owner revocation after save arm completes must fail closed"); |
| 1104 | managers.lock().unwrap().remove(&s.owner.plugin_id); |
| 1105 | assert!( |
| 1106 | err.message.contains("owner is no longer current"), |
| 1107 | "{err:?}" |
| 1108 | ); |
| 1109 | assert!( |
| 1110 | guard.seal_held_image().is_none(), |
| 1111 | "late refusal must roll back newly staged held_image" |
| 1112 | ); |
| 1113 | let receipts = guard.seal_receipts().unwrap(); |
| 1114 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 1115 | let rolled_back = acts |
| 1116 | .iter() |
| 1117 | .find(|act| act["method"] == "save" && act["outcome"] == "refused_after_hold") |
| 1118 | .expect("refused_after_hold receipt record"); |
| 1119 | assert_eq!(rolled_back["reason"], "owner_stale"); |
| 1120 | assert_eq!( |
| 1121 | rolled_back["attachment_id"], |
| 1122 | format!("sha256:{}", sha256_hex(PNG_1X1)) |
| 1123 | ); |
| 1124 | |
| 1125 | let s2 = seam("att-late-preserve"); |
| 1126 | let ctx2 = s2.context("att-late-2"); |
| 1127 | let guard2 = s2.begin(&ctx2, "call-late-2"); |
| 1128 | let _saved = wrong_guard_save(&s2, &guard2).await; |
| 1129 | managers |
| 1130 | .lock() |
| 1131 | .unwrap() |
| 1132 | .insert(s2.owner.plugin_id.clone(), Arc::clone(&s2.manager)); |
| 1133 | let ticket2 = guard2 |
| 1134 | .broker_tickets() |
| 1135 | .unwrap() |
| 1136 | .into_iter() |
| 1137 | .find(|wire| wire.service == "attachments") |
| 1138 | .unwrap() |
| 1139 | .ticket; |
| 1140 | let (cx2, _v2, _c2) = HostRequestContext::for_test(40); |
| 1141 | let err2 = s2 |
| 1142 | .manager |
| 1143 | .shared |
| 1144 | .core_calls |
| 1145 | .serve_broker_in( |
| 1146 | &[(DshService::Attachments, revoke_owner_after_arm)], |
| 1147 | &s2.manager.shared, |
| 1148 | HostCohort::reviewed(), |
| 1149 | HOST_GENERATION, |
| 1150 | DshBrokerParams { |
| 1151 | owner: s2.owner.clone(), |
| 1152 | ticket: ticket2, |
| 1153 | service: "attachments".to_string(), |
| 1154 | method: "validate".to_string(), |
| 1155 | input: json!({ |
| 1156 | "data_base64": STANDARD.encode(PNG_1X1), |
| 1157 | "media_type": "image/png", |
| 1158 | }), |
| 1159 | }, |
| 1160 | cx2, |
| 1161 | ) |
| 1162 | .await |
| 1163 | .expect_err("subsequent validate call must fail closed when owner is revoked"); |
| 1164 | managers.lock().unwrap().remove(&s2.owner.plugin_id); |
| 1165 | assert!(err2.message.contains("owner is no longer current")); |
| 1166 | let still_held = guard2 |
| 1167 | .seal_held_image() |
| 1168 | .expect("later failing broker call must not roll back earlier held_image"); |
| 1169 | assert_eq!( |
| 1170 | still_held.attachment_id, |
| 1171 | format!("sha256:{}", sha256_hex(PNG_1X1)) |
| 1172 | ); |
| 1173 | } |
| 1174 | |
| 1175 | #[tokio::test] |
| 1176 | async fn revoked_attachments_grant_prevents_image_projection_and_records_drop() { |
| 1177 | let s = seam("att-revoke-proj"); |
| 1178 | let ctx = s.context("att-rev"); |
| 1179 | |
| 1180 | let guard = s.begin(&ctx, "call-rev-ref"); |
| 1181 | let saved = wrong_guard_save(&s, &guard).await; |
| 1182 | let id = saved["attachment"]["attachment_id"] |
| 1183 | .as_str() |
| 1184 | .unwrap() |
| 1185 | .to_string(); |
| 1186 | let mut settled = Ok(ToolResultWire { |
| 1187 | content: vec![ |
| 1188 | ContentBlockWire::Text { |
| 1189 | text: "image".to_string(), |
| 1190 | }, |
| 1191 | ContentBlockWire::ImageRef { attachment_id: id }, |
| 1192 | ], |
| 1193 | is_error: false, |
| 1194 | structured: None, |
| 1195 | }); |
| 1196 | let blocks = resolve_held_image(guard.seal_held_image(), false, &mut settled, Some(&guard)); |
| 1197 | assert!(blocks.is_empty()); |
| 1198 | let err = settled.unwrap_err(); |
| 1199 | assert!(err.to_string().contains("grant was revoked"), "{err}"); |
| 1200 | let receipts = guard.seal_receipts().unwrap(); |
| 1201 | let acts = receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 1202 | assert_eq!(acts.last().unwrap()["outcome"], "dropped"); |
| 1203 | assert_eq!(acts.last().unwrap()["reason"], "grant_revoked"); |
| 1204 | |
| 1205 | let guard_text = s.begin(&ctx, "call-rev-text"); |
| 1206 | let _ = wrong_guard_save(&s, &guard_text).await; |
| 1207 | let mut settled_text = Ok(ToolResultWire { |
| 1208 | content: vec![ContentBlockWire::Text { |
| 1209 | text: "text".to_string(), |
| 1210 | }], |
| 1211 | is_error: false, |
| 1212 | structured: None, |
| 1213 | }); |
| 1214 | let text_blocks = resolve_held_image( |
| 1215 | guard_text.seal_held_image(), |
| 1216 | false, |
| 1217 | &mut settled_text, |
| 1218 | Some(&guard_text), |
| 1219 | ); |
| 1220 | assert!(text_blocks.is_empty()); |
| 1221 | assert!(settled_text.is_ok()); |
| 1222 | let text_receipts = guard_text.seal_receipts().unwrap(); |
| 1223 | let text_acts = text_receipts["broker_acts"]["acts"].as_array().unwrap(); |
| 1224 | assert_eq!(text_acts.last().unwrap()["outcome"], "dropped"); |
| 1225 | assert_eq!(text_acts.last().unwrap()["reason"], "grant_revoked"); |
| 1226 | } |
| 1227 |