返回 CodeWhale
dsh_network.rs
根目录 / crates / engine / src / extension_host / dsh_network.rs
1 use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
2 use std::path::{Path, PathBuf};
3 use std::sync::{Arc, LazyLock, Mutex};
4 use std::time::{Duration, Instant};
5
6 use async_trait::async_trait;
7 use base64::{Engine as _, engine::general_purpose::STANDARD};
8 use codewhale_agent_contract::role::NETWORK_DENIAL_SENTINEL;
9 use codewhale_execpolicy::ApprovalMode;
10 use codewhale_execpolicy::tool_rules::tool_denied;
11 use codewhale_net::guard::{
12 PrivateTargets, guarded_reqwest_client_builder, validate_fetch_destination,
13 };
14 use codewhale_secrets::{FileKeyringStore, Secrets};
15 use reqwest::header::{HeaderName, HeaderValue};
16 use serde::{Deserialize, Serialize};
17 use serde_json::{Value, json};
18 use tokio::sync::Semaphore;
19
20 use super::dsh_broker::{
21 BrokerCall, BrokerEffect, BrokerFuture, BrokerMethods, BrokerRefusal, decode,
22 };
23 use super::protocol::DshService;
24 use crate::tools::spec::{
25 ApprovalRequirement, PreparedToolCall, ResourceClaim, ToolCapability, ToolContext, ToolError,
26 ToolResult, ToolSpec,
27 };
28 use crate::tools::web::fetch::network_authorized;
29 use crate::tools::web::guard::validate_network_policy;
30
31 pub const CREDENTIAL_HANDLE_PREFIX: &str = "codewhale-credential:";
32 pub const SEND_TOOL: &str = "plugin_network_send";
33 const MAX_REF_LEN: usize = 128;
34 const MIN_SECRET_BYTES: usize = 8;
35 const MAX_SECRET_BYTES: usize = 4096;
36 const MAX_REFS_PER_PLUGIN: usize = 16;
37 const MAX_REFS_TOTAL: usize = 256;
38 const MAX_HANDLES_PER_REQUEST: usize = 8;
39 const MAX_REDIRECTS: usize = 5;
40 const MAX_HEADERS: usize = 64;
41 const MAX_HEADER_BYTES: usize = 16 * 1024;
42 const MAX_REQUEST_BYTES: usize = 8 * 1024 * 1024;
43 const MAX_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
44 const MAX_FETCHES_AT_ONCE: usize = 4;
45 const MAX_REMEMBERED_ANSWERS: usize = 1024;
46 const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
47 const MAX_TIMEOUT: Duration = Duration::from_secs(120);
48 const AUDIT_LABEL: &str = "dsh_network";
49 const AUDIT_EVENT: &str = "plugin_network_send";
50 const VAULT_ENTRY: &str = "plugin-credentials";
51 const VAULT_FILE: &str = "plugin-credentials.json";
52 const LOG: &str = "codewhale::dsh_network";
53 const FORBIDDEN_HEADERS: &[&str] = &[
54 "host",
55 "connection",
56 "content-length",
57 "transfer-encoding",
58 "te",
59 "trailer",
60 "upgrade",
61 "keep-alive",
62 "proxy-authorization",
63 "proxy-connection",
64 ];
65 const FORBIDDEN_WITH_A_CREDENTIAL: &[&str] = &["accept-encoding", "range", "if-range"];
66 const DROPPED_ON_ANOTHER_SITE: &[&str] = &["authorization", "cookie", "cookie2"];
67 const METHODS: &[&str] = &["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
68
69 const NOT_ALLOWED_HERE: &str = "network access to this site is not allowed here";
70 const NOT_REVIEWED: &str = "this site is not one of the plugin's reviewed network sites";
71 const NOT_FOR_THIS_SITE: &str = "this credential is not stored for this site";
72 const DECLINED: &str = "the person declined to let this plugin send to this site in this session";
73 const VAULT_UNREADABLE: &str = "the plugin credential store could not be read";
74 const VAULT_FULL: &str = "the plugin credential store is full";
75
76 #[derive(Deserialize)]
77 #[serde(tag = "method", content = "input", deny_unknown_fields)]
78 enum NetworkMethod {
79 #[serde(rename = "fetch")]
80 Fetch(FetchInput),
81 #[serde(rename = "credentials.describe")]
82 Describe(CredentialRef),
83 #[serde(rename = "credentials.resolve")]
84 Resolve(CredentialRef),
85 #[serde(rename = "credentials.set")]
86 Set(CredentialWrite),
87 }
88
89 impl BrokerMethods for NetworkMethod {
90 const NAMES: &'static [&'static str] = &[
91 "fetch",
92 "credentials.describe",
93 "credentials.resolve",
94 "credentials.set",
95 ];
96 }
97
98 #[derive(Deserialize)]
99 #[serde(deny_unknown_fields)]
100 struct FetchInput {
101 url: String,
102 #[serde(default)]
103 method: Option<String>,
104 #[serde(default)]
105 headers: Vec<(String, String)>,
106 #[serde(default)]
107 body_base64: Option<String>,
108 #[serde(default)]
109 timeout_ms: Option<u64>,
110 }
111
112 #[derive(Deserialize)]
113 #[serde(deny_unknown_fields)]
114 struct CredentialRef {
115 #[serde(rename = "ref")]
116 name: String,
117 }
118
119 #[derive(Deserialize)]
120 #[serde(deny_unknown_fields)]
121 struct CredentialWrite {
122 #[serde(rename = "ref")]
123 name: String,
124 value: String,
125 site: String,
126 }
127
128 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
129 pub(super) struct Origin {
130 https: bool,
131 host: String,
132 port: u16,
133 }
134
135 impl Origin {
136 fn of(url: &reqwest::Url) -> Option<Self> {
137 let https = match url.scheme() {
138 "https" => true,
139 "http" => false,
140 _ => return None,
141 };
142 if !url.username().is_empty() || url.password().is_some() {
143 return None;
144 }
145 let host = url.host_str()?.to_ascii_lowercase();
146 if host.is_empty() || host.ends_with('.') {
147 return None;
148 }
149 Some(Self {
150 https,
151 host,
152 port: url.port_or_known_default()?,
153 })
154 }
155
156 pub(super) fn parse(site: &str) -> Option<Self> {
157 let url = reqwest::Url::parse(site).ok()?;
158 if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
159 return None;
160 }
161 Self::of(&url)
162 }
163 }
164
165 impl std::fmt::Display for Origin {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 let (scheme, default_port) = if self.https {
168 ("https", 443)
169 } else {
170 ("http", 80)
171 };
172 write!(f, "{scheme}://{}", self.host)?;
173 if self.port != default_port {
174 write!(f, ":{}", self.port)?;
175 }
176 Ok(())
177 }
178 }
179
180 #[derive(Clone, Serialize, Deserialize)]
181 struct Stored {
182 site: String,
183 value: String,
184 }
185
186 #[derive(Default, Serialize, Deserialize)]
187 struct PluginSlots {
188 build: String,
189 credentials: BTreeMap<String, Stored>,
190 }
191
192 #[derive(Default, Serialize, Deserialize)]
193 struct VaultFile {
194 plugins: BTreeMap<String, PluginSlots>,
195 }
196
197 enum VaultError {
198 Unreadable,
199 Full,
200 }
201
202 impl From<VaultError> for BrokerRefusal {
203 fn from(error: VaultError) -> Self {
204 BrokerRefusal::Refused {
205 service: DshService::Network,
206 message: match error {
207 VaultError::Unreadable => VAULT_UNREADABLE,
208 VaultError::Full => VAULT_FULL,
209 }
210 .to_string(),
211 }
212 }
213 }
214
215 #[derive(Clone)]
216 pub(super) struct Vault {
217 store: Secrets,
218 #[cfg(test)]
219 plaintext_for_test: bool,
220 }
221
222 pub(super) fn vault_path(codewhale_home: &Path) -> PathBuf {
223 codewhale_home.join("secrets").join(VAULT_FILE)
224 }
225
226 impl Vault {
227 pub(super) fn over(store: Secrets) -> Self {
228 Self {
229 store,
230 #[cfg(test)]
231 plaintext_for_test: false,
232 }
233 }
234
235 pub(super) fn at(path: PathBuf) -> Self {
236 Self::over(Secrets::new(Arc::new(FileKeyringStore::new(path))))
237 }
238
239 fn open() -> Option<Self> {
240 let home = codewhale_config::codewhale_home().ok()?;
241 Some(Self::at(vault_path(&home)))
242 }
243
244 fn carries(&self, site: &Origin) -> bool {
245 #[cfg(test)]
246 if self.plaintext_for_test {
247 return true;
248 }
249 site.https
250 }
251
252 fn load(&self) -> Result<VaultFile, VaultError> {
253 match self.store.get(VAULT_ENTRY) {
254 Ok(None) => Ok(VaultFile::default()),
255 Ok(Some(raw)) => serde_json::from_str(&raw).map_err(|_| VaultError::Unreadable),
256 Err(_) => Err(VaultError::Unreadable),
257 }
258 }
259
260 fn read_blocking(
261 &self,
262 plugin: &str,
263 build: &str,
264 ) -> Result<BTreeMap<String, Stored>, VaultError> {
265 Ok(self
266 .load()?
267 .plugins
268 .remove(plugin)
269 .filter(|slots| slots.build == build)
270 .map(|slots| slots.credentials)
271 .unwrap_or_default())
272 }
273
274 fn write_blocking(
275 &self,
276 plugin: &str,
277 build: &str,
278 name: &str,
279 stored: Stored,
280 ) -> Result<(), VaultError> {
281 self.store
282 .with_entry_transaction(VAULT_ENTRY, |entry| {
283 let mut file: VaultFile = match entry.as_deref() {
284 None => VaultFile::default(),
285 Some(raw) => match serde_json::from_str(raw) {
286 Ok(file) => file,
287 Err(_) => return Ok(Err(VaultError::Unreadable)),
288 },
289 };
290 let slots = file.plugins.entry(plugin.to_string()).or_default();
291 if slots.build != build {
292 *slots = PluginSlots {
293 build: build.to_string(),
294 credentials: BTreeMap::new(),
295 };
296 }
297 let new = !slots.credentials.contains_key(name);
298 if new && slots.credentials.len() >= MAX_REFS_PER_PLUGIN {
299 return Ok(Err(VaultError::Full));
300 }
301 let total: usize = file
302 .plugins
303 .values()
304 .map(|slots| slots.credentials.len())
305 .sum();
306 if new && total >= MAX_REFS_TOTAL {
307 return Ok(Err(VaultError::Full));
308 }
309 file.plugins
310 .entry(plugin.to_string())
311 .or_default()
312 .credentials
313 .insert(name.to_string(), stored);
314 *entry = Some(serde_json::to_string(&file)?);
315 Ok(Ok(()))
316 })
317 .unwrap_or(Err(VaultError::Unreadable))
318 }
319
320 fn forget_blocking(&self, plugin: &str) -> Result<(), VaultError> {
321 self.store
322 .with_entry_transaction(VAULT_ENTRY, |entry| {
323 let Some(raw) = entry.as_deref() else {
324 return Ok(Ok(()));
325 };
326 let mut file: VaultFile = match serde_json::from_str(raw) {
327 Ok(file) => file,
328 Err(_) => return Ok(Err(VaultError::Unreadable)),
329 };
330 if file.plugins.remove(plugin).is_some() {
331 *entry = Some(serde_json::to_string(&file)?);
332 }
333 Ok(Ok(()))
334 })
335 .unwrap_or(Err(VaultError::Unreadable))
336 }
337
338 async fn read(
339 &self,
340 plugin: &str,
341 build: &str,
342 ) -> Result<BTreeMap<String, Stored>, BrokerRefusal> {
343 let (vault, plugin, build) = (self.clone(), plugin.to_string(), build.to_string());
344 tokio::task::spawn_blocking(move || vault.read_blocking(&plugin, &build))
345 .await
346 .unwrap_or(Err(VaultError::Unreadable))
347 .map_err(BrokerRefusal::from)
348 }
349
350 async fn write(
351 &self,
352 plugin: &str,
353 build: &str,
354 name: &str,
355 stored: Stored,
356 ) -> Result<(), BrokerRefusal> {
357 let (vault, plugin, build, name) = (
358 self.clone(),
359 plugin.to_string(),
360 build.to_string(),
361 name.to_string(),
362 );
363 tokio::task::spawn_blocking(move || vault.write_blocking(&plugin, &build, &name, stored))
364 .await
365 .unwrap_or(Err(VaultError::Unreadable))
366 .map_err(BrokerRefusal::from)
367 }
368 }
369
370 pub fn forget_plugin_credentials(plugin_id: &str) -> bool {
371 Vault::open().is_some_and(|vault| vault.forget_blocking(plugin_id).is_ok())
372 }
373
374 #[derive(Clone)]
375 pub(super) struct NetworkAuthority {
376 pub build: String,
377 pub sites: BTreeSet<Origin>,
378 pub vault: Vault,
379 #[cfg(test)]
380 pub test_dns_pins: BTreeMap<String, std::net::IpAddr>,
381 }
382
383 fn reviewed_sites(
384 _plugin_id: &str,
385 _plugins: &codewhale_plugins::PluginRegistry,
386 ) -> BTreeSet<Origin> {
387 BTreeSet::new()
388 }
389
390 fn authority_of(call: &BrokerCall) -> Option<NetworkAuthority> {
391 let plugins = call.context.tool().plugin_registry.as_ref()?;
392 let plugin = plugins.get(&call.owner.plugin_id)?;
393 if !plugin.trusted() || !plugin.enabled {
394 return None;
395 }
396 Some(NetworkAuthority {
397 build: plugin.content_hash.clone(),
398 sites: reviewed_sites(&call.owner.plugin_id, plugins),
399 vault: Vault::open()?,
400 #[cfg(test)]
401 test_dns_pins: BTreeMap::new(),
402 })
403 }
404
405 pub(super) fn serve(call: BrokerCall) -> BrokerFuture {
406 match authority_of(&call) {
407 Some(authority) => serve_with(call, authority),
408 None => Box::pin(async move {
409 decode::<NetworkMethod>(&call)?;
410 Err(BrokerRefusal::NotAvailable(DshService::Network))
411 }),
412 }
413 }
414
415 pub(super) fn serve_with(call: BrokerCall, authority: NetworkAuthority) -> BrokerFuture {
416 Box::pin(async move {
417 let method = decode::<NetworkMethod>(&call)?;
418 let plugin = call.owner.plugin_id.clone();
419 if call.context.cancel().is_cancelled() {
420 return Err(refused(&plugin, "cancelled", NOT_ALLOWED_HERE));
421 }
422 match method {
423 NetworkMethod::Fetch(input) => fetch(&call, &authority, input).await,
424 NetworkMethod::Describe(CredentialRef { name }) => {
425 let name = checked_ref(&name)?;
426 call.context
427 .act("credentials.describe", BrokerEffect::Read, Some(name))
428 .await?;
429 let stored = authority
430 .vault
431 .read(&plugin, &authority.build)
432 .await?
433 .remove(name);
434 tracing::info!(target: LOG, plugin = %plugin, credential = %name, set = stored.is_some(), "credential described");
435 Ok(json!({
436 "ref": name,
437 "set": stored.is_some(),
438 "site": stored.map(|stored| stored.site),
439 "handle": handle(name),
440 }))
441 }
442 NetworkMethod::Resolve(CredentialRef { name }) => {
443 let name = checked_ref(&name)?;
444 call.context
445 .act("credentials.resolve", BrokerEffect::Read, Some(name))
446 .await?;
447 let set = authority
448 .vault
449 .read(&plugin, &authority.build)
450 .await?
451 .contains_key(name);
452 tracing::info!(target: LOG, plugin = %plugin, credential = %name, set, "credential resolved to its handle");
453 Ok(json!({ "ref": name, "value": set.then(|| handle(name)) }))
454 }
455 NetworkMethod::Set(CredentialWrite { name, value, site }) => {
456 let name = checked_ref(&name)?;
457 let site = Origin::parse(&site)
458 .filter(|site| authority.vault.carries(site))
459 .ok_or_else(|| {
460 invalid(
461 "a credential site is an https origin such as https://api.example.com",
462 )
463 })?;
464 if !authority.sites.contains(&site) {
465 return Err(refused(&plugin, "unreviewed_site", NOT_REVIEWED));
466 }
467 if !(MIN_SECRET_BYTES..=MAX_SECRET_BYTES).contains(&value.len()) {
468 return Err(invalid(format!(
469 "a credential value is {MIN_SECRET_BYTES} to {MAX_SECRET_BYTES} bytes"
470 )));
471 }
472 if value.contains(CREDENTIAL_HANDLE_PREFIX)
473 || HeaderValue::from_str(&value).is_err()
474 {
475 return Err(invalid(
476 "a credential value is text a request header can carry, not a handle",
477 ));
478 }
479 call.context
480 .act("credentials.set", BrokerEffect::Write, Some(name))
481 .await?;
482 if call.context.cancel().is_cancelled() {
483 return Err(refused(&plugin, "cancelled", NOT_ALLOWED_HERE));
484 }
485 authority
486 .vault
487 .write(
488 &plugin,
489 &authority.build,
490 name,
491 Stored {
492 site: site.to_string(),
493 value,
494 },
495 )
496 .await?;
497 tracing::info!(target: LOG, plugin = %plugin, credential = %name, site = %site, "credential stored");
498 Ok(
499 json!({ "ref": name, "set": true, "site": site.to_string(), "handle": handle(name) }),
500 )
501 }
502 }
503 })
504 }
505
506 fn invalid(message: impl Into<String>) -> BrokerRefusal {
507 BrokerRefusal::InvalidInput {
508 service: DshService::Network,
509 message: message.into(),
510 }
511 }
512
513 fn refused(plugin: &str, reason: &'static str, message: &'static str) -> BrokerRefusal {
514 tracing::info!(target: LOG, plugin = %plugin, reason, "network broker refused");
515 BrokerRefusal::Refused {
516 service: DshService::Network,
517 message: message.to_string(),
518 }
519 }
520
521 fn checked_ref(name: &str) -> Result<&str, BrokerRefusal> {
522 let ok = !name.is_empty()
523 && name.len() <= MAX_REF_LEN
524 && name
525 .bytes()
526 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'));
527 if ok {
528 Ok(name)
529 } else {
530 Err(invalid(format!(
531 "a credential ref is 1 to {MAX_REF_LEN} letters, digits, `_`, `-` or `.`"
532 )))
533 }
534 }
535
536 fn handle(name: &str) -> String {
537 format!("{CREDENTIAL_HANDLE_PREFIX}{name}")
538 }
539
540 fn caller_allows_network(tool: &ToolContext) -> bool {
541 let mut live = tool.clone();
542 live.refresh_live_posture();
543 let denied = |name: &str| tool_denied(Some(live.disallowed_tools.as_slice()), name);
544 network_authorized(&live)
545 && !matches!(live.approval_mode, ApprovalMode::Never | ApprovalMode::Auto)
546 && live.shell_network_denied_hint.is_none()
547 && live.acp_host != Some(codewhale_config::AppMode::Plan)
548 && !denied(NETWORK_DENIAL_SENTINEL)
549 && !denied(SEND_TOOL)
550 }
551
552 type AnswerKey = (String, String, String);
553
554 #[derive(Default)]
555 struct Answers {
556 known: HashMap<AnswerKey, bool>,
557 order: VecDeque<AnswerKey>,
558 asking: HashMap<AnswerKey, Arc<tokio::sync::Mutex<()>>>,
559 }
560
561 static ANSWERS: LazyLock<Mutex<Answers>> = LazyLock::new(Mutex::default);
562 static PENDING: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Mutex::default);
563 static SLOTS: LazyLock<Mutex<HashMap<String, Arc<Semaphore>>>> = LazyLock::new(Mutex::default);
564
565 struct PendingRequest(String);
566
567 impl PendingRequest {
568 fn open() -> Self {
569 let id = uuid::Uuid::new_v4().simple().to_string();
570 PENDING.lock().expect("pending lock").insert(id.clone());
571 Self(id)
572 }
573 }
574
575 impl Drop for PendingRequest {
576 fn drop(&mut self) {
577 PENDING.lock().expect("pending lock").remove(&self.0);
578 }
579 }
580
581 fn answered(key: &AnswerKey) -> Option<bool> {
582 ANSWERS
583 .lock()
584 .expect("answers lock")
585 .known
586 .get(key)
587 .copied()
588 }
589
590 fn declined() -> BrokerRefusal {
591 BrokerRefusal::Denied {
592 service: DshService::Network,
593 message: DECLINED.to_string(),
594 }
595 }
596
597 async fn consent(call: &BrokerCall, site: &Origin) -> Result<(), BrokerRefusal> {
598 let plugin = &call.owner.plugin_id;
599 let key = (call.session_id.clone(), plugin.clone(), site.to_string());
600 let turn = {
601 let mut answers = ANSWERS.lock().expect("answers lock");
602 match answers.known.get(&key).copied() {
603 Some(true) => return Ok(()),
604 Some(false) => return Err(declined()),
605 None => {
606 if answers.asking.len() >= MAX_REMEMBERED_ANSWERS {
607 answers.asking.retain(|_, turn| Arc::strong_count(turn) > 1);
608 }
609 Arc::clone(answers.asking.entry(key.clone()).or_default())
610 }
611 }
612 };
613 let waiting = turn.lock().await;
614 let mut answer = answered(&key);
615 if answer.is_none() {
616 let request = PendingRequest::open();
617 let outcome = call
618 .context
619 .core_call(
620 SEND_TOOL,
621 json!({ "request": request.0, "plugin": plugin, "url": format!("{site}/") }),
622 )
623 .await;
624 answer = match outcome {
625 Ok(response) if response.ok => Some(true),
626 Err(BrokerRefusal::Denied { .. }) => Some(false),
627 _ => None,
628 };
629 tracing::info!(target: LOG, plugin = %plugin, site = %site, answer = ?answer, "first send to a site asked");
630 }
631 {
632 let mut answers = ANSWERS.lock().expect("answers lock");
633 if let Some(answer) = answer
634 && answers.known.insert(key.clone(), answer).is_none()
635 {
636 answers.order.push_back(key.clone());
637 while answers.order.len() > MAX_REMEMBERED_ANSWERS {
638 if let Some(oldest) = answers.order.pop_front() {
639 answers.known.remove(&oldest);
640 }
641 }
642 }
643 drop(waiting);
644 if Arc::strong_count(&turn) <= 2 {
645 answers.asking.remove(&key);
646 }
647 }
648 match answer {
649 Some(true) => Ok(()),
650 Some(false) => Err(declined()),
651 None => Err(refused(plugin, "no_answer", NOT_ALLOWED_HERE)),
652 }
653 }
654
655 #[derive(Deserialize)]
656 #[serde(deny_unknown_fields)]
657 struct ConsentInput {
658 request: String,
659 plugin: String,
660 url: String,
661 }
662
663 fn pending(input: &Value) -> Result<ConsentInput, ToolError> {
664 let asked: ConsentInput = serde_json::from_value(input.clone())
665 .map_err(|_| ToolError::invalid_input("not a plugin network request"))?;
666 if PENDING
667 .lock()
668 .expect("pending lock")
669 .contains(&asked.request)
670 {
671 Ok(asked)
672 } else {
673 Err(ToolError::permission_denied(
674 "only the plugin network broker raises this request",
675 ))
676 }
677 }
678
679 pub(super) struct SendConsent;
680
681 #[async_trait]
682 impl ToolSpec for SendConsent {
683 fn name(&self) -> &str {
684 SEND_TOOL
685 }
686
687 fn description(&self) -> &str {
688 "Asks the person before a plugin sends data to a site for the first time in a session. Only the plugin network broker raises it."
689 }
690
691 fn input_schema(&self) -> Value {
692 json!({
693 "type": "object",
694 "properties": {
695 "request": { "type": "string" },
696 "plugin": { "type": "string" },
697 "url": { "type": "string" },
698 },
699 "required": ["request", "plugin", "url"],
700 "additionalProperties": false,
701 })
702 }
703
704 fn capabilities(&self) -> Vec<ToolCapability> {
705 vec![ToolCapability::Network, ToolCapability::RequiresApproval]
706 }
707
708 fn approval_requirement(&self) -> ApprovalRequirement {
709 ApprovalRequirement::Required
710 }
711
712 fn model_visible(&self) -> bool {
713 false
714 }
715
716 fn prepare(&self, input: Value, _context: &ToolContext) -> Result<PreparedToolCall, ToolError> {
717 let asked = pending(&input)?;
718 Ok(PreparedToolCall {
719 name: SEND_TOOL.to_string(),
720 description: format!(
721 "Plugin `{}` wants to send data to {}. Approving lets it send to this site for the rest of this session.",
722 asked.plugin,
723 asked.url.trim_end_matches('/')
724 ),
725 read_only: false,
726 supports_parallel: true,
727 starts_detached: false,
728 approval: ApprovalRequirement::Required,
729 resources: vec![ResourceClaim::GlobalExclusive],
730 input,
731 })
732 }
733
734 async fn execute(&self, input: Value, _context: &ToolContext) -> Result<ToolResult, ToolError> {
735 pending(&input)?;
736 Ok(ToolResult::success("approved"))
737 }
738 }
739
740 fn slots(call: &BrokerCall) -> Arc<Semaphore> {
741 let key = format!(
742 "{}\n{}",
743 call.session_id,
744 call.context
745 .tool()
746 .origin_tool_call_id
747 .as_deref()
748 .unwrap_or_default()
749 );
750 let mut slots = SLOTS.lock().expect("slots lock");
751 slots.retain(|_, slot| Arc::strong_count(slot) > 1);
752 Arc::clone(
753 slots
754 .entry(key)
755 .or_insert_with(|| Arc::new(Semaphore::new(MAX_FETCHES_AT_ONCE))),
756 )
757 }
758
759 enum Part {
760 Text(String),
761 Handle(String),
762 }
763
764 struct HeaderPlan {
765 name: HeaderName,
766 parts: Vec<Part>,
767 }
768
769 impl HeaderPlan {
770 fn refs(&self) -> impl Iterator<Item = &str> {
771 self.parts.iter().filter_map(|part| match part {
772 Part::Handle(name) => Some(name.as_str()),
773 Part::Text(_) => None,
774 })
775 }
776 }
777
778 fn plan_headers(headers: &[(String, String)]) -> Result<Vec<HeaderPlan>, BrokerRefusal> {
779 if headers.len() > MAX_HEADERS
780 || headers
781 .iter()
782 .map(|(name, value)| name.len() + value.len())
783 .sum::<usize>()
784 > MAX_HEADER_BYTES
785 {
786 return Err(invalid("too many or too large request headers"));
787 }
788 let mut plans = Vec::with_capacity(headers.len());
789 let mut handles = 0usize;
790 for (name, value) in headers {
791 let name = HeaderName::from_bytes(name.as_bytes())
792 .map_err(|_| invalid("a request header name is not valid"))?;
793 if FORBIDDEN_HEADERS.contains(&name.as_str()) {
794 return Err(invalid(format!(
795 "request header `{name}` is set by the broker, not the plugin"
796 )));
797 }
798 let mut parts = Vec::new();
799 let mut rest = value.as_str();
800 while let Some(at) = rest.find(CREDENTIAL_HANDLE_PREFIX) {
801 if at > 0 {
802 parts.push(Part::Text(rest[..at].to_string()));
803 }
804 let tail = &rest[at + CREDENTIAL_HANDLE_PREFIX.len()..];
805 let end = tail
806 .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')))
807 .unwrap_or(tail.len());
808 parts.push(Part::Handle(checked_ref(&tail[..end])?.to_string()));
809 handles += 1;
810 if handles > MAX_HANDLES_PER_REQUEST {
811 return Err(invalid(format!(
812 "a request carries at most {MAX_HANDLES_PER_REQUEST} credential handles"
813 )));
814 }
815 rest = &tail[end..];
816 }
817 if !rest.is_empty() {
818 parts.push(Part::Text(rest.to_string()));
819 }
820 plans.push(HeaderPlan { name, parts });
821 }
822 if handles > 0
823 && let Some(plan) = plans
824 .iter()
825 .find(|plan| FORBIDDEN_WITH_A_CREDENTIAL.contains(&plan.name.as_str()))
826 {
827 return Err(invalid(format!(
828 "request header `{}` is not sent together with a credential",
829 plan.name
830 )));
831 }
832 Ok(plans)
833 }
834
835 struct Rendered {
836 headers: Vec<(HeaderName, HeaderValue)>,
837 sent: Vec<String>,
838 }
839
840 fn render_headers(
841 plugin: &str,
842 plans: &[HeaderPlan],
843 credentials: &BTreeMap<String, Stored>,
844 vault: &Vault,
845 site: &Origin,
846 first: &Origin,
847 ) -> Result<Rendered, BrokerRefusal> {
848 let here = site.to_string();
849 let mut rendered = Rendered {
850 headers: Vec::with_capacity(plans.len()),
851 sent: Vec::new(),
852 };
853 let mut bytes = 0usize;
854 for plan in plans {
855 let bound_here = plan.refs().next().is_none()
856 || (vault.carries(site)
857 && plan.refs().all(|name| {
858 credentials
859 .get(name)
860 .is_some_and(|stored| stored.site == here)
861 }));
862 if !bound_here {
863 if site == first {
864 return Err(refused(plugin, "credential_binding", NOT_FOR_THIS_SITE));
865 }
866 continue;
867 }
868 if site != first && DROPPED_ON_ANOTHER_SITE.contains(&plan.name.as_str()) {
869 continue;
870 }
871 let mut value = String::new();
872 for part in &plan.parts {
873 match part {
874 Part::Text(text) => value.push_str(text),
875 Part::Handle(name) => {
876 value.push_str(&credentials[name].value);
877 if !rendered.sent.contains(name) {
878 rendered.sent.push(name.clone());
879 }
880 }
881 }
882 }
883 bytes += plan.name.as_str().len() + value.len();
884 if bytes > MAX_HEADER_BYTES {
885 return Err(invalid(
886 "request headers are too large once credentials are filled in",
887 ));
888 }
889 let value = HeaderValue::from_str(&value).map_err(|_| {
890 invalid(format!(
891 "request header `{}` has an invalid value",
892 plan.name
893 ))
894 })?;
895 rendered.headers.push((plan.name.clone(), value));
896 }
897 Ok(rendered)
898 }
899
900 fn failure_table(needle: &[u8]) -> Vec<usize> {
901 let mut table = vec![0usize; needle.len()];
902 let mut matched = 0usize;
903 for at in 1..needle.len() {
904 while matched > 0 && needle[matched] != needle[at] {
905 matched = table[matched - 1];
906 }
907 if needle[matched] == needle[at] {
908 matched += 1;
909 }
910 table[at] = matched;
911 }
912 table
913 }
914
915 fn scrub(bytes: &[u8], secrets: &[(String, String)], cap: usize) -> Option<Vec<u8>> {
916 const INSIDE: u8 = u8::MAX;
917 let mut cover = vec![0u8; bytes.len()];
918 for (index, (_, secret)) in secrets.iter().enumerate().take(usize::from(INSIDE) - 1) {
919 let needle = secret.as_bytes();
920 if needle.is_empty() || needle.len() > bytes.len() {
921 continue;
922 }
923 let table = failure_table(needle);
924 let tag = index as u8 + 1;
925 let (mut matched, mut marked) = (0usize, 0usize);
926 for (at, byte) in bytes.iter().enumerate() {
927 while matched > 0 && needle[matched] != *byte {
928 matched = table[matched - 1];
929 }
930 if needle[matched] == *byte {
931 matched += 1;
932 }
933 if matched == needle.len() {
934 let start = at + 1 - needle.len();
935 for slot in &mut cover[start.max(marked)..=at] {
936 if *slot == 0 {
937 *slot = INSIDE;
938 }
939 }
940 if cover[start] == INSIDE {
941 cover[start] = tag;
942 }
943 marked = at + 1;
944 matched = table[matched - 1];
945 }
946 }
947 }
948 let mut out = Vec::with_capacity(bytes.len().min(cap));
949 let mut at = 0usize;
950 while at < bytes.len() {
951 if cover[at] == 0 {
952 out.push(bytes[at]);
953 at += 1;
954 } else {
955 let handle = secrets
956 .get(usize::from(cover[at]) - 1)
957 .map_or(CREDENTIAL_HANDLE_PREFIX, |(handle, _)| handle.as_str());
958 out.extend_from_slice(handle.as_bytes());
959 while at < bytes.len() && cover[at] != 0 {
960 at += 1;
961 }
962 }
963 if out.len() > cap {
964 return None;
965 }
966 }
967 Some(out)
968 }
969
970 #[cfg(test)]
971 pub(super) static SCRUBBED_ON: Mutex<Option<std::thread::ThreadId>> = Mutex::new(None);
972
973 struct Scrubbed {
974 url: String,
975 headers: Vec<(String, String)>,
976 body_base64: String,
977 }
978
979 fn scrub_answer(
980 url: String,
981 headers: Vec<(String, Vec<u8>)>,
982 body: Vec<u8>,
983 secrets: Vec<(String, String)>,
984 ) -> Option<Scrubbed> {
985 #[cfg(test)]
986 {
987 *SCRUBBED_ON.lock().expect("scrub thread lock") = Some(std::thread::current().id());
988 }
989 let text = |bytes: &[u8], cap: usize| {
990 scrub(bytes, &secrets, cap).and_then(|clean| String::from_utf8(clean).ok())
991 };
992 Some(Scrubbed {
993 url: text(url.as_bytes(), MAX_RESPONSE_BYTES)?,
994 headers: headers
995 .into_iter()
996 .filter_map(|(name, value)| Some((name, text(&value, MAX_HEADER_BYTES)?)))
997 .collect(),
998 body_base64: STANDARD.encode(scrub(&body, &secrets, MAX_RESPONSE_BYTES)?),
999 })
1000 }
1001
1002 struct Receipt(Option<Value>);
1003
1004 impl Receipt {
1005 fn open(call: &BrokerCall, site: &Origin, method: &str, bytes_out: usize) -> Self {
1006 Self(Some(json!({
1007 "plugin": call.owner.plugin_id,
1008 "session": call.session_id,
1009 "site": site.to_string(),
1010 "method": method,
1011 "bytes_out": bytes_out,
1012 "bytes_in": 0,
1013 "status": Value::Null,
1014 "outcome": "cancelled",
1015 })))
1016 }
1017
1018 async fn close(mut self, status: Option<u16>, bytes_in: usize, outcome: &'static str) {
1019 if let Some(mut event) = self.0.take() {
1020 event["status"] = json!(status);
1021 event["bytes_in"] = json!(bytes_in);
1022 event["outcome"] = json!(outcome);
1023 let _ = tokio::task::spawn_blocking(move || {
1024 codewhale_runtime::audit::log_sensitive_event(AUDIT_EVENT, event);
1025 })
1026 .await;
1027 }
1028 }
1029 }
1030
1031 impl Drop for Receipt {
1032 fn drop(&mut self) {
1033 if let Some(event) = self.0.take()
1034 && let Ok(runtime) = tokio::runtime::Handle::try_current()
1035 {
1036 runtime.spawn_blocking(move || {
1037 codewhale_runtime::audit::log_sensitive_event(AUDIT_EVENT, event);
1038 });
1039 }
1040 }
1041 }
1042
1043 fn pinned_client(
1044 pin: Option<(String, std::net::IpAddr)>,
1045 timeout: Duration,
1046 ) -> Result<reqwest::Client, BrokerRefusal> {
1047 let mut builder = guarded_reqwest_client_builder()
1048 .timeout(timeout)
1049 .redirect(reqwest::redirect::Policy::none());
1050 if let Some((name, ip)) = pin {
1051 builder = builder.resolve(&name, std::net::SocketAddr::new(ip, 0));
1052 }
1053 builder
1054 .build()
1055 .map_err(|_| invalid("the network broker could not build its client"))
1056 }
1057
1058 fn failed(plugin: &str, error: &reqwest::Error) -> BrokerRefusal {
1059 let (reason, message) = if error.is_timeout() {
1060 ("timeout", "the request failed: timed out")
1061 } else if error.is_connect() {
1062 ("connect", "the request failed: could not connect")
1063 } else {
1064 ("transport", "the request failed: transport error")
1065 };
1066 refused(plugin, reason, message)
1067 }
1068
1069 async fn fetch(
1070 call: &BrokerCall,
1071 authority: &NetworkAuthority,
1072 input: FetchInput,
1073 ) -> Result<Value, BrokerRefusal> {
1074 let plugin = call.owner.plugin_id.as_str();
1075 let tool = call.context.tool();
1076 let mut url = reqwest::Url::parse(&input.url).map_err(|_| invalid("the URL is not valid"))?;
1077 if input.url.contains(CREDENTIAL_HANDLE_PREFIX) {
1078 return Err(invalid(
1079 "credential handles are substituted only in request header values",
1080 ));
1081 }
1082 let mut method = input
1083 .method
1084 .as_deref()
1085 .unwrap_or("GET")
1086 .to_ascii_uppercase();
1087 if !METHODS.contains(&method.as_str()) {
1088 return Err(invalid(
1089 "the request method is not one the network broker sends",
1090 ));
1091 }
1092 let plans = plan_headers(&input.headers)?;
1093 let mut body = match input.body_base64.as_deref() {
1094 Some(encoded) => {
1095 if encoded.len() > MAX_REQUEST_BYTES.div_ceil(3) * 4 {
1096 return Err(invalid("the request body is too large"));
1097 }
1098 let bytes = STANDARD
1099 .decode(encoded)
1100 .map_err(|_| invalid("body_base64 is not valid base64"))?;
1101 if bytes.len() > MAX_REQUEST_BYTES {
1102 return Err(invalid("the request body is too large"));
1103 }
1104 Some(bytes)
1105 }
1106 None => None,
1107 };
1108 let first = Origin::of(&url).ok_or_else(|| {
1109 invalid("only http and https URLs with a plain host and no userinfo are brokered")
1110 })?;
1111 let credentials = if plans.iter().any(|plan| plan.refs().next().is_some()) {
1112 let stored = authority.vault.read(plugin, &authority.build).await?;
1113 if let Some(missing) = plans
1114 .iter()
1115 .flat_map(|plan| plan.refs())
1116 .find(|name| !stored.contains_key(*name))
1117 {
1118 return Err(invalid(format!(
1119 "credential `{missing}` is not set for this plugin"
1120 )));
1121 }
1122 stored
1123 } else {
1124 BTreeMap::new()
1125 };
1126 let slot = slots(call);
1127 let _slot = slot
1128 .acquire()
1129 .await
1130 .map_err(|_| refused(plugin, "slots_closed", NOT_ALLOWED_HERE))?;
1131 let timeout = input
1132 .timeout_ms
1133 .map_or(DEFAULT_TIMEOUT, Duration::from_millis)
1134 .min(MAX_TIMEOUT);
1135 let mut deadline = Instant::now() + timeout;
1136 let mut redirects = 0usize;
1137 let mut sent: Vec<String> = Vec::new();
1138 let (response, receipt) = loop {
1139 if call.context.cancel().is_cancelled() || !caller_allows_network(tool) {
1140 return Err(refused(plugin, "caller_limit", NOT_ALLOWED_HERE));
1141 }
1142 let site = Origin::of(&url)
1143 .filter(|site| authority.sites.contains(site))
1144 .ok_or_else(|| refused(plugin, "unreviewed_site", NOT_REVIEWED))?;
1145 let decider = tool
1146 .network_policy
1147 .as_ref()
1148 .ok_or_else(|| refused(plugin, "no_policy", NOT_ALLOWED_HERE))?;
1149 validate_network_policy(&site.host, tool, AUDIT_LABEL)
1150 .map_err(|_| refused(plugin, "policy", NOT_ALLOWED_HERE))?;
1151 let pin = {
1152 #[cfg(test)]
1153 if let Some(ip) = authority.test_dns_pins.get(&site.host) {
1154 Some((site.host.clone(), *ip))
1155 } else {
1156 validate_fetch_destination(
1157 site.host.clone(),
1158 Some(decider),
1159 AUDIT_LABEL,
1160 true,
1161 PrivateTargets::Refuse,
1162 )
1163 .await
1164 .map_err(|_| refused(plugin, "address", NOT_ALLOWED_HERE))?
1165 }
1166 #[cfg(not(test))]
1167 validate_fetch_destination(
1168 site.host.clone(),
1169 Some(decider),
1170 AUDIT_LABEL,
1171 true,
1172 PrivateTargets::Refuse,
1173 )
1174 .await
1175 .map_err(|_| refused(plugin, "address", NOT_ALLOWED_HERE))?
1176 };
1177 let rendered = render_headers(
1178 plugin,
1179 &plans,
1180 &credentials,
1181 &authority.vault,
1182 &site,
1183 &first,
1184 )?;
1185 if answered(&(
1186 call.session_id.clone(),
1187 plugin.to_string(),
1188 site.to_string(),
1189 )) == Some(false)
1190 {
1191 return Err(declined());
1192 }
1193 let asked = Instant::now();
1194 call.context
1195 .act("fetch", BrokerEffect::Reach, Some(&site.host))
1196 .await?;
1197 consent(call, &site).await?;
1198 deadline += asked.elapsed();
1199 if call.context.cancel().is_cancelled() || !caller_allows_network(tool) {
1200 return Err(refused(plugin, "caller_limit", NOT_ALLOWED_HERE));
1201 }
1202 let remaining = deadline.saturating_duration_since(Instant::now());
1203 if remaining.is_zero() {
1204 return Err(refused(plugin, "timeout", "the request failed: timed out"));
1205 }
1206 let client = pinned_client(pin, remaining)?;
1207 let verb = reqwest::Method::from_bytes(method.as_bytes())
1208 .map_err(|_| invalid("the request method is not valid"))?;
1209 let mut request = client.request(verb, url.clone());
1210 for (name, value) in &rendered.headers {
1211 request = request.header(name, value);
1212 }
1213 if let Some(bytes) = body.clone() {
1214 request = request.body(bytes);
1215 }
1216 for name in rendered.sent {
1217 if !sent.contains(&name) {
1218 sent.push(name);
1219 }
1220 }
1221 let receipt = Receipt::open(call, &site, &method, body.as_ref().map_or(0, Vec::len));
1222 let response = match request.send().await {
1223 Ok(response) => response,
1224 Err(error) => {
1225 receipt.close(None, 0, "failed").await;
1226 return Err(failed(plugin, &error));
1227 }
1228 };
1229 let status = response.status();
1230 let location = status
1231 .is_redirection()
1232 .then(|| response.headers().get(reqwest::header::LOCATION))
1233 .flatten()
1234 .and_then(|value| value.to_str().ok());
1235 let Some(location) = location else {
1236 break (response, receipt);
1237 };
1238 let next = url.join(location);
1239 drop(response);
1240 receipt.close(Some(status.as_u16()), 0, "redirected").await;
1241 if redirects >= MAX_REDIRECTS {
1242 return Err(refused(
1243 plugin,
1244 "redirects",
1245 "the request failed: too many redirects",
1246 ));
1247 }
1248 if status == reqwest::StatusCode::SEE_OTHER
1249 || (matches!(status.as_u16(), 301 | 302) && method == "POST")
1250 {
1251 method = "GET".into();
1252 body = None;
1253 }
1254 url = next.map_err(|_| refused(plugin, "redirect_location", NOT_ALLOWED_HERE))?;
1255 redirects += 1;
1256 };
1257 let status = response.status().as_u16();
1258 let final_url = response.url().to_string();
1259 let headers: Vec<(String, Vec<u8>)> = response
1260 .headers()
1261 .iter()
1262 .map(|(name, value)| (name.as_str().to_string(), value.as_bytes().to_vec()))
1263 .collect();
1264 let mut response = response;
1265 let mut bytes = Vec::new();
1266 loop {
1267 let remaining = deadline.saturating_duration_since(Instant::now());
1268 let chunk = match tokio::time::timeout(remaining, response.chunk()).await {
1269 Ok(Ok(chunk)) => chunk,
1270 Ok(Err(_)) | Err(_) => {
1271 receipt.close(Some(status), bytes.len(), "failed").await;
1272 return Err(refused(
1273 plugin,
1274 "body",
1275 "the request failed: the response could not be read",
1276 ));
1277 }
1278 };
1279 let Some(chunk) = chunk else { break };
1280 if bytes.len() + chunk.len() > MAX_RESPONSE_BYTES {
1281 receipt
1282 .close(Some(status), bytes.len(), "response_too_large")
1283 .await;
1284 return Err(refused(
1285 plugin,
1286 "response_too_large",
1287 "the request failed: the response is larger than the broker returns",
1288 ));
1289 }
1290 bytes.extend_from_slice(&chunk);
1291 }
1292 let bytes_in = bytes.len();
1293 let secrets: Vec<(String, String)> = sent
1294 .iter()
1295 .map(|name| (handle(name), credentials[name].value.clone()))
1296 .collect();
1297 let scrubbed =
1298 tokio::task::spawn_blocking(move || scrub_answer(final_url, headers, bytes, secrets))
1299 .await
1300 .ok()
1301 .flatten();
1302 let Some(scrubbed) = scrubbed else {
1303 receipt
1304 .close(Some(status), bytes_in, "response_too_large")
1305 .await;
1306 return Err(refused(
1307 plugin,
1308 "scrub_cap",
1309 "the request failed: the response is larger than the broker returns",
1310 ));
1311 };
1312 receipt.close(Some(status), bytes_in, "ok").await;
1313 tracing::info!(target: LOG, plugin = %plugin, site = %first, status, redirects, "brokered fetch");
1314 Ok(json!({
1315 "status": status,
1316 "url": scrubbed.url,
1317 "redirected": redirects > 0,
1318 "headers": scrubbed.headers,
1319 "body_base64": scrubbed.body_base64,
1320 }))
1321 }
1322
1323 #[cfg(test)]
1324 #[path = "dsh_network_tests.rs"]
1325 mod tests;
1326
1326 lines RUST