forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

authentication.rs278 lines, 8.1 KiBHistoryRawDownload
1use argon2::{Argon2, PasswordHasher, PasswordVerifier};
2use common::{
3 call::{Call, Login, Register, Session},
4 error::Error as CommonError,
5 model::{Id, Role, ServerSettings, User},
6 permission,
7 transport::Close,
8};
9use sha2::{Digest, Sha256};
10
11use crate::{
12 db::{self, Connection},
13 error::{ServerError, ensure_with},
14 hub::{Client, Hub},
15 network::Shared,
16 request::limit_logins,
17};
18
19const SALT_LENGTH: usize = 16;
20const TOKEN_LENGTH: usize = 32;
21
22pub(crate) fn random_bytes<const N: usize>() -> Result<[u8; N], ServerError> {
23 let mut bytes = [0u8; N];
24 getrandom::fill(&mut bytes)
25 .map_err(|error| ServerError::Internal(format!("random: {error}")))?;
26
27 Ok(bytes)
28}
29
30pub fn token_hash(token: &str) -> Vec<u8> {
31 Sha256::digest(token.as_bytes()).to_vec()
32}
33
34fn hash(password: &str) -> Result<String, ServerError> {
35 let salt = random_bytes::<SALT_LENGTH>()?;
36 let hash = Argon2::default()
37 .hash_password_with_salt(password.as_bytes(), &salt)
38 .map_err(|error| ServerError::Internal(error.to_string()))?;
39
40 Ok(hash.to_string())
41}
42
43fn verify(password: &str, password_hash: &str) -> Result<(), ServerError> {
44 Argon2::default()
45 .verify_password(password.as_bytes(), password_hash)
46 .map_err(|_| ServerError::from(CommonError::WrongCredentials))
47}
48
49async fn hash_blocking(password: String) -> Result<String, ServerError> {
50 tokio::task::spawn_blocking(move || hash(&password)).await?
51}
52
53async fn verify_blocking(password: String, password_hash: String) -> Result<(), ServerError> {
54 tokio::task::spawn_blocking(move || verify(&password, &password_hash)).await?
55}
56
57async fn open_session(user_id: Id, db: &Connection) -> Result<String, ServerError> {
58 let token: String = random_bytes::<TOKEN_LENGTH>()?
59 .iter()
60 .map(|byte| format!("{byte:02x}"))
61 .collect();
62 let session_id = db::session::insert(&token_hash(&token), user_id, db).await?;
63 db::session::seen(session_id, db).await?;
64
65 Ok(token)
66}
67
68pub async fn create_account(
69 username: &str,
70 password: &str,
71 db: &Connection,
72) -> Result<User, ServerError> {
73 db::user::create(username, &hash(password)?, Role::User, db).await
74}
75
76pub(crate) async fn register(
77 call: Register,
78 client: &Client,
79 shared: &Shared,
80) -> Result<Session, ServerError> {
81 call.validate()?;
82 shared
83 .db
84 .run(async |db| limit_logins(&shared.services.rate_limit, client.conn.as_ref(), db).await)
85 .await?;
86 let password_hash = hash_blocking(call.password.clone()).await?;
87
88 shared
89 .db
90 .run(async |db| {
91 if db::server_ban::username_banned(&call.username, db).await? {
92 return Err(CommonError::Banned.into());
93 }
94 let settings = db::settings::read(db).await?;
95 let first = !db::user::any(db).await?;
96 if !settings.registration_open && !first {
97 let code = call
98 .invite
99 .as_deref()
100 .ok_or(CommonError::RegistrationClosed)?;
101 db::registration_code::consume(code, db).await?;
102 }
103 let role = if first { Role::Builder } else { Role::User };
104 let user = db::user::create(&call.username, &password_hash, role, db).await?;
105 admit(&user, &settings, db).await?;
106 let token = open_session(user.id, db).await?;
107
108 Ok(Session { user, token })
109 })
110 .await
111}
112
113pub(crate) async fn login(
114 call: Login,
115 client: &Client,
116 shared: &Shared,
117) -> Result<Session, ServerError> {
118 call.validate()?;
119 let (user, password_hash) = shared
120 .db
121 .run(async |db| {
122 limit_logins(&shared.services.rate_limit, client.conn.as_ref(), db).await?;
123 db::user::password_hash_of(&call.username, db)
124 .await?
125 .ok_or(CommonError::WrongCredentials.into())
126 })
127 .await?;
128 verify_blocking(call.password, password_hash).await?;
129
130 shared
131 .db
132 .run(async |db| {
133 let settings = db::settings::read(db).await?;
134 admit(&user, &settings, db).await?;
135 let token = open_session(user.id, db).await?;
136
137 Ok(Session { user, token })
138 })
139 .await
140}
141
142async fn admit(user: &User, settings: &ServerSettings, db: &Connection) -> Result<(), ServerError> {
143 if db::server_ban::username_banned(&user.username, db).await? {
144 return Err(CommonError::Banned.into());
145 }
146 if let Some(until_ms) = db::user::suspended(user.id, db).await? {
147 return Err(CommonError::Suspended { until_ms }.into());
148 }
149 if !permission::is_builder(user.role) && settings.maintenance {
150 return Err(CommonError::Maintenance.into());
151 }
152
153 Ok(())
154}
155
156pub async fn resume(token: &str, db: &Connection) -> Result<(Id, User), ServerError> {
157 let (session_id, user) = db::session::find(&token_hash(token), db)
158 .await?
159 .ok_or(CommonError::Unauthenticated)?;
160 admit(&user, &db::settings::read(db).await?, db).await?;
161 db::session::seen(session_id, db).await?;
162
163 Ok((session_id, user))
164}
165
166pub async fn recheck(session_id: Id, db: &Connection) -> Result<User, ServerError> {
167 let user = db::session::user_of(session_id, db)
168 .await?
169 .ok_or(CommonError::Unauthenticated)?;
170 admit(&user, &db::settings::read(db).await?, db).await?;
171
172 Ok(user)
173}
174
175pub async fn logout(session_id: Id, db: &Connection) -> Result<(), ServerError> {
176 db::session::delete(session_id, db).await
177}
178
179pub(crate) async fn revoke_sessions(user_id: Id, db: &Connection) -> Result<(), ServerError> {
180 db::session::delete_all(user_id, db).await
181}
182
183pub async fn reset_password(
184 user_id: Id,
185 password: &str,
186 db: &Connection,
187) -> Result<(), ServerError> {
188 db::user::set_password_hash(user_id, &hash(password)?, db).await
189}
190
191pub enum Revoke {
192 User(Id),
193 Session { user_id: Id, session_id: Id },
194}
195
196pub async fn revoke(hub: &Hub, target: Revoke, db: &Connection) -> Result<(), ServerError> {
197 match target {
198 Revoke::User(user_id) => {
199 revoke_sessions(user_id, db).await?;
200 hub.kick_user(user_id, Close::Revoked);
201 }
202 Revoke::Session {
203 user_id,
204 session_id,
205 } => {
206 let deleted = db::session::delete_of(user_id, session_id, db).await?;
207 ensure_with(deleted == 1, CommonError::NotFound)?;
208 hub.kick_session(session_id, Close::Revoked);
209 }
210 }
211
212 Ok(())
213}
214
215#[cfg(test)]
216mod tests {
217 use common::{
218 call::{Login, Register},
219 error::Error as CommonError,
220 };
221
222 use crate::{
223 authentication,
224 error::ServerError,
225 hub::Client,
226 network::{Services, Shared},
227 test,
228 };
229
230 #[tokio::test]
231 async fn register_and_login() {
232 let shared = Shared {
233 db: test::db().await,
234 services: Services::default(),
235 directory: test::directory(),
236 backups: test::directory(),
237 releases: Default::default(),
238 };
239 let client = Client::detached(None);
240
241 let registered = authentication::register(
242 Register {
243 username: "Tahinli".to_string(),
244 password: "correct horse".to_string(),
245 invite: None,
246 },
247 &client,
248 &shared,
249 )
250 .await
251 .unwrap();
252 let logged_in = authentication::login(
253 Login {
254 username: "tahinli".to_string(),
255 password: "correct horse".to_string(),
256 },
257 &client,
258 &shared,
259 )
260 .await
261 .unwrap();
262 let wrong_password = authentication::login(
263 Login {
264 username: "Tahinli".to_string(),
265 password: "wrong password".to_string(),
266 },
267 &client,
268 &shared,
269 )
270 .await;
271
272 assert_eq!(registered.user, logged_in.user);
273 assert!(matches!(
274 wrong_password,
275 Err(ServerError::Wire(CommonError::WrongCredentials))
276 ));
277 }
278}