1use core::{fmt, mem};
52
53use alloc::{
54 borrow::Cow,
55 format,
56 string::{String, ToString},
57 vec,
58 vec::Vec,
59};
60
61use imap_codec::{
62 AuthenticateDataCodec, CommandCodec,
63 fragmentizer::Fragmentizer,
64 imap_types::{
65 auth::{AuthMechanism, AuthenticateData},
66 command::{Command, CommandBody},
67 core::{IString, NString, TagGenerator},
68 response::{
69 Capability, Code, CommandContinuationRequest, Data, StatusBody, StatusKind, Tagged,
70 },
71 secret::Secret,
72 },
73};
74use log::{debug, trace};
75use thiserror::Error;
76
77use crate::{coroutine::*, imap_try, rfc2971::id::*, rfc3501::capability::*, send::*};
78
79#[derive(Clone, Debug, Error)]
81pub enum ImapAuthXoauth2Error {
82 #[error("IMAP AUTHENTICATE XOAUTH2 failed: NO {0}")]
84 No(String),
85 #[error("IMAP AUTHENTICATE XOAUTH2 failed: NO {info} ({err})")]
88 NoWithError {
89 info: String,
91 err: String,
93 },
94 #[error("IMAP AUTHENTICATE XOAUTH2 failed: BAD {0}")]
96 Bad(String),
97 #[error("IMAP AUTHENTICATE XOAUTH2 failed: BYE {0}")]
99 Bye(String),
100 #[error("IMAP AUTHENTICATE XOAUTH2 failed: server did not return a tagged response")]
102 MissingTagged,
103 #[error(
105 "IMAP AUTHENTICATE XOAUTH2 failed: server did not send the expected continuation request"
106 )]
107 ExpectedContinuationRequest,
108 #[error("IMAP AUTHENTICATE XOAUTH2 failed: expected NO got {kind:?} ({info})")]
111 UnexpectedStatus {
112 kind: StatusKind,
114 info: String,
116 },
117 #[error(
119 "IMAP AUTHENTICATE XOAUTH2 failed: server returned OK before the mechanism could complete"
120 )]
121 UnexpectedOk,
122 #[error("IMAP AUTHENTICATE XOAUTH2 failed: {0}")]
124 Send(#[from] ImapSendError),
125 #[error(transparent)]
127 Capability(#[from] ImapCapabilityGetError),
128 #[error(transparent)]
130 ServerId(#[from] ImapServerIdError),
131}
132
133#[derive(Clone, Debug, Default, Eq, PartialEq)]
135pub struct ImapAuthXoauth2Options {
136 pub initial_request: bool,
139 pub ensure_capabilities: bool,
142 pub auto_id: Option<Vec<(IString<'static>, NString<'static>)>>,
147}
148
149pub struct ImapAuthXoauth2 {
151 state: State,
152 error: Option<String>,
153 observed: Vec<Capability<'static>>,
154 opts: ImapAuthXoauth2Options,
155}
156
157impl ImapAuthXoauth2 {
158 pub fn new(
165 user: impl AsRef<str>,
166 token: impl AsRef<str>,
167 opts: ImapAuthXoauth2Options,
168 ) -> Self {
169 let user = user.as_ref();
170 let token = token.as_ref();
171 let payload = format!("user={user}\x01auth=Bearer {token}\x01\x01");
172 let payload = Cow::from(payload.into_bytes());
173 let tag = TagGenerator::new().generate();
174
175 let state = if opts.initial_request {
176 let body = CommandBody::Authenticate {
177 mechanism: AuthMechanism::XOAuth2,
178 initial_response: Some(Secret::new(payload)),
179 };
180 let cmd = Command { tag, body };
181 trace!("send IMAP command {cmd:?}");
182 State::SendIr(ImapSend::new(CommandCodec::new(), cmd))
183 } else {
184 let body = CommandBody::Authenticate {
185 mechanism: AuthMechanism::XOAuth2,
186 initial_response: None,
187 };
188 let cmd = Command { tag, body };
189 trace!("send IMAP command {cmd:?}");
190 let send = ImapSend::new(CommandCodec::new(), cmd);
191 State::Send { send, payload }
192 };
193
194 Self {
195 state,
196 error: None,
197 observed: Vec::new(),
198 opts,
199 }
200 }
201
202 fn wants_capability(
203 &mut self,
204 code: Option<Code<'static>>,
205 data: Vec<Data<'static>>,
206 untagged: Vec<StatusBody<'static>>,
207 ) -> Option<State> {
208 let mut new_capability = None;
209
210 if let Some(Code::Capability(capability)) = code {
211 new_capability.replace(capability);
212 }
213
214 for data in data {
215 if let Data::Capability(capability) = data {
216 new_capability.replace(capability);
217 }
218 }
219
220 for StatusBody { code, .. } in untagged {
221 if let Some(Code::Capability(capability)) = code {
222 new_capability.replace(capability);
223 }
224 }
225
226 if let Some(capability) = new_capability {
227 self.observed = capability.into_iter().collect();
228 }
229
230 (self.opts.ensure_capabilities && self.observed.is_empty())
231 .then(|| State::Capability(ImapCapabilityGet::new()))
232 }
233
234 fn wants_id(&mut self) -> Option<State> {
235 let params = self.opts.auto_id.take()?;
236 let wire = (!params.is_empty()).then_some(params);
237 Some(State::Id(ImapServerId::new(ImapServerIdOptions {
238 parameters: wire,
239 })))
240 }
241
242 fn extract_json_error(cr: &CommandContinuationRequest<'_>) -> String {
243 let err = match cr {
244 CommandContinuationRequest::Basic(err) => err.text().to_string().into(),
245 CommandContinuationRequest::Base64(err) => String::from_utf8_lossy(err),
246 };
247
248 err.to_string()
249 }
250}
251
252impl ImapCoroutine for ImapAuthXoauth2 {
253 type Yield = ImapYield;
254 type Return = Result<Vec<Capability<'static>>, ImapAuthXoauth2Error>;
255
256 fn resume(
257 &mut self,
258 fragmentizer: &mut Fragmentizer,
259 arg: Option<&[u8]>,
260 ) -> ImapCoroutineState<Self::Yield, Self::Return> {
261 loop {
262 match &mut self.state {
263 State::Send { send, payload } => {
264 let out = imap_try!(send, fragmentizer, arg);
265
266 if let Some(bye) = out.bye {
267 let err = ImapAuthXoauth2Error::Bye(bye.text.to_string());
268 return ImapCoroutineState::Complete(Err(err));
269 }
270
271 if out.continuation_request.is_some() {
272 let payload = mem::take(payload).into_owned();
273 let auth = AuthenticateData::r#continue(payload);
274 let codec = AuthenticateDataCodec::new();
275 self.state = State::Continue(ImapSend::new(codec, auth));
276 debug!("{}", self.state);
277 continue;
278 }
279
280 if let Some(Tagged { body, .. }) = out.tagged {
281 let err = match body.kind {
282 StatusKind::Ok => ImapAuthXoauth2Error::UnexpectedOk,
283 StatusKind::No => ImapAuthXoauth2Error::No(body.text.to_string()),
284 StatusKind::Bad => ImapAuthXoauth2Error::Bad(body.text.to_string()),
285 };
286
287 return ImapCoroutineState::Complete(Err(err));
288 }
289
290 let err = ImapAuthXoauth2Error::ExpectedContinuationRequest;
291 return ImapCoroutineState::Complete(Err(err));
292 }
293 State::SendIr(send) => {
294 let out = imap_try!(send, fragmentizer, arg);
295
296 if let Some(bye) = out.bye {
297 let err = ImapAuthXoauth2Error::Bye(bye.text.to_string());
298 return ImapCoroutineState::Complete(Err(err));
299 }
300
301 if let Some(cr) = out.continuation_request {
302 self.error.replace(Self::extract_json_error(&cr));
303 let auth = AuthenticateData::r#continue(vec![]);
304 let codec = AuthenticateDataCodec::new();
305 self.state = State::AcknowledgeError(ImapSend::new(codec, auth));
306 debug!("{}", self.state);
307 continue;
308 }
309
310 let Some(Tagged { body, .. }) = out.tagged else {
311 let err = ImapAuthXoauth2Error::MissingTagged;
312 return ImapCoroutineState::Complete(Err(err));
313 };
314
315 let code = match body.kind {
316 StatusKind::Ok => body.code,
317 StatusKind::No => {
318 let err = ImapAuthXoauth2Error::No(body.text.to_string());
319 return ImapCoroutineState::Complete(Err(err));
320 }
321 StatusKind::Bad => {
322 let err = ImapAuthXoauth2Error::Bad(body.text.to_string());
323 return ImapCoroutineState::Complete(Err(err));
324 }
325 };
326
327 if let Some(next) = self.wants_capability(code, out.data, out.untagged) {
328 self.state = next;
329 debug!("{}", self.state);
330 continue;
331 }
332
333 if let Some(next) = self.wants_id() {
334 self.state = next;
335 debug!("{}", self.state);
336 continue;
337 }
338
339 let capability = mem::take(&mut self.observed);
340 return ImapCoroutineState::Complete(Ok(capability));
341 }
342 State::Continue(send) => {
343 let out = imap_try!(send, fragmentizer, arg);
344
345 if let Some(bye) = out.bye {
346 let err = ImapAuthXoauth2Error::Bye(bye.text.to_string());
347 return ImapCoroutineState::Complete(Err(err));
348 }
349
350 if let Some(cr) = out.continuation_request {
351 self.error.replace(Self::extract_json_error(&cr));
352 let auth = AuthenticateData::r#continue(vec![]);
353 let codec = AuthenticateDataCodec::new();
354 self.state = State::AcknowledgeError(ImapSend::new(codec, auth));
355 debug!("{}", self.state);
356 continue;
357 }
358
359 let Some(Tagged { body, .. }) = out.tagged else {
360 let err = ImapAuthXoauth2Error::MissingTagged;
361 return ImapCoroutineState::Complete(Err(err));
362 };
363
364 let code = match body.kind {
365 StatusKind::Ok => body.code,
366 StatusKind::No => {
367 let err = ImapAuthXoauth2Error::No(body.text.to_string());
368 return ImapCoroutineState::Complete(Err(err));
369 }
370 StatusKind::Bad => {
371 let err = ImapAuthXoauth2Error::Bad(body.text.to_string());
372 return ImapCoroutineState::Complete(Err(err));
373 }
374 };
375
376 if let Some(next) = self.wants_capability(code, out.data, out.untagged) {
377 self.state = next;
378 debug!("{}", self.state);
379 continue;
380 }
381
382 if let Some(next) = self.wants_id() {
383 self.state = next;
384 debug!("{}", self.state);
385 continue;
386 }
387
388 let capability = mem::take(&mut self.observed);
389 return ImapCoroutineState::Complete(Ok(capability));
390 }
391 State::AcknowledgeError(send) => {
392 let out = imap_try!(send, fragmentizer, arg);
393
394 if let Some(bye) = out.bye {
395 let err = ImapAuthXoauth2Error::Bye(bye.text.to_string());
396 return ImapCoroutineState::Complete(Err(err));
397 }
398
399 let Some(Tagged { body, .. }) = out.tagged else {
400 let err = ImapAuthXoauth2Error::MissingTagged;
401 return ImapCoroutineState::Complete(Err(err));
402 };
403
404 let info = body.text.to_string();
405
406 let StatusKind::No = body.kind else {
407 let kind = body.kind;
408 let err = ImapAuthXoauth2Error::UnexpectedStatus { kind, info };
409 return ImapCoroutineState::Complete(Err(err));
410 };
411
412 let err = match self.error.take() {
413 Some(err) => ImapAuthXoauth2Error::NoWithError { info, err },
414 None => ImapAuthXoauth2Error::No(info),
415 };
416
417 return ImapCoroutineState::Complete(Err(err));
418 }
419 State::Capability(capability) => {
420 self.observed = imap_try!(capability, fragmentizer, arg);
421
422 if let Some(next) = self.wants_id() {
423 self.state = next;
424 debug!("{}", self.state);
425 continue;
426 }
427
428 let capability = mem::take(&mut self.observed);
429 return ImapCoroutineState::Complete(Ok(capability));
430 }
431 State::Id(id) => {
432 imap_try!(id, fragmentizer, arg);
433 let capability = mem::take(&mut self.observed);
434 return ImapCoroutineState::Complete(Ok(capability));
435 }
436 }
437 }
438 }
439}
440
441enum State {
442 Send {
443 send: ImapSend<CommandCodec>,
444 payload: Cow<'static, [u8]>,
445 },
446 SendIr(ImapSend<CommandCodec>),
447 Continue(ImapSend<AuthenticateDataCodec>),
448 AcknowledgeError(ImapSend<AuthenticateDataCodec>),
449 Capability(ImapCapabilityGet),
450 Id(ImapServerId),
451}
452
453impl fmt::Display for State {
454 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455 match self {
456 Self::Send { .. } => f.write_str("send auth"),
457 Self::SendIr(_) => f.write_str("send auth with ir"),
458 Self::Continue(_) => f.write_str("send credentials"),
459 Self::AcknowledgeError(_) => f.write_str("acknowledge error"),
460 Self::Capability(_) => f.write_str("fetch capabilities"),
461 Self::Id(_) => f.write_str("send id"),
462 }
463 }
464}
465
466#[cfg(test)]
467mod tests {
468 use core::str;
469
470 use crate::sasl::auth_xoauth2::*;
471
472 #[test]
473 fn ir_success_returns_ok() {
474 let opts = ImapAuthXoauth2Options {
475 initial_request: true,
476 ..Default::default()
477 };
478
479 let mut auth = ImapAuthXoauth2::new("user@example.org", "oauth-token", opts);
480 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
481
482 let bytes = expect_wants_write(&mut auth, &mut frag, None);
483 let line = str::from_utf8(&bytes).expect("utf8 command");
484 let tag = first_word(line);
485 assert!(line.contains("AUTHENTICATE XOAUTH2 "));
486
487 expect_wants_read(&mut auth, &mut frag);
488
489 let reply = format!("{tag} OK AUTHENTICATE completed\r\n");
490 expect_complete_ok(&mut auth, &mut frag, reply.as_bytes());
491 }
492
493 #[test]
494 fn ir_invalid_token_returns_no_with_error() {
495 let opts = ImapAuthXoauth2Options {
496 initial_request: true,
497 ..Default::default()
498 };
499
500 let mut auth = ImapAuthXoauth2::new("user@example.org", "expired-token", opts);
501 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
502
503 let bytes = expect_wants_write(&mut auth, &mut frag, None);
504 let tag = first_word(str::from_utf8(&bytes).expect("utf8 command"));
505
506 expect_wants_read(&mut auth, &mut frag);
507
508 let (err_json_b64, err_json) = fake_json_error();
509 let challenge = format!("+ {err_json_b64}\r\n");
510 let ack = expect_wants_write(&mut auth, &mut frag, Some(challenge.as_bytes()));
511 assert_eq!(b"\r\n", &*ack);
512
513 expect_wants_read(&mut auth, &mut frag);
514
515 let reply = format!("{tag} NO SASL authentication failed\r\n");
516 let err = expect_complete_err(&mut auth, &mut frag, reply.as_bytes());
517 let ImapAuthXoauth2Error::NoWithError { info, err } = err else {
518 panic!("expected ImapAuthXoauth2Error::NoWithError, got {err:?}");
519 };
520 assert_eq!(info, "SASL authentication failed");
521 assert_eq!(err, err_json);
522 }
523
524 #[test]
525 fn ir_tagged_bad_returns_bad_error() {
526 let opts = ImapAuthXoauth2Options {
527 initial_request: true,
528 ..Default::default()
529 };
530
531 let mut auth = ImapAuthXoauth2::new("user@example.org", "oauth-token", opts);
532 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
533
534 let bytes = expect_wants_write(&mut auth, &mut frag, None);
535 let tag = first_word(str::from_utf8(&bytes).expect("utf8 command"));
536
537 expect_wants_read(&mut auth, &mut frag);
538
539 let reply = format!("{tag} BAD AUTHENTICATE not enabled\r\n");
540 let err = expect_complete_err(&mut auth, &mut frag, reply.as_bytes());
541 let ImapAuthXoauth2Error::Bad(text) = err else {
542 panic!("expected ImapAuthXoauth2Error::NoWithError, got {err:?}");
543 };
544 assert_eq!(text, "AUTHENTICATE not enabled");
545 }
546
547 #[test]
548 fn non_ir_success_returns_ok() {
549 let opts = ImapAuthXoauth2Options::default();
550 let mut auth = ImapAuthXoauth2::new("user@example.org", "oauth-token", opts);
551 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
552
553 let bytes = expect_wants_write(&mut auth, &mut frag, None);
554 let line = str::from_utf8(&bytes).expect("utf8 command");
555 let tag = first_word(line);
556 assert!(line.trim_end().ends_with("AUTHENTICATE XOAUTH2"));
557
558 expect_wants_read(&mut auth, &mut frag);
559
560 let creds = expect_wants_write(&mut auth, &mut frag, Some(b"+ \r\n"));
561 assert!(creds.ends_with(b"\r\n"));
562
563 expect_wants_read(&mut auth, &mut frag);
564
565 let reply = format!("{tag} OK AUTHENTICATE completed\r\n");
566 expect_complete_ok(&mut auth, &mut frag, reply.as_bytes());
567 }
568
569 #[test]
570 fn non_ir_invalid_token_returns_no_with_error() {
571 let opts = ImapAuthXoauth2Options::default();
572 let mut auth = ImapAuthXoauth2::new("user@example.org", "expired-token", opts);
573 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
574
575 let bytes = expect_wants_write(&mut auth, &mut frag, None);
576 let tag = first_word(str::from_utf8(&bytes).expect("utf8 command"));
577
578 expect_wants_read(&mut auth, &mut frag);
579 expect_wants_write(&mut auth, &mut frag, Some(b"+ \r\n"));
580 expect_wants_read(&mut auth, &mut frag);
581
582 let (err_json_b64, err_json) = fake_json_error();
583 let challenge = format!("+ {err_json_b64}\r\n");
584 let ack = expect_wants_write(&mut auth, &mut frag, Some(challenge.as_bytes()));
585 assert_eq!(b"\r\n", &*ack);
586
587 expect_wants_read(&mut auth, &mut frag);
588
589 let reply = format!("{tag} NO SASL authentication failed\r\n");
590 let err = expect_complete_err(&mut auth, &mut frag, reply.as_bytes());
591 let ImapAuthXoauth2Error::NoWithError { info, err } = err else {
592 panic!("expected ImapAuthXoauth2Error::NoWithError, got {err:?}");
593 };
594 assert_eq!(info, "SASL authentication failed");
595 assert_eq!(err, err_json);
596 }
597
598 fn expect_wants_write(
599 cor: &mut ImapAuthXoauth2,
600 frag: &mut Fragmentizer,
601 arg: Option<&[u8]>,
602 ) -> Vec<u8> {
603 match cor.resume(frag, arg) {
604 ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
605 state => panic!("expected WantsWrite, got {state:?}"),
606 }
607 }
608
609 fn expect_wants_read(cor: &mut ImapAuthXoauth2, frag: &mut Fragmentizer) {
610 match cor.resume(frag, None) {
611 ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
612 state => panic!("expected WantsRead, got {state:?}"),
613 }
614 }
615
616 fn expect_complete_ok(cor: &mut ImapAuthXoauth2, frag: &mut Fragmentizer, reply: &[u8]) {
617 match cor.resume(frag, Some(reply)) {
618 ImapCoroutineState::Complete(Ok(_)) => {}
619 state => panic!("expected Complete(Ok), got {state:?}"),
620 }
621 }
622
623 fn expect_complete_err(
624 cor: &mut ImapAuthXoauth2,
625 frag: &mut Fragmentizer,
626 reply: &[u8],
627 ) -> ImapAuthXoauth2Error {
628 match cor.resume(frag, Some(reply)) {
629 ImapCoroutineState::Complete(Err(err)) => err,
630 state => panic!("expected Complete(Err), got {state:?}"),
631 }
632 }
633
634 fn first_word(line: &str) -> &str {
635 line.split_whitespace()
636 .next()
637 .expect("first whitespace-separated token")
638 }
639
640 fn fake_json_error() -> (&'static str, &'static str) {
641 (
642 "eyJzdGF0dXMiOiI0MDEiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==",
643 "{\"status\":\"401\",\"schemes\":\"Bearer\",\"scope\":\"https://mail.google.com/\"}",
644 )
645 }
646}