monocoque-rs-zmtp 0.3.0

Internal ZMTP 3.1 protocol implementation for Monocoque (use 'monocoque-rs' crate for public API)
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
//! PLAIN authentication mechanism (RFC 23)
//!
//! PLAIN provides simple username/password authentication using the ZAP protocol.
//!
//! ## Security Warning
//!
//! PLAIN sends credentials in cleartext! Only use over:
//! - Loopback/localhost connections
//! - Encrypted transports (TLS, VPN, SSH tunnel)
//! - Trusted networks
//!
//! For production over untrusted networks, use CURVE encryption.
//!
//! ## Protocol Flow
//!
//! **Client → Server: HELLO**
//! ```text
//! [0] 0x05 "HELLO"
//! [1] username (length-prefixed string)
//! [2] password (length-prefixed string)
//! ```
//!
//! **Server → ZAP Handler: REQUEST**
//! ```text
//! Multipart message with username + password
//! ```
//!
//! **ZAP Handler → Server: RESPONSE**
//! ```text
//! Status code (200 = success, 400 = failure)
//! ```
//!
//! **Server → Client: WELCOME or ERROR**
//! ```text
//! WELCOME (if 200) or ERROR (if not 200)
//! ```

use crate::codec::ZmtpError;
use crate::security::protocol::reject_immediately_available_trailing_bytes;
use crate::security::zap::{ZapMechanism, ZapRequest, ZapStatus};
use bytes::{Bytes, BytesMut};
use compio_io::{AsyncRead, AsyncWrite};
use std::fmt;
use std::time::Duration;
use tracing::{debug, warn};

/// PLAIN command identifiers
const PLAIN_HELLO: &[u8] = b"\x05HELLO";
const PLAIN_WELCOME: &[u8] = b"\x07WELCOME";
const PLAIN_ERROR: &[u8] = b"\x05ERROR";
const TRAILING_BYTE_CHECK_TIMEOUT: Duration = Duration::from_millis(10);

/// PLAIN client credentials
#[derive(Clone)]
pub struct PlainCredentials {
    /// Plaintext username.
    pub username: String,
    /// Plaintext password.
    pub password: String,
}

impl fmt::Debug for PlainCredentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PlainCredentials")
            .field("username", &self.username)
            .field("password", &"<redacted>")
            .finish()
    }
}

impl PlainCredentials {
    /// Create new credentials from the given username and password.
    pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
        Self {
            username: username.into(),
            password: password.into(),
        }
    }
}

/// PLAIN authentication handler trait
///
/// Implement this to provide custom credential validation.
/// The default implementation rejects all connections.
#[async_trait::async_trait(?Send)]
pub trait PlainAuthHandler {
    /// Validate username and password
    ///
    /// # Arguments
    /// * `username` - Plaintext username
    /// * `password` - Plaintext password
    /// * `domain` - ZAP security domain
    /// * `address` - Peer address (IP:port)
    ///
    /// # Returns
    /// * `Ok(user_id)` - Authentication successful, returns user ID
    /// * `Err(reason)` - Authentication failed, returns error message
    async fn authenticate(
        &self,
        username: &str,
        password: &str,
        domain: &str,
        address: &str,
    ) -> Result<String, String>;
}

/// Simple credential map handler
///
/// Validates against a static HashMap of username → password.
/// For production use, implement PlainAuthHandler with database lookup.
#[derive(Clone)]
pub struct StaticPlainHandler {
    /// Passwords are wrapped in `Zeroizing` so the plaintext is scrubbed from
    /// memory when an entry (or the whole map) is dropped, rather than lingering
    /// in freed heap.
    credentials: std::collections::HashMap<String, zeroize::Zeroizing<String>>,
}

impl fmt::Debug for StaticPlainHandler {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StaticPlainHandler")
            .field("credential_count", &self.credentials.len())
            .finish()
    }
}

impl StaticPlainHandler {
    /// Create a new handler with an empty credential map.
    pub fn new() -> Self {
        Self {
            credentials: std::collections::HashMap::new(),
        }
    }

