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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! ZeroMQ Authentication Protocol (ZAP) implementation
//!
//! ZAP is defined in RFC 27: <https://rfc.zeromq.org/spec/27/>
//!
//! ## Protocol Overview
//!
//! ZAP uses a REQ-REP pattern over inproc://zeromq.zap.01:
//! - Client (socket) sends authentication request
//! - Handler (user code) validates credentials and replies
//! - Socket accepts/rejects connection based on status code
//!
//! ## Message Format
//!
//! **Request** (multipart message):
//! 1. Version ("1.0")
//! 2. Request ID (unique per request)
//! 3. Domain (security domain)
//! 4. Address (peer IP address)
//! 5. Identity (ZMQ identity)
//! 6. Mechanism ("NULL", "PLAIN", "CURVE")
//! 7+. Credentials (mechanism-specific)
//!
//! **Response** (multipart message):
//! 1. Version ("1.0")
//! 2. Request ID (matches request)
//! 3. Status code ("200", "300", "400", "500")
//! 4. Status text (human-readable)
//! 5. User ID (authenticated user)
//! 6. Metadata (key-value pairs)

use bytes::Bytes;
use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};

/// Monotonic counter used to generate unique ZAP request IDs.
///
/// Each call to `ZapRequest::new_with_unique_id` increments this counter so
/// that every request sent to the ZAP handler has a distinct ID, preventing
/// response correlation mistakes when multiple requests are in-flight.
static ZAP_REQUEST_COUNTER: AtomicU64 = AtomicU64::new(1);

/// Generate the next unique ZAP request ID as a decimal string.
pub fn next_request_id() -> String {
    format!("{}", ZAP_REQUEST_COUNTER.fetch_add(1, Ordering::Relaxed))
}

/// ZAP version constant
pub const ZAP_VERSION: &str = "1.0";

/// ZAP endpoint for inproc transport
pub const ZAP_ENDPOINT: &str = "inproc://zeromq.zap.01";

/// Authentication mechanism
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ZapMechanism {
    /// No authentication (NULL mechanism).
    Null,
    /// Username/password authentication (PLAIN mechanism).
    Plain,
    /// Public-key authentication (CURVE mechanism).
    Curve,
}

impl ZapMechanism {
    /// Return the wire-format mechanism name string.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Null => "NULL",
            Self::Plain => "PLAIN",
            Self::Curve => "CURVE",
        }
    }

    /// Parse a mechanism from its wire-format name string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "NULL" => Some(Self::Null),
            "PLAIN" => Some(Self::Plain),
            "CURVE" => Some(Self::Curve),
            _ => None,
        }
    }
}

/// ZAP status codes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ZapStatus {
    /// Success - connection accepted
    Success = 200,
    /// Temporary error - retry later
    TemporaryError = 300,
    /// Authentication failure
    Failure = 400,
    /// Internal error
    InternalError = 500,
}

impl ZapStatus {
    /// Return the numeric status code as a string.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Success => "200",
            Self::TemporaryError => "300",
            Self::Failure => "400",
            Self::InternalError => "500",
        }
    }

    /// Parse a `ZapStatus` from its numeric string representation.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "200" => Some(Self::Success),
            "300" => Some(Self::TemporaryError),
            "400" => Some(Self::Failure),
            "500" => Some(Self::InternalError),
            _ => None,
        }
    }
}

/// ZAP authentication request
#[derive(Clone)]
pub struct ZapRequest {
    /// Version (always "1.0")
    pub version: String,
    /// Unique request ID
    pub request_id: String,
    /// Security domain
    pub domain: String,
    /// Peer address (IP:port)
    pub address: String,
    /// Peer identity
    pub identity: Bytes,
    /// Authentication mechanism
    pub mechanism: ZapMechanism,
    /// Mechanism-specific credentials
    pub credentials: Vec<Bytes>,
}

