use serde::Deserialize;
pub const SORLA_CATEGORY: &str = "sorla";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SorlaRouteDoc {
pub url: String,
pub token: Option<String>,
pub tenant: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SorlaRouteError {
Missing(String),
Invalid(String),
Unavailable(String),
}
impl std::fmt::Display for SorlaRouteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Missing(tried) => write!(f, "no sorla route document ({tried})"),
Self::Invalid(why) => write!(f, "sorla route document is invalid: {why}"),
Self::Unavailable(why) => {
write!(f, "sorla route document could not be read: {why}")
}
}
}
}
impl std::error::Error for SorlaRouteError {}
#[derive(Deserialize)]
struct RawDoc {
url: Option<String>,
token: Option<String>,
tenant: Option<String>,
}
pub async fn resolve_route(
secrets: &dyn greentic_secrets_lib::SecretsManager,
tenant: &str,
unit: Option<&str>,
sor: &str,
) -> Result<SorlaRouteDoc, SorlaRouteError> {
let uris = greentic_aw_runtime::scoped_secrets::secret_uri_candidates(
SORLA_CATEGORY,
tenant,
None,
unit,
sor,
)
.map_err(|error| SorlaRouteError::Invalid(format!("sor {sor}: {error}")))?;
let mut bytes: Option<Vec<u8>> = None;
let mut backend_error: Option<String> = None;
for uri in &uris {
match secrets.read(uri).await {
Ok(b) => {
bytes = Some(b);
break;
}
Err(greentic_secrets_lib::SecretError::NotFound(_)) => {}
Err(other) => {
tracing::debug!(
sor = %sor,
uri = %uri,
error = %other,
"sorla: route document read failed (backend error, not a miss)"
);
backend_error = Some(other.to_string());
break;
}
}
}
let bytes = match (bytes, backend_error) {
(Some(bytes), _) => bytes,
(None, Some(error)) => {
return Err(SorlaRouteError::Unavailable(format!("sor {sor}: {error}")));
}
(None, None) => {
tracing::debug!(sor = %sor, tried = %uris.join(" or "), "sorla: no route document at any scope");
return Err(SorlaRouteError::Missing(format!(
"sor {sor}: {}",
uris.join(" or ")
)));
}
};
let raw: RawDoc = serde_json::from_slice(&bytes)
.map_err(|_| SorlaRouteError::Invalid(format!("sor {sor}: not a JSON object")))?;
let url = raw
.url
.map(|u| u.trim().trim_end_matches('/').to_string())
.filter(|u| !u.is_empty())
.ok_or_else(|| SorlaRouteError::Invalid(format!("sor {sor}: `url` is missing")))?;
let tenant = raw
.tenant
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty())
.ok_or_else(|| SorlaRouteError::Invalid(format!("sor {sor}: `tenant` is missing")))?;
let token = raw
.token
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty());
Ok(SorlaRouteDoc { url, token, tenant })
}
#[cfg(test)]
pub(crate) mod test_secrets {
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Clone, Default)]
pub(crate) struct Handle {
entries: Arc<Mutex<HashMap<String, Vec<u8>>>>,
failing: Arc<Mutex<HashMap<String, String>>>,
}
#[allow(dead_code)]
impl Handle {
pub(crate) fn with(entries: &[(&str, &str)]) -> Self {
let map = entries
.iter()
.map(|(uri, body)| ((*uri).to_string(), body.as_bytes().to_vec()))
.collect();
Self {
entries: Arc::new(Mutex::new(map)),
failing: Arc::new(Mutex::new(HashMap::new())),
}
}
pub(crate) fn set(&self, uri: &str, body: &str) {
self.entries
.lock()
.unwrap()
.insert(uri.to_string(), body.as_bytes().to_vec());
}
pub(crate) fn fail(&self, uri: &str, message: &str) {
self.failing
.lock()
.unwrap()
.insert(uri.to_string(), message.to_string());
}
pub(crate) fn manager(&self) -> crate::secrets::DynSecretsManager {
Arc::new(self.clone())
}
}
#[async_trait::async_trait]
impl greentic_secrets_lib::SecretsManager for Handle {
async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
if let Some(message) = self.failing.lock().unwrap().get(path).cloned() {
return Err(greentic_secrets_lib::SecretError::Backend(message.into()));
}
self.entries
.lock()
.unwrap()
.get(path)
.cloned()
.ok_or_else(|| greentic_secrets_lib::SecretError::NotFound(path.to_string()))
}
async fn write(&self, path: &str, bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
self.entries
.lock()
.unwrap()
.insert(path.to_string(), bytes.to_vec());
Ok(())
}
async fn delete(&self, path: &str) -> greentic_secrets_lib::Result<()> {
self.entries.lock().unwrap().remove(path);
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::test_secrets::Handle;
use super::*;
#[tokio::test]
async fn resolves_a_tenant_default_document() {
let s = Handle::with(&[(
"secrets://default/acme/_/sorla/landlord",
r#"{"url":"http://127.0.0.1:9000","tenant":"acme"}"#,
)]);
let doc = resolve_route(&s, "acme", None, "landlord")
.await
.expect("resolves");
assert_eq!(doc.url, "http://127.0.0.1:9000");
assert_eq!(doc.token, None);
assert_eq!(doc.tenant, "acme");
}
#[tokio::test]
async fn a_blank_token_reads_as_no_token() {
let s = Handle::with(&[(
"secrets://default/acme/_/sorla/landlord",
r#"{"url":"http://x","token":" ","tenant":"acme"}"#,
)]);
assert_eq!(
resolve_route(&s, "acme", None, "landlord")
.await
.expect("resolves")
.token,
None
);
}
#[tokio::test]
async fn a_missing_document_names_what_was_tried() {
let s = Handle::with(&[]);
let err = resolve_route(&s, "acme", None, "landlord")
.await
.expect_err("missing");
assert!(matches!(err, SorlaRouteError::Missing(_)));
assert!(err.to_string().contains("sorla/landlord"));
}
#[tokio::test]
async fn a_backend_failure_is_unavailable_never_missing() {
let s = Handle::with(&[]);
s.fail(
"secrets://default/acme/_/sorla/landlord",
"connection refused",
);
let err = resolve_route(&s, "acme", None, "landlord")
.await
.expect_err("a backend failure must not resolve");
assert!(
matches!(err, SorlaRouteError::Unavailable(_)),
"got: {err:?}"
);
}
#[tokio::test]
async fn an_invalid_document_never_echoes_its_value() {
let s = Handle::with(&[(
"secrets://default/acme/_/sorla/landlord",
r#"{"token":"s3cr3t"}"#,
)]);
let err = resolve_route(&s, "acme", None, "landlord")
.await
.expect_err("invalid");
assert!(matches!(err, SorlaRouteError::Invalid(_)));
assert!(!err.to_string().contains("s3cr3t"));
}
}