1use serde::{Deserialize, Serialize};
8use unicode_normalization::{UnicodeNormalization, is_nfc};
9
10pub const MAX_NAME_CHARS: usize = 80;
12pub const MAX_AVATAR_BYTES: usize = 1_048_576;
14const MAX_SERVICE_CHARS: usize = 32;
15const MAX_ACCOUNT_CHARS: usize = 128;
16
17#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
19pub struct Appearance {
20 pub name: String,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub avatar: Option<String>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub persona: Option<Persona>,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
32pub struct Persona {
33 pub service: String,
35 pub account: String,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub linked: Option<String>,
42}
43
44#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
46pub enum AppearanceError {
47 #[error("the shown name is empty")]
49 EmptyName,
50 #[error("the shown name is longer than {MAX_NAME_CHARS} characters")]
52 NameTooLong,
53 #[error("the shown name is not trimmed and NFC-normalized")]
55 NotNormalized,
56 #[error("the shown name contains the hidden or direction-changing character U+{0:04X}")]
58 HiddenCharacter(u32),
59 #[error("the avatar does not name an image by its content hash")]
61 AvatarNotHash,
62 #[error("the avatar is larger than 1 MiB")]
64 AvatarTooLarge,
65 #[error("the avatar is not a PNG, JPEG, WebP or GIF image")]
67 AvatarNotImage,
68 #[error("the avatar is not in the workspace's content store")]
70 AvatarMissing,
71 #[error("the avatar's bytes do not match its hash")]
73 AvatarMismatch,
74 #[error("the persona's service must be 1 to 32 lowercase letters, digits or '-'")]
75 BadService,
76 #[error("the persona's account must be 1 to 128 visible characters")]
78 BadAccount,
79 #[error("the persona's linked member must be a root key in lowercase hex")]
81 BadLinked,
82}
83
84impl Appearance {
85 pub fn new(
87 name: &str,
88 avatar: Option<String>,
89 persona: Option<Persona>,
90 ) -> Result<Self, AppearanceError> {
91 let appearance = Self {
92 name: name.trim().nfc().collect(),
93 avatar,
94 persona,
95 };
96 appearance.validate()?;
97 Ok(appearance)
98 }
99
100 pub fn validate(&self) -> Result<(), AppearanceError> {
103 if let Some(hidden) = self.name.chars().find(|c| hidden(*c)) {
104 return Err(AppearanceError::HiddenCharacter(u32::from(hidden)));
105 }
106 if self.name.trim() != self.name || !is_nfc(&self.name) {
107 return Err(AppearanceError::NotNormalized);
108 }
109 match self.name.chars().count() {
110 0 => return Err(AppearanceError::EmptyName),
111 n if n > MAX_NAME_CHARS => return Err(AppearanceError::NameTooLong),
112 _ => {}
113 }
114 if self
115 .avatar
116 .as_deref()
117 .is_some_and(|hash| !tilo_content_types::valid_hash(hash))
118 {
119 return Err(AppearanceError::AvatarNotHash);
120 }
121 if let Some(persona) = &self.persona {
122 let service = persona.service.chars().count();
123 if !(1..=MAX_SERVICE_CHARS).contains(&service)
124 || !persona
125 .service
126 .bytes()
127 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
128 {
129 return Err(AppearanceError::BadService);
130 }
131 let account = persona.account.chars().count();
132 if !(1..=MAX_ACCOUNT_CHARS).contains(&account)
133 || persona
134 .account
135 .chars()
136 .any(|c| hidden(c) || c.is_whitespace())
137 {
138 return Err(AppearanceError::BadAccount);
139 }
140 if persona.linked.as_deref().is_some_and(|person| {
141 person.len() != 64
142 || !person
143 .bytes()
144 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
145 }) {
146 return Err(AppearanceError::BadLinked);
147 }
148 }
149 Ok(())
150 }
151}
152
153fn hidden(c: char) -> bool {
156 c.is_control()
157 || matches!(
158 c,
159 '\u{202A}'..='\u{202E}'
160 | '\u{2066}'..='\u{2069}'
161 | '\u{200E}'
162 | '\u{200F}'
163 | '\u{061C}'
164 | '\u{200B}'..='\u{200D}'
165 | '\u{2060}'
166 | '\u{FEFF}'
167 | '\u{180E}'
168 )
169}
170
171pub fn check_avatar_bytes(bytes: &[u8]) -> Result<(), AppearanceError> {
177 if bytes.len() > MAX_AVATAR_BYTES {
178 return Err(AppearanceError::AvatarTooLarge);
179 }
180 match tilo_content_types::image_format(bytes) {
181 Some(format) if matches!(format.extension, "png" | "jpg" | "webp" | "gif") => Ok(()),
182 _ => Err(AppearanceError::AvatarNotImage),
183 }
184}
185
186pub fn refuse_here(
193 request: &crate::remote::InvokeRequest,
194) -> Result<(), crate::remote::ActionCallError> {
195 match request.appearance {
196 Some(_) => Err(crate::remote::ActionCallError::Refused {
197 reason: "only a bot allowed to post under other names may carry an appearance".into(),
198 }),
199 None => Ok(()),
200 }
201}
202
203pub fn admit(
213 caller: &crate::remote::Caller,
214 appearance: &Appearance,
215 allows_personas: impl FnOnce(&str) -> bool,
216 avatar: impl FnOnce(&str) -> Option<Vec<u8>>,
217) -> Result<Appearance, crate::remote::ActionCallError> {
218 use crate::remote::ActionCallError;
219 let Some(installation) = caller.acting().bot_id() else {
220 return Err(ActionCallError::Refused {
221 reason: "only a bot allowed to post under other names may carry an appearance".into(),
222 });
223 };
224 if !allows_personas(installation) {
225 return Err(ActionCallError::Refused {
226 reason: "this bot's installation does not allow it to post under other names".into(),
227 });
228 }
229 let invalid = |error: AppearanceError| ActionCallError::InvalidRequest {
230 reason: error.to_string(),
231 };
232 appearance.validate().map_err(invalid)?;
233 if let Some(hash) = &appearance.avatar {
234 let bytes = avatar(hash).ok_or_else(|| invalid(AppearanceError::AvatarMissing))?;
235 if !blake3::hash(&bytes).to_hex().eq_ignore_ascii_case(hash) {
236 return Err(invalid(AppearanceError::AvatarMismatch));
237 }
238 check_avatar_bytes(&bytes).map_err(invalid)?;
239 }
240 Ok(appearance.clone())
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246
247 fn png() -> Vec<u8> {
248 let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec();
249 bytes.extend_from_slice(&[0; 32]);
250 bytes
251 }
252
253 tilo_test_env::scenario! {
254 fn an_appearance_is_checked_before_it_is_shown;
255
256 phase a_name_is_trimmed_and_nfc_normalized_once_and_then_must_stay_so;
257 {
258 let made = Appearance::new(" Rene\u{301} ", None, None).unwrap();
260 assert_eq!(made.name, "Ren\u{e9}");
261 let decomposed = Appearance {
262 name: "Rene\u{301}".into(),
263 avatar: None,
264 persona: None,
265 };
266 assert_eq!(decomposed.validate(), Err(AppearanceError::NotNormalized));
267 let padded = Appearance {
268 name: " alice".into(),
269 avatar: None,
270 persona: None,
271 };
272 assert_eq!(padded.validate(), Err(AppearanceError::NotNormalized));
273 }
274
275 phase a_name_is_one_to_eighty_characters;
276 {
277 assert_eq!(
278 Appearance::new(" ", None, None),
279 Err(AppearanceError::EmptyName)
280 );
281 assert!(Appearance::new(&"é".repeat(80), None, None).is_ok());
282 assert_eq!(
283 Appearance::new(&"é".repeat(81), None, None),
284 Err(AppearanceError::NameTooLong)
285 );
286 }
287
288 phase hidden_and_direction_changing_characters_refuse_the_name_rather_than_being_cleaned;
289 {
290 for (name, hidden) in [
291 ("a\u{200B}lice", 0x200B),
292 ("alice\u{202E}", 0x202E),
293 ("\u{2066}alice", 0x2066),
294 ("ali\u{200D}ce", 0x200D),
295 ("ali\u{FEFF}ce", 0xFEFF),
296 ("ali\u{061C}ce", 0x061C),
297 ("ali\u{180E}ce", 0x180E),
298 ("ali\nce", 0x0A),
299 ] {
300 assert_eq!(
301 Appearance::new(name, None, None),
302 Err(AppearanceError::HiddenCharacter(hidden)),
303 "{name:?}"
304 );
305 }
306 }
307
308 phase an_avatar_names_a_content_hash_and_a_persona_a_service_and_account;
309 {
310 let hash = blake3::hash(b"x").to_hex().to_string();
311 assert!(Appearance::new("alice", Some(hash), None).is_ok());
312 assert_eq!(
313 Appearance::new("alice", Some("../etc/passwd".into()), None),
314 Err(AppearanceError::AvatarNotHash)
315 );
316 let discord = Persona {
317 service: "discord".into(),
318 account: "80351110224678912".into(),
319 linked: None,
320 };
321 assert!(Appearance::new("alice", None, Some(discord)).is_ok());
322 let shouting = Persona {
323 service: "Discord".into(),
324 account: "1".into(),
325 linked: None,
326 };
327 assert_eq!(
328 Appearance::new("alice", None, Some(shouting)),
329 Err(AppearanceError::BadService)
330 );
331 let empty = Persona {
332 service: "discord".into(),
333 account: String::new(),
334 linked: None,
335 };
336 assert_eq!(
337 Appearance::new("alice", None, Some(empty)),
338 Err(AppearanceError::BadAccount)
339 );
340 let linked = |person: &str| Persona {
341 service: "discord".into(),
342 account: "1".into(),
343 linked: Some(person.into()),
344 };
345 assert!(Appearance::new("alice", None, Some(linked(&"ab".repeat(32)))).is_ok());
346 assert_eq!(
347 Appearance::new("alice", None, Some(linked("alice"))),
348 Err(AppearanceError::BadLinked)
349 );
350 }
351
352 phase avatar_bytes_are_a_small_raster_image;
353 {
354 assert_eq!(check_avatar_bytes(&png()), Ok(()));
355 assert_eq!(
356 check_avatar_bytes(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"),
357 Err(AppearanceError::AvatarNotImage)
358 );
359 assert_eq!(
360 check_avatar_bytes(b"hello"),
361 Err(AppearanceError::AvatarNotImage)
362 );
363 let mut big = png();
364 big.resize(MAX_AVATAR_BYTES + 1, 0);
365 assert_eq!(
366 check_avatar_bytes(&big),
367 Err(AppearanceError::AvatarTooLarge)
368 );
369 }
370
371 phase an_appearance_round_trips_and_leaves_out_what_it_lacks;
372 {
373 let appearance = Appearance::new("alice", None, None).unwrap();
374 let json = serde_json::to_string(&appearance).unwrap();
375 assert_eq!(json, r#"{"name":"alice"}"#);
376 assert_eq!(
377 serde_json::from_str::<Appearance>(&json).unwrap(),
378 appearance
379 );
380 }
381
382 phase a_api_that_cannot_check_a_bot_refuses_an_appearance;
383 {
384 use crate::remote::{ActionCallError, InvokeArgument, InvokeRequest, RemoteActionTarget};
385 let mut request = InvokeRequest {
386 invocation: crate::InvocationId(uuid::Uuid::from_u128(1)),
387 target: RemoteActionTarget {
388 provider: "p".into(),
389 address: crate::ActionAddress::new("r", "a"),
390 },
391 argument: InvokeArgument::None,
392 context: None,
393 confirmation: None,
394 revision: None,
395 on_behalf_of: None,
396 wait_ms: None,
397 appearance: None,
398 signed: None,
399 };
400 assert_eq!(refuse_here(&request), Ok(()));
401 request.appearance = Some(Appearance::new("alice", None, None).unwrap());
402 assert!(matches!(
403 refuse_here(&request),
404 Err(ActionCallError::Refused { .. })
405 ));
406 }
407
408 phase only_a_bot_whose_installation_allows_personas_is_admitted;
409 {
410 use crate::remote::{ActionCallError, Caller};
411 let alice = Appearance::new("alice", None, None).unwrap();
412 let bot = Caller::bot("7f1c", [1; 32], [2; 32]);
413 assert_eq!(
414 admit(
415 &bot,
416 &alice,
417 |installation| installation == "7f1c",
418 |_| None
419 ),
420 Ok(alice.clone())
421 );
422 assert!(matches!(
423 admit(&bot, &alice, |_| false, |_| None),
424 Err(ActionCallError::Refused { .. })
425 ));
426 let person = Caller::local_person("ada");
427 assert!(matches!(
428 admit(&person, &alice, |_| true, |_| None),
429 Err(ActionCallError::Refused { .. })
430 ));
431 let hidden = Appearance {
432 name: "a\u{200B}lice".into(),
433 avatar: None,
434 persona: None,
435 };
436 assert!(matches!(
437 admit(&bot, &hidden, |_| true, |_| None),
438 Err(ActionCallError::InvalidRequest { .. })
439 ));
440 }
441
442 phase an_avatar_must_be_in_the_store_match_its_hash_and_be_an_image;
443 {
444 use crate::remote::{ActionCallError, Caller};
445 let bot = Caller::bot("7f1c", [1; 32], [2; 32]);
446 let image = png();
447 let hash = blake3::hash(&image).to_hex().to_string();
448 let shown = Appearance::new("alice", Some(hash.clone()), None).unwrap();
449 let stored = |wanted: &str| (wanted == hash).then(|| image.clone());
450 assert_eq!(admit(&bot, &shown, |_| true, stored), Ok(shown.clone()));
451 let refused = |result: Result<Appearance, ActionCallError>, expected: AppearanceError| {
452 assert_eq!(
453 result,
454 Err(ActionCallError::InvalidRequest {
455 reason: expected.to_string()
456 })
457 );
458 };
459 refused(
460 admit(&bot, &shown, |_| true, |_| None),
461 AppearanceError::AvatarMissing,
462 );
463 refused(
464 admit(&bot, &shown, |_| true, |_| Some(b"other".to_vec())),
465 AppearanceError::AvatarMismatch,
466 );
467 let text = b"not an image".to_vec();
468 let named = Appearance::new(
469 "alice",
470 Some(blake3::hash(&text).to_hex().to_string()),
471 None,
472 )
473 .unwrap();
474 refused(
475 admit(&bot, &named, |_| true, |_| Some(text.clone())),
476 AppearanceError::AvatarNotImage,
477 );
478 }
479 }
480}