io-smtp 0.1.0

SMTP client library
Documentation
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! SMTP SASL XOAUTH2 coroutine (Google's pre-standard OAuth 2.0
//! mechanism, also accepted by Microsoft Exchange Online); supports
//! both the non-IR and SASL-IR (RFC 4954 ยง4) flows. Prefer
//! OAUTHBEARER (RFC 7628) on servers that support both.
//!
//! XOAUTH2: <https://developers.google.com/workspace/gmail/imap/xoauth2-protocol>
//!
//! # Example
//!
//! ```rust,no_run
//! use std::{
//!     borrow::Cow,
//!     io::{Read, Write},
//!     net::TcpStream,
//! };
//!
//! use secrecy::SecretString;
//!
//! use io_smtp::{
//!     coroutine::{SmtpCoroutine, SmtpCoroutineState, SmtpYield},
//!     rfc5321::types::{domain::Domain, ehlo_domain::EhloDomain},
//!     sasl::auth_xoauth2::{SmtpAuthXoauth2, SmtpAuthXoauth2Options},
//! };
//!
//! // Ready stream needed (TCP-connected, TLS-negociated, EHLO consumed)
//! let mut stream = TcpStream::connect("localhost:25").unwrap();
//!
//! let mut buf = [0u8; 4096];
//!
//! let token = SecretString::from("ya29.tokenvalue".to_string());
//! let domain = EhloDomain::Domain(Domain(Cow::Borrowed("client.example.org")));
//! let opts = SmtpAuthXoauth2Options::default();
//! let mut coroutine = SmtpAuthXoauth2::new("alice@example.org", &token, domain, opts);
//! let mut arg = None;
//!
//! loop {
//!     match coroutine.resume(arg.take()) {
//!         SmtpCoroutineState::Yielded(SmtpYield::WantsWrite(bytes)) => {
//!             stream.write_all(&bytes).unwrap();
//!         }
//!         SmtpCoroutineState::Yielded(SmtpYield::WantsRead) => {
//!             let n = stream.read(&mut buf).unwrap();
//!             arg = Some(&buf[..n]);
//!         }
//!         SmtpCoroutineState::Complete(Ok(())) => break,
//!         SmtpCoroutineState::Complete(Err(err)) => panic!("{err}"),
//!     }
//! }
//! ```

use core::fmt;

use alloc::{
    borrow::Cow,
    string::{String, ToString},
    vec::Vec,
};

use base64::{Engine, engine::general_purpose::STANDARD as base64};
use bounded_static::IntoBoundedStatic;
use log::trace;
use secrecy::{ExposeSecret, SecretBox, SecretString};
use thiserror::Error;

use crate::{
    coroutine::*,
    rfc4954::{auth::SmtpAuthCommand, auth_data::SmtpAuthData},
    rfc5321::{
        ehlo::{SmtpEhlo, SmtpEhloError},
        types::{ehlo_domain::EhloDomain, reply_code::ReplyCode},
    },
    send::*,
    smtp_try,
};

/// The SASL mechanism name as it appears on the wire.
pub const XOAUTH2: &str = "XOAUTH2";

/// Options for [`SmtpAuthXoauth2::new`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SmtpAuthXoauth2Options {
    /// `true` selects SASL-IR (inline credentials); `false` selects
    /// the non-IR challenge-response flow.
    pub initial_request: bool,
    /// Refresh capabilities with an `EHLO` after a successful auth.
    pub ensure_capabilities: bool,
}

impl Default for SmtpAuthXoauth2Options {
    fn default() -> Self {
        Self {
            initial_request: true,
            ensure_capabilities: true,
        }
    }
}

