Skip to main content

AuthError

Enum AuthError 

Source
pub enum AuthError {
Show 43 variants Configuration { message: String, source: Option<Box<dyn Error + Send + Sync>>, help: Option<String>, docs_url: Option<String>, suggested_fix: Option<String>, }, AuthMethod { method: String, message: String, help: Option<String>, docs_url: Option<String>, suggested_fix: Option<String>, }, Token(TokenError), Permission(PermissionError), Storage(StorageError), Network(Error), Json(Error), Jwt(Error), Yaml(Error), Toml(Error), Io(Error), Cli(String), SystemTime(SystemTimeError), RateLimit { message: String, }, TooManyConcurrentSessions, Mfa(MfaError), DeviceFlow(DeviceFlowError), OAuthProvider(OAuthProviderError), PasswordVerification(String), PasswordHashing(String), UserNotFound, InvalidInput(String), HardwareToken(String), BackupCodeVerification(String), BackupCodeHashing(String), InvalidSecret, UserProfile { message: String, }, InvalidCredential { credential_type: String, message: String, }, Timeout { timeout_seconds: u64, }, ProviderNotConfigured { provider: String, }, Crypto { message: String, }, Validation { message: String, }, Internal { message: String, }, InvalidRequest(String), StepUpRequired { current_level: String, required_level: String, step_up_url: String, }, SessionError(String), Unauthorized(String), TokenGeneration(String), InvalidToken(String), UnsupportedProvider(String), NetworkError(String), ParseError(String), ConfigurationError(String),
}
Expand description

Comprehensive error type covering all authentication and authorization failures.

AuthError provides detailed error information for all aspects of the authentication framework, from configuration issues to runtime failures. Each error variant includes contextual information to aid in debugging and provide appropriate user feedback.

This enhanced error type provides:

  • Actionable error messages with specific suggestions for fixes
  • Documentation links to relevant guides and troubleshooting
  • Contextual help that guides users to solutions
  • Security-aware messaging that doesn’t leak sensitive information

§Error Categories

§Configuration Errors

Errors that occur during framework setup and configuration validation.

§Authentication Errors

Errors related to credential validation and authentication method execution.

§Authorization Errors

Errors related to permission checking and access control.

§Token Errors

JWT token creation, validation, expiration, and lifecycle issues.

§Storage Errors

Database connectivity, query failures, and data persistence issues.

§Network Errors

External service communication, timeouts, and connectivity problems.

§Cryptographic Errors

Encryption, decryption, signing, and other security operation failures.

§Enhanced Error Handling

use auth_framework::AuthError;

// Enhanced error handling with contextual help
match auth_result {
    Err(AuthError::Configuration { message, help, docs_url, .. }) => {
        eprintln!("Configuration Error: {}", message);
        if let Some(help) = help {
            eprintln!("Help: {}", help);
        }
        if let Some(docs) = docs_url {
            eprintln!("See: {}", docs);
        }
    },
    Err(AuthError::InvalidCredential { credential_type, message, .. }) => {
        eprintln!("Invalid {}: {}", credential_type, message);
    },
    // ... handle other error types
    _ => {}
}

§Security Notes

Error messages are carefully crafted to:

  • Provide sufficient detail for debugging and monitoring
  • Avoid exposing sensitive information that could aid attackers
  • Enable security teams to identify potential threats
  • Support compliance and audit requirements
  • Guide users to secure solutions and best practices

Variants§

§

Configuration

Configuration validation and setup errors.

These errors occur when the authentication framework is misconfigured or when configuration validation fails during startup.

Fields

§message: String
§source: Option<Box<dyn Error + Send + Sync>>
§help: Option<String>

Helpful guidance for fixing the issue

§docs_url: Option<String>

Link to relevant documentation

§suggested_fix: Option<String>

Specific fix suggestion with commands or code

§

AuthMethod

Authentication method execution errors.

These errors occur when a specific authentication method fails to execute properly, such as OAuth provider communication failures.

Fields

§method: String
§message: String
§help: Option<String>

Helpful guidance for fixing the issue

§docs_url: Option<String>

Link to relevant documentation

§suggested_fix: Option<String>

Specific fix suggestion

§

Token(TokenError)

Token-related errors

§

Permission(PermissionError)

Permission-related errors

§

Storage(StorageError)

Storage-related errors

§

Network(Error)

Network/HTTP errors

§

Json(Error)

JSON parsing errors

§

Jwt(Error)

JWT errors

§

Yaml(Error)

YAML parsing errors

§

Toml(Error)

TOML parsing errors

§

