Skip to main content

waveless_runtime/services/auth/session/
watchdog.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use crate::*;
5
6/// TODO: add documentation.
7#[derive(Clone, Constructor, Debug)]
8pub struct SessionWatchdog<S>
9where
10    S: Service<RequestCx, Response = ResponseCx, Error = RequestError>,
11{
12    inner: S,
13}
14
15pub struct SessionWatchdogLayer;
16
17impl<S> Layer<S> for SessionWatchdogLayer
18where
19    S: Service<RequestCx, Response = ResponseCx, Error = RequestError>,
20{
21    type Service = SessionWatchdog<S>;
22
23    fn layer(&self, inner: S) -> Self::Service {
24        SessionWatchdog { inner }
25    }
26}
27
28impl<S> Service<RequestCx> for SessionWatchdog<S>
29where
30    S: Service<RequestCx, Response = ResponseCx, Error = RequestError> + Clone + Send + 'static,
31    S::Future: Send + 'static,
32    S::Response: Send + 'static,
33    S::Error: Send + 'static,
34{
35    type Response = S::Response;
36
37    type Error = S::Error;
38
39    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
40
41    fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
42        Poll::Ready(Ok(()))
43    }
44
45    #[instrument(skip_all)]
46    fn call(&mut self, mut cx: RequestCx) -> Self::Future {
47        let mut inner = self.inner.to_owned();
48
49        let future: Pin<_> = Box::pin(async move {
50            let RequestCx {
51                request,
52                request_params,
53                endpoint,
54                ..
55            } = &mut cx;
56
57            let auth = endpoint.auth();
58
59            let headers = request.headers();
60
61            let _build_lock = RuntimeCx::acquire().build();
62
63            let auth_config = _build_lock
64                .read()
65                .await
66                .config()
67                .authentication()
68                .to_owned();
69
70            if let Some(auth_config) = auth_config { 'auth_flow: {
71                // TODO: the compiler should fail when including endpoints
72                // that require authentication while not having
73                // authentication set for the project.
74
75                // Loads the session's method's and role's method's databases.
76                let session_method = auth_config.session();
77
78                let Ok(db_conns) = session_method.get_db_handle() else {
79                    return Err(RequestError::Other(eyre!(
80                        "Cannot get the database connection for the session databases.",
81                    )));
82                };
83
84                // Check the session.
85                let token = match (headers.get("Authorization"), headers.get("Cookie")) {
86                    (Some(auth_header), _) if !auth_header.is_empty() => {
87                        if let Ok(token) = auth_header.to_str() {
88                            Some(token)
89                        } else {
90                            // TODO: future connections from the same origin
91                            // may be throttled.
92
93                            return Err(RequestError::Expected(
94                                StatusCode::BAD_REQUEST,
95                                "Malformed auth header.".into(),
96                            ));
97                        }
98                    }
99                    (_, Some(cookie_header)) if !cookie_header.is_empty()=> {
100                        if let Ok(cookies) = cookie_header.to_str() {
101                            let cookies = cookies
102                                .trim()
103                                .split(';')
104                                .map(|cookie| cookie.split_once('='));
105
106                            let authorization_cookie = cookies
107                                .filter(|opt| {
108                                    opt.map(|(name, _)| name.to_lowercase() == "authorization")
109                                        .unwrap_or(false)
110                                })
111                                .flatten()
112                                .next();
113                            if let Some((_, token)) = authorization_cookie {
114                                Some(token)
115                            } else {
116                                None
117                            }
118                        } else {
119                            // TODO: future connections from the same origin
120                            // may be throttled.
121                            return Err(RequestError::Expected(
122                                StatusCode::BAD_REQUEST,
123                                "Malformed cookie header.".into(),
124                            ));
125                        }
126                    }
127                    _ => None,
128                };
129
130                let Some(token) = token else {
131                    if let AuthLevel::Required = auth.level() {
132                        return Err(RequestError::Expected(
133                            StatusCode::UNAUTHORIZED,
134                            format!("'{}' requires authentication.", endpoint.id()).into(),
135                        ));
136                    }
137                    else {
138                        break 'auth_flow;
139                    }
140                };
141
142                let session_check = session_method
143                    .check(db_conns, token.into())
144                    .await
145                    .map_err(|err| {
146                        RequestError::Other(eyre!("Cannot check the session token. {}", err))
147                })?;
148
149                match session_check {
150                    Some(user_id) => {
151                        // Inject user id if required.
152                        match auth.level() {
153                            AuthLevel::Required | AuthLevel::InjectWhenAvailable => {
154                                request_params.insert(
155                                    "user_id".into(),
156                                    ParamValue::Internal(user_id.to_compact_string()),
157                                );
158
159                                request_params
160                                    .insert("token".into(), ParamValue::Internal(token.into()));
161                            },
162                            _ => ()
163                        }
164
165                        if auth.allowed_roles().is_empty() {
166                            break 'auth_flow;
167                        } else {
168                            let Some(role_method) = auth_config.role() else {
169                                // TODO: the compiler should fail when including endpoints
170                                // that requires roles while not having roles set for the project.
171                                return Err(RequestError::Other(eyre!(
172                                    "Endpoint '{}' requires roles authentication but they are not set for this build.",
173                                    endpoint.id()
174                                )));
175                            };
176
177                            let Ok(role_db) = role_method.get_db_handle() else {
178                                return Err(RequestError::Other(eyre!(
179                                    "Cannot get the database connection for the roles databases."
180                                )));
181                            };
182
183                            let Ok(role_check) = role_method.get(role_db, user_id).await else {
184                                return Err(RequestError::Other(eyre!(
185                                    "Cannot check the user's role."
186                                )));
187                            };
188
189                            let Some(role) = role_check else {
190                                return Err(RequestError::Expected(
191                                    StatusCode::UNAUTHORIZED,
192                                    "Current user does not have any role.".into(),
193                                ));
194                            };
195
196                            if auth.allowed_roles().contains(&role.to_lowercase()) {
197                                break 'auth_flow;
198                            } else {
199                                return Err(RequestError::Expected(
200                                    StatusCode::UNAUTHORIZED,
201                                    "Current user does not have any of the allowed roles.".into(),
202                                ));
203                            }
204                        }
205                    }
206                    None if let AuthLevel::Required = auth.level() => {
207                        return Err(RequestError::Expected(
208                            StatusCode::UNAUTHORIZED,
209                            "Invalid session.".into(),
210                        ))
211                    },
212                    _ => (),
213                }}
214            } else {
215                if let AuthLevel::Required = auth.level() {
216                    Err(RequestError::Other(eyre!(
217                        "Endpoint '{}' requires auth but authentication is not set for this build.",
218                        endpoint.id()))
219                    )?
220                }
221            }
222
223            inner.call(cx).await
224        })
225        .into();
226
227        future as Self::Future // `rust-analyzer` complains here.
228    }
229}