Accept inbound Noise connections in remote exec-server (#62325)

## Why

Remote Noise executors previously connected outbound to a rendezvous relay. An inbound listener lets harnesses that can reach the executor connect directly while retaining registry-backed authorization.

## What changed

Use `--listen ws://IP:PORT` with `--remote` in Noise mode to accept inbound WebSockets. The listener serves RPCs over encrypted Noise streams after the registry authorizes the harness. It limits concurrent connections and handshake attempts, closes sockets that miss the first authorization deadline, and drains connections on shutdown.

Noise clients can attach optional admission headers from the connection bundle to `wss://` requests.

## Testing

The inbound integration test exercises a registry-authorized file read, rejection of a registry-denied harness, the absence of a plaintext RPC response, and connection closure on shutdown. Unit tests cover handshake limits and rejection of admission headers before dialing a plaintext WebSocket.

GitOrigin-RevId: b388672e49a3fe806e38f6db38825435ba25d27a
This commit is contained in:
richardopenai
2026-11-18 17:55:49 +00:00
committed by copyberry
parent f2d3086682
commit c1ed51ca2c
21 changed files with 646 additions and 48 deletions
@@ -0,0 +1,81 @@
//! Listener-wide admission for inbound Noise handshakes. The budget is charged
//! before parsing a hybrid handshake and held through its ERS validation.
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use tokio::sync::Notify;
use tokio::sync::OwnedSemaphorePermit;
use tokio::sync::Semaphore;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
const MAX_CONCURRENT_HANDSHAKES: usize = 16;
const MAX_HANDSHAKES_PER_SECOND: usize = 32;
const HANDSHAKE_WINDOW: Duration = Duration::from_secs(1);
pub(crate) struct HandshakeBudget {
permits: Arc<Semaphore>,
attempts: Mutex<VecDeque<Instant>>,
}
impl Default for HandshakeBudget {
fn default() -> Self {
Self {
permits: Arc::new(Semaphore::new(MAX_CONCURRENT_HANDSHAKES)),
attempts: Mutex::new(VecDeque::new()),
}
}
}
impl HandshakeBudget {
pub(crate) fn try_admit(&self) -> Option<OwnedSemaphorePermit> {
let permit = Arc::clone(&self.permits).try_acquire_owned().ok()?;
let now = Instant::now();
let mut attempts = self
.attempts
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
while attempts
.front()
.is_some_and(|time| now.duration_since(*time) >= HANDSHAKE_WINDOW)
{
attempts.pop_front();
}
if attempts.len() >= MAX_HANDSHAKES_PER_SECOND {
return None;
}
attempts.push_back(now);
Some(permit)
}
}
#[derive(Clone)]
pub(crate) struct InboundAdmission {
pub(crate) budget: Arc<HandshakeBudget>,
pub(crate) authorized: Arc<Notify>,
pub(crate) shutdown: CancellationToken,
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn budget_bounds_concurrency_and_reconnect_rate() {
let budget = HandshakeBudget::default();
let permits = (0..MAX_CONCURRENT_HANDSHAKES)
.map(|_| budget.try_admit().unwrap())
.collect::<Vec<_>>();
assert!(budget.try_admit().is_none());
drop(permits);
for _ in MAX_CONCURRENT_HANDSHAKES..MAX_HANDSHAKES_PER_SECOND {
drop(budget.try_admit().unwrap());
}
assert!(budget.try_admit().is_none());
tokio::time::advance(HANDSHAKE_WINDOW).await;
assert!(budget.try_admit().is_some());
}
}
@@ -9,6 +9,7 @@ use std::sync::Mutex;
use tokio::sync::mpsc;
use tokio::sync::watch;
use tokio_util::task::TaskTracker;
use tracing::warn;
use crate::ExecServerError;
@@ -86,8 +87,8 @@ impl<H: NoiseStreamHandler> NoiseVirtualStream<H> {
/// The returned value is the read half; the spawned task owns outbound framing
/// and reports its instance ID on exit so stream-ID reuse is safe.
pub(crate) fn spawn_noise_virtual_stream<H: NoiseStreamHandler>(
stream_id: String,
instance_id: u64,
instance: ClosedNoiseVirtualStream,
tasks: Option<&TaskTracker>,
handler: H,
physical_outgoing_tx: mpsc::Sender<Vec<u8>>,
closed_stream_tx: mpsc::Sender<ClosedNoiseVirtualStream>,
@@ -99,9 +100,10 @@ pub(crate) fn spawn_noise_virtual_stream<H: NoiseStreamHandler>(
let (disconnected_tx, disconnected_rx) = watch::channel(false);
let transport = Arc::new(Mutex::new(transport));
let writer_transport = Arc::clone(&transport);
let owner_stream_id = stream_id.clone();
let owner_stream_id = instance.stream_id.clone();
let instance_id = instance.instance_id;
let owner_closed_stream_tx = closed_stream_tx.clone();
let writer_stream_id = stream_id;
let writer_stream_id = instance.stream_id;
let writer_task = tokio::spawn(async move {
let mut next_seq = 0u32;
'writer: while let Some(message) = outgoing_rx.recv().await {
@@ -166,7 +168,7 @@ pub(crate) fn spawn_noise_virtual_stream<H: NoiseStreamHandler>(
writer_task,
executor_registration,
};
tokio::spawn(async move {
let owner = async move {
handler.run_connection(connection).await;
let _ = owner_closed_stream_tx
.send(ClosedNoiseVirtualStream {
@@ -174,7 +176,12 @@ pub(crate) fn spawn_noise_virtual_stream<H: NoiseStreamHandler>(
instance_id,
})
.await;
});
};
if let Some(tasks) = tasks {
tasks.spawn(owner);
} else {
tokio::spawn(owner);
}
NoiseVirtualStream {
incoming_tx,
@@ -90,8 +90,11 @@ async fn processor_exit_reports_closed_virtual_stream() -> Result<()> {
let (physical_outgoing_tx, _physical_outgoing_rx) = mpsc::channel(CHANNEL_CAPACITY);
let (closed_stream_tx, mut closed_stream_rx) = mpsc::channel(1);
let mut stream = spawn_noise_virtual_stream(
"stream-1".to_string(),
/*instance_id*/ 7,
ClosedNoiseVirtualStream {
stream_id: "stream-1".to_string(),
instance_id: 7,
},
/*tasks*/ None,
ConnectionProcessor::new(ExecServerRuntimeOptions::new(
std::env::current_exe()?,
/*codex_linux_sandbox_exe*/ None,
@@ -53,8 +53,11 @@ async fn forwards_opaque_noise_payloads_and_drains_before_closing() -> Result<()
let (physical_outgoing_tx, mut physical_outgoing_rx) = mpsc::channel(1);
let (closed_stream_tx, mut closed_stream_rx) = mpsc::channel(2);
let mut stream = spawn_noise_virtual_stream(
"stream-1".to_string(),
/*instance_id*/ 7,
ClosedNoiseVirtualStream {
stream_id: "stream-1".to_string(),
instance_id: 7,
},
/*tasks*/ None,
forwarder,
physical_outgoing_tx,
closed_stream_tx,
+2 -1
View File
@@ -1,3 +1,4 @@
pub(crate) mod admission;
pub(crate) mod executor_stream;
mod harness;
pub(crate) mod message_framing;
@@ -15,7 +16,7 @@ pub(crate) const NOISE_RELAY_RESET_REASON: &str = "noise_relay_protocol_error";
// This bounds allocation in tungstenite before protobuf and Noise record
// validation run. It comfortably fits one maximum Noise record plus metadata.
const MAX_NOISE_RELAY_WEBSOCKET_MESSAGE_SIZE: usize = 256 * 1024;
pub(crate) const MAX_NOISE_RELAY_WEBSOCKET_MESSAGE_SIZE: usize = 256 * 1024;
/// Return the websocket limits required by every Noise relay endpoint.
pub(crate) fn noise_relay_websocket_config() -> WebSocketConfig {