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
use std::{
    collections::HashSet,
    fmt::Display,
    process::{Command, Stdio},
    str::FromStr,
    time::Duration,
};

use chrono::{DateTime, Utc};
use keyring::Entry;
use reqwest::{blocking::Client, header::HeaderMap};
use serde::{Deserialize, Serialize};

const DEFAULT_OAUTH_SCOPES: &[&str] = &["https://www.googleapis.com/auth/cloud-platform"];

const DEFAULT_LIFETIME_SECONDS: u64 = 3600;
const IAM_API: &str = "https://iamcredentials.googleapis.com/v1";
static USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccessToken(String);

impl FromStr for AccessToken {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(s.to_string()))
    }
}

impl AsRef<str> for AccessToken {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

impl From<String> for AccessToken {
    fn from(value: String) -> Self {
        Self(value)
    }
}

#[derive(Debug)]
pub struct GcloudConfig {
    _account: String,
    access_token: AccessToken,
}

impl FromStr for GcloudConfig {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (account, access_token) = s.trim().split_once(',').expect("config-helper call failed");
        Ok(Self {
            _account: account.to_string(),
            access_token: AccessToken::from_str(access_token)
                .expect("failed to parse access token"),
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Email(String);

impl FromStr for Email {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(s.to_string()))
    }
}

impl AsRef<str> for Email {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

impl Display for Email {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Scopes(HashSet<String>);

impl FromStr for Scopes {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let scopes = s.split(',').map(|s| s.to_string()).collect();
        Ok(Self(scopes))
    }
}

impl Display for Scopes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sorted_scopes: Vec<String> = self.0.iter().map(|s| s.to_string()).collect();
        let scopes: String = sorted_scopes.join(",");
        write!(f, "{}", scopes)
    }
}
impl Default for Scopes {
    fn default() -> Self {
        let owned_scopes: HashSet<String> = DEFAULT_OAUTH_SCOPES
            .iter()
            .map(|scope| scope.to_string())
            .collect();
        Self(owned_scopes)
    }
}

impl Scopes {
    pub fn append_scopes(&self, additional_scopes: Scopes) -> Self {
        let mut scopes = Scopes::default();
        scopes.0.extend(additional_scopes.0);
        scopes
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Lifetime(u64);

// impl Serialize for Lifetime {
//     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
//     where
//         S: serde::Serializer,
//     {
//         serializer.serialize_u64(self.0.as_secs())
//     }
// }

// impl FromStr for Lifetime {
//     type Err = String;

//     fn from_str(s: &str) -> Result<Self, Self::Err> {
//         let trimmed_s = s.trim_end_matches('s');
//         let seconds: u64 = trimmed_s.parse::<u64>().expect("failed to convert number");
//         Ok(Self(Duration::from_secs(seconds)))
//     }
// }

// impl From<u64> for Lifetime {
//     fn from(value: u64) -> Self {
//         Self(Duration::from_secs(value))
//     }
// }

impl Display for Lifetime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}s", self.0)
    }
}

impl Default for Lifetime {
    fn default() -> Self {
        Self(DEFAULT_LIFETIME_SECONDS)
    }
}

pub fn get_gcloud_config() -> GcloudConfig {
    let config = Command::new("gcloud")
        .args([
            "config",
            "config-helper",
            "--format",
            "csv[no-heading](configuration.properties.core.account,credential.access_token)",
        ])
        .stderr(Stdio::inherit())
        .output()
        .expect("gcloud call failed");
    GcloudConfig::from_str(std::str::from_utf8(&config.stdout).unwrap()).unwrap()
}

#[derive(Debug, Serialize, Deserialize, Default)]
struct TokenRequest {
    lifetime: String,
    scope: Scopes,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct TokenResponse {
    access_token: AccessToken,
    expire_time: DateTime<Utc>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct StoredSecret {
    access_token: AccessToken,
    scopes: Scopes,
    expire_time: DateTime<Utc>,
}

pub fn get_access_token(
    gcloud_config: &GcloudConfig,
    service_account: &Email,
    lifetime: &Lifetime,
    scopes: &Scopes,
) -> anyhow::Result<AccessToken> {
    let stored_secret = get_token_from_keyring(service_account);
    match stored_secret {
        Ok(s) => {
            if &s.scopes != scopes {
                println!("Scopes are not equal, getting a new token!");
                let new_token =
                    get_token_from_gcloud(service_account, lifetime, scopes, gcloud_config)?;
                save_token_to_keyring(service_account, &new_token)?;
                return Ok(new_token.access_token);
            }

            if s.expire_time <= Utc::now() {
                println!("Token has expired, getting a new one!");
                let new_token =
                    get_token_from_gcloud(service_account, lifetime, scopes, gcloud_config)?;
                save_token_to_keyring(service_account, &new_token)?;
                return Ok(new_token.access_token);
            }
            return Ok(s.access_token);
        }
        Err(e) => match e {
            keyring::Error::NoEntry => {
                let new_token =
                    get_token_from_gcloud(service_account, lifetime, scopes, gcloud_config)?;
                save_token_to_keyring(service_account, &new_token)?;
                return Ok(new_token.access_token);
            }
            other_error => panic!("failed to get access token: {:?}", other_error),
        },
    }
}

fn get_token_from_gcloud(
    service_account: &Email,
    lifetime: &Lifetime,
    scopes: &Scopes,
    gcloud_config: &GcloudConfig,
) -> anyhow::Result<StoredSecret> {
    let client: Client = Client::builder()
        .user_agent(USER_AGENT)
        .timeout(Duration::from_secs(15))
        .build()?;

    let url = format!(
        "{}/projects/-/serviceAccounts/{}:generateAccessToken",
        IAM_API, service_account
    );

    let mut headers = HeaderMap::new();
    headers.insert(reqwest::header::ACCEPT, "application/json".parse()?);

    let token_request = TokenRequest {
        lifetime: format!("{}", lifetime),
        scope: scopes.clone(),
    };

    let request = client
        .post(url)
        .bearer_auth(gcloud_config.access_token.as_ref())
        .headers(headers)
        .json(&token_request);

    let response: TokenResponse = request.send()?.json()?;

    Ok(StoredSecret {
        access_token: response.access_token,
        scopes: scopes.clone(),
        expire_time: response.expire_time,
    })
}

fn get_token_from_keyring(service_account: &Email) -> Result<StoredSecret, keyring::Error> {
    let entry = Entry::new(env!("CARGO_PKG_NAME"), &service_account.0)?;
    match entry.get_password() {
        Ok(s) => {
            let stored_secret: StoredSecret =
                serde_json::from_str(&s).expect("failed to parse json from keyring");
            Ok(stored_secret)
        }
        Err(e) => Err(e),
    }
}

// fn delete_token_from_keyring(service_account: &Email) -> anyhow::Result<AccessToken> {
//     todo!()
// }

fn save_token_to_keyring(
    service_account: &Email,
    stored_secret: &StoredSecret,
) -> anyhow::Result<()> {
    println!("Saving token to OS keyring!");
    let secret_entry = serde_json::to_string(stored_secret)?;
    let entry = Entry::new(env!("CARGO_PKG_NAME"), &service_account.0)?;
    match entry.set_password(&secret_entry) {
        Ok(_) => Ok(()),
        Err(e) => Err(e.into()),
    }
}

// TODO: support delegate chains? https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken