arzmq 0.6.2

High-level bindings to the zeromq library
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! 0MQ security mechanisms
//!
//! Ssupports [`Null`] and [`Plain`] out of the box. `Curve` and `GSSAPI` can be enabled via
//! feature flags.
//!
//! [`Null`]: SecurityMechanism::Null
//! [`Plain`]: SecurityMechanism::Plain

use derive_more::Display;
#[cfg(zmq_has = "gssapi")]
pub use gssapi::GssApiNametype;

use crate::{
    ZmqError, ZmqResult, sealed,
    socket::{Socket, SocketOption},
    zmq_sys_crate,
};

#[derive(Default, Debug, Display, PartialEq, Eq, Clone, Hash)]
#[cfg_attr(feature = "builder", derive(serde::Deserialize, serde::Serialize))]
#[repr(i32)]
#[non_exhaustive]
/// # 0MQ security mechanisms
///
/// A 0MQ socket can select a security mechanism. Both peers must use the same security mechanism.
pub enum SecurityMechanism {
    #[default]
    /// Null security
    Null,
    #[display("Plain {{ username = {username}, password = {password} }}")]
    /// Plain-textauthentication using username and password
    Plain { username: String, password: String },
    #[cfg(zmq_has = "curve")]
    #[display("CurveClient {{ ... }}")]
    /// Elliptic curve client authentication and encryption
    CurveClient {
        server_key: Vec<u8>,
        public_key: Vec<u8>,
        secret_key: Vec<u8>,
    },
    #[cfg(zmq_has = "curve")]
    #[display("CurveServer {{ ... }}")]
    /// Elliptic curve server authentication and encryption
    CurveServer { secret_key: Vec<u8> },
    #[cfg(zmq_has = "gssapi")]
    #[display("GssApiClient {{ ... }}")]
    /// GSSAPI client authentication and encryption
    GssApiClient { service_principal: String },
    #[cfg(zmq_has = "gssapi")]
    #[display("GssApiServer {{ ... }}")]
    /// GSSAPI server authentication and encryption
    GssApiServer,
}

impl SecurityMechanism {
    /// Applies the security mechanism to the provided socket
    pub fn apply<T: sealed::SocketType>(&self, socket: &Socket<T>) -> ZmqResult<()> {
        match self {
            SecurityMechanism::Null => socket.set_sockopt_bool(SocketOption::PlainServer, false)?,
            SecurityMechanism::Plain { username, password } => {
                socket.set_sockopt_bool(SocketOption::PlainServer, true)?;
                socket.set_sockopt_string(SocketOption::PlainUsername, username)?;
                socket.set_sockopt_string(SocketOption::PlainPassword, password)?;
            }
            #[cfg(zmq_has = "curve")]
            SecurityMechanism::CurveServer { secret_key } => {
                socket.set_sockopt_bool(SocketOption::CurveServer, true)?;
                socket.set_sockopt_bytes(SocketOption::CurveSecretKey, secret_key)?;
            }
            #[cfg(zmq_has = "curve")]
            SecurityMechanism::CurveClient {
                server_key,
                public_key,
                secret_key,
            } => {
                socket.set_sockopt_bytes(SocketOption::CurveServerKey, server_key)?;
                socket.set_sockopt_bytes(SocketOption::CurvePublicKey, public_key)?;
                socket.set_sockopt_bytes(SocketOption::CurveSecretKey, secret_key)?;
            }
            #[cfg(zmq_has = "gssapi")]
            SecurityMechanism::GssApiClient { service_principal } => {
                socket
                    .set_sockopt_string(SocketOption::GssApiServicePrincipal, service_principal)?;
            }
            #[cfg(zmq_has = "gssapi")]
            SecurityMechanism::GssApiServer => {
                socket.set_sockopt_bool(SocketOption::GssApiServer, true)?;
            }
        }
        Ok(())
    }
}

impl<T: sealed::SocketType> TryFrom<&Socket<T>> for SecurityMechanism {
    type Error = ZmqError;

