Treat Noise relay handshake failures as retryable disconnects (#65114)

## Why

A malformed reply during the Noise relay handshake could surface as a
protocol error and stop connection preparation from retrying.

## What changed

Report handshake failures as disconnects and preserve the reason when the
connection fails before it is ready. Keep authenticated registry rejections
as a distinct error that stops retries.

## Testing

Update the transport test to assert the disconnect reason for both an
unexpected WebSocket text frame and a relay stream reset.

GitOrigin-RevId: 2ad2dbcce5518dcfd35141dd234c87c0d86aa1ae
This commit is contained in:
Krish Chainani
2026-12-02 00:11:21 +00:00
committed by copyberry
parent 88eff82bd7
commit 33811295ff
2 changed files with 44 additions and 85 deletions
@@ -420,14 +420,14 @@ async fn deferred_noise_connection(early_socket: EarlySocket, early_requests: us
}
#[tokio::test]
async fn noise_handshake_distinguishes_invalid_replies_from_resets() -> Result<()> {
#[derive(Clone, Copy)]
enum Reply {
Text,
InvalidHandshake,
Reset,
}
for reply in [Reply::Text, Reply::InvalidHandshake, Reply::Reset] {
async fn noise_handshake_reports_disconnect_reason() -> Result<()> {
for (send_reset, expected_reason) in [
(
false,
"Noise relay transport expects binary protobuf frames",
),
(true, "Noise relay stream reset"),
] {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let websocket_url = format!("ws://{}", listener.local_addr()?);
let server = tokio::spawn(async move {
@@ -438,16 +438,11 @@ async fn noise_handshake_distinguishes_invalid_replies_from_resets() -> Result<(
};
let stream_id = decode_relay_message_frame(&resume)?.stream_id;
let _handshake = websocket.next().await.unwrap()?;
let response = match reply {
Reply::Text => Message::Text("untrusted text".into()),
Reply::InvalidHandshake => {
let frame = RelayMessageFrame::handshake(stream_id, vec![1]);
Message::Binary(encode_relay_message_frame(&frame).into())
}
Reply::Reset => {
let frame = RelayMessageFrame::reset(stream_id, "untrusted reason".to_string());
Message::Binary(encode_relay_message_frame(&frame).into())
}
let response = if send_reset {
let frame = RelayMessageFrame::reset(stream_id, "untrusted reason".to_string());
Message::Binary(encode_relay_message_frame(&frame).into())
} else {
Message::Text("untrusted text".into())
};
websocket.send(response).await?;
anyhow::Ok(())
@@ -463,28 +458,15 @@ async fn noise_handshake_distinguishes_invalid_replies_from_resets() -> Result<(
.await
.err()
.expect("invalid handshake response must fail");
let ExecServerError::Disconnected(reason) = error else {
anyhow::bail!("expected disconnect, got {error:?}");
};
assert_eq!(
error.is_retryable_preparation_error(),
matches!(reply, Reply::Reset)
reason,
format!(
"Noise harness handshake failed before connection became ready: {expected_reason}"
)
);
match (reply, error) {
(Reply::Text, ExecServerError::Protocol(reason)) => {
assert_eq!(
reason,
"Noise relay transport expects binary protobuf frames"
);
}
(Reply::InvalidHandshake, ExecServerError::Protocol(reason)) => {
assert!(reason.starts_with("Noise relay handshake failed"));
}
(Reply::Reset, ExecServerError::Disconnected(reason)) => {
assert_eq!(
reason,
"Noise harness handshake failed before connection became ready: Noise relay stream reset"
);
}
(_, error) => anyhow::bail!("unexpected handshake error: {error:?}"),
}
server.await??;
}
Ok(())
+24 -47
View File
@@ -124,7 +124,6 @@ where
);
let websocket_task = tokio::spawn(async move {
let mut handshake_ready_tx = Some(handshake_ready_tx);
let mut websocket = stream;
let record_handshake_failure = |reason: &'static str| {
tracing::event!(
@@ -143,14 +142,11 @@ where
);
};
// Dropping the readiness sender signals a retryable disconnect. Report
// malformed handshakes explicitly so callers stop retrying the same peer.
let mut fail_protocol = |kind, reason: String| {
// Dropping the readiness sender reports a disconnect. Only an authenticated
// registry rejection needs a distinct error to stop retries.
let fail_handshake = |kind, reason| {
record_handshake_failure(kind);
send_disconnected(&incoming_tx, &disconnected_tx, reason.clone());
if let Some(ready) = handshake_ready_tx.take() {
let _ = ready.send(Err(ExecServerError::Protocol(reason)));
}
send_disconnected(&incoming_tx, &disconnected_tx, reason);
};
// Bind the Noise transcript to the exact environment registration and
@@ -166,7 +162,7 @@ where
) {
Ok(handshake) => handshake,
Err(error) => {
fail_protocol(
fail_handshake(
"handshake_start",
format!("failed to start Noise relay handshake: {error}"),
);
@@ -200,10 +196,8 @@ where
// create a plaintext or unauthenticated application path.
let mut transport = loop {
let Some(incoming_message) = websocket.next().await else {
record_handshake_failure("websocket_ended");
send_disconnected(
&incoming_tx,
&disconnected_tx,
fail_handshake(
"websocket_ended",
"Noise relay websocket ended during handshake".to_string(),
);
return;
@@ -211,17 +205,15 @@ where
let message = match incoming_message {
Ok(Message::Binary(payload)) => payload,
Ok(Message::Close(_)) => {
record_handshake_failure("websocket_close");
send_disconnected(
&incoming_tx,
&disconnected_tx,
fail_handshake(
"websocket_close",
"Noise relay websocket received close frame during handshake".to_string(),
);
return;
}
Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_)) => continue,
Ok(Message::Text(_)) => {
fail_protocol(
fail_handshake(
"unexpected_text",
"Noise relay transport expects binary protobuf frames".to_string(),
);
@@ -229,26 +221,17 @@ where
}
Err(error) => {
let kind = websocket_read_error_reason(&error);
let reason = format!("failed to read Noise relay websocket from {connection_label}: {kind}");
match error {
WebSocketError::Io(_)
| WebSocketError::ConnectionClosed
| WebSocketError::AlreadyClosed
| WebSocketError::Protocol(
ProtocolError::ResetWithoutClosingHandshake | ProtocolError::HandshakeIncomplete,
) => {
record_handshake_failure(kind);
send_disconnected(&incoming_tx, &disconnected_tx, reason);
}
_ => fail_protocol(kind, reason),
}
fail_handshake(
kind,
format!("failed to read Noise relay websocket from {connection_label}: {kind}"),
);
return;
}
};
let frame = match decode_relay_message_frame(message.as_ref()) {
Ok(frame) => frame,
Err(error) => {
fail_protocol(
fail_handshake(
"invalid_frame",
format!("failed to parse Noise relay frame: {error}"),
);
@@ -264,7 +247,7 @@ where
let response = match frame.into_handshake_payload() {
Ok(response) => response,
Err(error) => {
fail_protocol(
fail_handshake(
"invalid_response",
format!("invalid Noise relay handshake response: {error}"),
);
@@ -284,24 +267,20 @@ where
stream_id,
"Noise harness handshake completed"
);
if let Some(handshake_ready_tx) = handshake_ready_tx.take() {
let _ = handshake_ready_tx.send(Ok(()));
}
let _ = handshake_ready_tx.send(Ok(()));
break transport;
}
Err(NoiseChannelError::RegistryAuthenticationRejected) => {
record_handshake_failure("registry_authentication_rejected");
if let Some(handshake_ready_tx) = handshake_ready_tx.take() {
let _ = handshake_ready_tx.send(Err(ExecServerError::EnvironmentRegistryAuth(
"executor credentials rejected".to_string(),
)));
}
let _ = handshake_ready_tx.send(Err(ExecServerError::EnvironmentRegistryAuth(
"executor credentials rejected".to_string(),
)));
send_disconnected(&incoming_tx, &disconnected_tx,
"environment registry rejected executor credentials".to_string());
return;
}
Err(error) => {
fail_protocol(
fail_handshake(
"handshake_finish",
format!("Noise relay handshake failed: {error}"),
);
@@ -310,10 +289,8 @@ where
}
}
Ok(RelayFrameBodyKind::Reset) => {
record_handshake_failure("relay_reset");
send_disconnected(
&incoming_tx,
&disconnected_tx,
fail_handshake(
"relay_reset",
NOISE_RELAY_RESET_DISCONNECT_REASON.to_string(),
);
return;
@@ -324,7 +301,7 @@ where
| RelayFrameBodyKind::Heartbeat,
) => {}
Ok(RelayFrameBodyKind::Data) | Err(_) => {
fail_protocol(
fail_handshake(
"unexpected_frame",
"Noise relay received data before handshake completion".to_string(),
);