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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! OpenStack AuthToken based authorization (X-Auth-Token)

use std::fmt;
use std::fmt::Debug;
use std::str::FromStr;

use http::{HeaderMap, HeaderName, HeaderValue};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{debug, error, trace};

use crate::api::identity::v3::auth::token::create as token_v3;
use crate::api::identity::v3::auth::token::get as token_v3_info;
use crate::api::RestEndpoint;
use crate::auth::{
    authtoken_scope, v3applicationcredential, v3password, v3token, v3totp, v3websso, AuthState,
};
use crate::config;
use crate::types::identity::v3::{AuthReceiptResponse, AuthResponse};

pub use crate::auth::authtoken::authtoken_scope::AuthTokenScope;

/// AuthToken (X-Auth-Token) based auth errors
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum AuthTokenError {
    /// Header error
    #[error("header value error: {}", source)]
    HeaderValue {
        #[from]
        source: http::header::InvalidHeaderValue,
    },

    /// Unsupported identity method
    #[error(
        "AuthType `{}` is not a supported type for authenticating towards the cloud",
        auth_type
    )]
    IdentityMethod { auth_type: String },

    /// Unsupported identity method in sync mode
    #[error(
        "AuthType `{}` is not a supported type for authenticating towards the cloud with sync interface",
        auth_type
    )]
    IdentityMethodSync { auth_type: String },

    /// Auth data is missing
    #[error("Auth data is missing")]
    MissingAuthData,

    /// auth_url is missing
    #[error("Auth URL is missing")]
    MissingAuthUrl,

    /// `Identity` request part build error
    #[error("Cannot construct identity auth information from config: {}", source)]
    AuthRequestIdentity {
        /// The error source
        #[from]
        source: token_v3::IdentityBuilderError,
    },

    /// `Auth` request part build error
    #[error("error preparing auth request: {}", source)]
    AuthRequestAuth {
        /// The error source
        #[from]
        source: token_v3::AuthBuilderError,
    },

    /// Auth request build error
    #[error("error preparing auth request: {}", source)]
    AuthRequest {
        /// The error source
        #[from]
        source: token_v3::RequestBuilderError,
    },

    /// Token `Info` request build error
    #[error("error preparing token info request: {}", source)]
    InfoRequest {
        /// The error source
        #[from]
        source: token_v3_info::RequestBuilderError,
    },

    /// Token Scope error
    #[error("Scope error: {}", source)]
    Scope {
        /// The error source
        #[from]
        source: authtoken_scope::AuthTokenScopeError,
    },

    /// ApplicationCredentials Identity error
    #[error("ApplicationCredential authentication error: {}", source)]
    ApplicationCredential {
        /// The error source
        #[from]
        source: v3applicationcredential::ApplicationCredentialError,
    },

    /// Password Identity error
    #[error("Password based authentication error: {}", source)]
    Password {
        /// The error source
        #[from]
        source: v3password::PasswordError,
    },

    /// Token Identity error
    #[error("Token based authentication error: {}", source)]
    Token {
        /// The error source
        #[from]
        source: v3token::TokenError,
    },

    /// TOTP Idetinty error
    #[error("Password based authentication error: {}", source)]
    Totp {
        /// The error source
        #[from]
        source: v3totp::TotpError,
    },

    /// WebSSO Identity error
    #[error("SSO based authentication error: {}", source)]
    WebSso {
        /// The error source
        #[from]
        source: v3websso::WebSsoError,
    },
}

type AuthResult<T> = Result<T, AuthTokenError>;

/// OpenStack AuthToken authorization structure
#[derive(Clone, Default, Deserialize, Serialize)]
pub struct AuthToken {
    /// Token itself
    pub(crate) token: String,
    /// Auth info reported by the server
    pub(crate) auth_info: Option<AuthResponse>,
}

impl Debug for AuthToken {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Auth")
            .field("data", &self.auth_info)
            .finish()
    }
}

impl AuthToken {
    /// Adds X-Auth-Token header to a request headers.
    ///
    /// Returns an error if the token string cannot be parsed as a header value.
    pub fn set_header<'a>(
        &self,
        headers: &'a mut HeaderMap<HeaderValue>,
    ) -> AuthResult<&'a mut HeaderMap<HeaderValue>> {
        let mut token_header_value = HeaderValue::from_str(&self.token.clone())?;
        token_header_value.set_sensitive(true);
        headers.insert("X-Auth-Token", token_header_value);

        Ok(headers)
    }

    /// Detect authentication validity (valid/expired/unset)
    pub fn get_state(&self) -> AuthState {
        match &self.auth_info {
            Some(data) => {
                if data.token.expires_at <= chrono::offset::Local::now() {
                    AuthState::Expired
                } else {
                    AuthState::Valid
                }
            }
            None => AuthState::Unset,
        }
    }

    /// Get Token scope information
    pub fn get_scope(&self) -> AuthTokenScope {
        match &self.auth_info {
            Some(ref data) => AuthTokenScope::from(data),
            _ => AuthTokenScope::Unscoped,
        }
    }
}

