use greentic_deploy_spec::{EnvId, Environment};
use serde_json::Value;
use crate::cli::OpError;
use crate::environment::LocalFsStore;
#[cfg(feature = "k8s-client")]
pub fn resolve_bound_identity(
store: &LocalFsStore,
env: &Environment,
env_id: &EnvId,
answers: Option<&Value>,
) -> Result<Option<String>, OpError> {
match crate::cli::secrets::resolve_credentials_token(store, env, env_id) {
Ok(found) => Ok(found),
Err(OpError::Conflict(local_err)) => match read_from_cluster(env, env_id, answers) {
Ok(Some(bearer)) => Ok(Some(bearer)),
Ok(None) => Err(OpError::Conflict(local_err)),
Err(cluster_err) => Err(OpError::Conflict(format!(
"{local_err}; and the bound identity could not be read from the \
cluster Secret: {cluster_err}"
))),
},
Err(other) => Err(other),
}
}
#[cfg(feature = "k8s-client")]
fn read_from_cluster(
env: &Environment,
env_id: &EnvId,
answers: Option<&Value>,
) -> Result<Option<String>, String> {
use super::async_bridge::run_k8s_async;
use super::bootstrap::DEPLOYER_IDENTITY_SECRET_NAME;
use super::kube_client::read_deployer_identity_bearer;
use super::manifests::{K8sParams, kubeconfig_context_from_answers, namespace_for_env};
let namespace = match K8sParams::from_answers(env, answers) {
Ok(params) => params.namespace,
Err(_) => namespace_for_env(env_id),
};
let context = kubeconfig_context_from_answers(answers);
run_k8s_async(read_deployer_identity_bearer(
context.as_deref(),
&namespace,
DEPLOYER_IDENTITY_SECRET_NAME,
env_id.as_str(),
))
.map_err(|e| e.to_string())
}
#[cfg(not(feature = "k8s-client"))]
pub fn resolve_bound_identity(
store: &LocalFsStore,
env: &Environment,
env_id: &EnvId,
_answers: Option<&Value>,
) -> Result<Option<String>, OpError> {
crate::cli::secrets::resolve_credentials_token(store, env, env_id)
}
#[cfg(all(test, feature = "k8s-client"))]
mod tests {
use super::*;
use crate::cli::tests_common::make_env;
use crate::environment::EnvironmentStore;
use tempfile::tempdir;
#[test]
fn no_bound_ref_resolves_to_none_without_a_cluster_read() {
let dir = tempdir().unwrap();
let store = LocalFsStore::new(dir.path());
let env = make_env("local"); store.save(&env).unwrap();
let env_id = EnvId::try_from("local").unwrap();
assert_eq!(
resolve_bound_identity(&store, &env, &env_id, None).unwrap(),
None
);
}
}