Skip to main content

io_imap/rfc3501/
login.rs

1//! IMAP LOGIN coroutine; credentials travel in the clear, so the channel
2//! must be TLS-protected.
3//!
4//! # Example
5//!
6//! ```rust,no_run
7//! use std::{
8//!     io::{Read, Write},
9//!     net::TcpStream,
10//! };
11//!
12//! use io_imap::{
13//!     codec::fragmentizer::Fragmentizer,
14//!     coroutine::{ImapCoroutine, ImapCoroutineState, ImapYield},
15//!     rfc3501::login::{ImapLogin, ImapLoginOptions},
16//! };
17//!
18//! // Ready stream needed (TCP-connected, TLS-negociated)
19//! let mut stream = TcpStream::connect("localhost:143").unwrap();
20//!
21//! let mut fragmentizer = Fragmentizer::new(50 * 1024 * 1024);
22//! let mut buf = [0u8; 4096];
23//!
24//! let opts = ImapLoginOptions::default();
25//! let mut coroutine = ImapLogin::new("alice", "secret", opts).unwrap();
26//! let mut arg = None;
27//!
28//! let capability = loop {
29//!     match coroutine.resume(&mut fragmentizer, arg.take()) {
30//!         ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => {
31//!             stream.write_all(&bytes).unwrap();
32//!         }
33//!         ImapCoroutineState::Yielded(ImapYield::WantsRead) => {
34//!             let n = stream.read(&mut buf).unwrap();
35//!             arg = Some(&buf[..n]);
36//!         }
37//!         ImapCoroutineState::Complete(Ok(capability)) => break capability,
38//!         ImapCoroutineState::Complete(Err(err)) => panic!("{err}"),
39//!     }
40//! };
41//!
42//! println!("{capability:?}");
43//! ```
44
45use core::{fmt, mem};
46
47use alloc::{
48    string::{String, ToString},
49    vec::Vec,
50};
51
52use imap_codec::{
53    CommandCodec,
54    fragmentizer::Fragmentizer,
55    imap_types::{
56        command::{Command, CommandBody},
57        core::{IString, NString, TagGenerator},
58        error::ValidationError,
59        response::{Capability, Code, Data, StatusKind, Tagged},
60        secret::Secret,
61    },
62};
63use log::trace;
64use thiserror::Error;
65
66use crate::{coroutine::*, imap_try, rfc2971::id::*, rfc3501::capability::*, send::*};
67
68/// Failure causes during the IMAP LOGIN flow.
69#[derive(Clone, Debug, Error)]
70pub enum ImapLoginError {
71    #[error("IMAP LOGIN failed: NO {0}")]
72    No(String),
73    #[error("IMAP LOGIN failed: BAD {0}")]
74    Bad(String),
75    #[error("IMAP LOGIN failed: BYE {0}")]
76    Bye(String),
77
78    #[error("IMAP LOGIN failed: server did not return a tagged response")]
79    MissingTagged,
80
81    #[error("IMAP LOGIN failed: {0}")]
82    Send(#[from] SendImapCommandError),
83    #[error(transparent)]
84    Capability(#[from] ImapCapabilityGetError),
85    #[error(transparent)]
86    ServerId(#[from] ImapServerIdError),
87}
88
89/// Optional post-authentication round-trips.
90#[derive(Clone, Debug, Default, Eq, PartialEq)]
91pub struct ImapLoginOptions {
92    pub ensure_capabilities: bool,
93    pub auto_id: Option<Vec<(IString<'static>, NString<'static>)>>,
94}
95
96/// I/O-free IMAP LOGIN coroutine.
97pub struct ImapLogin {
98    state: State,
99    observed: Vec<Capability<'static>>,
100    opts: ImapLoginOptions,
101}
102
103impl ImapLogin {
104    /// Fails on credentials that cannot be encoded as IMAP AStrings
105    /// (NUL, CR, LF).
106    pub fn new(
107        user: impl AsRef<str>,
108        password: impl AsRef<str>,
109        opts: ImapLoginOptions,
110    ) -> Result<Self, ValidationError> {
111        let username = user.as_ref().to_string().try_into()?;
112        let password = Secret::new(password.as_ref().to_string().try_into()?);
113
114        let cmd = Command {
115            tag: TagGenerator::new().generate(),
116            body: CommandBody::Login { username, password },
117        };
118        trace!("send IMAP command {cmd:?}");
119        let send = SendImapCommand::new(CommandCodec::new(), cmd);
120
121        Ok(Self {
122            state: State::Send(send),
123            observed: Vec::new(),
124            opts,
125        })
126    }
127
128    fn wants_capability(&mut self) -> Option<State> {
129        (self.opts.ensure_capabilities && self.observed.is_empty())
130            .then(|| State::Capability(ImapCapabilityGet::new()))
131    }
132
133    fn wants_id(&mut self) -> Option<State> {
134        let params = self.opts.auto_id.take()?;
135        let wire = (!params.is_empty()).then_some(params);
136        Some(State::Id(ImapServerId::new(ImapServerIdOptions {
137            parameters: wire,
138        })))
139    }
140}
141
142impl ImapCoroutine for ImapLogin {
143    type Yield = ImapYield;
144    type Return = Result<Vec<Capability<'static>>, ImapLoginError>;
145
146    fn resume(
147        &mut self,
148        fragmentizer: &mut Fragmentizer,
149        arg: Option<&[u8]>,
150    ) -> ImapCoroutineState<Self::Yield, Self::Return> {
151        loop {
152            trace!("login: {}", self.state);
153            match &mut self.state {
154                State::Send(send) => {
155                    let out = imap_try!(send, fragmentizer, arg);
156
157                    if let Some(bye) = out.bye {
158                        let err = ImapLoginError::Bye(bye.text.to_string());
159                        return ImapCoroutineState::Complete(Err(err));
160                    }
161
162                    let Some(Tagged { body, .. }) = out.tagged else {
163                        let err = ImapLoginError::MissingTagged;
164                        return ImapCoroutineState::Complete(Err(err));
165                    };
166
167                    let code = match body.kind {
168                        StatusKind::Ok => body.code,
169                        StatusKind::No => {
170                            let err = ImapLoginError::No(body.text.to_string());
171                            return ImapCoroutineState::Complete(Err(err));
172                        }
173                        StatusKind::Bad => {
174                            let err = ImapLoginError::Bad(body.text.to_string());
175                            return ImapCoroutineState::Complete(Err(err));
176                        }
177                    };
178
179                    let mut new_capability = None;
180
181                    if let Some(Code::Capability(capability)) = code {
182                        new_capability.replace(capability);
183                    }
184
185                    for data in out.data {
186                        if let Data::Capability(capability) = data {
187                            new_capability.replace(capability);
188                        }
189                    }
190
191                    if let Some(capability) = new_capability {
192                        self.observed = capability.into_iter().collect();
193                    }
194
195                    if let Some(next) = self.wants_capability() {
196                        self.state = next;
197                        continue;
198                    }
199
200                    if let Some(next) = self.wants_id() {
201                        self.state = next;
202                        continue;
203                    }
204
205                    let capability = mem::take(&mut self.observed);
206                    return ImapCoroutineState::Complete(Ok(capability));
207                }
208                State::Capability(capability) => {
209                    self.observed = imap_try!(capability, fragmentizer, arg);
210
211                    if let Some(next) = self.wants_id() {
212                        self.state = next;
213                        continue;
214                    }
215
216                    let capability = mem::take(&mut self.observed);
217                    return ImapCoroutineState::Complete(Ok(capability));
218                }
219                State::Id(id) => {
220                    imap_try!(id, fragmentizer, arg);
221                    let capability = mem::take(&mut self.observed);
222                    return ImapCoroutineState::Complete(Ok(capability));
223                }
224            }
225        }
226    }
227}
228
229enum State {
230    Send(SendImapCommand<CommandCodec>),
231    Capability(ImapCapabilityGet),
232    Id(ImapServerId),
233}
234
235impl fmt::Display for State {
236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237        match self {
238            Self::Send(_) => f.write_str("send login"),
239            Self::Capability(_) => f.write_str("fetch capabilities"),
240            Self::Id(_) => f.write_str("send id"),
241        }
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use core::str;
248
249    use super::*;
250
251    #[test]
252    fn success_returns_ok() {
253        let opts = ImapLoginOptions::default();
254        let mut auth = ImapLogin::new("alice", "secret", opts).expect("valid credentials");
255        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
256
257        let bytes = expect_wants_write(&mut auth, &mut frag, None);
258        let line = str::from_utf8(&bytes).expect("utf8 command");
259        let tag = first_word(line);
260        assert!(line.contains("LOGIN "));
261
262        expect_wants_read(&mut auth, &mut frag);
263
264        let reply = format!("{tag} OK LOGIN completed\r\n");
265        expect_complete_ok(&mut auth, &mut frag, reply.as_bytes());
266    }
267
268    #[test]
269    fn invalid_credentials_returns_no_error() {
270        let opts = ImapLoginOptions::default();
271        let mut auth = ImapLogin::new("alice", "wrong", opts).expect("valid credentials");
272        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
273
274        let bytes = expect_wants_write(&mut auth, &mut frag, None);
275        let tag = first_word(str::from_utf8(&bytes).expect("utf8 command"));
276
277        expect_wants_read(&mut auth, &mut frag);
278
279        let reply = format!("{tag} NO authentication failed\r\n");
280        let err = expect_complete_err(&mut auth, &mut frag, reply.as_bytes());
281        let ImapLoginError::No(text) = err else {
282            panic!("expected ImapLoginError::No, got {err:?}");
283        };
284        assert_eq!(text, "authentication failed");
285    }
286
287    #[test]
288    fn tagged_bad_returns_bad_error() {
289        let opts = ImapLoginOptions::default();
290        let mut auth = ImapLogin::new("alice", "secret", opts).expect("valid credentials");
291        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
292
293        let bytes = expect_wants_write(&mut auth, &mut frag, None);
294        let tag = first_word(str::from_utf8(&bytes).expect("utf8 command"));
295
296        expect_wants_read(&mut auth, &mut frag);
297
298        let reply = format!("{tag} BAD LOGIN disabled\r\n");
299        let err = expect_complete_err(&mut auth, &mut frag, reply.as_bytes());
300        let ImapLoginError::Bad(text) = err else {
301            panic!("expected ImapLoginError::Bad, got {err:?}");
302        };
303        assert_eq!(text, "LOGIN disabled");
304    }
305
306    #[test]
307    fn success_with_capability_code_observes_capability() {
308        let opts = ImapLoginOptions::default();
309        let mut auth = ImapLogin::new("alice", "secret", opts).expect("valid credentials");
310        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
311
312        let bytes = expect_wants_write(&mut auth, &mut frag, None);
313        let tag = first_word(str::from_utf8(&bytes).expect("utf8 command"));
314
315        expect_wants_read(&mut auth, &mut frag);
316
317        let reply = format!("{tag} OK [CAPABILITY IMAP4rev1 IDLE] LOGIN completed\r\n");
318        let caps = match auth.resume(&mut frag, Some(reply.as_bytes())) {
319            ImapCoroutineState::Complete(Ok(caps)) => caps,
320            state => panic!("expected Complete(Ok), got {state:?}"),
321        };
322        assert!(caps.iter().any(|c| matches!(c, Capability::Imap4Rev1)));
323        assert!(caps.iter().any(|c| matches!(c, Capability::Idle)));
324    }
325
326    #[test]
327    fn nul_in_password_fails_at_construction() {
328        let opts = ImapLoginOptions::default();
329        let result = ImapLogin::new("alice", "bad\0password", opts);
330        assert!(
331            result.is_err(),
332            "expected construction to refuse NUL in password",
333        );
334    }
335
336    // --- utils
337
338    fn expect_wants_write(
339        cor: &mut ImapLogin,
340        frag: &mut Fragmentizer,
341        arg: Option<&[u8]>,
342    ) -> Vec<u8> {
343        match cor.resume(frag, arg) {
344            ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
345            state => panic!("expected WantsWrite, got {state:?}"),
346        }
347    }
348
349    fn expect_wants_read(cor: &mut ImapLogin, frag: &mut Fragmentizer) {
350        match cor.resume(frag, None) {
351            ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
352            state => panic!("expected WantsRead, got {state:?}"),
353        }
354    }
355
356    fn expect_complete_ok(cor: &mut ImapLogin, frag: &mut Fragmentizer, reply: &[u8]) {
357        match cor.resume(frag, Some(reply)) {
358            ImapCoroutineState::Complete(Ok(_)) => {}
359            state => panic!("expected Complete(Ok), got {state:?}"),
360        }
361    }
362
363    fn expect_complete_err(
364        cor: &mut ImapLogin,
365        frag: &mut Fragmentizer,
366        reply: &[u8],
367    ) -> ImapLoginError {
368        match cor.resume(frag, Some(reply)) {
369            ImapCoroutineState::Complete(Err(err)) => err,
370            state => panic!("expected Complete(Err), got {state:?}"),
371        }
372    }
373
374    fn first_word(line: &str) -> &str {
375        line.split_whitespace()
376            .next()
377            .expect("first whitespace-separated token")
378    }
379}