/// Supported AuthTypes
#[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
#[allow(clippy::enum_variant_names)]
pub enum AuthType {
    /// v3 Application Credentials
    V3ApplicationCredential,
    /// v3 Password
    V3Password,
    /// v3 Token
    V3Token,
    /// TOTP
    V3Totp,
    /// v3multifactor
    V3Multifactor,
    /// WebSSO
    V3WebSso,
}

impl FromStr for AuthType {
    type Err = AuthTokenError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "v3applicationcredential" | "applicationcredential" => {
                Ok(Self::V3ApplicationCredential)
            }
            "v3password" | "password" => Ok(Self::V3Password),
            "v3token" | "token" => Ok(Self::V3Token),
            "v3totp" => Ok(Self::V3Totp),
            "v3multifactor" => Ok(Self::V3Multifactor),
            "v3websso" => Ok(Self::V3WebSso),
            other => Err(Self::Err::IdentityMethod {
                auth_type: other.to_string(),
            }),
        }
    }
}

impl AuthType {
    /// Get the auth_type of the cloud connection
    pub fn from_cloud_config(config: &config::CloudConfig) -> Result<Self, AuthTokenError> {
        if let Some(auth_type) = &config.auth_type {
            Self::from_str(auth_type)
        } else {
            Ok(Self::V3Password)
        }
    }

    /// Return String representation of the AuthType
    pub fn as_str(self) -> &'static str {
        match self {
            Self::V3ApplicationCredential => "v3applicationcredential",
            Self::V3Password => "v3password",
            Self::V3Token => "v3token",
            Self::V3Multifactor => "v3multifactor",
            Self::V3Totp => "v3totp",
            Self::V3WebSso => "v3websso",
        }
    }
}

/// Fill identity part of the v3 token auth builder using configured auth type data
fn process_auth_type(
    identity_builder: &mut token_v3::IdentityBuilder<'_>,
    auth_data: &config::Auth,
    interactive: bool,
    auth_type: &AuthType,
) -> Result<(), AuthTokenError> {
    match auth_type {
        AuthType::V3ApplicationCredential => {
            v3applicationcredential::fill_identity(identity_builder, auth_data)?;
        }
        AuthType::V3Password => {
            v3password::fill_identity(identity_builder, auth_data, interactive)?;
        }
        AuthType::V3Token => {
            v3token::fill_identity(identity_builder, auth_data, interactive)?;
        }
        AuthType::V3Totp => {
            v3totp::fill_identity(identity_builder, auth_data, interactive)?;
        }
        other => {
            return Err(AuthTokenError::IdentityMethod {
                auth_type: other.as_str().to_string(),
            });
        }
    };
    Ok(())
}

/// Prepare Token endpoint filling identity data from `CloudConfig`
pub(crate) fn build_identity_data_from_config<'a>(
    config: &config::CloudConfig,
    interactive: bool,
) -> Result<token_v3::Identity<'a>, AuthTokenError> {
    let auth = config.auth.clone().ok_or(AuthTokenError::MissingAuthData)?;
    let auth_type = AuthType::from_cloud_config(config)?;
    let mut identity_builder = token_v3::IdentityBuilder::default();
    match auth_type {
        AuthType::V3Multifactor => {
            let mut methods: Vec<token_v3::Methods> = Vec::new();
            for auth_method in config
                .auth_methods
                .as_ref()
                .expect("`auth_methods` is an array of string when auth_type=`multifactor`")
            {
                let method_type = AuthType::from_str(auth_method)?;
                process_auth_type(&mut identity_builder, &auth, interactive, &method_type)?;
                // process_auth_type resets methods so we need to recover it
                match method_type {
                    AuthType::V3Password => {
                        methods.push(token_v3::Methods::Password);
                    }
                    AuthType::V3Token => {
                        methods.push(token_v3::Methods::Token);
                    }
                    AuthType::V3Totp => {
                        methods.push(token_v3::Methods::Totp);
                    }
                    _other => {}
                };
            }

            identity_builder.methods(methods);
        }
        other => {
            process_auth_type(&mut identity_builder, &auth, interactive, &other)?;
        }
    };
    Ok(identity_builder.build()?)
}

/// Build Auth request from `Identity` and `AuthScope`
pub(crate) fn build_auth_request_with_identity_and_scope<'a>(
    auth: &token_v3::Identity<'a>,
    scope: &AuthTokenScope,
) -> Result<token_v3::Request<'a>, AuthTokenError> {
    let mut auth_request_data = token_v3::AuthBuilder::default();
    auth_request_data.identity(auth.clone());
    match scope {
        // For no scope we should not fill anything
        AuthTokenScope::Unscoped => {}
        _ => {
            if let Ok(scope_data) = token_v3::Scope::try_from(scope) {
                auth_request_data.scope(scope_data);
            }
        }
    }

    Ok(token_v3::RequestBuilder::default()
        .auth(auth_request_data.build()?)
        .build()?)
}

