diff --git a/pr/3331/docs/iroh_relay/client/enum.RecvError.html b/pr/3331/docs/iroh_relay/client/enum.RecvError.html index 38efcbf209..9f659ea6dd 100644 --- a/pr/3331/docs/iroh_relay/client/enum.RecvError.html +++ b/pr/3331/docs/iroh_relay/client/enum.RecvError.html @@ -1,4 +1,4 @@ -RecvError in iroh_relay::client - Rust

Enum RecvError

Source
#[non_exhaustive]
pub enum RecvError { +RecvError in iroh_relay::client - Rust

Enum RecvError

Source
#[non_exhaustive]
pub enum RecvError { Protocol { source: Error, backtrace: Option<Backtrace>, @@ -10,11 +10,11 @@ span_trace: SpanTrace, }, }
Expand description

Errors when receiving messages from the relay server.

-

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Protocol

Fields

§source: Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

StreamError

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for RecvError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for RecvError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for RecvError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for RecvError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Protocol

Fields

§source: Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

StreamError

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for RecvError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for RecvError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for RecvError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for RecvError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Error> for RecvError

Source§

fn from(error: RecvRelayError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Error> for RecvError

Source§

fn from(error: RecvRelayError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3331/docs/iroh_relay/client/enum.SendError.html b/pr/3331/docs/iroh_relay/client/enum.SendError.html index 3005039e23..ef762bbaeb 100644 --- a/pr/3331/docs/iroh_relay/client/enum.SendError.html +++ b/pr/3331/docs/iroh_relay/client/enum.SendError.html @@ -1,4 +1,4 @@ -SendError in iroh_relay::client - Rust

Enum SendError

Source
#[non_exhaustive]
pub enum SendError { +SendError in iroh_relay::client - Rust

Enum SendError

Source
#[non_exhaustive]
pub enum SendError { StreamError { source: Error, backtrace: Option<Backtrace>, @@ -10,11 +10,11 @@ span_trace: SpanTrace, }, }
Expand description

Error for sending messages to the relay server.

-

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

StreamError

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ExceedsMaxPacketSize

Fields

§size: usize
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for SendError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for SendError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for SendError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for SendError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

StreamError

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ExceedsMaxPacketSize

Fields

§size: usize
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for SendError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for SendError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for SendError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for SendError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3331/docs/iroh_relay/index.html b/pr/3331/docs/iroh_relay/index.html index 34d10ce6e9..1201855850 100644 --- a/pr/3331/docs/iroh_relay/index.html +++ b/pr/3331/docs/iroh_relay/index.html @@ -1,4 +1,4 @@ -iroh_relay - Rust

Crate iroh_relay

Source
Expand description

Iroh’s relay is a feature within iroh, a peer-to-peer +iroh_relay - Rust

Crate iroh_relay

Source
Expand description

Iroh’s relay is a feature within iroh, a peer-to-peer networking system designed to facilitate direct, encrypted connections between devices. Iroh aims to simplify decentralized communication by automatically handling connections through “relays” when direct connections aren’t immediately possible. The relay server helps establish diff --git a/pr/3331/docs/iroh_relay/protos/handshake/enum.Error.html b/pr/3331/docs/iroh_relay/protos/handshake/enum.Error.html index 3187eebf0c..e4e2e031f8 100644 --- a/pr/3331/docs/iroh_relay/protos/handshake/enum.Error.html +++ b/pr/3331/docs/iroh_relay/protos/handshake/enum.Error.html @@ -1,4 +1,4 @@ -Error in iroh_relay::protos::handshake - Rust

Enum Error

Source
#[non_exhaustive]
pub enum Error { +Error in iroh_relay::protos::handshake - Rust

Enum Error

Source
#[non_exhaustive]
pub enum Error { Websocket { source: Error, backtrace: Option<Backtrace>, @@ -36,11 +36,11 @@ span_trace: SpanTrace, }, }

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Websocket

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Timeout

Fields

§source: Elapsed
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

UnexpectedEnd

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ServerDeniedAuth

Fields

§reason: String
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

UnexpectedFrameType

Fields

§frame_type: FrameType
§expected_types: Vec<FrameType>
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

DeserializationError

Fields

§frame_type: FrameType
§source: Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ClientAuthHeaderInvalid

Available on crate feature server only.

Failed to deserialize client auth header

-

Fields

§value: HeaderValue
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for Error

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +

Fields

§value: HeaderValue
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for Error

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Error> for ConnectError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Error> for ConnectError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3331/docs/iroh_relay/protos/handshake/index.html b/pr/3331/docs/iroh_relay/protos/handshake/index.html index 09384e95bb..3113bb6b22 100644 --- a/pr/3331/docs/iroh_relay/protos/handshake/index.html +++ b/pr/3331/docs/iroh_relay/protos/handshake/index.html @@ -1,2 +1,2 @@ -iroh_relay::protos::handshake - Rust

Module handshake

Source
Expand description

TODO(matheus23) docs

+iroh_relay::protos::handshake - Rust

Module handshake

Source
Expand description

TODO(matheus23) docs

Enums§

Error
\ No newline at end of file diff --git a/pr/3331/docs/iroh_relay/protos/send_recv/enum.Error.html b/pr/3331/docs/iroh_relay/protos/send_recv/enum.Error.html index 4926ff8a00..31590bc216 100644 --- a/pr/3331/docs/iroh_relay/protos/send_recv/enum.Error.html +++ b/pr/3331/docs/iroh_relay/protos/send_recv/enum.Error.html @@ -48,7 +48,7 @@ Self: Debug + Display,
Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for Error

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Elapsed> for Error

Source§

fn from(error: Elapsed) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: RecvRelayError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Elapsed> for Error

Source§

fn from(error: Elapsed) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: RecvRelayError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3331/docs/src/iroh_relay/client/conn.rs.html b/pr/3331/docs/src/iroh_relay/client/conn.rs.html index f417b227f2..2f512e708d 100644 --- a/pr/3331/docs/src/iroh_relay/client/conn.rs.html +++ b/pr/3331/docs/src/iroh_relay/client/conn.rs.html @@ -7,162 +7,161 @@ 7 task::{ready, Context, Poll}, 8}; 9 -10#[cfg(not(wasm_browser))] -11use bytes::BytesMut; -12use iroh_base::SecretKey; -13use n0_future::{Sink, Stream}; -14use nested_enum_utils::common_fields; -15use snafu::{Backtrace, Snafu}; -16use tracing::debug; -17 -18use super::KeyCache; -19#[cfg(not(wasm_browser))] -20use crate::client::streams::{MaybeTlsStream, ProxyStream}; -21use crate::{ -22 protos::{ -23 handshake, -24 send_recv::{ -25 ClientToServerMsg, Error as RecvRelayError, ServerToClientMsg, MAX_PAYLOAD_SIZE, -26 }, -27 streams::WsBytesFramed, -28 }, -29 MAX_PACKET_SIZE, -30}; -31 -32/// Error for sending messages to the relay server. -33#[common_fields({ -34 backtrace: Option<Backtrace>, -35 #[snafu(implicit)] -36 span_trace: n0_snafu::SpanTrace, -37})] -38#[allow(missing_docs)] -39#[derive(Debug, Snafu)] -40#[non_exhaustive] -41pub enum SendError { -42 #[snafu(transparent)] -43 StreamError { -44 #[cfg(not(wasm_browser))] -45 source: tokio_websockets::Error, -46 #[cfg(wasm_browser)] -47 source: ws_stream_wasm::WsErr, -48 }, -49 #[snafu(display("Exceeds max packet size ({MAX_PACKET_SIZE}): {size}"))] -50 ExceedsMaxPacketSize { size: usize }, -51} -52 -53/// Errors when receiving messages from the relay server. -54#[common_fields({ -55 backtrace: Option<Backtrace>, -56 #[snafu(implicit)] -57 span_trace: n0_snafu::SpanTrace, -58})] -59#[allow(missing_docs)] -60#[derive(Debug, Snafu)] -61#[non_exhaustive] -62pub enum RecvError { -63 #[snafu(transparent)] -64 Protocol { source: RecvRelayError }, -65 #[snafu(transparent)] -66 StreamError { -67 #[cfg(not(wasm_browser))] -68 source: tokio_websockets::Error, -69 #[cfg(wasm_browser)] -70 source: ws_stream_wasm::WsErr, -71 }, -72} -73 -74/// A connection to a relay server. -75/// -76/// This holds a connection to a relay server. It is: -77/// -78/// - A [`Stream`] for [`ServerToClientMsg`] to receive from the server. -79/// - A [`Sink`] for [`ClientToServerMsg`] to send to the server. -80#[derive(derive_more::Debug)] -81pub(crate) struct Conn { -82 #[debug("tokio_websockets::WebSocketStream")] -83 #[cfg(not(wasm_browser))] -84 pub(crate) conn: WsBytesFramed<MaybeTlsStream<ProxyStream>>, -85 #[debug("ws_stream_wasm::WsStream")] -86 #[cfg(wasm_browser)] -87 pub(crate) conn: WsBytesFramed, -88 pub(crate) key_cache: KeyCache, -89} -90 -91impl Conn { -92 #[cfg(test)] -93 pub(crate) fn test(io: tokio::io::DuplexStream) -> Self { -94 use crate::protos::send_recv::MAX_FRAME_SIZE; -95 Self { -96 conn: WsBytesFramed { -97 io: tokio_websockets::ClientBuilder::new() -98 .limits( -99 tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE)), -100 ) -101 .take_over(MaybeTlsStream::Test(io)), -102 }, -103 key_cache: KeyCache::test(), -104 } -105 } -106 -107 /// Constructs a new websocket connection, including the initial server handshake. -108 pub(crate) async fn new( -109 #[cfg(not(wasm_browser))] io: tokio_websockets::WebSocketStream< -110 MaybeTlsStream<ProxyStream>, -111 >, -112 #[cfg(wasm_browser)] io: ws_stream_wasm::WsStream, -113 key_cache: KeyCache, -114 secret_key: &SecretKey, -115 ) -> Result<Self, handshake::Error> { -116 let mut conn = WsBytesFramed { io }; -117 -118 // exchange information with the server -119 debug!("server_handshake: started"); -120 handshake::clientside(&mut conn, secret_key).await?; -121 debug!("server_handshake: done"); -122 -123 Ok(Self { conn, key_cache }) -124 } -125} -126 -127impl Stream for Conn { -128 type Item = Result<ServerToClientMsg, RecvError>; -129 -130 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { -131 let msg = ready!(Pin::new(&mut self.conn).poll_next(cx)); -132 match msg { -133 Some(Ok(msg)) => { -134 let message = ServerToClientMsg::from_bytes(msg, &self.key_cache); -135 Poll::Ready(Some(message.map_err(Into::into))) -136 } -137 Some(Err(e)) => Poll::Ready(Some(Err(e.into()))), -138 None => Poll::Ready(None), -139 } -140 } -141} -142 -143impl Sink<ClientToServerMsg> for Conn { -144 type Error = SendError; -145 -146 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -147 Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into) -148 } -149 -150 fn start_send(mut self: Pin<&mut Self>, frame: ClientToServerMsg) -> Result<(), Self::Error> { -151 if let ClientToServerMsg::SendDatagrams { datagrams, .. } = &frame { -152 let size = datagrams.contents.len(); -153 snafu::ensure!(size <= MAX_PAYLOAD_SIZE, ExceedsMaxPacketSizeSnafu { size }); -154 } -155 -156 Pin::new(&mut self.conn) -157 .start_send(frame.write_to(BytesMut::new()).freeze()) -158 .map_err(Into::into) -159 } -160 -161 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -162 Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into) -163 } -164 -165 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -166 Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into) -167 } -168}
\ No newline at end of file +10use bytes::BytesMut; +11use iroh_base::SecretKey; +12use n0_future::{Sink, Stream}; +13use nested_enum_utils::common_fields; +14use snafu::{Backtrace, Snafu}; +15use tracing::debug; +16 +17use super::KeyCache; +18#[cfg(not(wasm_browser))] +19use crate::client::streams::{MaybeTlsStream, ProxyStream}; +20use crate::{ +21 protos::{ +22 handshake, +23 send_recv::{ +24 ClientToServerMsg, Error as RecvRelayError, ServerToClientMsg, MAX_PAYLOAD_SIZE, +25 }, +26 streams::WsBytesFramed, +27 }, +28 MAX_PACKET_SIZE, +29}; +30 +31/// Error for sending messages to the relay server. +32#[common_fields({ +33 backtrace: Option<Backtrace>, +34 #[snafu(implicit)] +35 span_trace: n0_snafu::SpanTrace, +36})] +37#[allow(missing_docs)] +38#[derive(Debug, Snafu)] +39#[non_exhaustive] +40pub enum SendError { +41 #[snafu(transparent)] +42 StreamError { +43 #[cfg(not(wasm_browser))] +44 source: tokio_websockets::Error, +45 #[cfg(wasm_browser)] +46 source: ws_stream_wasm::WsErr, +47 }, +48 #[snafu(display("Exceeds max packet size ({MAX_PACKET_SIZE}): {size}"))] +49 ExceedsMaxPacketSize { size: usize }, +50} +51 +52/// Errors when receiving messages from the relay server. +53#[common_fields({ +54 backtrace: Option<Backtrace>, +55 #[snafu(implicit)] +56 span_trace: n0_snafu::SpanTrace, +57})] +58#[allow(missing_docs)] +59#[derive(Debug, Snafu)] +60#[non_exhaustive] +61pub enum RecvError { +62 #[snafu(transparent)] +63 Protocol { source: RecvRelayError }, +64 #[snafu(transparent)] +65 StreamError { +66 #[cfg(not(wasm_browser))] +67 source: tokio_websockets::Error, +68 #[cfg(wasm_browser)] +69 source: ws_stream_wasm::WsErr, +70 }, +71} +72 +73/// A connection to a relay server. +74/// +75/// This holds a connection to a relay server. It is: +76/// +77/// - A [`Stream`] for [`ServerToClientMsg`] to receive from the server. +78/// - A [`Sink`] for [`ClientToServerMsg`] to send to the server. +79#[derive(derive_more::Debug)] +80pub(crate) struct Conn { +81 #[debug("tokio_websockets::WebSocketStream")] +82 #[cfg(not(wasm_browser))] +83 pub(crate) conn: WsBytesFramed<MaybeTlsStream<ProxyStream>>, +84 #[debug("ws_stream_wasm::WsStream")] +85 #[cfg(wasm_browser)] +86 pub(crate) conn: WsBytesFramed, +87 pub(crate) key_cache: KeyCache, +88} +89 +90impl Conn { +91 #[cfg(test)] +92 pub(crate) fn test(io: tokio::io::DuplexStream) -> Self { +93 use crate::protos::send_recv::MAX_FRAME_SIZE; +94 Self { +95 conn: WsBytesFramed { +96 io: tokio_websockets::ClientBuilder::new() +97 .limits( +98 tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE)), +99 ) +100 .take_over(MaybeTlsStream::Test(io)), +101 }, +102 key_cache: KeyCache::test(), +103 } +104 } +105 +106 /// Constructs a new websocket connection, including the initial server handshake. +107 pub(crate) async fn new( +108 #[cfg(not(wasm_browser))] io: tokio_websockets::WebSocketStream< +109 MaybeTlsStream<ProxyStream>, +110 >, +111 #[cfg(wasm_browser)] io: ws_stream_wasm::WsStream, +112 key_cache: KeyCache, +113 secret_key: &SecretKey, +114 ) -> Result<Self, handshake::Error> { +115 let mut conn = WsBytesFramed { io }; +116 +117 // exchange information with the server +118 debug!("server_handshake: started"); +119 handshake::clientside(&mut conn, secret_key).await?; +120 debug!("server_handshake: done"); +121 +122 Ok(Self { conn, key_cache }) +123 } +124} +125 +126impl Stream for Conn { +127 type Item = Result<ServerToClientMsg, RecvError>; +128 +129 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { +130 let msg = ready!(Pin::new(&mut self.conn).poll_next(cx)); +131 match msg { +132 Some(Ok(msg)) => { +133 let message = ServerToClientMsg::from_bytes(msg, &self.key_cache); +134 Poll::Ready(Some(message.map_err(Into::into))) +135 } +136 Some(Err(e)) => Poll::Ready(Some(Err(e.into()))), +137 None => Poll::Ready(None), +138 } +139 } +140} +141 +142impl Sink<ClientToServerMsg> for Conn { +143 type Error = SendError; +144 +145 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +146 Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into) +147 } +148 +149 fn start_send(mut self: Pin<&mut Self>, frame: ClientToServerMsg) -> Result<(), Self::Error> { +150 if let ClientToServerMsg::SendDatagrams { datagrams, .. } = &frame { +151 let size = datagrams.contents.len(); +152 snafu::ensure!(size <= MAX_PAYLOAD_SIZE, ExceedsMaxPacketSizeSnafu { size }); +153 } +154 +155 Pin::new(&mut self.conn) +156 .start_send(frame.write_to(BytesMut::new()).freeze()) +157 .map_err(Into::into) +158 } +159 +160 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +161 Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into) +162 } +163 +164 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +165 Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into) +166 } +167}
\ No newline at end of file diff --git a/pr/3331/docs/src/iroh_relay/lib.rs.html b/pr/3331/docs/src/iroh_relay/lib.rs.html index f9b9bf9057..3951040745 100644 --- a/pr/3331/docs/src/iroh_relay/lib.rs.html +++ b/pr/3331/docs/src/iroh_relay/lib.rs.html @@ -56,10 +56,11 @@ 56}; 57 58pub(crate) trait ExportKeyingMaterial { -59 fn export_keying_material<T: AsMut<[u8]>>( -60 &self, -61 output: T, -62 label: &[u8], -63 context: Option<&[u8]>, -64 ) -> Option<T>; -65}
\ No newline at end of file +59 #[cfg_attr(wasm_browser, allow(unused))] +60 fn export_keying_material<T: AsMut<[u8]>>( +61 &self, +62 output: T, +63 label: &[u8], +64 context: Option<&[u8]>, +65 ) -> Option<T>; +66} \ No newline at end of file diff --git a/pr/3331/docs/src/iroh_relay/protos/handshake.rs.html b/pr/3331/docs/src/iroh_relay/protos/handshake.rs.html index dfc7e198f5..bc800ff18d 100644 --- a/pr/3331/docs/src/iroh_relay/protos/handshake.rs.html +++ b/pr/3331/docs/src/iroh_relay/protos/handshake.rs.html @@ -19,666 +19,668 @@ 19/// Authentication message from the client. 20#[derive(derive_more::Debug, serde::Serialize)] 21#[cfg_attr(feature = "server", derive(serde::Deserialize))] -22pub(crate) struct KeyMaterialClientAuth { -23 /// The client's public key -24 pub(crate) public_key: PublicKey, -25 /// A signature of (a hash of) extracted key material. -26 #[serde(with = "serde_bytes")] -27 pub(crate) signature: [u8; 64], -28 /// Part of the extracted key material. -29 /// -30 /// Allows making sure we have the same underlying key material. -31 pub(crate) key_material_suffix: [u8; 16], -32} -33 -34/// A challenge for the client to sign with their secret key for NodeId authentication. -35#[derive(derive_more::Debug, serde::Deserialize)] -36#[cfg_attr(feature = "server", derive(serde::Serialize))] -37pub(crate) struct ServerChallenge { -38 /// The challenge to sign. -39 /// Must be randomly generated with an RNG that is safe to use for crypto. -40 pub(crate) challenge: [u8; 16], -41} -42 -43/// Authentication message from the client. -44/// -45/// Used when authentication via [`KeyMaterialClientAuth`] didn't work. -46#[derive(derive_more::Debug, serde::Serialize)] -47#[cfg_attr(feature = "server", derive(serde::Deserialize))] -48pub(crate) struct ClientAuth { -49 /// The client's public key, a.k.a. the `NodeId` -50 pub(crate) public_key: PublicKey, -51 /// A signature of (a hash of) the [`ServerChallenge`]. -52 /// -53 /// This is what provides the authentication. -54 #[serde(with = "serde_bytes")] -55 pub(crate) signature: [u8; 64], -56} -57 -58/// Confirmation of successful connection. -59#[derive(derive_more::Debug, serde::Deserialize)] -60#[cfg_attr(feature = "server", derive(serde::Serialize))] -61pub(crate) struct ServerConfirmsAuth; -62 -63/// Denial of connection. The client couldn't be verified as authentic. -64#[derive(derive_more::Debug, Clone, serde::Deserialize)] -65#[cfg_attr(feature = "server", derive(serde::Serialize))] -66pub(crate) struct ServerDeniesAuth { -67 reason: String, -68} -69 -70/// Trait for getting the frame type tag for a frame. -71/// -72/// Used only in the handshake, as the frame we expect next -73/// is fairly stateful. -74/// Not used in the send/recv protocol, as any frame is -75/// allowed to happen at any time there. -76trait Frame { -77 /// The frame type this frame is identified by and prefixed with -78 const TAG: FrameType; -79} -80 -81impl<T: Frame> Frame for &T { -82 const TAG: FrameType = T::TAG; -83} -84 -85impl Frame for ServerChallenge { -86 const TAG: FrameType = FrameType::ServerChallenge; -87} -88 -89impl Frame for ClientAuth { -90 const TAG: FrameType = FrameType::ClientAuth; -91} -92 -93impl Frame for ServerConfirmsAuth { -94 const TAG: FrameType = FrameType::ServerConfirmsAuth; -95} -96 -97impl Frame for ServerDeniesAuth { -98 const TAG: FrameType = FrameType::ServerDeniesAuth; -99} -100 -101#[common_fields({ -102 backtrace: Option<Backtrace>, -103 #[snafu(implicit)] -104 span_trace: n0_snafu::SpanTrace, -105})] -106#[allow(missing_docs)] -107#[derive(Debug, Snafu)] -108#[non_exhaustive] -109pub enum Error { -110 #[snafu(transparent)] -111 Websocket { -112 #[cfg(not(wasm_browser))] -113 source: tokio_websockets::Error, -114 #[cfg(wasm_browser)] -115 source: ws_stream_wasm::WsErr, -116 }, -117 #[snafu(display("Handshake timeout reached"))] -118 Timeout { source: Elapsed }, -119 #[snafu(display("Handshake stream ended prematurely"))] -120 UnexpectedEnd {}, -121 #[snafu(display("The relay denied our authentication ({reason})"))] -122 ServerDeniedAuth { reason: String }, -123 #[snafu(display("Unexpected tag, got {frame_type}, but expected one of {expected_types:?}"))] -124 UnexpectedFrameType { -125 frame_type: FrameType, -126 expected_types: Vec<FrameType>, -127 }, -128 #[snafu(display("Handshake failed while deserializing {frame_type} frame"))] -129 DeserializationError { -130 frame_type: FrameType, -131 source: postcard::Error, -132 }, -133 #[cfg(feature = "server")] -134 /// Failed to deserialize client auth header -135 ClientAuthHeaderInvalid { value: HeaderValue }, -136} -137 -138impl ServerChallenge { -139 /// TODO(matheus23): docs -140 #[cfg(feature = "server")] -141 pub(crate) fn new(mut rng: impl RngCore + CryptoRng) -> Self { -142 let mut challenge = [0u8; 16]; -143 rng.fill_bytes(&mut challenge); -144 Self { challenge } -145 } -146 -147 fn message_to_sign(&self) -> [u8; 32] { -148 blake3::derive_key( -149 "iroh-relay handshake v1 challenge signature", -150 &self.challenge, -151 ) -152 } -153} -154 -155impl ClientAuth { -156 /// TODO(matheus23): docs -157 pub(crate) fn new(secret_key: &SecretKey, challenge: &ServerChallenge) -> Self { -158 Self { -159 public_key: secret_key.public(), -160 signature: secret_key.sign(&challenge.message_to_sign()).to_bytes(), -161 } -162 } -163 -164 /// TODO(matheus23): docs -165 #[cfg(feature = "server")] -166 pub(crate) fn verify(&self, challenge: &ServerChallenge) -> bool { -167 self.public_key -168 .verify( -169 &challenge.message_to_sign(), -170 &Signature::from_bytes(&self.signature), -171 ) -172 .is_ok() -173 } -174} -175 -176impl KeyMaterialClientAuth { -177 pub(crate) fn new(secret_key: &SecretKey, io: &impl ExportKeyingMaterial) -> Option<Self> { -178 let public_key = secret_key.public(); -179 let key_material = io.export_keying_material( -180 [0u8; 32], -181 b"iroh-relay handshake v1", -182 Some(secret_key.public().as_bytes()), -183 )?; -184 Some(Self { -185 public_key, -186 signature: secret_key.sign(&key_material[..16]).to_bytes(), -187 key_material_suffix: key_material[16..].try_into().expect("split right"), -188 }) -189 } -190 -191 pub(crate) fn into_header_value(self) -> HeaderValue { -192 HeaderValue::from_str( -193 &data_encoding::BASE64URL_NOPAD -194 .encode(&postcard::to_allocvec(&self).expect("encoding never fails")), -195 ) -196 .expect("BASE64URL_NOPAD encoding contained invisible ascii characters") -197 } -198 -199 #[cfg(feature = "server")] -200 pub(crate) fn verify(&self, io: &impl ExportKeyingMaterial) -> bool { -201 let Some(key_material) = io.export_keying_material( -202 [0u8; 32], -203 b"iroh-relay handshake v1", -204 Some(self.public_key.as_bytes()), -205 ) else { -206 return false; -207 }; -208 -209 key_material[16..] == self.key_material_suffix -210 && self -211 .public_key -212 .verify(&key_material[..16], &Signature::from_bytes(&self.signature)) -213 .is_ok() -214 } -215} -216 -217/// TODO(matheus23) docs -218pub(crate) async fn clientside( -219 io: &mut (impl BytesStreamSink + ExportKeyingMaterial), -220 secret_key: &SecretKey, -221) -> Result<ServerConfirmsAuth, Error> { -222 let (tag, frame) = read_frame( -223 io, -224 &[ServerChallenge::TAG, ServerConfirmsAuth::TAG], -225 time::Duration::from_secs(30), -226 ) -227 .await?; -228 -229 let (tag, frame) = if tag == ServerChallenge::TAG { -230 let challenge: ServerChallenge = deserialize_frame(frame)?; -231 -232 let client_info = ClientAuth::new(secret_key, &challenge); -233 write_frame(io, client_info).await?; -234 -235 read_frame( -236 io, -237 &[ServerConfirmsAuth::TAG, ServerDeniesAuth::TAG], -238 time::Duration::from_secs(30), -239 ) -240 .await? -241 } else { -242 (tag, frame) -243 }; -244 -245 match tag { -246 FrameType::ServerConfirmsAuth => { -247 let confirmation: ServerConfirmsAuth = deserialize_frame(frame)?; -248 Ok(confirmation) -249 } -250 FrameType::ServerDeniesAuth => { -251 let denial: ServerDeniesAuth = deserialize_frame(frame)?; -252 Err(ServerDeniedAuthSnafu { -253 reason: denial.reason, -254 } -255 .build()) -256 } -257 _ => unreachable!(), -258 } -259} -260 -261#[cfg(feature = "server")] -262#[derive(Debug)] -263pub(crate) struct SuccessfulAuthentication { -264 pub(crate) client_key: PublicKey, -265 pub(crate) mechanism: Mechanism, -266} -267 -268#[cfg(feature = "server")] -269#[derive(Debug, Clone, Copy, PartialEq, Eq)] -270pub(crate) enum Mechanism { -271 SignedChallenge, -272 SignedKeyMaterial, -273} -274 -275/// TODO(matheus23) docs -276#[cfg(feature = "server")] -277pub(crate) async fn serverside( -278 io: &mut (impl BytesStreamSink + ExportKeyingMaterial), -279 client_auth_header: Option<HeaderValue>, -280 rng: impl RngCore + CryptoRng, -281) -> Result<SuccessfulAuthentication, Error> { -282 if let Some(client_auth_header) = client_auth_header { -283 let client_auth_bytes = data_encoding::BASE64URL_NOPAD -284 .decode(client_auth_header.as_ref()) -285 .map_err(|_| { -286 ClientAuthHeaderInvalidSnafu { -287 value: client_auth_header.clone(), -288 } -289 .build() -290 })?; -291 -292 let client_auth: KeyMaterialClientAuth = -293 postcard::from_bytes(&client_auth_bytes).map_err(|_| { -294 ClientAuthHeaderInvalidSnafu { -295 value: client_auth_header.clone(), -296 } -297 .build() -298 })?; -299 -300 if client_auth.verify(io) { -301 tracing::trace!(?client_auth.public_key, "authentication succeeded via keying material"); -302 return Ok(SuccessfulAuthentication { -303 client_key: client_auth.public_key, -304 mechanism: Mechanism::SignedKeyMaterial, -305 }); -306 } -307 } -308 -309 let challenge = ServerChallenge::new(rng); -310 write_frame(io, &challenge).await?; -311 -312 let (_, frame) = read_frame(io, &[ClientAuth::TAG], time::Duration::from_secs(10)).await?; -313 let client_auth: ClientAuth = deserialize_frame(frame)?; -314 -315 if client_auth.verify(&challenge) { -316 tracing::trace!(?client_auth.public_key, "authentication succeeded via challenge"); -317 Ok(SuccessfulAuthentication { -318 client_key: client_auth.public_key, -319 mechanism: Mechanism::SignedChallenge, -320 }) -321 } else { -322 tracing::trace!(?client_auth.public_key, "authentication failed"); -323 let denial = ServerDeniesAuth { -324 reason: "signature invalid".into(), -325 }; -326 write_frame(io, denial.clone()).await?; -327 Err(ServerDeniedAuthSnafu { -328 reason: denial.reason, -329 } -330 .build()) -331 } -332} -333 -334#[cfg(feature = "server")] -335impl SuccessfulAuthentication { -336 pub async fn authorize( -337 self, -338 io: &mut (impl BytesStreamSink + ExportKeyingMaterial), -339 is_authorized: bool, -340 ) -> Result<PublicKey, Error> { -341 if is_authorized { -342 tracing::trace!("authorizing client"); -343 write_frame(io, ServerConfirmsAuth).await?; -344 Ok(self.client_key) -345 } else { -346 tracing::trace!("denying client auth"); -347 let denial = ServerDeniesAuth { -348 reason: "not authorized".into(), -349 }; -350 write_frame(io, denial.clone()).await?; -351 Err(ServerDeniedAuthSnafu { -352 reason: denial.reason, -353 } -354 .build()) -355 } -356 } -357} -358 -359async fn write_frame<F: serde::Serialize + Frame>( -360 io: &mut impl BytesStreamSink, -361 frame: F, -362) -> Result<(), Error> { -363 let mut bytes = BytesMut::new(); -364 tracing::trace!(frame_type = %F::TAG, "Writing frame"); -365 F::TAG.write_to(&mut bytes); -366 let bytes = postcard::to_io(&frame, bytes.writer()) -367 .expect("serialization failed") // buffer can't become "full" without being a critical failure, datastructures shouldn't ever fail serialization -368 .into_inner() -369 .freeze(); -370 io.send(bytes).await?; -371 io.flush().await?; -372 Ok(()) -373} -374 -375async fn read_frame( -376 io: &mut impl BytesStreamSink, -377 expected_types: &[FrameType], -378 timeout: time::Duration, -379) -> Result<(FrameType, Bytes), Error> { -380 let recv = time::timeout(timeout, io.try_next()) -381 .await -382 .context(TimeoutSnafu)?? -383 .ok_or_else(|| UnexpectedEndSnafu.build())?; -384 -385 let (frame_type, payload) = FrameType::from_bytes(recv).context(UnexpectedEndSnafu)?; -386 tracing::trace!(%frame_type, "Reading frame"); -387 snafu::ensure!( -388 expected_types.contains(&frame_type), -389 UnexpectedFrameTypeSnafu { -390 frame_type, -391 expected_types: expected_types.to_vec() -392 } -393 ); -394 -395 Ok((frame_type, payload)) -396} -397 -398fn deserialize_frame<F: Frame + serde::de::DeserializeOwned>(frame: Bytes) -> Result<F, Error> { -399 postcard::from_bytes(&frame).context(DeserializationSnafu { frame_type: F::TAG }) -400} -401 -402#[cfg(all(test, feature = "server"))] -403mod tests { -404 use bytes::BytesMut; -405 use iroh_base::{PublicKey, SecretKey}; -406 use n0_future::{Sink, SinkExt, Stream, TryStreamExt}; -407 use n0_snafu::{Result, ResultExt}; -408 use tokio_util::codec::{Framed, LengthDelimitedCodec}; -409 use tracing::{info_span, Instrument}; -410 use tracing_test::traced_test; -411 -412 use super::{ -413 ClientAuth, KeyMaterialClientAuth, Mechanism, ServerChallenge, ServerConfirmsAuth, -414 }; -415 use crate::ExportKeyingMaterial; -416 -417 struct TestKeyingMaterial<IO> { -418 shared_secret: Option<u64>, -419 inner: IO, -420 } -421 -422 trait WithTlsSharedSecret: Sized { -423 fn with_shared_secret(self, shared_secret: Option<u64>) -> TestKeyingMaterial<Self>; -424 } -425 -426 impl<T: Sized> WithTlsSharedSecret for T { -427 fn with_shared_secret(self, shared_secret: Option<u64>) -> TestKeyingMaterial<Self> { -428 TestKeyingMaterial { -429 shared_secret, -430 inner: self, -431 } -432 } -433 } -434 -435 impl<IO> ExportKeyingMaterial for TestKeyingMaterial<IO> { -436 fn export_keying_material<T: AsMut<[u8]>>( -437 &self, -438 mut output: T, -439 label: &[u8], -440 context: Option<&[u8]>, -441 ) -> Option<T> { -442 // we simulate something like exporting keying material using blake3 -443 -444 let label_key = blake3::hash(label); -445 let context_key = blake3::keyed_hash(label_key.as_bytes(), context.unwrap_or(&[])); -446 let mut hasher = blake3::Hasher::new_keyed(context_key.as_bytes()); -447 hasher.update(&self.shared_secret?.to_le_bytes()); -448 hasher.finalize_xof().fill(output.as_mut()); -449 -450 Some(output) -451 } -452 } -453 -454 impl<V, IO: Stream<Item = V> + Unpin> Stream for TestKeyingMaterial<IO> { -455 type Item = V; -456 -457 fn poll_next( -458 mut self: std::pin::Pin<&mut Self>, -459 cx: &mut std::task::Context<'_>, -460 ) -> std::task::Poll<Option<Self::Item>> { -461 std::pin::Pin::new(&mut self.inner).poll_next(cx) -462 } -463 } -464 -465 impl<V, E, IO: Sink<V, Error = E> + Unpin> Sink<V> for TestKeyingMaterial<IO> { -466 type Error = E; -467 -468 fn poll_ready( -469 mut self: std::pin::Pin<&mut Self>, -470 cx: &mut std::task::Context<'_>, -471 ) -> std::task::Poll<Result<(), Self::Error>> { -472 std::pin::Pin::new(&mut self.inner).poll_ready(cx) -473 } -474 -475 fn start_send(mut self: std::pin::Pin<&mut Self>, item: V) -> Result<(), Self::Error> { -476 std::pin::Pin::new(&mut self.inner).start_send(item) -477 } -478 -479 fn poll_flush( -480 mut self: std::pin::Pin<&mut Self>, -481 cx: &mut std::task::Context<'_>, -482 ) -> std::task::Poll<Result<(), Self::Error>> { -483 std::pin::Pin::new(&mut self.inner).poll_flush(cx) -484 } -485 -486 fn poll_close( -487 mut self: std::pin::Pin<&mut Self>, -488 cx: &mut std::task::Context<'_>, -489 ) -> std::task::Poll<Result<(), Self::Error>> { -490 std::pin::Pin::new(&mut self.inner).poll_close(cx) -491 } -492 } -493 -494 async fn simulate_handshake( -495 secret_key: &SecretKey, -496 client_shared_secret: Option<u64>, -497 server_shared_secret: Option<u64>, -498 restricted_to: Option<PublicKey>, -499 ) -> (Result<ServerConfirmsAuth>, Result<(PublicKey, Mechanism)>) { -500 let (client, server) = tokio::io::duplex(1024); -501 -502 let mut client_io = Framed::new(client, LengthDelimitedCodec::new()) -503 .map_ok(BytesMut::freeze) -504 .map_err(tokio_websockets::Error::Io) -505 .sink_map_err(tokio_websockets::Error::Io) -506 .with_shared_secret(client_shared_secret); -507 let mut server_io = Framed::new(server, LengthDelimitedCodec::new()) -508 .map_ok(BytesMut::freeze) -509 .map_err(tokio_websockets::Error::Io) -510 .sink_map_err(tokio_websockets::Error::Io) -511 .with_shared_secret(server_shared_secret); -512 -513 let client_auth_header = KeyMaterialClientAuth::new(secret_key, &client_io) -514 .map(KeyMaterialClientAuth::into_header_value); -515 -516 n0_future::future::zip( -517 async { -518 super::clientside(&mut client_io, secret_key) -519 .await -520 .context("clientside") -521 } -522 .instrument(info_span!("clientside")), -523 async { -524 let auth_n = -525 super::serverside(&mut server_io, client_auth_header, rand::rngs::OsRng) -526 .await -527 .context("serverside")?; -528 let mechanism = auth_n.mechanism; -529 let is_authorized = restricted_to.map_or(true, |key| key == auth_n.client_key); -530 let key = auth_n.authorize(&mut server_io, is_authorized).await?; -531 Ok((key, mechanism)) -532 } -533 .instrument(info_span!("serverside")), -534 ) -535 .await -536 } -537 -538 #[tokio::test] -539 #[traced_test] -540 async fn test_handshake_via_shared_secrets() -> Result { -541 let secret_key = SecretKey::generate(rand::rngs::OsRng); -542 let (client, server) = simulate_handshake(&secret_key, Some(42), Some(42), None).await; -543 client?; -544 let (public_key, auth) = server?; -545 assert_eq!(public_key, secret_key.public()); -546 assert_eq!(auth, Mechanism::SignedKeyMaterial); // it got verified via shared key material -547 Ok(()) -548 } -549 -550 #[tokio::test] -551 #[traced_test] -552 async fn test_handshake_via_challenge() -> Result { -553 let secret_key = SecretKey::generate(rand::rngs::OsRng); -554 let (client, server) = simulate_handshake(&secret_key, None, None, None).await; -555 client?; -556 let (public_key, auth) = server?; -557 assert_eq!(public_key, secret_key.public()); -558 assert_eq!(auth, Mechanism::SignedChallenge); -559 Ok(()) -560 } -561 -562 #[tokio::test] -563 #[traced_test] -564 async fn test_handshake_mismatching_shared_secrets() -> Result { -565 let secret_key = SecretKey::generate(rand::rngs::OsRng); -566 // mismatching shared secrets *might* happen with HTTPS proxies that don't also middle-man the shared secret -567 let (client, server) = simulate_handshake(&secret_key, Some(10), Some(99), None).await; -568 client?; -569 let (public_key, auth) = server?; -570 assert_eq!(public_key, secret_key.public()); -571 assert_eq!(auth, Mechanism::SignedChallenge); -572 Ok(()) -573 } -574 -575 #[tokio::test] -576 #[traced_test] -577 async fn test_handshake_challenge_fallback() -> Result { -578 let secret_key = SecretKey::generate(rand::rngs::OsRng); -579 // clients might not have access to shared secrets -580 let (client, server) = simulate_handshake(&secret_key, None, Some(99), None).await; -581 client?; -582 let (public_key, auth) = server?; -583 assert_eq!(public_key, secret_key.public()); -584 assert_eq!(auth, Mechanism::SignedChallenge); -585 Ok(()) -586 } -587 -588 #[tokio::test] -589 #[traced_test] -590 async fn test_handshake_with_auth_positive() -> Result { -591 let secret_key = SecretKey::generate(rand::rngs::OsRng); -592 let public_key = secret_key.public(); -593 let (client, server) = simulate_handshake(&secret_key, None, None, Some(public_key)).await; -594 client?; -595 let (public_key, _) = server?; -596 assert_eq!(public_key, secret_key.public()); -597 Ok(()) -598 } -599 -600 #[tokio::test] -601 #[traced_test] -602 async fn test_handshake_with_auth_negative() -> Result { -603 let secret_key = SecretKey::generate(rand::rngs::OsRng); -604 let public_key = secret_key.public(); -605 let wrong_secret_key = SecretKey::generate(rand::rngs::OsRng); -606 let (client, server) = -607 simulate_handshake(&wrong_secret_key, None, None, Some(public_key)).await; -608 assert!(client.is_err()); -609 assert!(server.is_err()); -610 Ok(()) -611 } -612 -613 #[tokio::test] -614 #[traced_test] -615 async fn test_handshake_via_shared_secret_with_auth_negative() -> Result { -616 let secret_key = SecretKey::generate(rand::rngs::OsRng); -617 let public_key = secret_key.public(); -618 let wrong_secret_key = SecretKey::generate(rand::rngs::OsRng); -619 let (client, server) = -620 simulate_handshake(&wrong_secret_key, Some(42), Some(42), Some(public_key)).await; -621 assert!(client.is_err()); -622 assert!(server.is_err()); -623 Ok(()) -624 } -625 -626 #[test] -627 fn test_client_auth_roundtrip() -> Result { -628 let secret_key = SecretKey::generate(rand::rngs::OsRng); -629 let challenge = ServerChallenge::new(rand::rngs::OsRng); -630 let client_auth = ClientAuth::new(&secret_key, &challenge); -631 -632 let bytes = postcard::to_allocvec(&client_auth).e()?; -633 let decoded: ClientAuth = postcard::from_bytes(&bytes).e()?; -634 -635 assert_eq!(client_auth.public_key, decoded.public_key); -636 assert_eq!(client_auth.signature, decoded.signature); -637 -638 Ok(()) -639 } -640 -641 #[test] -642 fn test_km_client_auth_roundtrip() -> Result { -643 let secret_key = SecretKey::generate(rand::rngs::OsRng); -644 let client_auth = KeyMaterialClientAuth::new( -645 &secret_key, -646 &TestKeyingMaterial { -647 inner: (), -648 shared_secret: Some(42), -649 }, -650 ) -651 .e()?; -652 -653 let bytes = postcard::to_allocvec(&client_auth).e()?; -654 let decoded: KeyMaterialClientAuth = postcard::from_bytes(&bytes).e()?; -655 -656 assert_eq!(client_auth.public_key, decoded.public_key); -657 assert_eq!(client_auth.signature, decoded.signature); -658 -659 Ok(()) -660 } -661 -662 #[test] -663 fn test_challenge_verification() -> Result { -664 let secret_key = SecretKey::generate(rand::rngs::OsRng); -665 let challenge = ServerChallenge::new(rand::rngs::OsRng); -666 let client_auth = ClientAuth::new(&secret_key, &challenge); -667 assert!(client_auth.verify(&challenge)); -668 -669 Ok(()) -670 } -671 -672 #[test] -673 fn test_key_material_verification() -> Result { -674 let secret_key = SecretKey::generate(rand::rngs::OsRng); -675 let io = TestKeyingMaterial { -676 inner: (), -677 shared_secret: Some(42), -678 }; -679 let client_auth = KeyMaterialClientAuth::new(&secret_key, &io).e()?; -680 assert!(client_auth.verify(&io)); -681 -682 Ok(()) -683 } -684} \ No newline at end of file +22#[cfg_attr(wasm_browser, allow(unused))] +23pub(crate) struct KeyMaterialClientAuth { +24 /// The client's public key +25 pub(crate) public_key: PublicKey, +26 /// A signature of (a hash of) extracted key material. +27 #[serde(with = "serde_bytes")] +28 pub(crate) signature: [u8; 64], +29 /// Part of the extracted key material. +30 /// +31 /// Allows making sure we have the same underlying key material. +32 pub(crate) key_material_suffix: [u8; 16], +33} +34 +35/// A challenge for the client to sign with their secret key for NodeId authentication. +36#[derive(derive_more::Debug, serde::Deserialize)] +37#[cfg_attr(feature = "server", derive(serde::Serialize))] +38pub(crate) struct ServerChallenge { +39 /// The challenge to sign. +40 /// Must be randomly generated with an RNG that is safe to use for crypto. +41 pub(crate) challenge: [u8; 16], +42} +43 +44/// Authentication message from the client. +45/// +46/// Used when authentication via [`KeyMaterialClientAuth`] didn't work. +47#[derive(derive_more::Debug, serde::Serialize)] +48#[cfg_attr(feature = "server", derive(serde::Deserialize))] +49pub(crate) struct ClientAuth { +50 /// The client's public key, a.k.a. the `NodeId` +51 pub(crate) public_key: PublicKey, +52 /// A signature of (a hash of) the [`ServerChallenge`]. +53 /// +54 /// This is what provides the authentication. +55 #[serde(with = "serde_bytes")] +56 pub(crate) signature: [u8; 64], +57} +58 +59/// Confirmation of successful connection. +60#[derive(derive_more::Debug, serde::Deserialize)] +61#[cfg_attr(feature = "server", derive(serde::Serialize))] +62pub(crate) struct ServerConfirmsAuth; +63 +64/// Denial of connection. The client couldn't be verified as authentic. +65#[derive(derive_more::Debug, Clone, serde::Deserialize)] +66#[cfg_attr(feature = "server", derive(serde::Serialize))] +67pub(crate) struct ServerDeniesAuth { +68 reason: String, +69} +70 +71/// Trait for getting the frame type tag for a frame. +72/// +73/// Used only in the handshake, as the frame we expect next +74/// is fairly stateful. +75/// Not used in the send/recv protocol, as any frame is +76/// allowed to happen at any time there. +77trait Frame { +78 /// The frame type this frame is identified by and prefixed with +79 const TAG: FrameType; +80} +81 +82impl<T: Frame> Frame for &T { +83 const TAG: FrameType = T::TAG; +84} +85 +86impl Frame for ServerChallenge { +87 const TAG: FrameType = FrameType::ServerChallenge; +88} +89 +90impl Frame for ClientAuth { +91 const TAG: FrameType = FrameType::ClientAuth; +92} +93 +94impl Frame for ServerConfirmsAuth { +95 const TAG: FrameType = FrameType::ServerConfirmsAuth; +96} +97 +98impl Frame for ServerDeniesAuth { +99 const TAG: FrameType = FrameType::ServerDeniesAuth; +100} +101 +102#[common_fields({ +103 backtrace: Option<Backtrace>, +104 #[snafu(implicit)] +105 span_trace: n0_snafu::SpanTrace, +106})] +107#[allow(missing_docs)] +108#[derive(Debug, Snafu)] +109#[non_exhaustive] +110pub enum Error { +111 #[snafu(transparent)] +112 Websocket { +113 #[cfg(not(wasm_browser))] +114 source: tokio_websockets::Error, +115 #[cfg(wasm_browser)] +116 source: ws_stream_wasm::WsErr, +117 }, +118 #[snafu(display("Handshake timeout reached"))] +119 Timeout { source: Elapsed }, +120 #[snafu(display("Handshake stream ended prematurely"))] +121 UnexpectedEnd {}, +122 #[snafu(display("The relay denied our authentication ({reason})"))] +123 ServerDeniedAuth { reason: String }, +124 #[snafu(display("Unexpected tag, got {frame_type}, but expected one of {expected_types:?}"))] +125 UnexpectedFrameType { +126 frame_type: FrameType, +127 expected_types: Vec<FrameType>, +128 }, +129 #[snafu(display("Handshake failed while deserializing {frame_type} frame"))] +130 DeserializationError { +131 frame_type: FrameType, +132 source: postcard::Error, +133 }, +134 #[cfg(feature = "server")] +135 /// Failed to deserialize client auth header +136 ClientAuthHeaderInvalid { value: HeaderValue }, +137} +138 +139impl ServerChallenge { +140 /// TODO(matheus23): docs +141 #[cfg(feature = "server")] +142 pub(crate) fn new(mut rng: impl RngCore + CryptoRng) -> Self { +143 let mut challenge = [0u8; 16]; +144 rng.fill_bytes(&mut challenge); +145 Self { challenge } +146 } +147 +148 fn message_to_sign(&self) -> [u8; 32] { +149 blake3::derive_key( +150 "iroh-relay handshake v1 challenge signature", +151 &self.challenge, +152 ) +153 } +154} +155 +156impl ClientAuth { +157 /// TODO(matheus23): docs +158 pub(crate) fn new(secret_key: &SecretKey, challenge: &ServerChallenge) -> Self { +159 Self { +160 public_key: secret_key.public(), +161 signature: secret_key.sign(&challenge.message_to_sign()).to_bytes(), +162 } +163 } +164 +165 /// TODO(matheus23): docs +166 #[cfg(feature = "server")] +167 pub(crate) fn verify(&self, challenge: &ServerChallenge) -> bool { +168 self.public_key +169 .verify( +170 &challenge.message_to_sign(), +171 &Signature::from_bytes(&self.signature), +172 ) +173 .is_ok() +174 } +175} +176 +177#[cfg_attr(wasm_browser, allow(unused))] +178impl KeyMaterialClientAuth { +179 pub(crate) fn new(secret_key: &SecretKey, io: &impl ExportKeyingMaterial) -> Option<Self> { +180 let public_key = secret_key.public(); +181 let key_material = io.export_keying_material( +182 [0u8; 32], +183 b"iroh-relay handshake v1", +184 Some(secret_key.public().as_bytes()), +185 )?; +186 Some(Self { +187 public_key, +188 signature: secret_key.sign(&key_material[..16]).to_bytes(), +189 key_material_suffix: key_material[16..].try_into().expect("split right"), +190 }) +191 } +192 +193 pub(crate) fn into_header_value(self) -> HeaderValue { +194 HeaderValue::from_str( +195 &data_encoding::BASE64URL_NOPAD +196 .encode(&postcard::to_allocvec(&self).expect("encoding never fails")), +197 ) +198 .expect("BASE64URL_NOPAD encoding contained invisible ascii characters") +199 } +200 +201 #[cfg(feature = "server")] +202 pub(crate) fn verify(&self, io: &impl ExportKeyingMaterial) -> bool { +203 let Some(key_material) = io.export_keying_material( +204 [0u8; 32], +205 b"iroh-relay handshake v1", +206 Some(self.public_key.as_bytes()), +207 ) else { +208 return false; +209 }; +210 +211 key_material[16..] == self.key_material_suffix +212 && self +213 .public_key +214 .verify(&key_material[..16], &Signature::from_bytes(&self.signature)) +215 .is_ok() +216 } +217} +218 +219/// TODO(matheus23) docs +220pub(crate) async fn clientside( +221 io: &mut (impl BytesStreamSink + ExportKeyingMaterial), +222 secret_key: &SecretKey, +223) -> Result<ServerConfirmsAuth, Error> { +224 let (tag, frame) = read_frame( +225 io, +226 &[ServerChallenge::TAG, ServerConfirmsAuth::TAG], +227 time::Duration::from_secs(30), +228 ) +229 .await?; +230 +231 let (tag, frame) = if tag == ServerChallenge::TAG { +232 let challenge: ServerChallenge = deserialize_frame(frame)?; +233 +234 let client_info = ClientAuth::new(secret_key, &challenge); +235 write_frame(io, client_info).await?; +236 +237 read_frame( +238 io, +239 &[ServerConfirmsAuth::TAG, ServerDeniesAuth::TAG], +240 time::Duration::from_secs(30), +241 ) +242 .await? +243 } else { +244 (tag, frame) +245 }; +246 +247 match tag { +248 FrameType::ServerConfirmsAuth => { +249 let confirmation: ServerConfirmsAuth = deserialize_frame(frame)?; +250 Ok(confirmation) +251 } +252 FrameType::ServerDeniesAuth => { +253 let denial: ServerDeniesAuth = deserialize_frame(frame)?; +254 Err(ServerDeniedAuthSnafu { +255 reason: denial.reason, +256 } +257 .build()) +258 } +259 _ => unreachable!(), +260 } +261} +262 +263#[cfg(feature = "server")] +264#[derive(Debug)] +265pub(crate) struct SuccessfulAuthentication { +266 pub(crate) client_key: PublicKey, +267 pub(crate) mechanism: Mechanism, +268} +269 +270#[cfg(feature = "server")] +271#[derive(Debug, Clone, Copy, PartialEq, Eq)] +272pub(crate) enum Mechanism { +273 SignedChallenge, +274 SignedKeyMaterial, +275} +276 +277/// TODO(matheus23) docs +278#[cfg(feature = "server")] +279pub(crate) async fn serverside( +280 io: &mut (impl BytesStreamSink + ExportKeyingMaterial), +281 client_auth_header: Option<HeaderValue>, +282 rng: impl RngCore + CryptoRng, +283) -> Result<SuccessfulAuthentication, Error> { +284 if let Some(client_auth_header) = client_auth_header { +285 let client_auth_bytes = data_encoding::BASE64URL_NOPAD +286 .decode(client_auth_header.as_ref()) +287 .map_err(|_| { +288 ClientAuthHeaderInvalidSnafu { +289 value: client_auth_header.clone(), +290 } +291 .build() +292 })?; +293 +294 let client_auth: KeyMaterialClientAuth = +295 postcard::from_bytes(&client_auth_bytes).map_err(|_| { +296 ClientAuthHeaderInvalidSnafu { +297 value: client_auth_header.clone(), +298 } +299 .build() +300 })?; +301 +302 if client_auth.verify(io) { +303 tracing::trace!(?client_auth.public_key, "authentication succeeded via keying material"); +304 return Ok(SuccessfulAuthentication { +305 client_key: client_auth.public_key, +306 mechanism: Mechanism::SignedKeyMaterial, +307 }); +308 } +309 } +310 +311 let challenge = ServerChallenge::new(rng); +312 write_frame(io, &challenge).await?; +313 +314 let (_, frame) = read_frame(io, &[ClientAuth::TAG], time::Duration::from_secs(10)).await?; +315 let client_auth: ClientAuth = deserialize_frame(frame)?; +316 +317 if client_auth.verify(&challenge) { +318 tracing::trace!(?client_auth.public_key, "authentication succeeded via challenge"); +319 Ok(SuccessfulAuthentication { +320 client_key: client_auth.public_key, +321 mechanism: Mechanism::SignedChallenge, +322 }) +323 } else { +324 tracing::trace!(?client_auth.public_key, "authentication failed"); +325 let denial = ServerDeniesAuth { +326 reason: "signature invalid".into(), +327 }; +328 write_frame(io, denial.clone()).await?; +329 Err(ServerDeniedAuthSnafu { +330 reason: denial.reason, +331 } +332 .build()) +333 } +334} +335 +336#[cfg(feature = "server")] +337impl SuccessfulAuthentication { +338 pub async fn authorize( +339 self, +340 io: &mut (impl BytesStreamSink + ExportKeyingMaterial), +341 is_authorized: bool, +342 ) -> Result<PublicKey, Error> { +343 if is_authorized { +344 tracing::trace!("authorizing client"); +345 write_frame(io, ServerConfirmsAuth).await?; +346 Ok(self.client_key) +347 } else { +348 tracing::trace!("denying client auth"); +349 let denial = ServerDeniesAuth { +350 reason: "not authorized".into(), +351 }; +352 write_frame(io, denial.clone()).await?; +353 Err(ServerDeniedAuthSnafu { +354 reason: denial.reason, +355 } +356 .build()) +357 } +358 } +359} +360 +361async fn write_frame<F: serde::Serialize + Frame>( +362 io: &mut impl BytesStreamSink, +363 frame: F, +364) -> Result<(), Error> { +365 let mut bytes = BytesMut::new(); +366 tracing::trace!(frame_type = %F::TAG, "Writing frame"); +367 F::TAG.write_to(&mut bytes); +368 let bytes = postcard::to_io(&frame, bytes.writer()) +369 .expect("serialization failed") // buffer can't become "full" without being a critical failure, datastructures shouldn't ever fail serialization +370 .into_inner() +371 .freeze(); +372 io.send(bytes).await?; +373 io.flush().await?; +374 Ok(()) +375} +376 +377async fn read_frame( +378 io: &mut impl BytesStreamSink, +379 expected_types: &[FrameType], +380 timeout: time::Duration, +381) -> Result<(FrameType, Bytes), Error> { +382 let recv = time::timeout(timeout, io.try_next()) +383 .await +384 .context(TimeoutSnafu)?? +385 .ok_or_else(|| UnexpectedEndSnafu.build())?; +386 +387 let (frame_type, payload) = FrameType::from_bytes(recv).context(UnexpectedEndSnafu)?; +388 tracing::trace!(%frame_type, "Reading frame"); +389 snafu::ensure!( +390 expected_types.contains(&frame_type), +391 UnexpectedFrameTypeSnafu { +392 frame_type, +393 expected_types: expected_types.to_vec() +394 } +395 ); +396 +397 Ok((frame_type, payload)) +398} +399 +400fn deserialize_frame<F: Frame + serde::de::DeserializeOwned>(frame: Bytes) -> Result<F, Error> { +401 postcard::from_bytes(&frame).context(DeserializationSnafu { frame_type: F::TAG }) +402} +403 +404#[cfg(all(test, feature = "server"))] +405mod tests { +406 use bytes::BytesMut; +407 use iroh_base::{PublicKey, SecretKey}; +408 use n0_future::{Sink, SinkExt, Stream, TryStreamExt}; +409 use n0_snafu::{Result, ResultExt}; +410 use tokio_util::codec::{Framed, LengthDelimitedCodec}; +411 use tracing::{info_span, Instrument}; +412 use tracing_test::traced_test; +413 +414 use super::{ +415 ClientAuth, KeyMaterialClientAuth, Mechanism, ServerChallenge, ServerConfirmsAuth, +416 }; +417 use crate::ExportKeyingMaterial; +418 +419 struct TestKeyingMaterial<IO> { +420 shared_secret: Option<u64>, +421 inner: IO, +422 } +423 +424 trait WithTlsSharedSecret: Sized { +425 fn with_shared_secret(self, shared_secret: Option<u64>) -> TestKeyingMaterial<Self>; +426 } +427 +428 impl<T: Sized> WithTlsSharedSecret for T { +429 fn with_shared_secret(self, shared_secret: Option<u64>) -> TestKeyingMaterial<Self> { +430 TestKeyingMaterial { +431 shared_secret, +432 inner: self, +433 } +434 } +435 } +436 +437 impl<IO> ExportKeyingMaterial for TestKeyingMaterial<IO> { +438 fn export_keying_material<T: AsMut<[u8]>>( +439 &self, +440 mut output: T, +441 label: &[u8], +442 context: Option<&[u8]>, +443 ) -> Option<T> { +444 // we simulate something like exporting keying material using blake3 +445 +446 let label_key = blake3::hash(label); +447 let context_key = blake3::keyed_hash(label_key.as_bytes(), context.unwrap_or(&[])); +448 let mut hasher = blake3::Hasher::new_keyed(context_key.as_bytes()); +449 hasher.update(&self.shared_secret?.to_le_bytes()); +450 hasher.finalize_xof().fill(output.as_mut()); +451 +452 Some(output) +453 } +454 } +455 +456 impl<V, IO: Stream<Item = V> + Unpin> Stream for TestKeyingMaterial<IO> { +457 type Item = V; +458 +459 fn poll_next( +460 mut self: std::pin::Pin<&mut Self>, +461 cx: &mut std::task::Context<'_>, +462 ) -> std::task::Poll<Option<Self::Item>> { +463 std::pin::Pin::new(&mut self.inner).poll_next(cx) +464 } +465 } +466 +467 impl<V, E, IO: Sink<V, Error = E> + Unpin> Sink<V> for TestKeyingMaterial<IO> { +468 type Error = E; +469 +470 fn poll_ready( +471 mut self: std::pin::Pin<&mut Self>, +472 cx: &mut std::task::Context<'_>, +473 ) -> std::task::Poll<Result<(), Self::Error>> { +474 std::pin::Pin::new(&mut self.inner).poll_ready(cx) +475 } +476 +477 fn start_send(mut self: std::pin::Pin<&mut Self>, item: V) -> Result<(), Self::Error> { +478 std::pin::Pin::new(&mut self.inner).start_send(item) +479 } +480 +481 fn poll_flush( +482 mut self: std::pin::Pin<&mut Self>, +483 cx: &mut std::task::Context<'_>, +484 ) -> std::task::Poll<Result<(), Self::Error>> { +485 std::pin::Pin::new(&mut self.inner).poll_flush(cx) +486 } +487 +488 fn poll_close( +489 mut self: std::pin::Pin<&mut Self>, +490 cx: &mut std::task::Context<'_>, +491 ) -> std::task::Poll<Result<(), Self::Error>> { +492 std::pin::Pin::new(&mut self.inner).poll_close(cx) +493 } +494 } +495 +496 async fn simulate_handshake( +497 secret_key: &SecretKey, +498 client_shared_secret: Option<u64>, +499 server_shared_secret: Option<u64>, +500 restricted_to: Option<PublicKey>, +501 ) -> (Result<ServerConfirmsAuth>, Result<(PublicKey, Mechanism)>) { +502 let (client, server) = tokio::io::duplex(1024); +503 +504 let mut client_io = Framed::new(client, LengthDelimitedCodec::new()) +505 .map_ok(BytesMut::freeze) +506 .map_err(tokio_websockets::Error::Io) +507 .sink_map_err(tokio_websockets::Error::Io) +508 .with_shared_secret(client_shared_secret); +509 let mut server_io = Framed::new(server, LengthDelimitedCodec::new()) +510 .map_ok(BytesMut::freeze) +511 .map_err(tokio_websockets::Error::Io) +512 .sink_map_err(tokio_websockets::Error::Io) +513 .with_shared_secret(server_shared_secret); +514 +515 let client_auth_header = KeyMaterialClientAuth::new(secret_key, &client_io) +516 .map(KeyMaterialClientAuth::into_header_value); +517 +518 n0_future::future::zip( +519 async { +520 super::clientside(&mut client_io, secret_key) +521 .await +522 .context("clientside") +523 } +524 .instrument(info_span!("clientside")), +525 async { +526 let auth_n = +527 super::serverside(&mut server_io, client_auth_header, rand::rngs::OsRng) +528 .await +529 .context("serverside")?; +530 let mechanism = auth_n.mechanism; +531 let is_authorized = restricted_to.is_none_or(|key| key == auth_n.client_key); +532 let key = auth_n.authorize(&mut server_io, is_authorized).await?; +533 Ok((key, mechanism)) +534 } +535 .instrument(info_span!("serverside")), +536 ) +537 .await +538 } +539 +540 #[tokio::test] +541 #[traced_test] +542 async fn test_handshake_via_shared_secrets() -> Result { +543 let secret_key = SecretKey::generate(rand::rngs::OsRng); +544 let (client, server) = simulate_handshake(&secret_key, Some(42), Some(42), None).await; +545 client?; +546 let (public_key, auth) = server?; +547 assert_eq!(public_key, secret_key.public()); +548 assert_eq!(auth, Mechanism::SignedKeyMaterial); // it got verified via shared key material +549 Ok(()) +550 } +551 +552 #[tokio::test] +553 #[traced_test] +554 async fn test_handshake_via_challenge() -> Result { +555 let secret_key = SecretKey::generate(rand::rngs::OsRng); +556 let (client, server) = simulate_handshake(&secret_key, None, None, None).await; +557 client?; +558 let (public_key, auth) = server?; +559 assert_eq!(public_key, secret_key.public()); +560 assert_eq!(auth, Mechanism::SignedChallenge); +561 Ok(()) +562 } +563 +564 #[tokio::test] +565 #[traced_test] +566 async fn test_handshake_mismatching_shared_secrets() -> Result { +567 let secret_key = SecretKey::generate(rand::rngs::OsRng); +568 // mismatching shared secrets *might* happen with HTTPS proxies that don't also middle-man the shared secret +569 let (client, server) = simulate_handshake(&secret_key, Some(10), Some(99), None).await; +570 client?; +571 let (public_key, auth) = server?; +572 assert_eq!(public_key, secret_key.public()); +573 assert_eq!(auth, Mechanism::SignedChallenge); +574 Ok(()) +575 } +576 +577 #[tokio::test] +578 #[traced_test] +579 async fn test_handshake_challenge_fallback() -> Result { +580 let secret_key = SecretKey::generate(rand::rngs::OsRng); +581 // clients might not have access to shared secrets +582 let (client, server) = simulate_handshake(&secret_key, None, Some(99), None).await; +583 client?; +584 let (public_key, auth) = server?; +585 assert_eq!(public_key, secret_key.public()); +586 assert_eq!(auth, Mechanism::SignedChallenge); +587 Ok(()) +588 } +589 +590 #[tokio::test] +591 #[traced_test] +592 async fn test_handshake_with_auth_positive() -> Result { +593 let secret_key = SecretKey::generate(rand::rngs::OsRng); +594 let public_key = secret_key.public(); +595 let (client, server) = simulate_handshake(&secret_key, None, None, Some(public_key)).await; +596 client?; +597 let (public_key, _) = server?; +598 assert_eq!(public_key, secret_key.public()); +599 Ok(()) +600 } +601 +602 #[tokio::test] +603 #[traced_test] +604 async fn test_handshake_with_auth_negative() -> Result { +605 let secret_key = SecretKey::generate(rand::rngs::OsRng); +606 let public_key = secret_key.public(); +607 let wrong_secret_key = SecretKey::generate(rand::rngs::OsRng); +608 let (client, server) = +609 simulate_handshake(&wrong_secret_key, None, None, Some(public_key)).await; +610 assert!(client.is_err()); +611 assert!(server.is_err()); +612 Ok(()) +613 } +614 +615 #[tokio::test] +616 #[traced_test] +617 async fn test_handshake_via_shared_secret_with_auth_negative() -> Result { +618 let secret_key = SecretKey::generate(rand::rngs::OsRng); +619 let public_key = secret_key.public(); +620 let wrong_secret_key = SecretKey::generate(rand::rngs::OsRng); +621 let (client, server) = +622 simulate_handshake(&wrong_secret_key, Some(42), Some(42), Some(public_key)).await; +623 assert!(client.is_err()); +624 assert!(server.is_err()); +625 Ok(()) +626 } +627 +628 #[test] +629 fn test_client_auth_roundtrip() -> Result { +630 let secret_key = SecretKey::generate(rand::rngs::OsRng); +631 let challenge = ServerChallenge::new(rand::rngs::OsRng); +632 let client_auth = ClientAuth::new(&secret_key, &challenge); +633 +634 let bytes = postcard::to_allocvec(&client_auth).e()?; +635 let decoded: ClientAuth = postcard::from_bytes(&bytes).e()?; +636 +637 assert_eq!(client_auth.public_key, decoded.public_key); +638 assert_eq!(client_auth.signature, decoded.signature); +639 +640 Ok(()) +641 } +642 +643 #[test] +644 fn test_km_client_auth_roundtrip() -> Result { +645 let secret_key = SecretKey::generate(rand::rngs::OsRng); +646 let client_auth = KeyMaterialClientAuth::new( +647 &secret_key, +648 &TestKeyingMaterial { +649 inner: (), +650 shared_secret: Some(42), +651 }, +652 ) +653 .e()?; +654 +655 let bytes = postcard::to_allocvec(&client_auth).e()?; +656 let decoded: KeyMaterialClientAuth = postcard::from_bytes(&bytes).e()?; +657 +658 assert_eq!(client_auth.public_key, decoded.public_key); +659 assert_eq!(client_auth.signature, decoded.signature); +660 +661 Ok(()) +662 } +663 +664 #[test] +665 fn test_challenge_verification() -> Result { +666 let secret_key = SecretKey::generate(rand::rngs::OsRng); +667 let challenge = ServerChallenge::new(rand::rngs::OsRng); +668 let client_auth = ClientAuth::new(&secret_key, &challenge); +669 assert!(client_auth.verify(&challenge)); +670 +671 Ok(()) +672 } +673 +674 #[test] +675 fn test_key_material_verification() -> Result { +676 let secret_key = SecretKey::generate(rand::rngs::OsRng); +677 let io = TestKeyingMaterial { +678 inner: (), +679 shared_secret: Some(42), +680 }; +681 let client_auth = KeyMaterialClientAuth::new(&secret_key, &io).e()?; +682 assert!(client_auth.verify(&io)); +683 +684 Ok(()) +685 } +686} \ No newline at end of file