use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use crate::runtime::block_on;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use greentic_secrets_lib::env::EnvSecretsManager;
use greentic_secrets_lib::{SecretScope, SecretsManager};
use greentic_types::TenantCtx;
use lru::LruCache;
use parking_lot::Mutex;
pub type DynSecretsManager = Arc<dyn SecretsManager>;
#[derive(Clone, Debug)]
pub enum SecretsBackend {
Env,
Broker {
endpoint: String,
token: String,
},
}
impl SecretsBackend {
pub fn from_env(value: Option<String>) -> Result<Self> {
match value
.unwrap_or_else(|| "env".into())
.trim()
.to_ascii_lowercase()
.as_str()
{
"" | "env" => Ok(SecretsBackend::Env),
"broker" => Self::broker_from_strings(
"broker",
std::env::var("SECRETS_BROKER_ENDPOINT")
.unwrap_or_default()
.as_str(),
std::env::var("SECRETS_BROKER_TOKEN")
.unwrap_or_default()
.as_str(),
),
other => Err(anyhow!("unsupported SECRETS_BACKEND `{other}`")),
}
}
pub(crate) fn broker_from_strings(kind: &str, endpoint: &str, token: &str) -> Result<Self> {
let endpoint = endpoint.trim().trim_end_matches('/');
if endpoint.is_empty() {
return Err(anyhow!(
"SECRETS_BACKEND={kind} requires SECRETS_BROKER_ENDPOINT to be set"
));
}
Ok(SecretsBackend::Broker {
endpoint: endpoint.to_owned(),
token: token.to_owned(),
})
}
pub fn from_config(cfg: &greentic_config_types::SecretsBackendRefConfig) -> Result<Self> {
match cfg.kind.trim().to_ascii_lowercase().as_str() {
"" | "none" | "env" => Ok(SecretsBackend::Env),
"broker" => {
let endpoint = cfg
.reference
.as_deref()
.unwrap_or("")
.trim()
.trim_end_matches('/');
let endpoint = if endpoint.is_empty() {
std::env::var("SECRETS_BROKER_ENDPOINT").unwrap_or_default()
} else {
endpoint.to_owned()
};
let token = std::env::var("SECRETS_BROKER_TOKEN").unwrap_or_default();
Self::broker_from_strings("broker", &endpoint, &token)
}
other => Err(anyhow!("unsupported secrets backend `{other}`")),
}
}
pub fn build_manager(&self) -> Result<DynSecretsManager> {
let inner: DynSecretsManager = match self {
SecretsBackend::Env => {
ensure_env_secrets_allowed()?;
Arc::new(EnvSecretsManager)
}
SecretsBackend::Broker { endpoint, token } => Arc::new(
crate::secrets_broker::BrokerSecretsManager::new(endpoint, token),
),
};
Ok(CachingSecretsManager::wrap(inner))
}
}
pub fn default_manager() -> Result<DynSecretsManager> {
SecretsBackend::Env.build_manager()
}
const DEFAULT_CACHE_TTL_SECS: u64 = 300;
const DEFAULT_CACHE_MAX_ENTRIES: usize = 512;
fn cache_ttl() -> Duration {
let secs = std::env::var("SECRETS_CACHE_TTL_SECS")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(DEFAULT_CACHE_TTL_SECS);
Duration::from_secs(secs)
}
fn cache_max_entries() -> NonZeroUsize {
let n = std::env::var("SECRETS_CACHE_MAX_ENTRIES")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|&v| v > 0)
.unwrap_or(DEFAULT_CACHE_MAX_ENTRIES);
NonZeroUsize::new(n).expect("cache max entries must be > 0")
}
struct CacheEntry {
data: Vec<u8>,
inserted_at: Instant,
}
pub struct CachingSecretsManager {
inner: DynSecretsManager,
cache: Mutex<LruCache<String, CacheEntry>>,
ttl: Duration,
generation: AtomicU64,
}
impl CachingSecretsManager {
pub fn wrap(inner: DynSecretsManager) -> DynSecretsManager {
Self::wrap_with(inner, cache_ttl(), cache_max_entries())
}
fn wrap_with(inner: DynSecretsManager, ttl: Duration, max: NonZeroUsize) -> DynSecretsManager {
if ttl.is_zero() {
tracing::info!("secrets cache disabled (TTL=0)");
return inner;
}
tracing::info!(
ttl_secs = ttl.as_secs(),
max_entries = max.get(),
"secrets value cache enabled"
);
Arc::new(Self {
inner,
cache: Mutex::new(LruCache::new(max)),
ttl,
generation: AtomicU64::new(0),
})
}
}
#[async_trait]
impl SecretsManager for CachingSecretsManager {
async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
{
let mut cache = self.cache.lock();
if let Some(entry) = cache.get(path) {
if entry.inserted_at.elapsed() < self.ttl {
return Ok(entry.data.clone());
}
cache.pop(path);
}
}
let generation = self.generation.load(Ordering::SeqCst);
let data = self.inner.read(path).await?;
{
let mut cache = self.cache.lock();
if self.generation.load(Ordering::SeqCst) == generation {
cache.put(
path.to_owned(),
CacheEntry {
data: data.clone(),
inserted_at: Instant::now(),
},
);
}
}
Ok(data)
}
async fn write(&self, path: &str, bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
self.generation.fetch_add(1, Ordering::SeqCst);
let result = self.inner.write(path, bytes).await;
self.generation.fetch_add(1, Ordering::SeqCst);
self.cache.lock().pop(path);
result
}
async fn delete(&self, path: &str) -> greentic_secrets_lib::Result<()> {
self.generation.fetch_add(1, Ordering::SeqCst);
let result = self.inner.delete(path).await;
self.generation.fetch_add(1, Ordering::SeqCst);
self.cache.lock().pop(path);
result
}
}
fn normalize_pack_segment(pack_id: &str) -> String {
pack_id
.chars()
.map(|ch| {
let ch = ch.to_ascii_lowercase();
match ch {
'a'..='z' | '0'..='9' | '_' | '-' => ch,
_ => '_',
}
})
.collect()
}
const UNIT_PACK_SEGMENT_MARKER: &str = "_unit_";
const UNIT_SEGMENT_SLUG_MAX: usize = 40;
const UNIT_SEGMENT_HASH_BYTES: usize = 6;
fn underscore_slug(raw: &str, max: usize) -> String {
let mut slug = String::with_capacity(raw.len());
for ch in raw.chars() {
let mapped = if ch.is_ascii_alphanumeric() {
ch.to_ascii_lowercase()
} else {
'_'
};
if mapped == '_' && (slug.is_empty() || slug.ends_with('_')) {
continue;
}
slug.push(mapped);
}
slug.truncate(max);
slug.trim_end_matches('_').to_string()
}
fn short_hash(raw: &str) -> String {
use sha2::{Digest, Sha256};
let digest = Sha256::digest(raw.as_bytes());
digest[..UNIT_SEGMENT_HASH_BYTES]
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
pub fn unit_pack_segment(pack_id: &str, unit_id: &str) -> Option<String> {
let pack_raw = pack_id.trim();
let unit_raw = unit_id.trim();
if pack_raw.is_empty() || unit_raw.is_empty() {
return None;
}
let pack_slug = underscore_slug(pack_raw, UNIT_SEGMENT_SLUG_MAX);
let pack_part = if pack_slug.is_empty() {
format!("pack_{}", short_hash(pack_raw))
} else if pack_slug == pack_raw {
pack_slug
} else {
format!("{pack_slug}_{}", short_hash(pack_raw))
};
let unit_hash = short_hash(unit_raw);
let unit_slug = underscore_slug(unit_raw, UNIT_SEGMENT_SLUG_MAX);
let unit_part = if unit_slug.is_empty() {
unit_hash
} else {
format!("{unit_slug}_{unit_hash}")
};
Some(format!("{pack_part}{UNIT_PACK_SEGMENT_MARKER}{unit_part}"))
}
pub fn scoped_secret_path_for_unit(
ctx: &TenantCtx,
pack_id: &str,
unit_id: &str,
key: &str,
) -> Result<Option<String>> {
match unit_pack_segment(pack_id, unit_id) {
Some(segment) => scoped_secret_path_for_pack(ctx, &segment, key).map(Some),
None => Ok(None),
}
}
fn pack_secret_path_candidates(
ctx: &TenantCtx,
pack_id: &str,
unit_id: Option<&str>,
key: &str,
) -> Result<Vec<String>> {
let bare = scoped_secret_path_for_pack(ctx, pack_id, key)?;
let unit = match unit_id {
Some(unit) => scoped_secret_path_for_unit(ctx, pack_id, unit, key)?,
None => None,
};
Ok(match unit {
Some(unit) if unit != bare => vec![unit, bare],
_ => vec![bare],
})
}
pub fn read_pack_secret_blocking(
manager: &DynSecretsManager,
ctx: &TenantCtx,
pack_id: &str,
unit_id: Option<&str>,
key: &str,
) -> std::result::Result<Vec<u8>, PackSecretError> {
let candidates = pack_secret_path_candidates(ctx, pack_id, unit_id, key)
.map_err(|err| PackSecretError::Backend(err.to_string()))?;
let mut failures = Vec::new();
for candidate in &candidates {
match block_on(manager.read(candidate.as_str())) {
Ok(bytes) => return Ok(bytes),
Err(err) => failures.push(err),
}
}
Err(classify_pack_secret_failures(&candidates, failures))
}
#[derive(Debug, thiserror::Error)]
pub enum PackSecretError {
#[error("no secret at {0}")]
NotFound(String),
#[error("secret read denied: {0}")]
Denied(String),
#[error("secret backend error: {0}")]
Backend(String),
}
fn classify_pack_secret_failures(
candidates: &[String],
failures: Vec<greentic_secrets_lib::SecretError>,
) -> PackSecretError {
let mut denied: Option<String> = None;
let mut backend: Option<String> = None;
for failure in failures {
match failure {
greentic_secrets_lib::SecretError::NotFound(_) => {}
greentic_secrets_lib::SecretError::Permission(detail) => {
denied.get_or_insert(detail);
}
other => {
backend.get_or_insert(other.to_string());
}
}
}
if let Some(detail) = denied {
return PackSecretError::Denied(detail);
}
if let Some(detail) = backend {
return PackSecretError::Backend(detail);
}
PackSecretError::NotFound(candidates.join(" or "))
}
pub fn write_pack_secret_blocking(
manager: &DynSecretsManager,
ctx: &TenantCtx,
pack_id: &str,
unit_id: Option<&str>,
key: &str,
value: &[u8],
) -> Result<()> {
let target = match unit_id {
Some(unit) => scoped_secret_path_for_unit(ctx, pack_id, unit, key)?,
None => None,
};
let target = match target {
Some(target) => target,
None => scoped_secret_path_for_pack(ctx, pack_id, key)?,
};
block_on(manager.write(target.as_str(), value)).map_err(|err| anyhow!(err.to_string()))?;
Ok(())
}
pub fn agent_tool_secret_uri(
env: &str,
tenant: &str,
provider: &str,
key: &str,
unit_id: Option<&str>,
) -> Option<String> {
let provider = provider.trim();
let key = key.trim();
if provider.is_empty() || key.is_empty() {
return None;
}
let category = match unit_id.and_then(|unit| unit_pack_segment(provider, unit)) {
Some(segment) => segment,
None => provider.to_string(),
};
if ![env, tenant, category.as_str(), key]
.into_iter()
.all(crate::secrets_broker::is_safe_secret_segment)
{
return None;
}
Some(format!("secrets://{env}/{tenant}/_/{category}/{key}"))
}
pub fn canonicalize_secret_key(raw: &str) -> String {
raw.trim()
.chars()
.map(|ch| {
let ch = ch.to_ascii_lowercase();
match ch {
'a'..='z' | '0'..='9' | '_' => ch,
_ => '_',
}
})
.collect()
}
fn normalize_team_segment(team: Option<&str>) -> String {
match team
.map(str::trim)
.filter(|value| !value.is_empty() && !value.eq_ignore_ascii_case("default"))
{
Some(value) => value.to_string(),
None => "_".to_string(),
}
}
pub fn scoped_secret_path_for_pack(ctx: &TenantCtx, pack_id: &str, key: &str) -> Result<String> {
let key = key.trim();
if key.is_empty() {
return Err(anyhow!("secret key must not be empty"));
}
let safe_key = canonicalize_secret_key(key);
let team = ctx.team_id.as_ref().or(ctx.team.as_ref());
let scope = SecretScope {
env: ctx.env.as_str().to_string(),
tenant: ctx.tenant.as_str().to_string(),
team: team.map(|value| value.as_str().to_string()),
};
let team_segment = normalize_team_segment(scope.team.as_deref());
for (label, value) in [
("env", scope.env.as_str()),
("tenant", scope.tenant.as_str()),
("team", team_segment.as_str()),
] {
if !crate::secrets_broker::is_safe_secret_segment(value) {
return Err(anyhow!(
"secret {label} is not a safe secret-path segment; refusing to build a secrets uri"
));
}
}
let pack_segment = pack_id.trim();
if pack_segment.is_empty() {
return Err(anyhow!("pack_id must not be empty for scoped secrets"));
}
let pack_segment = normalize_pack_segment(pack_segment);
Ok(format!(
"secrets://{}/{}/{}/{}/{}",
scope.env, scope.tenant, team_segment, pack_segment, safe_key
))
}
pub fn read_secret_blocking(
manager: &DynSecretsManager,
ctx: &TenantCtx,
pack_id: &str,
key: &str,
) -> Result<Vec<u8>> {
let scoped_key = scoped_secret_path_for_pack(ctx, pack_id, key)?;
let bytes =
block_on(manager.read(scoped_key.as_str())).map_err(|err| anyhow!(err.to_string()))?;
Ok(bytes)
}
pub fn write_secret_blocking(
manager: &DynSecretsManager,
ctx: &TenantCtx,
pack_id: &str,
key: &str,
value: &[u8],
) -> Result<()> {
let scoped_key = scoped_secret_path_for_pack(ctx, pack_id, key)?;
block_on(manager.write(scoped_key.as_str(), value)).map_err(|err| anyhow!(err.to_string()))?;
Ok(())
}
fn ensure_env_secrets_allowed() -> Result<()> {
check_env_secrets_allowed(crate::config::greentic_env().as_deref())
}
fn check_env_secrets_allowed(env: Option<&str>) -> Result<()> {
let env = match env {
Some(value) => value.to_string(),
None => {
tracing::warn!(
"GREENTIC_ENV is unset: assuming `local` and allowing the env secrets backend; \
set GREENTIC_ENV explicitly in deployed environments"
);
"local".to_string()
}
};
let env = env.trim().to_ascii_lowercase();
if matches!(env.as_str(), "local" | "dev" | "test") {
Ok(())
} else {
Err(anyhow!(
"env secrets backend is disabled for env '{env}' (dev/test only)"
))
}
}
#[cfg(test)]
mod env_secrets_gate_tests {
use super::*;
use crate::config::non_blank;
#[test]
fn blank_takes_the_same_branch_as_unset() {
for raw in [None, Some(""), Some(" ")] {
assert!(
check_env_secrets_allowed(non_blank(raw).as_deref()).is_ok(),
"{raw:?}"
);
}
}
#[test]
fn deployed_envs_are_still_refused() {
for raw in ["prod", "staging", " Prod "] {
assert!(
check_env_secrets_allowed(non_blank(Some(raw)).as_deref()).is_err(),
"{raw}"
);
}
assert!(check_env_secrets_allowed(Some("dev")).is_ok());
}
}
#[cfg(test)]
mod tests {
use super::*;
use greentic_config_types::SecretsBackendRefConfig;
use greentic_types::{EnvId, TeamId, TenantId, UserId};
use std::sync::atomic::{AtomicUsize, Ordering};
fn tenant_ctx() -> greentic_types::TenantCtx {
greentic_types::TenantCtx::new(
EnvId::new("local").expect("env"),
TenantId::new("tenant-a").expect("tenant"),
)
.with_team(Some(TeamId::new("team-a").expect("team")))
.with_user(Some(UserId::new("user-a").expect("user")))
}
#[test]
fn scoped_secret_path_normalizes_pack_and_key_segments() {
let path =
scoped_secret_path_for_pack(&tenant_ctx(), "My Pack/Prod", " API/KEY value ").unwrap();
assert_eq!(
path,
"secrets://local/tenant-a/team-a/my_pack_prod/api_key_value"
);
}
#[test]
fn scoped_secret_path_rejects_empty_inputs() {
let ctx = tenant_ctx();
assert!(scoped_secret_path_for_pack(&ctx, "demo", " ").is_err());
assert!(scoped_secret_path_for_pack(&ctx, " ", "key").is_err());
}
#[test]
fn scoped_secret_path_maps_default_team_to_underscore() {
let ctx = greentic_types::TenantCtx::new(
EnvId::new("dev").expect("env"),
TenantId::new("demo").expect("tenant"),
)
.with_team(Some(TeamId::new("default").expect("team")));
let path = scoped_secret_path_for_pack(&ctx, "ollama-runtime-repro", "ollama_api_key")
.expect("scoped secret path");
assert_eq!(
path,
"secrets://dev/demo/_/ollama-runtime-repro/ollama_api_key"
);
}
#[test]
fn scoped_secret_path_canonicalizes_provider_secret_keys() {
let ctx = greentic_types::TenantCtx::new(
EnvId::new("dev").expect("env"),
TenantId::new("demo").expect("tenant"),
)
.with_team(Some(TeamId::new("default").expect("team")))
.with_user(Some(UserId::new("operator").expect("user")));
let path = scoped_secret_path_for_pack(&ctx, "ollama-runtime-repro", "OLLAMA_API_KEY")
.expect("scoped secret path");
assert_eq!(
path,
"secrets://dev/demo/_/ollama-runtime-repro/ollama_api_key"
);
}
#[test]
fn the_unit_segment_is_a_fixed_point_of_both_canonicalizers() {
let ids = [
("pack.dw.support", "web-assistant"),
("My Pack/Prod", "Web Assistant (prod)"),
("demo pack", "unit_01JTKS.v2"),
("pack--x", "ÜNÏCÖDÉ-Ünit"),
("a.b-c_d", "---"),
("...", "a/b/c@d"),
("ollama-runtime-repro", " x "),
(
"a-very-long-pack-id-that-exceeds-the-slug-limit-by-a-lot-of-bytes",
"a-very-long-deployment-name-that-exceeds-the-slug-limit-by-a-lot",
),
];
for (pack, unit) in ids {
let segment = unit_pack_segment(pack, unit).expect("segment");
assert_eq!(
canonicalize_secret_key(&segment),
segment,
"`{pack}` / `{unit}` is not a fixed point of canonicalize_secret_key"
);
assert_eq!(
greentic_secrets_lib::spec::canonical_secret_name(&segment),
segment,
"`{pack}` / `{unit}` is not a fixed point of canonical_secret_name"
);
assert!(
segment
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
"`{pack}` / `{unit}` -> `{segment}`"
);
assert!(!segment.starts_with('_') && !segment.ends_with('_'));
assert!(!segment.contains("__"));
}
}
#[test]
fn a_unit_scoped_uri_parses_and_re_normalizes_to_itself() {
let ctx = tenant_ctx();
for (pack, unit) in [("pack.dw.support", "web-assistant"), ("...", "a/b@c")] {
let segment = unit_pack_segment(pack, unit).expect("segment");
assert_eq!(normalize_pack_segment(&segment), segment);
let uri = scoped_secret_path_for_unit(&ctx, pack, unit, "HUBSPOT/ACCESS_TOKEN")
.expect("uri")
.expect("some");
assert!(
greentic_secrets_lib::spec::SecretUri::parse(&uri).is_ok(),
"`{uri}` is not a valid secret URI"
);
assert!(uri.ends_with("/hubspot_access_token"), "got {uri}");
}
}
#[test]
fn the_unit_segment_is_deterministic_and_carries_a_hash() {
let a = unit_pack_segment("demo", "web-assistant").expect("segment");
assert_eq!(
a,
unit_pack_segment("demo", "web-assistant").expect("again")
);
assert_eq!(
a,
unit_pack_segment(" demo ", " web-assistant ").expect("trimmed")
);
let unit_part = a.strip_prefix("demo_unit_").expect("marker");
let (slug, hash) = unit_part.rsplit_once('_').expect("hash suffix");
assert_eq!(slug, "web_assistant");
assert_eq!(hash.len(), UNIT_SEGMENT_HASH_BYTES * 2);
assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn the_unit_segment_matches_the_pinned_values() {
assert_eq!(
unit_pack_segment("demo", "web-assistant").expect("segment"),
"demo_unit_web_assistant_9456a3393b7e"
);
assert_eq!(
unit_pack_segment("pack.dw.support", "Web Assistant (prod)").expect("segment"),
"pack_dw_support_339461568342_unit_web_assistant_prod_3ee04e3f306a"
);
}
#[test]
fn ids_the_slug_would_merge_still_get_distinct_segments() {
let pairs = [
(("demo", "Web Assistant"), ("demo", "web-assistant")),
(("demo", "web.assistant"), ("demo", "web_assistant")),
(("demo", "a/b"), ("demo", "a-b")),
(("demo", "unit_b"), ("demo_unit_b", "unit")),
(
(
"demo",
"a-very-long-deployment-name-over-the-slug-limit-one",
),
(
"demo",
"a-very-long-deployment-name-over-the-slug-limit-two",
),
),
];
for ((pack_l, unit_l), (pack_r, unit_r)) in pairs {
assert_ne!(
unit_pack_segment(pack_l, unit_l),
unit_pack_segment(pack_r, unit_r),
"`{pack_l}`/`{unit_l}` and `{pack_r}`/`{unit_r}` must not share a segment"
);
}
}
#[test]
fn lossy_pack_slugs_do_not_collide_but_lossless_ids_stay_unhashed() {
let a = unit_pack_segment("my.pack", "u").expect("a");
let b = unit_pack_segment("my_pack", "u").expect("b");
let c = unit_pack_segment("My-Pack", "u").expect("c");
assert_ne!(a, b);
assert_ne!(a, c);
assert_ne!(b, c);
assert!(b.starts_with("my_pack_unit_"), "got {b}");
let long_a = format!("{}-one", "x".repeat(44));
let long_b = format!("{}-two", "x".repeat(44));
assert_ne!(
unit_pack_segment(&long_a, "u"),
unit_pack_segment(&long_b, "u"),
"ids sharing a 40-byte prefix must not collide"
);
for id in ["my.pack", "My-Pack", long_a.as_str()] {
let seg = unit_pack_segment(id, "u").expect("seg");
assert_eq!(canonicalize_secret_key(&seg), seg);
assert_eq!(greentic_secrets_lib::spec::canonical_secret_name(&seg), seg);
}
}
#[test]
fn a_punctuation_only_pack_id_does_not_produce_a_leading_underscore() {
let segment = unit_pack_segment("...", "unit-a").expect("segment");
assert!(segment.starts_with("pack_"), "got {segment}");
assert_ne!(
unit_pack_segment("...", "unit-a"),
unit_pack_segment("///", "unit-a"),
"two punctuation-only pack ids must not collapse together"
);
}
#[test]
fn a_blank_pack_or_unit_id_has_no_unit_scope() {
assert!(unit_pack_segment("demo", "").is_none());
assert!(unit_pack_segment("demo", " ").is_none());
assert!(unit_pack_segment("", "unit-a").is_none());
assert!(unit_pack_segment(" ", "unit-a").is_none());
assert!(
scoped_secret_path_for_unit(&tenant_ctx(), "demo", " ", "key")
.expect("ok")
.is_none()
);
}
#[test]
fn the_bare_agent_tool_address_is_unchanged() {
assert_eq!(
agent_tool_secret_uri("dev", "acme", "tavily", "api_key", None).expect("uri"),
"secrets://dev/acme/_/tavily/api_key"
);
assert_eq!(
agent_tool_secret_uri("dev", "acme", "tavily", "api_key", Some(" ")).expect("uri"),
"secrets://dev/acme/_/tavily/api_key"
);
}
#[test]
fn the_unit_scoped_agent_tool_address_differs_only_in_the_category() {
let bare =
agent_tool_secret_uri("dev", "acme", "tavily", "api_key", None).expect("bare uri");
let scoped = agent_tool_secret_uri("dev", "acme", "tavily", "api_key", Some("web-chat"))
.expect("unit uri");
assert_ne!(bare, scoped);
let bare_parts: Vec<&str> = bare.split('/').collect();
let scoped_parts: Vec<&str> = scoped.split('/').collect();
assert_eq!(bare_parts.len(), scoped_parts.len());
let differing: Vec<usize> = bare_parts
.iter()
.zip(&scoped_parts)
.enumerate()
.filter(|(_, (a, b))| a != b)
.map(|(i, _)| i)
.collect();
assert_eq!(differing.len(), 1, "{bare} vs {scoped}");
assert_eq!(
scoped_parts[differing[0]],
unit_pack_segment("tavily", "web-chat").expect("segment")
);
}
#[test]
fn the_agent_tool_category_is_a_fixed_point_of_both_canonicalizers() {
for (provider, unit) in [
("tavily", "web-chat"),
("HubSpot", "Web Assistant (prod)"),
("greentic.hubspot", "unit_01JTKS.v2"),
("a-b_c", "ÜNÏCÖDÉ-Ünit"),
("...", "a/b@c"),
] {
let uri =
agent_tool_secret_uri("dev", "acme", provider, "api_key", Some(unit)).expect("uri");
let category = uri.split('/').nth(5).expect("category segment");
assert_eq!(canonicalize_secret_key(category), category, "{uri}");
assert_eq!(
greentic_secrets_lib::spec::canonical_secret_name(category),
category,
"{uri}"
);
assert!(
greentic_secrets_lib::spec::SecretUri::parse(&uri).is_ok(),
"`{uri}` is not a valid secret URI"
);
}
}
#[test]
fn two_units_one_provider_and_key_are_two_addresses() {
let a = agent_tool_secret_uri("dev", "acme", "hubspot", "access_token", Some("sales-bot"))
.expect("a");
let b = agent_tool_secret_uri(
"dev",
"acme",
"hubspot",
"access_token",
Some("support-bot"),
)
.expect("b");
let shared =
agent_tool_secret_uri("dev", "acme", "hubspot", "access_token", None).expect("shared");
assert_ne!(a, b);
assert_ne!(a, shared);
assert_ne!(b, shared);
}
#[test]
fn unsafe_segments_have_no_agent_tool_address() {
for bad in ["..", "a/b", "%2e%2e", "../x", ".h"] {
assert!(agent_tool_secret_uri("dev", "acme", bad, "api_key", None).is_none());
assert!(agent_tool_secret_uri("dev", "acme", "tavily", bad, None).is_none());
assert!(agent_tool_secret_uri(bad, "acme", "tavily", "api_key", None).is_none());
assert!(agent_tool_secret_uri("dev", bad, "tavily", "api_key", None).is_none());
}
}
#[test]
fn scoped_pack_path_normalises_hostile_pack_id() {
let ctx = greentic_types::TenantCtx::new(
EnvId::new("dev").expect("env"),
TenantId::new("acme").expect("tenant"),
);
let path = scoped_secret_path_for_pack(&ctx, "../../evil/pack%2e", "k")
.expect("pack_id is normalised, not rejected");
assert!(!path.contains(".."), "{path}");
assert!(!path.contains('%'), "{path}");
assert_eq!(path.matches('/').count(), 6, "{path}");
}
#[test]
fn a_blank_provider_or_key_has_no_agent_tool_address() {
assert!(agent_tool_secret_uri("dev", "acme", "", "api_key", Some("u")).is_none());
assert!(agent_tool_secret_uri("dev", "acme", "tavily", " ", Some("u")).is_none());
}
#[test]
fn candidates_put_the_unit_scope_first_and_keep_the_bare_scope() {
let ctx = tenant_ctx();
let with_unit =
pack_secret_path_candidates(&ctx, "demo", Some("unit-a"), "API_KEY").expect("uris");
assert_eq!(
with_unit,
vec![
scoped_secret_path_for_unit(&ctx, "demo", "unit-a", "API_KEY")
.expect("ok")
.expect("some"),
scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare"),
]
);
let without_unit =
pack_secret_path_candidates(&ctx, "demo", None, "API_KEY").expect("uris");
assert_eq!(
without_unit,
vec![scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare")],
"no unit known must keep today's single candidate exactly"
);
}
struct MapSecrets {
entries: std::collections::HashMap<String, Vec<u8>>,
seen: Mutex<Vec<String>>,
written: Mutex<Vec<(String, Vec<u8>)>>,
}
impl MapSecrets {
fn with(pairs: &[(&str, &str)]) -> Arc<Self> {
Arc::new(Self {
entries: pairs
.iter()
.map(|(k, v)| ((*k).to_string(), v.as_bytes().to_vec()))
.collect(),
seen: Mutex::new(Vec::new()),
written: Mutex::new(Vec::new()),
})
}
}
#[async_trait]
impl SecretsManager for MapSecrets {
async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
self.seen.lock().push(path.to_string());
self.entries
.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.written.lock().push((path.to_string(), bytes.to_vec()));
Ok(())
}
async fn delete(&self, _: &str) -> greentic_secrets_lib::Result<()> {
Ok(())
}
}
fn unit_uri(ctx: &TenantCtx, pack: &str, unit: &str, key: &str) -> String {
scoped_secret_path_for_unit(ctx, pack, unit, key)
.expect("ok")
.expect("some")
}
#[test]
fn the_unit_scope_wins_over_the_bare_pack_scope() {
let ctx = tenant_ctx();
let unit = unit_uri(&ctx, "demo", "unit-a", "API_KEY");
let bare = scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare");
let secrets = MapSecrets::with(&[
(unit.as_str(), "unit-value"),
(bare.as_str(), "shared-value"),
]);
let manager: DynSecretsManager = secrets.clone();
let got =
read_pack_secret_blocking(&manager, &ctx, "demo", Some("unit-a"), "API_KEY").unwrap();
assert_eq!(got, b"unit-value".to_vec());
assert_eq!(
secrets.seen.lock().as_slice(),
&[unit],
"the bare scope must not be read once the unit scope hits"
);
}
#[test]
fn a_missing_unit_scope_falls_back_to_the_bare_pack_scope() {
let ctx = tenant_ctx();
let unit = unit_uri(&ctx, "demo", "unit-a", "API_KEY");
let bare = scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare");
let secrets = MapSecrets::with(&[(bare.as_str(), "shared-value")]);
let manager: DynSecretsManager = secrets.clone();
let got =
read_pack_secret_blocking(&manager, &ctx, "demo", Some("unit-a"), "API_KEY").unwrap();
assert_eq!(got, b"shared-value".to_vec());
assert_eq!(secrets.seen.lock().as_slice(), &[unit, bare]);
}
#[test]
fn two_units_of_one_pack_resolve_their_own_values() {
let ctx = tenant_ctx();
let a = unit_uri(&ctx, "demo", "unit-a", "API_KEY");
let b = unit_uri(&ctx, "demo", "unit-b", "API_KEY");
let bare = scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare");
assert_ne!(a, b);
let secrets = MapSecrets::with(&[
(a.as_str(), "token-a"),
(b.as_str(), "token-b"),
(bare.as_str(), "shared-value"),
]);
let manager: DynSecretsManager = secrets.clone();
for (unit, expected) in [("unit-a", "token-a"), ("unit-b", "token-b")] {
let got =
read_pack_secret_blocking(&manager, &ctx, "demo", Some(unit), "API_KEY").unwrap();
assert_eq!(got, expected.as_bytes().to_vec(), "unit {unit}");
}
}
#[test]
fn no_unit_reads_exactly_todays_address() {
let ctx = tenant_ctx();
let bare = scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare");
let secrets = MapSecrets::with(&[(bare.as_str(), "shared-value")]);
let manager: DynSecretsManager = secrets.clone();
let got = read_pack_secret_blocking(&manager, &ctx, "demo", None, "API_KEY").unwrap();
assert_eq!(got, b"shared-value".to_vec());
assert_eq!(secrets.seen.lock().as_slice(), &[bare]);
}
#[test]
fn a_total_miss_names_every_uri_tried() {
let ctx = tenant_ctx();
let secrets = MapSecrets::with(&[]);
let manager: DynSecretsManager = secrets.clone();
let err = read_pack_secret_blocking(&manager, &ctx, "demo", Some("unit-a"), "API_KEY")
.expect_err("no value anywhere");
let rendered = err.to_string();
assert!(
rendered.contains(&unit_uri(&ctx, "demo", "unit-a", "API_KEY"))
&& rendered
.contains(&scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare")),
"got: {rendered}"
);
}
#[test]
fn a_write_lands_at_the_unit_address_only() {
let ctx = tenant_ctx();
let secrets = MapSecrets::with(&[]);
let manager: DynSecretsManager = secrets.clone();
write_pack_secret_blocking(&manager, &ctx, "demo", Some("unit-a"), "API_KEY", b"fresh")
.unwrap();
assert_eq!(
secrets.written.lock().as_slice(),
&[(
unit_uri(&ctx, "demo", "unit-a", "API_KEY"),
b"fresh".to_vec()
)],
"a unit write must never touch the address other units read"
);
}
#[test]
fn a_write_with_no_unit_lands_at_the_bare_address() {
let ctx = tenant_ctx();
let secrets = MapSecrets::with(&[]);
let manager: DynSecretsManager = secrets.clone();
write_pack_secret_blocking(&manager, &ctx, "demo", None, "API_KEY", b"fresh").unwrap();
assert_eq!(
secrets.written.lock().as_slice(),
&[(
scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare"),
b"fresh".to_vec()
)]
);
}
#[test]
fn from_env_parses_broker() {
let b = SecretsBackend::broker_from_strings("broker", "http://localhost:9", "").unwrap();
assert!(matches!(b, SecretsBackend::Broker { .. }));
}
#[test]
fn from_env_broker_rejects_empty_endpoint() {
let err = SecretsBackend::broker_from_strings("broker", "", "").unwrap_err();
assert!(
err.to_string().contains("SECRETS_BROKER_ENDPOINT"),
"error was: {err}"
);
}
#[test]
fn from_config_parses_broker() {
let b = SecretsBackend::from_config(&SecretsBackendRefConfig {
kind: "broker".into(),
reference: Some("http://localhost:9".into()),
})
.unwrap();
assert!(matches!(b, SecretsBackend::Broker { .. }));
}
#[test]
fn backend_parsers_reject_unknown_kinds() {
let err =
SecretsBackend::from_env(Some("vault".into())).expect_err("backend should be rejected");
assert!(err.to_string().contains("unsupported SECRETS_BACKEND"));
let err = SecretsBackend::from_config(&SecretsBackendRefConfig {
kind: "vault".into(),
reference: None,
})
.expect_err("backend config should be rejected");
assert!(err.to_string().contains("unsupported secrets backend"));
}
#[test]
fn backend_parsers_accept_default_aliases() {
assert!(matches!(
SecretsBackend::from_env(Some("".into())).unwrap(),
SecretsBackend::Env
));
assert!(matches!(
SecretsBackend::from_config(&SecretsBackendRefConfig {
kind: "none".into(),
reference: None,
})
.unwrap(),
SecretsBackend::Env
));
}
struct CountingManager {
read_count: AtomicUsize,
}
impl CountingManager {
fn new() -> Arc<Self> {
Arc::new(Self {
read_count: AtomicUsize::new(0),
})
}
fn reads(&self) -> usize {
self.read_count.load(Ordering::SeqCst)
}
}
#[async_trait]
impl SecretsManager for CountingManager {
async fn read(&self, _path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
self.read_count.fetch_add(1, Ordering::SeqCst);
Ok(b"secret-value".to_vec())
}
async fn write(&self, _path: &str, _bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
Ok(())
}
async fn delete(&self, _path: &str) -> greentic_secrets_lib::Result<()> {
Ok(())
}
}
fn make_cached(inner: Arc<CountingManager>) -> CachingSecretsManager {
CachingSecretsManager {
inner: inner as DynSecretsManager,
cache: Mutex::new(LruCache::new(NonZeroUsize::new(64).unwrap())),
ttl: Duration::from_secs(300),
generation: AtomicU64::new(0),
}
}
#[tokio::test]
async fn cached_read_avoids_backend_on_second_call() {
let inner = CountingManager::new();
let cached = make_cached(Arc::clone(&inner));
let v1 = cached.read("secrets://dev/t/team/pack/key").await.unwrap();
let v2 = cached.read("secrets://dev/t/team/pack/key").await.unwrap();
assert_eq!(v1, v2);
assert_eq!(inner.reads(), 1, "second read should hit cache");
}
#[tokio::test]
async fn write_invalidates_cache() {
let inner = CountingManager::new();
let cached = make_cached(Arc::clone(&inner));
cached.read("secrets://dev/t/team/pack/key").await.unwrap();
assert_eq!(inner.reads(), 1);
cached
.write("secrets://dev/t/team/pack/key", b"new")
.await
.unwrap();
cached.read("secrets://dev/t/team/pack/key").await.unwrap();
assert_eq!(inner.reads(), 2, "read after write should bypass cache");
}
#[tokio::test]
async fn delete_invalidates_cache() {
let inner = CountingManager::new();
let cached = make_cached(Arc::clone(&inner));
cached.read("secrets://dev/t/team/pack/key").await.unwrap();
cached
.delete("secrets://dev/t/team/pack/key")
.await
.unwrap();
cached.read("secrets://dev/t/team/pack/key").await.unwrap();
assert_eq!(inner.reads(), 2, "read after delete should bypass cache");
}
#[tokio::test]
async fn expired_entry_triggers_backend_read() {
let inner = CountingManager::new();
let cached = CachingSecretsManager {
inner: Arc::clone(&inner) as DynSecretsManager,
cache: Mutex::new(LruCache::new(NonZeroUsize::new(64).unwrap())),
ttl: Duration::from_millis(1), generation: AtomicU64::new(0),
};
cached.read("secrets://dev/t/team/pack/key").await.unwrap();
std::thread::sleep(Duration::from_millis(5));
cached.read("secrets://dev/t/team/pack/key").await.unwrap();
assert_eq!(inner.reads(), 2, "expired entry should re-fetch");
}
struct GatedManager {
value: Mutex<Vec<u8>>,
started: tokio::sync::Notify,
release: tokio::sync::Notify,
first: AtomicUsize,
}
#[async_trait]
impl SecretsManager for GatedManager {
async fn read(&self, _path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
let snapshot = self.value.lock().clone();
if self.first.fetch_add(1, Ordering::SeqCst) == 0 {
self.started.notify_one();
self.release.notified().await;
}
Ok(snapshot)
}
async fn write(&self, _path: &str, bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
*self.value.lock() = bytes.to_vec();
Ok(())
}
async fn delete(&self, _path: &str) -> greentic_secrets_lib::Result<()> {
Ok(())
}
}
#[tokio::test]
async fn stale_read_does_not_repopulate_cache_after_write() {
let inner = Arc::new(GatedManager {
value: Mutex::new(b"old".to_vec()),
started: tokio::sync::Notify::new(),
release: tokio::sync::Notify::new(),
first: AtomicUsize::new(0),
});
let cached = Arc::new(CachingSecretsManager {
inner: Arc::clone(&inner) as DynSecretsManager,
cache: Mutex::new(LruCache::new(NonZeroUsize::new(8).unwrap())),
ttl: Duration::from_secs(300),
generation: AtomicU64::new(0),
});
let reader = {
let cached = Arc::clone(&cached);
tokio::spawn(async move { cached.read("secrets://dev/t/_/p/k").await })
};
inner.started.notified().await;
cached.write("secrets://dev/t/_/p/k", b"new").await.unwrap();
inner.release.notify_one();
let stale = reader.await.unwrap().unwrap();
assert_eq!(stale, b"old");
let fresh = cached.read("secrets://dev/t/_/p/k").await.unwrap();
assert_eq!(fresh, b"new", "stale value must not be cached");
}
#[test]
fn wrap_with_zero_ttl_returns_inner_directly() {
let inner: DynSecretsManager = CountingManager::new();
let ptr_before = Arc::as_ptr(&inner);
let wrapped = CachingSecretsManager::wrap_with(
Arc::clone(&inner),
Duration::ZERO,
NonZeroUsize::new(64).unwrap(),
);
let ptr_after = Arc::as_ptr(&wrapped);
assert_eq!(ptr_before, ptr_after);
}
}
#[cfg(test)]
mod pack_secret_error_tests {
use super::*;
use greentic_secrets_lib::SecretError;
fn candidates() -> Vec<String> {
vec!["secrets://a".to_string(), "secrets://b".to_string()]
}
#[test]
fn not_found_only_when_every_scope_is_not_found() {
let err = classify_pack_secret_failures(
&candidates(),
vec![
SecretError::NotFound("a".into()),
SecretError::NotFound("b".into()),
],
);
assert!(matches!(err, PackSecretError::NotFound(_)));
}
#[test]
fn permission_error_is_not_masked_by_a_later_not_found() {
let err = classify_pack_secret_failures(
&candidates(),
vec![
SecretError::Permission("no".into()),
SecretError::NotFound("b".into()),
],
);
assert!(matches!(err, PackSecretError::Denied(_)));
}
#[test]
fn words_like_missing_in_a_backend_message_do_not_become_not_found() {
let err = classify_pack_secret_failures(
&candidates(),
vec![
SecretError::Backend("config missing".into()),
SecretError::NotFound("b".into()),
],
);
assert!(matches!(err, PackSecretError::Backend(_)));
}
}