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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

//! SSO Credentials Provider
//!
//! This credentials provider enables loading credentials from `~/.aws/sso/cache`. For more information,
//! see [Using AWS SSO Credentials](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/sso-credentials.html)
//!
//! This provider is included automatically when profiles are loaded.

use crate::fs_util::{home_dir, Os};
use crate::json_credentials::{json_parse_loop, InvalidJsonCredentials};
use crate::provider_config::ProviderConfig;

use aws_sdk_sso::middleware::DefaultMiddleware as SsoMiddleware;
use aws_sdk_sso::model::RoleCredentials;
use aws_smithy_client::erase::DynConnector;
use aws_smithy_types::date_time::Format;
use aws_smithy_types::DateTime;
use aws_types::credentials::{CredentialsError, ProvideCredentials};
use aws_types::os_shim_internal::{Env, Fs};
use aws_types::region::Region;
use aws_types::{credentials, Credentials};

use std::convert::TryInto;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::io;
use std::path::PathBuf;

use ring::digest;
use zeroize::Zeroizing;

impl crate::provider_config::ProviderConfig {
    pub(crate) fn sso_client(
        &self,
    ) -> aws_smithy_client::Client<aws_smithy_client::erase::DynConnector, SsoMiddleware> {
        use crate::connector::expect_connector;
        use aws_smithy_client::http_connector::HttpSettings;

        aws_smithy_client::Builder::<(), SsoMiddleware>::new()
            .connector(expect_connector(self.connector(&HttpSettings::default())))
            .sleep_impl(self.sleep())
            .build()
    }
}

/// SSO Credentials Provider
///
/// _Note: This provider is part of the default credentials chain and is integrated with the profile-file provider._
///
/// This credentials provider will use cached SSO tokens stored in `~/.aws/sso/cache/<hash>.json`.
/// `<hash>` is computed based on the configured [`start_url`](Builder::start_url).
#[derive(Debug)]
pub struct SsoCredentialsProvider {
    fs: Fs,
    env: Env,
    sso_config: SsoConfig,
    client: aws_smithy_client::Client<DynConnector, SsoMiddleware>,
}

impl SsoCredentialsProvider {
    /// Creates a builder for [`SsoCredentialsProvider`]
    pub fn builder() -> Builder {
        Builder::new()
    }

    pub(crate) fn new(provider_config: &ProviderConfig, sso_config: SsoConfig) -> Self {
        let fs = provider_config.fs();
        let env = provider_config.env();

        SsoCredentialsProvider {
            fs,
            env,
            client: provider_config.sso_client(),
            sso_config,
        }
    }

    async fn credentials(&self) -> credentials::Result {
        load_sso_credentials(&self.sso_config, &self.client, &self.env, &self.fs).await
    }
}

impl ProvideCredentials for SsoCredentialsProvider {
    fn provide_credentials<'a>(&'a self) -> credentials::future::ProvideCredentials<'a>
    where
        Self: 'a,
    {
        credentials::future::ProvideCredentials::new(self.credentials())
    }
}

/// Builder for [`SsoCredentialsProvider`]
#[derive(Default, Debug, Clone)]
pub struct Builder {
    provider_config: Option<ProviderConfig>,
    account_id: Option<String>,
    role_name: Option<String>,
    start_url: Option<String>,
    region: Option<Region>,
}

impl Builder {
    /// Create a new builder for [`SsoCredentialsProvider`]
    pub fn new() -> Self {
        Self::default()
    }

    /// Override the configuration used for this provider
    pub fn configure(mut self, provider_config: &ProviderConfig) -> Self {
        self.provider_config = Some(provider_config.clone());
        self
    }

    /// Set the account id used for SSO
    pub fn account_id(mut self, account_id: impl Into<String>) -> Self {
        self.account_id = Some(account_id.into());
        self
    }

    /// Set the role name used for SSO
    pub fn role_name(mut self, role_name: impl Into<String>) -> Self {
        self.role_name = Some(role_name.into());
        self
    }

    /// Set the start URL used for SSO
    pub fn start_url(mut self, start_url: impl Into<String>) -> Self {
        self.start_url = Some(start_url.into());
        self
    }

    /// Set the region used for SSO
    pub fn region(mut self, region: Region) -> Self {
        self.region = Some(region);
        self
    }

    /// Construct an SsoCredentialsProvider from the builder
    ///
    /// # Panics
    /// This method will panic if the any of the following required fields are unset:
    /// - [`start_url`](Self::start_url)
    /// - [`role_name`](Self::role_name)
    /// - [`account_id`](Self::account_id)
    /// - [`region`](Self::region)
    pub fn build(self) -> SsoCredentialsProvider {
        let provider_config = self.provider_config.unwrap_or_default();
        let sso_config = SsoConfig {
            account_id: self.account_id.expect("account_id must be set"),
            role_name: self.role_name.expect("role_name must be set"),
            start_url: self.start_url.expect("start_url must be set"),
            region: self.region.expect("region must be set"),
        };
        SsoCredentialsProvider::new(&provider_config, sso_config)
    }
}

