NonceError

Enum NonceError 

Source
pub enum NonceError {
    DuplicateNonce,
    InvalidSignature,
    TimestampOutOfWindow,
    StorageError(Box<dyn Error + Send + Sync>),
    CryptoError(String),
}
Expand description

Error types that can occur during nonce authentication operations.

This enum represents all possible errors that can occur when using the nonce authentication library. Each variant corresponds to a specific failure mode in the authentication process.

§Error Categories

  • Authentication Errors: DuplicateNonce, InvalidSignature, TimestampOutOfWindow
  • System Errors: StorageError, CryptoError

§Error Codes

Each error variant has a stable string code that can be used for programmatic error handling:

use nonce_auth::NonceError;

let error = NonceError::DuplicateNonce;
assert_eq!(error.code(), "duplicate_nonce");

§Example

use nonce_auth::{CredentialBuilder, CredentialVerifier, NonceError, storage::MemoryStorage};
use hmac::Mac;
use std::sync::Arc;

let storage = Arc::new(MemoryStorage::new());
let payload = b"test payload";
let credential = CredentialBuilder::new(b"secret").sign(payload)?;

// Handle different error types
match CredentialVerifier::new(storage)
    .with_secret(b"secret")
    .verify_with(&credential, |mac| {
        mac.update(credential.timestamp.to_string().as_bytes());
        mac.update(credential.nonce.as_bytes());
        mac.update(payload);
    })
    .await
{
    Ok(()) => println!("Request verified"),
    Err(NonceError::DuplicateNonce) => println!("Nonce already used"),
    Err(NonceError::InvalidSignature) => println!("Invalid signature"),
    Err(NonceError::TimestampOutOfWindow) => println!("Request too old"),
    Err(e) => println!("Other error: {e}"),
}

Variants§

§

DuplicateNonce

The nonce has already been used and cannot be reused.

This error occurs when attempting to use a nonce that has already been consumed. This is the primary mechanism for preventing replay attacks.

§When This Occurs

  • The same signed request is sent twice
  • A malicious actor attempts to replay a captured request
  • Network issues cause duplicate request delivery

§Resolution

A new signed request should be generated with a fresh nonce.

§

InvalidSignature

The HMAC signature verification failed.

This error occurs when the provided signature doesn’t match the expected signature calculated during verification. This indicates either a tampered request or mismatched secrets.

§When This Occurs

  • Different secret keys are being used for signing and verification
  • The request has been tampered with in transit
  • There’s a bug in the signature generation/verification logic
  • The timestamp or nonce values have been modified

§Resolution

  • Verify that the same secret key is used for signing and verification
  • Check for request tampering or transmission errors
  • Ensure proper signature generation during credential creation
§

TimestampOutOfWindow

The request timestamp is outside the allowed time window.

This error occurs when the timestamp in the signed request is either too old or too far in the future compared to the current current time, exceeding the configured time window.

§When This Occurs

  • System clocks are significantly out of sync
  • Network delays cause old requests to arrive late
  • The time window is configured too strictly
  • A malicious actor attempts to use very old captured requests

§Resolution

  • Synchronize system clocks (e.g., using NTP)
  • Increase the time window if appropriate for your use case
  • Generate fresh requests closer to when they’ll be sent
§

StorageError(Box<dyn Error + Send + Sync>)

A storage operation failed.

This error occurs when there’s a problem with the underlying storage backend operations, such as connection issues, disk space problems, or corruption. This applies to all storage backends including memory, SQLite, Redis, and others.

§When This Occurs

  • Storage backend is unavailable or unreachable
  • Database file is corrupted or inaccessible (SQLite)
  • Redis server connection issues (Redis)
  • Insufficient disk space for storage operations
  • Storage backend is locked by another process
  • File permission issues (file-based storage)

§Resolution

  • Check storage backend availability and connectivity
  • Verify storage permissions and disk space
  • Ensure proper storage initialization
  • Check for competing storage access
§

CryptoError(String)

A cryptographic operation failed.

This error occurs when there’s a problem with the HMAC signature generation or verification process, typically due to invalid key material or system-level crypto issues.