Io(Error)

IO errors

§

Cli(String)

CLI interaction errors

§

SystemTime(SystemTimeError)

System time errors

§

RateLimit

Rate limiting errors

Fields

§message: String
§

TooManyConcurrentSessions

Session-related errors

§

Mfa(MfaError)

MFA-related errors

§

DeviceFlow(DeviceFlowError)

Device flow errors

§

OAuthProvider(OAuthProviderError)

OAuth provider errors

§

PasswordVerification(String)

The stored password hash does not match the supplied credential.

This typically means the user entered the wrong password. Do not reveal which field (username vs. password) was incorrect to the caller.

§

PasswordHashing(String)

The password hashing algorithm (argon2/bcrypt) encountered an error.

§

UserNotFound

No user record exists for the given identifier.

§

InvalidInput(String)

A request parameter failed validation (e.g. empty username, invalid email format).

§

HardwareToken(String)

A hardware security key (FIDO2 / WebAuthn) operation failed.

§

BackupCodeVerification(String)

A one-time backup code was rejected (already used, incorrect, or expired).

§

BackupCodeHashing(String)

Failed to hash a backup code for secure storage.

§

InvalidSecret

The TOTP or MFA secret is in an invalid format (e.g. not valid Base32).

§

UserProfile

An error occurred while reading or updating a user profile.

Fields

§message: String
§

InvalidCredential

Credential validation errors

Fields

§credential_type: String
§message: String
§

Timeout

An authentication operation did not complete within the allowed window.

Fields

§timeout_seconds: u64
§

ProviderNotConfigured

Provider configuration missing

Fields

§provider: String
§

Crypto

Cryptography errors

Fields

§message: String
§

Validation

Validation errors

Fields

§message: String
§

Internal

Generic internal errors

Fields

§message: String
§

InvalidRequest(String)

Invalid request error

§

StepUpRequired

Step-up authentication required

Fields

§current_level: String
§required_level: String
§step_up_url: String
§

SessionError(String)

A session-layer error (e.g. session not found, session expired, store failure).

§

Unauthorized(String)

The caller lacks valid credentials or the credentials have been revoked.

§

TokenGeneration(String)

Token creation failed at the signing or encoding stage.

Consider using AuthError::token for richer TokenError variants.

§

InvalidToken(String)

👎Deprecated since 0.5.0:

Use AuthError::token(msg) instead — it routes through the structured TokenError hierarchy

Invalid token error.

Prefer AuthError::token which routes through the structured TokenError hierarchy for consistent token error handling.

§

UnsupportedProvider(String)

The named authentication provider is not compiled in or not recognized.

§

NetworkError(String)

👎Deprecated since 0.5.0:

Use AuthError::internal(msg) or let reqwest::Error convert via AuthError::Network instead

Network error with custom message.

Prefer AuthError::Internal with a descriptive message, or let reqwest::Error convert automatically via the From impl on AuthError::Network.

§

ParseError(String)

👎Deprecated since 0.5.0:

Use AuthError::internal(msg) or let serde errors convert via AuthError::Json instead

Parse error with custom message.

Prefer AuthError::Internal with a descriptive message, or let serde_json::Error convert automatically via the From impl on AuthError::Json.

§

ConfigurationError(String)

👎Deprecated since 0.5.0:

Use AuthError::config(msg) instead — it provides richer context fields

Configuration error with custom message.

Prefer AuthError::config or AuthError::config_with_help which carry richer context (help text, docs URL, suggested fix).

Implementations§

Source§

impl AuthError

Source

pub fn config(message: impl Into<String>) -> Self

Create a new configuration error.

§Example
use auth_framework::AuthError;

let err = AuthError::config("Missing database URL");
assert!(err.to_string().contains("Missing database URL"));
Source

pub fn config_with_help( message: impl Into<String>, help: impl Into<String>, suggested_fix: Option<String>, ) -> Self

Create a configuration error with helpful context.

Includes a human-readable help string and an optional suggested_fix that can be displayed by CLI tools or IDE integrations.

§Example
use auth_framework::AuthError;

let err = AuthError::config_with_help(
    "JWT secret not set",
    "Set the JWT_SECRET environment variable",
    Some("export JWT_SECRET=$(openssl rand -hex 32)".into()),
);
assert!(err.to_string().contains("JWT secret not set"));
Source

pub fn jwt_secret_too_short(current_length: usize) -> Self

Create a JWT secret validation error with helpful guidance.

§Example
use auth_framework::AuthError;

let err = AuthError::jwt_secret_too_short(16);
assert!(err.to_string().contains("16 characters"));
Source