#[derive(Debug)]
pub(crate) enum LoadTokenError {
    InvalidCredentials(InvalidJsonCredentials),
    NoHomeDirectory,
    IoError { err: io::Error, path: PathBuf },
}

impl Display for LoadTokenError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            LoadTokenError::InvalidCredentials(err) => {
                write!(f, "SSO Token was invalid (expected JSON): {}", err)
            }
            LoadTokenError::NoHomeDirectory => write!(f, "Could not resolve a home directory"),
            LoadTokenError::IoError { err, path } => {
                write!(f, "failed to read `{}`: {}", path.display(), err)
            }
        }
    }
}

impl Error for LoadTokenError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            LoadTokenError::InvalidCredentials(err) => Some(err as _),
            LoadTokenError::NoHomeDirectory => None,
            LoadTokenError::IoError { err, .. } => Some(err as _),
        }
    }
}

#[derive(Debug)]
pub(crate) struct SsoConfig {
    pub(crate) account_id: String,
    pub(crate) role_name: String,
    pub(crate) start_url: String,
    pub(crate) region: Region,
}

async fn load_sso_credentials(
    sso_config: &SsoConfig,
    sso: &aws_smithy_client::Client<DynConnector, SsoMiddleware>,
    env: &Env,
    fs: &Fs,
) -> credentials::Result {
    let token = load_token(&sso_config.start_url, env, fs)
        .await
        .map_err(CredentialsError::provider_error)?;
    let config = aws_sdk_sso::Config::builder()
        .region(sso_config.region.clone())
        .build();
    let operation = aws_sdk_sso::operation::GetRoleCredentials::builder()
        .role_name(&sso_config.role_name)
        .access_token(&*token.access_token)
        .account_id(&sso_config.account_id)
        .build()
        .map_err(|err| {
            CredentialsError::unhandled(format!("could not construct SSO token input: {}", err))
        })?
        .make_operation(&config)
        .await
        .map_err(CredentialsError::unhandled)?;
    let resp = sso
        .call(operation)
        .await
        .map_err(CredentialsError::provider_error)?;
    let credentials: RoleCredentials = resp
        .role_credentials
        .ok_or_else(|| CredentialsError::unhandled("SSO did not return credentials"))?;
    let akid = credentials
        .access_key_id
        .ok_or_else(|| CredentialsError::unhandled("no access key id in response"))?;
    let secret_key = credentials
        .secret_access_key
        .ok_or_else(|| CredentialsError::unhandled("no secret key in response"))?;
    let expiration = DateTime::from_millis(credentials.expiration)
        .try_into()
        .map_err(|err| {
            CredentialsError::unhandled(format!(
                "expiration could not be converted into a system time: {}",
                err
            ))
        })?;
    Ok(Credentials::new(
        akid,
        secret_key,
        credentials.session_token,
        Some(expiration),
        "SSO",
    ))
}

