Skip to main content

utopia_auth/
lib.rs

1//! The password hash algorithms of `utopia-php/auth` (`Utopia\Auth\Hashes`) that PHP
2//! itself does not provide: the scrypt KDF of the PECL `scrypt` extension, Firebase's
3//! modified scrypt, and phpass's portable hashes. The rest (`password_hash()`,
4//! `password_verify()`, `crypt()`, `hash()`) are PHP's own functions, ported in `php-std`.
5//!
6//! Every function here returns what PHP returns for the same input, byte for byte, including
7//! where PHP fails: [`scrypt::scrypt`] fails as `scrypt()` does, with its `Error`s, its
8//! warnings and its `false`.
9
10pub mod firebase;
11pub mod phpass;
12pub mod scrypt;
13
14// Hashing, proofs, session stores, JWTs, OAuth2 values and passkeys as Rust values, for
15// Appwrite's Rust services (`service`). The PHP extension uses the checks above alone.
16#[cfg(feature = "service")]
17mod error;
18#[cfg(feature = "service")]
19mod hash;
20#[cfg(feature = "service")]
21pub mod hashes;
22#[cfg(feature = "service")]
23pub mod jwt;
24#[cfg(feature = "service")]
25pub mod oauth2;
26#[cfg(feature = "service")]
27mod options;
28#[cfg(feature = "service")]
29pub mod passkeys;
30#[cfg(feature = "service")]
31pub mod proofs;
32#[cfg(feature = "service")]
33pub mod random;
34#[cfg(feature = "service")]
35mod store;
36
37#[cfg(feature = "service")]
38pub use error::Error;
39#[cfg(feature = "service")]
40pub use hash::Hash;
41#[cfg(feature = "service")]
42pub use options::{OptionValue, Options};
43#[cfg(feature = "service")]
44pub use store::Store;
45
46/// PHP `random_bytes($length)`: bytes from the operating system's CSPRNG.
47///
48/// # Panics
49///
50/// When the operating system cannot provide random bytes, where PHP throws its `Exception`
51/// ("Could not gather sufficient random data").
52#[must_use]
53pub fn random_bytes(length: usize) -> Vec<u8> {
54    let mut bytes = vec![0u8; length];
55    getrandom::fill(&mut bytes).expect("the operating system provides random bytes");
56    bytes
57}
58
59/// `php_password_make_salt($length)`, the salt `password_hash()` draws: `$length * 3 / 4 + 1`
60/// random bytes in base64, `+` as `.`, cut to `$length` characters (22 for bcrypt, 16 for
61/// Argon2, which hashes these characters as its salt).
62#[must_use]
63pub fn password_salt(length: usize) -> Vec<u8> {
64    let encoded = php_std::encoding::base64_encode(&random_bytes(length * 3 / 4 + 1));
65    encoded.bytes().take(length).map(|b| if b == b'+' { b'.' } else { b }).collect()
66}
67
68/// PHP `hash_equals($known, $user)`: false at once when the lengths differ (PHP leaks the
69/// length too), otherwise a comparison whose time does not depend on where they differ.
70#[must_use]
71pub fn hash_equals(known: &[u8], user: &[u8]) -> bool {
72    if known.len() != user.len() {
73        return false;
74    }
75    let difference = known.iter().zip(user).fold(0u8, |acc, (a, b)| acc | (a ^ b));
76    // `black_box` keeps the compiler from turning the fold into an early-exit comparison.
77    std::hint::black_box(difference) == 0
78}
79
80#[cfg(test)]
81mod tests {
82    use super::hash_equals;
83
84    #[test]
85    fn password_salts_are_php_salts() {
86        for length in [16, 22] {
87            let salt = super::password_salt(length);
88            assert_eq!(salt.len(), length);
89            assert!(salt.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'.' || *b == b'/'));
90        }
91    }
92
93    #[test]
94    fn hash_equals_is_php_hash_equals() {
95        assert!(hash_equals(b"", b""));
96        assert!(hash_equals(b"abc", b"abc"));
97        assert!(!hash_equals(b"abc", b"abd"));
98        assert!(!hash_equals(b"abc", b"ab"));
99        assert!(!hash_equals(b"ab", b"abc"));
100    }
101}