fix(app-server): bind remote control pairing responses

Reject server pairing responses whose server_id or environment_id no longer match the current enrollment, and discard in-flight pairing responses after remote-control enablement changes.

Co-authored-by: Codex noreply@openai.com
This commit is contained in:
viyatb-oai
2026-06-01 11:38:05 -07:00
co-authored by Codex noreply@openai.com
parent 5630b60791
commit 8575f41cf8
4 changed files with 147 additions and 3 deletions
@@ -29,6 +29,8 @@ use std::fmt;
use std::io;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::sync::watch;
@@ -53,6 +55,7 @@ pub(super) struct QueuedServerEnvelope {
#[derive(Clone)]
pub struct RemoteControlHandle {
enabled_tx: Arc<watch::Sender<bool>>,
pairing_generation: Arc<AtomicU64>,
status_tx: Arc<watch::Sender<RemoteControlStatusChangedNotification>>,
state_db_available: bool,
server: SharedRemoteControlServer,
@@ -86,6 +89,9 @@ impl RemoteControlHandle {
*state = true;
changed
});
if enabled_changed {
self.pairing_generation.fetch_add(1, Ordering::AcqRel);
}
let status = self.status();
info!(
@@ -112,6 +118,9 @@ impl RemoteControlHandle {
*state = false;
changed
});
if enabled_changed {
self.pairing_generation.fetch_add(1, Ordering::AcqRel);
}
let status = self.status();
info!(
@@ -137,10 +146,18 @@ impl RemoteControlHandle {
&self,
params: RemoteControlPairingStartParams,
) -> io::Result<RemoteControlPairingStartResponse> {
let pairing_generation = self.pairing_generation.load(Ordering::Acquire);
if !*self.enabled_tx.borrow() {
return Err(remote_control_pairing_disabled_error());
}
self.server.start_pairing(params).await
let pairing_response = self.server.start_pairing(params).await;
if self.pairing_generation.load(Ordering::Acquire) != pairing_generation {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"remote control pairing was interrupted by remote control enablement change",
));
}
pairing_response
}
fn publish_status(
@@ -323,6 +340,7 @@ pub async fn start_remote_control(
join_handle,
RemoteControlHandle {
enabled_tx: Arc::new(enabled_tx),
pairing_generation: Arc::new(AtomicU64::new(0)),
status_tx: Arc::new(status_tx),
state_db_available,
server,
@@ -69,6 +69,44 @@ async fn remote_control_pairing_posts_server_token_and_maps_response() {
pairing_server.await.expect("pairing server should join");
}
#[tokio::test]
async fn remote_control_pairing_rejects_mismatched_enrollment_response() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let remote_control_target = remote_control_target_for_listener(&listener);
let pairing_server = tokio::spawn(async move {
let pairing_request = accept_http_request(&listener).await;
respond_with_json(
pairing_request.stream,
json!({
"pairing_code": "pairing-code",
"manual_pairing_code": null,
"server_id": "other-server-id",
"environment_id": "environment-id",
"expires_at": "3026-05-22T12:34:56Z",
}),
)
.await
});
assert_eq!(
remote_control_server_state(
OffsetDateTime::from_unix_timestamp(33_336_362_096)
.expect("future timestamp should parse"),
)
.start_pairing(
&remote_control_target,
StartRemoteControlPairingRequest { manual_code: false },
)
.await
.expect_err("pairing response should be bound to current enrollment")
.to_string(),
"remote control pairing returned mismatched enrollment: expected server_id=server-id, environment_id=environment-id; got server_id=other-server-id, environment_id=environment-id"
);
pairing_server.await.expect("pairing server should join");
}
#[tokio::test]
async fn remote_control_pairing_preserves_backend_error_context() {
let listener = TcpListener::bind("127.0.0.1:0")
@@ -355,6 +393,88 @@ async fn remote_control_auth_change_cancels_in_flight_pairing() {
);
}
#[tokio::test]
async fn remote_control_enablement_change_rejects_in_flight_pairing() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let remote_control_url = remote_control_url_for_listener(&listener);
let codex_home = TempDir::new().expect("temp dir should create");
let (transport_event_tx, _transport_event_rx) =
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
let shutdown_token = CancellationToken::new();
let (remote_task, remote_handle) = start_remote_control(
RemoteControlStartConfig {
remote_control_url,
installation_id: TEST_INSTALLATION_ID.to_string(),
},
Some(remote_control_state_runtime(&codex_home).await),
remote_control_auth_manager(),
transport_event_tx,
shutdown_token.clone(),
/*app_server_client_name_rx*/ None,
/*initial_enabled*/ true,
)
.await
.expect("remote control should start");
let enroll_request = accept_http_request(&listener).await;
respond_with_json(
enroll_request.stream,
remote_control_server_token_response(
"srv_e_initial",
"env_initial",
TEST_REMOTE_CONTROL_SERVER_TOKEN,
),
)
.await;
let stalled_websocket_request = accept_http_request(&listener).await;
assert_eq!(
stalled_websocket_request.request_line,
"GET /backend-api/wham/remote/control/server HTTP/1.1"
);
let pairing_task = tokio::spawn({
let remote_handle = remote_handle.clone();
async move {
remote_handle
.start_pairing(RemoteControlPairingStartParams::default())
.await
}
});
let stalled_pairing_request = accept_http_request(&listener).await;
assert_eq!(
stalled_pairing_request.request_line,
"POST /backend-api/wham/remote/control/server/pair HTTP/1.1"
);
remote_handle.disable();
remote_handle.enable().expect("enable should succeed");
respond_with_json(
stalled_pairing_request.stream,
json!({
"pairing_code": "stale-pairing-code",
"manual_pairing_code": null,
"server_id": "srv_e_initial",
"environment_id": "env_initial",
"expires_at": "3026-05-22T12:34:56Z",
}),
)
.await;
assert_eq!(
pairing_task
.await
.expect("pairing task should join")
.expect_err("stale pairing should be discarded")
.to_string(),
"remote control pairing was interrupted by remote control enablement change"
);
drop(stalled_websocket_request);
shutdown_token.cancel();
let _ = remote_task.await;
}
fn remote_control_target_for_listener(listener: &TcpListener) -> RemoteControlTarget {
normalize_remote_control_url(&remote_control_url_for_listener(listener))
.expect("target should parse")
@@ -48,7 +48,7 @@ pub(super) struct StartRemoteControlPairingResponse {
pub(super) pairing_code: String,
pub(super) manual_pairing_code: Option<String>,
#[serde(rename = "server_id")]
pub(super) _server_id: String,
pub(super) server_id: String,
pub(super) environment_id: String,
pub(super) expires_at: String,
}
@@ -389,10 +389,16 @@ impl RemoteControlServer {
let StartRemoteControlPairingResponse {
pairing_code,
manual_pairing_code,
_server_id: _,
server_id,
environment_id,
expires_at,
} = pairing;
if server_id != self.server_id || environment_id != self.environment_id {
return Err(io::Error::other(format!(
"remote control pairing returned mismatched enrollment: expected server_id={}, environment_id={}; got server_id={}, environment_id={}",
self.server_id, self.environment_id, server_id, environment_id
)));
}
let expires_at = OffsetDateTime::parse(&expires_at, &Rfc3339)
.map_err(|err| {
io::Error::new(