1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use std::env;
use std::str::FromStr;

use async_recursion::async_recursion;
use compact_jwt::{JwsCompact, JwsEs256Verifier, JwsVerifier, JwtError};
use dialoguer::theme::ColorfulTheme;
use dialoguer::{Confirm, Select};
use kanidm_client::{KanidmClient, KanidmClientBuilder};
use kanidm_proto::constants::{DEFAULT_CLIENT_CONFIG_PATH, DEFAULT_CLIENT_CONFIG_PATH_HOME};
use kanidm_proto::v1::UserAuthToken;
use time::format_description::well_known::Rfc3339;
use time::OffsetDateTime;

use crate::session::read_tokens;
use crate::{CommonOpt, LoginOpt, ReauthOpt};

#[derive(Clone)]
pub enum OpType {
    Read,
    Write,
}

#[derive(Debug)]
pub enum ToClientError {
    NeedLogin(String),
    NeedReauth(String),
    Other,
}

impl CommonOpt {
    pub fn to_unauth_client(&self) -> KanidmClient {
        let config_path: String = shellexpand::tilde(DEFAULT_CLIENT_CONFIG_PATH_HOME).into_owned();

        let client_builder = KanidmClientBuilder::new()
            .read_options_from_optional_config(DEFAULT_CLIENT_CONFIG_PATH)
            .map_err(|e| {
                error!(
                    "Failed to parse config ({:?}) -- {:?}",
                    DEFAULT_CLIENT_CONFIG_PATH, e
                );
                e
            })
            .and_then(|cb| {
                cb.read_options_from_optional_config(&config_path)
                    .map_err(|e| {
                        error!("Failed to parse config ({:?}) -- {:?}", config_path, e);
                        e
                    })
            })
            .unwrap_or_else(|_e| {
                std::process::exit(1);
            });
        debug!(
            "Successfully loaded configuration, looked in {} and {} - client builder state: {:?}",
            DEFAULT_CLIENT_CONFIG_PATH, DEFAULT_CLIENT_CONFIG_PATH_HOME, &client_builder
        );

        let client_builder = match &self.addr {
            Some(a) => client_builder.address(a.to_string()),
            None => client_builder,
        };

        let ca_path: Option<&str> = self.ca_path.as_ref().and_then(|p| p.to_str());
        let client_builder = match ca_path {
            Some(p) => {
                debug!("Adding trusted CA cert {:?}", p);
                let client_builder = client_builder
                    .add_root_certificate_filepath(p)
                    .unwrap_or_else(|e| {
                        error!("Failed to add ca certificate -- {:?}", e);
                        std::process::exit(1);
                    });

                debug!(
                    "After attempting to add trusted CA cert, client builder state: {:?}",
                    client_builder
                );
                client_builder
            }
            None => client_builder,
        };

        let client_builder = match self.skip_hostname_verification {
            true => {
                warn!(
                    "Accepting invalid hostnames on the certificate for {:?}",
                    &self.addr
                );
                client_builder.danger_accept_invalid_hostnames(true)
            }
            false => client_builder,
        };

        client_builder.build().unwrap_or_else(|e| {
            error!("Failed to build client instance -- {:?}", e);
            std::process::exit(1);
        })
    }

