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
#![warn(missing_docs)]
pub mod error;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_json;
use eyre::{eyre, Report, Result};
use frank_jwt::{encode, Algorithm};
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use tempfile::NamedTempFile;
use url::Url;
#[derive(PartialEq, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
enum ServiceAccountKeyType {
ServiceAccount,
}
#[derive(Debug, Deserialize)]
struct ServiceAccountKey {
r#type: ServiceAccountKeyType,
project_id: String,
private_key_id: String,
private_key: String,
client_email: String,
client_id: String,
auth_uri: Url,
token_uri: Url,
auth_provider_x509_cert_url: String,
client_x509_cert_url: String,
}
impl ServiceAccountKey {
fn private_key_as_namedtempfile(&self) -> Result<NamedTempFile> {
let mut tmpf = NamedTempFile::new()?;
tmpf.write_all(self.private_key.as_bytes())?;
Ok(tmpf)
}
}
#[derive(Debug, Serialize)]
struct JWTHeaders;
#[derive(Debug, Serialize)]
struct JWTPayload {
iss: String,
scope: Option<String>,
aud: String,
exp: u64,
iat: u64,
}
impl JWTPayload {
fn new(account: String) -> JWTPayload {
let lifetime = 60;
let now = SystemTime::now();
let secs_since_epoc = now.duration_since(UNIX_EPOCH).unwrap();
JWTPayload {
iss: account,
scope: None,
aud: "https://oauth2.googleapis.com/token".to_string(),
exp: secs_since_epoc.as_secs() + lifetime,
iat: secs_since_epoc.as_secs(),
}
}
}
#[derive(Debug, Deserialize)]
pub enum GoogleAccessTokenType {
Bearer,
}
#[derive(Debug, Deserialize)]
pub struct GoogleAccessToken {
pub access_token: String,
pub scope: Option<String>,
pub token_type: GoogleAccessTokenType,
pub expires_in: u64,
}
#[derive(Debug, Deserialize)]
pub struct GoogleIDToken {
pub id_token: String,
}
pub struct GoogleServiceAccountAuthenticator {
headers: JWTHeaders,
payload: JWTPayload,
service_account_key: ServiceAccountKey,
}
impl GoogleServiceAccountAuthenticator {
pub fn new_from_service_account_key_file(
keyfile: &Path,
) -> Result<GoogleServiceAccountAuthenticator> {
let service_account_key: ServiceAccountKey =
serde_json::from_str(&std::fs::read_to_string(keyfile)?)?;
let headers = JWTHeaders {};
let payload = JWTPayload::new(service_account_key.client_email.clone());
Ok(GoogleServiceAccountAuthenticator {
headers,
payload,
service_account_key,
})
}
fn create_token(&self) -> Result<String> {
let private_key = self.service_account_key.private_key_as_namedtempfile()?;
let token = encode(
json!(self.headers),
&private_key.path().to_path_buf(),
&json!(self.payload),
Algorithm::RS256,
)?;
private_key.close()?;
Ok(token)
}
async fn request(&mut self, scope: String) -> Result<String> {
self.payload.scope = Some(scope);
let token = self.create_token()?;
let params = [
("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
("assertion", &token),
];
let client = reqwest::Client::new();
let response = client
.post("https://oauth2.googleapis.com/token")
.form(¶ms)
.send()
.await?;
let status = response.status().as_u16();
let text = response.text().await?;
trace!("response code = {}, response text = {}", status, text);
if status == 200 {
return Ok(text);
}
if (400..500).contains(&status) {
let google_jwt_error: crate::error::GoogleJWTError = serde_json::from_str(&text)?;
let e: Report = eyre!(google_jwt_error);
return Err(e);
} else {
let e: Report = eyre!(format!(
"Unknown HTTP error code from Google authentication service received: {}",
status
));
return Err(e);
}
}
pub async fn request_access_token(&mut self) -> Result<GoogleAccessToken> {
let text = self
.request("https://www.googleapis.com/auth/prediction".to_string())
.await?;
let access_token: GoogleAccessToken = serde_json::from_str(&text)?;
Ok(access_token)
}
pub async fn request_id_token(&mut self, scope: String) -> Result<GoogleIDToken> {
let text = self.request(scope).await?;
let id_token: GoogleIDToken = serde_json::from_str(&text)?;
Ok(id_token)
}
}
#[cfg(test)]
mod tests {
use crate::{GoogleServiceAccountAuthenticator, ServiceAccountKeyType};
const KEYFILE: &str = "test-service-account.json";
const PUBFILE: &str = "test-publickey.pem";
const SCOPE: &str = "http://test.tld/scope-definition";
#[test]
fn new_service_account_from_key() {
let authenticator = GoogleServiceAccountAuthenticator::new_from_service_account_key_file(
std::path::Path::new(KEYFILE),
)
.unwrap();
assert_eq!(
authenticator.service_account_key.r#type,
ServiceAccountKeyType::ServiceAccount
);
assert_eq!(
authenticator.service_account_key.client_email,
"test-account@test-project-id.iam.gserviceaccount.com".to_string()
);
}
#[test]
fn create_token() {
use frank_jwt::{decode, Algorithm, ValidationOptions};
let mut authenticator =
GoogleServiceAccountAuthenticator::new_from_service_account_key_file(
std::path::Path::new(KEYFILE),
)
.unwrap();
authenticator.payload.scope = Some(SCOPE.to_string());
let token = authenticator.create_token().unwrap();
let (_header, payload) = decode(
&token,
&std::path::Path::new(PUBFILE).to_path_buf(),
Algorithm::RS256,
&ValidationOptions::default(),
)
.unwrap();
println!("{}", _header);
println!("{}", payload);
assert_eq!(
payload["iss"],
authenticator.service_account_key.client_email
);
assert_eq!(payload["scope"], SCOPE);
}
}