/// Load the token for `start_url` from `~/.aws/sso/cache/<hashofstarturl>.json`
async fn load_token(start_url: &str, env: &Env, fs: &Fs) -> Result<SsoToken, LoadTokenError> {
    let home = home_dir(env, Os::real()).ok_or(LoadTokenError::NoHomeDirectory)?;
    let path = sso_token_path(start_url, &home);
    let data =
        Zeroizing::new(
            fs.read_to_end(&path)
                .await
                .map_err(|err| LoadTokenError::IoError {
                    err,
                    path: path.to_path_buf(),
                })?,
        );
    let token = parse_token_json(&data).map_err(LoadTokenError::InvalidCredentials)?;
    Ok(token)
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct SsoToken {
    access_token: Zeroizing<String>,
    expires_at: DateTime,
    region: Option<Region>,
}

/// Parse SSO token JSON from input
fn parse_token_json(input: &[u8]) -> Result<SsoToken, InvalidJsonCredentials> {
    /*
      Example:
      {
        "accessToken": "base64string",
        "expiresAt": "2019-11-14T04:05:45Z",
        "region": "us-west-2",
        "startUrl": "https://d-abc123.awsapps.com/start"
    }*/
    let mut acccess_token = None;
    let mut expires_at = None;
    let mut region = None;
    let mut start_url = None;
    json_parse_loop(input, |key, value| match key {
        key if key.eq_ignore_ascii_case("accessToken") => acccess_token = Some(value.to_string()),
        key if key.eq_ignore_ascii_case("expiresAt") => expires_at = Some(value),
        key if key.eq_ignore_ascii_case("region") => region = Some(value.to_string()),
        key if key.eq_ignore_ascii_case("startUrl") => start_url = Some(value.to_string()),
        _other => {} // ignored
    })?;
    let access_token =
        Zeroizing::new(acccess_token.ok_or(InvalidJsonCredentials::MissingField("accessToken"))?);
    let expires_at = expires_at.ok_or(InvalidJsonCredentials::MissingField("expiresAt"))?;
    let expires_at = DateTime::from_str(expires_at.as_ref(), Format::DateTime).map_err(|e| {
        InvalidJsonCredentials::InvalidField {
            field: "expiresAt",
            err: e.into(),
        }
    })?;
    let region = region.map(Region::new);
    Ok(SsoToken {
        access_token,
        expires_at,
        region,
    })
}

/// Determine the SSO token path for a given start_url
fn sso_token_path(start_url: &str, home: &str) -> PathBuf {
    // hex::encode returns a lowercase string
    let mut out = PathBuf::with_capacity(home.len() + "/.aws/sso/cache".len() + ".json".len() + 40);
    out.push(home);
    out.push(".aws/sso/cache");
    out.push(&hex::encode(digest::digest(
        &digest::SHA1_FOR_LEGACY_USE_ONLY,
        start_url.as_bytes(),
    )));
    out.set_extension("json");
    out
}

#[cfg(test)]
mod test {
    use crate::json_credentials::InvalidJsonCredentials;
    use crate::sso::{load_token, parse_token_json, sso_token_path, LoadTokenError, SsoToken};
    use aws_smithy_types::DateTime;
    use aws_types::os_shim_internal::{Env, Fs};
    use aws_types::region::Region;
    use zeroize::Zeroizing;

    #[test]
    fn deserialize_valid_tokens() {
        let token = br#"
        {
            "accessToken": "base64string",
            "expiresAt": "2009-02-13T23:31:30Z",
            "region": "us-west-2",
            "startUrl": "https://d-abc123.awsapps.com/start"
        }"#;
        assert_eq!(
            parse_token_json(token).expect("valid"),
            SsoToken {
                access_token: Zeroizing::new("base64string".into()),
                expires_at: DateTime::from_secs(1234567890),
                region: Some(Region::from_static("us-west-2"))
            }
        );

        let no_region = br#"{
            "accessToken": "base64string",
            "expiresAt": "2009-02-13T23:31:30Z"
        }"#;
        assert_eq!(
            parse_token_json(no_region).expect("valid"),
            SsoToken {
                access_token: Zeroizing::new("base64string".into()),
                expires_at: DateTime::from_secs(1234567890),
                region: None
            }
        );
    }

    #[test]
    fn invalid_timestamp() {
        let token = br#"
        {
            "accessToken": "base64string",
            "expiresAt": "notatimestamp",
            "region": "us-west-2",
            "startUrl": "https://d-abc123.awsapps.com/start"
        }"#;
        let err = parse_token_json(token).expect_err("invalid timestamp");
        assert!(
            format!("{}", err).contains("Invalid field in response: `expiresAt`."),
            "{}",
            err
        );
    }

    #[test]
    fn missing_fields() {
        let token = br#"
        {
            "expiresAt": "notatimestamp",
            "region": "us-west-2",
            "startUrl": "https://d-abc123.awsapps.com/start"
        }"#;
        let err = parse_token_json(token).expect_err("missing akid");
        assert!(
            matches!(err, InvalidJsonCredentials::MissingField("accessToken")),
            "incorrect error: {:?}",
            err
        );

        let token = br#"
        {
            "accessToken": "akid",
            "region": "us-west-2",
            "startUrl": "https://d-abc123.awsapps.com/start"
        }"#;
        let err = parse_token_json(token).expect_err("missing expiry");
        assert!(
            matches!(err, InvalidJsonCredentials::MissingField("expiresAt")),
            "incorrect error: {:?}",
            err
        );
    }

    #[test]
    fn determine_correct_cache_filenames() {
        assert_eq!(
            sso_token_path("https://d-92671207e4.awsapps.com/start", "/home/me").as_os_str(),
            "/home/me/.aws/sso/cache/13f9d35043871d073ab260e020f0ffde092cb14b.json"
        );
        assert_eq!(
            sso_token_path("https://d-92671207e4.awsapps.com/start", "/home/me/").as_os_str(),
            "/home/me/.aws/sso/cache/13f9d35043871d073ab260e020f0ffde092cb14b.json"
        );
    }

    #[tokio::test]
    async fn gracefully_handle_missing_files() {
        let err = load_token(
            "asdf",
            &Env::from_slice(&[("HOME", "/home")]),
            &Fs::from_slice(&[]),
        )
        .await
        .expect_err("should fail, file is missing");
        assert!(
            matches!(err, LoadTokenError::IoError { .. }),
            "should be io error, got {}",
            err
        );
    }
}