    async fn try_to_client(&self, optype: OpType) -> Result<KanidmClient, ToClientError> {
        let client = self.to_unauth_client();
        // Read the token file.
        let tokens = match read_tokens(&client.get_token_cache_path()) {
            Ok(t) => t,
            Err(_e) => {
                error!("Error retrieving authentication token store");
                return Err(ToClientError::Other);
            }
        };

        if tokens.is_empty() {
            error!(
                "No valid authentication tokens found. Please login with the 'login' subcommand."
            );
            return Err(ToClientError::Other);
        }

        // If we have a username, use that to select tokens
        let (spn, token) = match &self.username {
            Some(filter_username) => {
                let possible_token = if filter_username.contains('@') {
                    // If there is an @, it's an spn so just get the token directly.
                    tokens
                        .get(filter_username)
                        .map(|t| (filter_username.clone(), t.clone()))
                } else {
                    // first we try to find user@hostname
                    let filter_username_with_hostname = format!(
                        "{}@{}",
                        filter_username,
                        client.get_origin().host_str().unwrap_or("localhost")
                    );
                    debug!(
                        "Looking for tokens matching {}",
                        filter_username_with_hostname
                    );

                    let mut token_refs: Vec<_> = tokens
                        .iter()
                        .filter(|(t, _)| *t == &filter_username_with_hostname)
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect();

                    if token_refs.len() == 1 {
                        // return the token
                        token_refs.pop()
                    } else {
                        // otherwise let's try the fallback
                        let filter_username = format!("{}@", filter_username);
                        // Filter for tokens that match the pattern
                        let mut token_refs: Vec<_> = tokens
                            .into_iter()
                            .filter(|(t, _)| t.starts_with(&filter_username))
                            .collect();

                        match token_refs.len() {
                            0 => None,
                            1 => token_refs.pop(),
                            _ => {
                                error!("Multiple authentication tokens found for {}. Please specify the full spn to proceed", filter_username);
                                return Err(ToClientError::Other);
                            }
                        }
                    }
                };

                // Is it in the store?
                match possible_token {
                    Some(t) => t,
                    None => {
                        error!(
                            "No valid authentication tokens found for {}.",
                            filter_username
                        );
                        return Err(ToClientError::NeedLogin(filter_username.clone()));
                    }
                }
            }
            None => {
                if tokens.len() == 1 {
                    #[allow(clippy::expect_used)]
                    let (f_uname, f_token) = tokens.iter().next().expect("Memory Corruption");
                    // else pick the first token
                    debug!("Using cached token for name {}", f_uname);
                    (f_uname.clone(), f_token.clone())
                } else {
                    // Unable to automatically select the user because multiple tokens exist
                    // so we'll prompt the user to select one
                    match prompt_for_username_get_values(&client.get_token_cache_path()) {
                        Ok(tuple) => tuple,
                        Err(msg) => {
                            error!("Error: {}", msg);
                            std::process::exit(1);
                        }
                    }
                }
            }
        };

        let jwsc = match JwsCompact::from_str(&token) {
            Ok(jwtu) => jwtu,
            Err(e) => {
                error!("Unable to parse token - {:?}", e);
                return Err(ToClientError::Other);
            }
        };

        // Is the token (probably) valid?
        let jws_verifier = if let Some(pub_jwk) = jwsc.get_jwk_pubkey() {
            match JwsEs256Verifier::try_from(pub_jwk) {
                Ok(verifier) => verifier,
                Err(err) => {
                    error!(?err, "Unable to configure jws verifier");
                    return Err(ToClientError::Other);
                }
            }
        } else {
            error!("Unable to access token public key");
            return Err(ToClientError::Other);
        };

        match jws_verifier.verify(&jwsc).and_then(|jws| {
            jws.from_json::<UserAuthToken>().map_err(|serde_err| {
                error!(?serde_err);
                JwtError::InvalidJwt
            })
        }) {
            Ok(uat) => {
                let now_utc = time::OffsetDateTime::now_utc();
                if let Some(exp) = uat.expiry {
                    if now_utc >= exp {
                        error!(
                            "Session has expired for {} - you may need to login again.",
                            uat.spn
                        );
                        return Err(ToClientError::NeedLogin(spn));
                    }
                }

                // Check what we are doing based on op.
                match optype {
                    OpType::Read => {}
                    OpType::Write => {
                        if !uat.purpose_readwrite_active(now_utc + time::Duration::new(20, 0)) {
                            error!(
                                "Privileges have expired for {} - you need to re-authenticate again.",
                                uat.spn
                            );
                            return Err(ToClientError::NeedReauth(spn));
                        }
                    }
                }
            }
            Err(e) => {
                error!("Unable to read token for requested user - you may need to login again.");
                debug!(?e, "JWT Error");
                return Err(ToClientError::NeedLogin(spn));
            }
        };

        // Set it into the client
        client.set_token(token).await;

        Ok(client)
    }