pub fn production_memory_storage() -> Self

Create a production environment error with guidance.

§Example
use auth_framework::AuthError;

let err = AuthError::production_memory_storage();
assert!(err.to_string().contains("Memory storage"));
Source

pub fn auth_method( method: impl Into<String>, message: impl Into<String>, ) -> Self

Create a new auth method error.

§Example
use auth_framework::AuthError;

let err = AuthError::auth_method("oauth2", "token endpoint unreachable");
assert!(err.to_string().contains("oauth2"));
Source

pub fn auth_method_with_help( method: impl Into<String>, message: impl Into<String>, help: impl Into<String>, suggested_fix: Option<String>, ) -> Self

Create an auth method error with helpful context.

§Example
use auth_framework::AuthError;

let err = AuthError::auth_method_with_help(
    "saml",
    "certificate expired",
    "Renew the SAML signing certificate",
    Some("openssl x509 -req -in cert.csr -signkey key.pem -out cert.pem".into()),
);
assert!(err.to_string().contains("saml"));
Source

pub fn rate_limit(message: impl Into<String>) -> Self

Create a new rate limit error.

§Example
use auth_framework::AuthError;

let err = AuthError::rate_limit("too many login attempts");
assert!(err.to_string().contains("too many login attempts"));
Source

pub fn crypto(message: impl Into<String>) -> Self

Create a new crypto error.

§Example
use auth_framework::AuthError;

let err = AuthError::crypto("HMAC key too short");
assert!(err.to_string().contains("HMAC key too short"));
Source

pub fn validation(message: impl Into<String>) -> Self

Create a new validation error.

§Example
use auth_framework::AuthError;

let err = AuthError::validation("email format invalid");
assert!(err.to_string().contains("email format invalid"));
Source

pub fn internal(message: impl Into<String>) -> Self

Create a new internal error.

§Example
use auth_framework::AuthError;

let err = AuthError::internal("unexpected state");
assert!(err.to_string().contains("unexpected state"));
Source

pub fn authorization(message: impl Into<String>) -> Self

Create an authorization error.

§Example
use auth_framework::AuthError;

let err = AuthError::authorization("insufficient privileges");
assert!(err.to_string().contains("insufficient privileges"));
Source

pub fn access_denied(message: impl Into<String>) -> Self

Create an access denied error.

§Example
use auth_framework::AuthError;

let err = AuthError::access_denied("admin role required");
assert!(err.to_string().contains("admin role required"));
Source

pub fn token(message: impl Into<String>) -> Self

Create a token error.

§Example
use auth_framework::AuthError;

let err = AuthError::token("signature mismatch");
assert!(err.to_string().contains("signature mismatch"));
Source

pub fn device_flow(error: DeviceFlowError) -> Self

Create a device flow error.

§Example
use auth_framework::errors::{AuthError, DeviceFlowError};

let err = AuthError::device_flow(DeviceFlowError::ExpiredToken);
assert!(err.to_string().contains("expired"));
Source

pub fn oauth_provider(error: OAuthProviderError) -> Self

Create an OAuth provider error.

§Example
use auth_framework::errors::{AuthError, OAuthProviderError};

let err = AuthError::oauth_provider(OAuthProviderError::InvalidRedirectUri);
assert!(err.to_string().contains("redirect"));
Source

pub fn user_profile(message: impl Into<String>) -> Self

Create a user profile error.

§Example
use auth_framework::AuthError;

let err = AuthError::user_profile("email already in use");
assert!(err.to_string().contains("email already in use"));
Source

pub fn invalid_credential( credential_type: impl Into<String>, message: impl Into<String>, ) -> Self

Create an invalid credential error.

§Example
use auth_framework::AuthError;

let err = AuthError::invalid_credential("password", "too short");
assert!(err.to_string().contains("password"));
Source

pub fn timeout(timeout_seconds: u64) -> Self

Create a timeout error.

§Example
use auth_framework::AuthError;

let err = AuthError::timeout(30);
assert!(err.to_string().contains("30"));
Source

pub fn provider_not_configured(provider: impl Into<String>) -> Self

Create a provider not configured error.

§Example
use auth_framework::AuthError;

let err = AuthError::provider_not_configured("github");
assert!(err.to_string().contains("github"));
Source

pub fn rate_limited(message: impl Into<String>) -> Self

Create a rate limited error (alias for rate_limit).

§Example
use auth_framework::AuthError;

let err = AuthError::rate_limited("5 requests per second exceeded");
assert!(err.to_string().contains("5 requests"));
Source

