Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion kube-client/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,9 @@ impl Client {
upgrade::StreamProtocol::add_to_headers(&mut parts.headers)?;

let res = self.send(Request::from_parts(parts, Body::from(body))).await?;
let protocol = upgrade::verify_response(&res, &key).map_err(Error::UpgradeConnection)?;
let (protocol, res) = upgrade::verify_response(res, &key)
.await
.map_err(Error::UpgradeConnection)?;
match hyper::upgrade::on(res).await {
Ok(upgraded) => Ok(Connection {
stream: WebSocketStream::from_raw_socket(
Expand Down
28 changes: 22 additions & 6 deletions kube-client/src/client/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,14 @@ pub enum UpgradeConnectionError {
/// connection.
///
/// [`SWITCHING_PROTOCOLS`]: http::status::StatusCode::SWITCHING_PROTOCOLS
#[error("failed to switch protocol: {0}")]
ProtocolSwitch(http::status::StatusCode),
#[error("failed to switch protocol: {status}: {body}")]
ProtocolSwitch {
/// HTTP status code returned by the API server.
status: http::status::StatusCode,
/// Response body, typically a JSON-encoded `metav1.Status` with
/// message, reason, and details explaining the failure.
body: String,
},

/// `Upgrade` header was not set to `websocket` (case insensitive)
#[error("upgrade header was not set to websocket")]
Expand All @@ -116,9 +122,19 @@ pub enum UpgradeConnectionError {

// Verify upgrade response according to RFC6455.
// Based on `tungstenite` and added subprotocol verification.
pub fn verify_response(res: &Response<Body>, key: &str) -> Result<StreamProtocol, UpgradeConnectionError> {
pub async fn verify_response(
res: Response<Body>,
key: &str,
) -> Result<(StreamProtocol, Response<Body>), UpgradeConnectionError> {
if res.status() != StatusCode::SWITCHING_PROTOCOLS {
return Err(UpgradeConnectionError::ProtocolSwitch(res.status()));
let status = res.status();
let body = res
.into_body()
.collect_bytes()
.await
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_default();
return Err(UpgradeConnectionError::ProtocolSwitch { status, body });
}

let headers = res.headers();
Expand Down Expand Up @@ -150,10 +166,10 @@ pub fn verify_response(res: &Response<Body>, key: &str) -> Result<StreamProtocol
}

// Make sure that the server returned an expected subprotocol.
let protocol = match StreamProtocol::get_from_response(res) {
let protocol = match StreamProtocol::get_from_response(&res) {
Some(p) => p,
None => return Err(UpgradeConnectionError::SecWebSocketProtocolMismatch),
};

Ok(protocol)
Ok((protocol, res))
}
Loading