Skip to main content

confluent_kafka/common/security/auth/
security_protocol.rs

1// Copyright 2025 Confluent Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Security protocol enum for Kafka connections.
16//!
17//! Translated from `org.apache.kafka.common.security.auth.SecurityProtocol`.
18
19use std::fmt;
20use std::str::FromStr;
21
22/// Defines the security protocol used for communication with Kafka brokers.
23///
24/// Each protocol has a permanent, immutable numeric ID that matches the
25/// wire-protocol values used by the Java client.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
27#[non_exhaustive]
28#[doc(alias = "org.apache.kafka.common.security.auth.SecurityProtocol")]
29pub enum SecurityProtocol {
30    /// Un-authenticated, non-encrypted channel.
31    Plaintext,
32    /// SSL channel.
33    Ssl,
34    /// SASL authenticated, non-encrypted channel.
35    SaslPlaintext,
36    /// SASL authenticated, SSL channel.
37    SaslSsl,
38}
39
40impl SecurityProtocol {
41    /// All protocol variants in declaration order.
42    const ALL: [SecurityProtocol; 4] = [
43        SecurityProtocol::Plaintext,
44        SecurityProtocol::Ssl,
45        SecurityProtocol::SaslPlaintext,
46        SecurityProtocol::SaslSsl,
47    ];
48
49    /// Returns the permanent and immutable numeric ID for this security protocol.
50    ///
51    /// This value matches `kafka.cluster.SecurityProtocol` and must never change.
52    #[doc(alias = "org.apache.kafka.common.security.auth.SecurityProtocol#id")]
53    pub fn id(self) -> i16 {
54        match self {
55            SecurityProtocol::Plaintext => 0,
56            SecurityProtocol::Ssl => 1,
57            SecurityProtocol::SaslPlaintext => 2,
58            SecurityProtocol::SaslSsl => 3,
59        }
60    }
61
62    /// Returns the protocol name as used in configuration (e.g. `"PLAINTEXT"`, `"SASL_SSL"`).
63    #[doc(alias = "org.apache.kafka.common.security.auth.SecurityProtocol#name")]
64    pub fn name(self) -> &'static str {
65        match self {
66            SecurityProtocol::Plaintext => "PLAINTEXT",
67            SecurityProtocol::Ssl => "SSL",
68            SecurityProtocol::SaslPlaintext => "SASL_PLAINTEXT",
69            SecurityProtocol::SaslSsl => "SASL_SSL",
70        }
71    }
72
73    /// Looks up a security protocol by its numeric ID.
74    ///
75    /// # Arguments
76    ///
77    /// - `id` - the protocol's numeric ID
78    ///
79    /// # Returns
80    ///
81    /// The protocol, or `None` if no protocol has the given ID.
82    #[doc(alias = "org.apache.kafka.common.security.auth.SecurityProtocol#forId")]
83    pub fn for_id(id: i16) -> Option<Self> {
84        match id {
85            0 => Some(SecurityProtocol::Plaintext),
86            1 => Some(SecurityProtocol::Ssl),
87            2 => Some(SecurityProtocol::SaslPlaintext),
88            3 => Some(SecurityProtocol::SaslSsl),
89            _ => None,
90        }
91    }
92
93    /// Case insensitive lookup by protocol name.
94    ///
95    /// # Arguments
96    ///
97    /// - `name` - the protocol name
98    ///
99    /// # Returns
100    ///
101    /// The protocol, or `None` if no protocol matches the given name.
102    #[doc(alias = "org.apache.kafka.common.security.auth.SecurityProtocol#forName")]
103    pub fn for_name(name: &str) -> Option<Self> {
104        let upper = name.to_uppercase();
105        Self::ALL.iter().find(|p| p.name() == upper).copied()
106    }
107
108    /// Returns the names of all security protocols.
109    #[doc(alias = "org.apache.kafka.common.security.auth.SecurityProtocol#names")]
110    pub fn names() -> Vec<&'static str> {
111        Self::ALL.iter().map(|p| p.name()).collect()
112    }
113}
114
115impl fmt::Display for SecurityProtocol {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        write!(f, "{}", self.name())
118    }
119}
120
121impl FromStr for SecurityProtocol {
122    type Err = String;
123
124    // Parses a security protocol from its name (case-insensitive).
125    fn from_str(s: &str) -> Result<Self, Self::Err> {
126        SecurityProtocol::for_name(s).ok_or_else(|| format!("No enum constant SecurityProtocol.{}", s))
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    #[test]
135    fn test_id_values() {
136        assert_eq!(SecurityProtocol::Plaintext.id(), 0);
137        assert_eq!(SecurityProtocol::Ssl.id(), 1);
138        assert_eq!(SecurityProtocol::SaslPlaintext.id(), 2);
139        assert_eq!(SecurityProtocol::SaslSsl.id(), 3);
140    }
141
142    #[test]
143    fn test_name_values() {
144        assert_eq!(SecurityProtocol::Plaintext.name(), "PLAINTEXT");
145        assert_eq!(SecurityProtocol::Ssl.name(), "SSL");
146        assert_eq!(SecurityProtocol::SaslPlaintext.name(), "SASL_PLAINTEXT");
147        assert_eq!(SecurityProtocol::SaslSsl.name(), "SASL_SSL");
148    }
149
150    #[test]
151    fn test_for_id_roundtrip() {
152        for id in 0..=3 {
153            let protocol = SecurityProtocol::for_id(id).unwrap();
154            assert_eq!(protocol.id(), id);
155        }
156    }
157
158    #[test]
159    fn test_for_id_invalid() {
160        assert_eq!(SecurityProtocol::for_id(-1), None);
161        assert_eq!(SecurityProtocol::for_id(4), None);
162        assert_eq!(SecurityProtocol::for_id(100), None);
163    }
164
165    #[test]
166    fn test_for_name_roundtrip() {
167        let names = ["PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"];
168        for name in &names {
169            let protocol = SecurityProtocol::for_name(name).unwrap();
170            assert_eq!(protocol.name(), *name);
171        }
172    }
173
174    #[test]
175    fn test_for_name_case_insensitive() {
176        assert_eq!(SecurityProtocol::for_name("plaintext"), Some(SecurityProtocol::Plaintext));
177        assert_eq!(SecurityProtocol::for_name("Plaintext"), Some(SecurityProtocol::Plaintext));
178        assert_eq!(SecurityProtocol::for_name("sasl_ssl"), Some(SecurityProtocol::SaslSsl));
179        assert_eq!(
180            SecurityProtocol::for_name("Sasl_Plaintext"),
181            Some(SecurityProtocol::SaslPlaintext)
182        );
183    }
184
185    #[test]
186    fn test_for_name_invalid() {
187        assert_eq!(SecurityProtocol::for_name("INVALID"), None);
188        assert_eq!(SecurityProtocol::for_name(""), None);
189    }
190
191    #[test]
192    fn test_names() {
193        let names = SecurityProtocol::names();
194        assert_eq!(names.len(), 4);
195        assert_eq!(names[0], "PLAINTEXT");
196        assert_eq!(names[1], "SSL");
197        assert_eq!(names[2], "SASL_PLAINTEXT");
198        assert_eq!(names[3], "SASL_SSL");
199    }
200
201    #[test]
202    fn test_display() {
203        assert_eq!(format!("{}", SecurityProtocol::Plaintext), "PLAINTEXT");
204        assert_eq!(format!("{}", SecurityProtocol::SaslSsl), "SASL_SSL");
205    }
206
207    #[test]
208    fn test_from_str() {
209        assert_eq!("PLAINTEXT".parse::<SecurityProtocol>().unwrap(), SecurityProtocol::Plaintext);
210        assert_eq!("ssl".parse::<SecurityProtocol>().unwrap(), SecurityProtocol::Ssl);
211        assert!("INVALID".parse::<SecurityProtocol>().is_err());
212    }
213
214    #[test]
215    fn test_equality_and_hash() {
216        use std::collections::HashSet;
217        let mut set = HashSet::new();
218        set.insert(SecurityProtocol::Plaintext);
219        set.insert(SecurityProtocol::Plaintext);
220        assert_eq!(set.len(), 1);
221        set.insert(SecurityProtocol::Ssl);
222        assert_eq!(set.len(), 2);
223    }
224
225    #[test]
226    fn test_clone_and_copy() {
227        let p = SecurityProtocol::SaslPlaintext;
228        let p2 = p;
229        assert_eq!(p, p2);
230    }
231}