Skip to main content

kanidm_client/
lib.rs

1#![deny(warnings)]
2#![warn(unused_extern_crates)]
3#![deny(clippy::todo)]
4#![deny(clippy::unimplemented)]
5#![deny(clippy::unwrap_used)]
6#![deny(clippy::expect_used)]
7#![deny(clippy::panic)]
8#![deny(clippy::unreachable)]
9#![deny(clippy::await_holding_lock)]
10#![deny(clippy::needless_pass_by_value)]
11#![deny(clippy::trivially_copy_pass_by_ref)]
12
13#[macro_use]
14extern crate tracing;
15
16#[cfg(target_family = "unix")] // not needed for windows builds
17use std::fs::{metadata, Metadata};
18#[cfg(target_family = "unix")] // not needed for windows builds
19use std::os::unix::fs::MetadataExt;
20use std::{
21    collections::{BTreeMap, BTreeSet},
22    fmt::{Debug, Display, Formatter},
23    fs::File,
24    io::{ErrorKind, Read},
25    path::Path,
26    sync::Arc,
27    time::Duration,
28};
29
30use compact_jwt::Jwk;
31
32pub use http;
33use kanidm_proto::{
34    constants::{
35        uri::V1_AUTH_VALID, ATTR_DOMAIN_DISPLAY_NAME, ATTR_DOMAIN_LDAP_BASEDN, ATTR_DOMAIN_SSID,
36        ATTR_ENTRY_MANAGED_BY, ATTR_KEY_ACTION_REVOKE, ATTR_LDAP_ALLOW_UNIX_PW_BIND,
37        ATTR_LDAP_MAX_QUERYABLE_ATTRS, ATTR_NAME, CLIENT_TOKEN_CACHE, KOPID, KSESSIONID, KVERSION,
38    },
39    internal::*,
40    v1::*,
41};
42pub use reqwest::StatusCode;
43use reqwest::{
44    cookie::{CookieStore, Jar},
45    Response,
46};
47use serde::{de::DeserializeOwned, Deserialize, Serialize};
48use serde_json::error::Error as SerdeJsonError;
49use serde_urlencoded::ser::Error as UrlEncodeError;
50use tokio::sync::{Mutex, RwLock};
51use url::Url;
52use uuid::Uuid;
53use webauthn_rs_proto::{
54    PublicKeyCredential, RegisterPublicKeyCredential, RequestChallengeResponse,
55};
56
57mod application;
58mod domain;
59mod feature;
60mod group;
61mod message;
62mod oauth;
63mod person;
64mod schema;
65mod scim;
66mod service_account;
67mod sync_account;
68mod system;
69
70const EXPECT_VERSION: &str = env!("CARGO_PKG_VERSION");
71
72#[derive(Debug)]
73pub enum ClientError {
74    Unauthorized,
75    SessionExpired,
76    Http(reqwest::StatusCode, Option<OperationError>, String),
77    Transport(reqwest::Error),
78    AuthenticationFailed,
79    EmptyResponse,
80    TotpVerifyFailed(Uuid, TotpSecret),
81    TotpInvalidSha1(Uuid),
82    JsonDecode(reqwest::Error, String),
83    InvalidResponseFormat(String),
84    JsonEncode(SerdeJsonError),
85    UrlEncode(UrlEncodeError),
86    SystemError,
87    ConfigParseIssue(String),
88    CertParseIssue(String),
89    UntrustedCertificate(String),
90    InvalidRequest(String),
91}
92
93/// Settings describing a single instance.
94#[derive(Debug, Deserialize, Serialize)]
95pub struct KanidmClientConfigInstance {
96    /// The URL of the server, ie `https://example.com`.
97    ///
98    /// Environment variable is `KANIDM_URL`. Yeah, we know.
99    pub uri: Option<String>,
100    /// Whether to verify the TLS certificate of the server matches the hostname you connect to, defaults to `true`.
101    ///
102    /// Environment variable is slightly inverted - `KANIDM_SKIP_HOSTNAME_VERIFICATION`.
103    pub verify_hostnames: Option<bool>,
104    /// Whether to verify the Certificate Authority details of the server's TLS certificate, defaults to `true`.
105    ///
106    /// Environment variable is slightly inverted - `KANIDM_ACCEPT_INVALID_CERTS`.
107    pub verify_ca: Option<bool>,
108    /// Optionally you can specify the path of a CA certificate to use for verifying the server, if you're not using one trusted by your system certificate store.
109    ///
110    /// Environment variable is `KANIDM_CA_PATH`.
111    pub ca_path: Option<String>,
112
113    /// Connection Timeout for the client, in seconds.
114    pub connect_timeout: Option<u64>,
115}
116
117#[derive(Debug, Deserialize, Serialize)]
118/// This struct is what Kanidm uses for parsing the client configuration at runtime.
119///
120/// # Configuration file inheritance
121///
122/// The configuration files are loaded in order, with the last one loaded overriding the previous one.
123///
124/// 1. The "system" config is loaded from in [kanidm_proto::constants::DEFAULT_CLIENT_CONFIG_PATH].
125/// 2. Then a per-user configuration, from [kanidm_proto::constants::DEFAULT_CLIENT_CONFIG_PATH_HOME] is loaded.
126/// 3. All of these may be overridden by setting environment variables.
127///
128pub struct KanidmClientConfig {
129    // future editors, please leave this public so others can parse the config!
130    #[serde(flatten)]
131    pub default: KanidmClientConfigInstance,
132
133    #[serde(flatten)]
134    // future editors, please leave this public so others can parse the config!
135    pub instances: BTreeMap<String, KanidmClientConfigInstance>,
136}
137
138#[derive(Debug, Clone, Default)]
139pub struct KanidmClientBuilder {
140    address: Option<String>,
141    verify_ca: bool,
142    verify_hostnames: bool,
143    ca: Option<reqwest::Certificate>,
144    connect_timeout: Option<u64>,
145    request_timeout: Option<u64>,
146    use_system_proxies: bool,
147    /// Where to store auth tokens, only use in testing!
148    token_cache_path: Option<String>,
149    disable_system_ca_store: bool,
150}
151
152impl Display for KanidmClientBuilder {
153    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
154        match &self.address {
155            Some(value) => writeln!(f, "address: {value}")?,
156            None => writeln!(f, "address: unset")?,
157        }
158        writeln!(f, "verify_ca: {}", self.verify_ca)?;
159        writeln!(f, "verify_hostnames: {}", self.verify_hostnames)?;
160        match &self.ca {
161            Some(value) => writeln!(f, "ca: {value:#?}")?,
162            None => writeln!(f, "ca: unset")?,
163        }
164        match self.connect_timeout {
165            Some(value) => writeln!(f, "connect_timeout: {value}")?,
166            None => writeln!(f, "connect_timeout: unset")?,
167        }
168        match self.request_timeout {
169            Some(value) => writeln!(f, "request_timeout: {value}")?,
170            None => writeln!(f, "request_timeout: unset")?,
171        }
172        writeln!(f, "use_system_proxies: {}", self.use_system_proxies)?;
173        writeln!(
174            f,
175            "token_cache_path: {}",
176            self.token_cache_path
177                .clone()
178                .unwrap_or(CLIENT_TOKEN_CACHE.to_string())
179        )
180    }
181}
182
183#[derive(Debug)]
184pub struct KanidmClient {
185    pub(crate) client: reqwest::Client,
186    client_cookies: Arc<Jar>,
187    pub(crate) addr: String,
188    pub(crate) origin: Url,
189    pub(crate) builder: KanidmClientBuilder,
190    pub(crate) bearer_token: RwLock<Option<String>>,
191    pub(crate) auth_session_id: RwLock<Option<String>>,
192    pub(crate) check_version: Mutex<bool>,
193    /// Where to store the tokens when you auth, only modify in testing.
194    token_cache_path: String,
195}
196
197#[cfg(target_family = "unix")]
198fn read_file_metadata<P: AsRef<Path>>(path: &P) -> Result<Metadata, ()> {
199    metadata(path).map_err(|e| {
200        error!(
201            "Unable to read metadata for {} - {:?}",
202            path.as_ref().to_str().unwrap_or("Alert: invalid path"),
203            e
204        );
205    })
206}
207
208impl KanidmClientBuilder {
209    pub fn new() -> Self {
210        KanidmClientBuilder {
211            address: None,
212            verify_ca: true,
213            verify_hostnames: true,
214            ca: None,
215            connect_timeout: None,
216            request_timeout: None,
217            use_system_proxies: true,
218            token_cache_path: None,
219            disable_system_ca_store: false,
220        }
221    }
222
223    fn parse_certificate(ca_path: &str) -> Result<reqwest::Certificate, ClientError> {
224        let mut buf = Vec::new();
225        // Is the CA secure?
226        #[cfg(target_family = "windows")]
227        warn!("File metadata checks on Windows aren't supported right now, this could be a security risk.");
228
229        #[cfg(target_family = "unix")]
230        {
231            let path = Path::new(ca_path);
232            let ca_meta = read_file_metadata(&path).map_err(|e| {
233                error!("{:?}", e);
234                ClientError::ConfigParseIssue(format!("{e:?}"))
235            })?;
236
237            trace!("uid:gid {}:{}", ca_meta.uid(), ca_meta.gid());
238
239            #[cfg(not(debug_assertions))]
240            if ca_meta.uid() != 0 || ca_meta.gid() != 0 {
241                warn!(
242                    "{} should be owned be root:root to prevent tampering",
243                    ca_path
244                );
245            }
246
247            trace!("mode={:o}", ca_meta.mode());
248            if (ca_meta.mode() & 0o7133) != 0 {
249                warn!("permissions on {} are NOT secure. 0644 is a secure default. Should not be setuid, executable or allow group/other writes.", ca_path);
250            }
251        }
252
253        let mut f = File::open(ca_path).map_err(|e| {
254            error!("{:?}", e);
255            ClientError::ConfigParseIssue(format!("{e:?}"))
256        })?;
257        f.read_to_end(&mut buf).map_err(|e| {
258            error!("{:?}", e);
259            ClientError::ConfigParseIssue(format!("{e:?}"))
260        })?;
261        reqwest::Certificate::from_pem(&buf).map_err(|e| {
262            error!("{:?}", e);
263            ClientError::CertParseIssue(format!("{e:?}"))
264        })
265    }
266
267    fn apply_config_options(self, kcc: KanidmClientConfigInstance) -> Result<Self, ClientError> {
268        let KanidmClientBuilder {
269            address,
270            verify_ca,
271            verify_hostnames,
272            ca,
273            connect_timeout,
274            request_timeout,
275            use_system_proxies,
276            token_cache_path,
277            disable_system_ca_store,
278        } = self;
279        // Process and apply all our options if they exist.
280        let address = match kcc.uri {
281            Some(uri) => Some(uri),
282            None => {
283                debug!("No URI in config supplied to apply_config_options");
284                address
285            }
286        };
287        let verify_ca = kcc.verify_ca.unwrap_or(verify_ca);
288        let verify_hostnames = kcc.verify_hostnames.unwrap_or(verify_hostnames);
289        let ca = match kcc.ca_path {
290            Some(ca_path) => Some(Self::parse_certificate(&ca_path)?),
291            None => ca,
292        };
293        let connect_timeout = kcc.connect_timeout.or(connect_timeout);
294
295        Ok(KanidmClientBuilder {
296            address,
297            verify_ca,
298            verify_hostnames,
299            ca,
300            connect_timeout,
301            request_timeout,
302            use_system_proxies,
303            token_cache_path,
304            disable_system_ca_store,
305        })
306    }
307
308    pub fn read_options_from_optional_config<P: AsRef<Path> + std::fmt::Debug>(
309        self,
310        config_path: P,
311    ) -> Result<Self, ClientError> {
312        self.read_options_from_optional_instance_config(config_path, None)
313    }
314
315    pub fn read_options_from_optional_instance_config<P: AsRef<Path> + std::fmt::Debug>(
316        self,
317        config_path: P,
318        instance: Option<&str>,
319    ) -> Result<Self, ClientError> {
320        debug!(
321            "Attempting to load {} instance configuration from {:#?}",
322            instance.unwrap_or("default"),
323            &config_path
324        );
325
326        // We have to check the .exists case manually, because there are some weird overlayfs
327        // issues in docker where when the file does NOT exist, but we "open it" we get an
328        // error describing that the file is actually a directory rather than a not exists
329        // error. This check enforces that we get the CORRECT error message instead.
330        if !config_path.as_ref().exists() {
331            debug!("{:?} does not exist", config_path);
332            let diag = kanidm_lib_file_permissions::diagnose_path(config_path.as_ref());
333            debug!(%diag);
334            return Ok(self);
335        };
336
337        // If the file does not exist, we skip this function.
338        let mut f = match File::open(&config_path) {
339            Ok(f) => {
340                debug!("Successfully opened configuration file {:#?}", &config_path);
341                f
342            }
343            Err(e) => {
344                match e.kind() {
345                    ErrorKind::NotFound => {
346                        debug!(
347                            "Configuration file {:#?} not found, skipping.",
348                            &config_path
349                        );
350                    }
351                    ErrorKind::PermissionDenied => {
352                        warn!(
353                            "Permission denied loading configuration file {:#?}, skipping.",
354                            &config_path
355                        );
356                    }
357                    _ => {
358                        debug!(
359                            "Unable to open config file {:#?} [{:?}], skipping ...",
360                            &config_path, e
361                        );
362                    }
363                };
364                let diag = kanidm_lib_file_permissions::diagnose_path(config_path.as_ref());
365                info!(%diag);
366
367                return Ok(self);
368            }
369        };
370
371        let mut contents = String::new();
372        f.read_to_string(&mut contents).map_err(|e| {
373            error!("{:?}", e);
374            ClientError::ConfigParseIssue(format!("{e:?}"))
375        })?;
376
377        let mut config: KanidmClientConfig = toml::from_str(&contents).map_err(|e| {
378            error!("{:?}", e);
379            ClientError::ConfigParseIssue(format!("{e:?}"))
380        })?;
381
382        if let Some(instance_name) = instance {
383            if let Some(instance_config) = config.instances.remove(instance_name) {
384                self.apply_config_options(instance_config)
385            } else {
386                info!(
387                    "instance {} does not exist in config file {}",
388                    instance_name,
389                    config_path.as_ref().display()
390                );
391
392                // It's not an error if the instance isn't present, the build step
393                // will fail if there is insufficient information to proceed.
394                Ok(self)
395            }
396        } else {
397            self.apply_config_options(config.default)
398        }
399    }
400
401    pub fn address(self, address: String) -> Self {
402        KanidmClientBuilder {
403            address: Some(address),
404            ..self
405        }
406    }
407
408    /// Enable or disable the native ca roots. By default these roots are enabled.
409    pub fn enable_native_ca_roots(self, enable: bool) -> Self {
410        KanidmClientBuilder {
411            // We have to flip the bool state here due to Default on bool being false
412            // and we want our options to be positive to a native speaker.
413            disable_system_ca_store: !enable,
414            ..self
415        }
416    }
417
418    pub fn danger_accept_invalid_hostnames(self, accept_invalid_hostnames: bool) -> Self {
419        KanidmClientBuilder {
420            // We have to flip the bool state here due to english language.
421            verify_hostnames: !accept_invalid_hostnames,
422            ..self
423        }
424    }
425
426    pub fn danger_accept_invalid_certs(self, accept_invalid_certs: bool) -> Self {
427        KanidmClientBuilder {
428            // We have to flip the bool state here due to english language.
429            verify_ca: !accept_invalid_certs,
430            ..self
431        }
432    }
433
434    pub fn connect_timeout(self, secs: u64) -> Self {
435        KanidmClientBuilder {
436            connect_timeout: Some(secs),
437            ..self
438        }
439    }
440
441    pub fn request_timeout(self, secs: u64) -> Self {
442        KanidmClientBuilder {
443            request_timeout: Some(secs),
444            ..self
445        }
446    }
447
448    pub fn no_proxy(self) -> Self {
449        KanidmClientBuilder {
450            use_system_proxies: false,
451            ..self
452        }
453    }
454
455    pub fn set_token_cache_path(self, token_cache_path: Option<String>) -> Self {
456        KanidmClientBuilder {
457            token_cache_path,
458            ..self
459        }
460    }
461
462    #[allow(clippy::result_unit_err)]
463    pub fn add_root_certificate_filepath(self, ca_path: &str) -> Result<Self, ClientError> {
464        //Okay we have a ca to add. Let's read it in and setup.
465        let ca = Self::parse_certificate(ca_path).map_err(|e| {
466            error!("{:?}", e);
467            ClientError::CertParseIssue(format!("{e:?}"))
468        })?;
469
470        Ok(KanidmClientBuilder {
471            ca: Some(ca),
472            ..self
473        })
474    }
475
476    fn display_warnings(&self, address: &str) {
477        // Check for problems now
478        if !self.verify_ca {
479            warn!("verify_ca set to false in client configuration - this may allow network interception of passwords!");
480        }
481
482        if !self.verify_hostnames {
483            warn!(
484                "verify_hostnames set to false in client configuration - this may allow network interception of passwords!"
485            );
486        }
487        if !address.starts_with("https://") {
488            warn!("Address does not start with 'https://' - this may allow network interception of passwords!");
489        }
490    }
491
492    /// Generates a useragent header based on the package name and version
493    pub fn user_agent() -> &'static str {
494        static APP_USER_AGENT: &str =
495            concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
496        APP_USER_AGENT
497    }
498
499    /*
500    /// Consume self and return an async client.
501    pub fn build(self) -> Result<KanidmClient, reqwest::Error> {
502        self.build_async().map(|asclient| KanidmClient { asclient })
503    }
504    */
505
506    /// Build the client ready for usage.
507    pub fn build(self) -> Result<KanidmClient, ClientError> {
508        // Errghh, how to handle this cleaner.
509        let address = match &self.address {
510            Some(a) => a.clone(),
511            None => {
512                error!("Configuration option 'uri' missing from client configuration, cannot continue client startup without specifying a server to connect to. 🤔");
513                return Err(ClientError::ConfigParseIssue(
514                    "Configuration option 'uri' missing from client configuration, cannot continue client startup without specifying a server to connect to. 🤔".to_string(),
515                ));
516            }
517        };
518
519        self.display_warnings(&address);
520
521        let client_cookies = Arc::new(Jar::default());
522
523        let mut client_builder = reqwest::Client::builder()
524            .user_agent(KanidmClientBuilder::user_agent())
525            // We don't directly use cookies, but it may be required for load balancers that
526            // implement sticky sessions with cookies.
527            .cookie_store(true)
528            .cookie_provider(client_cookies.clone());
529
530        if let Some(cacert) = self.ca.as_ref() {
531            if self.disable_system_ca_store {
532                client_builder = client_builder.tls_certs_only(vec![cacert.clone()])
533            }
534        };
535
536        client_builder = client_builder
537            // .tls_built_in_native_certs(!self.disable_system_ca_store)
538            .danger_accept_invalid_hostnames(!self.verify_hostnames)
539            .danger_accept_invalid_certs(!self.verify_ca);
540
541        let client_builder = match self.use_system_proxies {
542            true => client_builder,
543            false => client_builder.no_proxy(),
544        };
545
546        let client_builder = match &self.ca {
547            Some(cert) => client_builder.add_root_certificate(cert.clone()),
548            None => client_builder,
549        };
550
551        let client_builder = match &self.connect_timeout {
552            Some(secs) => client_builder.connect_timeout(Duration::from_secs(*secs)),
553            None => client_builder,
554        };
555
556        let client_builder = match &self.request_timeout {
557            Some(secs) => client_builder.timeout(Duration::from_secs(*secs)),
558            None => client_builder,
559        };
560
561        let client = client_builder.build().map_err(ClientError::Transport)?;
562
563        // Now get the origin.
564        #[allow(clippy::expect_used)]
565        let uri = Url::parse(&address).expect("failed to parse address");
566
567        #[allow(clippy::expect_used)]
568        let origin =
569            Url::parse(&uri.origin().ascii_serialization()).expect("failed to parse origin");
570
571        let token_cache_path = match self.token_cache_path.clone() {
572            Some(val) => val.to_string(),
573            None => CLIENT_TOKEN_CACHE.to_string(),
574        };
575
576        Ok(KanidmClient {
577            client,
578            client_cookies,
579            addr: address,
580            builder: self,
581            bearer_token: RwLock::new(None),
582            auth_session_id: RwLock::new(None),
583            origin,
584            check_version: Mutex::new(true),
585            token_cache_path,
586        })
587    }
588}
589
590/// This is probably pretty jank but it works and was pulled from here:
591/// <https://github.com/seanmonstar/reqwest/issues/1602#issuecomment-1220996681>
592fn find_reqwest_error_source<E: std::error::Error + 'static>(
593    orig: &dyn std::error::Error,
594) -> Option<&E> {
595    let mut cause = orig.source();
596    while let Some(err) = cause {
597        if let Some(typed) = err.downcast_ref::<E>() {
598            return Some(typed);
599        }
600        cause = err.source();
601    }
602
603    // else
604    None
605}
606
607impl KanidmClient {
608    /// Access the underlying reqwest client that has been configured for this Kanidm server
609    pub fn client(&self) -> &reqwest::Client {
610        &self.client
611    }
612
613    pub fn get_origin(&self) -> &Url {
614        &self.origin
615    }
616
617    /// Returns the base URL of the server
618    pub fn get_url(&self) -> Url {
619        #[allow(clippy::panic)]
620        match self.addr.parse::<Url>() {
621            Ok(val) => val,
622            Err(err) => panic!("Failed to parse {} into URL: {:?}", self.addr, err),
623        }
624    }
625
626    /// Get a URL based on adding an endpoint to the base URL of the server
627    pub fn make_url(&self, endpoint: &str) -> Url {
628        #[allow(clippy::expect_used)]
629        self.get_url().join(endpoint).expect("Failed to join URL")
630    }
631
632    pub async fn set_token(&self, new_token: String) {
633        let mut tguard = self.bearer_token.write().await;
634        *tguard = Some(new_token);
635    }
636
637    pub async fn get_token(&self) -> Option<String> {
638        let tguard = self.bearer_token.read().await;
639        (*tguard).as_ref().cloned()
640    }
641
642    pub fn new_session(&self) -> Result<Self, ClientError> {
643        // Copy our builder, and then just process it.
644        let builder = self.builder.clone();
645        builder.build()
646    }
647
648    pub async fn logout(&self) -> Result<(), ClientError> {
649        match self.perform_get_request("/v1/logout").await {
650            Err(ClientError::Unauthorized)
651            | Err(ClientError::Http(reqwest::StatusCode::UNAUTHORIZED, _, _))
652            | Ok(()) => {
653                let mut tguard = self.bearer_token.write().await;
654                *tguard = None;
655                Ok(())
656            }
657            e => e,
658        }
659    }
660
661    pub fn get_token_cache_path(&self) -> String {
662        self.token_cache_path.clone()
663    }
664
665    /// Check that we're getting the right version back from the server.
666    async fn expect_version(&self, response: &reqwest::Response) {
667        let mut guard = self.check_version.lock().await;
668
669        if !*guard {
670            return;
671        }
672
673        if response.status() == StatusCode::BAD_GATEWAY
674            || response.status() == StatusCode::GATEWAY_TIMEOUT
675        {
676            // don't need to check versions when there's an intermediary reporting connectivity
677            debug!("Gateway error in response - we're going through a proxy so the version check is skipped.");
678            *guard = false;
679            return;
680        }
681
682        let ver: &str = response
683            .headers()
684            .get(KVERSION)
685            .and_then(|hv| hv.to_str().ok())
686            .unwrap_or("");
687
688        let matching = ver == EXPECT_VERSION;
689
690        if !matching {
691            warn!(server_version = ?ver, client_version = ?EXPECT_VERSION, "Mismatched client and server version - features may not work, or other unforeseen errors may occur.")
692        }
693
694        #[cfg(any(test, debug_assertions))]
695        if !matching && std::env::var("KANIDM_DEV_YOLO").is_err() {
696            eprintln!("⚠️  You're in debug/dev mode, so we're going to quit here.");
697            eprintln!("If you really must do this, set KANIDM_DEV_YOLO=1");
698            std::process::exit(1);
699        }
700
701        // Check is done once, mark as no longer needing to occur
702        *guard = false;
703    }
704
705    /// You've got the response from a reqwest and you want to turn it into a `ClientError`
706    pub fn handle_response_error(&self, error: reqwest::Error) -> ClientError {
707        if error.is_connect() {
708            if find_reqwest_error_source::<std::io::Error>(&error).is_some() {
709                // TODO: one day handle IO errors better
710                trace!("Got an IO error! {:?}", &error);
711                return ClientError::Transport(error);
712            }
713            if let Some(hyper_error) = find_reqwest_error_source::<hyper::Error>(&error) {
714                // hyper errors can be *anything* depending on the underlying client libraries
715                // ref: https://github.com/hyperium/hyper/blob/9feb70e9249d9fb99634ec96f83566e6bb3b3128/src/error.rs#L26C2-L26C2
716                if format!("{hyper_error:?}")
717                    .to_lowercase()
718                    .contains("certificate")
719                {
720                    return ClientError::UntrustedCertificate(format!("{hyper_error}"));
721                }
722            }
723        }
724        ClientError::Transport(error)
725    }
726
727    fn get_kopid_from_response(&self, response: &Response) -> String {
728        let opid = response
729            .headers()
730            .get(KOPID)
731            .and_then(|hv| hv.to_str().ok())
732            .unwrap_or("missing_kopid")
733            .to_string();
734
735        debug!("opid -> {:?}", opid);
736        opid
737    }
738
739    async fn perform_simple_post_request<R: Serialize, T: DeserializeOwned>(
740        &self,
741        dest: &str,
742        request: &R,
743    ) -> Result<T, ClientError> {
744        let response = self.client.post(self.make_url(dest)).json(request);
745
746        let response = response
747            .send()
748            .await
749            .map_err(|err| self.handle_response_error(err))?;
750
751        self.expect_version(&response).await;
752
753        let opid = self.get_kopid_from_response(&response);
754
755        self.ok_or_clienterror(&opid, response)
756            .await?
757            .json()
758            .await
759            .map_err(|e| ClientError::JsonDecode(e, opid))
760    }
761
762    async fn perform_auth_post_request<R: Serialize, T: DeserializeOwned>(
763        &self,
764        dest: &str,
765        request: R,
766    ) -> Result<T, ClientError> {
767        trace!("perform_auth_post_request connecting to {}", dest);
768
769        let auth_url = self.make_url(dest);
770
771        let response = self.client.post(auth_url.clone()).json(&request);
772
773        // If we have a bearer token, set it now.
774        let response = {
775            let tguard = self.bearer_token.read().await;
776            if let Some(token) = &(*tguard) {
777                response.bearer_auth(token)
778            } else {
779                response
780            }
781        };
782
783        // If we have a session header, set it now. This is only used when connecting
784        // to an older server.
785        let response = {
786            let sguard = self.auth_session_id.read().await;
787            if let Some(sessionid) = &(*sguard) {
788                response.header(KSESSIONID, sessionid)
789            } else {
790                response
791            }
792        };
793
794        let response = response
795            .send()
796            .await
797            .map_err(|err| self.handle_response_error(err))?;
798
799        self.expect_version(&response).await;
800
801        // If we have a sessionid header in the response, get it now.
802        let opid = self.get_kopid_from_response(&response);
803
804        let response = self.ok_or_clienterror(&opid, response).await?;
805
806        // Do we have a cookie? Our job here isn't to parse and validate the cookies, but just to
807        // know if the session id was set *in* our cookie store at all.
808        let cookie_present = self
809            .client_cookies
810            .cookies(&auth_url)
811            .map(|cookie_header| {
812                cookie_header
813                    .to_str()
814                    .ok()
815                    .map(|cookie_str| {
816                        cookie_str
817                            .split(';')
818                            .filter_map(|c| c.split_once('='))
819                            .any(|(name, _)| name == COOKIE_AUTH_SESSION_ID)
820                    })
821                    .unwrap_or_default()
822            })
823            .unwrap_or_default();
824
825        {
826            let headers = response.headers();
827
828            let mut sguard = self.auth_session_id.write().await;
829            trace!(?cookie_present);
830            if cookie_present {
831                // Clear and auth session id if present, we have the cookie instead.
832                *sguard = None;
833            } else {
834                // This situation occurs when a newer client connects to an older server
835                debug!("Auth SessionID cookie not present, falling back to header.");
836                *sguard = headers
837                    .get(KSESSIONID)
838                    .and_then(|hv| hv.to_str().ok().map(str::to_string));
839            }
840        }
841
842        response
843            .json()
844            .await
845            .map_err(|e| ClientError::JsonDecode(e, opid))
846    }
847
848    pub async fn perform_post_request<R: Serialize, T: DeserializeOwned>(
849        &self,
850        dest: &str,
851        request: R,
852    ) -> Result<T, ClientError> {
853        let response = self.client.post(self.make_url(dest)).json(&request);
854
855        let response = {
856            let tguard = self.bearer_token.read().await;
857            if let Some(token) = &(*tguard) {
858                response.bearer_auth(token)
859            } else {
860                response
861            }
862        };
863
864        let response = response
865            .send()
866            .await
867            .map_err(|err| self.handle_response_error(err))?;
868
869        self.expect_version(&response).await;
870
871        let opid = self.get_kopid_from_response(&response);
872
873        self.ok_or_clienterror(&opid, response)
874            .await?
875            .json()
876            .await
877            .map_err(|e| ClientError::JsonDecode(e, opid))
878    }
879
880    async fn perform_put_request<R: Serialize, T: DeserializeOwned>(
881        &self,
882        dest: &str,
883        request: R,
884    ) -> Result<T, ClientError> {
885        let response = self.client.put(self.make_url(dest)).json(&request);
886
887        let response = {
888            let tguard = self.bearer_token.read().await;
889            if let Some(token) = &(*tguard) {
890                response.bearer_auth(token)
891            } else {
892                response
893            }
894        };
895
896        let response = response
897            .send()
898            .await
899            .map_err(|err| self.handle_response_error(err))?;
900
901        self.expect_version(&response).await;
902
903        let opid = self.get_kopid_from_response(&response);
904
905        match response.status() {
906            reqwest::StatusCode::OK => {}
907            reqwest::StatusCode::UNPROCESSABLE_ENTITY => {
908                return Err(ClientError::InvalidRequest(format!("Something about the request content was invalid, check the server logs for further information. Operation ID: {} Error: {:?}",opid, response.text().await.ok() )))
909            }
910
911            unexpected => {
912                return Err(ClientError::Http(
913                    unexpected,
914                    response.json().await.ok(),
915                    opid,
916                ))
917            }
918        }
919
920        response
921            .json()
922            .await
923            .map_err(|e| ClientError::JsonDecode(e, opid))
924    }
925
926    /// Handles not-OK responses and turns them into ClientErrors
927    async fn ok_or_clienterror(
928        &self,
929        opid: &str,
930        response: reqwest::Response,
931    ) -> Result<reqwest::Response, ClientError> {
932        match response.status() {
933            reqwest::StatusCode::OK => Ok(response),
934            unexpected => Err(ClientError::Http(
935                unexpected,
936                response.json().await.ok(),
937                opid.to_string(),
938            )),
939        }
940    }
941
942    pub async fn perform_patch_request<R: Serialize, T: DeserializeOwned>(
943        &self,
944        dest: &str,
945        request: R,
946    ) -> Result<T, ClientError> {
947        let response = self.client.patch(self.make_url(dest)).json(&request);
948
949        let response = {
950            let tguard = self.bearer_token.read().await;
951            if let Some(token) = &(*tguard) {
952                response.bearer_auth(token)
953            } else {
954                response
955            }
956        };
957
958        let response = response
959            .send()
960            .await
961            .map_err(|err| self.handle_response_error(err))?;
962
963        self.expect_version(&response).await;
964
965        let opid = self.get_kopid_from_response(&response);
966
967        self.ok_or_clienterror(&opid, response)
968            .await?
969            .json()
970            .await
971            .map_err(|e| ClientError::JsonDecode(e, opid))
972    }
973
974    #[instrument(level = "debug", skip(self))]
975    pub async fn perform_get_request<T: DeserializeOwned>(
976        &self,
977        dest: &str,
978    ) -> Result<T, ClientError> {
979        let query: Option<()> = None;
980        self.perform_get_request_query(dest, query).await
981    }
982
983    #[instrument(level = "debug", skip(self))]
984    pub async fn perform_get_request_query<T: DeserializeOwned, Q: Serialize + Debug>(
985        &self,
986        dest: &str,
987        query: Option<Q>,
988    ) -> Result<T, ClientError> {
989        let mut dest_url = self.make_url(dest);
990
991        if let Some(query) = query {
992            let txt = serde_urlencoded::to_string(&query).map_err(ClientError::UrlEncode)?;
993
994            if !txt.is_empty() {
995                dest_url.set_query(Some(txt.as_str()));
996            }
997        }
998
999        let response = self.client.get(dest_url);
1000        let response = {
1001            let tguard = self.bearer_token.read().await;
1002            if let Some(token) = &(*tguard) {
1003                response.bearer_auth(token)
1004            } else {
1005                response
1006            }
1007        };
1008
1009        let response = response
1010            .send()
1011            .await
1012            .map_err(|err| self.handle_response_error(err))?;
1013
1014        self.expect_version(&response).await;
1015
1016        let opid = self.get_kopid_from_response(&response);
1017
1018        self.ok_or_clienterror(&opid, response)
1019            .await?
1020            .json()
1021            .await
1022            .map_err(|e| ClientError::JsonDecode(e, opid))
1023    }
1024
1025    async fn perform_delete_request(&self, dest: &str) -> Result<(), ClientError> {
1026        let response = self
1027            .client
1028            .delete(self.make_url(dest))
1029            // empty-ish body that makes the parser happy
1030            .json(&serde_json::json!([]));
1031
1032        let response = {
1033            let tguard = self.bearer_token.read().await;
1034            if let Some(token) = &(*tguard) {
1035                response.bearer_auth(token)
1036            } else {
1037                response
1038            }
1039        };
1040
1041        let response = response
1042            .send()
1043            .await
1044            .map_err(|err| self.handle_response_error(err))?;
1045
1046        self.expect_version(&response).await;
1047
1048        let opid = self.get_kopid_from_response(&response);
1049
1050        self.ok_or_clienterror(&opid, response)
1051            .await?
1052            .json()
1053            .await
1054            .map_err(|e| ClientError::JsonDecode(e, opid))
1055    }
1056
1057    async fn perform_delete_request_with_body<R: Serialize>(
1058        &self,
1059        dest: &str,
1060        request: R,
1061    ) -> Result<(), ClientError> {
1062        let response = self.client.delete(self.make_url(dest)).json(&request);
1063
1064        let response = {
1065            let tguard = self.bearer_token.read().await;
1066            if let Some(token) = &(*tguard) {
1067                response.bearer_auth(token)
1068            } else {
1069                response
1070            }
1071        };
1072
1073        let response = response
1074            .send()
1075            .await
1076            .map_err(|err| self.handle_response_error(err))?;
1077
1078        self.expect_version(&response).await;
1079
1080        let opid = self.get_kopid_from_response(&response);
1081
1082        self.ok_or_clienterror(&opid, response)
1083            .await?
1084            .json()
1085            .await
1086            .map_err(|e| ClientError::JsonDecode(e, opid))
1087    }
1088
1089    #[instrument(level = "debug", skip(self))]
1090    pub async fn auth_step_init(&self, ident: &str) -> Result<BTreeSet<AuthMech>, ClientError> {
1091        let auth_init = AuthRequest {
1092            step: AuthStep::Init2 {
1093                username: ident.to_string(),
1094                issue: AuthIssueSession::Token,
1095                privileged: false,
1096            },
1097        };
1098
1099        let r: Result<AuthResponse, _> =
1100            self.perform_auth_post_request("/v1/auth", auth_init).await;
1101        r.map(|v| {
1102            debug!("Authentication Session ID -> {:?}", v.sessionid);
1103            // Stash the session ID header.
1104            v.state
1105        })
1106        .and_then(|state| match state {
1107            AuthState::Choose(mechs) => Ok(mechs),
1108            _ => Err(ClientError::AuthenticationFailed),
1109        })
1110        .map(|mechs| mechs.into_iter().collect())
1111    }
1112
1113    #[instrument(level = "debug", skip(self))]
1114    pub async fn auth_step_begin(&self, mech: AuthMech) -> Result<Vec<AuthAllowed>, ClientError> {
1115        let auth_begin = AuthRequest {
1116            step: AuthStep::Begin(mech),
1117        };
1118
1119        let r: Result<AuthResponse, _> =
1120            self.perform_auth_post_request("/v1/auth", auth_begin).await;
1121        r.map(|v| {
1122            debug!("Authentication Session ID -> {:?}", v.sessionid);
1123            v.state
1124        })
1125        .and_then(|state| match state {
1126            AuthState::Continue(allowed) => Ok(allowed),
1127            _ => Err(ClientError::AuthenticationFailed),
1128        })
1129        // For converting to a Set
1130        // .map(|allowed| allowed.into_iter().collect())
1131    }
1132
1133    #[instrument(level = "debug", skip_all)]
1134    pub async fn auth_step_anonymous(&self) -> Result<AuthResponse, ClientError> {
1135        let auth_anon = AuthRequest {
1136            step: AuthStep::Cred(AuthCredential::Anonymous),
1137        };
1138        let r: Result<AuthResponse, _> =
1139            self.perform_auth_post_request("/v1/auth", auth_anon).await;
1140
1141        if let Ok(ar) = &r {
1142            if let AuthState::Success(token) = &ar.state {
1143                self.set_token(token.clone()).await;
1144            };
1145        };
1146        r
1147    }
1148
1149    #[instrument(level = "debug", skip_all)]
1150    pub async fn auth_step_password(&self, password: &str) -> Result<AuthResponse, ClientError> {
1151        let auth_req = AuthRequest {
1152            step: AuthStep::Cred(AuthCredential::Password(password.to_string())),
1153        };
1154        let r: Result<AuthResponse, _> = self.perform_auth_post_request("/v1/auth", auth_req).await;
1155
1156        if let Ok(ar) = &r {
1157            if let AuthState::Success(token) = &ar.state {
1158                self.set_token(token.clone()).await;
1159            };
1160        };
1161        r
1162    }
1163
1164    #[instrument(level = "debug", skip_all)]
1165    pub async fn auth_step_backup_code(
1166        &self,
1167        backup_code: &str,
1168    ) -> Result<AuthResponse, ClientError> {
1169        let auth_req = AuthRequest {
1170            step: AuthStep::Cred(AuthCredential::BackupCode(backup_code.to_string())),
1171        };
1172        let r: Result<AuthResponse, _> = self.perform_auth_post_request("/v1/auth", auth_req).await;
1173
1174        if let Ok(ar) = &r {
1175            if let AuthState::Success(token) = &ar.state {
1176                self.set_token(token.clone()).await;
1177            };
1178        };
1179        r
1180    }
1181
1182    #[instrument(level = "debug", skip_all)]
1183    pub async fn auth_step_totp(&self, totp: u32) -> Result<AuthResponse, ClientError> {
1184        let auth_req = AuthRequest {
1185            step: AuthStep::Cred(AuthCredential::Totp(totp)),
1186        };
1187        let r: Result<AuthResponse, _> = self.perform_auth_post_request("/v1/auth", auth_req).await;
1188
1189        if let Ok(ar) = &r {
1190            if let AuthState::Success(token) = &ar.state {
1191                self.set_token(token.clone()).await;
1192            };
1193        };
1194        r
1195    }
1196
1197    #[instrument(level = "debug", skip_all)]
1198    pub async fn auth_step_securitykey_complete(
1199        &self,
1200        pkc: Box<PublicKeyCredential>,
1201    ) -> Result<AuthResponse, ClientError> {
1202        let auth_req = AuthRequest {
1203            step: AuthStep::Cred(AuthCredential::SecurityKey(pkc)),
1204        };
1205        let r: Result<AuthResponse, _> = self.perform_auth_post_request("/v1/auth", auth_req).await;
1206
1207        if let Ok(ar) = &r {
1208            if let AuthState::Success(token) = &ar.state {
1209                self.set_token(token.clone()).await;
1210            };
1211        };
1212        r
1213    }
1214
1215    #[instrument(level = "debug", skip_all)]
1216    pub async fn auth_step_passkey_complete(
1217        &self,
1218        pkc: Box<PublicKeyCredential>,
1219    ) -> Result<AuthResponse, ClientError> {
1220        let auth_req = AuthRequest {
1221            step: AuthStep::Cred(AuthCredential::Passkey(pkc)),
1222        };
1223        let r: Result<AuthResponse, _> = self.perform_auth_post_request("/v1/auth", auth_req).await;
1224
1225        if let Ok(ar) = &r {
1226            if let AuthState::Success(token) = &ar.state {
1227                self.set_token(token.clone()).await;
1228            };
1229        };
1230        r
1231    }
1232
1233    #[instrument(level = "debug", skip(self))]
1234    pub async fn auth_anonymous(&self) -> Result<(), ClientError> {
1235        let mechs = match self.auth_step_init("anonymous").await {
1236            Ok(s) => s,
1237            Err(e) => return Err(e),
1238        };
1239
1240        if !mechs.contains(&AuthMech::Anonymous) {
1241            debug!("Anonymous mech not presented");
1242            return Err(ClientError::AuthenticationFailed);
1243        }
1244
1245        let _state = match self.auth_step_begin(AuthMech::Anonymous).await {
1246            Ok(s) => s,
1247            Err(e) => return Err(e),
1248        };
1249
1250        let r = self.auth_step_anonymous().await?;
1251
1252        match r.state {
1253            AuthState::Success(token) => {
1254                self.set_token(token.clone()).await;
1255                Ok(())
1256            }
1257            _ => Err(ClientError::AuthenticationFailed),
1258        }
1259    }
1260
1261    #[instrument(level = "debug", skip(self, password))]
1262    pub async fn auth_simple_password(
1263        &self,
1264        ident: &str,
1265        password: &str,
1266    ) -> Result<(), ClientError> {
1267        trace!("Init auth step");
1268        let mechs = match self.auth_step_init(ident).await {
1269            Ok(s) => s,
1270            Err(e) => return Err(e),
1271        };
1272
1273        if !mechs.contains(&AuthMech::Password) {
1274            debug!("Password mech not presented");
1275            return Err(ClientError::AuthenticationFailed);
1276        }
1277
1278        let _state = match self.auth_step_begin(AuthMech::Password).await {
1279            Ok(s) => s,
1280            Err(e) => return Err(e),
1281        };
1282
1283        let r = self.auth_step_password(password).await?;
1284
1285        match r.state {
1286            AuthState::Success(_) => Ok(()),
1287            _ => Err(ClientError::AuthenticationFailed),
1288        }
1289    }
1290
1291    #[instrument(level = "debug", skip(self, password, totp))]
1292    pub async fn auth_password_totp(
1293        &self,
1294        ident: &str,
1295        password: &str,
1296        totp: u32,
1297    ) -> Result<(), ClientError> {
1298        let mechs = match self.auth_step_init(ident).await {
1299            Ok(s) => s,
1300            Err(e) => return Err(e),
1301        };
1302
1303        if !mechs.contains(&AuthMech::PasswordTotp) {
1304            debug!("PasswordTotp mech not presented");
1305            return Err(ClientError::AuthenticationFailed);
1306        }
1307
1308        let state = match self.auth_step_begin(AuthMech::PasswordTotp).await {
1309            Ok(s) => s,
1310            Err(e) => return Err(e),
1311        };
1312
1313        if !state.contains(&AuthAllowed::Totp) {
1314            debug!("TOTP step not offered.");
1315            return Err(ClientError::AuthenticationFailed);
1316        }
1317
1318        let r = self.auth_step_totp(totp).await?;
1319
1320        // Should need to continue.
1321        match r.state {
1322            AuthState::Continue(allowed) => {
1323                if !allowed.contains(&AuthAllowed::Password) {
1324                    debug!("Password step not offered.");
1325                    return Err(ClientError::AuthenticationFailed);
1326                }
1327            }
1328            _ => {
1329                debug!("Invalid AuthState presented.");
1330                return Err(ClientError::AuthenticationFailed);
1331            }
1332        };
1333
1334        let r = self.auth_step_password(password).await?;
1335
1336        match r.state {
1337            AuthState::Success(_token) => Ok(()),
1338            _ => Err(ClientError::AuthenticationFailed),
1339        }
1340    }
1341
1342    #[instrument(level = "debug", skip(self, password, backup_code))]
1343    pub async fn auth_password_backup_code(
1344        &self,
1345        ident: &str,
1346        password: &str,
1347        backup_code: &str,
1348    ) -> Result<(), ClientError> {
1349        let mechs = match self.auth_step_init(ident).await {
1350            Ok(s) => s,
1351            Err(e) => return Err(e),
1352        };
1353
1354        if !mechs.contains(&AuthMech::PasswordBackupCode) {
1355            debug!("PasswordBackupCode mech not presented");
1356            return Err(ClientError::AuthenticationFailed);
1357        }
1358
1359        let state = match self.auth_step_begin(AuthMech::PasswordBackupCode).await {
1360            Ok(s) => s,
1361            Err(e) => return Err(e),
1362        };
1363
1364        if !state.contains(&AuthAllowed::BackupCode) {
1365            debug!("Backup Code step not offered.");
1366            return Err(ClientError::AuthenticationFailed);
1367        }
1368
1369        let r = self.auth_step_backup_code(backup_code).await?;
1370
1371        // Should need to continue.
1372        match r.state {
1373            AuthState::Continue(allowed) => {
1374                if !allowed.contains(&AuthAllowed::Password) {
1375                    debug!("Password step not offered.");
1376                    return Err(ClientError::AuthenticationFailed);
1377                }
1378            }
1379            _ => {
1380                debug!("Invalid AuthState presented.");
1381                return Err(ClientError::AuthenticationFailed);
1382            }
1383        };
1384
1385        let r = self.auth_step_password(password).await?;
1386
1387        match r.state {
1388            AuthState::Success(_token) => Ok(()),
1389            _ => Err(ClientError::AuthenticationFailed),
1390        }
1391    }
1392
1393    #[instrument(level = "debug", skip(self))]
1394    pub async fn auth_passkey_begin(
1395        &self,
1396        ident: &str,
1397    ) -> Result<RequestChallengeResponse, ClientError> {
1398        let mechs = match self.auth_step_init(ident).await {
1399            Ok(s) => s,
1400            Err(e) => return Err(e),
1401        };
1402
1403        if !mechs.contains(&AuthMech::Passkey) {
1404            debug!("Webauthn mech not presented");
1405            return Err(ClientError::AuthenticationFailed);
1406        }
1407
1408        let state = match self.auth_step_begin(AuthMech::Passkey).await {
1409            Ok(mut s) => s.pop(),
1410            Err(e) => return Err(e),
1411        };
1412
1413        // State is now a set of auth continues.
1414        match state {
1415            Some(AuthAllowed::Passkey(r)) => Ok(r),
1416            _ => Err(ClientError::AuthenticationFailed),
1417        }
1418    }
1419
1420    #[instrument(level = "debug", skip_all)]
1421    pub async fn auth_passkey_complete(
1422        &self,
1423        pkc: Box<PublicKeyCredential>,
1424    ) -> Result<(), ClientError> {
1425        let r = self.auth_step_passkey_complete(pkc).await?;
1426        match r.state {
1427            AuthState::Success(_token) => Ok(()),
1428            _ => Err(ClientError::AuthenticationFailed),
1429        }
1430    }
1431
1432    pub async fn reauth_begin(&self) -> Result<Vec<AuthAllowed>, ClientError> {
1433        let issue = AuthIssueSession::Token;
1434        let r: Result<AuthResponse, _> = self.perform_auth_post_request("/v1/reauth", issue).await;
1435
1436        r.map(|v| {
1437            debug!("Authentication Session ID -> {:?}", v.sessionid);
1438            v.state
1439        })
1440        .and_then(|state| match state {
1441            AuthState::Continue(allowed) => Ok(allowed),
1442            _ => Err(ClientError::AuthenticationFailed),
1443        })
1444    }
1445
1446    #[instrument(level = "debug", skip_all)]
1447    pub async fn reauth_simple_password(&self, password: &str) -> Result<(), ClientError> {
1448        let state = match self.reauth_begin().await {
1449            Ok(mut s) => s.pop(),
1450            Err(e) => return Err(e),
1451        };
1452
1453        match state {
1454            Some(AuthAllowed::Password) => {}
1455            _ => {
1456                return Err(ClientError::AuthenticationFailed);
1457            }
1458        };
1459
1460        let r = self.auth_step_password(password).await?;
1461
1462        match r.state {
1463            AuthState::Success(_) => Ok(()),
1464            _ => Err(ClientError::AuthenticationFailed),
1465        }
1466    }
1467
1468    #[instrument(level = "debug", skip_all)]
1469    pub async fn reauth_password_totp(&self, password: &str, totp: u32) -> Result<(), ClientError> {
1470        let state = match self.reauth_begin().await {
1471            Ok(s) => s,
1472            Err(e) => return Err(e),
1473        };
1474
1475        if !state.contains(&AuthAllowed::Totp) {
1476            debug!("TOTP step not offered.");
1477            return Err(ClientError::AuthenticationFailed);
1478        }
1479
1480        let r = self.auth_step_totp(totp).await?;
1481
1482        // Should need to continue.
1483        match r.state {
1484            AuthState::Continue(allowed) => {
1485                if !allowed.contains(&AuthAllowed::Password) {
1486                    debug!("Password step not offered.");
1487                    return Err(ClientError::AuthenticationFailed);
1488                }
1489            }
1490            _ => {
1491                debug!("Invalid AuthState presented.");
1492                return Err(ClientError::AuthenticationFailed);
1493            }
1494        };
1495
1496        let r = self.auth_step_password(password).await?;
1497
1498        match r.state {
1499            AuthState::Success(_token) => Ok(()),
1500            _ => Err(ClientError::AuthenticationFailed),
1501        }
1502    }
1503
1504    #[instrument(level = "debug", skip_all)]
1505    pub async fn reauth_passkey_begin(&self) -> Result<RequestChallengeResponse, ClientError> {
1506        let state = match self.reauth_begin().await {
1507            Ok(mut s) => s.pop(),
1508            Err(e) => return Err(e),
1509        };
1510
1511        // State is now a set of auth continues.
1512        match state {
1513            Some(AuthAllowed::Passkey(r)) => Ok(r),
1514            _ => Err(ClientError::AuthenticationFailed),
1515        }
1516    }
1517
1518    #[instrument(level = "debug", skip_all)]
1519    pub async fn reauth_passkey_complete(
1520        &self,
1521        pkc: Box<PublicKeyCredential>,
1522    ) -> Result<(), ClientError> {
1523        let r = self.auth_step_passkey_complete(pkc).await?;
1524        match r.state {
1525            AuthState::Success(_token) => Ok(()),
1526            _ => Err(ClientError::AuthenticationFailed),
1527        }
1528    }
1529
1530    pub async fn auth_valid(&self) -> Result<(), ClientError> {
1531        self.perform_get_request(V1_AUTH_VALID).await
1532    }
1533
1534    pub async fn get_public_jwk(&self, key_id: &str) -> Result<Jwk, ClientError> {
1535        self.perform_get_request(&format!("/v1/jwk/{key_id}")).await
1536    }
1537
1538    pub async fn whoami(&self) -> Result<Option<Entry>, ClientError> {
1539        let response = self.client.get(self.make_url("/v1/self"));
1540
1541        let response = {
1542            let tguard = self.bearer_token.read().await;
1543            if let Some(token) = &(*tguard) {
1544                response.bearer_auth(token)
1545            } else {
1546                response
1547            }
1548        };
1549
1550        let response = response
1551            .send()
1552            .await
1553            .map_err(|err| self.handle_response_error(err))?;
1554
1555        self.expect_version(&response).await;
1556
1557        let opid = self.get_kopid_from_response(&response);
1558        match response.status() {
1559            // Continue to process.
1560            reqwest::StatusCode::OK => {}
1561            reqwest::StatusCode::UNAUTHORIZED => return Ok(None),
1562            unexpected => {
1563                return Err(ClientError::Http(
1564                    unexpected,
1565                    response.json().await.ok(),
1566                    opid,
1567                ))
1568            }
1569        }
1570
1571        let r: WhoamiResponse = response
1572            .json()
1573            .await
1574            .map_err(|e| ClientError::JsonDecode(e, opid))?;
1575
1576        Ok(Some(r.youare))
1577    }
1578
1579    // Raw DB actions
1580    pub async fn search(&self, filter: Filter) -> Result<Vec<Entry>, ClientError> {
1581        let sr = SearchRequest { filter };
1582        let r: Result<SearchResponse, _> = self.perform_post_request("/v1/raw/search", sr).await;
1583        r.map(|v| v.entries)
1584    }
1585
1586    pub async fn create(&self, entries: Vec<Entry>) -> Result<(), ClientError> {
1587        let c = CreateRequest { entries };
1588        self.perform_post_request("/v1/raw/create", c).await
1589    }
1590
1591    pub async fn modify(&self, filter: Filter, modlist: ModifyList) -> Result<(), ClientError> {
1592        let mr = ModifyRequest { filter, modlist };
1593        self.perform_post_request("/v1/raw/modify", mr).await
1594    }
1595
1596    pub async fn delete(&self, filter: Filter) -> Result<(), ClientError> {
1597        let dr = DeleteRequest { filter };
1598        self.perform_post_request("/v1/raw/delete", dr).await
1599    }
1600
1601    // === idm actions here ==
1602
1603    // ===== GROUPS
1604    pub async fn idm_group_list(&self) -> Result<Vec<Entry>, ClientError> {
1605        self.perform_get_request("/v1/group").await
1606    }
1607
1608    pub async fn idm_group_get(&self, id: &str) -> Result<Option<Entry>, ClientError> {
1609        self.perform_get_request(&format!("/v1/group/{id}")).await
1610    }
1611
1612    pub async fn idm_group_get_members(
1613        &self,
1614        id: &str,
1615    ) -> Result<Option<Vec<String>>, ClientError> {
1616        self.perform_get_request(&format!("/v1/group/{id}/_attr/member"))
1617            .await
1618    }
1619
1620    pub async fn idm_group_create(
1621        &self,
1622        name: &str,
1623        entry_managed_by: Option<&str>,
1624    ) -> Result<(), ClientError> {
1625        let mut new_group = Entry {
1626            attrs: BTreeMap::new(),
1627        };
1628        new_group
1629            .attrs
1630            .insert(ATTR_NAME.to_string(), vec![name.to_string()]);
1631
1632        if let Some(entry_manager) = entry_managed_by {
1633            new_group.attrs.insert(
1634                ATTR_ENTRY_MANAGED_BY.to_string(),
1635                vec![entry_manager.to_string()],
1636            );
1637        }
1638
1639        self.perform_post_request("/v1/group", new_group).await
1640    }
1641
1642    pub async fn idm_group_set_entry_managed_by(
1643        &self,
1644        id: &str,
1645        entry_manager: &str,
1646    ) -> Result<(), ClientError> {
1647        let data = vec![entry_manager];
1648        self.perform_put_request(&format!("/v1/group/{id}/_attr/entry_managed_by"), data)
1649            .await
1650    }
1651
1652    pub async fn idm_group_set_members(
1653        &self,
1654        id: &str,
1655        members: &[&str],
1656    ) -> Result<(), ClientError> {
1657        let m: Vec<_> = members.iter().map(|v| (*v).to_string()).collect();
1658        self.perform_put_request(&format!("/v1/group/{id}/_attr/member"), m)
1659            .await
1660    }
1661
1662    pub async fn idm_group_add_members(
1663        &self,
1664        id: &str,
1665        members: &[&str],
1666    ) -> Result<(), ClientError> {
1667        let m: Vec<_> = members.iter().map(|v| (*v).to_string()).collect();
1668        self.perform_post_request(&format!("/v1/group/{id}/_attr/member"), m)
1669            .await
1670    }
1671
1672    pub async fn idm_group_remove_members(
1673        &self,
1674        group: &str,
1675        members: &[&str],
1676    ) -> Result<(), ClientError> {
1677        debug!(
1678            "Asked to remove members {} from {}",
1679            &members.join(","),
1680            group
1681        );
1682        self.perform_delete_request_with_body(&format!("/v1/group/{group}/_attr/member"), &members)
1683            .await
1684    }
1685
1686    pub async fn idm_group_purge_members(&self, id: &str) -> Result<(), ClientError> {
1687        self.perform_delete_request(&format!("/v1/group/{id}/_attr/member"))
1688            .await
1689    }
1690
1691    pub async fn idm_group_unix_extend(
1692        &self,
1693        id: &str,
1694        gidnumber: Option<u32>,
1695    ) -> Result<(), ClientError> {
1696        let gx = GroupUnixExtend { gidnumber };
1697        self.perform_post_request(&format!("/v1/group/{id}/_unix"), gx)
1698            .await
1699    }
1700
1701    pub async fn idm_group_unix_token_get(&self, id: &str) -> Result<UnixGroupToken, ClientError> {
1702        self.perform_get_request(&format!("/v1/group/{id}/_unix/_token"))
1703            .await
1704    }
1705
1706    pub async fn idm_group_delete(&self, id: &str) -> Result<(), ClientError> {
1707        self.perform_delete_request(&format!("/v1/group/{id}"))
1708            .await
1709    }
1710
1711    // ==== ACCOUNTS
1712
1713    pub async fn idm_account_unix_token_get(&self, id: &str) -> Result<UnixUserToken, ClientError> {
1714        self.perform_get_request(&format!("/v1/account/{id}/_unix/_token"))
1715            .await
1716    }
1717
1718    #[instrument(level = "debug", skip(self))]
1719    pub async fn idm_person_account_credential_update_send_intent(
1720        &self,
1721        id: &str,
1722        ttl: Option<u64>,
1723        email: Option<String>,
1724    ) -> Result<Uuid, ClientError> {
1725        let req = CUIntentSend { ttl, email };
1726        self.perform_post_request(
1727            &format!("/v1/person/{id}/_credential/_update_intent_send"),
1728            req,
1729        )
1730        .await
1731    }
1732
1733    // == new credential update session code.
1734    #[instrument(level = "debug", skip(self))]
1735    pub async fn idm_person_account_credential_update_intent(
1736        &self,
1737        id: &str,
1738        ttl: Option<u32>,
1739    ) -> Result<CUIntentToken, ClientError> {
1740        if let Some(ttl) = ttl {
1741            self.perform_get_request(&format!("/v1/person/{id}/_credential/_update_intent/{ttl}"))
1742                .await
1743        } else {
1744            self.perform_get_request(&format!("/v1/person/{id}/_credential/_update_intent"))
1745                .await
1746        }
1747    }
1748
1749    pub async fn idm_account_credential_update_begin(
1750        &self,
1751        id: &str,
1752    ) -> Result<(CUSessionToken, CUStatus), ClientError> {
1753        self.perform_get_request(&format!("/v1/person/{id}/_credential/_update"))
1754            .await
1755    }
1756
1757    pub async fn idm_account_credential_update_exchange(
1758        &self,
1759        intent_token: String,
1760    ) -> Result<(CUSessionToken, CUStatus), ClientError> {
1761        // We don't need to send the UAT with these, which is why we use the different path.
1762        self.perform_simple_post_request("/v1/credential/_exchange_intent", &intent_token)
1763            .await
1764    }
1765
1766    pub async fn idm_account_credential_update_status(
1767        &self,
1768        session_token: &CUSessionToken,
1769    ) -> Result<CUStatus, ClientError> {
1770        self.perform_simple_post_request("/v1/credential/_status", &session_token)
1771            .await
1772    }
1773
1774    pub async fn idm_account_credential_update_set_password(
1775        &self,
1776        session_token: &CUSessionToken,
1777        pw: &str,
1778    ) -> Result<CUStatus, ClientError> {
1779        let scr = CURequest::Password(pw.to_string());
1780        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1781            .await
1782    }
1783
1784    pub async fn idm_account_credential_update_cancel_mfareg(
1785        &self,
1786        session_token: &CUSessionToken,
1787    ) -> Result<CUStatus, ClientError> {
1788        let scr = CURequest::CancelMFAReg;
1789        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1790            .await
1791    }
1792
1793    pub async fn idm_account_credential_update_init_totp(
1794        &self,
1795        session_token: &CUSessionToken,
1796    ) -> Result<CUStatus, ClientError> {
1797        let scr = CURequest::TotpGenerate;
1798        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1799            .await
1800    }
1801
1802    pub async fn idm_account_credential_update_check_totp(
1803        &self,
1804        session_token: &CUSessionToken,
1805        totp_chal: u32,
1806        label: &str,
1807    ) -> Result<CUStatus, ClientError> {
1808        let scr = CURequest::TotpVerify(totp_chal, label.to_string());
1809        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1810            .await
1811    }
1812
1813    // TODO: add test coverage
1814    pub async fn idm_account_credential_update_accept_sha1_totp(
1815        &self,
1816        session_token: &CUSessionToken,
1817    ) -> Result<CUStatus, ClientError> {
1818        let scr = CURequest::TotpAcceptSha1;
1819        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1820            .await
1821    }
1822
1823    pub async fn idm_account_credential_update_remove_totp(
1824        &self,
1825        session_token: &CUSessionToken,
1826        label: &str,
1827    ) -> Result<CUStatus, ClientError> {
1828        let scr = CURequest::TotpRemove(label.to_string());
1829        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1830            .await
1831    }
1832
1833    // TODO: add test coverage
1834    pub async fn idm_account_credential_update_backup_codes_generate(
1835        &self,
1836        session_token: &CUSessionToken,
1837    ) -> Result<CUStatus, ClientError> {
1838        let scr = CURequest::BackupCodeGenerate;
1839        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1840            .await
1841    }
1842
1843    // TODO: add test coverage
1844    pub async fn idm_account_credential_update_primary_remove(
1845        &self,
1846        session_token: &CUSessionToken,
1847    ) -> Result<CUStatus, ClientError> {
1848        let scr = CURequest::PrimaryRemove;
1849        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1850            .await
1851    }
1852
1853    pub async fn idm_account_credential_update_set_unix_password(
1854        &self,
1855        session_token: &CUSessionToken,
1856        pw: &str,
1857    ) -> Result<CUStatus, ClientError> {
1858        let scr = CURequest::UnixPassword(pw.to_string());
1859        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1860            .await
1861    }
1862
1863    pub async fn idm_account_credential_update_unix_remove(
1864        &self,
1865        session_token: &CUSessionToken,
1866    ) -> Result<CUStatus, ClientError> {
1867        let scr = CURequest::UnixPasswordRemove;
1868        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1869            .await
1870    }
1871
1872    pub async fn idm_account_credential_update_sshkey_add(
1873        &self,
1874        session_token: &CUSessionToken,
1875        label: String,
1876        key: SshPublicKey,
1877    ) -> Result<CUStatus, ClientError> {
1878        let scr = CURequest::SshPublicKey(label, key);
1879        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1880            .await
1881    }
1882
1883    pub async fn idm_account_credential_update_sshkey_remove(
1884        &self,
1885        session_token: &CUSessionToken,
1886        label: String,
1887    ) -> Result<CUStatus, ClientError> {
1888        let scr = CURequest::SshPublicKeyRemove(label);
1889        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1890            .await
1891    }
1892
1893    pub async fn idm_account_credential_update_passkey_init(
1894        &self,
1895        session_token: &CUSessionToken,
1896    ) -> Result<CUStatus, ClientError> {
1897        let scr = CURequest::PasskeyInit;
1898        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1899            .await
1900    }
1901
1902    pub async fn idm_account_credential_update_passkey_finish(
1903        &self,
1904        session_token: &CUSessionToken,
1905        label: String,
1906        registration: RegisterPublicKeyCredential,
1907    ) -> Result<CUStatus, ClientError> {
1908        let scr = CURequest::PasskeyFinish(label, registration);
1909        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1910            .await
1911    }
1912
1913    // TODO: add test coverage
1914    pub async fn idm_account_credential_update_passkey_remove(
1915        &self,
1916        session_token: &CUSessionToken,
1917        uuid: Uuid,
1918    ) -> Result<CUStatus, ClientError> {
1919        let scr = CURequest::PasskeyRemove(uuid);
1920        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1921            .await
1922    }
1923
1924    pub async fn idm_account_credential_update_attested_passkey_init(
1925        &self,
1926        session_token: &CUSessionToken,
1927    ) -> Result<CUStatus, ClientError> {
1928        let scr = CURequest::AttestedPasskeyInit;
1929        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1930            .await
1931    }
1932
1933    pub async fn idm_account_credential_update_attested_passkey_finish(
1934        &self,
1935        session_token: &CUSessionToken,
1936        label: String,
1937        registration: RegisterPublicKeyCredential,
1938    ) -> Result<CUStatus, ClientError> {
1939        let scr = CURequest::AttestedPasskeyFinish(label, registration);
1940        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1941            .await
1942    }
1943
1944    pub async fn idm_account_credential_update_attested_passkey_remove(
1945        &self,
1946        session_token: &CUSessionToken,
1947        uuid: Uuid,
1948    ) -> Result<CUStatus, ClientError> {
1949        let scr = CURequest::AttestedPasskeyRemove(uuid);
1950        self.perform_simple_post_request("/v1/credential/_update", &(scr, &session_token))
1951            .await
1952    }
1953
1954    pub async fn idm_account_credential_update_commit(
1955        &self,
1956        session_token: &CUSessionToken,
1957    ) -> Result<(), ClientError> {
1958        self.perform_simple_post_request("/v1/credential/_commit", &session_token)
1959            .await
1960    }
1961
1962    // == radius
1963
1964    pub async fn idm_account_radius_token_get(
1965        &self,
1966        id: &str,
1967    ) -> Result<RadiusAuthToken, ClientError> {
1968        self.perform_get_request(&format!("/v1/account/{id}/_radius/_token"))
1969            .await
1970    }
1971
1972    pub async fn idm_account_unix_cred_verify(
1973        &self,
1974        id: &str,
1975        cred: &str,
1976    ) -> Result<Option<UnixUserToken>, ClientError> {
1977        let req = SingleStringRequest {
1978            value: cred.to_string(),
1979        };
1980        self.perform_post_request(&format!("/v1/account/{id}/_unix/_auth"), req)
1981            .await
1982    }
1983
1984    // == generic ssh key handlers
1985    // These return the ssh keys in their "authorized keys" form rather than a format that
1986    // shows labels and can be easily updated.
1987    pub async fn idm_account_get_ssh_pubkey(
1988        &self,
1989        id: &str,
1990        tag: &str,
1991    ) -> Result<Option<String>, ClientError> {
1992        self.perform_get_request(&format!("/v1/account/{id}/_ssh_pubkeys/{tag}"))
1993            .await
1994    }
1995
1996    pub async fn idm_account_get_ssh_pubkeys(&self, id: &str) -> Result<Vec<String>, ClientError> {
1997        self.perform_get_request(&format!("/v1/account/{id}/_ssh_pubkeys"))
1998            .await
1999    }
2000
2001    // ==== domain_info (aka domain)
2002    pub async fn idm_domain_get(&self) -> Result<Entry, ClientError> {
2003        let r: Result<Vec<Entry>, ClientError> = self.perform_get_request("/v1/domain").await;
2004        r.and_then(|mut v| v.pop().ok_or(ClientError::EmptyResponse))
2005    }
2006
2007    /// Sets the domain display name using a PUT request
2008    pub async fn idm_domain_set_display_name(
2009        &self,
2010        new_display_name: &str,
2011    ) -> Result<(), ClientError> {
2012        self.perform_put_request(
2013            &format!("/v1/domain/_attr/{ATTR_DOMAIN_DISPLAY_NAME}"),
2014            vec![new_display_name],
2015        )
2016        .await
2017    }
2018
2019    pub async fn idm_domain_set_ldap_basedn(&self, new_basedn: &str) -> Result<(), ClientError> {
2020        self.perform_put_request(
2021            &format!("/v1/domain/_attr/{ATTR_DOMAIN_LDAP_BASEDN}"),
2022            vec![new_basedn],
2023        )
2024        .await
2025    }
2026
2027    /// Sets the maximum number of LDAP attributes that can be queryed in a single operation
2028    pub async fn idm_domain_set_ldap_max_queryable_attrs(
2029        &self,
2030        max_queryable_attrs: usize,
2031    ) -> Result<(), ClientError> {
2032        self.perform_put_request(
2033            &format!("/v1/domain/_attr/{ATTR_LDAP_MAX_QUERYABLE_ATTRS}"),
2034            vec![max_queryable_attrs.to_string()],
2035        )
2036        .await
2037    }
2038
2039    pub async fn idm_set_ldap_allow_unix_password_bind(
2040        &self,
2041        enable: bool,
2042    ) -> Result<(), ClientError> {
2043        self.perform_put_request(
2044            &format!("{}{}", "/v1/domain/_attr/", ATTR_LDAP_ALLOW_UNIX_PW_BIND),
2045            vec![enable.to_string()],
2046        )
2047        .await
2048    }
2049
2050    pub async fn idm_domain_get_ssid(&self) -> Result<String, ClientError> {
2051        self.perform_get_request(&format!("/v1/domain/_attr/{ATTR_DOMAIN_SSID}"))
2052            .await
2053            .and_then(|mut r: Vec<String>|
2054                // Get the first result
2055                r.pop()
2056                .ok_or(
2057                    ClientError::EmptyResponse
2058                ))
2059    }
2060
2061    pub async fn idm_domain_set_ssid(&self, ssid: &str) -> Result<(), ClientError> {
2062        self.perform_put_request(
2063            &format!("/v1/domain/_attr/{ATTR_DOMAIN_SSID}"),
2064            vec![ssid.to_string()],
2065        )
2066        .await
2067    }
2068
2069    pub async fn idm_domain_revoke_key(&self, key_id: &str) -> Result<(), ClientError> {
2070        self.perform_put_request(
2071            &format!("/v1/domain/_attr/{ATTR_KEY_ACTION_REVOKE}"),
2072            vec![key_id.to_string()],
2073        )
2074        .await
2075    }
2076
2077    // ==== schema
2078    pub async fn idm_schema_list(&self) -> Result<Vec<Entry>, ClientError> {
2079        self.perform_get_request("/v1/schema").await
2080    }
2081
2082    pub async fn idm_schema_attributetype_list(&self) -> Result<Vec<Entry>, ClientError> {
2083        self.perform_get_request("/v1/schema/attributetype").await
2084    }
2085
2086    pub async fn idm_schema_attributetype_get(
2087        &self,
2088        id: &str,
2089    ) -> Result<Option<Entry>, ClientError> {
2090        self.perform_get_request(&format!("/v1/schema/attributetype/{id}"))
2091            .await
2092    }
2093
2094    pub async fn idm_schema_classtype_list(&self) -> Result<Vec<Entry>, ClientError> {
2095        self.perform_get_request("/v1/schema/classtype").await
2096    }
2097
2098    pub async fn idm_schema_classtype_get(&self, id: &str) -> Result<Option<Entry>, ClientError> {
2099        self.perform_get_request(&format!("/v1/schema/classtype/{id}"))
2100            .await
2101    }
2102
2103    // ==== recycle bin
2104    pub async fn recycle_bin_list(&self) -> Result<Vec<Entry>, ClientError> {
2105        self.perform_get_request("/v1/recycle_bin").await
2106    }
2107
2108    pub async fn recycle_bin_get(&self, id: &str) -> Result<Option<Entry>, ClientError> {
2109        self.perform_get_request(&format!("/v1/recycle_bin/{id}"))
2110            .await
2111    }
2112
2113    pub async fn recycle_bin_revive(&self, id: &str) -> Result<(), ClientError> {
2114        self.perform_post_request(&format!("/v1/recycle_bin/{id}/_revive"), ())
2115            .await
2116    }
2117}
2118
2119#[cfg(test)]
2120mod tests {
2121    use super::{KanidmClient, KanidmClientBuilder};
2122    use kanidm_proto::constants::CLIENT_TOKEN_CACHE;
2123    use reqwest::StatusCode;
2124    use url::Url;
2125
2126    #[tokio::test]
2127    async fn test_no_client_version_check_on_502() {
2128        let res = reqwest::Response::from(
2129            http::Response::builder()
2130                .status(StatusCode::GATEWAY_TIMEOUT)
2131                .body("")
2132                .unwrap(),
2133        );
2134        let client = KanidmClientBuilder::new()
2135            .address("http://localhost:8080".to_string())
2136            .enable_native_ca_roots(false)
2137            .build()
2138            .expect("Failed to build client");
2139        eprintln!("This should pass because we are returning 504 and shouldn't check version...");
2140        client.expect_version(&res).await;
2141
2142        let res = reqwest::Response::from(
2143            http::Response::builder()
2144                .status(StatusCode::BAD_GATEWAY)
2145                .body("")
2146                .unwrap(),
2147        );
2148        let client = KanidmClientBuilder::new()
2149            .address("http://localhost:8080".to_string())
2150            .enable_native_ca_roots(false)
2151            .build()
2152            .expect("Failed to build client");
2153        eprintln!("This should pass because we are returning 502 and shouldn't check version...");
2154        client.expect_version(&res).await;
2155    }
2156
2157    #[test]
2158    fn test_make_url() {
2159        use kanidm_proto::constants::DEFAULT_SERVER_ADDRESS;
2160        let client: KanidmClient = KanidmClientBuilder::new()
2161            .address(format!("https://{DEFAULT_SERVER_ADDRESS}"))
2162            .enable_native_ca_roots(false)
2163            .build()
2164            .unwrap();
2165        assert_eq!(
2166            client.get_url(),
2167            Url::parse(&format!("https://{DEFAULT_SERVER_ADDRESS}")).unwrap()
2168        );
2169        assert_eq!(
2170            client.make_url("/hello"),
2171            Url::parse(&format!("https://{DEFAULT_SERVER_ADDRESS}/hello")).unwrap()
2172        );
2173
2174        let client: KanidmClient = KanidmClientBuilder::new()
2175            .address(format!("https://{DEFAULT_SERVER_ADDRESS}/cheese/"))
2176            .enable_native_ca_roots(false)
2177            .build()
2178            .unwrap();
2179        assert_eq!(
2180            client.make_url("hello"),
2181            Url::parse(&format!("https://{DEFAULT_SERVER_ADDRESS}/cheese/hello")).unwrap()
2182        );
2183    }
2184
2185    #[test]
2186    fn test_kanidmclientbuilder_display() {
2187        let defaultclient = KanidmClientBuilder::default();
2188        println!("{defaultclient}");
2189        assert!(defaultclient.to_string().contains("verify_ca"));
2190
2191        let testclient = KanidmClientBuilder {
2192            address: Some("https://example.com".to_string()),
2193            verify_ca: true,
2194            verify_hostnames: true,
2195            ca: None,
2196            connect_timeout: Some(420),
2197            request_timeout: Some(69),
2198            use_system_proxies: true,
2199            token_cache_path: Some(CLIENT_TOKEN_CACHE.to_string()),
2200            disable_system_ca_store: false,
2201        };
2202        println!("testclient {testclient}");
2203        assert!(testclient.to_string().contains("verify_ca: true"));
2204        assert!(testclient.to_string().contains("verify_hostnames: true"));
2205
2206        let badness = testclient.danger_accept_invalid_hostnames(true);
2207        let badness = badness.danger_accept_invalid_certs(true);
2208        println!("badness: {badness}");
2209        assert!(badness.to_string().contains("verify_ca: false"));
2210        assert!(badness.to_string().contains("verify_hostnames: false"));
2211    }
2212}