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