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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use std::{
path::{Path, PathBuf},
process::Command,
sync::Arc,
};
use chrono::{DateTime, Duration, Utc};
use futures::future::BoxFuture;
use http::{
header::{InvalidHeaderValue, AUTHORIZATION},
HeaderValue, Request,
};
use jsonpath_lib::select as jsonpath_select;
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::sync::{Mutex, RwLock};
use tower::{filter::AsyncPredicate, BoxError};
use crate::config::{AuthInfo, AuthProviderConfig, ExecConfig};
#[cfg(feature = "oauth")] mod oauth;
#[cfg(feature = "oauth")] pub use oauth::Error as OAuthError;
#[derive(Error, Debug)]
pub enum Error {
#[error("invalid basic auth: {0}")]
InvalidBasicAuth(#[source] InvalidHeaderValue),
#[error("invalid bearer token: {0}")]
InvalidBearerToken(#[source] InvalidHeaderValue),
#[error("tried to refresh a token and got a non-refreshable token response")]
UnrefreshableTokenResponse,
#[error("exec-plugin response did not contain a status")]
ExecPluginFailed,
#[error("malformed token expiration date: {0}")]
MalformedTokenExpirationDate(#[source] chrono::ParseError),
#[error("unable to run auth exec: {0}")]
AuthExecStart(#[source] std::io::Error),
#[error("auth exec command '{cmd}' failed with status {status}: {out:?}")]
AuthExecRun {
cmd: String,
status: std::process::ExitStatus,
out: std::process::Output,
},
#[error("failed to parse auth exec output: {0}")]
AuthExecParse(#[source] serde_json::Error),
#[error("failed exec auth: {0}")]
AuthExec(String),
#[error("failed to read token file '{1:?}': {0}")]
ReadTokenFile(#[source] std::io::Error, PathBuf),
#[error("failed to parse token-key")]
ParseTokenKey(#[source] serde_json::Error),
#[cfg(feature = "oauth")]
#[cfg_attr(docsrs, doc(cfg(feature = "oauth")))]
#[error("failed OAuth: {0}")]
OAuth(#[source] OAuthError),
}
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub(crate) enum Auth {
None,
Basic(String, SecretString),
Bearer(SecretString),
RefreshableToken(RefreshableToken),
}
#[derive(Debug)]
pub struct TokenFile {
path: PathBuf,
token: SecretString,
expires_at: DateTime<Utc>,
}
impl TokenFile {
fn new<P: AsRef<Path>>(path: P) -> Result<TokenFile, Error> {
let token = std::fs::read_to_string(&path)
.map_err(|source| Error::ReadTokenFile(source, path.as_ref().to_owned()))?;
Ok(Self {
path: path.as_ref().to_owned(),
token: SecretString::from(token),
expires_at: Utc::now() + Duration::seconds(60),
})
}
fn is_expiring(&self) -> bool {
Utc::now() + Duration::seconds(10) > self.expires_at
}
fn cached_token(&self) -> Option<&str> {
(!self.is_expiring()).then(|| self.token.expose_secret().as_ref())
}
fn token(&mut self) -> &str {
if self.is_expiring() {
if let Ok(token) = std::fs::read_to_string(&self.path) {
self.token = SecretString::from(token);
}
self.expires_at = Utc::now() + Duration::seconds(60);
}
self.token.expose_secret()
}
}
#[derive(Debug, Clone)]
pub enum RefreshableToken {
Exec(Arc<Mutex<(SecretString, DateTime<Utc>, AuthInfo)>>),
File(Arc<RwLock<TokenFile>>),
#[cfg(feature = "oauth")]
GcpOauth(Arc<Mutex<oauth::Gcp>>),
}
impl<B> AsyncPredicate<Request<B>> for RefreshableToken
where
B: http_body::Body + Send + 'static,
{
type Future = BoxFuture<'static, Result<Request<B>, BoxError>>;
type Request = Request<B>;
fn check(&mut self, mut request: Self::Request) -> Self::Future {
let refreshable = self.clone();
Box::pin(async move {
refreshable.to_header().await.map_err(Into::into).map(|value| {
request.headers_mut().insert(AUTHORIZATION, value);
request
})
})
}
}
impl RefreshableToken {
async fn to_header(&self) -> Result<HeaderValue, Error> {
match self {
RefreshableToken::Exec(data) => {
let mut locked_data = data.lock().await;
if Utc::now() + Duration::seconds(60) >= locked_data.1 {
match Auth::try_from(&locked_data.2)? {
Auth::None | Auth::Basic(_, _) | Auth::Bearer(_) => {
return Err(Error::UnrefreshableTokenResponse);
}
Auth::RefreshableToken(RefreshableToken::Exec(d)) => {
let (new_token, new_expire, new_info) = Arc::try_unwrap(d)
.expect("Unable to unwrap Arc, this is likely a programming error")
.into_inner();
locked_data.0 = new_token;
locked_data.1 = new_expire;
locked_data.2 = new_info;
}
Auth::RefreshableToken(RefreshableToken::File(_)) => unreachable!(),
#[cfg(feature = "oauth")]
Auth::RefreshableToken(RefreshableToken::GcpOauth(_)) => unreachable!(),
}
}
bearer_header(locked_data.0.expose_secret())
}
RefreshableToken::File(token_file) => {
let guard = token_file.read().await;
if let Some(header) = guard.cached_token().map(bearer_header) {
return header;
}
drop(guard);
bearer_header(token_file.write().await.token())
}
#[cfg(feature = "oauth")]
RefreshableToken::GcpOauth(data) => {
let gcp_oauth = data.lock().await;
let token = (*gcp_oauth).token().await.map_err(Error::OAuth)?;
bearer_header(&token.access_token)
}
}
}
}
fn bearer_header(token: &str) -> Result<HeaderValue, Error> {
let mut value = HeaderValue::try_from(format!("Bearer {}", token)).map_err(Error::InvalidBearerToken)?;
value.set_sensitive(true);
Ok(value)
}
impl TryFrom<&AuthInfo> for Auth {
type Error = Error;
fn try_from(auth_info: &AuthInfo) -> Result<Self, Self::Error> {
if let Some(provider) = &auth_info.auth_provider {
match token_from_provider(provider)? {
ProviderToken::Oidc(token) => {
return Ok(Self::Bearer(SecretString::from(token)));
}
ProviderToken::GcpCommand(token, Some(expiry)) => {
let mut info = auth_info.clone();
let mut provider = provider.clone();
provider.config.insert("access-token".into(), token.clone());
provider.config.insert("expiry".into(), expiry.to_rfc3339());
info.auth_provider = Some(provider);
return Ok(Self::RefreshableToken(RefreshableToken::Exec(Arc::new(
Mutex::new((SecretString::from(token), expiry, info)),
))));
}
ProviderToken::GcpCommand(token, None) => {
return Ok(Self::Bearer(SecretString::from(token)));
}
#[cfg(feature = "oauth")]
ProviderToken::GcpOauth(gcp) => {
return Ok(Self::RefreshableToken(RefreshableToken::GcpOauth(Arc::new(
Mutex::new(gcp),
))));
}
}
}
if let (Some(u), Some(p)) = (&auth_info.username, &auth_info.password) {
return Ok(Self::Basic(u.to_owned(), p.to_owned()));
}
if let Some(token) = &auth_info.token {
return Ok(Self::Bearer(token.clone()));
}
if let Some(file) = &auth_info.token_file {
return Ok(Self::RefreshableToken(RefreshableToken::File(Arc::new(
RwLock::new(TokenFile::new(file)?),
))));
}
if let Some(exec) = &auth_info.exec {
let creds = auth_exec(exec)?;
let status = creds.status.ok_or(Error::ExecPluginFailed)?;
let expiration = status
.expiration_timestamp
.map(|ts| ts.parse())
.transpose()
.map_err(Error::MalformedTokenExpirationDate)?;
match (status.token.map(SecretString::from), expiration) {
(Some(token), Some(expire)) => Ok(Self::RefreshableToken(RefreshableToken::Exec(Arc::new(
Mutex::new((token, expire, auth_info.clone())),
)))),
(Some(token), None) => Ok(Self::Bearer(token)),
_ => Ok(Self::None),
}
} else {
Ok(Self::None)
}
}
}
enum ProviderToken {
Oidc(String),
GcpCommand(String, Option<DateTime<Utc>>),
#[cfg(feature = "oauth")]
GcpOauth(oauth::Gcp),
}
fn token_from_provider(provider: &AuthProviderConfig) -> Result<ProviderToken, Error> {
match provider.name.as_ref() {
"oidc" => token_from_oidc_provider(provider),
"gcp" => token_from_gcp_provider(provider),
_ => Err(Error::AuthExec(format!(
"Authentication with provider {:} not supported",
provider.name
))),
}
}
fn token_from_oidc_provider(provider: &AuthProviderConfig) -> Result<ProviderToken, Error> {
match provider.config.get("id-token") {
Some(id_token) => Ok(ProviderToken::Oidc(id_token.clone())),
None => Err(Error::AuthExec(
"No id-token for oidc Authentication provider".into(),
)),
}
}
fn token_from_gcp_provider(provider: &AuthProviderConfig) -> Result<ProviderToken, Error> {
if let Some(id_token) = provider.config.get("id-token") {
return Ok(ProviderToken::GcpCommand(id_token.clone(), None));
}
if let Some(access_token) = provider.config.get("access-token") {
if let Some(expiry) = provider.config.get("expiry") {
let expiry_date = expiry
.parse::<DateTime<Utc>>()
.map_err(Error::MalformedTokenExpirationDate)?;
if Utc::now() + Duration::seconds(60) < expiry_date {
return Ok(ProviderToken::GcpCommand(access_token.clone(), Some(expiry_date)));
}
}
}
if let Some(cmd) = provider.config.get("cmd-path") {
let params = provider.config.get("cmd-args").cloned().unwrap_or_default();
let output = Command::new(cmd)
.args(params.trim().split(' '))
.output()
.map_err(|e| Error::AuthExec(format!("Executing {:} failed: {:?}", cmd, e)))?;
if !output.status.success() {
return Err(Error::AuthExecRun {
cmd: format!("{} {}", cmd, params),
status: output.status,
out: output,
});
}
if let Some(field) = provider.config.get("token-key") {
let json_output: serde_json::Value =
serde_json::from_slice(&output.stdout).map_err(Error::ParseTokenKey)?;
let token = extract_value(&json_output, field)?;
if let Some(field) = provider.config.get("expiry-key") {
let expiry = extract_value(&json_output, field)?;
let expiry = expiry
.parse::<DateTime<Utc>>()
.map_err(Error::MalformedTokenExpirationDate)?;
return Ok(ProviderToken::GcpCommand(token, Some(expiry)));
} else {
return Ok(ProviderToken::GcpCommand(token, None));
}
} else {
let token = std::str::from_utf8(&output.stdout)
.map_err(|e| Error::AuthExec(format!("Result is not a string {:?} ", e)))?
.to_owned();
return Ok(ProviderToken::GcpCommand(token, None));
}
}
#[cfg(feature = "oauth")]
{
Ok(ProviderToken::GcpOauth(
oauth::Gcp::default_credentials_with_scopes(provider.config.get("scopes"))
.map_err(Error::OAuth)?,
))
}
#[cfg(not(feature = "oauth"))]
{
Err(Error::AuthExec(
"Enable oauth feature to use Google Application Credentials-based token source".into(),
))
}
}
fn extract_value(json: &serde_json::Value, path: &str) -> Result<String, Error> {
let pure_path = path.trim_matches(|c| c == '"' || c == '{' || c == '}');
match jsonpath_select(json, &format!("${}", pure_path)) {
Ok(v) if !v.is_empty() => {
if let serde_json::Value::String(res) = v[0] {
Ok(res.clone())
} else {
Err(Error::AuthExec(format!(
"Target value at {:} is not a string",
pure_path
)))
}
}
Err(e) => Err(Error::AuthExec(format!("Could not extract JSON value: {:}", e))),
_ => Err(Error::AuthExec(format!("Target value {:} not found", pure_path))),
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExecCredential {
pub kind: Option<String>,
#[serde(rename = "apiVersion")]
pub api_version: Option<String>,
pub spec: Option<ExecCredentialSpec>,
pub status: Option<ExecCredentialStatus>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExecCredentialSpec {}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExecCredentialStatus {
#[serde(rename = "expirationTimestamp")]
pub expiration_timestamp: Option<String>,
pub token: Option<String>,
#[serde(rename = "clientCertificateData")]
pub client_certificate_data: Option<String>,
#[serde(rename = "clientKeyData")]
pub client_key_data: Option<String>,
}
fn auth_exec(auth: &ExecConfig) -> Result<ExecCredential, Error> {
let mut cmd = Command::new(&auth.command);
if let Some(args) = &auth.args {
cmd.args(args);
}
if let Some(env) = &auth.env {
let envs = env
.iter()
.flat_map(|env| match (env.get("name"), env.get("value")) {
(Some(name), Some(value)) => Some((name, value)),
_ => None,
});
cmd.envs(envs);
}
let out = cmd.output().map_err(Error::AuthExecStart)?;
if !out.status.success() {
return Err(Error::AuthExecRun {
cmd: format!("{:?}", cmd),
status: out.status,
out,
});
}
let creds = serde_json::from_slice(&out.stdout).map_err(Error::AuthExecParse)?;
Ok(creds)
}
#[cfg(test)]
mod test {
use crate::config::Kubeconfig;
use super::*;
#[tokio::test]
async fn exec_auth_command() -> Result<(), Error> {
let expiry = (Utc::now() + Duration::seconds(60 * 60)).to_rfc3339();
let test_file = format!(
r#"
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: XXXXXXX
server: https://36.XXX.XXX.XX
name: generic-name
contexts:
- context:
cluster: generic-name
user: generic-name
name: generic-name
current-context: generic-name
kind: Config
preferences: {{}}
users:
- name: generic-name
user:
auth-provider:
config:
cmd-args: '{{"something": "else", "credential": {{"access_token": "my_token", "token_expiry": "{expiry}"}}}}'
cmd-path: echo
expiry-key: '{{.credential.token_expiry}}'
token-key: '{{.credential.access_token}}'
name: gcp
"#,
expiry = expiry
);
let config: Kubeconfig = serde_yaml::from_str(&test_file).unwrap();
let auth_info = &config.auth_infos[0].auth_info;
match Auth::try_from(auth_info).unwrap() {
Auth::RefreshableToken(RefreshableToken::Exec(refreshable)) => {
let (token, _expire, info) = Arc::try_unwrap(refreshable).unwrap().into_inner();
assert_eq!(token.expose_secret(), &"my_token".to_owned());
let config = info.auth_provider.unwrap().config;
assert_eq!(config.get("access-token"), Some(&"my_token".to_owned()));
}
_ => unreachable!(),
}
Ok(())
}
#[test]
fn token_file() {
let file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(file.path(), "token1").unwrap();
let mut token_file = TokenFile::new(file.path()).unwrap();
assert_eq!(token_file.cached_token().unwrap(), "token1");
assert!(!token_file.is_expiring());
assert_eq!(token_file.token(), "token1");
std::fs::write(file.path(), "token2").unwrap();
assert_eq!(token_file.token(), "token1");
token_file.expires_at = Utc::now();
assert!(token_file.is_expiring());
assert_eq!(token_file.cached_token(), None);
assert_eq!(token_file.token(), "token2");
assert!(!token_file.is_expiring());
assert_eq!(token_file.cached_token().unwrap(), "token2");
}
}