actix-security-core 0.2.3

Spring Security-like authentication and authorization for Actix Web - Core library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Password encoding utilities.
//!
//! # Spring Security Equivalent
//! `org.springframework.security.crypto.password.PasswordEncoder`
//!
//! # Feature Flags
//! - `argon2`: Enables `Argon2PasswordEncoder` (recommended, default)
//! - `bcrypt`: Enables `BCryptPasswordEncoder` (widely compatible)

#[cfg(feature = "argon2")]
use argon2::password_hash::rand_core::OsRng;
#[cfg(feature = "argon2")]
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
#[cfg(feature = "argon2")]
use argon2::Argon2;

/// Trait for encoding and verifying passwords.
///
/// # Spring Security Equivalent
/// `PasswordEncoder` interface
///
/// # Example
/// ```ignore
/// use actix_security_core::http::security::crypto::{PasswordEncoder, Argon2PasswordEncoder};
///
/// let encoder = Argon2PasswordEncoder::new();
/// let hash = encoder.encode("my_password");
/// assert!(encoder.matches("my_password", &hash));
/// ```
pub trait PasswordEncoder: Send + Sync {
    /// Encode the raw password.
    ///
    /// # Spring Equivalent
    /// `PasswordEncoder.encode(CharSequence rawPassword)`
    fn encode(&self, raw_password: &str) -> String;

    /// Verify a raw password against an encoded password.
    ///
    /// # Spring Equivalent
    /// `PasswordEncoder.matches(CharSequence rawPassword, String encodedPassword)`
    fn matches(&self, raw_password: &str, encoded_password: &str) -> bool;

    /// Returns true if the encoded password should be upgraded for better security.
    ///
    /// # Spring Equivalent
    /// `PasswordEncoder.upgradeEncoding(String encodedPassword)`
    fn upgrade_encoding(&self, _encoded_password: &str) -> bool {
        false
    }
}

/// Argon2 password encoder - the recommended encoder for new applications.
///
/// # Spring Security Equivalent
/// `Argon2PasswordEncoder`
///
/// Argon2 is the winner of the Password Hashing Competition and is recommended
/// by OWASP for password storage.
///
/// # Feature Flag
/// Requires the `argon2` feature (enabled by default).
///
/// # Example
/// ```
/// use actix_security_core::http::security::crypto::{PasswordEncoder, Argon2PasswordEncoder};
///
/// let encoder = Argon2PasswordEncoder::new();
/// let hash = encoder.encode("secret_password");
///
/// // Verify correct password
/// assert!(encoder.matches("secret_password", &hash));
///
/// // Verify wrong password
/// assert!(!encoder.matches("wrong_password", &hash));
/// ```
#[cfg(feature = "argon2")]
#[derive(Clone)]
pub struct Argon2PasswordEncoder {
    argon2: Argon2<'static>,
}

#[cfg(feature = "argon2")]
impl Argon2PasswordEncoder {
    /// Creates a new Argon2 password encoder with default settings.
    pub fn new() -> Self {
        Argon2PasswordEncoder {
            argon2: Argon2::default(),
        }
    }
}

#[cfg(feature = "argon2")]
impl Default for Argon2PasswordEncoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "argon2")]
impl PasswordEncoder for Argon2PasswordEncoder {
    fn encode(&self, raw_password: &str) -> String {
        let salt = SaltString::generate(&mut OsRng);
        self.argon2
            .hash_password(raw_password.as_bytes(), &salt)
            .expect("Failed to hash password")
            .to_string()
    }

    fn matches(&self, raw_password: &str, encoded_password: &str) -> bool {
        match PasswordHash::new(encoded_password) {
            Ok(parsed_hash) => self
                .argon2
                .verify_password(raw_password.as_bytes(), &parsed_hash)
                .is_ok(),
            Err(_) => false,
        }
    }
}

/// BCrypt password encoder - widely compatible with other frameworks.
///
/// # Spring Security Equivalent
/// `BCryptPasswordEncoder`
///
/// BCrypt is a widely-used password hashing algorithm that is compatible with
/// many other frameworks (PHP, Node.js, etc.). Use this when migrating from
/// other systems or for interoperability.
///
/// # Feature Flag
/// Requires the `bcrypt` feature.
///
/// # Example
/// ```ignore
/// use actix_security_core::http::security::crypto::{PasswordEncoder, BCryptPasswordEncoder};
///
/// let encoder = BCryptPasswordEncoder::new();
/// let hash = encoder.encode("secret_password");
///
/// // Verify correct password
/// assert!(encoder.matches("secret_password", &hash));
/// ```
#[cfg(feature = "bcrypt")]
#[derive(Clone)]
pub struct BCryptPasswordEncoder {
    cost: u32,
}

