Skip to main content

confluent_kafka/common/security/auth/
kafka_principal.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//! Kafka principal type.
16//!
17//! Corresponds to `org.apache.kafka.common.security.auth.KafkaPrincipal`.
18
19use std::fmt;
20use std::hash::{Hash, Hasher};
21
22/// Principals in Kafka are defined by a type and a name.
23///
24/// The principal type will always be `"User"` for the simple authorizer that is
25/// enabled by default, but custom authorizers can leverage different principal
26/// types (such as to enable group or role-based ACLs).
27#[derive(Debug, Clone)]
28#[doc(alias = "org.apache.kafka.common.security.auth.KafkaPrincipal")]
29pub struct KafkaPrincipal {
30    principal_type: String,
31    name: String,
32    token_authenticated: bool,
33}
34
35impl KafkaPrincipal {
36    /// The principal type used by the default authorizer.
37    pub const USER_TYPE: &'static str = "User";
38
39    /// Creates a new principal from a type and name (not token-authenticated).
40    ///
41    /// # Arguments
42    ///
43    /// - `principal_type` - the principal type, such as [`Self::USER_TYPE`]
44    /// - `name` - the principal name
45    #[doc(alias = "org.apache.kafka.common.security.auth.KafkaPrincipal#KafkaPrincipal")]
46    pub fn new(principal_type: impl Into<String>, name: impl Into<String>) -> Self {
47        Self::with_token_authenticated(principal_type, name, false)
48    }
49
50    /// Creates a new principal from a type, name, and token-authenticated flag.
51    ///
52    /// # Arguments
53    ///
54    /// - `principal_type` - the principal type, such as [`Self::USER_TYPE`]
55    /// - `name` - the principal name
56    /// - `token_authenticated` - whether the principal was authenticated with a delegation token
57    #[doc(alias = "org.apache.kafka.common.security.auth.KafkaPrincipal#KafkaPrincipal")]
58    pub fn with_token_authenticated(
59        principal_type: impl Into<String>,
60        name: impl Into<String>,
61        token_authenticated: bool,
62    ) -> Self {
63        Self { principal_type: principal_type.into(), name: name.into(), token_authenticated }
64    }
65
66    /// The anonymous principal (`User:ANONYMOUS`).
67    ///
68    /// Modeled as a function rather than a
69    /// constant because the name is an owned `String`.
70    #[doc(alias = "org.apache.kafka.common.security.auth.KafkaPrincipal#ANONYMOUS")]
71    pub fn anonymous() -> Self {
72        Self::new(Self::USER_TYPE, "ANONYMOUS")
73    }
74
75    /// Returns the principal name.
76    #[doc(alias = "org.apache.kafka.common.security.auth.KafkaPrincipal#getName")]
77    pub fn name(&self) -> &str {
78        &self.name
79    }
80
81    /// Returns the principal type.
82    #[doc(alias = "org.apache.kafka.common.security.auth.KafkaPrincipal#getPrincipalType")]
83    pub fn principal_type(&self) -> &str {
84        &self.principal_type
85    }
86
87    /// Sets whether the principal was authenticated with a delegation token.
88    ///
89    /// # Arguments
90    ///
91    /// - `token_authenticated` - whether the principal was authenticated with a delegation token
92    #[doc(alias = "org.apache.kafka.common.security.auth.KafkaPrincipal#tokenAuthenticated")]
93    pub fn set_token_authenticated(&mut self, token_authenticated: bool) {
94        self.token_authenticated = token_authenticated;
95    }
96
97    /// Returns whether the principal was authenticated with a delegation token.
98    #[doc(alias = "org.apache.kafka.common.security.auth.KafkaPrincipal#tokenAuthenticated")]
99    pub fn token_authenticated(&self) -> bool {
100        self.token_authenticated
101    }
102}
103
104impl fmt::Display for KafkaPrincipal {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        write!(f, "{}:{}", self.principal_type, self.name)
107    }
108}
109
110// `equals` / `hashCode` in Java consider only `principalType` and `name`
111// (never the mutable `tokenAuthenticated` flag), so we implement them by hand
112// rather than deriving.
113impl PartialEq for KafkaPrincipal {
114    fn eq(&self, other: &Self) -> bool {
115        self.principal_type == other.principal_type && self.name == other.name
116    }
117}
118
119impl Eq for KafkaPrincipal {}
120
121impl Hash for KafkaPrincipal {
122    fn hash<H: Hasher>(&self, state: &mut H) {
123        self.principal_type.hash(state);
124        self.name.hash(state);
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use std::collections::hash_map::DefaultHasher;
132
133    fn hash_of(p: &KafkaPrincipal) -> u64 {
134        let mut hasher = DefaultHasher::new();
135        p.hash(&mut hasher);
136        hasher.finish()
137    }
138
139    #[test]
140    fn to_string_is_type_colon_name() {
141        let principal = KafkaPrincipal::new(KafkaPrincipal::USER_TYPE, "alice");
142        assert_eq!(principal.to_string(), "User:alice");
143    }
144
145    #[test]
146    fn accessors_return_components() {
147        let principal = KafkaPrincipal::new("Group", "admins");
148        assert_eq!(principal.principal_type(), "Group");
149        assert_eq!(principal.name(), "admins");
150        assert!(!principal.token_authenticated());
151    }
152
153    #[test]
154    fn equals_and_hash_ignore_token_authenticated() {
155        let a = KafkaPrincipal::with_token_authenticated(KafkaPrincipal::USER_TYPE, "bob", false);
156        let b = KafkaPrincipal::with_token_authenticated(KafkaPrincipal::USER_TYPE, "bob", true);
157        assert_eq!(a, b);
158        assert_eq!(hash_of(&a), hash_of(&b));
159    }
160
161    #[test]
162    fn differs_by_type_or_name() {
163        let base = KafkaPrincipal::new(KafkaPrincipal::USER_TYPE, "bob");
164        assert_ne!(base, KafkaPrincipal::new(KafkaPrincipal::USER_TYPE, "carol"));
165        assert_ne!(base, KafkaPrincipal::new("Group", "bob"));
166    }
167
168    #[test]
169    fn anonymous_is_user_anonymous() {
170        let anon = KafkaPrincipal::anonymous();
171        assert_eq!(anon.principal_type(), KafkaPrincipal::USER_TYPE);
172        assert_eq!(anon.name(), "ANONYMOUS");
173        assert_eq!(anon.to_string(), "User:ANONYMOUS");
174    }
175
176    #[test]
177    fn setter_updates_token_authenticated() {
178        let mut principal = KafkaPrincipal::new(KafkaPrincipal::USER_TYPE, "dave");
179        principal.set_token_authenticated(true);
180        assert!(principal.token_authenticated());
181    }
182}