rusmes-imap 0.1.2

Async IMAP4rev2 server for RusMES — RFC 9051 compliant with CONDSTORE, QRESYNC, UIDPLUS, MOVE, IDLE, NAMESPACE, and SPECIAL-USE extensions
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! IMAP AUTHENTICATE command implementation with SASL integration
//!
//! This module implements the AUTHENTICATE command as specified in RFC 3501 Section 6.2.2,
//! integrating the SASL framework from rusmes-auth.
//!
//! Supported SASL mechanisms:
//! - PLAIN (RFC 4616)
//! - LOGIN (obsolete but widely used)
//! - CRAM-MD5 (RFC 2195)
//! - SCRAM-SHA-256 (RFC 5802, RFC 7677)
//! - XOAUTH2 (RFC 7628)
//!
//! # Authentication Flow
//!
//! ## Basic Flow (PLAIN, single-step)
//! ```text
//! C: A001 AUTHENTICATE PLAIN
//! S: +
//! C: <base64-encoded credentials>
//! S: A001 OK AUTHENTICATE completed
//! ```
//!
//! ## Challenge-Response Flow (CRAM-MD5, SCRAM-SHA-256)
//! ```text
//! C: A001 AUTHENTICATE CRAM-MD5
//! S: + <base64-encoded challenge>
//! C: <base64-encoded response>
//! S: A001 OK AUTHENTICATE completed
//! ```
//!
//! ## Initial Response Optimization (RFC 4959)
//! ```text
//! C: A001 AUTHENTICATE PLAIN <base64-encoded credentials>
//! S: A001 OK AUTHENTICATE completed
//! ```

use crate::response::ImapResponse;
use crate::session::{ImapSession, ImapState};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use rusmes_auth::{sasl::SaslServer, AuthBackend};

/// Authentication state for multi-step SASL authentication
#[derive(Debug)]
pub enum AuthenticateState {
    /// Initial state - mechanism selected, waiting for client data
    Initial,
    /// Challenge sent, waiting for response
    Challenge,
    /// Completed (success or failure)
    Completed,
}

/// AUTHENTICATE command context for tracking multi-step authentication
pub struct AuthenticateContext {
    /// SASL mechanism instance
    mechanism: Box<dyn rusmes_auth::sasl::SaslMechanism>,
    /// Current authentication state
    #[allow(dead_code)]
    state: AuthenticateState,
    /// Tag from original AUTHENTICATE command
    tag: String,
}

impl AuthenticateContext {
    /// Create a new authentication context
    pub fn new(mechanism: Box<dyn rusmes_auth::sasl::SaslMechanism>, tag: String) -> Self {
        Self {
            mechanism,
            state: AuthenticateState::Initial,
            tag,
        }
    }

    /// Get the tag
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// Get the mechanism name
    pub fn mechanism_name(&self) -> &str {
        self.mechanism.name()
    }
}

