-
Notifications
You must be signed in to change notification settings - Fork 14
refactor(auth): connection hooks #177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
2f89a1d
refactor(auth): connection hooks
Karrq 0ff635d
chore: fmt
Karrq f14e578
Merge remote-tracking branch 'origin/main' into refactor/auth
Karrq e55bbe2
fix: typo
Karrq 08feb80
docs: update CLAUDE.md
Karrq 0941d6a
deps: remove unused tokio-util
Karrq c57c8f1
refactor: review
Karrq c7365b3
chore: fmt
Karrq 245ca62
docs: fix refs in test
Karrq cfa8331
feat: challenge-response auth example
Karrq 24be1fe
Merge branch 'main' into refactor/auth
Karrq c8dee23
chore: fmt
Karrq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| //! Connection hooks for customizing connection establishment. | ||
| //! | ||
| //! Connection hooks are attached when establishing connections and allow custom | ||
| //! authentication, handshakes, or protocol negotiations. The [`ConnectionHook`] trait | ||
| //! is called during connection setup, before the connection is used for messaging. | ||
| //! | ||
| //! # Built-in Hooks | ||
| //! | ||
| //! The [`token`] module provides ready-to-use token-based authentication hooks: | ||
| //! - [`token::ServerHook`] - Server-side hook that validates client tokens | ||
| //! - [`token::ClientHook`] - Client-side hook that sends a token to the server | ||
| //! | ||
| //! # Custom Hooks | ||
| //! | ||
| //! Implement [`ConnectionHook`] for custom authentication or protocol negotiation: | ||
| //! | ||
| //! ```no_run | ||
| //! use msg_socket::hooks::{ConnectionHook, Error, HookResult}; | ||
| //! use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; | ||
| //! | ||
| //! struct MyAuth; | ||
| //! | ||
| //! #[derive(Debug, thiserror::Error)] | ||
| //! enum MyAuthError { | ||
| //! #[error("invalid token")] | ||
| //! InvalidToken, | ||
| //! } | ||
| //! | ||
| //! impl<Io> ConnectionHook<Io> for MyAuth | ||
| //! where | ||
| //! Io: AsyncRead + AsyncWrite + Send + Unpin + 'static, | ||
| //! { | ||
| //! type Error = MyAuthError; | ||
| //! | ||
| //! async fn on_connection(&self, mut io: Io) -> HookResult<Io, Self::Error> { | ||
| //! let mut buf = [0u8; 32]; | ||
| //! io.read_exact(&mut buf).await?; | ||
| //! if &buf == b"expected_token_value_32_bytes!!!" { | ||
| //! io.write_all(b"OK").await?; | ||
| //! Ok(io) | ||
| //! } else { | ||
| //! Err(Error::hook(MyAuthError::InvalidToken)) | ||
| //! } | ||
| //! } | ||
| //! } | ||
| //! ``` | ||
| //! | ||
| //! # Future Extensions | ||
| //! | ||
| //! TODO: Additional hooks may be added for different parts of the connection lifecycle | ||
| //! (e.g., disconnection, reconnection, periodic health checks). | ||
|
|
||
| use std::{error::Error as StdError, future::Future, io, pin::Pin, sync::Arc}; | ||
|
|
||
| use tokio::io::{AsyncRead, AsyncWrite}; | ||
|
|
||
| pub mod token; | ||
|
|
||
| /// Error type for connection hooks. | ||
| /// | ||
| /// Distinguishes between I/O errors and hook-specific errors. | ||
| #[derive(Debug, thiserror::Error)] | ||
| pub enum Error<E> { | ||
| /// An I/O error occurred. | ||
| #[error("IO error: {0}")] | ||
| Io(#[from] io::Error), | ||
| /// A hook-specific error. | ||
| #[error("Hook error: {0}")] | ||
| Hook(#[source] E), | ||
| } | ||
|
|
||
| impl<E> Error<E> { | ||
| /// Create a hook error from a hook-specific error. | ||
| pub fn hook(err: E) -> Self { | ||
| Error::Hook(err) | ||
| } | ||
| } | ||
|
|
||
| /// Result type for connection hooks. | ||
| /// | ||
| /// This is intentionally named `HookResult` (not `Result`) to make it clear this is not | ||
| /// `std::result::Result`. A `HookResult` can be: | ||
| /// - `Ok(io)` - success, returns the IO stream | ||
| /// - `Err(Error::Io(..))` - an I/O error occurred | ||
| /// - `Err(Error::Hook(..))` - a hook-specific error occurred | ||
| pub type HookResult<T, E> = std::result::Result<T, Error<E>>; | ||
|
|
||
| /// Type-erased hook result used internally by drivers. | ||
| pub(crate) type ErasedHookResult<T> = HookResult<T, Box<dyn StdError + Send + Sync>>; | ||
|
|
||
| /// Connection hook executed during connection establishment. | ||
| /// | ||
| /// For server sockets: called when a connection is accepted. | ||
| /// For client sockets: called after connecting. | ||
| /// | ||
| /// The connection hook receives the raw IO stream and has full control over the handshake protocol. | ||
| pub trait ConnectionHook<Io>: Send + Sync + 'static | ||
| where | ||
| Io: AsyncRead + AsyncWrite + Send + Unpin + 'static, | ||
| { | ||
| /// The hook-specific error type. | ||
| type Error: StdError + Send + Sync + 'static; | ||
|
|
||
| /// Called when a connection is established. | ||
| /// | ||
| /// # Arguments | ||
| /// * `io` - The raw IO stream for this connection | ||
| /// | ||
| /// # Returns | ||
| /// - `Ok(io)` - The IO stream on success (potentially wrapped/transformed) | ||
| /// - `Err(Error::Io(..))` - An I/O error occurred | ||
| /// - `Err(Error::Hook(Self::Error))` - A hook-specific error to reject the connection | ||
| fn on_connection(&self, io: Io) -> impl Future<Output = HookResult<Io, Self::Error>> + Send; | ||
| } | ||
|
|
||
| // ============================================================================ | ||
| // Type-erased connection hook for internal use | ||
| // ============================================================================ | ||
|
|
||
| /// Type-erased connection hook for internal use. | ||
| /// | ||
| /// This trait allows storing connection hooks with different concrete types behind a single | ||
| /// `Arc<dyn ConnectionHookErased<Io>>`. The hook error type is erased to `Box<dyn Error>`. | ||
| pub(crate) trait ConnectionHookErased<Io>: Send + Sync + 'static | ||
| where | ||
| Io: AsyncRead + AsyncWrite + Send + Unpin + 'static, | ||
| { | ||
| fn on_connection( | ||
| self: Arc<Self>, | ||
| io: Io, | ||
| ) -> Pin<Box<dyn Future<Output = ErasedHookResult<Io>> + Send + 'static>>; | ||
| } | ||
|
|
||
| impl<T, Io> ConnectionHookErased<Io> for T | ||
| where | ||
| T: ConnectionHook<Io>, | ||
| Io: AsyncRead + AsyncWrite + Send + Unpin + 'static, | ||
| { | ||
| fn on_connection( | ||
| self: Arc<Self>, | ||
| io: Io, | ||
| ) -> Pin<Box<dyn Future<Output = ErasedHookResult<Io>> + Send + 'static>> { | ||
| Box::pin(async move { | ||
| ConnectionHook::on_connection(&*self, io).await.map_err(|e| match e { | ||
| Error::Io(io_err) => Error::Io(io_err), | ||
| Error::Hook(hook_err) => { | ||
| Error::Hook(Box::new(hook_err) as Box<dyn StdError + Send + Sync>) | ||
| } | ||
| }) | ||
| }) | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice pattern! Simplifies implementation for any consumers of this API