zaun_community_protocol/command/object/bot/
check.rs1use super::{Capabilities, ConfigKey, Grants, Manifest};
4use crate::command::object::embed::link;
5use crate::command::{BodyError, Validate, check};
6use crate::limits::{
7 BOT_CONFIG_KEYS, BOT_CONFIG_VALUE_MAX, BOT_DESCRIPTION_MAX, BOT_LOCAL_NETWORK,
8 BOT_NETWORK_HOSTS, BOT_STORAGE_MAX, DISPLAY_NAME,
9};
10use crate::signed::{valid_app_id, valid_version};
11
12#[must_use]
15pub fn host_pattern_ok(host: &str) -> bool {
16 let name = host.strip_prefix("*.").unwrap_or(host);
17 let label = |l: &str| {
18 (1..=63).contains(&l.len())
19 && !l.starts_with('-')
20 && !l.ends_with('-')
21 && l.bytes()
22 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
23 };
24 let tld = name.rsplit('.').next().unwrap_or_default();
26 name.len() <= 253
27 && name.split('.').count() >= 2
28 && name.split('.').all(label)
29 && !tld.bytes().all(|b| b.is_ascii_digit())
30}
31
32#[must_use]
36pub fn local_address_ok(addr: &str) -> bool {
37 let Some((host, port)) = addr.rsplit_once(':') else {
38 return false;
39 };
40 let port_ok = port.parse::<u16>().is_ok_and(|p| p != 0) && !port.starts_with('0');
41 let ipv6 = host
42 .strip_prefix('[')
43 .and_then(|h| h.strip_suffix(']'))
44 .is_some_and(|h| h.parse::<std::net::Ipv6Addr>().is_ok());
45 let name = !host.is_empty()
46 && host.len() <= 253
47 && host.split('.').all(|l| {
48 !l.is_empty()
49 && l.len() <= 63
50 && l.bytes()
51 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
52 });
53 port_ok && (ipv6 || name)
54}
55
56#[must_use]
58pub fn config_key_ok(key: &str) -> bool {
59 let mut bytes = key.bytes();
60 key.len() <= 64
61 && bytes.next().is_some_and(|b| b.is_ascii_lowercase())
62 && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
63}
64
65fn check_config(config: &std::collections::BTreeMap<String, ConfigKey>) -> Result<(), BodyError> {
68 check::count("manifest.config", config.len(), BOT_CONFIG_KEYS)?;
69 for (key, k) in config {
70 let field = format!("manifest.config.{key}");
71 if !config_key_ok(key) {
72 return Err(BodyError::bad(&field, "is not a lowercase key"));
73 }
74 check::text(&format!("{field}.description"), &k.description, (1, 200))?;
75 match &k.default {
76 Some(_) if k.secret => {
77 return Err(BodyError::bad(&field, "a secret has no default"));
78 }
79 Some(d) if d.len() > BOT_CONFIG_VALUE_MAX => {
80 return Err(BodyError::bad(&format!("{field}.default"), "is over 4 KiB"));
81 }
82 _ => {}
83 }
84 }
85 Ok(())
86}
87
88impl Capabilities {
89 pub(crate) fn check(&self, field: &str) -> Result<(), BodyError> {
91 check::count(
92 &format!("{field}.network"),
93 self.network.len(),
94 BOT_NETWORK_HOSTS,
95 )?;
96 check::unique(&format!("{field}.network"), &self.network)?;
97 if !self.network.iter().all(|h| host_pattern_ok(h)) {
98 return Err(BodyError::bad(
99 &format!("{field}.network"),
100 "is not a host name",
101 ));
102 }
103 let local = format!("{field}.local_network");
104 check::count(&local, self.local_network.len(), BOT_LOCAL_NETWORK)?;
105 check::unique(&local, &self.local_network)?;
106 if !self.local_network.iter().all(|a| local_address_ok(a)) {
107 return Err(BodyError::bad(&local, "is not host:port"));
108 }
109 check::range(
110 &format!("{field}.storage_bytes"),
111 self.storage_bytes,
112 0,
113 BOT_STORAGE_MAX,
114 )
115 }
116}
117
118impl Validate for Grants {
119 fn validate(&self) -> Result<(), BodyError> {
120 check::known_bits("grants.permissions", self.permissions)?;
121 self.capabilities.check("grants.capabilities")
122 }
123}
124
125impl Validate for Manifest {
126 fn validate(&self) -> Result<(), BodyError> {
127 if !valid_app_id(&self.app_id) {
128 return Err(BodyError::bad(
129 "manifest.app_id",
130 "is not a lowercase reverse-DNS name",
131 ));
132 }
133 if !valid_version(&self.version) {
134 return Err(BodyError::bad(
135 "manifest.version",
136 "is not a semantic version",
137 ));
138 }
139 check::text("manifest.name", &self.name, DISPLAY_NAME)?;
140 check::opt_text(
141 "manifest.description",
142 self.description.as_deref(),
143 (0, BOT_DESCRIPTION_MAX),
144 )?;
145 check::known_bits("manifest.permissions", self.permissions)?;
146 self.capabilities.check("manifest.capabilities")?;
147 check::count("manifest.events", self.events.len(), 64)?;
148 if let Some(e) = self.events.iter().find(|e| !super::events::known(e)) {
149 return Err(BodyError::bad(
150 "manifest.events",
151 format!("{e} is not an event type or group"),
152 ));
153 }
154 if let Some(url) = &self.update_url {
155 link("manifest.update_url", url)?;
156 }
157 check_config(&self.config)
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164
165 #[test]
166 fn names() {
167 assert!(host_pattern_ok("api.example.com"));
168 assert!(host_pattern_ok("*.example.com"));
169 assert!(!host_pattern_ok("*"));
170 assert!(!host_pattern_ok("localhost"));
171 assert!(!host_pattern_ok("a.*.com"));
172 assert!(!host_pattern_ok("127.0.0.1"));
173 }
174}