/// Build Auth request from `AuthToken` and `AuthScope
pub(crate) fn build_reauth_request<'a>(
    auth: &AuthToken,
    scope: &AuthTokenScope,
) -> Result<token_v3::Request<'a>, AuthTokenError> {
    let identity_data = token_v3::Identity::try_from(auth)?;
    let mut auth_request_data = token_v3::AuthBuilder::default();
    auth_request_data.identity(identity_data);
    match scope {
        // For no scope we should not fill anything
        AuthTokenScope::Unscoped => {}
        _ => {
            if let Ok(scope_data) = token_v3::Scope::try_from(scope) {
                auth_request_data.scope(scope_data);
            }
        }
    }

    Ok(token_v3::RequestBuilder::default()
        .auth(auth_request_data.build()?)
        .build()?)
}

/// Build Auth request from `Receipt`
pub(crate) fn build_auth_request_from_receipt<'a>(
    config: &config::CloudConfig,
    receipt_header: HeaderValue,
    receipt_data: &AuthReceiptResponse,
    scope: &AuthTokenScope,
    interactive: bool,
) -> Result<impl RestEndpoint + 'a, AuthTokenError> {
    let mut identity_builder = token_v3::IdentityBuilder::default();
    let auth = config.auth.clone().ok_or(AuthTokenError::MissingAuthData)?;
    // Check required_auth_methods rules
    // Note: Keystone returns list of lists (as set of different rules)
    debug!(
        "Server requests additional authentication with one of: {:?}",
        &receipt_data.required_auth_methods
    );
    for auth_rule in &receipt_data.required_auth_methods {
        for required_method in auth_rule {
            if !receipt_data
                .receipt
                .methods
                .iter()
                .any(|x| x == required_method)
            {
                trace!("Adding {:?} auth data", required_method);
                process_auth_type(
                    &mut identity_builder,
                    &auth,
                    interactive,
                    &AuthType::from_str(required_method)?,
                )?;
            }
        }
    }

    let mut auth_request_data = token_v3::AuthBuilder::default();
    auth_request_data.identity(identity_builder.build()?);

    if let Ok(scope_data) = token_v3::Scope::try_from(scope) {
        auth_request_data.scope(scope_data);
    }

    Ok(token_v3::RequestBuilder::default()
        .auth(auth_request_data.build()?)
        .headers(
            [(
                Some(HeaderName::from_static("openstack-auth-receipt")),
                receipt_header,
            )]
            .iter()
            .cloned(),
        )
        .build()?)
}

/// Prepare Endpoint for token info
pub(crate) fn build_token_info_endpoint<S: AsRef<str>>(
    subject_token: S,
) -> Result<token_v3_info::Request, AuthTokenError> {
    Ok(token_v3_info::RequestBuilder::default()
        .headers(
            [(
                Some(HeaderName::from_static("x-subject-token")),
                HeaderValue::from_str(subject_token.as_ref()).expect("Valid string"),
            )]
            .into_iter(),
        )
        .build()?)
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    use crate::config;

    #[test]
    fn test_config_into_auth_password() -> Result<(), &'static str> {
        let config = config::CloudConfig {
            auth: Some(config::Auth {
                password: Some("pwd".into()),
                username: Some("un".into()),
                user_id: Some("ui".into()),
                user_domain_name: Some("udn".into()),
                user_domain_id: Some("udi".into()),
                ..Default::default()
            }),
            auth_type: Some("password".into()),
            ..Default::default()
        };

        let auth_data = build_identity_data_from_config(&config, false).unwrap();
        assert_eq!(
            json!({
              "methods": ["password"],
              "password": {
                "user": {
                  "name": "un",
                  "id": "ui",
                  "password": "pwd",
                  "domain": {
                    "id": "udi",
                    "name": "udn"
                  }
                }
              }
            }),
            serde_json::to_value(auth_data).unwrap()
        );
        Ok(())
    }

    #[test]
    fn test_config_into_auth_token() -> Result<(), &'static str> {
        let config = config::CloudConfig {
            auth: Some(config::Auth {
                token: Some("token".into()),
                user_domain_name: Some("udn".into()),
                user_domain_id: Some("udi".into()),
                ..Default::default()
            }),
            auth_type: Some("token".into()),
            ..Default::default()
        };

        let auth_data = build_identity_data_from_config(&config, false).unwrap();
        assert_eq!(
            json!({
              "methods": ["token"],
                "token": {
                  "id": "token",
              }
            }),
            serde_json::to_value(auth_data).unwrap()
        );
        Ok(())
    }
}