impl fmt::Debug for ZapRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ZapRequest")
            .field("version", &self.version)
            .field("request_id", &self.request_id)
            .field("domain", &self.domain)
            .field("address", &self.address)
            .field("identity", &self.identity)
            .field("mechanism", &self.mechanism)
            .field(
                "credentials",
                &ZapRequestCredentialsDebug {
                    len: self.credentials.len(),
                },
            )
            .finish()
    }
}

struct ZapRequestCredentialsDebug {
    len: usize,
}

impl fmt::Debug for ZapRequestCredentialsDebug {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.len == 0 {
            f.write_str("[]")
        } else {
            write!(f, "[<{} credential frame(s) redacted>]", self.len)
        }
    }
}
impl ZapRequest {
    /// Create a new ZAP request with a caller-supplied request ID.
    ///
    /// Prefer [`ZapRequest::new_with_unique_id`] in production code to ensure
    /// that every request has a distinct, monotonically increasing ID.
    pub fn new(
        request_id: impl Into<String>,
        domain: impl Into<String>,
        address: impl Into<String>,
        identity: Bytes,
        mechanism: ZapMechanism,
        credentials: Vec<Bytes>,
    ) -> Self {
        Self {
            version: ZAP_VERSION.to_string(),
            request_id: request_id.into(),
            domain: domain.into(),
            address: address.into(),
            identity,
            mechanism,
            credentials,
        }
    }

    /// Create a new ZAP request with an automatically generated unique request ID.
    ///
    /// The request ID is produced by a process-wide `AtomicU64` counter that
    /// starts at 1 and increments on every call.  This guarantees uniqueness
    /// within a process and makes it straightforward to correlate responses
    /// to their originating requests even when several ZAP round-trips are
    /// concurrent.
    pub fn new_with_unique_id(
        domain: impl Into<String>,
        address: impl Into<String>,
        identity: Bytes,
        mechanism: ZapMechanism,
        credentials: Vec<Bytes>,
    ) -> Self {
        Self::new(
            next_request_id(),
            domain,
            address,
            identity,
            mechanism,
            credentials,
        )
    }

    /// Encode request as multipart message
    pub fn encode(&self) -> Vec<Bytes> {
        let mut frames = vec![
            Bytes::from(self.version.clone()),
            Bytes::from(self.request_id.clone()),
            Bytes::from(self.domain.clone()),
            Bytes::from(self.address.clone()),
            self.identity.clone(),
            Bytes::from(self.mechanism.as_str()),
        ];
        frames.extend(self.credentials.clone());
        frames
    }

    /// Decode multipart message into request
    pub fn decode(frames: &[Bytes]) -> Result<Self, String> {
        if frames.len() < 6 {
            return Err("ZAP request requires at least 6 frames".to_string());
        }

        let version =
            String::from_utf8(frames[0].to_vec()).map_err(|_| "Invalid version string")?;
        if version != ZAP_VERSION {
            return Err("Unsupported ZAP request version".to_string());
        }
        let request_id = String::from_utf8(frames[1].to_vec()).map_err(|_| "Invalid request ID")?;
        let domain = String::from_utf8(frames[2].to_vec()).map_err(|_| "Invalid domain string")?;
        let address =
            String::from_utf8(frames[3].to_vec()).map_err(|_| "Invalid address string")?;
        if address.is_empty() {
            return Err("ZAP address cannot be empty".to_string());
        }
        let identity = frames[4].clone();
        if identity.len() > 255 {
            return Err("ZAP identity cannot exceed 255 bytes".to_string());
        }

        let mechanism_str =
            String::from_utf8(frames[5].to_vec()).map_err(|_| "Invalid mechanism string")?;
        let mechanism = ZapMechanism::from_str(&mechanism_str).ok_or("Unknown mechanism")?;

        let credentials = frames[6..].to_vec();
        let expected_credentials = match mechanism {
            ZapMechanism::Null => 0,
            ZapMechanism::Plain => 2,
            ZapMechanism::Curve => 1,
        };
        if credentials.len() != expected_credentials {
            return Err("ZAP credential count does not match mechanism".to_string());
        }

        Ok(Self {
            version,
            request_id,
            domain,
            address,
            identity,
            mechanism,
            credentials,
        })
    }
}