    /// Register a username/password pair in the credential map.
    pub fn add_user(&mut self, username: impl Into<String>, password: impl Into<String>) {
        self.credentials
            .insert(username.into(), zeroize::Zeroizing::new(password.into()));
    }
}

impl Default for StaticPlainHandler {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait::async_trait(?Send)]
impl PlainAuthHandler for StaticPlainHandler {
    async fn authenticate(
        &self,
        username: &str,
        password: &str,
        _domain: &str,
        _address: &str,
    ) -> Result<String, String> {
        use subtle::ConstantTimeEq;

        // Always run a constant-time comparison, even when the username is
        // unknown, so response timing cannot distinguish "unknown user" from
        // "known user, wrong password" (username enumeration). On a miss we
        // compare the supplied password against a fixed dummy value instead of
        // returning early.
        const DUMMY_PASSWORD: &str = "\0monocoque-plain-miss-placeholder\0";
        let expected = self.credentials.get(username);
        let reference = expected.map_or(DUMMY_PASSWORD, |p| p.as_str());
        let password_matches: bool = reference.as_bytes().ct_eq(password.as_bytes()).into();

        if expected.is_some() && password_matches {
            Ok(username.to_string())
        } else {
            // Single, indistinguishable error for both bad-password and
            // unknown-user so the reason string does not leak which failed.
            Err("Invalid credentials".to_string())
        }
    }
}

/// PLAIN client handshake
///
/// Sends HELLO with username/password, waits for WELCOME or ERROR.
pub async fn plain_client_handshake<S>(
    stream: &mut S,
    credentials: &PlainCredentials,
    timeout: Option<Duration>,
) -> Result<(), ZmtpError>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    use compio_buf::BufResult;
    use monocoque_core::timeout::{read_exact_with_timeout, write_all_with_timeout};

    debug!(
        "[PLAIN CLIENT] Starting PLAIN authentication for user: {}",
        credentials.username
    );

    // Build HELLO command
    let mut hello = BytesMut::new();
    hello.extend_from_slice(PLAIN_HELLO);

    // Username (length-prefixed)
    let username_bytes = credentials.username.as_bytes();
    if username_bytes.len() > 255 {
        return Err(ZmtpError::Protocol);
    }
    hello.extend_from_slice(&[username_bytes.len() as u8]);
    hello.extend_from_slice(username_bytes);

    // Password (length-prefixed)
    let password_bytes = credentials.password.as_bytes();
    if password_bytes.len() > 255 {
        return Err(ZmtpError::Protocol);
    }
    hello.extend_from_slice(&[password_bytes.len() as u8]);
    hello.extend_from_slice(password_bytes);

    // Send HELLO
    let buf_result = write_all_with_timeout(stream, hello.freeze().to_vec(), timeout).await?;
    let BufResult(result, _) = buf_result;
    result?;

    // Read the first byte to determine response type (command name length)
    let len_buf = vec![0u8; 1];
    let BufResult(res, len_buf) = read_exact_with_timeout(stream, len_buf, timeout).await?;
    res?;
    let cmd_len = len_buf[0] as usize;
    if cmd_len == 0 || cmd_len > 32 {
        warn!(
            "[PLAIN CLIENT] Invalid PLAIN response command length: {}",
            cmd_len
        );
        return Err(ZmtpError::Protocol);
    }
    // Read command name
    let cmd_buf = vec![0u8; cmd_len];
    let BufResult(res, cmd_buf) = read_exact_with_timeout(stream, cmd_buf, timeout).await?;
    res?;

    match cmd_buf.as_slice() {
        b"WELCOME" => {
            debug!("[PLAIN CLIENT] Authentication successful");
            Ok(())
        }
        b"ERROR" => {
            warn!("[PLAIN CLIENT] Authentication failed");
            Err(ZmtpError::AuthenticationFailed)
        }
        other => {
            warn!(
                "[PLAIN CLIENT] Invalid PLAIN response command: {:?}",
                String::from_utf8_lossy(other)
            );
            Err(ZmtpError::Protocol)
        }
    }
}

