use std::{collections::BTreeMap, sync::Arc};
use anyhow::Context;
use rho_providers::credentials::CredentialStore;
use super::{validate_identity, validate_secret_name};
const ACCOUNT_PREFIX: &str = "mcp-secret";
fn account_name(identity: &str, name: &str) -> String {
format!("{ACCOUNT_PREFIX}:{identity}:{name}")
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum StoredSecrets {
Ready(BTreeMap<String, String>),
Missing(Vec<String>),
}
pub(crate) async fn resolve(
store: Arc<dyn CredentialStore>,
identity: &str,
names: &[String],
) -> anyhow::Result<StoredSecrets> {
if names.is_empty() {
return Ok(StoredSecrets::Ready(BTreeMap::new()));
}
let identity = identity.to_owned();
let names = names.to_vec();
let (answer, answered) = tokio::sync::oneshot::channel();
let read = move || -> anyhow::Result<StoredSecrets> {
let mut values = BTreeMap::new();
let mut missing = Vec::new();
for name in names {
match store
.get_secret_fresh(&account_name(&identity, &name))
.with_context(|| format!("could not read MCP secret `{name}` of `{identity}`"))?
{
Some(value) => {
values.insert(name, value);
}
None => missing.push(name),
}
}
Ok(if missing.is_empty() {
StoredSecrets::Ready(values)
} else {
StoredSecrets::Missing(missing)
})
};
std::thread::Builder::new()
.name("rho-mcp-secrets".into())
.spawn(move || {
let _ = answer.send(read());
})
.context("could not start the MCP secret reader")?;
answered.await.context("MCP secret lookup panicked")?
}
pub(crate) fn store(
store: &dyn CredentialStore,
identity: &str,
name: &str,
value: &str,
) -> anyhow::Result<()> {
validate_identity(identity)?;
validate_secret_name(name)?;
if value.is_empty() {
anyhow::bail!("MCP secret `{name}` must not be empty");
}
store
.set_secret(&account_name(identity, name), value)
.with_context(|| format!("could not store MCP secret `{name}` of `{identity}`"))
}
pub(crate) fn delete(
store: &dyn CredentialStore,
identity: &str,
name: &str,
) -> anyhow::Result<bool> {
validate_identity(identity)?;
validate_secret_name(name)?;
store
.delete_secret(&account_name(identity, name))
.with_context(|| format!("could not delete MCP secret `{name}` of `{identity}`"))
}
#[cfg(test)]
#[path = "secrets_tests.rs"]
mod tests;