Skip to main content

confluent_kafka/admin/
user_scram_credential_upsertion.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//! A request to update/insert a SASL/SCRAM credential for a user.
16
17use std::fmt;
18
19use rand::Rng;
20
21use super::ScramCredentialInfo;
22use crate::common::config::types::Password;
23
24/// A request to update/insert a SASL/SCRAM credential for a user.
25///
26/// See [KIP-554: Add Broker-side SCRAM Config API](https://cwiki.apache.org/confluence/display/KAFKA/KIP-554%3A+Add+Broker-side+SCRAM+Config+API).
27///
28/// # Translation notes
29///
30/// `Debug` hides the salt and the password.
31#[derive(Clone)]
32#[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialUpsertion")]
33pub struct UserScramCredentialUpsertion {
34    user: String,
35    info: ScramCredentialInfo,
36    salt: Vec<u8>,
37    password: Vec<u8>,
38}
39
40impl UserScramCredentialUpsertion {
41    /// Constructor that accepts a string password and generates a random salt.
42    ///
43    /// The password is encoded with UTF-8.
44    ///
45    /// # Arguments
46    ///
47    /// - `user` - the user for which the credential is to be updated/inserted
48    /// - `credential_info` - the mechanism and iterations to be used
49    /// - `password` - the password
50    #[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialUpsertion#UserScramCredentialUpsertion")]
51    pub fn with_str(user: impl Into<String>, credential_info: ScramCredentialInfo, password: &str) -> Self {
52        Self::with_bytes(user, credential_info, password.as_bytes().to_vec())
53    }
54
55    /// Constructor that accepts a byte password and generates a random salt.
56    ///
57    /// # Arguments
58    ///
59    /// - `user` - the user for which the credential is to be updated/inserted
60    /// - `credential_info` - the mechanism and iterations to be used
61    /// - `password` - the password
62    #[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialUpsertion#UserScramCredentialUpsertion")]
63    pub fn with_bytes(user: impl Into<String>, credential_info: ScramCredentialInfo, password: Vec<u8>) -> Self {
64        let salt = generate_random_salt();
65        Self::with_salt(user, credential_info, password, salt)
66    }
67
68    /// Constructor that accepts an explicit salt.
69    ///
70    /// # Arguments
71    ///
72    /// - `user` - the user for which the credential is to be updated/inserted
73    /// - `credential_info` - the mechanism and iterations to be used
74    /// - `password` - the password
75    /// - `salt` - the salt to be used
76    #[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialUpsertion#UserScramCredentialUpsertion")]
77    pub fn with_salt(
78        user: impl Into<String>,
79        credential_info: ScramCredentialInfo,
80        password: Vec<u8>,
81        salt: Vec<u8>,
82    ) -> Self {
83        Self { user: user.into(), info: credential_info, salt, password }
84    }
85
86    /// Returns the always non-null user.
87    #[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialAlteration#user")]
88    pub fn user(&self) -> &str {
89        &self.user
90    }
91
92    /// Returns the mechanism and iterations.
93    #[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialUpsertion#credentialInfo")]
94    pub fn credential_info(&self) -> &ScramCredentialInfo {
95        &self.info
96    }
97
98    /// Returns the salt.
99    #[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialUpsertion#salt")]
100    pub fn salt(&self) -> &[u8] {
101        &self.salt
102    }
103
104    /// Returns the password.
105    #[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialUpsertion#password")]
106    pub fn password(&self) -> &[u8] {
107        &self.password
108    }
109}
110
111/// Java has no `toString()` here, so there is no Java rendering to mirror; a
112/// derived `Debug` would print the password (and the salt, keyed material for
113/// the stored credential) as their byte values, so both are hidden. Each renders
114/// as `Password::HIDDEN` with no quotes, as a `Password`'s own `Debug` does.
115impl fmt::Debug for UserScramCredentialUpsertion {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        // Destructured exhaustively, so a field added to the struct must be
118        // considered here; the two secrets are bound to `_` deliberately.
119        let Self { user, info, salt: _, password: _ } = self;
120        f.debug_struct("UserScramCredentialUpsertion")
121            .field("user", user)
122            .field("info", info)
123            .field("salt", &format_args!("{}", Password::HIDDEN))
124            .field("password", &format_args!("{}", Password::HIDDEN))
125            .finish()
126    }
127}
128
129/// Generates a random salt.
130///
131/// Mirrors `ScramFormatter.secureRandomBytes(new SecureRandom())` in spirit:
132/// Java produces the UTF-8 bytes of a 130-bit random base-36 string. Rather than
133/// pull in the full `ScramFormatter` (out of scope — only `hi()` is translated),
134/// we generate the equivalent: a random radix-36 string of the same magnitude.
135/// The salt is opaque random data sent verbatim to the broker, so any
136/// cryptographically-random value of adequate length is behavior-equivalent.
137#[doc(alias = "org.apache.kafka.clients.admin.UserScramCredentialUpsertion#generateRandomSalt")]
138fn generate_random_salt() -> Vec<u8> {
139    const ALPHABET: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
140    // 26 base-36 characters is ~134 bits of entropy, matching Java's 130-bit
141    // `new BigInteger(130, random)`.
142    let mut rng = rand::rng();
143    (0..26).map(|_| ALPHABET[rng.random_range(0..ALPHABET.len())]).collect()
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149    use crate::admin::ScramMechanism;
150
151    #[test]
152    fn string_constructor_encodes_password_utf8_and_generates_salt() {
153        let upsertion = UserScramCredentialUpsertion::with_str(
154            "alice",
155            ScramCredentialInfo::new(ScramMechanism::ScramSha256, 4096),
156            "pw",
157        );
158        assert_eq!(upsertion.user(), "alice");
159        assert_eq!(upsertion.password(), b"pw");
160        assert_eq!(upsertion.credential_info().mechanism(), ScramMechanism::ScramSha256);
161        assert!(!upsertion.salt().is_empty());
162    }
163
164    #[test]
165    fn explicit_salt_is_preserved() {
166        let upsertion = UserScramCredentialUpsertion::with_salt(
167            "bob",
168            ScramCredentialInfo::new(ScramMechanism::ScramSha512, 8192),
169            b"secret".to_vec(),
170            b"my-salt".to_vec(),
171        );
172        assert_eq!(upsertion.salt(), b"my-salt");
173        assert_eq!(upsertion.password(), b"secret");
174    }
175
176    /// New test, no Java original (Java has no `toString()`): `{:?}` and
177    /// `{:#?}` show the user and the credential info but neither the password
178    /// nor the salt, which a derived `Debug` would print as their byte values.
179    /// Both render as `[hidden]` with no quotes, as a `Password`'s `Debug` does.
180    #[test]
181    fn debug_hides_password_and_salt() {
182        let password = b"alice-S3cr3t-pw";
183        let salt = b"alice-salt-bytes";
184        let upsertion = UserScramCredentialUpsertion::with_salt(
185            "alice",
186            ScramCredentialInfo::new(ScramMechanism::ScramSha512, 8192),
187            password.to_vec(),
188            salt.to_vec(),
189        );
190        let rendered = format!("{upsertion:?}");
191        assert_eq!(
192            rendered,
193            format!(
194                "UserScramCredentialUpsertion {{ user: \"alice\", info: {:?}, salt: [hidden], password: [hidden] }}",
195                upsertion.credential_info()
196            )
197        );
198        for secret in [&password[..], &salt[..]] {
199            assert!(!rendered.contains(&format!("{secret:?}")), "{rendered}");
200            assert!(!rendered.contains(std::str::from_utf8(secret).unwrap()), "{rendered}");
201        }
202        assert!(rendered.contains("ScramSha512"), "{rendered}");
203        assert!(rendered.contains("8192"), "{rendered}");
204
205        let pretty = format!("{upsertion:#?}");
206        assert!(pretty.contains("\"alice\""), "{pretty}");
207        assert!(
208            pretty.ends_with("\n    salt: [hidden],\n    password: [hidden],\n}"),
209            "{pretty}"
210        );
211        assert_eq!(pretty.matches(Password::HIDDEN).count(), 2, "{pretty}");
212        assert!(!pretty.contains("\"[hidden]\""), "{pretty}");
213        for secret in [&password[..], &salt[..]] {
214            assert!(!pretty.contains(std::str::from_utf8(secret).unwrap()), "{pretty}");
215        }
216    }
217
218    #[test]
219    fn generated_salts_are_random() {
220        let a = generate_random_salt();
221        let b = generate_random_salt();
222        assert_eq!(a.len(), 26);
223        assert_ne!(a, b);
224    }
225}