Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_mail/tests/imap_authenticate.rs

9.1 KiB, 1 run

created by r18615380:77330, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! IMAP `AUTHENTICATE` (RFC 3501 §6.2.2) with the PLAIN and LOGIN mechanisms, and the initial
2//! response of RFC 4959, against the same user store `LOGIN` checks.
3
4use oxedyne_fe2o3_core::prelude::*;
5use oxedyne_fe2o3_mail::maildir::MaildirStore;
6use oxedyne_fe2o3_net::{
7 imap::server::ImapServer,
8 mail::{
9 store::{
10 MailStore,
11 MailUser,
12 },
13 user::UserStore,
14 },
15};
16use oxedyne_fe2o3_text::base64;
17
18use std::{
19 fs,
20 path::PathBuf,
21 sync::Arc,
22};
23
24use tokio::{
25 io::{
26 AsyncBufReadExt,
27 AsyncWriteExt,
28 BufReader,
29 },
30 net::{
31 TcpListener,
32 TcpStream,
33 },
34};
35
36
37const USER: &str = "alice@test.local";
38const PASS: &str = "correct-horse";
39
40#[derive(Clone, Debug)]
41struct OneUser;
42
43impl UserStore for OneUser {
44 fn authenticate(&self, address: &str, password: &str) -> Outcome<Option<MailUser>> {
45 if address.eq_ignore_ascii_case(USER) && password == PASS {
46 return self.lookup(address);
47 }
48 Ok(None)
49 }
50
51 fn lookup(&self, address: &str) -> Outcome<Option<MailUser>> {
52 if !address.eq_ignore_ascii_case(USER) { return Ok(None); }
53 Ok(Some(MailUser {
54 local: fmt!("alice"),
55 domain: fmt!("test.local"),
56 delivery_key: fmt!("test.local/alice"),
57 send_as: Vec::new(),
58 }))
59 }
60}
61
62struct Sess {
63 r: BufReader<TcpStream>,
64 root: PathBuf,
65}
66
67impl Sess {
68 async fn open(name: &str) -> Outcome<Self> {
69 let root = std::env::temp_dir().join(fmt!("fe2o3_imap_auth_{}_{}", name, std::process::id()));
70 let _ = fs::remove_dir_all(&root);
71 res!(fs::create_dir_all(&root), IO, File);
72 let store = res!(MaildirStore::new(root.clone(), "test.local"));
73 let u = match res!(OneUser.lookup(USER)) {
74 Some(u) => u,
75 None => return Err(err!("The test user did not resolve."; Test, Bug)),
76 };
77 res!(store.ensure_user(&u));
78 let lis = res!(TcpListener::bind("127.0.0.1:0").await, IO, Network);
79 let port = res!(lis.local_addr(), IO, Network).port();
80 let srv = ImapServer { store, users: OneUser, hostname: Arc::new(fmt!("test.local")) };
81 tokio::spawn(async move {
82 while let Ok((sock, peer)) = lis.accept().await {
83 let s = srv.clone();
84 tokio::spawn(async move { let _ = s.run(sock, peer).await; });
85 }
86 });
87 let t = res!(TcpStream::connect(("127.0.0.1", port)).await, IO, Network);
88 let mut s = Sess { r: BufReader::new(t), root };
89 res!(s.line().await);
90 Ok(s)
91 }
92
93 async fn send(&mut self, text: &str) -> Outcome<()> {
94 res!(self.r.get_mut().write_all(fmt!("{}\r\n", text).as_bytes()).await, IO, Network);
95 Ok(())
96 }
97
98 async fn line(&mut self) -> Outcome<String> {
99 let mut l = String::new();
100 if res!(self.r.read_line(&mut l).await, IO, Network) == 0 {
101 return Err(err!("The server closed the connection."; IO, Network));
102 }
103 Ok(l.trim_end().to_string())
104 }
105
106 /// Reads to the line tagged `tag`, or to a `+` continuation, and returns it.
107 async fn reply(&mut self, tag: &str) -> Outcome<String> {
108 loop {
109 let l = res!(self.line().await);
110 if l.starts_with(&fmt!("{} ", tag)) || l.starts_with('+') { return Ok(l); }
111 }
112 }
113
114 async fn cmd(&mut self, tag: &str, text: &str) -> Outcome<String> {
115 res!(self.send(&fmt!("{} {}", tag, text)).await);
116 self.reply(tag).await
117 }
118}
119
120impl Drop for Sess {
121 fn drop(&mut self) { let _ = fs::remove_dir_all(&self.root); }
122}
123
124fn plain(authzid: &str, user: &str, pass: &str) -> String {
125 base64::encode(fmt!("{}\0{}\0{}", authzid, user, pass).as_bytes())
126}
127
128fn is(line: &str, tag: &str, status: &str) -> bool {
129 line.starts_with(&fmt!("{} {}", tag, status))
130}
131
132/// Whether the session is signed in, judged by a command that needs it.
133async fn signed_in(s: &mut Sess) -> Outcome<bool> {
134 let l = res!(s.cmd("s1", "SELECT INBOX").await);
135 Ok(is(&l, "s1", "OK"))
136}
137
138#[tokio::test(flavor = "multi_thread")]
139async fn plain_with_an_initial_response_signs_in() -> Outcome<()> {
140 let mut s = res!(Sess::open("ir").await);
141 let l = res!(s.cmd("a1", &fmt!("AUTHENTICATE PLAIN {}", plain("", USER, PASS))).await);
142 req!(true, is(&l, "a1", "OK"), "AUTHENTICATE PLAIN with SASL-IR: {}", l);
143 req!(true, res!(signed_in(&mut s).await));
144 Ok(())
145}
146
147#[tokio::test(flavor = "multi_thread")]
148async fn plain_after_a_continuation_signs_in() -> Outcome<()> {
149 let mut s = res!(Sess::open("cont").await);
150 let l = res!(s.cmd("a1", "AUTHENTICATE PLAIN").await);
151 req!(true, l.starts_with('+'), "Expected a continuation, got: {}", l);
152 res!(s.send(&plain(USER, USER, PASS)).await);
153 let l = res!(s.reply("a1").await);
154 req!(true, is(&l, "a1", "OK"), "AUTHENTICATE PLAIN after +: {}", l);
155 req!(true, res!(signed_in(&mut s).await));
156 Ok(())
157}
158
159#[tokio::test(flavor = "multi_thread")]
160async fn plain_with_a_wrong_password_is_no() -> Outcome<()> {
161 let mut s = res!(Sess::open("wrong").await);
162 let l = res!(s.cmd("a1", &fmt!("AUTHENTICATE PLAIN {}", plain("", USER, "wrong"))).await);
163 req!(true, is(&l, "a1", "NO"), "A wrong password: {}", l);
164 req!(true, l.contains("AUTHENTICATIONFAILED"), "A wrong password: {}", l);
165 req!(false, res!(signed_in(&mut s).await));
166 Ok(())
167}
168
169#[tokio::test(flavor = "multi_thread")]
170async fn plain_acting_as_another_account_is_no() -> Outcome<()> {
171 let mut s = res!(Sess::open("authz").await);
172 let l = res!(s.cmd("a1", &fmt!("AUTHENTICATE PLAIN {}",
173 plain("bob@test.local", USER, PASS))).await);
174 req!(true, is(&l, "a1", "NO"), "Another authzid: {}", l);
175 req!(false, res!(signed_in(&mut s).await));
176 Ok(())
177}
178
179#[tokio::test(flavor = "multi_thread")]
180async fn a_response_that_is_not_base64_is_refused() -> Outcome<()> {
181 let mut s = res!(Sess::open("b64").await);
182 let l = res!(s.cmd("a1", "AUTHENTICATE PLAIN not!base64").await);
183 req!(true, is(&l, "a1", "BAD") || is(&l, "a1", "NO"), "Not base64: {}", l);
184 let l = res!(s.cmd("a2", &fmt!("AUTHENTICATE PLAIN {}",
185 base64::encode(b"no separators here"))).await);
186 req!(true, is(&l, "a2", "BAD") || is(&l, "a2", "NO"), "No NULs: {}", l);
187 req!(false, res!(signed_in(&mut s).await));
188 Ok(())
189}
190
191#[tokio::test(flavor = "multi_thread")]
192async fn a_cancelled_exchange_is_bad() -> Outcome<()> {
193 let mut s = res!(Sess::open("cancel").await);
194 let l = res!(s.cmd("a1", "AUTHENTICATE PLAIN").await);
195 req!(true, l.starts_with('+'), "Expected a continuation, got: {}", l);
196 res!(s.send("*").await);
197 let l = res!(s.reply("a1").await);
198 req!(true, is(&l, "a1", "BAD"), "A cancelled exchange: {}", l);
199 req!(false, res!(signed_in(&mut s).await));
200 Ok(())
201}
202
203#[tokio::test(flavor = "multi_thread")]
204async fn the_login_mechanism_signs_in() -> Outcome<()> {
205 let mut s = res!(Sess::open("mechlogin").await);
206 let l = res!(s.cmd("a1", "AUTHENTICATE LOGIN").await);
207 req!(fmt!("+ {}", base64::encode(b"Username:")), l);
208 res!(s.send(&base64::encode(USER.as_bytes())).await);
209 let l = res!(s.reply("a1").await);
210 req!(fmt!("+ {}", base64::encode(b"Password:")), l);
211 res!(s.send(&base64::encode(PASS.as_bytes())).await);
212 let l = res!(s.reply("a1").await);
213 req!(true, is(&l, "a1", "OK"), "AUTHENTICATE LOGIN: {}", l);
214 req!(true, res!(signed_in(&mut s).await));
215 Ok(())
216}
217
218#[tokio::test(flavor = "multi_thread")]
219async fn the_login_command_still_signs_in() -> Outcome<()> {
220 let mut s = res!(Sess::open("cmdlogin").await);
221 let l = res!(s.cmd("a1", &fmt!("LOGIN {} wrong", USER)).await);
222 req!(true, is(&l, "a1", "NO"), "LOGIN with a wrong password: {}", l);
223 let l = res!(s.cmd("a2", &fmt!("LOGIN {} {}", USER, PASS)).await);
224 req!(true, is(&l, "a2", "OK"), "LOGIN: {}", l);
225 req!(true, res!(signed_in(&mut s).await));
226 Ok(())
227}
228
229/// Every advertised `AUTH=` mechanism runs an exchange, rather than being refused as unknown.
230#[tokio::test(flavor = "multi_thread")]
231async fn every_advertised_mechanism_is_implemented() -> Outcome<()> {
232 let mut s = res!(Sess::open("caps").await);
233 res!(s.send("c1 CAPABILITY").await);
234 let mut caps = String::new();
235 loop {
236 let l = res!(s.line().await);
237 if l.starts_with("* CAPABILITY ") { caps = l.clone(); }
238 if l.starts_with("c1 ") { break; }
239 }
240 let mechs: Vec<&str> = caps.split_whitespace().filter_map(|w| w.strip_prefix("AUTH=")).collect();
241 req!(true, mechs.contains(&"PLAIN"), "{}", caps);
242 req!(true, caps.split_whitespace().any(|w| w == "SASL-IR"), "{}", caps);
243 for (i, m) in mechs.iter().enumerate() {
244 let tag = fmt!("m{}", i);
245 let l = res!(s.cmd(&tag, &fmt!("AUTHENTICATE {}", m)).await);
246 req!(true, l.starts_with('+'), "AUTH={} gave no continuation: {}", m, l);
247 res!(s.send("*").await);
248 let l = res!(s.reply(&tag).await);
249 req!(true, is(&l, &tag, "BAD"), "AUTH={} cancel: {}", m, l);
250 }
251 let l = res!(s.cmd("x1", "AUTHENTICATE CRAM-MD5").await);
252 req!(true, is(&l, "x1", "NO"), "An unadvertised mechanism: {}", l);
253 Ok(())
254}