use std::fmt;
use rho_providers::credentials::CredentialStore;
use serde::{Deserialize, Serialize};
use url::{Host, Url};
use super::token_store::{self, StoredSet};
use crate::app::http_guard::validate_name;
pub(crate) const ACCOUNT: &str = "mcp-serve-webhooks";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub(crate) struct WebhookSet {
pub(crate) targets: Vec<WebhookTarget>,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct WebhookTarget {
pub(crate) name: String,
pub(crate) url: String,
pub(crate) secret: String,
pub(crate) tokens: Vec<String>,
}
impl fmt::Debug for WebhookTarget {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("WebhookTarget")
.field("name", &self.name)
.field("url", &self.url)
.field("tokens", &self.tokens)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error(
"token {token:?} may not use webhook {webhook:?}; it may use: {}",
list(usable)
)]
pub(crate) struct Unbound {
pub(crate) token: String,
pub(crate) webhook: String,
pub(crate) usable: Vec<String>,
}
fn list(names: &[String]) -> String {
if names.is_empty() {
return "(none)".to_owned();
}
names.join(", ")
}
impl StoredSet for WebhookSet {
const ACCOUNT: &'static str = ACCOUNT;
const WHAT: &'static str = "MCP server webhooks";
}
impl WebhookSet {
pub(crate) fn load(store: &dyn CredentialStore) -> anyhow::Result<Self> {
token_store::load(store)
}
pub(crate) fn upsert(
&mut self,
name: &str,
url: &str,
secret: &str,
tokens: &[String],
) -> anyhow::Result<()> {
validate_name("webhook", name)?;
let url = validate_url(url)?;
let secret = secret.trim();
if secret.is_empty() || secret.chars().any(char::is_control) {
anyhow::bail!("the webhook secret must be one non-empty line");
}
if tokens.is_empty() {
anyhow::bail!(
"a webhook needs at least one --token: the tokens whose watches may use it"
);
}
let mut bound: Vec<String> = Vec::new();
for token in tokens {
validate_name("token", token)?;
if !bound.contains(token) {
bound.push(token.clone());
}
}
let target = WebhookTarget {
name: name.to_owned(),
url: url.to_string(),
secret: secret.to_owned(),
tokens: bound,
};
match self.targets.iter_mut().find(|target| target.name == name) {
Some(existing) => *existing = target,
None => self.targets.push(target),
}
Ok(())
}
pub(crate) fn remove(&mut self, name: &str) -> bool {
let before = self.targets.len();
self.targets.retain(|target| target.name != name);
self.targets.len() != before
}
pub(crate) fn for_token(&self, token: &str, name: &str) -> Result<&WebhookTarget, Unbound> {
let bound = |target: &&WebhookTarget| target.tokens.iter().any(|bound| bound == token);
self.targets
.iter()
.filter(bound)
.find(|target| target.name == name)
.ok_or_else(|| Unbound {
token: token.to_owned(),
webhook: name.to_owned(),
usable: self
.targets
.iter()
.filter(bound)
.map(|target| target.name.clone())
.collect(),
})
}
}
pub(crate) fn validate_url(url: &str) -> anyhow::Result<Url> {
let parsed =
Url::parse(url).map_err(|error| anyhow::anyhow!("webhook URL {url:?}: {error}"))?;
if !parsed.username().is_empty() || parsed.password().is_some() {
anyhow::bail!(
"the webhook URL carries a user name or password; pipe the secret on stdin instead"
);
}
let loopback = match parsed.host() {
Some(Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
Some(Host::Ipv4(address)) => address.is_loopback(),
Some(Host::Ipv6(address)) => address.is_loopback(),
None => anyhow::bail!("webhook URL {url:?} names no host"),
};
match parsed.scheme() {
"https" => Ok(parsed),
"http" if loopback => Ok(parsed),
"http" => anyhow::bail!(
"webhook URL {url:?} must use https; plain http is allowed only to a loopback host"
),
scheme => anyhow::bail!("webhook URL {url:?} must use https, not {scheme}"),
}
}
#[cfg(test)]
#[path = "webhooks_tests.rs"]
mod tests;