#[cfg(feature = "bcrypt")]
impl BCryptPasswordEncoder {
    /// Creates a new BCrypt password encoder with default cost (12).
    pub fn new() -> Self {
        Self { cost: 12 }
    }

    /// Creates a new BCrypt password encoder with custom cost.
    ///
    /// Cost should be between 4 and 31. Higher values are more secure
    /// but slower. Default is 12.
    pub fn with_cost(cost: u32) -> Self {
        let cost = cost.clamp(4, 31);
        Self { cost }
    }

    /// Create encoder with strength level.
    ///
    /// - `weak`: cost 10 (fast, for development)
    /// - `default`: cost 12 (balanced)
    /// - `strong`: cost 14 (secure, slower)
    pub fn with_strength(strength: &str) -> Self {
        let cost = match strength {
            "weak" => 10,
            "strong" => 14,
            _ => 12,
        };
        Self { cost }
    }
}

#[cfg(feature = "bcrypt")]
impl Default for BCryptPasswordEncoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "bcrypt")]
impl PasswordEncoder for BCryptPasswordEncoder {
    fn encode(&self, raw_password: &str) -> String {
        bcrypt::hash(raw_password, self.cost).expect("Failed to hash password with bcrypt")
    }

    fn matches(&self, raw_password: &str, encoded_password: &str) -> bool {
        bcrypt::verify(raw_password, encoded_password).unwrap_or(false)
    }

    fn upgrade_encoding(&self, encoded_password: &str) -> bool {
        // Check if the cost in the hash is lower than current setting
        // BCrypt hashes start with $2a$, $2b$, or $2y$ followed by cost
        if encoded_password.starts_with("$2") && encoded_password.len() > 7 {
            // Extract cost from hash (format: $2a$XX$ where XX is cost)
            if let Some(cost_str) = encoded_password.get(4..6) {
                if let Ok(hash_cost) = cost_str.parse::<u32>() {
                    return hash_cost < self.cost;
                }
            }
        }
        true // Invalid hash or unable to parse, recommend re-encoding
    }
}

/// No-op password encoder that stores passwords in plain text.
///
/// # Spring Security Equivalent
/// `NoOpPasswordEncoder`
///
/// # Warning
/// **NEVER use this in production!** This is only for testing/development.
/// Passwords are stored in plain text without any hashing.
///
/// # Example
/// ```
/// use actix_security_core::http::security::crypto::{PasswordEncoder, NoOpPasswordEncoder};
///
/// let encoder = NoOpPasswordEncoder;
/// let encoded = encoder.encode("password");
/// assert_eq!(encoded, "password"); // Plain text!
/// assert!(encoder.matches("password", &encoded));
/// ```
#[derive(Clone, Copy, Default)]
pub struct NoOpPasswordEncoder;

impl PasswordEncoder for NoOpPasswordEncoder {
    fn encode(&self, raw_password: &str) -> String {
        raw_password.to_string()
    }

    fn matches(&self, raw_password: &str, encoded_password: &str) -> bool {
        raw_password == encoded_password
    }
}

/// Default encoding algorithm for DelegatingPasswordEncoder.
#[derive(Debug, Clone, Copy, Default)]
pub enum DefaultEncoder {
    /// Use Argon2 (recommended)
    #[default]
    Argon2,
    /// Use BCrypt (compatible)
    BCrypt,
}

/// Delegating password encoder that supports multiple encoding formats.
///
/// # Spring Security Equivalent
/// `DelegatingPasswordEncoder`
///
/// This encoder can verify passwords encoded with different algorithms
/// by detecting the encoding format from a prefix in the stored hash.
///
/// Supported formats:
/// - `{argon2}hash` - Argon2 encoded password
/// - `{bcrypt}hash` - BCrypt encoded password
/// - `{noop}plain` - Plain text (for testing only!)
///
/// # Feature Flag
/// Requires the `argon2` feature (enabled by default).
///
/// # Example
/// ```
/// use actix_security_core::http::security::crypto::{PasswordEncoder, DelegatingPasswordEncoder};
///
/// let encoder = DelegatingPasswordEncoder::new();
///
/// // Encode with default (argon2)
/// let hash = encoder.encode("password");
/// assert!(hash.starts_with("{argon2}"));
///
/// // Can verify both formats
/// assert!(encoder.matches("password", &hash));
/// assert!(encoder.matches("plain", "{noop}plain"));
/// ```
#[cfg(feature = "argon2")]
#[derive(Clone)]
pub struct DelegatingPasswordEncoder {
    argon2: Argon2PasswordEncoder,
    #[cfg(feature = "bcrypt")]
    bcrypt: BCryptPasswordEncoder,
    default_encoder: DefaultEncoder,
}

