Skip to main content

serenade_security/
firewall.rs

1//! HTTP firewall middleware (header → authenticator → request token attribute).
2
3use std::sync::Arc;
4
5use serenade_http::{HttpError, Middleware, Request, RequestHandler, Response};
6
7use crate::{SecurityError, UsernamePasswordToken};
8
9/// Request attribute key where the firewall stores the security token.
10pub const TOKEN_ATTRIBUTE: &str = "_security_token";
11
12/// Turns request credentials into a [`UsernamePasswordToken`].
13pub trait Authenticator: Send + Sync {
14    /// Authenticates using the raw header value (for example `Bearer …` or an API key).
15    ///
16    /// # Errors
17    ///
18    /// Returns [`SecurityError::Authentication`] when credentials are invalid.
19    fn authenticate(
20        &self,
21        credentials: Option<&str>,
22    ) -> Result<UsernamePasswordToken, SecurityError>;
23}
24
25/// Firewall that reads a header, runs an [`Authenticator`], and stores the token on the request.
26pub struct FirewallMiddleware {
27    header_name: String,
28    authenticator: Arc<dyn Authenticator>,
29    allow_anonymous: bool,
30}
31
32impl FirewallMiddleware {
33    /// Creates a firewall reading `header_name` (default apps use `Authorization`).
34    #[must_use]
35    pub fn new(
36        header_name: impl Into<String>,
37        authenticator: impl Authenticator + 'static,
38    ) -> Self {
39        Self {
40            header_name: header_name.into(),
41            authenticator: Arc::new(authenticator),
42            allow_anonymous: false,
43        }
44    }
45
46    /// When `true`, missing credentials become an anonymous token instead of 401.
47    #[must_use]
48    pub const fn allow_anonymous(mut self, allow: bool) -> Self {
49        self.allow_anonymous = allow;
50        self
51    }
52}
53
54impl Middleware for FirewallMiddleware {
55    fn process(
56        &self,
57        request: &mut Request,
58        next: &dyn RequestHandler,
59    ) -> Result<Response, HttpError> {
60        let credentials = request.headers().get(&self.header_name);
61        let token = if credentials.is_none() && self.allow_anonymous {
62            UsernamePasswordToken::anonymous()
63        } else {
64            self.authenticator
65                .authenticate(credentials)
66                .map_err(|err| HttpError::status(401, err.to_string()))?
67        };
68        request.attributes_mut().insert(TOKEN_ATTRIBUTE, token);
69        next.handle(request)
70    }
71}
72
73/// Returns the firewall token from request attributes when present.
74#[must_use]
75pub fn request_token(request: &Request) -> Option<&UsernamePasswordToken> {
76    request
77        .attributes()
78        .get::<UsernamePasswordToken>(TOKEN_ATTRIBUTE)
79}