1use std::time::Duration;
16
17use nexo_broker::{AnyBroker, BrokerHandle, Message};
18use serde::{Deserialize, Serialize};
19use serde_json::{json, Value};
20
21const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
22
23pub const RESERVED_ADMIN_PREFIXES: &[&str] = &[
30 "nexo/admin/agents/",
31 "nexo/admin/credentials/",
32 "nexo/admin/pairing/",
33 "nexo/admin/llm/",
34 "nexo/admin/channels/",
35 "nexo/admin/tenants/",
36 "nexo/admin/memory/",
37 "nexo/admin/sessions/",
38 "nexo/admin/snapshots/",
39 "nexo/admin/policy/",
40];
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct PluginAdminResponse {
47 pub ok: bool,
49 #[serde(default)]
52 pub result: Value,
53 #[serde(default)]
55 pub error: String,
56}
57
58#[derive(Debug, Clone)]
59struct Route {
60 method_prefix: String,
61 broker_topic_prefix: String,
62 plugin_id: String,
63 timeout: Duration,
64}
65
66#[derive(Debug, Default)]
71pub struct PluginAdminRouter {
72 routes: std::sync::RwLock<Vec<Route>>,
73}
74
75impl PluginAdminRouter {
76 pub fn new() -> Self {
77 Self::default()
78 }
79
80 pub fn register(
84 &self,
85 plugin_id: &str,
86 method_prefix: &str,
87 broker_topic_prefix: &str,
88 timeout: Option<Duration>,
89 ) -> Result<(), AdminRouteRegistrationError> {
90 for reserved in RESERVED_ADMIN_PREFIXES {
91 if method_prefix == *reserved
92 || method_prefix.starts_with(reserved)
93 || reserved.starts_with(method_prefix)
94 {
95 return Err(AdminRouteRegistrationError::Reserved {
96 requested: method_prefix.to_string(),
97 reserved: (*reserved).to_string(),
98 });
99 }
100 }
101 let mut routes = self.routes.write().expect("router lock poisoned");
102 routes.retain(|r| r.plugin_id != plugin_id);
103 routes.push(Route {
104 method_prefix: method_prefix.to_string(),
105 broker_topic_prefix: broker_topic_prefix.to_string(),
106 plugin_id: plugin_id.to_string(),
107 timeout: timeout.unwrap_or(DEFAULT_TIMEOUT),
108 });
109 routes.sort_by(|a, b| {
110 b.method_prefix
111 .len()
112 .cmp(&a.method_prefix.len())
113 .then_with(|| a.plugin_id.cmp(&b.plugin_id))
114 });
115 Ok(())
116 }
117
118 pub fn match_method(&self, method: &str) -> Option<MatchInfo> {
124 let routes = self.routes.read().expect("router lock poisoned");
125 routes
126 .iter()
127 .find(|r| method.starts_with(&r.method_prefix))
128 .map(|r| MatchInfo {
129 plugin_id: r.plugin_id.clone(),
130 broker_topic_prefix: r.broker_topic_prefix.clone(),
131 method_prefix: r.method_prefix.clone(),
132 timeout: r.timeout,
133 })
134 }
135
136 pub fn is_empty(&self) -> bool {
137 self.routes.read().expect("router lock poisoned").is_empty()
138 }
139}
140
141#[derive(Debug, Clone)]
146pub struct MatchInfo {
147 pub plugin_id: String,
148 pub broker_topic_prefix: String,
149 pub method_prefix: String,
150 pub timeout: Duration,
151}
152
153pub fn method_to_broker_suffix(method: &str, prefix: &str) -> String {
158 method
159 .strip_prefix(prefix)
160 .unwrap_or(method)
161 .replace('/', ".")
162}
163
164pub async fn forward_request(
168 broker: &AnyBroker,
169 info: MatchInfo,
170 method: &str,
171 params: Value,
172) -> Result<PluginAdminResponse, PluginAdminForwardError> {
173 let suffix = method_to_broker_suffix(method, &info.method_prefix);
174 let topic = format!("{}.{suffix}", info.broker_topic_prefix);
175 let payload = json!({ "method": method, "params": params });
176 let msg = Message::new(topic.clone(), payload);
177 let reply = broker
178 .request(&topic, msg, info.timeout)
179 .await
180 .map_err(|e| PluginAdminForwardError::Broker(e.to_string()))?;
181 serde_json::from_value::<PluginAdminResponse>(reply.payload).map_err(|e| {
182 PluginAdminForwardError::ParseReply(format!(
183 "plugin {} returned malformed admin reply: {e}",
184 info.plugin_id
185 ))
186 })
187}
188
189#[derive(Debug, thiserror::Error)]
192pub enum AdminRouteRegistrationError {
193 #[error("method_prefix `{requested}` collides with daemon-reserved prefix `{reserved}`")]
194 Reserved { requested: String, reserved: String },
195}
196
197#[derive(Debug, thiserror::Error)]
199pub enum PluginAdminForwardError {
200 #[error("broker error: {0}")]
201 Broker(String),
202 #[error("plugin reply parse error: {0}")]
203 ParseReply(String),
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn match_method_uses_longest_prefix_first() {
212 let r = PluginAdminRouter::new();
213 r.register("wa", "nexo/admin/whatsapp/", "plugin.whatsapp.admin", None)
214 .unwrap();
215 r.register(
216 "wa_bot",
217 "nexo/admin/whatsapp/bot/",
218 "plugin.whatsapp.bot",
219 None,
220 )
221 .unwrap();
222 let m = r
223 .match_method("nexo/admin/whatsapp/bot/list")
224 .expect("matches");
225 assert_eq!(m.plugin_id, "wa_bot");
226 }
227
228 #[test]
229 fn match_method_falls_back_to_shorter_prefix() {
230 let r = PluginAdminRouter::new();
231 r.register("wa", "nexo/admin/whatsapp/", "plugin.whatsapp.admin", None)
232 .unwrap();
233 r.register(
234 "wa_bot",
235 "nexo/admin/whatsapp/bot/",
236 "plugin.whatsapp.bot",
237 None,
238 )
239 .unwrap();
240 let m = r
241 .match_method("nexo/admin/whatsapp/session/qr")
242 .expect("matches");
243 assert_eq!(m.plugin_id, "wa");
244 }
245
246 #[test]
247 fn match_method_returns_none_on_miss() {
248 let r = PluginAdminRouter::new();
249 r.register("wa", "nexo/admin/whatsapp/", "plugin.whatsapp.admin", None)
250 .unwrap();
251 assert!(r.match_method("nexo/admin/agents/list").is_none());
252 }
253
254 #[test]
255 fn register_rejects_reserved_prefixes() {
256 let r = PluginAdminRouter::new();
257 for reserved in RESERVED_ADMIN_PREFIXES {
258 let result = r.register("evil", reserved, "plugin.evil", None);
259 assert!(
260 matches!(result, Err(AdminRouteRegistrationError::Reserved { .. })),
261 "expected rejection for `{reserved}`",
262 );
263 }
264 }
265
266 #[test]
267 fn register_rejects_subpath_of_reserved() {
268 let r = PluginAdminRouter::new();
269 let result = r.register("evil", "nexo/admin/agents/sneaky/", "plugin.evil", None);
270 assert!(matches!(
271 result,
272 Err(AdminRouteRegistrationError::Reserved { .. })
273 ));
274 }
275
276 #[test]
277 fn register_rejects_super_prefix_of_reserved() {
278 let r = PluginAdminRouter::new();
283 let result = r.register("evil", "nexo/admin/", "plugin.evil", None);
284 assert!(matches!(
285 result,
286 Err(AdminRouteRegistrationError::Reserved { .. })
287 ));
288 }
289
290 #[test]
291 fn method_to_broker_suffix_replaces_slashes_with_dots() {
292 let suffix =
293 method_to_broker_suffix("nexo/admin/whatsapp/bot/list", "nexo/admin/whatsapp/");
294 assert_eq!(suffix, "bot.list");
295 }
296
297 #[test]
298 fn method_to_broker_suffix_falls_back_when_prefix_missing() {
299 let suffix =
302 method_to_broker_suffix("nexo/admin/whatsapp/bot/list", "nexo/admin/telegram/");
303 assert_eq!(suffix, "nexo.admin.whatsapp.bot.list");
304 }
305
306 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
307 async fn forward_request_returns_broker_error_with_no_subscriber() {
308 let broker = AnyBroker::Local(nexo_broker::LocalBroker::new());
309 let router = PluginAdminRouter::new();
310 router
311 .register(
312 "wa",
313 "nexo/admin/whatsapp/",
314 "plugin.whatsapp.admin",
315 Some(Duration::from_millis(100)),
316 )
317 .unwrap();
318 let info = router.match_method("nexo/admin/whatsapp/bot/list").unwrap();
319 let result =
320 forward_request(&broker, info, "nexo/admin/whatsapp/bot/list", json!({})).await;
321 assert!(matches!(result, Err(PluginAdminForwardError::Broker(_))));
322 }
323}