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