Skip to main content

tilo_actions/
appearance.rs

1//! The name and avatar a bot shows for one action, as a webhook does: a
2//! bridge posts a Discord user's message under that user's name. The bot
3//! stays the author; an appearance is presentation recorded in provenance,
4//! never identity. A value that fails validation refuses the invocation; it is
5//! never cleaned up, so what a reader sees is exactly what the bot sent.
6
7use serde::{Deserialize, Serialize};
8use unicode_normalization::{UnicodeNormalization, is_nfc};
9
10/// The longest name, in characters, after trimming.
11pub const MAX_NAME_CHARS: usize = 80;
12/// The largest avatar image.
13pub const MAX_AVATAR_BYTES: usize = 1_048_576;
14const MAX_SERVICE_CHARS: usize = 32;
15const MAX_ACCOUNT_CHARS: usize = 128;
16
17/// What a bot showed for one action instead of its own name and icon.
18#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
19pub struct Appearance {
20    /// The shown name: trimmed, NFC-normalized, 1..=80 characters.
21    pub name: String,
22    /// BLAKE3 hex of an image in the workspace's content store.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub avatar: Option<String>,
25    /// The outside account this stands for.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub persona: Option<Persona>,
28}
29
30/// An account on another service, such as `discord` / `80351110224678912`.
31#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
32pub struct Persona {
33    /// The service, lowercase: `discord`.
34    pub service: String,
35    /// The account's stable id on that service.
36    pub account: String,
37    /// The workspace member (their root key, hex) the account is linked to, as
38    /// the bot speaking for it keeps the link: the shown name is then that
39    /// member's own, not one made to look like it.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub linked: Option<String>,
42}
43
44/// Why an appearance was refused.
45#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
46pub enum AppearanceError {
47    /// Nothing is left after trimming.
48    #[error("the shown name is empty")]
49    EmptyName,
50    /// Longer than [`MAX_NAME_CHARS`].
51    #[error("the shown name is longer than {MAX_NAME_CHARS} characters")]
52    NameTooLong,
53    /// Not in the form [`Appearance::new`] makes.
54    #[error("the shown name is not trimmed and NFC-normalized")]
55    NotNormalized,
56    /// A character that hides or reorders text, by code point.
57    #[error("the shown name contains the hidden or direction-changing character U+{0:04X}")]
58    HiddenCharacter(u32),
59    /// The avatar is no content hash.
60    #[error("the avatar does not name an image by its content hash")]
61    AvatarNotHash,
62    /// Larger than [`MAX_AVATAR_BYTES`].
63    #[error("the avatar is larger than 1 MiB")]
64    AvatarTooLarge,
65    /// Not a raster image.
66    #[error("the avatar is not a PNG, JPEG, WebP or GIF image")]
67    AvatarNotImage,
68    /// Not in the workspace's content store.
69    #[error("the avatar is not in the workspace's content store")]
70    AvatarMissing,
71    /// The bytes do not hash to the name.
72    #[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    /// The account is malformed.
77    #[error("the persona's account must be 1 to 128 visible characters")]
78    BadAccount,
79    /// The linked member is not named by a root key.
80    #[error("the persona's linked member must be a root key in lowercase hex")]
81    BadLinked,
82}
83
84impl Appearance {
85    /// An appearance whose name is trimmed and NFC-normalized, then checked.
86    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    /// Check a value as received: it must already be in the form
101    /// [`Self::new`] makes, so two readers never disagree on the name.
102    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
153/// Characters that hide or reorder text: a name carrying one could render
154/// as somebody else's.
155fn 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
171/// Check the bytes an avatar hash names: small, and a raster image. SVG is
172/// refused because it is a document, not a picture.
173///
174/// # Errors
175/// [`AppearanceError::AvatarTooLarge`] or [`AppearanceError::AvatarNotImage`].
176pub 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
186/// For an API that cannot check that its caller is a bot allowed to show
187/// other names: refuse a request carrying an appearance instead of running
188/// it under the caller's own name.
189///
190/// # Errors
191/// [`crate::remote::ActionCallError::Refused`] when the request carries one.
192pub 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
203/// Admit `appearance` on a request from `caller`, for the workspace-action API:
204/// only a bot whose installation `allows_personas` may show another name, the
205/// appearance must be valid, and its avatar must be an image `avatar` finds
206/// in the workspace's content store under its own hash.
207///
208/// # Errors
209/// [`crate::remote::ActionCallError::Refused`] for a caller that may not show
210/// another name; [`crate::remote::ActionCallError::InvalidRequest`] for an
211/// invalid appearance or avatar.
212pub 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            // "e" + combining acute becomes the single precomposed "é".
259            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}