subspace_core/config/
web_boards.rs1use std::collections::BTreeMap;
7use std::net::IpAddr;
8use std::path::PathBuf;
9
10use serde_json::Value;
11
12use crate::Secret;
13
14pub const MAX_WEB_BOARD_ID_CHARS: usize = 40;
16pub const MAX_WEB_BOARD_TITLE_CHARS: usize = 60;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct WebBoard {
21 pub id: String,
24 pub title: String,
26 pub source: WebBoardSource,
27 pub settings: BTreeMap<String, Value>,
30 pub secrets: BTreeMap<String, Secret>,
33 pub permissions: BTreeMap<String, bool>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum WebBoardSource {
40 Url(String),
42 Folder(PathBuf),
45}
46
47pub fn valid_web_board_id(id: &str) -> bool {
49 !id.is_empty()
50 && id.len() <= MAX_WEB_BOARD_ID_CHARS
51 && id.starts_with(|c: char| c.is_ascii_lowercase())
52 && id
53 .chars()
54 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
55}
56
57pub fn web_board_url_allowed(url: &url::Url) -> bool {
61 let plain = url.username().is_empty() && url.password().is_none();
62 let secure = match url.scheme() {
63 "https" => url.host().is_some(),
64 "http" => is_loopback(url),
65 _ => false,
66 };
67 plain && secure
68}
69
70fn is_loopback(url: &url::Url) -> bool {
71 match url.host() {
72 Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
73 Some(url::Host::Ipv4(address)) => IpAddr::V4(address).is_loopback(),
74 Some(url::Host::Ipv6(address)) => IpAddr::V6(address).is_loopback(),
75 None => false,
76 }
77}
78
79#[cfg(test)]
80mod tests {
81 use super::{valid_web_board_id, web_board_url_allowed};
82
83 fn allowed(value: &str) -> bool {
84 url::Url::parse(value).is_ok_and(|url| web_board_url_allowed(&url))
85 }
86
87 #[test]
88 fn https_and_local_http_pages_are_allowed() {
89 for value in [
90 "https://example.com",
91 "https://example.com:8443/path?q=1#top",
92 "http://localhost:5173/",
93 "http://LOCALHOST:3000",
94 "http://127.0.0.1:8080",
95 "http://127.1.2.3",
96 "http://[::1]:4000/app",
97 ] {
98 assert!(allowed(value), "{value}");
99 }
100 }
101
102 #[test]
103 fn other_schemes_remote_http_and_credentials_are_refused() {
104 for value in [
105 "http://example.com",
106 "http://localhost.example.com",
107 "http://10.0.0.1",
108 "https://user:secret@example.com",
109 "https://user@example.com",
110 "http://user@localhost:3000",
111 "file:///etc/passwd",
112 "javascript:alert(1)",
113 "data:text/html,<p>hi</p>",
114 "about:blank",
115 "ftp://example.com",
116 ] {
117 assert!(!allowed(value), "{value}");
118 }
119 }
120
121 #[test]
122 fn ids_are_short_lower_case_names() {
123 for id in ["grafana", "my-app", "a1", "x"] {
124 assert!(valid_web_board_id(id), "{id}");
125 }
126 for id in [
127 "",
128 "Grafana",
129 "1app",
130 "-app",
131 "my_app",
132 "my app",
133 "é",
134 &"a".repeat(41),
135 ] {
136 assert!(!valid_web_board_id(id), "{id}");
137 }
138 }
139}