Skip to main content

gent_protocol/
dashboard.rs

1//! Declarative, chat-owned dashboards. Values contain no executable markup.
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::collections::BTreeSet;
5
6mod image;
7
8pub const MAX_BOARD_BYTES: usize = 32 * 1024;
9
10#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
11#[serde(deny_unknown_fields)]
12pub struct Board {
13    pub title: String,
14    pub widgets: Vec<Widget>,
15}
16
17#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "snake_case")]
19pub enum Kind {
20    Text,
21    Events,
22    Graph,
23    Gauge,
24    Progress,
25    Button,
26    Link,
27    Metric,
28    Bar,
29    Pie,
30    Radar,
31    Scatter,
32    Image,
33}
34
35#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
36#[serde(deny_unknown_fields)]
37pub struct Widget {
38    pub id: String,
39    pub label: String,
40    pub kind: Kind,
41    pub value: Value,
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub unit: Option<String>,
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub x_unit: Option<String>,
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub min: Option<f64>,
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub max: Option<f64>,
50}
51
52fn label(s: &str, limit: usize) -> bool {
53    !s.trim().is_empty() && s.len() <= limit && !s.chars().any(char::is_control)
54}
55fn text(v: &Value) -> bool {
56    v.as_str().is_some_and(|s| {
57        s.len() <= 2048
58            && !s
59                .chars()
60                .any(|c| c.is_control() && !matches!(c, '\n' | '\t'))
61    })
62}
63
64/// Whether a dashboard destination can be opened by the system web browser.
65pub fn web_url(value: &str) -> bool {
66    let Some((scheme, authority_and_path)) = value.split_once("://") else {
67        return false;
68    };
69    // URL parsers can repair missing hosts, extra slashes and backslashes.
70    // Keep the same explicit web destination across the native browser handlers.
71    value.len() <= 2048
72        && (scheme.eq_ignore_ascii_case("https") || scheme.eq_ignore_ascii_case("http"))
73        && !authority_and_path.starts_with(['/', '?', '#'])
74        && !value.contains(|c: char| c.is_whitespace() || c.is_control() || c == '\\')
75        && url::Url::parse(value).is_ok_and(|url| url.has_host())
76}
77
78fn number(v: &Value) -> bool {
79    v.as_f64().is_some_and(|n| n.abs() <= 1e100)
80}
81
82fn categories(kind: Kind, value: &Value) -> bool {
83    let Some(entries) = value.as_array() else {
84        return false;
85    };
86    if entries.len() > 16 || (kind == Kind::Radar && entries.len() < 3) {
87        return false;
88    }
89    let mut positive = false;
90    for entry in entries {
91        let Some(obj) = entry.as_object() else {
92            return false;
93        };
94        if obj.len() != 2 || !entry["label"].as_str().is_some_and(|s| label(s, 128)) {
95            return false;
96        }
97        let Some(n) = entry["value"].as_f64() else {
98            return false;
99        };
100        if n.abs() > 1e100 || (kind != Kind::Bar && n < 0.) {
101            return false;
102        }
103        positive |= n > 0.;
104    }
105    kind != Kind::Pie || positive
106}
107
108impl Widget {
109    pub fn validate(&self) -> Result<(), &'static str> {
110        if self.id.is_empty()
111            || self.id.len() > 64
112            || !self
113                .id
114                .bytes()
115                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
116            || !label(&self.label, 128)
117            || self.unit.as_ref().is_some_and(|u| !label(u, 32))
118        {
119            return Err("invalid widget key, label or unit");
120        }
121        if self
122            .x_unit
123            .as_ref()
124            .is_some_and(|u| self.kind != Kind::Scatter || !label(u, 32))
125        {
126            return Err("x_unit requires a scatter widget and a label of 1–32 bytes");
127        }
128        let valid = match self.kind {
129            Kind::Text => text(&self.value),
130            Kind::Link => {
131                if !self.value.as_str().is_some_and(web_url) {
132                    return Err("use an absolute HTTP or HTTPS URL for a dashboard link");
133                }
134                if self.unit.is_some() {
135                    return Err("omit the unit on a dashboard link");
136                }
137                true
138            }
139            Kind::Button => {
140                text(&self.value) && self.value.as_str().is_some_and(|v| !v.trim().is_empty())
141            }
142            Kind::Events => self
143                .value
144                .as_array()
145                .is_some_and(|a| a.len() <= 64 && a.iter().all(text)),
146            Kind::Graph => self
147                .value
148                .as_array()
149                .is_some_and(|a| a.len() <= 256 && a.iter().all(number)),
150            Kind::Progress | Kind::Gauge => {
151                let min = self.min.unwrap_or(0.);
152                let max = self.max.unwrap_or(100.);
153                min.abs() <= 1e100
154                    && max.abs() <= 1e100
155                    && min < max
156                    && self
157                        .value
158                        .as_f64()
159                        .is_some_and(|v| (min..=max).contains(&v))
160            }
161            Kind::Metric => number(&self.value),
162            Kind::Bar | Kind::Pie | Kind::Radar => categories(self.kind, &self.value),
163            Kind::Scatter => self.value.as_array().is_some_and(|a| {
164                a.len() <= 256
165                    && a.iter().all(|p| {
166                        p.as_array()
167                            .is_some_and(|xy| xy.len() == 2 && xy.iter().all(number))
168                    })
169            }),
170            Kind::Image => self.value.as_str().is_some_and(image::valid),
171        };
172        if !valid {
173            return Err("invalid value for dashboard widget type");
174        }
175        Ok(())
176    }
177}
178
179impl Board {
180    pub fn validate(&self) -> Result<(), &'static str> {
181        if !label(&self.title, 128) || !(1..=32).contains(&self.widgets.len()) {
182            return Err("use a title and 1–32 widgets");
183        }
184        if serde_json::to_vec(self)
185            .map_err(|_| "invalid dashboard")?
186            .len()
187            > MAX_BOARD_BYTES
188        {
189            return Err("dashboard exceeds 32 KiB");
190        }
191        let mut keys = BTreeSet::new();
192        for widget in &self.widgets {
193            if !keys.insert(&widget.id) {
194                return Err("duplicate widget key");
195            }
196            widget.validate()?;
197        }
198        Ok(())
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn link_widgets_reject_display_units() {
208        let board: Board = serde_json::from_value(serde_json::json!({
209            "title":"Results", "widgets":[{
210                "id":"report", "label":"Open report", "kind":"link",
211                "value":"https://example.org/report", "unit":"ms"
212            }]
213        }))
214        .unwrap();
215        assert_eq!(board.validate(), Err("omit the unit on a dashboard link"));
216    }
217
218    #[test]
219    fn links_accept_only_explicit_web_destinations() {
220        for value in [
221            "https://example.org/runs/42?q=a%20b&tag=last#chart",
222            "HTTP://localhost:8000/",
223            "https://[::1]/",
224            "https://例え.jp/結果",
225        ] {
226            assert!(web_url(value), "{value}");
227        }
228        for value in [
229            "javascript:alert(1)",
230            "file:///tmp/status",
231            "data:text/html,page",
232            "gent://some-action",
233            "//example.org",
234            "/report",
235            "https:example.org",
236            "https:///example.org",
237            "https://",
238            "http://[::1",
239            "https://host:65536/",
240            "https://example.org/a b",
241            "https://example.org/\n",
242            "https://example.org\\other",
243            "https://example.org/\u{0}",
244        ] {
245            assert!(!web_url(value), "{value:?}");
246        }
247    }
248}
249
250#[cfg(test)]
251mod chart_tests {
252    use super::*;
253    use serde_json::json;
254
255    fn widget(kind: Kind, value: Value) -> Widget {
256        serde_json::from_value(json!({"id":"chart","kind":kind,"label":"Chart","value":value}))
257            .unwrap()
258    }
259
260    #[test]
261    fn category_charts_check_shape_bounds_and_totals() {
262        let item = |n| json!({"label":"North","value":n});
263        for (kind, values, ok) in [
264            (Kind::Bar, vec![], true),
265            (Kind::Bar, vec![item(-4); 16], true),
266            (Kind::Bar, vec![item(1); 17], false),
267            (Kind::Pie, vec![], false),
268            (Kind::Pie, vec![item(0); 2], false),
269            (Kind::Pie, vec![item(0), item(1)], true),
270            (Kind::Pie, vec![item(2), item(-1)], false),
271            (Kind::Radar, vec![item(4); 2], false),
272            (Kind::Radar, vec![item(0); 3], true),
273            (Kind::Radar, vec![item(4), item(1), item(-1)], false),
274        ] {
275            assert_eq!(
276                widget(kind, json!(values)).validate().is_ok(),
277                ok,
278                "{kind:?}"
279            );
280        }
281        for invalid in [
282            json!([1]),
283            json!([{"label":"  ","value":1}]),
284            json!([{"label":"x","value":"1"}]),
285            json!([{"label":"x","value":1e101}]),
286            json!([{"label":"x","value":1,"extra":true}]),
287        ] {
288            assert!(widget(Kind::Bar, invalid).validate().is_err());
289        }
290    }
291
292    #[test]
293    fn scatter_has_pairs_and_units_while_graph_keeps_numeric_samples() {
294        let mut scatter = widget(Kind::Scatter, json!(vec![[-1.0, 2.5]; 256]));
295        scatter.x_unit = Some("s".into());
296        scatter.unit = Some("m".into());
297        assert!(scatter.validate().is_ok());
298        assert!(widget(Kind::Scatter, json!([])).validate().is_ok());
299        for bad in [
300            json!(vec![[0, 1]; 257]),
301            json!([1, 2]),
302            json!([[1, 2, 3]]),
303            json!([[1, "2"]]),
304            json!([[0, 1e101]]),
305        ] {
306            assert!(widget(Kind::Scatter, bad).validate().is_err());
307        }
308        scatter.kind = Kind::Graph;
309        scatter.value = json!([1, 2]);
310        assert!(scatter.validate().is_err());
311        scatter.x_unit = None;
312        assert!(scatter.validate().is_ok());
313        assert!(widget(Kind::Graph, json!([[1, 2]])).validate().is_err());
314        assert!(widget(Kind::Metric, json!(-1e100)).validate().is_ok());
315        assert!(widget(Kind::Metric, json!("1")).validate().is_err());
316        assert!(widget(Kind::Metric, json!(1e101)).validate().is_err());
317    }
318}