    fn try_from(socket: &Socket<T>) -> Result<Self, Self::Error> {
        match socket.get_sockopt_int::<i32>(SocketOption::Mechanism)? {
            value if value == zmq_sys_crate::ZMQ_NULL as i32 => Ok(Self::Null),
            value if value == zmq_sys_crate::ZMQ_PLAIN as i32 => {
                let username = socket.get_sockopt_string(SocketOption::PlainUsername)?;
                let password = socket.get_sockopt_string(SocketOption::PlainPassword)?;
                Ok(Self::Plain { username, password })
            }
            #[cfg(zmq_has = "curve")]
            value if value == zmq_sys_crate::ZMQ_CURVE as i32 => {
                let secret_key = socket.get_sockopt_curve(SocketOption::CurveSecretKey)?;
                if socket.get_sockopt_bool(SocketOption::CurveServer)? {
                    Ok(Self::CurveServer { secret_key })
                } else {
                    let server_key = socket.get_sockopt_curve(SocketOption::CurveServerKey)?;
                    let public_key = socket.get_sockopt_curve(SocketOption::CurvePublicKey)?;
                    Ok(Self::CurveClient {
                        server_key,
                        public_key,
                        secret_key,
                    })
                }
            }
            #[cfg(zmq_has = "gssapi")]
            value if value == zmq_sys_crate::ZMQ_GSSAPI as i32 => {
                if socket.get_sockopt_bool(SocketOption::GssApiServer)? {
                    Ok(Self::GssApiServer)
                } else {
                    let service_principal =
                        socket.get_sockopt_string(SocketOption::GssApiServicePrincipal)?;
                    Ok(Self::GssApiClient { service_principal })
                }
            }
            _ => Err(ZmqError::Unsupported),
        }
    }
}

#[cfg(test)]
mod security_mechanism_tests {
    use super::SecurityMechanism;
    #[cfg(zmq_has = "curve")]
    use super::curve::curve_keypair;
    use crate::{
        prelude::{Context, DealerSocket, SocketOption, ZmqResult},
        zmq_sys_crate,
    };

    #[test]
    fn apply_null_security() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;

        SecurityMechanism::Null.apply(&socket)?;

        assert_eq!(
            socket.get_sockopt_int::<i32>(SocketOption::Mechanism)?,
            zmq_sys_crate::ZMQ_NULL as i32
        );