pub fn configuration(message: impl Into<String>) -> Self

Create a configuration error (alias for config).

§Example
use auth_framework::AuthError;

let err = AuthError::configuration("invalid issuer URL");
assert!(err.to_string().contains("invalid issuer URL"));
Source

pub fn http_status_code(&self) -> u16

Return the HTTP status code that best represents this error.

This is framework-agnostic and works without enabling any web framework feature flag. Web framework integrations (actix-web, axum, …) use this internally but you can also call it directly when building custom response types.

§Example
use auth_framework::AuthError;

assert_eq!(AuthError::rate_limit("slow down").http_status_code(), 429);
assert_eq!(AuthError::internal("oops").http_status_code(), 500);
assert_eq!(AuthError::token("bad jwt").http_status_code(), 401);
Source

pub fn is_retryable(&self) -> bool

Whether this error is transient and the operation may succeed on retry.

Returns true for rate-limit, timeout, network, and storage connectivity errors. Returns false for authentication failures, validation errors, and other permanent conditions.

§Example
use auth_framework::AuthError;

assert!(AuthError::rate_limit("too fast").is_retryable());
assert!(AuthError::timeout(30).is_retryable());
assert!(!AuthError::token("invalid").is_retryable());
assert!(!AuthError::validation("bad input").is_retryable());
Source

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

A short, stable, machine-readable code for this error category.

Useful for API responses, metrics labels, and log filtering. These codes are stable across patch releases.

§Example
use auth_framework::AuthError;

assert_eq!(AuthError::rate_limit("nope").error_code(), "rate_limit");
assert_eq!(AuthError::token("bad").error_code(), "invalid_token");
assert_eq!(AuthError::config("bad").error_code(), "configuration");
Source

pub fn is_client_error(&self) -> bool

Whether this is a client-side error (4xx status code).

§Example
use auth_framework::AuthError;

assert!(AuthError::validation("bad").is_client_error());
assert!(!AuthError::internal("oops").is_client_error());
Source

pub fn is_server_error(&self) -> bool

Whether this is a server-side error (5xx status code).

§Example
use auth_framework::AuthError;

assert!(AuthError::internal("oops").is_server_error());
assert!(!AuthError::validation("bad").is_server_error());

Trait Implementations§

Source§

impl Debug for AuthError

Source§

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

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

impl Display for AuthError

Source§

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

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

impl Error for AuthError

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

impl From<AuthError> for ApiResponse<()>

Convert an AuthError into an appropriate API error response.

Maps error variants to HTTP-semantic error codes:

  • TokenINVALID_TOKEN
  • ValidationVALIDATION_ERROR
  • AuthMethodINVALID_CREDENTIALS
  • UserNotFoundNOT_FOUND
  • PermissionFORBIDDEN
  • RateLimitRATE_LIMITED
  • everything else → SERVER_ERROR
Source§

fn from(error: AuthError) -> Self

Converts to this type from the input type.
Source§

impl From<Box<dyn Error>> for AuthError

Source§

fn from(error: Box<dyn Error>) -> Self

Converts to this type from the input type.
Source§

impl From<Box<dyn Error + Sync + Send>> for AuthError

Source§

fn from(error: Box<dyn Error + Send + Sync>) -> Self

Converts to this type from the input type.
Source§

impl From<DeviceFlowError> for AuthError

Source§

fn from(source: DeviceFlowError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for AuthError

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for AuthError

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for AuthError

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for AuthError

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for AuthError

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for AuthError

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<MfaError> for AuthError

Source§

fn from(source: MfaError) -> Self

Converts to this type from the input type.
Source§

impl From<OAuthProviderError> for AuthError

Source§

fn from(source: OAuthProviderError) -> Self

Converts to this type from the input type.
Source§

impl From<PermissionError> for AuthError

Source§

fn from(source: PermissionError) -> Self

Converts to this type from the input type.
Source§

impl From<StorageError> for AuthError

Source§

fn from(source: StorageError) -> Self

Converts to this type from the input type.
Source§

impl From<SystemTimeError> for AuthError

Source§

fn from(source: SystemTimeError) -> Self

Converts to this type from the input type.
Source§

impl From<TenantRegistryError> for AuthError

Source§

fn from(err: TenantRegistryError) -> Self

Converts to this type from the input type.
Source§

impl From<TokenError> for AuthError

Source§

fn from(source: TokenError) -> 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
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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> ToStringFallible for T
where T: Display,

Source§

fn try_to_string(&self) -> Result<String, TryReserveError>

ToString::to_string, but without panic on OOM.

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

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more