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
use chrono::{DateTime, Utc};
use futures::join;
use lazy_static::lazy_static;
use percent_encoding::percent_encode;
use serde::{Deserialize, Serialize};
use std::{
cell::RefCell,
collections::HashMap,
net::{SocketAddr, ToSocketAddrs},
sync::Mutex,
};
use tink_core::{utils::wrap_err, TinkError};
use tokio::time::timeout;
const METADATA_IP_STR: &str = "169.254.169.254";
const METADATA_IP: [u8; 4] = [169, 254, 169, 254];
const METADATA_HOST_ENV: &str = "GCE_METADATA_HOST";
const USER_AGENT: &str = "tink-gcpkms/Rust";
lazy_static! {
static ref ON_GCE: Mutex<Option<bool>> = Mutex::new(None);
}
async fn on_gce() -> bool {
if let Some(v) = *ON_GCE.lock().unwrap() {
return v;
}
let result = on_gce_test().await;
*ON_GCE.lock().unwrap() = Some(result);
result
}
async fn on_gce_test() -> bool {
if let Ok(val) = std::env::var(METADATA_HOST_ENV) {
if !val.is_empty() {
return true;
}
}
let http_result = async {
let client = hyper::Client::new();
let uri = match format!("http://{}", METADATA_IP_STR).parse() {
Ok(v) => v,
Err(_) => return false,
};
let rsp = match client.get(uri).await {
Ok(v) => v,
Err(_) => return false,
};
return rsp.headers().get("Metadata-Flavor")
== Some(&http::HeaderValue::from_static("Google"));
};
let timed_http_result = async {
timeout(std::time::Duration::from_secs(2), http_result)
.await
.unwrap_or(false)
};
let dns_result = async {
if let Ok(iter) = "metadata.google.internal:80".to_socket_addrs() {
let needle = SocketAddr::from((METADATA_IP, 80));
for addr in iter {
if addr == needle {
return true;
}
}
}
false
};
let results = join!(timed_http_result, dns_result);
return results.0 || results.1;
}
async fn get_gce_metadata(name: &str) -> Result<String, TinkError> {
let host = std::env::var(METADATA_HOST_ENV).unwrap_or_else(|_e| METADATA_IP_STR.to_string());
let authority: http::uri::Authority = host
.parse()
.map_err(|e| wrap_err("failed to parse host", e))?;
let uri = hyper::Uri::builder()
.scheme("http")
.authority(authority)
.path_and_query(format!("/computeMetadata/v1/{}", name))
.build()
.map_err(|e| wrap_err("failed to build Uri", e))?;
let client = hyper::Client::new();
let req = hyper::Request::builder()
.method(http::method::Method::GET)
.uri(uri)
.header(http::header::USER_AGENT, USER_AGENT)
.header("Metadata-Flavor", "Google")
.body(hyper::Body::empty())
.map_err(|e| wrap_err("failed to build request", e))?;
let rsp = client
.request(req)
.await
.map_err(|e| wrap_err("failed to execute request", e))?;
if rsp.status() != http::StatusCode::OK {
return Err("failed HTTP request".into());
}
let bytes = hyper::body::to_bytes(rsp.into_body())
.await
.map_err(|e| wrap_err("failed to retrieve response body", e))?;
String::from_utf8(bytes.to_vec()).map_err(|e| wrap_err("failed to convert body to string", e))
}
#[derive(Deserialize)]
struct Token {
pub access_token: String,
pub expires_in: i64,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
struct AccessTokenClone {
pub value: String,
pub expires_at: Option<DateTime<Utc>>,
}
pub struct DefaultServiceAccountAuthenticator {
tokens: RefCell<HashMap<String, yup_oauth2::AccessToken>>,
}
impl DefaultServiceAccountAuthenticator {
pub async fn new() -> Result<Self, TinkError> {
if !on_gce().await {
return Err("not running on GCE".into());
}
Ok(Self {
tokens: RefCell::new(HashMap::new()),
})
}
pub async fn token(&self, scopes: &[&str]) -> Result<yup_oauth2::AccessToken, TinkError> {
let scopelist = scopes.join(",");
if let Some(token) = self.tokens.borrow().get(&scopelist) {
if !token.is_expired() {
return Ok(token.clone());
}
}
let token = self.refresh_token(&scopelist).await?;
self.tokens
.borrow_mut()
.insert(scopelist.to_string(), token.clone());
Ok(token)
}
pub async fn refresh_token(
&self,
scopelist: &str,
) -> Result<yup_oauth2::AccessToken, TinkError> {
if !on_gce().await {
return Err("not running on GCE".into());
}
let token_json = get_gce_metadata(&format!(
"instance/service-accounts/default/token?{}",
percent_encode(scopelist.as_bytes(), crate::DEFAULT_URL_ENCODE_SET),
))
.await?;
let token: Token = serde_json::from_str(&token_json)
.map_err(|e| wrap_err("failed to parse token JSON", e))?;
if token.access_token.is_empty() || token.expires_in == 0 {
return Err("invalid token contents".into());
}
let token_expiry = Utc::now()
.checked_add_signed(chrono::Duration::seconds(token.expires_in))
.ok_or_else(|| TinkError::new("failed to calculate expiry time"))?;
let token_clone = AccessTokenClone {
value: token.access_token,
expires_at: Some(token_expiry),
};
let token_json = serde_json::to_string(&token_clone)
.map_err(|e| wrap_err("failed to JSON encode", e))?;
let token: yup_oauth2::AccessToken = serde_json::from_str(&token_json)
.map_err(|e| wrap_err("failed to parse internal JSON", e))?;
Ok(token)
}
}
impl super::Authenticator for DefaultServiceAccountAuthenticator {
fn get_token(
&self,
runtime: &mut tokio::runtime::Runtime,
scopes: &[&str],
) -> Result<yup_oauth2::AccessToken, TinkError> {
runtime.block_on(self.token(scopes))
}
}