steid

@jamesgill /

Rust6.1 KBCode·Blame·History·Raw
1use crate::domain::{Actor, DomainError, Email, repository::UserRepository};
2
3use super::{error::Result, port::PasswordHasher};
4
5/// A hash to verify against when no user matched.
6///
7/// Without this, an unknown email returns before hashing and a known one doesn't, so
8/// response time tells an attacker which addresses have accounts. Verifying a dummy
9/// keeps both paths doing the same work.
10///
11/// Shared with [`password_reset`](super::password_reset) rather than copied: it is one
12/// constant with one test proving the real hasher can still parse it, and a second copy
13/// is a second thing to keep parseable.
14pub(super) const ABSENT_USER_HASH: &str =
15 "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0c2FsdA$YXNkZmFzZGZhc2RmYXNkZmFzZGZhc2Rm";
16
17/// Verifies credentials and returns the resulting actor.
18///
19/// Every failure — unknown email, malformed email, wrong password — yields
20/// [`DomainError::InvalidCredentials`]. Distinguishing them would let anyone probe
21/// which addresses have accounts.
22pub async fn login(
23 email: &str,
24 password: &str,
25 users: &impl UserRepository,
26 hasher: &impl PasswordHasher,
27) -> Result<Actor> {
28 let user = match Email::new(email) {
29 Ok(email) => users.find_by_email(&email).await?,
30 // A malformed address can't match anyone, but still costs the same work.
31 Err(_) => None,
32 };
33
34 let Some(user) = user else {
35 let _ = hasher.verify(
36 password,
37 &crate::domain::PasswordHash::from_trusted(ABSENT_USER_HASH),
38 );
39 return Err(DomainError::InvalidCredentials.into());
40 };
41
42 if hasher.verify(password, &user.password_hash)? {
43 Ok(Actor::User(user.id))
44 } else {
45 Err(DomainError::InvalidCredentials.into())
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52 use crate::{
53 application::error::Error,
54 domain::{OrgId, PasswordHash, User, UserId},
55 infrastructure::{password::StubHasher, repository::InMemoryUserRepo},
56 };
57
58 async fn repo_with_user(email: &str, password: &str) -> (InMemoryUserRepo, UserId) {
59 let repo = InMemoryUserRepo::new();
60 let hasher = StubHasher::new();
61 let user = User::new(
62 UserId::generate(),
63 Email::new(email).expect("valid email"),
64 hasher.hash(password).expect("hash"),
65 OrgId::generate(),
66 );
67 let id = user.id.clone();
68 repo.save(&user).await.expect("save");
69 (repo, id)
70 }
71
72 fn assert_invalid_credentials(error: Error) {
73 assert!(
74 matches!(error, Error::Domain(DomainError::InvalidCredentials)),
75 "expected InvalidCredentials, got {error:?}"
76 );
77 }
78
79 #[tokio::test]
80 async fn correct_credentials_yield_the_user() {
81 let (users, id) = repo_with_user("dev@example.com", "hunter2").await;
82
83 let actor = login("dev@example.com", "hunter2", &users, &StubHasher::new())
84 .await
85 .expect("login");
86
87 assert_eq!(actor, Actor::User(id));
88 }
89
90 #[tokio::test]
91 async fn the_email_is_normalised_before_lookup() {
92 let (users, id) = repo_with_user("dev@example.com", "hunter2").await;
93
94 let actor = login(" DEV@Example.COM ", "hunter2", &users, &StubHasher::new())
95 .await
96 .expect("login");
97
98 assert_eq!(actor, Actor::User(id));
99 }
100
101 #[tokio::test]
102 async fn a_wrong_password_is_rejected() {
103 let (users, _) = repo_with_user("dev@example.com", "hunter2").await;
104
105 let error = login("dev@example.com", "wrong", &users, &StubHasher::new())
106 .await
107 .expect_err("should reject");
108
109 assert_invalid_credentials(error);
110 }
111
112 #[tokio::test]
113 async fn an_unknown_email_is_rejected_the_same_way() {
114 let (users, _) = repo_with_user("dev@example.com", "hunter2").await;
115
116 let error = login("nobody@example.com", "hunter2", &users, &StubHasher::new())
117 .await
118 .expect_err("should reject");
119
120 assert_invalid_credentials(error);
121 }
122
123 #[tokio::test]
124 async fn a_malformed_email_is_rejected_the_same_way() {
125 let (users, _) = repo_with_user("dev@example.com", "hunter2").await;
126
127 let error = login("not-an-email", "hunter2", &users, &StubHasher::new())
128 .await
129 .expect_err("should reject");
130
131 assert_invalid_credentials(error);
132 }
133
134 #[tokio::test]
135 async fn an_empty_password_does_not_match_a_stored_hash() {
136 let (users, _) = repo_with_user("dev@example.com", "hunter2").await;
137
138 let error = login("dev@example.com", "", &users, &StubHasher::new())
139 .await
140 .expect_err("should reject");
141
142 assert_invalid_credentials(error);
143 }
144
145 /// Guards the timing defence. If `ABSENT_USER_HASH` stops being parseable, the
146 /// real hasher returns early instead of doing the work, and the unknown-email path
147 /// becomes measurably faster than the known-email one again — silently.
148 #[test]
149 fn the_absent_user_hash_is_parseable_by_the_real_hasher() {
150 use crate::infrastructure::password::Argon2Hasher;
151
152 let outcome =
153 Argon2Hasher::new().verify("anything", &PasswordHash::from_trusted(ABSENT_USER_HASH));
154
155 assert!(
156 matches!(outcome, Ok(false)),
157 "dummy hash must verify to Ok(false), got {outcome:?}"
158 );
159 }
160
161 #[tokio::test]
162 async fn a_corrupt_stored_hash_surfaces_rather_than_reading_as_a_bad_password() {
163 let users = InMemoryUserRepo::new();
164 users
165 .save(&User::new(
166 UserId::generate(),
167 Email::new("dev@example.com").expect("valid email"),
168 PasswordHash::from_trusted("not-a-stub-hash"),
169 OrgId::generate(),
170 ))
171 .await
172 .expect("save");
173
174 let error = login("dev@example.com", "hunter2", &users, &StubHasher::new())
175 .await
176 .expect_err("should fail");
177
178 assert!(
179 matches!(error, Error::Password(_)),
180 "a broken hash is an operational fault, not a failed login: got {error:?}"
181 );
182 }
183}