decane 1.1.0

Server-side SDK for Decane Connect Kit: verify access tokens, sign users in, per-user records and server-side wallet creation.
Documentation
//! Error types.
//!
//! Three failure domains, one enum:
//!
//! - Token **verification** failures are [`DecaneError::Auth`]: bad signature,
//!   expired, missing `uid`, or a `project_id` that does not match the
//!   configured app id. Fail-closed middleware turns these into a 401.
//! - Backend **API** failures are [`DecaneError::Api`], carrying the backend's
//!   error code and the HTTP status (0 when the request never got a response).
//! - **Configuration** mistakes (a missing key, an empty argument, a malformed
//!   verification key) are [`DecaneError::Config`]. These are raised before any
//!   network call.

use std::convert::Infallible;
use std::fmt;
use std::str::FromStr;

/// `Result` with [`DecaneError`] as the default error type.
pub type Result<T, E = DecaneError> = std::result::Result<T, E>;

/// Why an access token was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AuthErrorReason {
    /// The signature, format or expiry was rejected.
    InvalidToken,
    /// The token verified but carries no `uid` claim.
    MissingUid,
    /// The token's `project_id` differs from the configured app id.
    ProjectMismatch,
}

impl AuthErrorReason {
    /// The reason as decane-node spells it: `invalid_token`, `missing_uid`,
    /// `project_mismatch`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::InvalidToken => "invalid_token",
            Self::MissingUid => "missing_uid",
            Self::ProjectMismatch => "project_mismatch",
        }
    }
}

impl fmt::Display for AuthErrorReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

