Skip to main content

puerto_nucleo/
auth.rs

1//! Auth (ADR-0021): who is calling and the port that says so. A route sees a [`Principal`], never a
2//! token; where the token was checked — an OIDC provider, a local session — is the
3//! [`Autenticador`]'s business. The adapters are `puerto-auth`'s and `puerto-sqlx`'s, the HTTP
4//! side (`BearerAuth`, `#[requiere_rol]`) `puerto-web`'s.
5
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8use thiserror::Error;
9use uuid::Uuid;
10
11use crate::ErrorRepositorio;
12
13/// The authenticated caller.
14///
15/// `id_usuario` is the local `User` row every caller has (ADR-0021 § 3); `sujeto` is who the
16/// provider says it is. `roles` decide `#[requiere_rol]`; rules that depend on data take the
17/// principal in their params and decide in the use case.
18///
19/// `#[non_exhaustive]`: built with [`Principal::new`] and the `with_*` methods, so a new field
20/// later breaks no one.
21#[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    /// Whether the caller holds `role` — compared exactly, as the provider or the `roles` column
67    /// spells it.
68    pub fn tiene_rol(&self, role: &str) -> bool {
69        self.roles.iter().any(|held| held == role)
70    }
71}
72
73/// Why a token did not become a [`Principal`]. The first two are the caller's (401), the last is
74/// ours (503): the adapter logs the cause, the API answers the code.
75#[non_exhaustive]
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
77pub enum ErrorAuth {
78    /// Malformed, badly signed, for another issuer or audience, or an unknown session.
79    #[error("auth.invalido")]
80    Invalido,
81    /// Was valid once: the token or the session expired.
82    #[error("auth.expirado")]
83    Expirado,
84    /// Could not be checked: the provider or the database is unreachable.
85    #[error("auth.no_disponible")]
86    NoDisponible,
87}
88
89/// Turns a bearer token into the caller. `bootstrap.rs` registers one on the routes;
90/// `puerto_web::auth::BearerAuth` asks it on every protected request.
91#[async_trait]
92pub trait Autenticador: Send + Sync {
93    async fn autenticar(&self, token: &str) -> Result<Principal, ErrorAuth>;
94}
95
96// ── Local mode (ADR-0021 § 2): the API is the identity provider ─────────────────
97
98/// Hashing a password failed — ours, not the caller's (500).
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
100#[error("auth.hash_fallido")]
101pub struct ErrorHash;
102
103/// Turns passwords into stored hashes and checks them. `puerto_auth::HasherArgon2` in a project;
104/// the generated `register_user` and `login` use cases see only this port.
105#[async_trait]
106pub trait HasherContrasena: Send + Sync {
107    async fn hash(&self, password: &str) -> Result<String, ErrorHash>;
108
109    /// Whether `password` matches `hash`. `None` — an unknown email — still does the work against
110    /// a fixed hash and answers `false`: the caller cannot tell the two cases apart by the time
111    /// the answer takes.
112    async fn verificar(&self, password: &str, hash: Option<String>) -> bool;
113}
114
115/// Where each user's password hash is kept, apart from the user (`User` carries no secret).
116#[async_trait]
117pub trait AlmacenCredenciales: Send + Sync {
118    async fn hash_contrasena(&self, id_usuario: Uuid) -> Result<Option<String>, ErrorRepositorio>;
119    /// Sets or replaces the user's hash.
120    async fn guardar_hash_contrasena(
121        &self,
122        id_usuario: Uuid,
123        hash: &str,
124    ) -> Result<(), ErrorRepositorio>;
125}
126
127/// A session `login` opened: the opaque token the client sends back as a bearer token, and when
128/// it stops being accepted.
129#[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/// Opens and revokes sessions. `puerto_sqlx::auth::PgSessions` keeps them, and is the
146/// [`Autenticador`] of a local project too.
147#[async_trait]
148pub trait AlmacenSesiones: Send + Sync {
149    async fn abrir(&self, id_usuario: Uuid) -> Result<Sesion, ErrorRepositorio>;
150    /// Revokes the session `token` opened; an unknown token is already revoked.
151    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    /// Quien llama, para los tests (ADR-0021): un usuario con sesión y un id nuevo, con o sin
160    /// roles.
161    #[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        /// Alguien con sesión y sin ningún rol.
189        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        // Act
244        let admin = dobles::MadrePrincipal::new()
245            .con_roles(["admin"])
246            .construir();
247        let otro = dobles::MadrePrincipal::aleatorio();
248
249        // Assert
250        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        // Arrange
258        let id_usuario = Uuid::now_v7();
259
260        // Act
261        let principal = Principal::new(id_usuario, "auth0|ada");
262
263        // Assert
264        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        // Arrange
274        let id_usuario = Uuid::now_v7();
275
276        // Act
277        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
284        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        // Arrange
293        let principal = Principal::new(Uuid::nil(), "ada").con_roles(["admin"]);
294
295        // Act / Assert
296        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        // Arrange
312        let expira_en = chrono::Utc::now();
313
314        // Act
315        let session = Sesion::new("opaque", expira_en);
316
317        // Assert
318        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        // Arrange
326        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        // Act
346        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
352        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        // Arrange
361        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        // Act
371        let accepted = authenticator.autenticar("good").await;
372        let rejected = authenticator.autenticar("old").await;
373
374        // Assert
375        assert_eq!(accepted.map(|p| p.sujeto), Ok("ada".to_string()));
376        assert_eq!(rejected, Err(ErrorAuth::Expirado));
377    }
378}