/// Handle AUTHENTICATE command
///
/// # Arguments
/// * `session` - Current IMAP session
/// * `tag` - Command tag
/// * `mechanism_name` - SASL mechanism name (e.g., "PLAIN", "CRAM-MD5")
/// * `initial_response` - Optional initial response (RFC 4959 SASL-IR)
/// * `sasl_server` - SASL server for mechanism creation
/// * `auth_backend` - Authentication backend
///
/// # Returns
/// Returns an IMAP response and optionally an authentication context for multi-step auth
pub async fn handle_authenticate(
    session: &mut ImapSession,
    tag: &str,
    mechanism_name: &str,
    initial_response: Option<&str>,
    sasl_server: &SaslServer,
    auth_backend: &dyn AuthBackend,
) -> anyhow::Result<(ImapResponse, Option<AuthenticateContext>)> {
    // Must be in NotAuthenticated state
    if !matches!(session.state(), ImapState::NotAuthenticated) {
        return Ok((ImapResponse::bad(tag, "Already authenticated"), None));
    }

    // Check if mechanism is supported
    if !sasl_server.is_mechanism_enabled(mechanism_name) {
        return Ok((
            ImapResponse::no(
                tag,
                format!(
                    "[AUTHENTICATIONFAILED] Mechanism {} not supported",
                    mechanism_name
                ),
            ),
            None,
        ));
    }

    // Create mechanism instance
    let mut mechanism = match sasl_server.create_mechanism(mechanism_name) {
        Ok(m) => m,
        Err(e) => {
            return Ok((
                ImapResponse::no(tag, format!("[AUTHENTICATIONFAILED] {}", e)),
                None,
            ));
        }
    };

    // Handle initial response if provided (SASL-IR, RFC 4959)
    if let Some(initial_resp) = initial_response {
        // Decode the base64-encoded initial response
        let decoded = match BASE64.decode(initial_resp.trim()) {
            Ok(d) => d,
            Err(e) => {
                return Ok((
                    ImapResponse::bad(tag, format!("Invalid Base64 in initial response: {}", e)),
                    None,
                ));
            }
        };

        let decoded_str = std::str::from_utf8(&decoded).unwrap_or("");

        return handle_authenticate_step(session, tag, mechanism, decoded_str, auth_backend).await;
    }

    // No initial response - send continuation or challenge based on mechanism
    let auth_backend_ref: &dyn AuthBackend = auth_backend;

    match mechanism.step(b"", auth_backend_ref).await {
        Ok(rusmes_auth::sasl::SaslStep::Challenge { data }) => {
            // Mechanism needs to send a challenge
            let encoded = BASE64.encode(&data);
            let ctx = AuthenticateContext {
                mechanism,
                state: AuthenticateState::Challenge,
                tag: tag.to_string(),
            };
            Ok((ImapResponse::new(None, "+", encoded), Some(ctx)))
        }
        Ok(rusmes_auth::sasl::SaslStep::Continue) => {
            // Mechanism needs more data from client (no challenge)
            let ctx = AuthenticateContext {
                mechanism,
                state: AuthenticateState::Initial,
                tag: tag.to_string(),
            };
            Ok((ImapResponse::new(None, "+", ""), Some(ctx)))
        }
        Ok(rusmes_auth::sasl::SaslStep::Done { success, username }) => {
            // Authentication completed in first step (shouldn't happen without initial response)
            if success && username.is_some() {
                session.state = ImapState::Authenticated;
                session.username = username;
                Ok((ImapResponse::ok(tag, "AUTHENTICATE completed"), None))
            } else {
                Ok((
                    ImapResponse::no(tag, "[AUTHENTICATIONFAILED] Authentication failed"),
                    None,
                ))
            }
        }
        Err(e) => Ok((
            ImapResponse::no(tag, format!("[AUTHENTICATIONFAILED] {}", e)),
            None,
        )),
    }
}

/// Continue multi-step authentication with client response
///
/// # Arguments
/// * `session` - Current IMAP session
/// * `ctx` - Authentication context from previous step
/// * `client_data` - Base64-encoded client response
/// * `auth_backend` - Authentication backend
///
/// # Returns
/// Returns an IMAP response and optionally an updated authentication context
pub async fn handle_authenticate_continue(
    session: &mut ImapSession,
    ctx: AuthenticateContext,
    client_data: &str,
    auth_backend: &dyn AuthBackend,
) -> anyhow::Result<(ImapResponse, Option<AuthenticateContext>)> {
    // Check for cancellation (client sends "*")
    if client_data.trim() == "*" {
        return Ok((ImapResponse::bad(&ctx.tag, "AUTHENTICATE cancelled"), None));
    }

    // Decode client response
    let decoded = match BASE64.decode(client_data.trim()) {
        Ok(d) => d,
        Err(e) => {
            return Ok((
                ImapResponse::bad(&ctx.tag, format!("Invalid Base64: {}", e)),
                None,
            ));
        }
    };

    // Process the step
    handle_authenticate_step(
        session,
        &ctx.tag,
        ctx.mechanism,
        std::str::from_utf8(&decoded).unwrap_or(""),
        auth_backend,
    )
    .await
}

