| 339 | // `tonic::Status` is large but is the API surface of gRPC handlers. |
| 340 | #[allow(clippy::result_large_err)] |
| 341 | pub fn claim_relay( |
| 342 | &self, |
| 343 | channel_id: &str, |
| 344 | principal: Option<&Principal>, |
| 345 | ) -> Result<tokio::io::DuplexStream, Status> { |
| 346 | let pending = { |
| 347 | let mut map = self.pending_relays.lock().unwrap(); |
| 348 | let pending = map |
| 349 | .get(channel_id) |
| 350 | .ok_or_else(|| Status::not_found("unknown or expired relay channel"))?; |
| 351 | |
| 352 | if let Some(principal) = principal |
| 353 | && let Err(status) = crate::auth::guard::ensure_sandbox_principal_scope( |
| 354 | principal, |
| 355 | &pending.sandbox_id, |
| 356 | ) |
| 357 | { |
| 358 | info!( |
| 359 | channel_id = %channel_id, |
| 360 | sandbox_id = %pending.sandbox_id, |
| 361 | "relay stream: rejecting cross-sandbox claim" |
| 362 | ); |
| 363 | return Err(status); |
| 364 | } |
| 365 | |
| 366 | if pending.created_at.elapsed() > RELAY_PENDING_TIMEOUT { |
| 367 | map.remove(channel_id); |
| 368 | return Err(Status::deadline_exceeded("relay channel timed out")); |
| 369 | } |
| 370 | |
| 371 | map.remove(channel_id) |
| 372 | .expect("pending relay existed before removal") |
| 373 | }; |
| 374 | |
| 375 | // Create a duplex stream pair: one end for the gateway bridge, one for |
| 376 | // the supervisor HTTP CONNECT handler. |
| 377 | let (gateway_stream, supervisor_stream) = tokio::io::duplex(64 * 1024); |
| 378 | |
| 379 | // Send the gateway-side stream to the waiter (exec handler or forward handler). |
| 380 | if pending.sender.send(Ok(gateway_stream)).is_err() { |
| 381 | return Err(Status::internal("relay requester dropped")); |
| 382 | } |
| 383 | |
| 384 | Ok(supervisor_stream) |
| 385 | } |
| 386 | |
| 387 | /// Remove all pending relays that have exceeded the timeout. |
| 388 | pub fn reap_expired_relays(&self) { |