macro_rules! api_error_codes {
    ($( $(#[$meta:meta])* $variant:ident => $wire:literal ),* $(,)?) => {
        /// Backend error codes surfaced by [`DecaneError::Api`].
        ///
        /// Most come straight from the backend's `{ error: { code } }`
        /// envelope; [`RateLimited`](Self::RateLimited), [`Unknown`](Self::Unknown)
        /// and [`NetworkError`](Self::NetworkError) are synthesised client-side
        /// when the envelope is absent. A code this version does not know by
        /// name arrives as [`Other`](Self::Other) with the wire string intact.
        ///
        /// [`Display`](fmt::Display) and [`FromStr`] round-trip the wire string.
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        pub enum ApiErrorCode {
            $( $(#[$meta])* $variant, )*
            /// A code this SDK does not know by name; the wire string is kept.
            Other(String),
        }

        impl ApiErrorCode {
            /// The wire string, e.g. `INVALID_CODE`.
            pub fn as_str(&self) -> &str {
                match self {
                    $( Self::$variant => $wire, )*
                    Self::Other(code) => code,
                }
            }
        }

        impl FromStr for ApiErrorCode {
            type Err = Infallible;

            fn from_str(s: &str) -> std::result::Result<Self, Infallible> {
                Ok(match s {
                    $( $wire => Self::$variant, )*
                    other => Self::Other(other.to_owned()),
                })
            }
        }
    };
}

api_error_codes! {
    /// Email or phone OTP wrong or expired.
    InvalidCode => "INVALID_CODE",
    /// Provider token rejected (Google, KingsChat, email).
    AuthFailed => "AUTH_FAILED",
    /// Custom-auth JWT rejected.
    InvalidToken => "INVALID_TOKEN",
    /// The project has no enabled custom-auth provider.
    NoProvider => "NO_PROVIDER",
    /// More than one provider is enabled and no `provider_id` was given.
    AmbiguousProvider => "AMBIGUOUS_PROVIDER",
    /// The custom-auth JWT lacks the configured identity claim.
    MissingClaim => "MISSING_CLAIM",
    /// The request was malformed.
    BadRequest => "BAD_REQUEST",
    /// The `X-API-Key` was refused.
    InvalidApiKey => "INVALID_API_KEY",
    /// `X-App-Id` does not match the API key's project.
    AppIdMismatch => "APP_ID_MISMATCH",
    /// Phone sign-in on a deployment with no SMS provider.
    SmsNotConfigured => "SMS_NOT_CONFIGURED",
    /// The project has no KingsChat client id.
    KingsChatNotConfigured => "KINGSCHAT_NOT_CONFIGURED",
    /// Upstream KingsChat unreachable (HTTP 503).
    KingsChatUnavailable => "KINGSCHAT_UNAVAILABLE",
    /// The revocation could not be recorded.
    RevokeFailed => "REVOKE_FAILED",
    /// A preferences or metadata write broke the record rules (see [`Record`](crate::Record)).
    InvalidRecord => "INVALID_RECORD",
    /// No such user in this project (record methods).
    NotFound => "NOT_FOUND",
    /// The token or project secret was refused.
    Unauthorized => "UNAUTHORIZED",
    /// Server-side creation is off for this project.
    ServerWalletsDisabled => "SERVER_WALLETS_DISABLED",
    /// `create_user`: the identifier is malformed or names an unknown provider.
    InvalidIdentifier => "INVALID_IDENTIFIER",
    /// `create_user_wallet`: the user already has a wallet.
    WalletExists => "WALLET_EXISTS",
    /// The wallet is frozen; nothing can be created or replaced.
    WalletFrozen => "WALLET_FROZEN",
    /// `link_external_login`: the login already opens another account.
    LoginInUse => "LOGIN_IN_USE",
    /// The signing enclave could not be reached (503); retry.
    EnclaveUnavailable => "ENCLAVE_UNAVAILABLE",
    /// Creation attempts for this user are capped (429); retry in an hour.
    RetryLater => "RETRY_LATER",
    /// HTTP 429 with no error envelope.
    RateLimited => "RATE_LIMITED",
    /// A non-2xx response with an unparseable body.
    Unknown => "UNKNOWN",
    /// The request itself failed; `status` is 0.
    NetworkError => "NETWORK_ERROR",
}

impl fmt::Display for ApiErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for ApiErrorCode {
    fn from(s: &str) -> Self {
        s.parse().unwrap_or_else(|never| match never {})
    }
}

/// The underlying error behind a [`DecaneError`], when there is one.
pub type Source = Box<dyn std::error::Error + Send + Sync + 'static>;

/// Everything this crate can fail with.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DecaneError {
    /// An access token cannot be trusted.
    #[error("{message}")]
    Auth {
        /// Machine-readable reason.
        reason: AuthErrorReason,
        /// Human-readable message.
        message: String,
        /// The underlying JWT error, when the failure originated there.
        #[source]
        source: Option<Source>,
    },
    /// A call to the Decane backend failed.
    #[error("{message} ({code}, HTTP {status})")]
    Api {
        /// The backend's error code, or a synthesised one.
        code: ApiErrorCode,
        /// HTTP status; 0 when the request never got a response.
        status: u16,
        /// The backend's message, or a synthesised one.
        message: String,
        /// The transport error, when the request never got a response.
        #[source]
        source: Option<Source>,
    },
    /// The client is misconfigured or was called with an empty argument.
    /// Raised before any network call.
    #[error("{0}")]
    Config(String),
}

impl DecaneError {
    pub(crate) fn auth(reason: AuthErrorReason, message: impl Into<String>) -> Self {
        Self::Auth {
            reason,
            message: message.into(),
            source: None,
        }
    }

    pub(crate) fn config(message: impl Into<String>) -> Self {
        Self::Config(message.into())
    }

    /// True for [`DecaneError::Auth`]: the token was refused.
    pub fn is_auth(&self) -> bool {
        matches!(self, Self::Auth { .. })
    }

    /// The verification reason, for [`DecaneError::Auth`].
    pub fn auth_reason(&self) -> Option<AuthErrorReason> {
        match self {
            Self::Auth { reason, .. } => Some(*reason),
            _ => None,
        }
    }

    /// The backend error code, for [`DecaneError::Api`].
    pub fn api_code(&self) -> Option<&ApiErrorCode> {
        match self {
            Self::Api { code, .. } => Some(code),
            _ => None,
        }
    }

    /// The HTTP status, for [`DecaneError::Api`].
    pub fn status(&self) -> Option<u16> {
        match self {
            Self::Api { status, .. } => Some(*status),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn api_error_code_round_trips_the_wire_string() {
        let known: ApiErrorCode = "KINGSCHAT_UNAVAILABLE".parse().unwrap();
        assert_eq!(known, ApiErrorCode::KingsChatUnavailable);
        assert_eq!(known.to_string(), "KINGSCHAT_UNAVAILABLE");

        let other: ApiErrorCode = "SOMETHING_NEW".parse().unwrap();
        assert_eq!(other, ApiErrorCode::Other("SOMETHING_NEW".into()));
        assert_eq!(other.to_string(), "SOMETHING_NEW");
    }

    #[test]
    fn auth_reason_matches_node_spelling() {
        assert_eq!(
            AuthErrorReason::ProjectMismatch.to_string(),
            "project_mismatch"
        );
        assert_eq!(AuthErrorReason::MissingUid.as_str(), "missing_uid");
        assert_eq!(AuthErrorReason::InvalidToken.as_str(), "invalid_token");
    }
}