/// Failure causes during the SMTP AUTH XOAUTH2 exchange.
#[derive(Debug, Error)]
pub enum SmtpAuthXoauth2Error {
    #[error("SMTP AUTH XOAUTH2 failed: rejected {code} {message}")]
    Rejected { code: u16, message: String },
    #[error("SMTP AUTH XOAUTH2 failed: server did not send the expected continuation request")]
    ExpectedContinuationRequest,
    #[error("SMTP AUTH XOAUTH2 failed: {0}")]
    Send(#[from] SendSmtpCommandError),
    #[error(transparent)]
    Ehlo(#[from] SmtpEhloError),
}

/// I/O-free SMTP AUTH XOAUTH2 coroutine. The connection MUST be
/// TLS-protected before calling this.
pub struct SmtpAuthXoauth2 {
    state: State,
    domain: Option<EhloDomain<'static>>,
    payload: Option<Vec<u8>>,
    error_detail: Option<String>,
    opts: SmtpAuthXoauth2Options,
}

impl SmtpAuthXoauth2 {
    pub fn new(
        username: &str,
        token: &SecretString,
        domain: EhloDomain<'_>,
        opts: SmtpAuthXoauth2Options,
    ) -> Self {
        let payload = build_payload(username, token);

        let state = if opts.initial_request {
            let cmd = SmtpAuthCommand {
                mechanism: Cow::Borrowed(XOAUTH2),
                initial_response: Some(SecretBox::new(payload.clone().into_boxed_slice())),
            };
            State::Send(SendSmtpCommand::new(cmd))
        } else {
            let cmd = SmtpAuthCommand {
                mechanism: Cow::Borrowed(XOAUTH2),
                initial_response: None,
            };
            State::Send(SendSmtpCommand::new(cmd))
        };

        Self {
            state,
            domain: Some(domain.into_static()),
            payload: Some(payload),
            error_detail: None,
            opts,
        }
    }
}

impl SmtpCoroutine for SmtpAuthXoauth2 {
    type Yield = SmtpYield;
    type Return = Result<(), SmtpAuthXoauth2Error>;

    fn resume(&mut self, arg: Option<&[u8]>) -> SmtpCoroutineState<Self::Yield, Self::Return> {
        loop {
            trace!("auth xoauth2: {}", self.state);

            match &mut self.state {
                State::Send(send) => {
                    let out = smtp_try!(send, arg);

                    if out.response.code == ReplyCode::AUTH_SUCCESSFUL {
                        if self.opts.initial_request {
                            self.advance_after_auth();
                            continue;
                        }
                        return SmtpCoroutineState::Complete(Err(
                            SmtpAuthXoauth2Error::ExpectedContinuationRequest,
                        ));
                    }

                    if out.response.code == ReplyCode::AUTH_CONTINUE {
                        if self.opts.initial_request {
                            // Server is asking us to ack the JSON
                            // error detail (XOAUTH2 failure flow).
                            let text = out.response.text().0.trim_start();
                            if let Ok(detail_bytes) = base64.decode(text.as_bytes()) {
                                self.error_detail = String::from_utf8(detail_bytes).ok();
                            }

                            let ack = SmtpAuthData::r#continue(vec![0x01u8]);
                            self.state = State::AckError(SendSmtpCommand::new(ack));
                            continue;
                        }

                        // Non-IR: send the credentials now.
                        let payload = self.payload.take().expect("payload taken twice");
                        let data = SmtpAuthData::r#continue(payload.into_boxed_slice());
                        self.state = State::Continue(SendSmtpCommand::new(data));
                        continue;
                    }

                    let code = out.response.code.code();
                    let message = out.response.text().to_string();
                    return SmtpCoroutineState::Complete(Err(SmtpAuthXoauth2Error::Rejected {
                        code,
                        message,
                    }));
                }
                State::Continue(send) => {
                    let out = smtp_try!(send, arg);

                    if out.response.code == ReplyCode::AUTH_SUCCESSFUL {
                        self.advance_after_auth();
                        continue;
                    }

                    if out.response.code == ReplyCode::AUTH_CONTINUE {
                        let text = out.response.text().0.trim_start();
                        if let Ok(detail_bytes) = base64.decode(text.as_bytes()) {
                            self.error_detail = String::from_utf8(detail_bytes).ok();
                        }

                        let ack = SmtpAuthData::r#continue(vec![0x01u8]);
                        self.state = State::AckError(SendSmtpCommand::new(ack));
                        continue;
                    }

                    let code = out.response.code.code();
                    let message = out.response.text().to_string();
                    return SmtpCoroutineState::Complete(Err(SmtpAuthXoauth2Error::Rejected {
                        code,
                        message,
                    }));
                }
                State::AckError(send) => {
                    let _ = smtp_try!(send, arg);

                    let message = self
                        .error_detail
                        .take()
                        .unwrap_or_else(|| "authentication failed".into());

                    return SmtpCoroutineState::Complete(Err(SmtpAuthXoauth2Error::Rejected {
                        code: 535,
                        message,
                    }));
                }
                State::Ehlo(ehlo) => {
                    let _ = smtp_try!(ehlo, arg);
                    return SmtpCoroutineState::Complete(Ok(()));
                }
                State::Done => return SmtpCoroutineState::Complete(Ok(())),
            }
        }
    }
}

impl SmtpAuthXoauth2 {
    fn advance_after_auth(&mut self) {
        let _ = self.payload.take();
        if self.opts.ensure_capabilities {
            let domain = self.domain.take().expect("domain taken twice");
            self.state = State::Ehlo(SmtpEhlo::new(domain));
        } else {
            self.state = State::Done;
        }
    }
}

enum State {
    Send(SendSmtpCommand<SmtpAuthCommand<'static>>),
    Continue(SendSmtpCommand<SmtpAuthData>),
    AckError(SendSmtpCommand<SmtpAuthData>),
    Ehlo(SmtpEhlo),
    Done,
}

impl fmt::Display for State {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Send(_) => f.write_str("send auth xoauth2"),
            Self::Continue(_) => f.write_str("send credentials"),
            Self::AckError(_) => f.write_str("ack error detail"),
            Self::Ehlo(_) => f.write_str("refresh capabilities"),
            Self::Done => f.write_str("done"),
        }
    }
}

/// Build the XOAUTH2 wire payload:
/// `user=<u>\x01auth=Bearer <t>\x01\x01`.
fn build_payload(username: &str, token: &SecretString) -> Vec<u8> {
    let mut payload = Vec::new();
    payload.extend_from_slice(b"user=");
    payload.extend_from_slice(username.as_bytes());
    payload.push(0x01);
    payload.extend_from_slice(b"auth=Bearer ");
    payload.extend_from_slice(token.expose_secret().as_bytes());
    payload.push(0x01);
    payload.push(0x01);
    payload
}

#[cfg(test)]
mod tests {
    use crate::rfc5321::types::domain::Domain;

