Skip to main content

bcrypt_rust/
error.rs

1//! Error and result types for the crate.
2//!
3//! The variant set mirrors the de-facto standard [`bcrypt`
4//! crate](https://crates.io/crates/bcrypt) (0.19) so switching crates is a
5//! mechanical change; the one deliberate difference is the payload of
6//! [`BcryptError::Rand`], which is this crate's own [`EntropyError`] because
7//! OS entropy here is hand-declared rather than pulled from `getrandom`.
8
9use core::fmt;
10
11/// Convenience alias mirroring the `bcrypt` crate.
12pub type BcryptResult<T> = Result<T, BcryptError>;
13
14/// Everything that can go wrong in the public API.
15///
16/// No variant carries attacker-controlled content, so `Display` is safe to
17/// log on an authentication path.
18#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum BcryptError {
21    /// Cost outside the allowed range `4..=31` (bcrypt's `log2(rounds)`).
22    CostNotAllowed(u32),
23    /// The hash string is malformed; the payload names the failing part.
24    InvalidHash(&'static str),
25    /// A `non_truncating_*` function received a password of 72 bytes or more.
26    /// The payload is the input length including the terminator bcrypt appends.
27    Truncation(usize),
28    /// The OS CSPRNG could not produce a salt.
29    Rand(EntropyError),
30    /// A batch function received `passwords` and `salts` slices of different
31    /// lengths. Batch outputs are position-preserving, so a mismatch has no
32    /// meaningful result and is rejected up front.
33    ///
34    /// In [`verify_many`](crate::verify_many), which takes `hashes` rather
35    /// than `salts`, the `salts` field reports the `hashes` length.
36    BatchLengthMismatch {
37        /// Number of passwords passed.
38        passwords: usize,
39        /// Number of salts (or hashes, for `verify_many`) passed.
40        salts: usize,
41    },
42}
43
44/// Failure of the OS entropy source.
45///
46/// Wraps the platform error code where one exists (`errno` on Unix, the
47/// `NTSTATUS`-style status on Windows, the WASI `errno` on wasm); `None` means
48/// the platform reported failure without a code.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct EntropyError {
51    code: Option<i32>,
52}
53
54impl EntropyError {
55    // Only `crate::random` (std-gated) ever constructs an entropy error;
56    // without `std` this constructor is legitimately unused.
57    #[cfg_attr(not(feature = "std"), allow(dead_code))]
58    pub(crate) const fn new(code: Option<i32>) -> Self {
59        EntropyError { code }
60    }
61
62    /// The platform error code, if the platform provided one.
63    #[inline]
64    #[must_use]
65    pub const fn code(self) -> Option<i32> {
66        self.code
67    }
68}
69
70impl fmt::Display for EntropyError {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self.code {
73            Some(code) => write!(f, "OS entropy source failed (code {code})"),
74            None => f.write_str("OS entropy source failed"),
75        }
76    }
77}
78
79impl fmt::Display for BcryptError {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        match self {
82            BcryptError::CostNotAllowed(cost) => {
83                write!(f, "cost {cost} not allowed: must be in 4..=31")
84            }
85            BcryptError::InvalidHash(part) => write!(f, "invalid hash: {part}"),
86            BcryptError::Truncation(len) => {
87                write!(f, "password is {len} bytes; bcrypt truncates at 72")
88            }
89            BcryptError::Rand(err) => write!(f, "{err}"),
90            BcryptError::BatchLengthMismatch { passwords, salts } => {
91                write!(
92                    f,
93                    "batch length mismatch: {passwords} passwords but {salts} salts"
94                )
95            }
96        }
97    }
98}
99
100#[cfg(feature = "std")]
101impl std::error::Error for EntropyError {}
102
103#[cfg(feature = "std")]
104impl std::error::Error for BcryptError {
105    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
106        match self {
107            BcryptError::Rand(err) => Some(err),
108            _ => None,
109        }
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    // `no_std`: `ToString` is not in the prelude, so pull it from `alloc`.
117    use alloc::string::ToString;
118
119    #[test]
120    fn display_is_informative() {
121        assert_eq!(
122            BcryptError::CostNotAllowed(3).to_string(),
123            "cost 3 not allowed: must be in 4..=31"
124        );
125        assert!(BcryptError::Truncation(73).to_string().contains("72"));
126        assert_eq!(
127            BcryptError::BatchLengthMismatch {
128                passwords: 3,
129                salts: 2
130            }
131            .to_string(),
132            "batch length mismatch: 3 passwords but 2 salts"
133        );
134        assert_eq!(EntropyError::new(Some(1)).code(), Some(1));
135        assert!(EntropyError::new(None).to_string().contains("failed"));
136    }
137}