#[cfg(feature = "argon2")]
impl DelegatingPasswordEncoder {
    /// Creates a new delegating password encoder.
    /// Default encoding is Argon2.
    pub fn new() -> Self {
        DelegatingPasswordEncoder {
            argon2: Argon2PasswordEncoder::new(),
            #[cfg(feature = "bcrypt")]
            bcrypt: BCryptPasswordEncoder::new(),
            default_encoder: DefaultEncoder::Argon2,
        }
    }

    /// Set the default encoder to use for new passwords.
    pub fn default_encoder(mut self, encoder: DefaultEncoder) -> Self {
        self.default_encoder = encoder;
        self
    }

    /// Use BCrypt as the default encoder.
    #[cfg(feature = "bcrypt")]
    pub fn use_bcrypt(self) -> Self {
        self.default_encoder(DefaultEncoder::BCrypt)
    }
}

#[cfg(feature = "argon2")]
impl Default for DelegatingPasswordEncoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "argon2")]
impl PasswordEncoder for DelegatingPasswordEncoder {
    fn encode(&self, raw_password: &str) -> String {
        match self.default_encoder {
            DefaultEncoder::Argon2 => {
                format!("{{argon2}}{}", self.argon2.encode(raw_password))
            }
            #[cfg(feature = "bcrypt")]
            DefaultEncoder::BCrypt => {
                format!("{{bcrypt}}{}", self.bcrypt.encode(raw_password))
            }
            #[cfg(not(feature = "bcrypt"))]
            DefaultEncoder::BCrypt => {
                // Fall back to argon2 if bcrypt not available
                format!("{{argon2}}{}", self.argon2.encode(raw_password))
            }
        }
    }

    fn matches(&self, raw_password: &str, encoded_password: &str) -> bool {
        if let Some(hash) = encoded_password.strip_prefix("{argon2}") {
            self.argon2.matches(raw_password, hash)
        } else if let Some(plain) = encoded_password.strip_prefix("{noop}") {
            raw_password == plain
        } else {
            #[cfg(feature = "bcrypt")]
            if let Some(hash) = encoded_password.strip_prefix("{bcrypt}") {
                return self.bcrypt.matches(raw_password, hash);
            }
            // Legacy: try bcrypt without prefix (common in migrations)
            #[cfg(feature = "bcrypt")]
            if encoded_password.starts_with("$2") {
                return self.bcrypt.matches(raw_password, encoded_password);
            }
            // Legacy: assume plain text for backward compatibility
            raw_password == encoded_password
        }
    }

    fn upgrade_encoding(&self, encoded_password: &str) -> bool {
        // Recommend upgrade if not using the preferred encoder
        match self.default_encoder {
            DefaultEncoder::Argon2 => !encoded_password.starts_with("{argon2}"),
            DefaultEncoder::BCrypt => !encoded_password.starts_with("{bcrypt}"),
        }
    }
}

#[cfg(all(test, feature = "argon2"))]
mod tests {
    use super::*;

    #[test]
    fn test_argon2_encoder() {
        let encoder = Argon2PasswordEncoder::new();
        let password = "test_password_123";

        let hash = encoder.encode(password);

        // Hash should not equal plain password
        assert_ne!(hash, password);

        // Should verify correctly
        assert!(encoder.matches(password, &hash));
        assert!(!encoder.matches("wrong_password", &hash));
    }

    #[test]
    fn test_noop_encoder() {
        let encoder = NoOpPasswordEncoder;
        let password = "plain_password";

        let encoded = encoder.encode(password);
        assert_eq!(encoded, password);
        assert!(encoder.matches(password, &encoded));
    }

    #[test]
    fn test_delegating_encoder() {
        let encoder = DelegatingPasswordEncoder::new();

        // Test argon2 encoding
        let hash = encoder.encode("password");
        assert!(hash.starts_with("{argon2}"));
        assert!(encoder.matches("password", &hash));

        // Test noop format
        assert!(encoder.matches("plain", "{noop}plain"));

        // Test upgrade recommendation
        assert!(encoder.upgrade_encoding("{noop}plain"));
        assert!(!encoder.upgrade_encoding(&hash));
    }
}