返回 CodeWhale
dsh_remote.rs
根目录 / crates / engine / src / extension_host / dsh_remote.rs
1 use std::collections::HashMap;
2 use std::net::IpAddr;
3 use std::sync::{Mutex, OnceLock};
4 use std::time::{Duration, Instant, SystemTime};
5
6 use codewhale_config::OwnerRef;
7 use codewhale_core::secret_eq::constant_time_eq;
8 use serde::Deserialize;
9 use serde_json::{Value, json};
10 use sha2::{Digest, Sha256};
11 use unicode_normalization::UnicodeNormalization;
12
13 use super::ExtensionHostManager;
14 use super::dsh_broker::{
15 self, BrokerCall, BrokerEffect, BrokerFuture, BrokerMethods, BrokerRefusal, decode,
16 };
17 use super::protocol::DshService;
18 use super::tier::HostTier;
19
20 const PAIRING_TTL: Duration = Duration::from_secs(10 * 60);
21 const CLIENT_TTL: Duration = Duration::from_secs(30 * 60);
22 const MAX_PENDING_PER_SESSION: usize = 4;
23 const MAX_PENDING_PER_PLUGIN: usize = 8;
24 const MAX_PENDING_TOTAL: usize = 16;
25 const MAX_GRANTS: usize = 64;
26 const MAX_LABEL_CHARS: usize = 32;
27 const LABEL_MARKS: &str = "-_.'()#+&";
28 const HOST_NAME: &str = "codewhale";
29 const GRANT_PREFIX: &str = "cwrg_";
30 const PAIRING_PREFIX: &str = "cwrp_";
31 const CLIENT_PREFIX: &str = "cwrc_";
32
33 #[derive(Deserialize)]
34 #[serde(
35 tag = "method",
36 content = "input",
37 rename_all = "snake_case",
38 deny_unknown_fields
39 )]
40 enum RemoteMethod {
41 Status {},
42 Pair {
43 #[serde(default)]
44 label: Option<String>,
45 },
46 Clients {},
47 Revoke {
48 grant: String,
49 },
50 }
51
52 impl BrokerMethods for RemoteMethod {
53 const NAMES: &'static [&'static str] = &["status", "pair", "clients", "revoke"];
54 }
55
56 #[derive(Clone)]
57 pub struct RemoteSecret(String);
58
59 impl RemoteSecret {
60 #[must_use]
61 pub fn expose(&self) -> &str {
62 &self.0
63 }
64 }
65
66 impl std::fmt::Debug for RemoteSecret {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 f.write_str("RemoteSecret(..)")
69 }
70 }
71
72 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
73 pub enum RemoteState {
74 AwaitingHost,
75 Paired,
76 }
77
78 impl RemoteState {
79 fn name(self) -> &'static str {
80 match self {
81 Self::AwaitingHost => "awaiting_host",
82 Self::Paired => "paired",
83 }
84 }
85 }
86
87 #[derive(Debug, Clone, PartialEq, Eq)]
88 pub struct RemotePairing {
89 pub grant: String,
90 pub plugin_id: String,
91 pub plugin_name: String,
92 pub session_id: String,
93 pub state: RemoteState,
94 pub plugin_label: String,
95 pub client_label: Option<String>,
96 pub expires_in_seconds: u64,
97 }
98
99 #[derive(Debug, Clone)]
100 pub struct RemoteClient {
101 pub grant: String,
102 pub session_id: String,
103 pub token: RemoteSecret,
104 pub expires_in_seconds: u64,
105 }
106
107 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
108 pub enum RemoteDenial {
109 Unknown,
110 NonLoopback,
111 ForeignSession,
112 }
113
114 #[cfg(test)]
115 thread_local! {
116 static WALL_SKEW: std::cell::Cell<Duration> = const { std::cell::Cell::new(Duration::ZERO) };
117 }
118
119 #[derive(Clone, Copy)]
120 struct Now {
121 mono: Instant,
122 wall: SystemTime,
123 }
124
125 impl Now {
126 fn read() -> Self {
127 let wall = SystemTime::now();
128 #[cfg(test)]
129 let wall = wall + WALL_SKEW.with(std::cell::Cell::get);
130 Self {
131 mono: Instant::now(),
132 wall,
133 }
134 }
135
136 fn after(self, ttl: Duration) -> Deadline {
137 Deadline {
138 mono: self.mono + ttl,
139 wall: self.wall + ttl,
140 }
141 }
142 }
143
144 #[derive(Clone, Copy)]
145 struct Deadline {
146 mono: Instant,
147 wall: SystemTime,
148 }
149
150 impl Deadline {
151 fn passed(self, now: Now) -> bool {
152 now.mono >= self.mono || now.wall >= self.wall
153 }
154
155 fn seconds_left(self, now: Now) -> u64 {
156 self.mono
157 .saturating_duration_since(now.mono)
158 .min(self.wall.duration_since(now.wall).unwrap_or_default())
159 .as_secs()
160 }
161 }
162
163 enum Stage {
164 AwaitingHost {
165 presented: Option<[u8; 32]>,
166 },
167 Paired {
168 token: [u8; 32],
169 client_label: String,
170 },
171 }
172
173 struct Grant {
174 owner: OwnerRef,
175 session_id: String,
176 label: String,
177 expires: Deadline,
178 stage: Stage,
179 }
180
181 impl Grant {
182 fn state(&self) -> RemoteState {
183 match self.stage {
184 Stage::AwaitingHost { .. } => RemoteState::AwaitingHost,
185 Stage::Paired { .. } => RemoteState::Paired,
186 }
187 }
188
189 fn held_by(&self, owner: &OwnerRef, session: &str) -> bool {
190 self.owner == *owner && self.session_id == session
191 }
192 }
193
194 type Table = HashMap<String, Grant>;
195
196 struct RemoteGrants {
197 pairing_ttl: Duration,
198 client_ttl: Duration,
199 grants: Mutex<Table>,
200 }
201
202 fn remote_grants() -> &'static RemoteGrants {
203 static GRANTS: OnceLock<RemoteGrants> = OnceLock::new();
204 GRANTS.get_or_init(|| RemoteGrants::new(PAIRING_TTL, CLIENT_TTL))
205 }
206
207 pub(super) fn serve(call: BrokerCall) -> BrokerFuture {
208 Box::pin(async move { remote_grants().serve(&call).await })
209 }
210
211 pub(super) fn withdraw_owner(owner: &OwnerRef) -> usize {
212 remote_grants().withdraw_owner(owner)
213 }
214
215 pub(crate) fn end_remote_session(session_id: &str) -> usize {
216 remote_grants().revoke_session(session_id)
217 }
218
219 fn refused(message: &str) -> BrokerRefusal {
220 BrokerRefusal::Refused {
221 service: DshService::Remote,
222 message: message.to_string(),
223 }
224 }
225
226 fn invalid(message: impl Into<String>) -> BrokerRefusal {
227 BrokerRefusal::InvalidInput {
228 service: DshService::Remote,
229 message: message.into(),
230 }
231 }
232
233 fn prune_stale_generation(grants: &mut Table, owner: &OwnerRef) -> Result<(), BrokerRefusal> {
234 if grants.values().any(|grant| {
235 grant.owner.plugin_id == owner.plugin_id && grant.owner.generation > owner.generation
236 }) {
237 return Err(refused(
238 "the remote broker serves the plugin's current activation only",
239 ));
240 }
241 grants.retain(|_, grant| grant.owner.plugin_id != owner.plugin_id || grant.owner == *owner);
242 Ok(())
243 }
244
245 fn held_grant(grants: &Table, owner: &OwnerRef, session: &str, grant: &str) -> bool {
246 well_formed(grant, GRANT_PREFIX)
247 && grants
248 .get(grant)
249 .is_some_and(|row| row.held_by(owner, session))
250 }
251
252 impl RemoteGrants {
253 fn new(pairing_ttl: Duration, client_ttl: Duration) -> Self {
254 Self {
255 pairing_ttl,
256 client_ttl,
257 grants: Mutex::new(Table::new()),
258 }
259 }
260
261 fn lock(&self) -> (std::sync::MutexGuard<'_, Table>, Now) {
262 let mut grants = self
263 .grants
264 .lock()
265 .unwrap_or_else(|poisoned| poisoned.into_inner());
266 let now = Now::read();
267 grants.retain(|_, grant| !grant.expires.passed(now));
268 (grants, now)
269 }
270
271 fn has_pairing_room(&self, grants: &Table, plugin: &str, session: &str) -> bool {
272 let pending = |counted: &dyn Fn(&Grant) -> bool| {
273 grants
274 .values()
275 .filter(|grant| grant.state() == RemoteState::AwaitingHost && counted(grant))
276 .count()
277 };
278 grants.len() < MAX_GRANTS
279 && pending(&|_| true) < MAX_PENDING_TOTAL
280 && pending(&|grant| grant.owner.plugin_id == plugin) < MAX_PENDING_PER_PLUGIN
281 && pending(&|grant| grant.owner.plugin_id == plugin && grant.session_id == session)
282 < MAX_PENDING_PER_SESSION
283 }
284
285 fn validate_pair(
286 &self,
287 grants: &Table,
288 call: &BrokerCall,
289 session: &str,
290 label: Option<&str>,
291 ) -> Result<String, BrokerRefusal> {
292 let execution = &call.context.tool().execution;
293 if execution.owner_agent_id.is_some() || execution.child_host.is_some() {
294 return Err(refused(
295 "remote pairing is offered to the main session only, not to a child agent",
296 ));
297 }
298 let label = plugin_label(label).map_err(invalid)?;
299 if !self.has_pairing_room(grants, &call.owner.plugin_id, session) {
300 return Err(refused(
301 "too many remote pairings are waiting; revoke one or try again later",
302 ));
303 }
304 Ok(label)
305 }
306
307 fn precheck(
308 &self,
309 call: &BrokerCall,
310 method: &RemoteMethod,
311 ) -> Result<(&'static str, BrokerEffect), BrokerRefusal> {
312 let owner = &call.owner;
313 if HostTier::Plugin.check_owner_id(&owner.plugin_id).is_err() {
314 return Err(refused("the remote broker serves reviewed plugins only"));
315 }
316 let session = call.session_id.as_str();
317 let (mut grants, _) = self.lock();
318 prune_stale_generation(&mut grants, owner)?;
319 match method {
320 RemoteMethod::Status {} => Ok(("status", BrokerEffect::Read)),
321 RemoteMethod::Clients {} => Ok(("clients", BrokerEffect::Read)),
322 RemoteMethod::Pair { label } => {
323 self.validate_pair(&grants, call, session, label.as_deref())?;
324 Ok(("pair", BrokerEffect::Reach))
325 }
326 RemoteMethod::Revoke { grant } => {
327 if !held_grant(&grants, owner, session, grant) {
328 return Err(invalid("no such remote grant for this plugin and session"));
329 }
330 Ok(("revoke", BrokerEffect::Write))
331 }
332 }
333 }
334
335 async fn serve(&self, call: &BrokerCall) -> Result<Value, BrokerRefusal> {
336 if call.context.cancel().is_cancelled() {
337 return Err(refused("the remote broker call was withdrawn"));
338 }
339 let method = decode::<RemoteMethod>(call)?;
340 let (method_name, effect) = self.precheck(call, &method)?;
341 call.context.act(method_name, effect, None).await?;
342 let owner = &call.owner;
343 let session = call.session_id.as_str();
344 let (mut grants, now) = self.lock();
345 prune_stale_generation(&mut grants, owner)?;
346 match method {
347 RemoteMethod::Status {} => Ok(status(&grants, owner, session)),
348 RemoteMethod::Pair { label } => {
349 self.pair(&mut grants, now, call, session, label.as_deref())
350 }
351 RemoteMethod::Clients {} => Ok(clients(&grants, now, owner, session)),
352 RemoteMethod::Revoke { grant } => {
353 if !held_grant(&grants, owner, session, &grant) {
354 return Err(invalid("no such remote grant for this plugin and session"));
355 }
356 grants.remove(&grant);
357 Ok(json!({ "grant": grant, "revoked": true }))
358 }
359 }
360 }
361
362 fn pair(
363 &self,
364 grants: &mut Table,
365 now: Now,
366 call: &BrokerCall,
367 session: &str,
368 label: Option<&str>,
369 ) -> Result<Value, BrokerRefusal> {
370 let label = self.validate_pair(grants, call, session, label)?;
371 let id = random_capability(GRANT_PREFIX);
372 grants.insert(
373 id.clone(),
374 Grant {
375 owner: call.owner.clone(),
376 session_id: session.to_string(),
377 label: label.clone(),
378 expires: now.after(self.pairing_ttl),
379 stage: Stage::AwaitingHost { presented: None },
380 },
381 );
382 Ok(json!({
383 "grant": id,
384 "label": label,
385 "state": RemoteState::AwaitingHost.name(),
386 "expires_in_seconds": self.pairing_ttl.as_secs(),
387 }))
388 }
389
390 fn rows(&self) -> Vec<(OwnerRef, RemotePairing)> {
391 let (grants, now) = self.lock();
392 let mut rows: Vec<(OwnerRef, RemotePairing)> = grants
393 .iter()
394 .map(|(id, grant)| {
395 (
396 grant.owner.clone(),
397 RemotePairing {
398 grant: id.clone(),
399 plugin_id: grant.owner.plugin_id.clone(),
400 plugin_name: String::new(),
401 session_id: grant.session_id.clone(),
402 state: grant.state(),
403 plugin_label: grant.label.clone(),
404 client_label: match &grant.stage {
405 Stage::AwaitingHost { .. } => None,
406 Stage::Paired { client_label, .. } => Some(client_label.clone()),
407 },
408 expires_in_seconds: grant.expires.seconds_left(now),
409 },
410 )
411 })
412 .collect();
413 rows.sort_by(|a, b| a.1.grant.cmp(&b.1.grant));
414 rows
415 }
416
417 fn admit(
418 &self,
419 find: impl Fn(&Table) -> Option<String>,
420 live: &dyn Fn(&OwnerRef) -> bool,
421 ) -> Result<String, RemoteDenial> {
422 let (id, owner) = {
423 let (grants, _) = self.lock();
424 let id = find(&grants).ok_or(RemoteDenial::Unknown)?;
425 let owner = grants[&id].owner.clone();
426 (id, owner)
427 };
428 if live(&owner) {
429 return Ok(id);
430 }
431 self.lock().0.remove(&id);
432 Err(RemoteDenial::Unknown)
433 }
434
435 fn present(
436 &self,
437 grant: &str,
438 live: &dyn Fn(&OwnerRef) -> bool,
439 ) -> Result<RemoteSecret, RemoteDenial> {
440 if !well_formed(grant, GRANT_PREFIX) {
441 return Err(RemoteDenial::Unknown);
442 }
443 let id = self.admit(
444 |grants| grants.contains_key(grant).then(|| grant.to_string()),
445 live,
446 )?;
447 let (mut grants, _) = self.lock();
448 let Some(Stage::AwaitingHost { presented }) = grants.get_mut(&id).map(|row| &mut row.stage)
449 else {
450 return Err(RemoteDenial::Unknown);
451 };
452 let secret = random_capability(PAIRING_PREFIX);
453 *presented = Some(digest(&secret));
454 Ok(RemoteSecret(secret))
455 }
456
457 fn redeem(
458 &self,
459 secret: &str,
460 client_label: &str,
461 peer: IpAddr,
462 live: &dyn Fn(&OwnerRef) -> bool,
463 ) -> Result<RemoteClient, RemoteDenial> {
464 if !peer.is_loopback() {
465 return Err(RemoteDenial::NonLoopback);
466 }
467 if !well_formed(secret, PAIRING_PREFIX) {
468 return Err(RemoteDenial::Unknown);
469 }
470 let wanted = digest(secret);
471 let presented = |grant: &Grant| match &grant.stage {
472 Stage::AwaitingHost {
473 presented: Some(presented),
474 } => constant_time_eq(presented, &wanted),
475 _ => false,
476 };
477 let id = self.admit(|grants| find(grants, &presented), live)?;
478 let (mut grants, now) = self.lock();
479 let Some(grant) = grants.get_mut(&id) else {
480 return Err(RemoteDenial::Unknown);
481 };
482 if !presented(grant) {
483 return Err(RemoteDenial::Unknown);
484 }
485 let token = random_capability(CLIENT_PREFIX);
486 grant.stage = Stage::Paired {
487 token: digest(&token),
488 client_label: device_label(client_label),
489 };
490 grant.expires = now.after(self.client_ttl);
491 Ok(RemoteClient {
492 grant: id,
493 session_id: grant.session_id.clone(),
494 token: RemoteSecret(token),
495 expires_in_seconds: self.client_ttl.as_secs(),
496 })
497 }
498
499 fn authorize(
500 &self,
501 token: &str,
502 session_id: &str,
503 live: &dyn Fn(&OwnerRef) -> bool,
504 ) -> Result<String, RemoteDenial> {
505 if !well_formed(token, CLIENT_PREFIX) {
506 return Err(RemoteDenial::Unknown);
507 }
508 let wanted = digest(token);
509 let paired = |grant: &Grant| match &grant.stage {
510 Stage::Paired { token, .. } => constant_time_eq(token, &wanted),
511 Stage::AwaitingHost { .. } => false,
512 };
513 let id = self.admit(|grants| find(grants, &paired), live)?;
514 let (grants, _) = self.lock();
515 let Some(grant) = grants.get(&id) else {
516 return Err(RemoteDenial::Unknown);
517 };
518 if !paired(grant) {
519 return Err(RemoteDenial::Unknown);
520 }
521 if grant.session_id != session_id {
522 return Err(RemoteDenial::ForeignSession);
523 }
524 Ok(id)
525 }
526
527 fn withdraw(&self, grant: &str) -> bool {
528 well_formed(grant, GRANT_PREFIX) && self.lock().0.remove(grant).is_some()
529 }
530
531 fn withdraw_owner(&self, owner: &OwnerRef) -> usize {
532 self.drop_where(|grant| grant.owner == *owner)
533 }
534
535 fn revoke_session(&self, session_id: &str) -> usize {
536 self.drop_where(|grant| grant.session_id == session_id)
537 }
538
539 fn drop_where(&self, gone: impl Fn(&Grant) -> bool) -> usize {
540 let (mut grants, _) = self.lock();
541 let before = grants.len();
542 grants.retain(|_, grant| !gone(grant));
543 before - grants.len()
544 }
545 }
546
547 fn status(grants: &Table, owner: &OwnerRef, session: &str) -> Value {
548 let count = |state: RemoteState| {
549 grants
550 .values()
551 .filter(|grant| grant.held_by(owner, session) && grant.state() == state)
552 .count()
553 };
554 json!({
555 "transport": "runtime_http_sse",
556 "pairing": "host_presented",
557 "public_listener": false,
558 "tunnel": false,
559 "awaiting_host": count(RemoteState::AwaitingHost),
560 "paired": count(RemoteState::Paired),
561 "max_pending": MAX_PENDING_PER_SESSION,
562 })
563 }
564
565 fn clients(grants: &Table, now: Now, owner: &OwnerRef, session: &str) -> Value {
566 let mut rows: Vec<Value> = grants
567 .iter()
568 .filter(|(_, grant)| grant.held_by(owner, session))
569 .map(|(id, grant)| {
570 json!({
571 "grant": id,
572 "label": grant.label,
573 "state": grant.state().name(),
574 "expires_in_seconds": grant.expires.seconds_left(now),
575 })
576 })
577 .collect();
578 rows.sort_by(|a, b| a["grant"].as_str().cmp(&b["grant"].as_str()));
579 json!({ "clients": rows })
580 }
581
582 fn find(grants: &Table, matches: &dyn Fn(&Grant) -> bool) -> Option<String> {
583 let mut found = None;
584 for (id, grant) in grants {
585 if matches(grant) {
586 found = Some(id.clone());
587 }
588 }
589 found
590 }
591
592 impl ExtensionHostManager {
593 fn remote_owner_is_live(&self, owner: &OwnerRef) -> bool {
594 let registry = self.shared.registry.lock().expect("registry lock");
595 registry.tier_of(owner) == Some(HostTier::Plugin)
596 && dsh_broker::granted(&registry, owner, DshService::Remote)
597 }
598
599 #[must_use]
600 pub fn remote_pairings(&self) -> Vec<RemotePairing> {
601 let rows = remote_grants().rows();
602 let registry = self.shared.registry.lock().expect("registry lock");
603 rows.into_iter()
604 .filter_map(|(owner, mut row)| {
605 let entry = registry.owner(&owner.plugin_id).filter(|entry| {
606 entry.owner == owner
607 && registry.tier_of(&owner) == Some(HostTier::Plugin)
608 && dsh_broker::granted(&registry, &owner, DshService::Remote)
609 })?;
610 row.plugin_name.clone_from(&entry.plugin_name);
611 Some(row)
612 })
613 .collect()
614 }
615
616 pub fn present_remote_pairing(&self, grant: &str) -> Result<RemoteSecret, RemoteDenial> {
617 remote_grants().present(grant, &|owner| self.remote_owner_is_live(owner))
618 }
619
620 pub fn redeem_remote_pairing(
621 &self,
622 secret: &str,
623 client_label: &str,
624 peer: IpAddr,
625 ) -> Result<RemoteClient, RemoteDenial> {
626 remote_grants().redeem(secret, client_label, peer, &|owner| {
627 self.remote_owner_is_live(owner)
628 })
629 }
630
631 pub fn authorize_remote_client(
632 &self,
633 token: &str,
634 session_id: &str,
635 ) -> Result<String, RemoteDenial> {
636 remote_grants().authorize(token, session_id, &|owner| self.remote_owner_is_live(owner))
637 }
638
639 pub fn withdraw_remote_grant(&self, grant: &str) -> bool {
640 remote_grants().withdraw(grant)
641 }
642 }
643
644 fn label_char(ch: char) -> bool {
645 ch.is_alphanumeric() || ch == ' ' || LABEL_MARKS.contains(ch)
646 }
647
648 fn names_the_host(label: &str) -> bool {
649 label
650 .chars()
651 .filter(|ch| ch.is_alphanumeric())
652 .flat_map(char::to_lowercase)
653 .collect::<String>()
654 .contains(HOST_NAME)
655 }
656
657 fn plugin_label(label: Option<&str>) -> Result<String, String> {
658 let label: String = label.unwrap_or("").trim().nfkc().collect();
659 if label.chars().count() > MAX_LABEL_CHARS {
660 return Err(format!(
661 "a remote label is at most {MAX_LABEL_CHARS} characters"
662 ));
663 }
664 if !label.chars().all(label_char) || label.contains(" ") {
665 return Err(format!(
666 "a remote label holds letters, digits, single spaces and {LABEL_MARKS} only"
667 ));
668 }
669 if names_the_host(&label) {
670 return Err("a remote label may not name the host".into());
671 }
672 Ok(label)
673 }
674
675 fn device_label(label: &str) -> String {
676 let mut cleaned = String::new();
677 for ch in label.nfkc().filter(|ch| label_char(*ch)) {
678 if ch == ' ' && (cleaned.is_empty() || cleaned.ends_with(' ')) {
679 continue;
680 }
681 if cleaned.chars().count() == MAX_LABEL_CHARS {
682 break;
683 }
684 cleaned.push(ch);
685 }
686 let cleaned = cleaned.trim_end();
687 if names_the_host(cleaned) {
688 String::new()
689 } else {
690 cleaned.to_string()
691 }
692 }
693
694 fn well_formed(value: &str, prefix: &str) -> bool {
695 value.strip_prefix(prefix).is_some_and(|random| {
696 random.len() == 64 && random.bytes().all(|byte| byte.is_ascii_hexdigit())
697 })
698 }
699
700 fn digest(secret: &str) -> [u8; 32] {
701 Sha256::digest(secret.as_bytes()).into()
702 }
703
704 fn random_capability(prefix: &str) -> String {
705 format!(
706 "{prefix}{}{}",
707 uuid::Uuid::new_v4().simple(),
708 uuid::Uuid::new_v4().simple()
709 )
710 }
711
712 #[cfg(test)]
713 mod tests;
714
714 lines RUST