        Ok(())
    }

    #[test]
    fn apply_plain_security() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        let security = SecurityMechanism::Plain {
            username: "username".to_string(),
            password: "password".to_string(),
        };

        security.apply(&socket)?;

        assert_eq!(
            socket.get_sockopt_int::<i32>(SocketOption::Mechanism)?,
            zmq_sys_crate::ZMQ_PLAIN as i32
        );
        assert_eq!(
            socket.get_sockopt_string(SocketOption::PlainUsername)?,
            "username"
        );
        assert_eq!(
            socket.get_sockopt_string(SocketOption::PlainPassword)?,
            "password"
        );

        Ok(())
    }

    #[cfg(zmq_has = "curve")]
    #[test]
    fn apply_curve_server_security() -> ZmqResult<()> {
        let (_, secret_key) = curve_keypair()?;

        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        let security = SecurityMechanism::CurveServer {
            secret_key: secret_key.clone(),
        };
        security.apply(&socket)?;

        assert_eq!(
            socket.get_sockopt_int::<i32>(SocketOption::Mechanism)?,
            zmq_sys_crate::ZMQ_CURVE as i32
        );
        assert!(socket.get_sockopt_bool(SocketOption::CurveServer)?);
        assert_eq!(
            socket.get_sockopt_curve(SocketOption::CurveSecretKey)?,
            secret_key
        );

        Ok(())
    }

    #[cfg(zmq_has = "curve")]
    #[test]
    fn apply_curve_client_security() -> ZmqResult<()> {
        let (_, server_key) = curve_keypair()?;
        let (public_key, secret_key) = curve_keypair()?;

        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        let security = SecurityMechanism::CurveClient {
            server_key: server_key.clone(),
            public_key: public_key.clone(),
            secret_key: secret_key.clone(),
        };
        security.apply(&socket)?;

        assert_eq!(
            socket.get_sockopt_int::<i32>(SocketOption::Mechanism)?,
            zmq_sys_crate::ZMQ_CURVE as i32
        );
        assert!(!socket.get_sockopt_bool(SocketOption::CurveServer)?);
        assert_eq!(
            socket.get_sockopt_curve(SocketOption::CurveServerKey)?,
            server_key
        );
        assert_eq!(
            socket.get_sockopt_curve(SocketOption::CurvePublicKey)?,
            public_key
        );
        assert_eq!(
            socket.get_sockopt_curve(SocketOption::CurveSecretKey)?,
            secret_key
        );

        Ok(())
    }

    #[cfg(zmq_has = "gssapi")]
    #[test]
    fn apply_gssapi_server_security() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        let security = SecurityMechanism::GssApiServer;
        security.apply(&socket)?;

        assert!(socket.get_sockopt_bool(SocketOption::GssApiServer)?);

        Ok(())
    }

    #[cfg(zmq_has = "gssapi")]
    #[test]
    fn apply_gssapi_client_security() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        let security = SecurityMechanism::GssApiClient {
            service_principal: "service_principal".to_string(),
        };
        security.apply(&socket)?;

        assert_eq!(
            socket.get_sockopt_string(SocketOption::GssApiServicePrincipal)?,
            "service_principal"
        );

        Ok(())
    }

    #[test]
    fn try_from_socket_with_no_security() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;

        assert_eq!(
            SecurityMechanism::try_from(&socket)?,
            SecurityMechanism::Null
        );

        Ok(())
    }

    #[test]
    fn try_from_socket_with_plain_security() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        socket.set_sockopt_string(SocketOption::PlainUsername, "username")?;
        socket.set_sockopt_string(SocketOption::PlainPassword, "password")?;

        assert_eq!(
            SecurityMechanism::try_from(&socket)?,
            SecurityMechanism::Plain {
                username: "username".to_string(),
                password: "password".to_string(),
            }
        );

        Ok(())
    }

    #[cfg(zmq_has = "curve")]
    #[test]
    fn try_from_socket_with_curve_security() -> ZmqResult<()> {
        let (_, secret_key) = curve_keypair()?;

        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;

        socket.set_sockopt_bytes(SocketOption::CurveSecretKey, secret_key.clone())?;
        socket.set_sockopt_bool(SocketOption::CurveServer, true)?;
        assert_eq!(
            SecurityMechanism::try_from(&socket)?,
            SecurityMechanism::CurveServer {
                secret_key: secret_key.clone(),
            }
        );

        Ok(())
    }

    #[cfg(zmq_has = "curve")]
    #[test]
    fn try_from_socket_with_curve_client_security() -> ZmqResult<()> {
        let (_, server_key) = curve_keypair()?;
        let (public_key, secret_key) = curve_keypair()?;

        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        socket.set_sockopt_bool(SocketOption::CurveServer, false)?;
        socket.set_sockopt_bytes(SocketOption::CurveServerKey, server_key.clone())?;
        socket.set_sockopt_bytes(SocketOption::CurvePublicKey, public_key.clone())?;
        socket.set_sockopt_bytes(SocketOption::CurveSecretKey, secret_key.clone())?;
        assert_eq!(
            SecurityMechanism::try_from(&socket)?,
            SecurityMechanism::CurveClient {
                server_key: server_key.clone(),
                public_key: public_key.clone(),
                secret_key: secret_key.clone(),
            }
        );

        Ok(())
    }

    #[cfg(zmq_has = "gssapi")]
    #[test]
    fn try_from_socket_with_gssapi_security() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        socket.set_sockopt_string(SocketOption::GssApiServicePrincipal, "service_principal")?;
        socket.set_sockopt_bool(SocketOption::GssApiServer, true)?;
        assert_eq!(
            SecurityMechanism::try_from(&socket)?,
            SecurityMechanism::GssApiServer
        );

        Ok(())
    }

    #[cfg(zmq_has = "gssapi")]
    #[test]
    fn try_from_socket_with_gssapi_client_security() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = DealerSocket::from_context(&context)?;
        socket.set_sockopt_string(SocketOption::GssApiServicePrincipal, "service_principal")?;
        socket.set_sockopt_bool(SocketOption::GssApiServer, false)?;
        assert_eq!(
            SecurityMechanism::try_from(&socket)?,
            SecurityMechanism::GssApiClient {
                service_principal: "service_principal".to_string()
            }
        );

        Ok(())
    }
}

/// # `Curve` related convenience functions
#[cfg(zmq_has = "curve")]
pub mod curve {
    use alloc::ffi::CString;
    use core::ffi::c_char;
    #[cfg(nightly)]
    use core::hint::cold_path;

    use derive_more::Display;
    use thiserror::Error;

    use crate::{
        prelude::{ZmqError, ZmqResult},
        zmq_sys_crate,
    };

    #[derive(Debug, PartialEq, Eq, Clone, Hash, Error, Display)]
    /// Error that can occur while encoding Z85
    pub enum EncodeError {
        /// The input string slice’s length was not a multiple of 4.
        BadLength,
        /// The underlying `zmq_z85_encode()` function returned an error.
        EncodingFailed,
        /// Converting the returned string failed.
        Utf8Error,
    }

