1use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8use thiserror::Error;
9use uuid::Uuid;
10
11use crate::ErrorRepositorio;
12
13#[non_exhaustive]
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Principal {
24 pub id_usuario: Uuid,
25 pub sujeto: String,
26 pub email: Option<String>,
27 pub nombre: Option<String>,
28 pub roles: Vec<String>,
29}
30
31impl Principal {
32 pub fn new(id_usuario: Uuid, sujeto: impl Into<String>) -> Self {
33 Self {
34 id_usuario,
35 sujeto: sujeto.into(),
36 email: None,
37 nombre: None,
38 roles: Vec::new(),
39 }
40 }
41
42 pub fn con_id_usuario(mut self, id_usuario: Uuid) -> Self {
43 self.id_usuario = id_usuario;
44 self
45 }
46
47 pub fn con_email(mut self, email: impl Into<String>) -> Self {
48 self.email = Some(email.into());
49 self
50 }
51
52 pub fn con_nombre(mut self, nombre: impl Into<String>) -> Self {
53 self.nombre = Some(nombre.into());
54 self
55 }
56
57 pub fn con_roles<I, S>(mut self, roles: I) -> Self
58 where
59 I: IntoIterator<Item = S>,
60 S: Into<String>,
61 {
62 self.roles = roles.into_iter().map(Into::into).collect();
63 self
64 }
65
66 pub fn tiene_rol(&self, role: &str) -> bool {
69 self.roles.iter().any(|held| held == role)
70 }
71}
72
73#[non_exhaustive]
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
77pub enum ErrorAuth {
78 #[error("auth.invalido")]
80 Invalido,
81 #[error("auth.expirado")]
83 Expirado,
84 #[error("auth.no_disponible")]
86 NoDisponible,
87}
88
89#[async_trait]
92pub trait Autenticador: Send + Sync {
93 async fn autenticar(&self, token: &str) -> Result<Principal, ErrorAuth>;
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
100#[error("auth.hash_fallido")]
101pub struct ErrorHash;
102
103#[async_trait]
106pub trait HasherContrasena: Send + Sync {
107 async fn hash(&self, password: &str) -> Result<String, ErrorHash>;
108
109 async fn verificar(&self, password: &str, hash: Option<String>) -> bool;
113}
114
115#[async_trait]
117pub trait AlmacenCredenciales: Send + Sync {
118 async fn hash_contrasena(&self, id_usuario: Uuid) -> Result<Option<String>, ErrorRepositorio>;
119 async fn guardar_hash_contrasena(
121 &self,
122 id_usuario: Uuid,
123 hash: &str,
124 ) -> Result<(), ErrorRepositorio>;
125}
126
127#[non_exhaustive]
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct Sesion {
132 pub token: String,
133 pub expira_en: DateTime<Utc>,
134}
135
136impl Sesion {
137 pub fn new(token: impl Into<String>, expira_en: DateTime<Utc>) -> Self {
138 Self {
139 token: token.into(),
140 expira_en,
141 }
142 }
143}
144
145#[async_trait]
148pub trait AlmacenSesiones: Send + Sync {
149 async fn abrir(&self, id_usuario: Uuid) -> Result<Sesion, ErrorRepositorio>;
150 async fn revocar(&self, token: &str) -> Result<(), ErrorRepositorio>;
152}
153
154#[cfg(any(test, feature = "pruebas"))]
155pub mod dobles {
156 use super::*;
157 use mockall::mock;
158
159 #[derive(Debug, Default)]
162 pub struct MadrePrincipal {
163 roles: Vec<String>,
164 }
165
166 impl MadrePrincipal {
167 pub fn new() -> Self {
168 Self::default()
169 }
170
171 pub fn con_roles<I, S>(mut self, roles: I) -> Self
172 where
173 I: IntoIterator<Item = S>,
174 S: Into<String>,
175 {
176 self.roles = roles.into_iter().map(Into::into).collect();
177 self
178 }
179
180 pub fn construir(self) -> Principal {
181 let id_usuario = Uuid::now_v7();
182 Principal::new(id_usuario, format!("sujeto-{id_usuario}"))
183 .con_email(format!("{}@example.com", id_usuario.simple()))
184 .con_nombre("Ada Lovelace")
185 .con_roles(self.roles)
186 }
187
188 pub fn aleatorio() -> Principal {
190 Self::new().construir()
191 }
192 }
193
194 mock! {
195 pub Autenticador {}
196
197 #[async_trait]
198 impl Autenticador for Autenticador {
199 async fn autenticar(&self, token: &str) -> Result<Principal, ErrorAuth>;
200 }
201 }
202
203 mock! {
204 pub HasherContrasena {}
205
206 #[async_trait]
207 impl HasherContrasena for HasherContrasena {
208 async fn hash(&self, password: &str) -> Result<String, ErrorHash>;
209 async fn verificar(&self, password: &str, hash: Option<String>) -> bool;
210 }
211 }
212
213 mock! {
214 pub AlmacenCredenciales {}
215
216 #[async_trait]
217 impl AlmacenCredenciales for AlmacenCredenciales {
218 async fn hash_contrasena(&self, id_usuario: Uuid) -> Result<Option<String>, ErrorRepositorio>;
219 async fn guardar_hash_contrasena(&self, id_usuario: Uuid, hash: &str) -> Result<(), ErrorRepositorio>;
220 }
221 }
222
223 mock! {
224 pub AlmacenSesiones {}
225
226 #[async_trait]
227 impl AlmacenSesiones for AlmacenSesiones {
228 async fn abrir(&self, id_usuario: Uuid) -> Result<Sesion, ErrorRepositorio>;
229 async fn revocar(&self, token: &str) -> Result<(), ErrorRepositorio>;
230 }
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use super::dobles::{
237 MockAlmacenCredenciales, MockAlmacenSesiones, MockAutenticador, MockHasherContrasena,
238 };
239 use super::*;
240
241 #[test]
242 fn should_build_a_fresh_caller_with_the_roles_it_is_given() {
243 let admin = dobles::MadrePrincipal::new()
245 .con_roles(["admin"])
246 .construir();
247 let otro = dobles::MadrePrincipal::aleatorio();
248
249 assert!(admin.tiene_rol("admin"));
251 assert!(otro.roles.is_empty());
252 assert_ne!(admin.id_usuario, otro.id_usuario);
253 }
254
255 #[test]
256 fn should_hold_no_role_or_profile_when_built_from_an_id_and_a_subject() {
257 let id_usuario = Uuid::now_v7();
259
260 let principal = Principal::new(id_usuario, "auth0|ada");
262
263 assert_eq!(principal.id_usuario, id_usuario);
265 assert_eq!(principal.sujeto, "auth0|ada");
266 assert_eq!(principal.email, None);
267 assert_eq!(principal.nombre, None);
268 assert!(principal.roles.is_empty());
269 }
270
271 #[test]
272 fn should_carry_the_profile_when_given_one() {
273 let id_usuario = Uuid::now_v7();
275
276 let principal = Principal::new(Uuid::nil(), "ada")
278 .con_id_usuario(id_usuario)
279 .con_email("ada@example.com")
280 .con_nombre("Ada Lovelace")
281 .con_roles(["admin", "editor"]);
282
283 assert_eq!(principal.id_usuario, id_usuario);
285 assert_eq!(principal.email.as_deref(), Some("ada@example.com"));
286 assert_eq!(principal.nombre.as_deref(), Some("Ada Lovelace"));
287 assert_eq!(principal.roles, vec!["admin", "editor"]);
288 }
289
290 #[test]
291 fn should_have_a_role_only_when_it_holds_exactly_that_role() {
292 let principal = Principal::new(Uuid::nil(), "ada").con_roles(["admin"]);
294
295 assert!(principal.tiene_rol("admin"));
297 assert!(!principal.tiene_rol("Admin"));
298 assert!(!principal.tiene_rol("adm"));
299 assert!(!principal.tiene_rol("editor"));
300 }
301
302 #[test]
303 fn should_keep_error_codes_stable_when_logged() {
304 assert_eq!(ErrorAuth::Invalido.to_string(), "auth.invalido");
305 assert_eq!(ErrorAuth::Expirado.to_string(), "auth.expirado");
306 assert_eq!(ErrorAuth::NoDisponible.to_string(), "auth.no_disponible");
307 }
308
309 #[test]
310 fn should_keep_the_token_and_its_expiry_when_a_session_is_built() {
311 let expira_en = chrono::Utc::now();
313
314 let session = Sesion::new("opaque", expira_en);
316
317 assert_eq!(session.token, "opaque");
319 assert_eq!(session.expira_en, expira_en);
320 assert_eq!(ErrorHash.to_string(), "auth.hash_fallido");
321 }
322
323 #[tokio::test]
324 async fn should_drive_the_local_ports_when_mocked() {
325 let id_usuario = Uuid::now_v7();
327 let mut hasher = MockHasherContrasena::new();
328 hasher
329 .expect_verificar()
330 .returning(|password, hash| hash.as_deref() == Some("h") && password == "secret");
331 let mut credentials = MockAlmacenCredenciales::new();
332 credentials
333 .expect_hash_contrasena()
334 .returning(|_| Ok(Some("h".to_string())));
335 let mut sessions = MockAlmacenSesiones::new();
336 sessions
337 .expect_abrir()
338 .returning(|_| Ok(Sesion::new("t", chrono::Utc::now())));
339 let (hasher, credentials, sessions): (
340 &dyn HasherContrasena,
341 &dyn AlmacenCredenciales,
342 &dyn AlmacenSesiones,
343 ) = (&hasher, &credentials, &sessions);
344
345 let hash = credentials.hash_contrasena(id_usuario).await;
347 let accepted = hasher.verificar("secret", Some("h".to_string())).await;
348 let unknown = hasher.verificar("secret", None).await;
349 let session = sessions.abrir(id_usuario).await;
350
351 assert_eq!(hash, Ok(Some("h".to_string())));
353 assert!(accepted);
354 assert!(!unknown);
355 assert_eq!(session.map(|s| s.token), Ok("t".to_string()));
356 }
357
358 #[tokio::test]
359 async fn should_answer_what_the_test_programs_when_mocked() {
360 let mut authenticator = MockAutenticador::new();
362 authenticator
363 .expect_autenticar()
364 .returning(|token| match token {
365 "good" => Ok(Principal::new(Uuid::nil(), "ada")),
366 _ => Err(ErrorAuth::Expirado),
367 });
368 let authenticator: &dyn Autenticador = &authenticator;
369
370 let accepted = authenticator.autenticar("good").await;
372 let rejected = authenticator.autenticar("old").await;
373
374 assert_eq!(accepted.map(|p| p.sujeto), Ok("ada".to_string()));
376 assert_eq!(rejected, Err(ErrorAuth::Expirado));
377 }
378}