/// PLAIN server handshake
///
/// Receives HELLO, validates via ZAP handler, sends WELCOME or ERROR.
pub async fn plain_server_handshake<S, H>(
    stream: &mut S,
    handler: &H,
    domain: &str,
    peer_address: &str,
    timeout: Option<Duration>,
) -> Result<String, ZmtpError>
where
    S: AsyncRead + AsyncWrite + Unpin,
    H: PlainAuthHandler,
{
    use compio_buf::BufResult;
    use monocoque_core::timeout::{read_exact_with_timeout, write_all_with_timeout};

    debug!(
        "[PLAIN SERVER] Waiting for PLAIN HELLO from {}",
        peer_address
    );

    // Read command header (6 bytes: \x05HELLO)
    let header = vec![0u8; 6];
    let buf_result = read_exact_with_timeout(stream, header, timeout).await?;
    let BufResult(result, header) = buf_result;
    result?;

    if &header[..] != PLAIN_HELLO {
        warn!("[PLAIN SERVER] Invalid PLAIN command header");
        return Err(ZmtpError::Protocol);
    }

    // Read username length
    let len_buf = vec![0u8; 1];
    let buf_result = read_exact_with_timeout(stream, len_buf, timeout).await?;
    let BufResult(result, len_buf) = buf_result;
    result?;
    let username_len = len_buf[0] as usize;

    // Read username
    let username_buf = vec![0u8; username_len];
    let buf_result = read_exact_with_timeout(stream, username_buf, timeout).await?;
    let BufResult(result, username_buf) = buf_result;
    result?;
    let username = String::from_utf8(username_buf).map_err(|_| ZmtpError::Protocol)?;

    // Read password length
    let len_buf = vec![0u8; 1];
    let buf_result = read_exact_with_timeout(stream, len_buf, timeout).await?;
    let BufResult(result, len_buf) = buf_result;
    result?;
    let password_len = len_buf[0] as usize;

    // Read password
    let password_buf = vec![0u8; password_len];
    let buf_result = read_exact_with_timeout(stream, password_buf, timeout).await?;
    let BufResult(result, password_buf) = buf_result;
    result?;
    let password = String::from_utf8(password_buf).map_err(|_| ZmtpError::Protocol)?;
    reject_immediately_available_trailing_bytes(stream, TRAILING_BYTE_CHECK_TIMEOUT).await?;

    debug!("[PLAIN SERVER] Received credentials for user: {}", username);

    // Authenticate via handler
    match handler
        .authenticate(&username, &password, domain, peer_address)
        .await
    {
        Ok(user_id) => {
            debug!(
                "[PLAIN SERVER] Authentication successful for user: {}",
                user_id
            );

            // Send WELCOME
            let buf_result =
                write_all_with_timeout(stream, PLAIN_WELCOME.to_vec(), timeout).await?;
            let BufResult(result, _) = buf_result;
            result?;

            Ok(user_id)
        }
        Err(reason) => {
            warn!("[PLAIN SERVER] Authentication failed: {}", reason);

            // Send ERROR
            let buf_result = write_all_with_timeout(stream, PLAIN_ERROR.to_vec(), timeout).await?;
            let BufResult(result, _) = buf_result;
            result?;

            Err(ZmtpError::AuthenticationFailed)
        }
    }
}

