CredentialVerifier

Struct CredentialVerifier 

Source
pub struct CredentialVerifier { /* private fields */ }
Expand description

Verifier for cryptographic credentials.

CredentialVerifier provides a fluent interface for configuring and verifying NonceCredential instances. It supports various verification methods including dynamic secret resolution and context isolation.

This verifier is Send + Sync and can be safely shared across threads using Arc<CredentialVerifier>, making it suitable for server environments with high concurrency requirements.

Implementations§

Source§

impl CredentialVerifier

Source

pub fn new(storage: Arc<dyn NonceStorage>) -> Self

Creates a new CredentialVerifier with default settings.

§Arguments
  • storage - The storage backend for nonce tracking
§Default Settings
  • Storage TTL: 5 minutes
  • Time window: 1 minute
  • Signature algorithm: HMAC-SHA256
§Example
use nonce_auth::{CredentialVerifier, storage::MemoryStorage};
use std::sync::Arc;

let storage = Arc::new(MemoryStorage::new());
let verifier = CredentialVerifier::new(storage);
Source

pub fn with_secret(self, secret: &[u8]) -> Self

Sets the shared secret for verification.

Source

pub fn with_context(self, context: Option<&str>) -> Self

Sets the context for nonce isolation.

Contexts allow the same nonce to be used across different scopes while still preventing replay attacks within each scope.

Source

pub fn with_storage_ttl(self, storage_ttl: Duration) -> Self

Sets the storage TTL (time-to-live) for nonce records.

This determines how long nonces are kept in storage before they can be cleaned up. This should be longer than the time window to ensure nonces aren’t reused.

§Arguments
  • storage_ttl - Duration for which nonces should be stored
§Example
let verifier = CredentialVerifier::new(storage)
    .with_storage_ttl(Duration::from_secs(600)); // 10 minutes
Source

pub fn with_time_window(self, time_window: Duration) -> Self

Sets the time window for timestamp validation.

Source

pub fn with_secret_provider<P, F>(self, provider: P) -> Self
where P: for<'a> Fn(Option<&'a str>) -> F + Send + Sync + 'static, F: Future<Output = Result<Vec<u8>, NonceError>> + Send + 'static,

Sets a dynamic secret provider for verification.

This allows secrets to be resolved dynamically based on the context, enabling multi-user scenarios where each user has a different secret.

§Arguments
  • provider - Function that resolves the secret based on context
§Example
let verifier = CredentialVerifier::new(storage)
    .with_context(Some("user123"))
    .with_secret_provider(|context| {
        let owned_context = context.map(|s| s.to_owned());
        async move {
            match owned_context.as_deref() {
                Some("user123") => Ok(b"user123_secret".to_vec()),
                Some("user456") => Ok(b"user456_secret".to_vec()),
                _ => Err(NonceError::CryptoError("Unknown user".to_string())),
            }
        }
    });
Source

pub async fn verify( self, credential: &NonceCredential, payload: &[u8], ) -> Result<(), NonceError>

Verifies a credential with a standard payload.

This method performs the complete verification process:

  1. Validates the timestamp is within the time window
  2. Checks that the nonce hasn’t been used before
  3. Verifies the HMAC signature
  4. Stores the nonce to prevent replay attacks
§Arguments
  • credential - The credential to verify
  • payload - The data that was signed
§Returns

Ok(()) if verification succeeds, or a NonceError if verification fails.

§Example
let result = CredentialVerifier::new(storage)
    .with_secret(b"shared_secret")
    .verify(&credential, b"payload")
    .await?;
Source

pub async fn verify_structured( self, credential: &NonceCredential, components: &[&[u8]], ) -> Result<(), NonceError>

Verifies a credential with structured data components.

This method verifies credentials that were created using sign_structured(). The components must be provided in the same order as during signing.

§Arguments
  • credential - The credential to verify
  • components - Array of data components in the same order as signing
§Example
let result = CredentialVerifier::new(storage)
    .with_secret(b"shared_secret")
    .verify_structured(&credential, &[b"user123", b"action", b"data"])
    .await?;
Source

pub async fn verify_with<F>( self, credential: &NonceCredential, mac_fn: F, ) -> Result<(), NonceError>
where F: FnOnce(&mut Hmac<Sha256>),

Verifies a credential using a custom MAC construction function.

This method provides maximum flexibility by allowing custom MAC verification that matches the signing process used with sign_with().

§Arguments
  • credential - The credential to verify
  • mac_fn - Function that constructs the MAC for verification
§Example
let result = CredentialVerifier::new(storage)
    .with_secret(b"shared_secret")
    .verify_with(&credential, |mac| {
        mac.update(b"prefix:");
        mac.update(credential.timestamp.to_string().as_bytes());
        mac.update(b":nonce:");
        mac.update(credential.nonce.as_bytes());
        mac.update(b":custom_data");
    })
    .await?;

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, 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.