§When This Occurs

  • Invalid or corrupted secret key
  • System-level cryptographic library issues
  • Memory allocation failures during crypto operations

§Resolution

  • Verify the secret key is valid and properly formatted
  • Check system cryptographic library installation
  • Ensure sufficient system resources

Implementations§

Source§

impl NonceError

Source

pub fn code(&self) -> &'static str

Returns a stable string code for this error that can be used for programmatic error handling.

The error codes are guaranteed to remain stable across versions, making them suitable for use in error handling logic, logging, monitoring, and API responses.

§Error Codes
  • duplicate_nonce: Nonce has already been used
  • invalid_signature: HMAC signature verification failed
  • timestamp_out_of_window: Request timestamp is outside allowed window
  • storage_error: Storage backend operation failed
  • crypto_error: Cryptographic operation failed
§Example
use nonce_auth::NonceError;

let error = NonceError::DuplicateNonce;
assert_eq!(error.code(), "duplicate_nonce");

match error.code() {
    "duplicate_nonce" => println!("Replay attack detected"),
    "invalid_signature" => println!("Authentication failed"),
    "storage_error" => println!("Storage backend issue"),
    _ => println!("Other error"),
}
Source

pub fn from_storage_error<E>(error: E) -> Self
where E: Error + Send + Sync + 'static,

Creates a new StorageError from any error that implements the standard library’s Error trait.

This is a convenience method for creating storage errors while preserving the original error information. The original error will be available through the source() method.

§Example
use nonce_auth::NonceError;
use std::io;
use std::error::Error;

let io_error = io::Error::new(io::ErrorKind::PermissionDenied, "File access denied");
let nonce_error = NonceError::from_storage_error(io_error);

assert_eq!(nonce_error.code(), "storage_error");
assert!(nonce_error.source().is_some());
Source

pub fn from_storage_message<S: Into<String>>(message: S) -> Self

Creates a new StorageError from a string message.

This method is useful when you need to create a storage error from a string without an underlying error type.

§Example
use nonce_auth::NonceError;

let error = NonceError::from_storage_message("Connection timeout");
assert_eq!(error.code(), "storage_error");
Source

pub fn is_temporary(&self) -> bool

Returns true if this is a temporary error that might succeed if retried.

Temporary errors are typically system-level issues like database connectivity problems or transient resource constraints. Authentication errors like InvalidSignature or DuplicateNonce are not considered temporary.

§Example
use nonce_auth::NonceError;

let auth_error = NonceError::InvalidSignature;
let db_error = NonceError::from_storage_message("Connection timeout");

assert!(!auth_error.is_temporary());
assert!(db_error.is_temporary());
Source

pub fn is_authentication_error(&self) -> bool

Returns true if this is an authentication-related error.

Authentication errors indicate issues with the credential verification process, as opposed to system-level errors.

§Example
use nonce_auth::NonceError;

let auth_error = NonceError::InvalidSignature;
let system_error = NonceError::from_storage_message("Connection timeout");

assert!(auth_error.is_authentication_error());
assert!(!system_error.is_authentication_error());
Source

pub fn is_client_error(&self) -> bool

Returns true if this error represents a request-side issue.

Request errors indicate problems with the request that should be fixed before retrying.

§Example
use nonce_auth::NonceError;

let request_error = NonceError::InvalidSignature;
let system_error = NonceError::from_storage_message("Connection failed");

assert!(request_error.is_client_error());
assert!(!system_error.is_client_error());
Source

pub fn is_server_error(&self) -> bool

Returns true if this error represents a system-side issue.

System errors indicate problems with the system that are not the request’s fault and may be temporary.

§Example
use nonce_auth::NonceError;

let system_error = NonceError::from_storage_message("Connection failed");
let request_error = NonceError::InvalidSignature;

assert!(system_error.is_server_error());
assert!(!request_error.is_server_error());

Trait Implementations§

Source§

impl Debug for NonceError

Source§

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

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

impl Display for NonceError

Source§

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

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

impl Error for NonceError

Source§

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

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

fn description(&self) -> &str

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

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

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
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

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
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.