    use super::*;

    fn domain() -> EhloDomain<'static> {
        EhloDomain::Domain(Domain(Cow::Borrowed("example.com")))
    }

    fn token() -> SecretString {
        SecretString::from("ya29.tokenvalue".to_string())
    }

    #[test]
    fn ir_success_then_ehlo_returns_ok() {
        let opts = SmtpAuthXoauth2Options::default();
        let mut auth = SmtpAuthXoauth2::new("alice@example.com", &token(), domain(), opts);

        let _ = expect_wants_write(&mut auth, None);
        expect_wants_read(&mut auth);
        let _ehlo = expect_wants_write(&mut auth, Some(b"235 OK\r\n"));
        expect_wants_read(&mut auth);
        expect_complete_ok(&mut auth, b"250 server.example.com\r\n");
    }

    #[test]
    fn ir_success_without_ehlo_returns_ok() {
        let opts = SmtpAuthXoauth2Options {
            initial_request: true,
            ensure_capabilities: false,
        };
        let mut auth = SmtpAuthXoauth2::new("alice@example.com", &token(), domain(), opts);
        let _ = expect_wants_write(&mut auth, None);
        expect_wants_read(&mut auth);
        expect_complete_ok(&mut auth, b"235 OK\r\n");
    }

    #[test]
    fn error_detail_returns_rejected() {
        let opts = SmtpAuthXoauth2Options {
            initial_request: true,
            ensure_capabilities: false,
        };
        let mut auth = SmtpAuthXoauth2::new("alice@example.com", &token(), domain(), opts);
        let _ = expect_wants_write(&mut auth, None);
        expect_wants_read(&mut auth);

        let challenge = b"334 eyJzdGF0dXMiOiI0MDEifQ==\r\n";
        let _ack = expect_wants_write(&mut auth, Some(challenge));
        expect_wants_read(&mut auth);

        let err = expect_complete_err(&mut auth, b"535 authentication failed\r\n");
        let SmtpAuthXoauth2Error::Rejected { code, message } = err else {
            panic!("expected SmtpAuthXoauth2Error::Rejected, got {err:?}");
        };
        assert_eq!(code, 535);
        assert!(message.contains("status") || message.contains("401"));
    }

    #[test]
    fn rejected_returns_rejected_error() {
        let opts = SmtpAuthXoauth2Options::default();
        let mut auth = SmtpAuthXoauth2::new("alice@example.com", &token(), domain(), opts);
        let _ = expect_wants_write(&mut auth, None);
        expect_wants_read(&mut auth);

        let err = expect_complete_err(&mut auth, b"504 mechanism disabled\r\n");
        let SmtpAuthXoauth2Error::Rejected { code, message } = err else {
            panic!("expected SmtpAuthXoauth2Error::Rejected, got {err:?}");
        };
        assert_eq!(code, 504);
        assert_eq!(message, "mechanism disabled");
    }

    #[test]
    fn eof_returns_eof_error() {
        let opts = SmtpAuthXoauth2Options::default();
        let mut auth = SmtpAuthXoauth2::new("alice@example.com", &token(), domain(), opts);
        let _ = expect_wants_write(&mut auth, None);
        expect_wants_read(&mut auth);

        let err = expect_complete_err(&mut auth, b"");
        assert!(matches!(
            err,
            SmtpAuthXoauth2Error::Send(SendSmtpCommandError::Eof)
        ));
    }

    // --- utils

    fn expect_wants_write(cor: &mut SmtpAuthXoauth2, arg: Option<&[u8]>) -> Vec<u8> {
        match cor.resume(arg) {
            SmtpCoroutineState::Yielded(SmtpYield::WantsWrite(bytes)) => bytes,
            state => panic!("expected WantsWrite, got {state:?}"),
        }
    }

    fn expect_wants_read(cor: &mut SmtpAuthXoauth2) {
        match cor.resume(None) {
            SmtpCoroutineState::Yielded(SmtpYield::WantsRead) => {}
            state => panic!("expected WantsRead, got {state:?}"),
        }
    }

    fn expect_complete_ok(cor: &mut SmtpAuthXoauth2, reply: &[u8]) {
        match cor.resume(Some(reply)) {
            SmtpCoroutineState::Complete(Ok(())) => {}
            state => panic!("expected Complete(Ok), got {state:?}"),
        }
    }

    fn expect_complete_err(cor: &mut SmtpAuthXoauth2, reply: &[u8]) -> SmtpAuthXoauth2Error {
        match cor.resume(Some(reply)) {
            SmtpCoroutineState::Complete(Err(err)) => err,
            state => panic!("expected Complete(Err), got {state:?}"),
        }
    }
}