use dynamic_config::Error;
pub const SERVICE_ACCOUNT_TOKEN: &str =
dynamic_config_store_core::credential::SERVICE_ACCOUNT_TOKEN;
#[derive(Clone)]
#[non_exhaustive]
pub enum Auth {
Anonymous,
Token(String),
Login {
method: String,
bearer: Bearer,
meta: Vec<(String, String)>,
},
}
#[derive(Clone)]
#[non_exhaustive]
pub enum Bearer {
Literal(String),
File(String),
}
impl Auth {
pub fn token(token: impl Into<String>) -> Self {
Self::Token(token.into())
}
#[must_use]
pub fn from_environment() -> Self {
match std::env::var("CONSUL_HTTP_TOKEN") {
Ok(token) if !token.is_empty() => Self::Token(token),
_ => Self::Anonymous,
}
}
pub fn kubernetes(method: impl Into<String>) -> Self {
Self::Login {
method: method.into(),
bearer: Bearer::File(SERVICE_ACCOUNT_TOKEN.to_owned()),
meta: Vec::new(),
}
}
pub fn jwt(method: impl Into<String>, token: impl Into<String>) -> Self {
Self::Login {
method: method.into(),
bearer: Bearer::Literal(token.into()),
meta: Vec::new(),
}
}
#[must_use]
pub fn with_bearer_file(mut self, path: impl Into<String>) -> Self {
if let Self::Login { bearer, .. } = &mut self {
*bearer = Bearer::File(path.into());
}
self
}
#[must_use]
pub fn with_meta(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
if let Self::Login { meta, .. } = &mut self {
meta.push((name.into(), value.into()));
}
self
}
pub(crate) fn login_body(&self) -> Result<Option<serde_json::Value>, Error> {
let Self::Login {
method,
bearer,
meta,
} = self
else {
return Ok(None);
};
let token = match bearer {
Bearer::Literal(token) => token.clone(),
Bearer::File(path) => std::fs::read_to_string(path)
.map_err(|error| {
Error::remote(format!(
"consul: cannot read the bearer token at {path}: {error}"
))
})?
.trim()
.to_owned(),
};
let meta: serde_json::Map<String, serde_json::Value> = meta
.iter()
.map(|(name, value)| (name.clone(), serde_json::Value::from(value.clone())))
.collect();
Ok(Some(serde_json::json!({
"AuthMethod": method,
"BearerToken": token,
"Meta": meta,
})))
}
pub(crate) fn describe(&self) -> String {
match self {
Self::Anonymous => "no token".to_owned(),
Self::Token(_) => "a supplied token".to_owned(),
Self::Login { method, .. } => format!("auth method `{method}`"),
}
}
}
impl std::fmt::Debug for Auth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Anonymous => f.write_str("Anonymous"),
Self::Token(_) => f.write_str("Token(***)"),
Self::Login { method, meta, .. } => f
.debug_struct("Login")
.field("method", method)
.field("meta", meta)
.finish_non_exhaustive(),
}
}
}
impl std::fmt::Debug for Bearer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Literal(_) => f.write_str("Literal(***)"),
Self::File(path) => f.debug_tuple("File").field(path).finish(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_supplied_token_needs_no_login() {
assert!(Auth::token("t").login_body().unwrap().is_none());
assert!(Auth::Anonymous.login_body().unwrap().is_none());
}
#[test]
fn a_login_presents_its_bearer_token_to_a_named_method() {
let body = Auth::jwt("kubernetes", "a.b.c")
.login_body()
.unwrap()
.expect("this one logs in");
assert_eq!(body["AuthMethod"], "kubernetes");
assert_eq!(body["BearerToken"], "a.b.c");
}
#[test]
fn meta_is_carried_through_for_the_audit_log() {
let body = Auth::jwt("kubernetes", "a.b.c")
.with_meta("pod", "myapp-7f9")
.login_body()
.unwrap()
.unwrap();
assert_eq!(body["Meta"]["pod"], "myapp-7f9");
}
#[test]
fn a_missing_bearer_file_says_where_it_looked() {
let error = Auth::kubernetes("kubernetes")
.with_bearer_file("/no/such/token")
.login_body()
.expect_err("there is no token there");
assert!(error.to_string().contains("/no/such/token"), "{error}");
}
#[test]
fn an_unset_environment_variable_is_anonymous_rather_than_an_error() {
std::env::remove_var("CONSUL_HTTP_TOKEN");
assert!(matches!(Auth::from_environment(), Auth::Anonymous));
}
}