    /// # encode a binary key as Z85 printable text
    ///
    /// The [`encode()`] function shall encode the binary block specified by 'data' into a string.
    /// The size of the binary block must be divisible by 4. A 32-byte CURVE key is encoded as 40 ASCII
    /// characters plus a null terminator.
    ///
    /// [`encode()`]: #method.encode
    pub fn encode<T>(data: T) -> Result<String, EncodeError>
    where
        T: AsRef<[u8]>,
    {
        let input = data.as_ref();
        let input_len = input.len();
        if input_len % 4 != 0 {
            return Err(EncodeError::BadLength);
        }

        let len = input_len * 5 / 4 + 1;
        let mut dest = vec![0u8; len];

        if unsafe {
            zmq_sys_crate::zmq_z85_encode(
                dest.as_mut_ptr() as *mut c_char,
                input.as_ptr(),
                input.len(),
            )
        }
        .is_null()
        {
            #[cfg(nightly)]
            cold_path();
            return Err(EncodeError::EncodingFailed);
        }

        dest.truncate(len - 1);
        String::from_utf8(dest).map_err(|_| EncodeError::Utf8Error)
    }

    #[cfg(test)]
    mod z85_encode_tests {
        use super::{EncodeError, encode};

        #[test]
        fn z85_encode_for_empty_input() -> Result<(), EncodeError> {
            let encoded_string = encode(vec![])?;
            assert_eq!(encoded_string, "");
            Ok(())
        }

        #[test]
        fn z85_encode_for_invalid_input_length() {
            let result = encode(b"a");
            assert!(result.is_err_and(|err| err == EncodeError::BadLength));
        }

        #[test]
        fn z85_encode_for_valid_input() -> Result<(), EncodeError> {
            let encoded_string = encode(b"Hello World!")?;
            assert_eq!(encoded_string, "nm=QNzY&b1A+]nf");

            Ok(())
        }
    }

    #[derive(Debug, PartialEq, Eq, Clone, Hash, Error, Display)]
    /// Error that can occur while decoding Z85.
    pub enum DecodeError {
        /// The input string slice’s length was not a multiple of 5.
        InvalidLength,
        /// The underlying `zmq_z85_decode()` function returned an error.
        DecodingFailed,
    }

    /// # decode a binary key from Z85 printable text
    ///
    /// The [`decode()`] function shall decode 'string'. The length of 'string' shall be divisible
    /// by 5.
    ///
    /// [`decode()`]: #method.decode
    pub fn decode<T>(string: T) -> Result<Vec<u8>, DecodeError>
    where
        T: AsRef<str>,
    {
        let input = string.as_ref();
        let input_len = input.len();
        if input_len == 0 {
            return Ok(vec![]);
        }

        if input_len % 5 != 0 {
            return Err(DecodeError::InvalidLength);
        }

        let dest_len = input_len * 4 / 5;
        let mut dest = vec![0; dest_len];

        let c_str = CString::new(input).map_err(|_| DecodeError::DecodingFailed)?;

        if unsafe { zmq_sys_crate::zmq_z85_decode(dest.as_mut_ptr(), c_str.into_raw()) }.is_null() {
            #[cfg(nightly)]
            cold_path();
            return Err(DecodeError::DecodingFailed);
        }

        Ok(dest)
    }

    #[cfg(test)]
    mod z85_decode_tests {
        use super::{DecodeError, decode};

        #[test]
        fn z85_decode_z85_encoded_string() -> Result<(), DecodeError> {
            let encoded_string = "nm=QNzY&b1A+]nf";
            let decoded_string = decode(encoded_string)?;

            assert_eq!(decoded_string, b"Hello World!");

            Ok(())
        }

        #[test]
        fn z85_decode_for_empty_input() -> Result<(), DecodeError> {
            let encoded_string = "";
            let decoded_string = decode(encoded_string)?;

            assert_eq!(decoded_string, vec![]);

            Ok(())
        }

        #[test]
        fn z85_decode_for_invalid_input_length() {
            let encoded_string = "a";
            let result = decode(encoded_string);

            assert!(result.is_err_and(|err| err == DecodeError::InvalidLength));
        }
    }

