summaryrefslogtreecommitdiff
path: root/crates/jmap/src/auth/authenticate.rs
blob: 4e04d9ab13f09db9f9d16de25cbf016d4ae1cad5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use std::sync::Arc;

use common::{auth::AuthRequest, listener::limiter::InFlight, Server};
use hyper::header;
use mail_parser::decoders::base64::base64_decode;
use mail_send::Credentials;
use utils::map::ttl_dashmap::TtlMap;

use crate::api::{http::HttpSessionData, HttpRequest};

use common::auth::AccessToken;
use std::future::Future;

use super::rate_limit::RateLimiter;

pub trait Authenticator: Sync + Send {
    fn authenticate_headers(
        &self,
        req: &HttpRequest,
        session: &HttpSessionData,
        allow_api_access: bool,
    ) -> impl Future<Output = trc::Result<(InFlight, Arc<AccessToken>)>> + Send;
}

impl Authenticator for Server {
    async fn authenticate_headers(
        &self,
        req: &HttpRequest,
        session: &HttpSessionData,
        allow_api_access: bool,
    ) -> trc::Result<(InFlight, Arc<AccessToken>)> {
        if let Some((mechanism, token)) = req.authorization() {
            let access_token =
                if let Some(account_id) = self.inner.data.http_auth_cache.get_with_ttl(token) {
                    self.get_cached_access_token(account_id).await?
                } else {
                    let credentials = if mechanism.eq_ignore_ascii_case("basic") {
                        // Throttle authentication requests
                        self.is_auth_allowed_soft(&session.remote_ip).await?;

                        // Decode the base64 encoded credentials
                        decode_plain_auth(token).ok_or_else(|| {
                            trc::AuthEvent::Error
                                .into_err()
                                .details("Failed to decode Basic auth request.")
                                .id(token.to_string())
                                .caused_by(trc::location!())
                        })?
                    } else if mechanism.eq_ignore_ascii_case("bearer") {
                        // Enforce anonymous rate limit
                        self.is_anonymous_allowed(&session.remote_ip).await?;

                        decode_bearer_token(token, allow_api_access).ok_or_else(|| {
                            trc::AuthEvent::Error
                                .into_err()
                                .details("Failed to decode Bearer token.")
                                .id(token.to_string())
                                .caused_by(trc::location!())
                        })?
                    } else {
                        // Enforce anonymous rate limit
                        self.is_anonymous_allowed(&session.remote_ip).await?;

                        return Err(trc::AuthEvent::Error
                            .into_err()
                            .reason("Unsupported authentication mechanism.")
                            .details(token.to_string())
                            .caused_by(trc::location!()));
                    };

                    // Authenticate
                    let access_token = match self
                        .authenticate(&AuthRequest::from_credentials(
                            credentials,
                            session.session_id,
                            session.remote_ip,
                        ))
                        .await
                    {
                        Ok(access_token) => access_token,
                        Err(err) => {
                            if err.matches(trc::EventType::Auth(trc::AuthEvent::Failed)) {
                                let _ = self.is_auth_allowed_hard(&session.remote_ip).await;
                            }
                            return Err(err);
                        }
                    };

                    // Cache session
                    self.cache_session(token.to_string(), &access_token);
                    access_token
                };

            // Enforce authenticated rate limit
            self.is_account_allowed(&access_token)
                .await
                .map(|in_flight| (in_flight, access_token))
        } else {
            // Enforce anonymous rate limit
            self.is_anonymous_allowed(&session.remote_ip).await?;

            Err(trc::AuthEvent::Failed
                .into_err()
                .details("Missing Authorization header.")
                .caused_by(trc::location!()))
        }
    }
}

pub trait HttpHeaders {
    fn authorization(&self) -> Option<(&str, &str)>;
    fn authorization_basic(&self) -> Option<&str>;
}

impl HttpHeaders for HttpRequest {
    fn authorization(&self) -> Option<(&str, &str)> {
        self.headers()
            .get(header::AUTHORIZATION)
            .and_then(|h| h.to_str().ok())
            .and_then(|h| h.split_once(' ').map(|(l, t)| (l, t.trim())))
    }

    fn authorization_basic(&self) -> Option<&str> {
        self.authorization().and_then(|(l, t)| {
            if l.eq_ignore_ascii_case("basic") {
                Some(t)
            } else {
                None
            }
        })
    }
}

fn decode_plain_auth(token: &str) -> Option<Credentials<String>> {
    base64_decode(token.as_bytes())
        .and_then(|token| String::from_utf8(token).ok())
        .and_then(|token| {
            token
                .split_once(':')
                .map(|(login, secret)| Credentials::Plain {
                    username: login.trim().to_lowercase(),
                    secret: secret.to_string(),
                })
        })
}

fn decode_bearer_token(token: &str, allow_api_access: bool) -> Option<Credentials<String>> {
    if allow_api_access {
        if let Some(token) = token.strip_prefix("api_") {
            return decode_plain_auth(token);
        }
    }

    Some(Credentials::OAuthBearer {
        token: token.to_string(),
    })
}