/// Handle a single authentication step
async fn handle_authenticate_step(
    session: &mut ImapSession,
    tag: &str,
    mut mechanism: Box<dyn rusmes_auth::sasl::SaslMechanism>,
    client_data: &str,
    auth_backend: &dyn AuthBackend,
) -> anyhow::Result<(ImapResponse, Option<AuthenticateContext>)> {
    let auth_backend_ref: &dyn AuthBackend = auth_backend;

    match mechanism
        .step(client_data.as_bytes(), auth_backend_ref)
        .await
    {
        Ok(rusmes_auth::sasl::SaslStep::Challenge { data }) => {
            // Send another challenge
            let encoded = BASE64.encode(&data);
            let ctx = AuthenticateContext {
                mechanism,
                state: AuthenticateState::Challenge,
                tag: tag.to_string(),
            };
            Ok((ImapResponse::new(None, "+", encoded), Some(ctx)))
        }
        Ok(rusmes_auth::sasl::SaslStep::Continue) => {
            // Need more data from client
            let ctx = AuthenticateContext {
                mechanism,
                state: AuthenticateState::Challenge,
                tag: tag.to_string(),
            };
            Ok((ImapResponse::new(None, "+", ""), Some(ctx)))
        }
        Ok(rusmes_auth::sasl::SaslStep::Done { success, username }) => {
            // Authentication completed
            if success && username.is_some() {
                session.state = ImapState::Authenticated;
                session.username = username.clone();
                let user_str = username
                    .map(|u| u.to_string())
                    .unwrap_or_else(|| "user".to_string());
                Ok((
                    ImapResponse::ok(tag, format!("{} authenticated", user_str)),
                    None,
                ))
            } else {
                Ok((
                    ImapResponse::no(tag, "[AUTHENTICATIONFAILED] Authentication failed"),
                    None,
                ))
            }
        }
        Err(e) => Ok((
            ImapResponse::no(tag, format!("[AUTHENTICATIONFAILED] {}", e)),
            None,
        )),
    }
}

/// Parse AUTHENTICATE command
///
/// Syntax: AUTHENTICATE `<mechanism>` \[`<initial-response>`\]
///
/// Returns (mechanism_name, optional_initial_response)
pub fn parse_authenticate_args(args: &str) -> anyhow::Result<(String, Option<String>)> {
    let parts: Vec<&str> = args.split_whitespace().collect();

    if parts.is_empty() {
        return Err(anyhow::anyhow!("Missing mechanism name"));
    }

    let mechanism = parts[0].to_uppercase();
    let initial_response = if parts.len() > 1 {
        // Handle "=" as empty initial response (RFC 4959)
        if parts[1] == "=" {
            Some(String::new())
        } else {
            Some(parts[1].to_string())
        }
    } else {
        None
    };

    Ok((mechanism, initial_response))
}

