use std::cell::RefCell;
use std::collections::HashMap;
use serde::Deserialize;
use serde_json::Value;
use crate::abi::{read_bytes, respond_err, respond_err_code, respond_ok};
use crate::host::{HttpRequest, HttpResponse, OAuthFetchRequest, SelfInfo, UploadRequest};
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Scopes {
#[serde(default)]
pub http_hosts: Vec<String>,
#[serde(default)]
pub config_keys: Vec<String>,
#[serde(default)]
pub kv: bool,
#[serde(default)]
pub core: Vec<String>,
#[serde(default)]
pub oauth: bool,
#[serde(default)]
pub persistent_connection: Option<PersistentConnectionScope>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct PersistentConnectionScope {
#[serde(default)]
pub transport: String,
#[serde(default)]
pub url_config_key: String,
}
#[derive(Deserialize)]
struct ManifestFile {
#[serde(default)]
scopes: Scopes,
}
const CORE_OPS: &[(&str, &[&str], &[&str])] = &[
("ticket_types", &["list"], &[]),
("ticket_statuses", &["list"], &[]),
("ticket_priorities", &["list"], &[]),
("tags", &["list", "for_ticket"], &["add_to_ticket", "remove_from_ticket"]),
("users", &["list", "get", "by_email"], &["upsert"]),
("organizations", &["list", "get", "by_domain", "members"], &["upsert"]),
("teams", &["list", "members"], &[]),
("sla_policies", &["list", "for_priority"], &[]),
("custom_fields", &["list"], &[]),
("business_hours", &["get"], &[]),
(
"tickets",
&["get", "list_by_requester", "list_by_organization", "messages"],
&["add_note", "create", "update"],
),
];
type HttpResponder = Box<dyn Fn(&HttpRequest) -> Result<HttpResponse, String>>;
type CoreResponder = Box<dyn Fn(&str, &str, &Value) -> Result<Value, String>>;
type OAuthResponder = Box<dyn Fn(&OAuthFetchRequest) -> Result<HttpResponse, String>>;
type UploadResponder = Box<dyn Fn(&UploadRequest) -> Result<HttpResponse, String>>;
type WSResponder = Box<dyn Fn(&str) -> Result<(), String>>;
#[derive(Default)]
pub struct MockHost {
scopes: Scopes,
config: HashMap<String, String>,
kv: HashMap<String, String>,
core: HashMap<(String, String), Value>,
http: Option<HttpResponder>,
core_fn: Option<CoreResponder>,
oauth: Option<OAuthResponder>,
upload: Option<UploadResponder>,
allowed_attachments: Vec<String>,
self_info: SelfInfo,
logs: Vec<String>,
ws: Option<WSResponder>,
ws_frames: Vec<String>,
}
impl MockHost {
pub fn new() -> Self {
Self::default()
}
pub fn from_manifest(manifest_toml: &str) -> Self {
let parsed: ManifestFile = toml::from_str(manifest_toml).expect("MockHost::from_manifest: invalid manifest TOML");
Self { scopes: parsed.scopes, ..Self::default() }
}
pub fn scopes(mut self, scopes: Scopes) -> Self {
self.scopes = scopes;
self
}
pub fn config(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.config.insert(key.into(), value.into());
self
}
pub fn kv(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.kv.insert(key.into(), value.into());
self
}
pub fn upload(mut self, allowed_attachment_ids: &[&str], f: impl Fn(&UploadRequest) -> Result<HttpResponse, String> + 'static) -> Self {
self.allowed_attachments = allowed_attachment_ids.iter().map(|s| s.to_string()).collect();
self.upload = Some(Box::new(f));
self
}
pub fn self_info(mut self, info: SelfInfo) -> Self {
self.self_info = info;
self
}
pub fn http<F>(mut self, f: F) -> Self
where
F: Fn(&HttpRequest) -> Result<HttpResponse, String> + 'static,
{
self.http = Some(Box::new(f));
self
}
pub fn core(mut self, resource: impl Into<String>, action: impl Into<String>, data: Value) -> Self {
self.core.insert((resource.into(), action.into()), data);
self
}
pub fn core_fn<F>(mut self, f: F) -> Self
where
F: Fn(&str, &str, &Value) -> Result<Value, String> + 'static,
{
self.core_fn = Some(Box::new(f));
self
}
pub fn oauth_fetch<F>(mut self, f: F) -> Self
where
F: Fn(&OAuthFetchRequest) -> Result<HttpResponse, String> + 'static,
{
self.oauth = Some(Box::new(f));
self
}
pub fn ws_send<F>(mut self, f: F) -> Self
where
F: Fn(&str) -> Result<(), String> + 'static,
{
self.ws = Some(Box::new(f));
self
}
pub fn install(self) -> MockGuard {
CURRENT.with(|c| {
let previous = c.borrow_mut().replace(self);
MockGuard { previous: RefCell::new(previous) }
})
}
}
pub struct MockGuard {
previous: RefCell<Option<MockHost>>,
}
impl MockGuard {
pub fn logs(&self) -> Vec<String> {
with_host(|h| h.logs.clone()).unwrap_or_default()
}
pub fn kv(&self) -> HashMap<String, String> {
with_host(|h| h.kv.clone()).unwrap_or_default()
}
pub fn ws_frames_sent(&self) -> Vec<String> {
with_host(|h| h.ws_frames.clone()).unwrap_or_default()
}
}
impl Drop for MockGuard {
fn drop(&mut self) {
let previous = self.previous.borrow_mut().take();
CURRENT.with(|c| {
*c.borrow_mut() = previous;
});
}
}
thread_local! {
static CURRENT: RefCell<Option<MockHost>> = const { RefCell::new(None) };
}
fn with_host<T>(f: impl FnOnce(&mut MockHost) -> T) -> Option<T> {
CURRENT.with(|c| c.borrow_mut().as_mut().map(f))
}
fn no_host() -> u64 {
respond_err("no MockHost is installed on this thread — call MockHost::new().install() first (see salamandr_plugin_sdk::testing)")
}
fn host_allowed(allowed: &[String], host: &str) -> bool {
let host = host.to_lowercase();
allowed.iter().any(|entry| {
let entry = entry.to_lowercase();
match entry.strip_prefix('*') {
Some(suffix) if suffix.starts_with('.') => host.ends_with(suffix) && host.len() > suffix.len(),
_ => entry == host,
}
})
}
fn host_of(url: &str) -> Option<String> {
let rest = url.split_once("://")?.1;
let authority = rest.split(['/', '?', '#']).next()?;
let hostport = authority.rsplit_once('@').map(|(_, h)| h).unwrap_or(authority);
let host = match hostport.strip_prefix('[') {
Some(rest) => rest.split_once(']')?.0.to_string(),
None => hostport.split(':').next()?.to_string(),
};
(!host.is_empty()).then_some(host)
}
fn core_op_kind(resource: &str, action: &str) -> Result<bool, String> {
let Some((_, reads, writes)) = CORE_OPS.iter().find(|(r, _, _)| *r == resource) else {
let known: Vec<&str> = CORE_OPS.iter().map(|(r, _, _)| *r).collect();
return Err(format!("unknown core resource {resource:?} (known: {})", known.join(", ")));
};
if writes.contains(&action) {
return Ok(true);
}
if reads.contains(&action) {
return Ok(false);
}
let mut known: Vec<&str> = reads.to_vec();
known.extend_from_slice(writes);
Err(format!(
"core resource {resource:?} has no action {action:?} (known: {})",
known.join(", ")
))
}
pub(crate) unsafe extern "C" fn host_log(ptr: u32, len: u32) {
let msg = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
with_host(|h| h.logs.push(msg));
}
pub(crate) unsafe extern "C" fn host_http_fetch(ptr: u32, len: u32) -> u64 {
let raw = read_bytes(ptr, len);
let req: HttpRequest = match serde_json::from_slice(raw) {
Ok(v) => v,
Err(e) => return respond_err(&format!("invalid request JSON: {e}")),
};
let result = with_host(|h| {
if h.scopes.http_hosts.is_empty() {
return Err("this extension was not granted the http scope".to_string());
}
let Some(host) = host_of(&req.url) else {
return Err("invalid url".to_string());
};
if !host_allowed(&h.scopes.http_hosts, &host) {
return Err(format!("host {host:?} is not in this extension's granted http_hosts"));
}
match &h.http {
Some(responder) => responder(&req),
None => Err(format!(
"MockHost has no HTTP responder installed, but the plugin called {} {} — add .http(|req| ...)",
req.method, req.url
)),
}
});
match result {
None => no_host(),
Some(Err(msg)) => respond_err(&msg),
Some(Ok(resp)) => respond_ok(&resp),
}
}
pub(crate) unsafe extern "C" fn host_self() -> u64 {
match with_host(|h| h.self_info.clone()) {
None => no_host(),
Some(info) => respond_ok(&info),
}
}
pub(crate) unsafe extern "C" fn host_http_upload(ptr: u32, len: u32) -> u64 {
let raw = read_bytes(ptr, len);
let req: UploadRequest = match serde_json::from_slice(raw) {
Ok(v) => v,
Err(e) => return respond_err(&format!("invalid request JSON: {e}")),
};
let result = with_host(|h| {
if h.scopes.http_hosts.is_empty() {
return Err("this extension was not granted the http scope".to_string());
}
let Some(host) = host_of(&req.url) else {
return Err("invalid url".to_string());
};
if !host_allowed(&h.scopes.http_hosts, &host) {
return Err(format!("host {host:?} is not in this extension's granted http_hosts"));
}
if !h.allowed_attachments.iter().any(|id| *id == req.attachment_id) {
return Err("this attachment is not one of the files on the message being delivered".to_string());
}
match &h.upload {
Some(responder) => responder(&req),
None => Err(format!(
"MockHost has no upload responder installed, but the plugin uploaded to {} — add .upload(&[ids], |req| ...)",
req.url
)),
}
});
match result {
None => no_host(),
Some(Err(msg)) => respond_err(&msg),
Some(Ok(resp)) => respond_ok(&resp),
}
}
pub(crate) unsafe extern "C" fn host_oauth_fetch(ptr: u32, len: u32) -> u64 {
let raw = read_bytes(ptr, len);
let req: OAuthFetchRequest = match serde_json::from_slice(raw) {
Ok(v) => v,
Err(e) => return respond_err(&format!("invalid request JSON: {e}")),
};
let result = with_host(|h| {
if !h.scopes.oauth {
return Err("this extension was not granted the oauth scope".to_string());
}
if req.headers.keys().any(|k| k.eq_ignore_ascii_case("authorization")) {
return Err(r#"the "Authorization" header is set by the host, not the guest"#.to_string());
}
let Some(host) = host_of(&req.url) else {
return Err("invalid url".to_string());
};
if !host_allowed(&h.scopes.http_hosts, &host) {
return Err(format!("host {host:?} is not in this extension's granted http_hosts"));
}
match &h.oauth {
Some(responder) => responder(&req),
None => Err(format!(
"MockHost has no oauth_fetch responder installed, but the plugin called {} {} — add .oauth_fetch(|req| ...)",
req.method, req.url
)),
}
});
match result {
None => no_host(),
Some(Err(msg)) => respond_err(&msg),
Some(Ok(resp)) => respond_ok(&resp),
}
}
pub(crate) unsafe extern "C" fn host_get_config(ptr: u32, len: u32) -> u64 {
let key = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
let result = with_host(|h| {
if !h.scopes.config_keys.contains(&key) {
return Err((
format!("config key {key:?} was not declared in this extension's manifest"),
String::new(),
));
}
h.config
.get(&key)
.cloned()
.ok_or_else(|| ("not set".to_string(), crate::error::code::NOT_SET.to_string()))
});
match result {
None => no_host(),
Some(Err((msg, code))) => respond_err_code(&msg, &code),
Some(Ok(value)) => respond_ok(&value),
}
}
fn strip_tags(html: &str) -> String {
let mut out = String::with_capacity(html.len());
let mut in_tag = false;
for c in html.chars() {
match c {
'<' => in_tag = true,
'>' => in_tag = false,
_ if !in_tag => out.push(c),
_ => {}
}
}
out
}
pub(crate) unsafe extern "C" fn host_richtext_to_markdown(ptr: u32, len: u32) -> u64 {
let html = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
respond_ok(&strip_tags(&html))
}
pub(crate) unsafe extern "C" fn host_richtext_to_jira_wiki(ptr: u32, len: u32) -> u64 {
let html = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
respond_ok(&strip_tags(&html))
}
pub(crate) unsafe extern "C" fn host_kv_get(ptr: u32, len: u32) -> u64 {
let key = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
let result = with_host(|h| {
if !h.scopes.kv {
return Err(("this extension was not granted the kv scope".to_string(), String::new()));
}
h.kv.get(&key)
.cloned()
.ok_or_else(|| ("not found".to_string(), crate::error::code::NOT_FOUND.to_string()))
});
match result {
None => no_host(),
Some(Err((msg, code))) => respond_err_code(&msg, &code),
Some(Ok(value)) => respond_ok(&value),
}
}
pub(crate) unsafe extern "C" fn host_kv_set(key_ptr: u32, key_len: u32, val_ptr: u32, val_len: u32) -> u64 {
let key = String::from_utf8_lossy(read_bytes(key_ptr, key_len)).into_owned();
let value = String::from_utf8_lossy(read_bytes(val_ptr, val_len)).into_owned();
let result = with_host(|h| {
if !h.scopes.kv {
return Err("this extension was not granted the kv scope".to_string());
}
h.kv.insert(key, value);
Ok(())
});
match result {
None => no_host(),
Some(Err(msg)) => respond_err(&msg),
Some(Ok(())) => respond_ok(&()),
}
}
pub(crate) unsafe extern "C" fn host_kv_delete(ptr: u32, len: u32) -> u64 {
let key = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
let result = with_host(|h| {
if !h.scopes.kv {
return Err("this extension was not granted the kv scope".to_string());
}
h.kv.remove(&key);
Ok(())
});
match result {
None => no_host(),
Some(Err(msg)) => respond_err(&msg),
Some(Ok(())) => respond_ok(&()),
}
}
pub(crate) unsafe extern "C" fn host_ws_send(ptr: u32, len: u32) -> u64 {
let frame = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
let result = with_host(|h| {
if h.scopes.persistent_connection.is_none() {
return Err("this extension was not granted the persistent_connection scope".to_string());
}
let outcome = match &h.ws {
Some(responder) => responder(&frame),
None => Ok(()),
};
h.ws_frames.push(frame.clone());
outcome
});
match result {
None => no_host(),
Some(Err(msg)) => respond_err(&msg),
Some(Ok(())) => respond_ok(&()),
}
}
pub(crate) unsafe extern "C" fn host_kv_list(ptr: u32, len: u32) -> u64 {
let prefix = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
let result = with_host(|h| {
if !h.scopes.kv {
return Err("this extension was not granted the kv scope".to_string());
}
let mut keys: Vec<String> = h.kv.keys().filter(|k| k.starts_with(&prefix)).cloned().collect();
keys.sort();
Ok(keys)
});
match result {
None => no_host(),
Some(Err(msg)) => respond_err(&msg),
Some(Ok(keys)) => respond_ok(&keys),
}
}
pub(crate) unsafe extern "C" fn host_core(ptr: u32, len: u32) -> u64 {
#[derive(Deserialize)]
struct CoreRequest {
resource: String,
action: String,
#[serde(default)]
params: Value,
}
let raw = read_bytes(ptr, len);
let req: CoreRequest = match serde_json::from_slice(raw) {
Ok(v) => v,
Err(e) => return respond_err(&format!("invalid request JSON: {e}")),
};
let result = with_host(|h| {
let write = core_op_kind(&req.resource, &req.action).map_err(|m| (m, String::new()))?;
let needed = format!("{}:{}", req.resource, if write { "write" } else { "read" });
if !h.scopes.core.iter().any(|s| *s == needed) {
return Err((
format!("this extension was not granted the {needed:?} core scope"),
String::new(),
));
}
if let Some(data) = h.core.get(&(req.resource.clone(), req.action.clone())) {
return Ok(data.clone());
}
match &h.core_fn {
Some(f) => f(&req.resource, &req.action, &req.params).map_err(|m| (m, String::new())),
None => Err(("not found".to_string(), crate::error::code::NOT_FOUND.to_string())),
}
});
match result {
None => no_host(),
Some(Err((msg, code))) => respond_err_code(&msg, &code),
Some(Ok(data)) => respond_ok(&data),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{core, get_config, http_fetch, kv_get, kv_set, ws_send};
fn manifest() -> &'static str {
r#"
name = "test-plugin"
version = "0.1.0"
kind = "crm"
entrypoints = ["fetch_context"]
[scopes]
http_hosts = ["api.acme.com", "*.vendor.com"]
config_keys = ["api_key"]
kv = true
core = ["users:read", "tags:write"]
"#
}
#[test]
fn scopes_come_from_the_manifest() {
let _guard = MockHost::from_manifest(manifest())
.config("api_key", "k")
.http(|_| Ok(HttpResponse { status: 204, ..Default::default() }))
.install();
assert_eq!(get_config("api_key").unwrap().as_deref(), Some("k"));
assert_eq!(http_fetch(HttpRequest::get("https://api.acme.com/x")).unwrap().status, 204);
assert_eq!(http_fetch(HttpRequest::get("https://shop.vendor.com/x")).unwrap().status, 204);
}
#[test]
fn an_undeclared_config_key_is_refused_even_when_seeded() {
let _guard = MockHost::from_manifest(manifest()).config("other", "v").install();
let err = get_config("other").expect_err("undeclared key must be refused");
assert!(err.to_string().contains("was not declared"), "{err}");
}
#[test]
fn an_unset_declared_key_is_none_not_an_error() {
let _guard = MockHost::from_manifest(manifest()).install();
assert_eq!(get_config("api_key").unwrap(), None);
}
#[test]
fn a_host_outside_the_allow_list_is_refused() {
let _guard = MockHost::from_manifest(manifest())
.http(|_| Ok(HttpResponse { status: 200, ..Default::default() }))
.install();
let err = http_fetch(HttpRequest::get("https://evil.example.com/x")).expect_err("must be refused");
assert!(err.to_string().contains("granted http_hosts"), "{err}");
let err = http_fetch(HttpRequest::get("https://vendor.com/x")).expect_err("bare domain must be refused");
assert!(err.to_string().contains("granted http_hosts"), "{err}");
}
#[test]
fn kv_round_trips_and_is_visible_to_the_test() {
let guard = MockHost::from_manifest(manifest()).kv("seeded", "1").install();
assert_eq!(kv_get("seeded").unwrap().as_deref(), Some("1"));
assert_eq!(kv_get("missing").unwrap(), None);
kv_set("written", "2").unwrap();
assert_eq!(guard.kv().get("written").map(String::as_str), Some("2"));
}
#[test]
fn core_reads_the_canned_page() {
let _guard = MockHost::from_manifest(manifest())
.core(
"users",
"by_email",
serde_json::json!({"id": "u1", "email": "ada@example.com", "name": "Ada", "role": "customer"}),
)
.install();
let user = core::user_by_email("ada@example.com").unwrap().expect("some user");
assert_eq!(user.email, "ada@example.com");
}
#[test]
fn core_without_the_scope_is_refused() {
let _guard = MockHost::from_manifest(manifest()).install();
let err = core::teams(core::Paging::default()).expect_err("teams:read was never granted");
assert!(err.to_string().contains("teams:read"), "{err}");
}
#[test]
fn core_read_scope_does_not_imply_write() {
let _guard = MockHost::from_manifest(manifest()).install();
let err = core::tags().expect_err("tags:read was never granted");
assert!(err.to_string().contains("tags:read"), "{err}");
}
#[test]
fn an_unknown_core_action_names_the_real_ones() {
let _guard = MockHost::from_manifest(manifest()).install();
let err = crate::host::core_call::<(), serde_json::Value>("users", "by_phone", None).expect_err("no such action");
assert!(err.to_string().contains("has no action"), "{err}");
}
#[test]
fn a_missing_core_answer_reads_as_not_found() {
let _guard = MockHost::from_manifest(manifest()).install();
assert!(core::user("u1").unwrap().is_none());
}
#[test]
fn logs_are_captured() {
let guard = MockHost::new().install();
crate::log("hello");
assert_eq!(guard.logs(), vec!["hello".to_string()]);
}
#[test]
fn richtext_conversion_round_trips_through_the_mock() {
let _guard = MockHost::new().install();
let md = crate::richtext_to_markdown("<p>Hello <strong>world</strong></p>").expect("richtext_to_markdown");
assert_eq!(md, "Hello world");
let wiki = crate::richtext_to_jira_wiki("<p>Hello <strong>world</strong></p>").expect("richtext_to_jira_wiki");
assert_eq!(wiki, "Hello world");
}
#[test]
fn no_installed_host_says_so() {
let err = get_config("api_key").expect_err("no host installed");
assert!(err.to_string().contains("no MockHost is installed"), "{err}");
}
fn persistent_connection_manifest() -> &'static str {
r#"
name = "test-persistent-plugin"
version = "0.1.0"
kind = "chatops"
dialect = "markdown"
entrypoints = ["chatops_post_root", "chatops_post_reply", "persistent_connect", "persistent_receive"]
[scopes]
config_keys = ["ws_url"]
persistent_connection = { transport = "websocket", url_config_key = "ws_url" }
"#
}
#[test]
fn ws_send_without_the_scope_is_refused() {
let _guard = MockHost::from_manifest(manifest()).install();
let err = ws_send("hello").expect_err("persistent_connection was never granted");
assert!(err.to_string().contains("persistent_connection"), "{err}");
}
#[test]
fn ws_send_delivers_and_is_recorded() {
let guard = MockHost::from_manifest(persistent_connection_manifest()).install();
ws_send(r#"{"type":"hello"}"#).expect("ws_send");
assert_eq!(guard.ws_frames_sent(), vec![r#"{"type":"hello"}"#.to_string()]);
}
#[test]
fn ws_send_responder_can_reject_a_frame() {
let _guard = MockHost::from_manifest(persistent_connection_manifest())
.ws_send(|frame| {
if frame.contains("bad") {
return Err("malformed handshake".to_string());
}
Ok(())
})
.install();
let err = ws_send("bad frame").expect_err("responder rejected it");
assert!(err.to_string().contains("malformed handshake"), "{err}");
ws_send("good frame").expect("responder accepts this one");
}
}