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
use base64::prelude::*;
use serde::Deserialize;
use tokio::fs;

use crate::error::Error;

const CREDENTIALS_FILE: &str = "application_default_credentials.json";

#[allow(dead_code)]
#[derive(Deserialize, Clone)]
pub struct ServiceAccountImpersonationInfo {
    pub(crate) token_lifetime_seconds: i32,
}

#[allow(dead_code)]
#[derive(Deserialize, Clone)]
pub struct ExecutableConfig {
    pub(crate) command: String,
    pub(crate) timeout_millis: Option<i32>,
    pub(crate) output_file: String,
}

#[allow(dead_code)]
#[derive(Deserialize, Clone)]
pub struct Format {
    pub(crate) tp: String,
    pub(crate) subject_token_field_name: String,
}

#[allow(dead_code)]
#[derive(Deserialize, Clone)]
pub struct CredentialSource {
    pub(crate) file: Option<String>,

    pub(crate) url: Option<String>,
    pub(crate) headers: Option<std::collections::HashMap<String, String>>,

    pub(crate) executable: Option<ExecutableConfig>,

    pub(crate) environment_id: Option<String>,
    pub(crate) region_url: Option<String>,
    pub(crate) regional_cred_verification_url: Option<String>,
    pub(crate) cred_verification_url: Option<String>,
    pub(crate) imdsv2_session_token_url: Option<String>,
    pub(crate) format: Option<Format>,
}

#[allow(dead_code)]
#[derive(Deserialize, Clone)]
pub struct CredentialsFile {
    #[serde(rename(deserialize = "type"))]
    pub tp: String,

    // Service Account fields
    pub client_email: Option<String>,
    pub private_key_id: Option<String>,
    pub private_key: Option<String>,
    pub auth_uri: Option<String>,
    pub token_uri: Option<String>,
    pub project_id: Option<String>,

    // User Credential fields
    // (These typically come from gcloud auth.)
    pub client_secret: Option<String>,
    pub client_id: Option<String>,
    pub refresh_token: Option<String>,

    // External Account fields
    pub audience: Option<String>,
    pub subject_token_type: Option<String>,
    #[serde(rename = "token_url")]
    pub token_url_external: Option<String>,
    pub token_info_url: Option<String>,
    pub service_account_impersonation_url: Option<String>,
    pub service_account_impersonation: Option<ServiceAccountImpersonationInfo>,
    pub delegates: Option<Vec<String>>,
    pub credential_source: Option<CredentialSource>,
    pub quota_project_id: Option<String>,
    pub workforce_pool_user_project: Option<String>,
}

impl CredentialsFile {
    pub async fn new() -> Result<Self, Error> {
        let credentials_json = {
            if let Ok(credentials) = Self::json_from_env().await {
                credentials
            } else {
                Self::json_from_file().await?
            }
        };

        Ok(serde_json::from_slice(credentials_json.as_slice())?)
    }

    pub async fn new_from_file(filepath: String) -> Result<Self, Error> {
        let credentials_json = fs::read(filepath).await?;
        Ok(serde_json::from_slice(credentials_json.as_slice())?)
    }

    async fn json_from_env() -> Result<Vec<u8>, ()> {
        let credentials = std::env::var("GOOGLE_APPLICATION_CREDENTIALS_JSON")
            .map_err(|_| ())
            .map(Vec::<u8>::from)?;

        if let Ok(decoded) = BASE64_STANDARD.decode(credentials.clone()) {
            Ok(decoded)
        } else {
            Ok(credentials)
        }
    }

    async fn json_from_file() -> Result<Vec<u8>, Error> {
        let path = match std::env::var("GOOGLE_APPLICATION_CREDENTIALS") {
            Ok(s) => Ok(std::path::Path::new(s.as_str()).to_path_buf()),
            Err(_e) => {
                // get well known file name
                if cfg!(target_os = "windows") {
                    let app_data = std::env::var("APPDATA")?;
                    Ok(std::path::Path::new(app_data.as_str())
                        .join("gcloud")
                        .join(CREDENTIALS_FILE))
                } else {
                    match home::home_dir() {
                        Some(s) => Ok(s.join(".config").join("gcloud").join(CREDENTIALS_FILE)),
                        None => Err(Error::NoHomeDirectoryFound),
                    }
                }
            }
        }?;

        let credentials_json = fs::read(path).await?;

        Ok(credentials_json)
    }

    pub(crate) fn try_to_private_key(&self) -> Result<jsonwebtoken::EncodingKey, Error> {
        match self.private_key.as_ref() {
            Some(key) => Ok(jsonwebtoken::EncodingKey::from_rsa_pem(key.as_bytes())?),
            None => Err(Error::NoPrivateKeyFound),
        }
    }
}