Skip to main content

cpa_plugin/
management.rs

1//! Plugin-owned Management API and resource routes (internal/pluginhost/management.go,
2//! internal/htmlsanitize).
3//!
4//! Plugins declare exact routes under `/v0/management/` (management-authenticated) and
5//! GET resources under `/v0/resource/plugins/<id>/` (unauthenticated, browser
6//! navigable). Higher-priority plugins win collisions; built-in routes always win.
7
8use std::collections::{BTreeMap, HashSet};
9
10use bytes::Bytes;
11use cpa_common::json::GoValue;
12
13use crate::abi::{self, method};
14use crate::api::{
15    ManagementRegistrationRequest, ManagementRegistrationResponse, ManagementResponse, ManagementRoute, ResourceRoute,
16};
17use crate::callbacks::RequestScope;
18use crate::gojson::{Header, NonNilBytes};
19use crate::host::Host;
20
21pub const MANAGEMENT_BASE: &str = "/v0/management";
22pub const RESOURCE_BASE: &str = "/v0/resource/plugins";
23const LEGACY_PLUGIN_PREFIX: &str = "/plugins";
24
25#[derive(Debug, Clone, PartialEq)]
26pub struct RouteRecord {
27    pub plugin_id: String,
28    pub path: std::path::PathBuf,
29    pub version: String,
30    pub schema_version: u32,
31    pub route: ManagementRoute,
32}
33
34#[derive(Debug, Clone, PartialEq)]
35pub struct ResourceRecord {
36    pub plugin_id: String,
37    pub path: std::path::PathBuf,
38    pub version: String,
39    pub route: ResourceRoute,
40}
41
42/// Go `managementRouteKey`.
43pub fn route_key(method: &str, path: &str) -> String {
44    format!("{} {}", method.trim().to_ascii_uppercase(), path.trim())
45}
46
47fn has_space(s: &str) -> bool {
48    s.contains([' ', '\t', '\r', '\n'])
49}
50
51/// Go `normalizeManagementRoute`: `(METHOD, /v0/management/...)`.
52pub fn normalize_route(route: &ManagementRoute) -> Option<(String, String)> {
53    let mut method = route.method.trim().to_ascii_uppercase();
54    if method.is_empty() {
55        method = "GET".into();
56    }
57    if has_space(&method) {
58        return None;
59    }
60    let mut path = route.path.trim().to_owned();
61    if path.is_empty() {
62        return None;
63    }
64    if !path.starts_with('/') {
65        path.insert(0, '/');
66    }
67    if path.starts_with(&format!("{MANAGEMENT_BASE}/")) {
68        path = path[MANAGEMENT_BASE.len()..].to_owned();
69    }
70    let path = path.trim_end_matches('/');
71    if path.is_empty() {
72        return None;
73    }
74    let full = format!("{MANAGEMENT_BASE}{path}");
75    if !full.starts_with(&format!("{MANAGEMENT_BASE}/")) || has_space(&full) || full.contains(':') || full.contains('*')
76    {
77        return None;
78    }
79    Some((method, full))
80}
81
82/// Go `normalizeResourceRoute`.
83pub fn normalize_resource(plugin_id: &str, route: &ResourceRoute) -> Option<String> {
84    let plugin_id = plugin_id.trim();
85    if plugin_id.is_empty() {
86        return None;
87    }
88    let mut path = route.path.trim().to_owned();
89    if path.is_empty() {
90        return None;
91    }
92    if !path.starts_with('/') {
93        path.insert(0, '/');
94    }
95    let base = format!("{RESOURCE_BASE}/{plugin_id}");
96    let legacy = format!("{LEGACY_PLUGIN_PREFIX}/{plugin_id}");
97    if path.starts_with(&format!("{base}/")) {
98        path = path[base.len()..].to_owned();
99    } else if path.starts_with(&format!("{legacy}/")) {
100        path = path[legacy.len()..].to_owned();
101    }
102    let path = path.trim_end_matches('/');
103    if path.is_empty() {
104        return None;
105    }
106    let full = format!("{base}{path}");
107    if !full.starts_with(&format!("{base}/"))
108        || has_space(&full)
109        || full.contains(':')
110        || full.contains('*')
111        || full.contains("..")
112    {
113        return None;
114    }
115    Some(full)
116}
117
118/// A response for the HTTP layer to write.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct Reply {
121    pub status: u16,
122    /// In the plugin's order; names as the plugin spelled them (Go canonicalizes on
123    /// write).
124    pub headers: Vec<(String, String)>,
125    pub body: Bytes,
126}
127
128impl Reply {
129    /// Go `http.Error`.
130    pub fn error(status: u16, message: &str) -> Self {
131        Self {
132            status,
133            headers: vec![
134                ("Content-Type".into(), "text/plain; charset=utf-8".into()),
135                ("X-Content-Type-Options".into(), "nosniff".into()),
136            ],
137            body: Bytes::from(format!("{message}\n")),
138        }
139    }
140
141    fn from_plugin(resp: ManagementResponse) -> Self {
142        let headers = resp
143            .headers
144            .into_iter()
145            .flat_map(|(name, values)| values.into_iter().map(move |v| (name.clone(), v)))
146            .collect();
147        Self {
148            status: if resp.status_code == 0 {
149                200
150            } else {
151                u16::try_from(resp.status_code).unwrap_or(500)
152            },
153            headers,
154            body: resp.body,
155        }
156    }
157}
158
159/// One inbound management or resource request.
160#[derive(Debug, Clone, Default)]
161pub struct Inbound {
162    pub method: String,
163    /// The decoded URL path.
164    pub path: String,
165    /// Go canonical header names.
166    pub headers: Header,
167    pub query: Header,
168    pub body: Bytes,
169    pub scope: RequestScope,
170}
171
172crate::go_struct! {
173    /// `rpcManagementRequest`.
174    pub struct ManagementCall("pluginhost.rpcManagementRequest") {
175        "Method" => method: String,
176        "Path" => path: String,
177        "Headers" => headers: Header,
178        "Query" => query: Header,
179        /// Go reads management bodies with `io.ReadAll` (non-nil); resource requests
180        /// carry none (nil).
181        "Body" => body: Option<NonNilBytes>,
182        "host_callback_id" omitempty => host_callback_id: String,
183    }
184}
185
186impl Host {
187    /// Go `RegisterManagementRoutes`: asks every active plugin with the capability for its
188    /// routes and rebuilds both tables. `reserved` holds built-in `METHOD /path` keys.
189    pub async fn register_management_routes(&self, reserved: &HashSet<String>) {
190        let mut routes: BTreeMap<String, RouteRecord> = BTreeMap::new();
191        let mut resources: BTreeMap<String, ResourceRecord> = BTreeMap::new();
192        for record in self.active_records() {
193            if !record.plugin.caps.management_api || self.is_fused(&record.id) || !self.record_current(&record) {
194                continue;
195            }
196            let request = ManagementRegistrationRequest {
197                plugin: record.plugin.metadata.clone(),
198                base_path: MANAGEMENT_BASE.into(),
199                resource_base_path: format!("{RESOURCE_BASE}/{}", record.id),
200            };
201            let resp: ManagementRegistrationResponse =
202                match self.call(&record, method::MANAGEMENT_REGISTER, &request).await {
203                    Ok(resp) => resp,
204                    Err(e) => {
205                        tracing::warn!("pluginhost: management registrar {} failed: {e}", record.id);
206                        continue;
207                    }
208                };
209            let register_resource = |resources: &mut BTreeMap<String, ResourceRecord>, route: ResourceRoute| -> bool {
210                let Some(path) = normalize_resource(&record.id, &route) else {
211                    return false;
212                };
213                let key = route_key("GET", &path);
214                if resources.contains_key(&key) {
215                    tracing::warn!(
216                        "pluginhost: plugin {} resource route {key} conflicts with a higher-priority plugin and was skipped",
217                        record.id
218                    );
219                    return true;
220                }
221                resources.insert(
222                    key,
223                    ResourceRecord {
224                        plugin_id: record.id.clone(),
225                        path: record.path.clone(),
226                        version: record.version.clone(),
227                        route: ResourceRoute { path, ..route },
228                    },
229                );
230                true
231            };
232            for item in resp.routes {
233                let Some((method, path)) = normalize_route(&item) else {
234                    tracing::warn!(
235                        "pluginhost: plugin {} declared invalid management route {} {}",
236                        record.id,
237                        item.method,
238                        item.path
239                    );
240                    continue;
241                };
242                if method.eq_ignore_ascii_case("GET") && !item.menu.trim().is_empty() {
243                    let resource = ResourceRoute {
244                        path: item.path.clone(),
245                        menu: item.menu.clone(),
246                        description: item.description.clone(),
247                    };
248                    if !register_resource(&mut resources, resource) {
249                        tracing::warn!(
250                            "pluginhost: plugin {} declared invalid resource route {}",
251                            record.id,
252                            item.path
253                        );
254                    }
255                    continue;
256                }
257                let key = route_key(&method, &path);
258                if reserved.contains(&key) {
259                    tracing::warn!(
260                        "pluginhost: plugin {} management route {key} conflicts with an existing route and was skipped",
261                        record.id
262                    );
263                    continue;
264                }
265                if routes.contains_key(&key) {
266                    tracing::warn!(
267                        "pluginhost: plugin {} management route {key} conflicts with a higher-priority plugin and was skipped",
268                        record.id
269                    );
270                    continue;
271                }
272                routes.insert(
273                    key,
274                    RouteRecord {
275                        plugin_id: record.id.clone(),
276                        path: record.path.clone(),
277                        version: record.version.clone(),
278                        schema_version: record.plugin.schema_version,
279                        route: ManagementRoute { method, path, ..item },
280                    },
281                );
282            }
283            for item in resp.resources {
284                let path = item.path.clone();
285                if !register_resource(&mut resources, item) {
286                    tracing::warn!(
287                        "pluginhost: plugin {} declared invalid resource route {path}",
288                        record.id
289                    );
290                }
291            }
292        }
293        let mut state = self.state();
294        state.management_routes = routes;
295        state.resource_routes = resources;
296    }
297
298    /// Plugin management routes currently registered, by key.
299    pub fn management_routes(&self) -> Vec<RouteRecord> {
300        self.state().management_routes.values().cloned().collect()
301    }
302
303    pub fn resource_routes(&self) -> Vec<ResourceRecord> {
304        self.state().resource_routes.values().cloned().collect()
305    }
306
307    /// Whether [`Self::serve_management`] would call a plugin for this method and decoded
308    /// path (Go checks this before reading the body).
309    pub fn has_management_route(&self, method: &str, path: &str) -> bool {
310        let record = self.state().management_routes.get(&route_key(method, path)).cloned();
311        record.is_some_and(|r| !self.is_fused(&r.plugin_id))
312    }
313
314    /// Go `ServeManagementHTTP`: `None` when no plugin route matches.
315    pub async fn serve_management(&self, req: Inbound) -> Option<Reply> {
316        let key = route_key(&req.method, &req.path);
317        let record = self.state().management_routes.get(&key).cloned()?;
318        if self.is_fused(&record.plugin_id) {
319            return None;
320        }
321        let request = ManagementCall {
322            method: req.method.clone(),
323            path: req.path.clone(),
324            headers: req.headers.clone(),
325            query: req.query.clone(),
326            body: Some(NonNilBytes(req.body.clone())),
327            host_callback_id: String::new(),
328        };
329        match self
330            .call_route_handler(&record.plugin_id, &record.path, &record.version, request, req.scope)
331            .await
332        {
333            Err(e) => {
334                tracing::warn!("pluginhost: management handler {} failed: {e}", record.plugin_id);
335                Some(Reply::error(502, "plugin management handler failed"))
336            }
337            Ok(mut resp) => {
338                if record.schema_version < abi::SCHEMA_RAW_MANAGEMENT_RESPONSE {
339                    let content_type = header_get(&resp.headers, "Content-Type");
340                    if let Some(body) = escape_json_body_if_likely(&resp.body, content_type) {
341                        resp.body = body;
342                    }
343                }
344                Some(Reply::from_plugin(resp))
345            }
346        }
347    }
348
349    /// Go `ServeResourceHTTP`: GET only, no body forwarded.
350    pub async fn serve_resource(&self, req: Inbound) -> Option<Reply> {
351        if !req.method.eq_ignore_ascii_case("GET") {
352            return None;
353        }
354        let record = self
355            .state()
356            .resource_routes
357            .get(&route_key("GET", &req.path))
358            .cloned()?;
359        if self.is_fused(&record.plugin_id) {
360            return None;
361        }
362        let request = ManagementCall {
363            method: "GET".into(),
364            path: req.path.clone(),
365            headers: req.headers.clone(),
366            query: req.query.clone(),
367            body: None,
368            host_callback_id: String::new(),
369        };
370        match self
371            .call_route_handler(&record.plugin_id, &record.path, &record.version, request, req.scope)
372            .await
373        {
374            Err(e) => {
375                tracing::warn!("pluginhost: resource handler {} failed: {e}", record.plugin_id);
376                Some(Reply::error(502, "plugin resource handler failed"))
377            }
378            Ok(resp) => Some(Reply::from_plugin(resp)),
379        }
380    }
381
382    /// `management.handle` with a callback context. A plugin that is no longer the
383    /// current identity yields an empty response, as in Go.
384    async fn call_route_handler(
385        &self,
386        plugin_id: &str,
387        path: &std::path::Path,
388        version: &str,
389        mut call: ManagementCall,
390        mut scope: RequestScope,
391    ) -> Result<ManagementResponse, crate::rpc::CallError> {
392        let Some(record) = self.record(plugin_id) else {
393            return Ok(ManagementResponse::default());
394        };
395        if record.path != path || record.version != version {
396            return Ok(ManagementResponse::default());
397        }
398        scope.headers = call.headers.clone();
399        scope.query = call.query.clone();
400        scope.cancel = scope.cancel.child_token();
401        let _cancel = scope.cancel.clone().drop_guard();
402        let guard = self
403            .inner
404            .callbacks
405            .open(plugin_id, Some(record.client.instance().clone()), scope);
406        call.host_callback_id = guard.id().to_owned();
407        let result = self.call(&record, method::MANAGEMENT_HANDLE, &call).await;
408        drop(guard);
409        result
410    }
411}
412
413/// `http.Header.Get`: canonicalizes the key, then looks it up exactly. A decoded map
414/// whose key is spelled `content-type` does not match.
415pub fn header_get<'a>(headers: &'a Header, name: &str) -> &'a str {
416    headers
417        .get(&cpa_exec::proxy::canonical_header(name))
418        .and_then(|v| v.first())
419        .map(String::as_str)
420        .unwrap_or_default()
421}
422
423/// Go `htmlsanitize.JSONBodyIfLikely`: HTML-escapes every string value of a JSON body
424/// (schema < 6 management responses). `None` when the body is left as is.
425pub fn escape_json_body_if_likely(body: &[u8], content_type: &str) -> Option<Bytes> {
426    if !(is_json_content_type(content_type) || looks_like_json(body)) {
427        return None;
428    }
429    let trimmed = body.trim_ascii();
430    if trimmed.is_empty() {
431        return None;
432    }
433    let mut value = GoValue::parse(trimmed)?;
434    value.visit_mut(|v| {
435        if let GoValue::String(s) = v {
436            *s = html_escape(s);
437        }
438    });
439    Some(Bytes::from(value.marshal_no_html()))
440}
441
442/// Go `html.EscapeString`.
443pub fn html_escape(s: &str) -> String {
444    let mut out = String::with_capacity(s.len());
445    for c in s.chars() {
446        match c {
447            '<' => out.push_str("&lt;"),
448            '>' => out.push_str("&gt;"),
449            '&' => out.push_str("&amp;"),
450            '\'' => out.push_str("&#39;"),
451            '"' => out.push_str("&#34;"),
452            c => out.push(c),
453        }
454    }
455    out
456}
457
458/// Go `htmlsanitize.IsJSONContentType` (`mime.ParseMediaType`, falling back to the raw
459/// value when the parameters do not parse).
460fn is_json_content_type(content_type: &str) -> bool {
461    let content_type = content_type.trim();
462    let media = match content_type.split_once(';') {
463        Some((media, params)) if params.split(';').all(|p| p.trim().is_empty() || p.contains('=')) => media.trim(),
464        Some(_) => content_type,
465        None => content_type,
466    };
467    let media = media.to_ascii_lowercase();
468    media == "application/json" || media.ends_with("+json")
469}
470
471fn looks_like_json(body: &[u8]) -> bool {
472    matches!(body.trim_ascii().first(), Some(b'{' | b'['))
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478
479    /// Go `TestNormalizeManagementRoute*` / resource normalization.
480    #[test]
481    fn route_normalization_matches_go() {
482        let route = |m: &str, p: &str| ManagementRoute {
483            method: m.into(),
484            path: p.into(),
485            ..Default::default()
486        };
487        assert_eq!(
488            normalize_route(&route("", "status/")),
489            Some(("GET".into(), "/v0/management/status".into()))
490        );
491        assert_eq!(
492            normalize_route(&route("post", "/v0/management/x")),
493            Some(("POST".into(), "/v0/management/x".into()))
494        );
495        assert_eq!(normalize_route(&route("GET", "/v0/management/")), None);
496        assert_eq!(normalize_route(&route("GET", "/a/:id")), None);
497        assert_eq!(normalize_route(&route("GE T", "/a")), None);
498        let res = |p: &str| ResourceRoute {
499            path: p.into(),
500            ..Default::default()
501        };
502        assert_eq!(
503            normalize_resource("p", &res("status")),
504            Some("/v0/resource/plugins/p/status".into())
505        );
506        assert_eq!(
507            normalize_resource("p", &res("/plugins/p/a/")),
508            Some("/v0/resource/plugins/p/a".into())
509        );
510        assert_eq!(
511            normalize_resource("p", &res("/v0/resource/plugins/p/b")),
512            Some("/v0/resource/plugins/p/b".into())
513        );
514        assert_eq!(normalize_resource("p", &res("/a/../b")), None);
515    }
516
517    /// Go `TestJSONBodyEscapesStringValues` / `TestJSONBodyIfLikelySkipsNonJSONHTML`.
518    #[test]
519    fn legacy_json_escaping_matches_htmlsanitize() {
520        let got = escape_json_body_if_likely(br#" {"title":"<b>","n":1.50,"items":["a & b",{"z":"'"}]} "#, "").unwrap();
521        assert_eq!(
522            &got[..],
523            br#"{"items":["a &amp; b",{"z":"&#39;"}],"n":1.50,"title":"&lt;b&gt;"}"#
524        );
525        assert_eq!(
526            escape_json_body_if_likely(b"<!doctype html>", "text/html; charset=utf-8"),
527            None
528        );
529        assert_eq!(escape_json_body_if_likely(b"{bad", "application/json"), None);
530        assert!(is_json_content_type("application/problem+json; charset=utf-8"));
531        // Go's Header.Get does not find a lowercase key decoded from JSON.
532        let lower: Header = [("content-type".to_owned(), vec!["application/json".to_owned()])].into();
533        assert_eq!(header_get(&lower, "Content-Type"), "");
534        assert_eq!(
535            escape_json_body_if_likely(br#""<b>""#, header_get(&lower, "Content-Type")),
536            None
537        );
538    }
539
540    /// A legacy response at encoding/json's depth limit escapes on a 2 MiB stack.
541    #[test]
542    fn legacy_json_escaping_handles_the_depth_limit() {
543        std::thread::Builder::new()
544            .stack_size(2 << 20)
545            .spawn(|| {
546                let deep = |leaf: &str| format!("{}[\"{leaf}\"]{}", r#"[{"s":"#.repeat(4_999), "}]".repeat(4_999));
547                let got = escape_json_body_if_likely(deep("<b>").as_bytes(), "application/json").unwrap();
548                assert_eq!(&got[..], deep("&lt;b&gt;").as_bytes());
549            })
550            .unwrap()
551            .join()
552            .unwrap();
553    }
554}