Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding google cloud auth per exec #328

Merged
merged 4 commits into from
Oct 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions kube/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Inflector = "0.11.4"
tokio = { version = "0.2.22", features = ["time", "signal", "sync"] }
static_assertions = "1.1.0"
kube-derive = { path = "../kube-derive", version = "^0.42.0", optional = true }
jsonpath_lib = "0.2.5"

[dependencies.reqwest]
version = "0.10.7"
Expand Down
96 changes: 96 additions & 0 deletions kube/src/config/file_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use crate::{config::utils, error::ConfigError, oauth2, Result};

use serde::{Deserialize, Serialize};

use jsonpath_lib::select as jsonpath_select;

/// [`Kubeconfig`] represents information on how to connect to a remote Kubernetes cluster
/// that is normally stored in `~/.kube/config`
///
Expand Down Expand Up @@ -179,6 +181,58 @@ impl AuthInfo {
if let Some(id_token) = provider.config.get("id-token") {
self.token = Some(id_token.clone());
}

if self.token.is_none() {
if let Some(cmd) = provider.config.get("cmd-path") {
let params = provider.config.get("cmd-args").cloned().unwrap_or_default();

let output = std::process::Command::new(cmd)
.args(params.trim().split(" "))
.output()
.map_err(|e|
ConfigError::AuthExec(format!("Executing {:} failed: {:?}", cmd, e))
)?;

if !output.status.success() {
return Err(ConfigError::AuthExecRun {
cmd: format!{"{} {}", cmd, params},
status: output.status,
out: output,
}.into());
}

if let Some(field) = provider.config.get("token-key") {
let pure_path = field
.trim_matches(|c| c == '"' || c == '{' || c == '}');
clux marked this conversation as resolved.
Show resolved Hide resolved
let json_output : serde_json::Value = serde_json::from_slice(&output.stdout)?;
match jsonpath_select(&json_output, &format!("${}", pure_path)) {
clux marked this conversation as resolved.
Show resolved Hide resolved
Ok(v) if v.len() > 0 => {
if let serde_json::Value::String(res) = v[0] {
self.token = Some(res.clone());
} else {
return Err(ConfigError::AuthExec(
format!("Target value at {:} is not a string", pure_path)).into());
}
}
Err(e) => {
return Err(ConfigError::AuthExec(
format!("Could not extract JSON value: {:}", e)).into());
}
_ => {
return Err(ConfigError::AuthExec(
format!("Target value {:} not found", pure_path)).into());
}
};
} else {
self.token = Some(
std::str::from_utf8(&output.stdout).map_err(|e|
ConfigError::AuthExec(format!("Result is not a string {:?} ", e))
)?.to_owned());
}
} else {
return Err(ConfigError::AuthExec(format!("no token or command provided. Authoring mechanism {:} not supported", provider.name)).into());
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't this else case happening when token.is_some(), don't you need another is_none check?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch, this is supposed to be the else for the previous block. will fix.

}
None => {}
};
Expand All @@ -193,3 +247,45 @@ impl AuthInfo {
utils::data_or_file_with_base64(&self.client_key_data, &self.client_key)
}
}

#[cfg(test)]
mod test {
use super::*;
#[tokio::test]
async fn exec_auth_command() -> Result<()> {
let test_file = "
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\"} }'
cmd-path: echo
expiry-key: '{.credential.token_expiry}'
token-key: '{.credential.access_token}'
name: gcp
";

let mut config : Kubeconfig = serde_yaml::from_str(test_file).map_err(ConfigError::ParseYaml)?;
let auth_info = &mut config.auth_infos[0].auth_info;
assert!(auth_info.token.is_none());
auth_info.load_gcp().await?;
assert_eq!(auth_info.token, Some("my_token".to_owned()));

Ok(())
}
}
2 changes: 2 additions & 0 deletions kube/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ pub enum ConfigError {
},
#[error("Failed to parse auth exec output: {0}")]
AuthExecParse(#[source] serde_json::Error),
#[error("Failed exec auth: {0}")]
AuthExec(String),
}

/// An Error response from the API
Expand Down