/// PLAIN server handshake using ZAP protocol
///
/// Receives HELLO, sends ZAP request to inproc://zeromq.zap.01, sends WELCOME or ERROR.
/// This is the recommended approach for production deployments.
pub async fn plain_server_handshake_zap<S>(
    stream: &mut S,
    domain: &str,
    peer_address: &str,
    timeout: Option<Duration>,
) -> Result<String, ZmtpError>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    use crate::security::zap_client::ZapClient;
    use compio_buf::BufResult;
    use monocoque_core::timeout::{read_exact_with_timeout, write_all_with_timeout};

    debug!(
        "[PLAIN SERVER ZAP] Waiting for PLAIN HELLO from {}",
        peer_address
    );

    // Read command header (6 bytes: \x05HELLO)
    let header = vec![0u8; 6];
    let buf_result = read_exact_with_timeout(stream, header, timeout).await?;
    let BufResult(result, header) = buf_result;
    result?;

    if &header[..] != PLAIN_HELLO {
        warn!("[PLAIN SERVER ZAP] Invalid PLAIN command header");
        return Err(ZmtpError::Protocol);
    }

    // Read username length
    let len_buf = vec![0u8; 1];
    let buf_result = read_exact_with_timeout(stream, len_buf, timeout).await?;
    let BufResult(result, len_buf) = buf_result;
    result?;
    let username_len = len_buf[0] as usize;

    // Read username
    let username_buf = vec![0u8; username_len];
    let buf_result = read_exact_with_timeout(stream, username_buf, timeout).await?;
    let BufResult(result, username_buf) = buf_result;
    result?;
    let username = String::from_utf8(username_buf).map_err(|_| ZmtpError::Protocol)?;

    // Read password length
    let len_buf = vec![0u8; 1];
    let buf_result = read_exact_with_timeout(stream, len_buf, timeout).await?;
    let BufResult(result, len_buf) = buf_result;
    result?;
    let password_len = len_buf[0] as usize;

    // Read password
    let password_buf = vec![0u8; password_len];
    let buf_result = read_exact_with_timeout(stream, password_buf, timeout).await?;
    let BufResult(result, password_buf) = buf_result;
    result?;
    let password = String::from_utf8(password_buf).map_err(|_| ZmtpError::Protocol)?;
    reject_immediately_available_trailing_bytes(stream, TRAILING_BYTE_CHECK_TIMEOUT).await?;

    debug!(
        "[PLAIN SERVER ZAP] Received credentials for user: {}, sending ZAP request",
        username
    );

    // Create ZAP client and send authentication request
    let mut zap_client = ZapClient::new(Duration::from_secs(5)).map_err(|_| {
        warn!("[PLAIN SERVER ZAP] Failed to connect to ZAP handler");
        ZmtpError::AuthenticationFailed
    })?;

    let zap_response = zap_client
        .authenticate_plain(&username, &password, domain, peer_address)
        .await
        .map_err(|e| {
            warn!("[PLAIN SERVER ZAP] ZAP request failed: {}", e);
            ZmtpError::AuthenticationFailed
        })?;

    // Check ZAP response status
    if matches!(zap_response.status_code, ZapStatus::Success) {
        debug!(
            "[PLAIN SERVER ZAP] Authentication successful for user: {}",
            zap_response.user_id
        );

        // Send WELCOME
        let buf_result = write_all_with_timeout(stream, PLAIN_WELCOME.to_vec(), timeout).await?;
        let BufResult(result, _) = buf_result;
        result?;

        Ok(zap_response.user_id)
    } else {
        warn!(
            "[PLAIN SERVER ZAP] Authentication failed: {}",
            zap_response.status_text
        );

        // Send ERROR
        let buf_result = write_all_with_timeout(stream, PLAIN_ERROR.to_vec(), timeout).await?;
        let BufResult(result, _) = buf_result;
        result?;

        Err(ZmtpError::AuthenticationFailed)
    }
}