/// ZAP authentication response
#[derive(Debug, Clone)]
pub struct ZapResponse {
    /// Version (matches request)
    pub version: String,
    /// Request ID (matches request)
    pub request_id: String,
    /// Status code
    pub status_code: ZapStatus,
    /// Human-readable status text
    pub status_text: String,
    /// Authenticated user ID (empty if rejected)
    pub user_id: String,
    /// Optional metadata (RFC 35)
    pub metadata: HashMap<String, String>,
}

impl ZapResponse {
    /// Create a success response
    pub fn success(request_id: impl Into<String>, user_id: impl Into<String>) -> Self {
        Self {
            version: ZAP_VERSION.to_string(),
            request_id: request_id.into(),
            status_code: ZapStatus::Success,
            status_text: "OK".to_string(),
            user_id: user_id.into(),
            metadata: HashMap::new(),
        }
    }

    /// Create a failure response
    pub fn failure(request_id: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            version: ZAP_VERSION.to_string(),
            request_id: request_id.into(),
            status_code: ZapStatus::Failure,
            status_text: reason.into(),
            user_id: String::new(),
            metadata: HashMap::new(),
        }
    }

    /// Create an internal error response
    pub fn internal_error(request_id: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            version: ZAP_VERSION.to_string(),
            request_id: request_id.into(),
            status_code: ZapStatus::InternalError,
            status_text: reason.into(),
            user_id: String::new(),
            metadata: HashMap::new(),
        }
    }

    /// Encode response as multipart message
    pub fn encode(&self) -> Vec<Bytes> {
        // Encode metadata as key-value pairs (RFC 35 format)
        let metadata_bytes = if self.metadata.is_empty() {
            Bytes::new()
        } else {
            let mut buf = Vec::new();
            for (key, value) in &self.metadata {
                // RFC 35: key is 1-byte length-prefixed, so max 255 bytes.
                let key_bytes = key.as_bytes();
                let key_len = key_bytes.len().min(255);
                buf.push(key_len as u8);
                buf.extend_from_slice(&key_bytes[..key_len]);
                let value_len = (value.len() as u32).to_be_bytes();
                buf.extend_from_slice(&value_len);
                buf.extend_from_slice(value.as_bytes());
            }
            Bytes::from(buf)
        };

        vec![
            Bytes::from(self.version.clone()),
            Bytes::from(self.request_id.clone()),
            Bytes::from(self.status_code.as_str()),
            Bytes::from(self.status_text.clone()),
            Bytes::from(self.user_id.clone()),
            metadata_bytes,
        ]
    }

    /// Decode multipart message into response
    pub fn decode(frames: &[Bytes]) -> Result<Self, String> {
        if frames.len() != 6 {
            return Err(format!(
                "ZAP response requires 6 frames, got {}",
                frames.len()
            ));
        }

        let version =
            String::from_utf8(frames[0].to_vec()).map_err(|_| "Invalid version string")?;
        if version != ZAP_VERSION {
            return Err("Unsupported ZAP response version".to_string());
        }
        let request_id = String::from_utf8(frames[1].to_vec()).map_err(|_| "Invalid request ID")?;

        let status_str =
            String::from_utf8(frames[2].to_vec()).map_err(|_| "Invalid status code")?;
        let status_code = ZapStatus::from_str(&status_str).ok_or("Unknown status code")?;

        let status_text =
            String::from_utf8(frames[3].to_vec()).map_err(|_| "Invalid status text")?;
        if status_text.len() > 255 {
            return Err("ZAP status text cannot exceed 255 bytes".to_string());
        }
        if !frames[4].is_ascii() {
            return Err("Invalid user ID".to_string());
        }
        let user_id = String::from_utf8(frames[4].to_vec()).map_err(|_| "Invalid user ID")?;

        // Parse metadata (RFC 35 format)
        let metadata = Self::parse_metadata(&frames[5])?;

        Ok(Self {
            version,
            request_id,
            status_code,
            status_text,
            user_id,
            metadata,
        })
    }

    fn parse_metadata(data: &Bytes) -> Result<HashMap<String, String>, String> {
        let mut metadata = HashMap::new();
        if data.is_empty() {
            return Ok(metadata);
        }

        let mut cursor = 0;
        while cursor < data.len() {
            // Read key length (1 byte)
            if cursor >= data.len() {
                break;
            }
            let key_len = data[cursor] as usize;
            cursor += 1;

            // Read key
            if cursor + key_len > data.len() {
                return Err("Invalid metadata: key out of bounds".to_string());
            }
            let key = String::from_utf8(data[cursor..cursor + key_len].to_vec())
                .map_err(|_| "Invalid metadata key")?;
            cursor += key_len;

            // Read value length (4 bytes, big-endian)
            if cursor + 4 > data.len() {
                return Err("Invalid metadata: value length out of bounds".to_string());
            }
            let value_len = u32::from_be_bytes([
                data[cursor],
                data[cursor + 1],
                data[cursor + 2],
                data[cursor + 3],
            ]) as usize;
            cursor += 4;

            // Read value
            if cursor + value_len > data.len() {
                return Err("Invalid metadata: value out of bounds".to_string());
            }
            let value = String::from_utf8(data[cursor..cursor + value_len].to_vec())
                .map_err(|_| "Invalid metadata value")?;
            cursor += value_len;

            metadata.insert(key, value);
        }

        Ok(metadata)
    }
}

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

    #[test]
    fn test_zap_request_encode_decode() {
        let request = ZapRequest::new(
            "123",
            "test",
            "127.0.0.1:5555",
            Bytes::from("client1"),
            ZapMechanism::Plain,
            vec![Bytes::from("admin"), Bytes::from("password")],
        );

        let frames = request.encode();
        let decoded = ZapRequest::decode(&frames).unwrap();

        assert_eq!(decoded.version, ZAP_VERSION);
        assert_eq!(decoded.request_id, "123");
        assert_eq!(decoded.domain, "test");
        assert_eq!(decoded.mechanism, ZapMechanism::Plain);
        assert_eq!(decoded.credentials.len(), 2);
    }

    #[test]
    fn zap_request_decode_rejects_wrong_protocol_version() {
        let frames = vec![
            Bytes::from("0.9"),
            Bytes::from("123"),
            Bytes::from("test"),
            Bytes::from("127.0.0.1:5555"),
            Bytes::from("client1"),
            Bytes::from("PLAIN"),
            Bytes::from("admin"),
            Bytes::from("password"),
        ];

        assert!(
            ZapRequest::decode(&frames).is_err(),
            "ZAP accepted an authentication request with an unsupported protocol version"
        );
    }

    #[test]
    fn zap_request_decode_rejects_null_credentials() {
        let frames = vec![
            Bytes::from(ZAP_VERSION),
            Bytes::from("123"),
            Bytes::from("test"),
            Bytes::from("127.0.0.1"),
            Bytes::new(),
            Bytes::from("NULL"),
            Bytes::from("unexpected"),
        ];

        assert!(ZapRequest::decode(&frames).is_err());
    }

    #[test]
    fn zap_request_decode_accepts_empty_domain_as_default() {
        let frames = vec![
            Bytes::from(ZAP_VERSION),
            Bytes::from("123"),
            Bytes::new(),
            Bytes::from("127.0.0.1"),
            Bytes::new(),
            Bytes::from("NULL"),
        ];

        let request = ZapRequest::decode(&frames).unwrap();
        assert!(request.domain.is_empty());
    }

    #[test]
    fn zap_request_decode_rejects_empty_address() {
        let frames = vec![
            Bytes::from(ZAP_VERSION),
            Bytes::from("123"),
            Bytes::from("test"),
            Bytes::new(),
            Bytes::new(),
            Bytes::from("NULL"),
        ];

        assert!(ZapRequest::decode(&frames).is_err());
    }

    #[test]
    fn zap_request_decode_rejects_overlong_identity() {
        let frames = vec![
            Bytes::from(ZAP_VERSION),
            Bytes::from("123"),
            Bytes::from("test"),
            Bytes::from("127.0.0.1"),
            Bytes::from(vec![0u8; 256]),
            Bytes::from("NULL"),
        ];

        assert!(ZapRequest::decode(&frames).is_err());
    }

    #[test]
    fn zap_request_decode_rejects_plain_extra_credentials() {
        let frames = vec![
            Bytes::from(ZAP_VERSION),
            Bytes::from("123"),
            Bytes::from("test"),
            Bytes::from("127.0.0.1"),
            Bytes::new(),
            Bytes::from("PLAIN"),
            Bytes::from("admin"),
            Bytes::from("secret"),
            Bytes::from("shadow"),
        ];

        assert!(ZapRequest::decode(&frames).is_err());
    }

    #[test]
    fn zap_request_decode_rejects_curve_extra_credentials() {
        let frames = vec![
            Bytes::from(ZAP_VERSION),
            Bytes::from("123"),
            Bytes::from("test"),
            Bytes::from("127.0.0.1"),
            Bytes::new(),
            Bytes::from("CURVE"),
            Bytes::from(vec![0u8; 32]),
            Bytes::from("shadow"),
        ];

        assert!(ZapRequest::decode(&frames).is_err());
    }

    #[test]
    fn test_zap_response_success() {
        let response = ZapResponse::success("123", "testuser");
        let frames = response.encode();
        let decoded = ZapResponse::decode(&frames).unwrap();

        assert_eq!(decoded.status_code, ZapStatus::Success);
        assert_eq!(decoded.user_id, "testuser");
        assert_eq!(decoded.request_id, "123");
    }

    #[test]
    fn test_zap_response_failure() {
        let response = ZapResponse::failure("123", "Invalid credentials");
        let frames = response.encode();
        let decoded = ZapResponse::decode(&frames).unwrap();

        assert_eq!(decoded.status_code, ZapStatus::Failure);
        assert_eq!(decoded.status_text, "Invalid credentials");
        assert!(decoded.user_id.is_empty());
    }

    #[test]
    fn zap_response_decode_rejects_wrong_protocol_version() {
        let frames = vec![
            Bytes::from("0.9"),
            Bytes::from("123"),
            Bytes::from("200"),
            Bytes::from("OK"),
            Bytes::from("admin"),
            Bytes::new(),
        ];

        assert!(
            ZapResponse::decode(&frames).is_err(),
            "ZAP accepted an authentication success response with an unsupported protocol version"
        );
    }

    #[test]
    fn zap_response_decode_rejects_non_ascii_user_id() {
        let frames = vec![
            Bytes::from(ZAP_VERSION),
            Bytes::from("123"),
            Bytes::from("200"),
            Bytes::from("OK"),
            Bytes::from_static(b"jos\xc3\xa9"),
            Bytes::new(),
        ];

        assert!(ZapResponse::decode(&frames).is_err());
    }

    #[test]
    fn zap_response_decode_rejects_overlong_status_text() {
        let frames = vec![
            Bytes::from(ZAP_VERSION),
            Bytes::from("123"),
            Bytes::from("200"),
            Bytes::from("a".repeat(256)),
            Bytes::from("testuser"),
            Bytes::new(),
        ];

        assert!(ZapResponse::decode(&frames).is_err());
    }

    #[test]
    fn test_zap_metadata() {
        let mut response = ZapResponse::success("123", "admin");
        response
            .metadata
            .insert("role".to_string(), "superuser".to_string());
        response
            .metadata
            .insert("email".to_string(), "admin@example.com".to_string());

        let frames = response.encode();
        let decoded = ZapResponse::decode(&frames).unwrap();

        assert_eq!(decoded.metadata.len(), 2);
        assert_eq!(decoded.metadata.get("role"), Some(&"superuser".to_string()));
        assert_eq!(
            decoded.metadata.get("email"),
            Some(&"admin@example.com".to_string())
        );
    }
}