Skip to main content

confluent_kafka/admin/
describe_user_scram_credentials_result.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//! The result of the `Admin::describe_user_scram_credentials` call.
16
17use std::collections::HashMap;
18
19use crate::DescribeUserScramCredentialsResponseData;
20use crate::common::protocol::Errors;
21use crate::common::{Error, KafkaFuture};
22use crate::describe_user_scram_credentials_response_data::DescribeUserScramCredentialsResult as WireUserResult;
23
24use super::{ScramCredentialInfo, ScramMechanism, UserScramCredentialsDescription};
25
26/// The result of the `Admin::describe_user_scram_credentials` call.
27// Holds a single future over the raw response data; `all()`, `users()` and
28// `description()` are per-view refinements (Java uses `whenComplete` on the
29// data future to complete new `KafkaFutureImpl`s — here `then_apply`
30// expresses the same transform-on-completion).
31#[derive(Debug, Clone)]
32#[doc(alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResult")]
33pub struct DescribeUserScramCredentialsResult {
34    data_future: KafkaFuture<DescribeUserScramCredentialsResponseData>,
35}
36
37impl DescribeUserScramCredentialsResult {
38    /// Creates a new result from the future indicating response data from the
39    /// call.
40    #[doc(
41        alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResult#DescribeUserScramCredentialsResult"
42    )]
43    pub(crate) fn new(data_future: KafkaFuture<DescribeUserScramCredentialsResponseData>) -> Self {
44        Self { data_future }
45    }
46
47    /// Returns a future for the results of all described users, keyed by user
48    /// name. The future completes successfully only if all such user
49    /// descriptions complete successfully.
50    ///
51    /// A successfully
52    /// described user is one with *either* a `NONE` or a `RESOURCE_NOT_FOUND`
53    /// error code; the first user with any other error code fails the whole
54    /// future.
55    #[doc(alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResult#all")]
56    pub fn all(&self) -> KafkaFuture<HashMap<String, UserScramCredentialsDescription>> {
57        self.data_future.then_apply(|data: DescribeUserScramCredentialsResponseData| {
58            if let Some(first_failed) = data.results.iter().find(|result| {
59                result.error_code != Errors::None.code() && result.error_code != Errors::ResourceNotFound.code()
60            }) {
61                return Err(api_error(first_failed.error_code, &first_failed.error_message));
62            }
63            let mut map = HashMap::with_capacity(data.results.len());
64            for user_result in &data.results {
65                map.insert(
66                    user_result.user.clone(),
67                    UserScramCredentialsDescription::new(
68                        user_result.user.clone(),
69                        scram_credential_infos_for(user_result),
70                    ),
71                );
72            }
73            Ok(map)
74        })
75    }
76
77    /// Returns a future indicating the distinct users that meet the request criteria and that
78    /// have at least one credential. The future will not complete successfully if the user is
79    /// not authorized to perform the describe operation; otherwise, it will complete
80    /// successfully as long as the list of users with credentials can be successfully determined
81    /// within some hard-coded timeout period. Note that the returned list will not include users
82    /// that do not exist/have no credentials: a request to describe an explicit list of users,
83    /// none of which existed/had a credential, will result in a future that returns an empty
84    /// list being returned here. A returned list will include users that have a credential but
85    /// that could not be described.
86    #[doc(alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResult#users")]
87    pub fn users(&self) -> KafkaFuture<Vec<String>> {
88        self.data_future.then_apply(|data: DescribeUserScramCredentialsResponseData| {
89            Ok(data
90                .results
91                .iter()
92                .filter(|result| result.error_code != Errors::ResourceNotFound.code())
93                .map(|result| result.user.clone())
94                .collect())
95        })
96    }
97
98    /// Returns a future indicating the description results for the given user. The future will
99    /// complete with an error if the future returned by [`users`](Self::users) completes with an
100    /// error. Note that if the given user does not exist in the list of described users then the
101    /// returned future will complete with an error answering
102    /// `Error::is_resource_not_found_error`.
103    ///
104    /// # Arguments
105    ///
106    /// - `user_name` - the name of the user description being requested
107    #[doc(alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResult#description")]
108    pub fn description(&self, user_name: &str) -> KafkaFuture<UserScramCredentialsDescription> {
109        let user_name = user_name.to_string();
110        self.data_future
111            .then_apply(move |data: DescribeUserScramCredentialsResponseData| {
112                match data.results.iter().find(|result| result.user == user_name) {
113                    None => Err(Error::with_message(
114                        Errors::ResourceNotFound,
115                        format!("No such user: {user_name}"),
116                    )),
117                    Some(user_result) => {
118                        if user_result.error_code != Errors::None.code() {
119                            // RESOURCE_NOT_FOUND is included here.
120                            Err(api_error(user_result.error_code, &user_result.error_message))
121                        } else {
122                            Ok(UserScramCredentialsDescription::new(
123                                user_result.user.clone(),
124                                scram_credential_infos_for(user_result),
125                            ))
126                        }
127                    },
128                }
129            })
130    }
131}
132
133/// Mirrors `DescribeUserScramCredentialsResult.getScramCredentialInfosFor`.
134#[doc(alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResult#getScramCredentialInfosFor")]
135fn scram_credential_infos_for(user_result: &WireUserResult) -> Vec<ScramCredentialInfo> {
136    user_result
137        .credential_infos
138        .iter()
139        .map(|info| ScramCredentialInfo::new(ScramMechanism::from_type(info.mechanism), info.iterations))
140        .collect()
141}
142
143/// Builds a [`Error`] from a wire error code and optional message, mirroring
144/// `Errors.forCode(code).exception(message)`.
145fn api_error(code: i16, message: &Option<String>) -> Error {
146    let error = Errors::for_code(code);
147    // `org.apache.kafka.common.protocol.Errors#exception(String)` falls back to
148    // the code's default text only when the message is **null**; a non-null
149    // empty string is passed straight through to the builder. Treating `Some("")` as absent would
150    // substitute the default where the broker deliberately sent none.
151    match message {
152        Some(m) => Error::with_message(error, m.clone()),
153        None => Error::new(error),
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use crate::describe_user_scram_credentials_response_data::CredentialInfo;
161
162    fn user_result(user: &str, error_code: i16, infos: Vec<(i8, i32)>) -> WireUserResult {
163        let mut r = WireUserResult::new();
164        r.set_user(user.to_string()).set_error_code(error_code);
165        r.set_credential_infos(
166            infos
167                .into_iter()
168                .map(|(mech, it)| {
169                    let mut ci = CredentialInfo::new();
170                    ci.set_mechanism(mech).set_iterations(it);
171                    ci
172                })
173                .collect(),
174        );
175        r
176    }
177
178    fn data_future_completed(results: Vec<WireUserResult>) -> KafkaFuture<DescribeUserScramCredentialsResponseData> {
179        let mut data = DescribeUserScramCredentialsResponseData::new();
180        data.set_error_code(Errors::None.code()).set_results(results);
181        KafkaFuture::completed_future(Ok(data))
182    }
183
184    // Mirrors `DescribeUserScramCredentialsResultTest.testTopLevelError`.
185    #[tokio::test]
186    #[doc(alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResultTest#testTopLevelError")]
187    async fn test_top_level_error() {
188        let data_future: KafkaFuture<DescribeUserScramCredentialsResponseData> =
189            KafkaFuture::completed_future(Err(Error::new(Errors::UnknownServerError)));
190        let results = DescribeUserScramCredentialsResult::new(data_future);
191        assert!(results.all().get().await.is_err());
192        assert!(results.users().get().await.is_err());
193        assert!(results.description("whatever").get().await.is_err());
194    }
195
196    // Mirrors `DescribeUserScramCredentialsResultTest.testUserLevelErrors`.
197    #[tokio::test]
198    #[doc(alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResultTest#testUserLevelErrors")]
199    async fn test_user_level_errors() {
200        let good_user = "goodUser";
201        let unknown_user = "unknownUser";
202        let failed_user = "failedUser";
203        let iterations = 4096;
204        let sha256 = ScramMechanism::ScramSha256;
205        let data_future = data_future_completed(vec![
206            user_result(good_user, Errors::None.code(), vec![(sha256.r#type(), iterations)]),
207            user_result(unknown_user, Errors::ResourceNotFound.code(), vec![]),
208            user_result(failed_user, Errors::DuplicateResource.code(), vec![]),
209        ]);
210        let results = DescribeUserScramCredentialsResult::new(data_future);
211
212        assert!(
213            results.all().get().await.is_err(),
214            "expected all() to fail on a user-level error"
215        );
216
217        let users = results.users().get().await.unwrap();
218        assert_eq!(
219            users,
220            vec![good_user.to_string(), failed_user.to_string()],
221            "Expected 2 users with credentials"
222        );
223
224        let good_description = results.description(good_user).get().await.unwrap();
225        assert_eq!(
226            good_description,
227            UserScramCredentialsDescription::new(good_user, vec![ScramCredentialInfo::new(sha256, iterations)])
228        );
229        assert!(results.description(failed_user).get().await.is_err());
230        assert!(results.description(unknown_user).get().await.is_err());
231    }
232
233    // Mirrors `DescribeUserScramCredentialsResultTest.testSuccessfulDescription`.
234    #[tokio::test]
235    #[doc(alias = "org.apache.kafka.clients.admin.DescribeUserScramCredentialsResultTest#testSuccessfulDescription")]
236    async fn test_successful_description() {
237        let good_user = "goodUser";
238        let unknown_user = "unknownUser";
239        let iterations = 4096;
240        let sha256 = ScramMechanism::ScramSha256;
241        let data_future = data_future_completed(vec![user_result(
242            good_user,
243            Errors::None.code(),
244            vec![(sha256.r#type(), iterations)],
245        )]);
246        let results = DescribeUserScramCredentialsResult::new(data_future);
247
248        assert_eq!(results.users().get().await.unwrap(), vec![good_user.to_string()]);
249        let all_results = results.all().get().await.unwrap();
250        assert_eq!(all_results.len(), 1);
251        let via_all = all_results.get(good_user).unwrap().clone();
252        assert_eq!(
253            via_all,
254            UserScramCredentialsDescription::new(good_user, vec![ScramCredentialInfo::new(sha256, iterations)])
255        );
256        assert_eq!(via_all, results.description(good_user).get().await.unwrap());
257        assert!(results.description(unknown_user).get().await.is_err());
258    }
259}