/// Create a ZAP request for PLAIN authentication
pub fn create_plain_zap_request(
    request_id: impl Into<String>,
    domain: impl Into<String>,
    address: impl Into<String>,
    identity: Bytes,
    username: impl Into<String>,
    password: impl Into<String>,
) -> ZapRequest {
    ZapRequest::new(
        request_id,
        domain,
        address,
        identity,
        ZapMechanism::Plain,
        vec![Bytes::from(username.into()), Bytes::from(password.into())],
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "runtime-compio")]
    fn plain_hello(username: &[u8], password: &[u8]) -> Vec<u8> {
        let mut hello = Vec::new();
        hello.extend_from_slice(PLAIN_HELLO);
        hello.push(username.len() as u8);
        hello.extend_from_slice(username);
        hello.push(password.len() as u8);
        hello.extend_from_slice(password);
        hello
    }

    #[test]
    fn test_static_plain_handler() {
        monocoque_core::rt::LocalRuntime::new()
            .unwrap()
            .block_on(test_static_plain_handler_impl());
    }

    async fn test_static_plain_handler_impl() {
        let mut handler = StaticPlainHandler::new();
        handler.add_user("admin", "secret123");
        handler.add_user("guest", "guest123");

        // Valid credentials
        let result = handler
            .authenticate("admin", "secret123", "test", "127.0.0.1")
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "admin");

        // Invalid password
        let wrong_password = handler
            .authenticate("admin", "wrong", "test", "127.0.0.1")
            .await;
        assert!(wrong_password.is_err());

        // Unknown user
        let unknown_user = handler
            .authenticate("unknown", "password", "test", "127.0.0.1")
            .await;
        assert!(unknown_user.is_err());

        // The two failure modes must be indistinguishable in their error
        // reason, so a caller cannot enumerate valid usernames from the
        // response. (The constant-time compare closes the timing channel.)
        assert_eq!(
            wrong_password.unwrap_err(),
            unknown_user.unwrap_err(),
            "wrong-password and unknown-user must return the same error"
        );
    }

    #[test]
    fn test_plain_zap_request() {
        let request = create_plain_zap_request(
            "req123",
            "production",
            "192.168.1.100:5555",
            Bytes::from("client1"),
            "testuser",
            "testpass",
        );

        assert_eq!(request.mechanism, ZapMechanism::Plain);
        assert_eq!(request.credentials.len(), 2);
        assert_eq!(&request.credentials[0][..], b"testuser");
        assert_eq!(&request.credentials[1][..], b"testpass");
    }

    #[cfg(feature = "runtime-compio")]
    #[test]
    fn plain_server_rejects_hello_with_trailing_credential_bytes() {
        use compio_buf::BufResult;
        use monocoque_core::rt::{LocalRuntime, TcpListener, TcpStream};
        use monocoque_core::timeout::{read_exact_with_timeout, write_all_with_timeout};
        use std::time::Duration;

        LocalRuntime::new().unwrap().block_on(async {
            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
            let addr = listener.local_addr().unwrap();
            let server_task = monocoque_core::rt::spawn(async move {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut handler = StaticPlainHandler::new();
                handler.add_user("admin", "secret");

                plain_server_handshake(
                    &mut stream,
                    &handler,
                    "global",
                    "127.0.0.1:1",
                    Some(Duration::from_secs(1)),
                )
                .await
            });

            let mut stream = TcpStream::connect(addr).await.unwrap();
            let mut hello = plain_hello(b"admin", b"secret");
            hello.extend_from_slice(b"\x05extra");
            let BufResult(write_result, _) =
                write_all_with_timeout(&mut stream, hello, Some(Duration::from_secs(1)))
                    .await
                    .unwrap();
            write_result.unwrap();

            let response = vec![0u8; PLAIN_WELCOME.len()];
            let BufResult(read_result, response) =
                read_exact_with_timeout(&mut stream, response, Some(Duration::from_secs(1)))
                    .await
                    .unwrap();
            let _ = read_result;

            let result = monocoque_core::rt::join(server_task).await;
            assert!(
                result.is_err() && response.as_slice() != PLAIN_WELCOME,
                "PLAIN server authenticated a HELLO command with trailing credential bytes"
            );
        });
    }

    #[test]
    fn debug_output_redacts_static_plain_handler_passwords() {
        let mut handler = StaticPlainHandler::new();
        handler.add_user("alice", "handler-password");

        let debug = format!("{handler:?}");

        assert!(
            !debug.contains("handler-password"),
            "StaticPlainHandler Debug output exposes stored PLAIN passwords"
        );
    }
}