Skip to main content

confluent_kafka/common/security/token/delegation/
delegation_token.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//! Delegation token.
16//!
17//! Corresponds to
18//! `org.apache.kafka.common.security.token.delegation.DelegationToken`.
19
20use std::fmt;
21
22use crate::common::security::token::delegation::TokenInformation;
23
24/// Standard Base64 alphabet (RFC 4648), matching `java.util.Base64.getEncoder()`.
25const BASE64_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
26
27/// Encodes bytes using the standard Base64 alphabet with padding, mirroring
28/// `java.util.Base64.getEncoder().encodeToString`.
29fn base64_encode(data: &[u8]) -> String {
30    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
31    for chunk in data.chunks(3) {
32        let b0 = chunk[0] as u32;
33        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
34        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
35        let triple = (b0 << 16) | (b1 << 8) | b2;
36        out.push(BASE64_ALPHABET[((triple >> 18) & 0x3F) as usize] as char);
37        out.push(BASE64_ALPHABET[((triple >> 12) & 0x3F) as usize] as char);
38        if chunk.len() > 1 {
39            out.push(BASE64_ALPHABET[((triple >> 6) & 0x3F) as usize] as char);
40        } else {
41            out.push('=');
42        }
43        if chunk.len() > 2 {
44            out.push(BASE64_ALPHABET[(triple & 0x3F) as usize] as char);
45        } else {
46            out.push('=');
47        }
48    }
49    out
50}
51
52/// A class representing a delegation token.
53#[derive(Clone, PartialEq, Eq, Hash)]
54#[doc(alias = "org.apache.kafka.common.security.token.delegation.DelegationToken")]
55pub struct DelegationToken {
56    token_information: TokenInformation,
57    hmac: Vec<u8>,
58}
59
60impl DelegationToken {
61    /// Creates a delegation token from its information and HMAC bytes.
62    ///
63    /// # Arguments
64    ///
65    /// - `token_information` - the token information
66    /// - `hmac` - the token's HMAC bytes
67    #[doc(alias = "org.apache.kafka.common.security.token.delegation.DelegationToken#DelegationToken")]
68    pub fn new(token_information: TokenInformation, hmac: Vec<u8>) -> Self {
69        Self { token_information, hmac }
70    }
71
72    /// Returns the token information.
73    #[doc(alias = "org.apache.kafka.common.security.token.delegation.DelegationToken#tokenInfo")]
74    pub fn token_info(&self) -> &TokenInformation {
75        &self.token_information
76    }
77
78    /// Returns a mutable reference to the token information.
79    ///
80    /// Enables the mock's `renewDelegationToken`, which mutates the stored
81    /// token's expiry timestamp (`token.tokenInfo().setExpiryTimestamp(...)`).
82    pub(crate) fn token_info_mut(&mut self) -> &mut TokenInformation {
83        &mut self.token_information
84    }
85
86    /// Returns the HMAC bytes.
87    #[doc(alias = "org.apache.kafka.common.security.token.delegation.DelegationToken#hmac")]
88    pub fn hmac(&self) -> &[u8] {
89        &self.hmac
90    }
91
92    /// Returns the HMAC bytes as a standard Base64 string.
93    #[doc(alias = "org.apache.kafka.common.security.token.delegation.DelegationToken#hmacAsBase64String")]
94    pub fn hmac_as_base64_string(&self) -> String {
95        base64_encode(&self.hmac)
96    }
97}
98
99impl fmt::Display for DelegationToken {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        // Mirrors Java's `toString`, which redacts the HMAC.
102        write!(
103            f,
104            "DelegationToken{{tokenInformation={}, hmac=[*******]}}",
105            self.token_information
106        )
107    }
108}
109
110impl fmt::Debug for DelegationToken {
111    // Delegates to `fmt::Display`: Java has a single `toString()`, and it
112    // redacts the HMAC, so the Rust `Debug` must not print it either.
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        fmt::Display::fmt(self, f)
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::common::security::auth::KafkaPrincipal;
122
123    fn token_info() -> TokenInformation {
124        TokenInformation::new(
125            "token-id",
126            KafkaPrincipal::new(KafkaPrincipal::USER_TYPE, "alice"),
127            vec![KafkaPrincipal::new(KafkaPrincipal::USER_TYPE, "bob")],
128            1,
129            100,
130            50,
131        )
132    }
133
134    #[test]
135    fn accessors_return_components() {
136        let token = DelegationToken::new(token_info(), b"hmac-bytes".to_vec());
137        assert_eq!(token.token_info().token_id(), "token-id");
138        assert_eq!(token.hmac(), b"hmac-bytes");
139    }
140
141    #[test]
142    fn base64_matches_java_encoder() {
143        // Known vectors from java.util.Base64.getEncoder().encodeToString.
144        assert_eq!(base64_encode(b""), "");
145        assert_eq!(base64_encode(b"f"), "Zg==");
146        assert_eq!(base64_encode(b"fo"), "Zm8=");
147        assert_eq!(base64_encode(b"foo"), "Zm9v");
148        assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
149        assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
150        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
151        // Bytes exercising the '+' and '/' alphabet entries.
152        assert_eq!(base64_encode(&[0xFB, 0xFF, 0xFE]), "+//+");
153    }
154
155    #[test]
156    fn hmac_as_base64_string_uses_standard_encoder() {
157        let token = DelegationToken::new(token_info(), b"foobar".to_vec());
158        assert_eq!(token.hmac_as_base64_string(), "Zm9vYmFy");
159    }
160
161    #[test]
162    fn display_redacts_hmac() {
163        let token = DelegationToken::new(token_info(), b"secret".to_vec());
164        let rendered = token.to_string();
165        assert!(rendered.contains("hmac=[*******]"), "{rendered}");
166        assert!(!rendered.contains("secret"), "{rendered}");
167    }
168
169    /// Java has a single `toString()`, so `Debug` renders exactly what
170    /// `Display` does and never the HMAC, which a derived `Debug` would print
171    /// as its byte values.
172    #[test]
173    fn debug_redacts_hmac() {
174        let token = DelegationToken::new(token_info(), b"secret".to_vec());
175        for rendered in [format!("{token:?}"), format!("{token:#?}")] {
176            assert_eq!(rendered, token.to_string());
177            assert!(rendered.contains("hmac=[*******]"), "{rendered}");
178            assert!(!rendered.contains("secret"), "{rendered}");
179            assert!(!rendered.contains(&format!("{:?}", token.hmac())), "{rendered}");
180            assert!(!rendered.contains("115, 101, 99"), "{rendered}");
181        }
182    }
183
184    #[test]
185    fn equals_considers_info_and_hmac() {
186        let a = DelegationToken::new(token_info(), b"x".to_vec());
187        let b = DelegationToken::new(token_info(), b"x".to_vec());
188        let c = DelegationToken::new(token_info(), b"y".to_vec());
189        assert_eq!(a, b);
190        assert_ne!(a, c);
191    }
192}