/// Helper to create a SASL server with default configuration
pub fn create_default_sasl_server(hostname: String) -> SaslServer {
    use rusmes_auth::sasl::SaslConfig;
    let config = SaslConfig {
        enabled_mechanisms: vec![
            "PLAIN".to_string(),
            "LOGIN".to_string(),
            "CRAM-MD5".to_string(),
            "SCRAM-SHA-256".to_string(),
            "XOAUTH2".to_string(),
        ],
        hostname,
    };
    SaslServer::new(config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use rusmes_auth::sasl::SaslConfig;
    use rusmes_proto::Username;

    // Mock auth backend for testing
    struct MockAuthBackend {
        valid_users: Vec<(String, String)>,
    }

    #[async_trait]
    impl AuthBackend for MockAuthBackend {
        async fn authenticate(&self, username: &Username, password: &str) -> anyhow::Result<bool> {
            Ok(self
                .valid_users
                .iter()
                .any(|(u, p)| u == username.as_str() && p == password))
        }

        async fn verify_identity(&self, username: &Username) -> anyhow::Result<bool> {
            Ok(self.valid_users.iter().any(|(u, _)| u == username.as_str()))
        }

        async fn list_users(&self) -> anyhow::Result<Vec<Username>> {
            Ok(vec![])
        }

        async fn create_user(&self, _username: &Username, _password: &str) -> anyhow::Result<()> {
            Ok(())
        }

        async fn delete_user(&self, _username: &Username) -> anyhow::Result<()> {
            Ok(())
        }

        async fn change_password(
            &self,
            _username: &Username,
            _new_password: &str,
        ) -> anyhow::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn test_parse_authenticate_args_basic() {
        let (mechanism, initial_resp) =
            parse_authenticate_args("PLAIN").expect("PLAIN mechanism parse should succeed");
        assert_eq!(mechanism, "PLAIN");
        assert!(initial_resp.is_none());
    }

    #[test]
    fn test_parse_authenticate_args_with_initial_response() {
        let (mechanism, initial_resp) = parse_authenticate_args("PLAIN AHRlc3R1c2VyAHRlc3RwYXNz")
            .expect("PLAIN with initial response parse should succeed");
        assert_eq!(mechanism, "PLAIN");
        assert_eq!(initial_resp, Some("AHRlc3R1c2VyAHRlc3RwYXNz".to_string()));
    }

    #[test]
    fn test_parse_authenticate_args_empty_initial_response() {
        let (mechanism, initial_resp) = parse_authenticate_args("PLAIN =")
            .expect("PLAIN with empty initial response (=) parse should succeed");
        assert_eq!(mechanism, "PLAIN");
        assert_eq!(initial_resp, Some(String::new()));
    }

    #[test]
    fn test_parse_authenticate_args_case_insensitive() {
        let (mechanism, _) =
            parse_authenticate_args("plain").expect("lowercase plain parse should succeed");
        assert_eq!(mechanism, "PLAIN");

        let (mechanism, _) =
            parse_authenticate_args("Cram-Md5").expect("mixed-case Cram-Md5 parse should succeed");
        assert_eq!(mechanism, "CRAM-MD5");
    }

    #[test]
    fn test_parse_authenticate_args_no_mechanism() {
        let result = parse_authenticate_args("");
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_handle_authenticate_plain_with_initial_response() {
        let backend = MockAuthBackend {
            valid_users: vec![("testuser".to_string(), "testpass".to_string())],
        };

        let config = SaslConfig {
            enabled_mechanisms: vec!["PLAIN".to_string()],
            hostname: "localhost".to_string(),
        };
        let sasl_server = SaslServer::new(config);

        let mut session = ImapSession::new();

        // PLAIN credentials: \0testuser\0testpass encoded in base64
        let initial_response = BASE64.encode(b"\0testuser\0testpass");

        let (response, ctx) = handle_authenticate(
            &mut session,
            "A001",
            "PLAIN",
            Some(&initial_response),
            &sasl_server,
            &backend,
        )
        .await
        .expect("PLAIN auth with valid credentials should succeed");

        assert!(ctx.is_none()); // Should complete in one step
        assert!(response.format().contains("OK"));
        assert!(matches!(session.state(), ImapState::Authenticated));
    }

    #[tokio::test]
    async fn test_handle_authenticate_plain_wrong_credentials() {
        let backend = MockAuthBackend {
            valid_users: vec![("testuser".to_string(), "testpass".to_string())],
        };

        let config = SaslConfig {
            enabled_mechanisms: vec!["PLAIN".to_string()],
            hostname: "localhost".to_string(),
        };
        let sasl_server = SaslServer::new(config);

        let mut session = ImapSession::new();

        // Wrong password
        let initial_response = BASE64.encode(b"\0testuser\0wrongpass");

        let (response, ctx) = handle_authenticate(
            &mut session,
            "A001",
            "PLAIN",
            Some(&initial_response),
            &sasl_server,
            &backend,
        )
        .await
        .expect("PLAIN auth handler should not error even with wrong credentials");

        assert!(ctx.is_none());
        assert!(response.format().contains("NO"));
        assert!(response.format().contains("AUTHENTICATIONFAILED"));
        assert!(matches!(session.state(), ImapState::NotAuthenticated));
    }

    #[tokio::test]
    async fn test_handle_authenticate_unsupported_mechanism() {
        let backend = MockAuthBackend {
            valid_users: vec![],
        };

        let config = SaslConfig {
            enabled_mechanisms: vec!["PLAIN".to_string()],
            hostname: "localhost".to_string(),
        };
        let sasl_server = SaslServer::new(config);

        let mut session = ImapSession::new();

        let (response, ctx) = handle_authenticate(
            &mut session,
            "A001",
            "UNKNOWN",
            None,
            &sasl_server,
            &backend,
        )
        .await
        .expect("auth handler should not error for unsupported mechanism");

        assert!(ctx.is_none());
        assert!(response.format().contains("NO"));
        assert!(response.format().contains("not supported"));
    }

    #[tokio::test]
    async fn test_handle_authenticate_already_authenticated() {
        let backend = MockAuthBackend {
            valid_users: vec![],
        };

        let config = SaslConfig {
            enabled_mechanisms: vec!["PLAIN".to_string()],
            hostname: "localhost".to_string(),
        };
        let sasl_server = SaslServer::new(config);

        let mut session = ImapSession::new();
        session.state = ImapState::Authenticated; // Already authenticated

        let (response, ctx) =
            handle_authenticate(&mut session, "A001", "PLAIN", None, &sasl_server, &backend)
                .await
                .expect("auth handler should not error for already-authenticated session");

        assert!(ctx.is_none());
        assert!(response.format().contains("BAD"));
        assert!(response.format().contains("Already authenticated"));
    }

    #[tokio::test]
    async fn test_handle_authenticate_login_multi_step() {
        let backend = MockAuthBackend {
            valid_users: vec![("testuser".to_string(), "testpass".to_string())],
        };

        let config = SaslConfig {
            enabled_mechanisms: vec!["LOGIN".to_string()],
            hostname: "localhost".to_string(),
        };
        let sasl_server = SaslServer::new(config);

        let mut session = ImapSession::new();

        // Step 1: Start authentication
        let (response, ctx) =
            handle_authenticate(&mut session, "A001", "LOGIN", None, &sasl_server, &backend)
                .await
                .expect("LOGIN auth initiation should succeed");

        assert!(ctx.is_some());
        assert!(response.format().contains("+"));

        let ctx = ctx.expect("LOGIN step 1 should return a continuation context");

        // Step 2: Send username
        let username_b64 = BASE64.encode(b"testuser");
        let (response, ctx) =
            handle_authenticate_continue(&mut session, ctx, &username_b64, &backend)
                .await
                .expect("LOGIN step 2 (username) should succeed");

        assert!(ctx.is_some());
        assert!(response.format().contains("+"));

        let ctx = ctx.expect("LOGIN step 2 should return a continuation context for password");

        // Step 3: Send password
        let password_b64 = BASE64.encode(b"testpass");
        let (response, ctx) =
            handle_authenticate_continue(&mut session, ctx, &password_b64, &backend)
                .await
                .expect("LOGIN step 3 (password) should succeed");

        assert!(ctx.is_none());
        assert!(response.format().contains("OK"));
        assert!(matches!(session.state(), ImapState::Authenticated));
    }

    #[tokio::test]
    async fn test_handle_authenticate_cancel() {
        let backend = MockAuthBackend {
            valid_users: vec![],
        };

        let config = SaslConfig {
            enabled_mechanisms: vec!["LOGIN".to_string()],
            hostname: "localhost".to_string(),
        };
        let sasl_server = SaslServer::new(config);

        let mut session = ImapSession::new();

        // Start authentication
        let (_, ctx) =
            handle_authenticate(&mut session, "A001", "LOGIN", None, &sasl_server, &backend)
                .await
                .expect("LOGIN auth initiation should succeed");

        let ctx = ctx.expect("LOGIN auth initiation should return a continuation context");

        // Cancel with "*"
        let (response, ctx) = handle_authenticate_continue(&mut session, ctx, "*", &backend)
            .await
            .expect("auth cancellation via * should not error");

        assert!(ctx.is_none());
        assert!(response.format().contains("BAD"));
        assert!(response.format().contains("cancelled"));
    }

    #[test]
    fn test_create_default_sasl_server() {
        let server = create_default_sasl_server("localhost".to_string());

        assert!(server.is_mechanism_enabled("PLAIN"));
        assert!(server.is_mechanism_enabled("LOGIN"));
        assert!(server.is_mechanism_enabled("CRAM-MD5"));
        assert!(server.is_mechanism_enabled("SCRAM-SHA-256"));
        assert!(server.is_mechanism_enabled("XOAUTH2"));
    }
}