    /// # generate a new CURVE keypair
    ///
    /// The [`curve_keypair()`] function returns a newly generated random keypair consisting of a
    /// public key and a secret key. The keys are encoded using [`z85_encode()`].
    ///
    /// [`curve_keypair()`]: curve_keypair
    /// [`z85_encode()`]: encode
    pub fn curve_keypair() -> ZmqResult<(Vec<u8>, Vec<u8>)> {
        let mut public_key: [u8; 41] = [0; 41];
        let mut secret_key: [u8; 41] = [0; 41];

        if unsafe {
            zmq_sys_crate::zmq_curve_keypair(
                public_key.as_mut_ptr() as *mut c_char,
                secret_key.as_mut_ptr() as *mut c_char,
            )
        } == -1
        {
            #[cfg(nightly)]
            cold_path();
            match unsafe { zmq_sys_crate::zmq_errno() } {
                errno @ zmq_sys_crate::errno::ENOTSUP => return Err(ZmqError::from(errno)),
                _ => unreachable!(),
            }
        }

        Ok((public_key.to_vec(), secret_key.to_vec()))
    }

    /// # derive the public key from a private key
    ///
    /// The [`curve_public()`] function shall derive the public key from a private key. The keys are
    /// encoded using [`z85_encode()`].
    ///
    /// [`curve_public()`]: curve_public
    /// [`z85_encode()`]: encode
    pub fn curve_public<T>(mut secret_key: T) -> ZmqResult<Vec<u8>>
    where
        T: AsMut<[u8]>,
    {
        let mut public_key: [u8; 41] = [0; 41];
        let secret_key_array = secret_key.as_mut();

        if unsafe {
            zmq_sys_crate::zmq_curve_public(
                public_key.as_mut_ptr() as *mut c_char,
                secret_key_array.as_ptr() as *const c_char,
            )
        } == -1
        {
            #[cfg(nightly)]
            cold_path();
            match unsafe { zmq_sys_crate::zmq_errno() } {
                errno @ zmq_sys_crate::errno::ENOTSUP => return Err(ZmqError::from(errno)),
                _ => unreachable!(),
            }
        }

        Ok(public_key.to_vec())
    }

    #[cfg(test)]
    mod curve_keypair_tests {
        use super::{curve_keypair, curve_public};
        use crate::prelude::ZmqResult;

        #[test]
        fn curve_keypair_generate_curve_keypair() -> ZmqResult<()> {
            let (public_key, secret_key) = curve_keypair()?;

            let pub_key = curve_public(secret_key)?;

            assert_eq!(public_key, pub_key);

            Ok(())
        }
    }
}

#[cfg(zmq_has = "gssapi")]
mod gssapi {
    use derive_more::Display;

    use crate::{prelude::ZmqError, zmq_sys_crate};

    #[derive(Debug, Display, PartialEq, Eq, Clone, Hash)]
    #[repr(i32)]
    /// # name types for GSSAPI
    pub enum GssApiNametype {
        /// the name is interpreted as a host based name
        NtHostbased,
        /// the name is interpreted as a local user name
        NtUsername,
        /// the name is interpreted as an unparsed principal name string (valid only with the krb5
        /// GSSAPI mechanism).
        NtKrb5Principal,
    }

    impl TryFrom<i32> for GssApiNametype {
        type Error = ZmqError;

        fn try_from(value: i32) -> Result<Self, Self::Error> {
            match value {
                _ if value == zmq_sys_crate::ZMQ_GSSAPI_NT_HOSTBASED as i32 => {
                    Ok(Self::NtHostbased)
                }
                _ if value == zmq_sys_crate::ZMQ_GSSAPI_NT_USER_NAME as i32 => Ok(Self::NtUsername),
                _ if value == zmq_sys_crate::ZMQ_GSSAPI_NT_KRB5_PRINCIPAL as i32 => {
                    Ok(Self::NtKrb5Principal)
                }
                _ => Err(ZmqError::Unsupported),
            }
        }
    }

    #[cfg(test)]
    mod gss_api_nametype_tests {
        use rstest::*;

        use super::GssApiNametype;
        use crate::{
            prelude::{ZmqError, ZmqResult},
            zmq_sys_crate,
        };

        #[rstest]
        #[case(zmq_sys_crate::ZMQ_GSSAPI_NT_HOSTBASED as i32, Ok(GssApiNametype::NtHostbased))]
        #[case(zmq_sys_crate::ZMQ_GSSAPI_NT_USER_NAME as i32, Ok(GssApiNametype::NtUsername))]
        #[case(zmq_sys_crate::ZMQ_GSSAPI_NT_KRB5_PRINCIPAL as i32, Ok(GssApiNametype::NtKrb5Principal)
        )]
        #[case(666, Err(ZmqError::Unsupported))]
        fn nametype_try_from(#[case] value: i32, #[case] expected: ZmqResult<GssApiNametype>) {
            assert_eq!(expected, GssApiNametype::try_from(value));
        }
    }
}