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