summaryrefslogtreecommitdiff
path: root/crates/pop3/src/op/authenticate.rs
blob: 1924d4f2bdf897b6103557e6300002f56ffae565 (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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use common::{
    listener::{limiter::ConcurrencyLimiter, SessionStream},
    ConcurrencyLimiters,
};
use directory::Permission;
use imap::op::authenticate::{decode_challenge_oauth, decode_challenge_plain};
use jmap::auth::{
    authenticate::Authenticator, oauth::token::TokenHandler, rate_limit::RateLimiter,
};
use mail_parser::decoders::base64::base64_decode;
use mail_send::Credentials;
use std::sync::Arc;

use crate::{
    protocol::{request, Command, Mechanism},
    Session, State,
};

impl<T: SessionStream> Session<T> {
    pub async fn handle_sasl(
        &mut self,
        mechanism: Mechanism,
        mut params: Vec<String>,
    ) -> trc::Result<()> {
        match mechanism {
            Mechanism::Plain | Mechanism::OAuthBearer => {
                if !params.is_empty() {
                    let credentials = base64_decode(params.pop().unwrap().as_bytes())
                        .ok_or("Failed to decode challenge.")
                        .and_then(|challenge| {
                            if mechanism == Mechanism::Plain {
                                decode_challenge_plain(&challenge)
                            } else {
                                decode_challenge_oauth(&challenge)
                            }
                        })
                        .map_err(|err| trc::AuthEvent::Error.into_err().details(err))?;

                    self.handle_auth(credentials).await
                } else {
                    // TODO: This hack is temporary until the SASL library is developed
                    self.receiver.state = request::State::Argument {
                        request: Command::Auth {
                            mechanism: mechanism.as_str().as_bytes().to_vec(),
                            params: vec![],
                        },
                        num: 1,
                        last_is_space: true,
                    };

                    self.write_bytes("+\r\n").await
                }
            }
            _ => Err(trc::AuthEvent::Error
                .into_err()
                .details("Authentication mechanism not supported.")),
        }
    }

    pub async fn handle_auth(&mut self, credentials: Credentials<String>) -> trc::Result<()> {
        // Throttle authentication requests
        self.server.is_auth_allowed_soft(&self.remote_addr).await?;

        // Authenticate
        let access_token = match credentials {
            Credentials::Plain { username, secret } | Credentials::XOauth2 { username, secret } => {
                self.server
                    .authenticate_plain(&username, &secret, self.remote_addr, self.session_id)
                    .await
            }
            Credentials::OAuthBearer { token } => {
                match self
                    .server
                    .validate_access_token("access_token", &token)
                    .await
                {
                    Ok((account_id, _, _)) => self.server.get_access_token(account_id).await,
                    Err(err) => Err(err),
                }
            }
        }
        .map_err(|err| {
            if err.matches(trc::EventType::Auth(trc::AuthEvent::Failed)) {
                match &self.state {
                    State::NotAuthenticated {
                        auth_failures,
                        username,
                    } if *auth_failures < self.server.core.imap.max_auth_failures => {
                        self.state = State::NotAuthenticated {
                            auth_failures: auth_failures + 1,
                            username: username.clone(),
                        };
                    }
                    _ => {
                        return trc::AuthEvent::TooManyAttempts.into_err().caused_by(err);
                    }
                }
            }

            err
        })?;

        // Enforce concurrency limits
        let in_flight = match self
            .get_concurrency_limiter(access_token.primary_id())
            .map(|limiter| limiter.concurrent_requests.is_allowed())
        {
            Some(Some(limiter)) => Some(limiter),
            None => None,
            Some(None) => {
                return Err(trc::LimitEvent::ConcurrentRequest.into_err());
            }
        };

        // Validate access
        access_token.assert_has_permission(Permission::Pop3Authenticate)?;

        // Cache access token
        let access_token = Arc::new(access_token);
        self.server.cache_access_token(access_token.clone());

        // Fetch mailbox
        let mailbox = self.fetch_mailbox(access_token.primary_id()).await?;

        // Create session
        self.state = State::Authenticated {
            in_flight,
            mailbox,
            access_token,
        };
        self.write_ok("Authentication successful").await
    }

    pub fn get_concurrency_limiter(&self, account_id: u32) -> Option<Arc<ConcurrencyLimiters>> {
        let rate = self.server.core.imap.rate_concurrent?;
        self.server
            .inner
            .data
            .imap_limiter
            .get(&account_id)
            .map(|limiter| limiter.clone())
            .unwrap_or_else(|| {
                let limiter = Arc::new(ConcurrencyLimiters {
                    concurrent_requests: ConcurrencyLimiter::new(rate),
                    concurrent_uploads: ConcurrencyLimiter::new(rate),
                });
                self.server
                    .inner
                    .data
                    .imap_limiter
                    .insert(account_id, limiter.clone());
                limiter
            })
            .into()
    }
}