Skip to content

Commit

Permalink
Convert AuthError to Error<AuthErrorKind>
Browse files Browse the repository at this point in the history
The only change here is that the `AuthError` became
a specialization of the `error::Error<T>` generic.
The error messages are moved to the implementation
of its kind `AuthErrorKind`.
  • Loading branch information
nepalez committed Sep 22, 2023
1 parent 02fd086 commit b928510
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 25 deletions.
2 changes: 1 addition & 1 deletion async-nats/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ where

/// Enables wrapping source errors to the crate-specific error type
/// by additionally specifying the kind of the target error.
trait WithKind<Kind>
pub(crate) trait WithKind<Kind>
where
Kind: Clone + Debug + Display + PartialEq,
Self: Into<crate::Error>,
Expand Down
9 changes: 8 additions & 1 deletion async-nats/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ mod options;

pub use auth::Auth;
pub use client::{Client, PublishError, Request, RequestError, RequestErrorKind, SubscribeError};
pub use options::{AuthError, ConnectOptions};
pub use options::{AuthError, AuthErrorKind, ConnectOptions};

pub mod error;
pub mod header;
Expand Down Expand Up @@ -987,6 +987,12 @@ impl From<io::Error> for ConnectError {
}
}

impl From<AuthError> for ConnectError {
fn from(value: AuthError) -> Self {
value.with_kind(ConnectErrorKind::Authentication)
}
}

/// Retrieves messages from given `subscription` created by [Client::subscribe].
///
/// Implements [futures::stream::Stream] for ergonomic async message processing.
Expand Down Expand Up @@ -1418,6 +1424,7 @@ macro_rules! from_with_timeout {
}
};
}
use crate::error::WithKind;
pub(crate) use from_with_timeout;

#[cfg(test)]
Expand Down
44 changes: 21 additions & 23 deletions async-nats/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@

use crate::auth::Auth;
use crate::connector;
use crate::error::Error;
use crate::{Client, ConnectError, Event, ToServerAddrs};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::engine::Engine;
use futures::Future;
use std::fmt::Formatter;
use std::fmt::{Display, Formatter};
use std::{
fmt,
path::{Path, PathBuf},
Expand Down Expand Up @@ -337,7 +338,7 @@ impl ConnectOptions {
/// let jwt = load_jwt().await?;
/// let nc = async_nats::ConnectOptions::with_jwt(jwt, move |nonce| {
/// let key_pair = key_pair.clone();
/// async move { key_pair.sign(&nonce).map_err(async_nats::AuthError::new) }
/// async move { key_pair.sign(&nonce) }
/// })
/// .connect("localhost")
/// .await?;
Expand Down Expand Up @@ -371,7 +372,7 @@ impl ConnectOptions {
/// let nc = async_nats::ConnectOptions::new()
/// .jwt(jwt, move |nonce| {
/// let key_pair = key_pair.clone();
/// async move { key_pair.sign(&nonce).map_err(async_nats::AuthError::new) }
/// async move { key_pair.sign(&nonce) }
/// })
/// .connect("localhost")
/// .await?;
Expand All @@ -390,7 +391,7 @@ impl ConnectOptions {
Box::pin(async move {
let sig = sign_cb(nonce.as_bytes().to_vec())
.await
.map_err(AuthError::new)?;
.map_err(|_| AuthError::new(AuthErrorKind::InvalidSignature))?;
Ok(URL_SAFE_NO_PAD.encode(sig))
})
}));
Expand Down Expand Up @@ -506,7 +507,11 @@ impl ConnectOptions {

Ok(self.jwt(jwt.to_owned(), move |nonce| {
let key_pair = key_pair.clone();
async move { key_pair.sign(&nonce).map_err(AuthError::new) }
async move {
key_pair
.sign(&nonce)
.map_err(|_| AuthErrorKind::InvalidKeyPair.into())
}
}))
}

Expand Down Expand Up @@ -899,27 +904,20 @@ impl<A, T> fmt::Debug for CallbackArg1<A, T> {
}
}

/// Error report from signing callback.
// This was needed because std::io::Error isn't Send.
#[derive(Clone, PartialEq)]
pub struct AuthError(String);

impl AuthError {
pub fn new(s: impl ToString) -> Self {
Self(s.to_string())
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AuthErrorKind {
InvalidKeyPair,
InvalidSignature,
}

impl std::fmt::Display for AuthError {
impl Display for AuthErrorKind {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(&format!("AuthError({})", &self.0))
}
}

impl std::fmt::Debug for AuthError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(&format!("AuthError({})", &self.0))
match self {
Self::InvalidKeyPair => f.write_str("invalid keypair"),
Self::InvalidSignature => f.write_str("invalid signature"),
}
}
}

impl std::error::Error for AuthError {}
/// Error report from signing callback.
pub type AuthError = Error<AuthErrorKind>;

0 comments on commit b928510

Please sign in to comment.