    #[async_recursion]
    pub async fn to_client(&self, optype: OpType) -> KanidmClient {
        match self.try_to_client(optype.clone()).await {
            Ok(c) => c,
            Err(e) => {
                match e {
                    ToClientError::NeedLogin(username) => {
                        if !Confirm::new()
                            .with_prompt("Would you like to login again?")
                            .default(true)
                            .interact()
                            .expect("Failed to interact with interactive session")
                        {
                            std::process::exit(1);
                        }
                        let mut copt = self.clone();
                        copt.username = Some(username);
                        let login_opt = LoginOpt {
                            copt,
                            password: env::var("KANIDM_PASSWORD").ok(),
                        };
                        login_opt.exec().await;
                        // we still use `to_client` instead of `try_to_client` because we may need to prompt user to re-auth again.
                        // since reauth_opt will call `to_client`, this function is recursive anyway.
                        // we use copt since it's username is updated.
                        return login_opt.copt.to_client(optype).await;
                    }
                    ToClientError::NeedReauth(username) => {
                        if !Confirm::new()
                            .with_prompt("Would you like to re-authenticate?")
                            .default(true)
                            .interact()
                            .expect("Failed to interact with interactive session")
                        {
                            std::process::exit(1);
                        }
                        let mut copt = self.clone();
                        copt.username = Some(username);
                        let reauth_opt = ReauthOpt { copt };
                        // calls `to_client` recursively
                        // but should not goes into `NeedLogin` branch again
                        reauth_opt.exec().await;
                        if let Ok(c) = reauth_opt.copt.try_to_client(optype).await {
                            return c;
                        }
                    }
                    ToClientError::Other => {
                        std::process::exit(1);
                    }
                }
                std::process::exit(1);
            }
        }
    }
}

/// This parses the token store and prompts the user to select their username, returns the username/token as a tuple of Strings
///
/// Used to reduce duplication in implementing [prompt_for_username_get_username] and `prompt_for_username_get_token`
pub fn prompt_for_username_get_values(token_cache_path: &str) -> Result<(String, String), String> {
    let tokens = match read_tokens(token_cache_path) {
        Ok(value) => value,
        _ => return Err("Error retrieving authentication token store".to_string()),
    };
    if tokens.is_empty() {
        error!("No tokens in store, quitting!");
        std::process::exit(1);
    }
    let mut options = Vec::new();
    for option in tokens.iter() {
        options.push(String::from(option.0));
    }
    let user_select = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("Multiple authentication tokens exist. Please select one")
        .default(0)
        .items(&options)
        .interact();
    let selection = match user_select {
        Err(error) => {
            error!("Failed to handle user input: {:?}", error);
            std::process::exit(1);
        }
        Ok(value) => value,
    };
    debug!("Index of the chosen menu item: {:?}", selection);

    match tokens.iter().nth(selection) {
        Some(value) => {
            let (f_uname, f_token) = value;
            debug!("Using cached token for name {}", f_uname);
            debug!("Cached token: {}", f_token);
            Ok((f_uname.to_string(), f_token.to_string()))
        }
        None => {
            error!("Memory corruption trying to read token store, quitting!");
            std::process::exit(1);
        }
    }
}

/// This parses the token store and prompts the user to select their username, returns the username as a String
///
/// Powered by [prompt_for_username_get_values]
pub fn prompt_for_username_get_username(token_cache_path: &str) -> Result<String, String> {
    match prompt_for_username_get_values(token_cache_path) {
        Ok(value) => {
            let (f_user, _) = value;
            Ok(f_user)
        }
        Err(err) => Err(err),
    }
}

/*
/// This parses the token store and prompts the user to select their username, returns the token as a String
///
/// Powered by [prompt_for_username_get_values]
pub fn prompt_for_username_get_token() -> Result<String, String> {
    match prompt_for_username_get_values() {
        Ok(value) => {
            let (_, f_token) = value;
            Ok(f_token)
        }
        Err(err) => Err(err),
    }
}
*/

/// This parses the input for the person/service-account expire-at CLI commands
///
/// If it fails, return error, if it needs to *clear* the result, return Ok(None),
/// otherwise return Ok(Some(String)) which is the new value to set.
pub(crate) fn try_expire_at_from_string(input: &str) -> Result<Option<String>, ()> {
    match input {
        "any" | "never" | "clear" => Ok(None),
        "now" => match OffsetDateTime::now_utc().format(&Rfc3339) {
            Ok(s) => Ok(Some(s)),
            Err(e) => {
                error!(err = ?e, "Unable to format current time to rfc3339");
                Err(())
            }
        },
        "epoch" => match OffsetDateTime::UNIX_EPOCH.format(&Rfc3339) {
            Ok(val) => Ok(Some(val)),
            Err(err) => {
                error!("Failed to format epoch timestamp as RFC3339: {:?}", err);
                Err(())
            }
        },
        _ => {
            // fall back to parsing it as a date
            match OffsetDateTime::parse(input, &Rfc3339) {
                Ok(_) => Ok(Some(input.to_string())),
                Err(err) => {
                    error!("Failed to parse supplied timestamp: {:?}", err);
                    Err(())
                }
            }
        }
    }
}