Skip to main content

babyrite/expand/
discord.rs

1//! Discord message link expansion.
2//!
3//! This module provides functionality for parsing Discord message links
4//! and generating embed previews of the linked messages.
5//!
6//! Migrated from `preview.rs` with support for multiple link expansion.
7
8use futures_util::future::{join_all, try_join_all};
9use regex::Regex;
10use std::collections::{HashMap, HashSet};
11use std::sync::LazyLock;
12use twilight_http::error::ErrorType;
13use twilight_model::channel::message::Embed;
14use twilight_model::channel::permission_overwrite::{PermissionOverwrite, PermissionOverwriteType};
15use twilight_model::channel::{Channel, ChannelType, Message};
16use twilight_model::guild::Permissions;
17use twilight_model::id::{
18    Id,
19    marker::{ChannelMarker, GuildMarker, MessageMarker, RoleMarker, UserMarker},
20};
21use twilight_model::user::User;
22use twilight_util::builder::embed::{
23    EmbedAuthorBuilder, EmbedBuilder, EmbedFooterBuilder, ImageSource,
24};
25
26use super::{ExpandContext, ExpandError, ExpandedContent, LinkExpander};
27use crate::cache::{CacheArgs, RolePermissions};
28use crate::config::BabyriteConfig;
29use crate::context::BotContext;
30
31/// Regex pattern for matching Discord message links.
32///
33/// Supports production, PTB, and Canary Discord URLs.
34pub static MESSAGE_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| {
35    Regex::new(r"https://(?:ptb\.|canary\.)?discord\.com/channels/(\d+)/(\d+)/(\d+)").unwrap()
36});
37
38/// Parsed IDs from a Discord message link.
39#[derive(Debug)]
40pub struct MessageLinkIDs {
41    /// The guild ID from the message link.
42    pub guild_id: Id<GuildMarker>,
43    /// The channel ID from the message link.
44    pub channel_id: Id<ChannelMarker>,
45    /// The message ID from the message link.
46    pub message_id: Id<MessageMarker>,
47}
48
49/// A preview containing the message and its channel.
50#[derive(Debug)]
51pub struct Preview {
52    /// The message to preview.
53    pub message: Message,
54    /// The channel containing the message.
55    pub channel: Channel,
56}
57
58/// Discord message link expander.
59pub struct DiscordExpander;
60
61#[async_trait::async_trait]
62impl LinkExpander for DiscordExpander {
63    /// Discord link expansion is the bot's core function and has no feature flag.
64    fn enabled(&self, _config: &BabyriteConfig) -> bool {
65        true
66    }
67
68    /// Expands Discord message links into embed previews.
69    ///
70    /// The source channel is resolved once — the expanded preview is posted
71    /// there, so it is needed to verify each link target is at least as visible
72    /// as that channel. If it cannot be resolved, Discord expansion is skipped
73    /// entirely (other expanders are unaffected).
74    ///
75    /// Whether a link may be expanded at all is decided by [`Preview::get`].
76    /// The rejections it reports are expected outcomes and are logged at
77    /// `debug`; only genuine failures reach `error` (see
78    /// [`PreviewError::is_policy_rejection`]).
79    #[cfg_attr(coverage_nightly, coverage(off))]
80    async fn expand_all(&self, cx: &ExpandContext<'_>) -> Vec<ExpandedContent> {
81        let links = MessageLinkIDs::parse_all(&cx.message.content);
82        if links.is_empty() {
83            return Vec::new();
84        }
85        tracing::debug!(count = links.len(), "parsed Discord links");
86
87        let source_channel = match (CacheArgs {
88            guild_id: cx.guild_id,
89            channel_id: cx.message.channel_id,
90        })
91        .get(&cx.ctx.http)
92        .await
93        {
94            Ok(channel) => channel,
95            Err(e) => {
96                tracing::error!(error = %e, "failed to resolve source channel");
97                return Vec::new();
98            }
99        };
100
101        join_all(
102            links
103                .iter()
104                .map(|ids| ids.fetch(cx.ctx, cx.guild_id, &source_channel)),
105        )
106        .await
107        .into_iter()
108        .filter_map(|result| match result {
109            Ok(content) => Some(content),
110            Err(ExpandError::Discord(e)) if e.is_policy_rejection() => {
111                tracing::debug!(error = %e, "skipped Discord link by visibility policy");
112                None
113            }
114            Err(e) => {
115                tracing::error!(error = %e, "failed to expand Discord link");
116                None
117            }
118        })
119        .collect()
120    }
121}
122
123/// Errors that can occur when generating a Discord message preview.
124#[derive(thiserror::Error, Debug)]
125pub enum PreviewError {
126    /// The link points into a guild other than the one it was posted in.
127    #[error("The link points to another guild, which cannot be expanded.")]
128    CrossGuild,
129    /// Failed to retrieve channel information from cache.
130    #[error("Failed to retrieve from cache.")]
131    Cache,
132    /// The target channel is marked as NSFW.
133    #[error("NSFW content previews are not permitted, but the channel is marked as NSFW.")]
134    Nsfw,
135    /// The target channel is private or a private thread.
136    #[error("The channel is a private channel or private thread.")]
137    Permission,
138    /// An error occurred while communicating with Discord.
139    // A trait object rather than twilight's error types: their constructors are
140    // private, so a concrete variant could not be built in tests.
141    #[error("Failed to fetch the linked message: {0}")]
142    Discord(#[source] Box<dyn std::error::Error + Send + Sync>),
143}
144
145impl From<twilight_http::Error> for PreviewError {
146    #[cfg_attr(coverage_nightly, coverage(off))]
147    fn from(e: twilight_http::Error) -> Self {
148        Self::Discord(Box::new(e))
149    }
150}
151
152impl From<twilight_http::response::DeserializeBodyError> for PreviewError {
153    #[cfg_attr(coverage_nightly, coverage(off))]
154    fn from(e: twilight_http::response::DeserializeBodyError) -> Self {
155        Self::Discord(Box::new(e))
156    }
157}
158
159impl PreviewError {
160    /// Whether this is the visibility policy working as designed rather than a
161    /// failure.
162    ///
163    /// Rejections happen during normal use, so callers log them at `debug` and
164    /// keep `error` for cases that need attention.
165    pub fn is_policy_rejection(&self) -> bool {
166        // Matched exhaustively rather than with a `_` arm so that a new variant
167        // has to declare its severity instead of silently counting as a failure.
168        match self {
169            Self::CrossGuild | Self::Nsfw | Self::Permission => true,
170            Self::Cache | Self::Discord(_) => false,
171        }
172    }
173}
174
175impl MessageLinkIDs {
176    /// Parses all Discord message links from the given text.
177    ///
178    /// Returns a `Vec<MessageLinkIDs>` containing all valid message links found.
179    /// The shared link policy applies (see [`super::parse_links`]): angle-bracket
180    /// wrapped and duplicate URLs are ignored, and at most 3 links are returned.
181    pub fn parse_all(text: &str) -> Vec<MessageLinkIDs> {
182        super::parse_links(text, &MESSAGE_LINK_REGEX, |captures| {
183            Some(MessageLinkIDs {
184                guild_id: Id::new_checked(captures.get(1)?.as_str().parse().ok()?)?,
185                channel_id: Id::new_checked(captures.get(2)?.as_str().parse().ok()?)?,
186                message_id: Id::new_checked(captures.get(3)?.as_str().parse().ok()?)?,
187            })
188        })
189    }
190
191    /// Fetches the linked message and returns an embed preview.
192    ///
193    /// `source_channel` is the channel where the request originated. It is used to
194    /// ensure the linked content is not exposed to members who could not otherwise
195    /// view it (see [`Preview::get`]). `guild_id` is the guild the request was
196    /// posted in.
197    #[cfg_attr(coverage_nightly, coverage(off))]
198    #[tracing::instrument(
199        skip(self, ctx, guild_id, source_channel),
200        fields(
201            guild_id = %self.guild_id,
202            channel_id = %self.channel_id,
203            message_id = %self.message_id,
204        )
205    )]
206    pub async fn fetch(
207        &self,
208        ctx: &BotContext,
209        guild_id: Id<GuildMarker>,
210        source_channel: &Channel,
211    ) -> Result<ExpandedContent, ExpandError> {
212        let Preview { message, channel } =
213            Preview::get(self, ctx, guild_id, source_channel).await?;
214
215        Ok(ExpandedContent::Embed(Box::new(preview_embed(
216            &message, &channel,
217        ))))
218    }
219}
220
221/// Accent colour of a message preview embed.
222const PREVIEW_EMBED_COLOUR: u32 = 0x7A4AFF;
223
224/// Renders a fetched message as the embed posted in the requester's channel.
225///
226/// Optional parts of the source message stay unset rather than being sent as an
227/// empty string: Discord rejects `""` where it expects a URL or footer text.
228fn preview_embed(message: &Message, channel: &Channel) -> Embed {
229    let mut author = EmbedAuthorBuilder::new(message.author.name.clone());
230    if let Some(url) = avatar_url(&message.author) {
231        author = author.icon_url(ImageSource::url(url).expect("CDN URL is https"));
232    }
233
234    let mut embed = EmbedBuilder::new()
235        .description(message.content.clone())
236        .author(author)
237        .timestamp(message.timestamp)
238        .color(PREVIEW_EMBED_COLOUR);
239
240    if let Some(name) = &channel.name {
241        embed = embed.footer(EmbedFooterBuilder::new(name.clone()));
242    }
243
244    if let Some(source) = message
245        .attachments
246        .first()
247        .and_then(|attachment| ImageSource::url(attachment.url.clone()).ok())
248    {
249        embed = embed.image(source);
250    }
251
252    embed.build()
253}
254
255/// Returns the CDN URL of `user`'s avatar, or `None` when they have none.
256fn avatar_url(user: &User) -> Option<String> {
257    let hash = user.avatar?;
258    let ext = if hash.is_animated() { "gif" } else { "webp" };
259    Some(format!(
260        "https://cdn.discordapp.com/avatars/{}/{hash}.{ext}?size=1024",
261        user.id
262    ))
263}
264
265/// Returns `true` for thread channel types.
266///
267/// Threads do not carry their own permission overwrites; their visibility
268/// follows the parent channel. This is used to decide whether visibility must be
269/// resolved against the parent (see [`permission_channel`]).
270fn is_thread(kind: ChannelType) -> bool {
271    matches!(
272        kind,
273        ChannelType::AnnouncementThread | ChannelType::PublicThread | ChannelType::PrivateThread
274    )
275}
276
277/// Returns `true` if any overwrite targets a kind Discord added after this
278/// library was written.
279///
280/// Its effect cannot be evaluated by [`Visibility`], so its presence forces a
281/// conservative rejection.
282fn has_unknown_overwrite(overwrites: &[PermissionOverwrite]) -> bool {
283    overwrites
284        .iter()
285        .any(|ow| matches!(ow.kind, PermissionOverwriteType::Unknown(_)))
286}
287
288/// The permission overwrites of `channel`; Discord omits the field when empty.
289fn overwrites(channel: &Channel) -> &[PermissionOverwrite] {
290    channel.permission_overwrites.as_deref().unwrap_or(&[])
291}
292
293/// Returns `true` when a link crosses a guild boundary.
294///
295/// Roles, permission overwrites and the `@everyone` id are all guild-local, so
296/// [`check_visibility`] cannot evaluate a channel in
297/// another guild — and the bot may not even be a member of that guild. Such
298/// links are refused outright rather than judged.
299fn is_cross_guild(link: Id<GuildMarker>, source: Id<GuildMarker>) -> bool {
300    link != source
301}
302
303/// Returns `true` when the readers of a channel of `kind` cannot be evaluated.
304///
305/// The readers of a DM or private thread are its members, and listing them
306/// needs the `GUILD_MEMBERS` intent. A private thread quoted from within itself
307/// (`same_channel`) is the exception: the reply reaches only its members, who
308/// all view the parent, so judging it by the parent over-approximates the
309/// readers, which can only cause a refusal.
310fn has_unlisted_readers(kind: ChannelType, same_channel: bool) -> bool {
311    match kind {
312        ChannelType::Private => true,
313        ChannelType::PrivateThread => !same_channel,
314        _ => false,
315    }
316}
317
318/// Permissions a member needs to read the linked message in a text channel.
319///
320/// `READ_MESSAGE_HISTORY` is required on top of `VIEW_CHANNEL`: without it a
321/// member only sees messages sent while they are watching, never an older one a
322/// link points at.
323const READ_TARGET: Permissions = Permissions::VIEW_CHANNEL.union(Permissions::READ_MESSAGE_HISTORY);
324
325/// Permissions a member needs to read the expanded reply in the source channel.
326const READ_SOURCE: Permissions = Permissions::VIEW_CHANNEL;
327
328/// Permissions a member needs to read the linked message in a channel of `kind`.
329///
330/// The text chat of voice and stage channels is closed to members who cannot
331/// `CONNECT`, even when they can view the channel itself.
332fn read_target_requirement(kind: ChannelType) -> Permissions {
333    match kind {
334        ChannelType::GuildVoice | ChannelType::GuildStageVoice => {
335            READ_TARGET | Permissions::CONNECT
336        }
337        _ => READ_TARGET,
338    }
339}
340
341/// Permissions a member needs to read the expanded reply in the source channel,
342/// when the link points to a channel of `target_kind`.
343///
344/// A link back into the source channel (`same_channel`) makes the source a
345/// channel of `target_kind` too, so reading the reply there takes what reading
346/// that channel does, short of `READ_MESSAGE_HISTORY`: the reply is a new
347/// message.
348fn read_source_requirement(target_kind: ChannelType, same_channel: bool) -> Permissions {
349    if same_channel {
350        read_target_requirement(target_kind) - Permissions::READ_MESSAGE_HISTORY
351    } else {
352        READ_SOURCE
353    }
354}
355
356/// The `(allow, deny)` pair of a permission overwrite.
357type OverwritePair = (Permissions, Permissions);
358
359const NO_OVERWRITE: OverwritePair = (Permissions::empty(), Permissions::empty());
360
361/// A channel's permission overwrites, split by what they target and masked to
362/// the permissions that matter for that channel.
363#[derive(Debug)]
364struct ChannelOverwrites {
365    everyone: OverwritePair,
366    roles: HashMap<Id<RoleMarker>, OverwritePair>,
367    members: HashMap<Id<UserMarker>, OverwritePair>,
368}
369
370impl ChannelOverwrites {
371    fn new(
372        overwrites: &[PermissionOverwrite],
373        everyone_role_id: Id<RoleMarker>,
374        relevant: Permissions,
375    ) -> Self {
376        let mut this = Self {
377            everyone: NO_OVERWRITE,
378            roles: HashMap::new(),
379            members: HashMap::new(),
380        };
381        for ow in overwrites {
382            let pair = (ow.allow & relevant, ow.deny & relevant);
383            match ow.kind {
384                PermissionOverwriteType::Role if ow.id.cast() == everyone_role_id => {
385                    this.everyone = pair;
386                }
387                PermissionOverwriteType::Role => {
388                    this.roles.insert(ow.id.cast(), pair);
389                }
390                PermissionOverwriteType::Member => {
391                    this.members.insert(ow.id.cast(), pair);
392                }
393                // Refused by `has_unknown_overwrite` before any of this is built.
394                _ => {}
395            }
396        }
397        this
398    }
399
400    fn role(&self, role_id: Id<RoleMarker>) -> OverwritePair {
401        self.roles.get(&role_id).copied().unwrap_or(NO_OVERWRITE)
402    }
403
404    fn member(&self, user_id: Id<UserMarker>) -> OverwritePair {
405        self.members.get(&user_id).copied().unwrap_or(NO_OVERWRITE)
406    }
407}
408
409/// What a set of roles contributes to a member's permissions in the source and
410/// target channels.
411///
412/// Discord merges a member's roles by OR-ing their base permissions, and their
413/// role overwrites by OR-ing the allows and the denies separately. Every field
414/// here is merged the same way, so the grant of any set of roles is the
415/// [`Self::union`] of the grants of its roles.
416#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
417struct RoleGrant {
418    base: Permissions,
419    source: OverwritePair,
420    target: OverwritePair,
421}
422
423impl RoleGrant {
424    fn union(self, other: Self) -> Self {
425        let merge = |(a1, d1): OverwritePair, (a2, d2): OverwritePair| (a1 | a2, d1 | d2);
426        Self {
427            base: self.base | other.base,
428            source: merge(self.source, other.source),
429            target: merge(self.target, other.target),
430        }
431    }
432}
433
434/// Applies Discord's permission algorithm to one channel.
435///
436/// `ADMINISTRATOR` in the base grants everything. Otherwise the `@everyone`
437/// overwrite, the merged role overwrites and the member's own overwrite are
438/// applied in that order, each as deny-then-allow.
439fn channel_permissions(
440    base: Permissions,
441    everyone: OverwritePair,
442    roles: OverwritePair,
443    member: OverwritePair,
444) -> Permissions {
445    if base.contains(Permissions::ADMINISTRATOR) {
446        return Permissions::all();
447    }
448    [everyone, roles, member]
449        .into_iter()
450        .fold(base, |perms, (allow, deny)| (perms - deny) | allow)
451}
452
453/// Decides whether everyone who can read the source channel could also read the
454/// target channel.
455///
456/// Members are split by whether either channel carries an overwrite for them
457/// personally:
458///
459/// - Without one, a member's access depends only on which roles they hold.
460///   [`Self::roles_preserve_visibility`] checks every combination of roles a
461///   member could hold — not just each role on its own, since Discord merges a
462///   member's role overwrites before applying them.
463/// - With one, the member is looked up and judged on their actual roles by
464///   [`Self::member_preserves_visibility`]. [`Self::members_to_verify`] lists
465///   only those whose personal overwrite could make a difference.
466#[derive(Debug)]
467struct Visibility {
468    source: ChannelOverwrites,
469    target: ChannelOverwrites,
470    /// What a member needs in the source, from [`read_source_requirement`].
471    read_source: Permissions,
472    /// What a member needs in the target, from [`read_target_requirement`].
473    read_target: Permissions,
474    everyone_role_id: Id<RoleMarker>,
475    role_perms: RolePermissions,
476    /// Every grant a member without personal overwrites can hold.
477    reachable: HashSet<RoleGrant>,
478}
479
480impl Visibility {
481    fn new(
482        source_overwrites: &[PermissionOverwrite],
483        target_overwrites: &[PermissionOverwrite],
484        read_source: Permissions,
485        read_target: Permissions,
486        role_perms: RolePermissions,
487        everyone_role_id: Id<RoleMarker>,
488    ) -> Self {
489        let mut this = Self {
490            source: ChannelOverwrites::new(source_overwrites, everyone_role_id, read_source),
491            target: ChannelOverwrites::new(target_overwrites, everyone_role_id, read_target),
492            read_source,
493            read_target,
494            everyone_role_id,
495            role_perms,
496            reachable: HashSet::new(),
497        };
498        this.reachable = this.reachable_grants();
499        this
500    }
501
502    /// The grant of `@everyone`, which every member holds. Its overwrite is
503    /// applied separately, so it contributes base permissions only.
504    fn everyone_grant(&self) -> RoleGrant {
505        RoleGrant {
506            base: self.base_of(self.everyone_role_id),
507            source: NO_OVERWRITE,
508            target: NO_OVERWRITE,
509        }
510    }
511
512    fn role_grant(&self, role_id: Id<RoleMarker>) -> RoleGrant {
513        RoleGrant {
514            base: self.base_of(role_id),
515            source: self.source.role(role_id),
516            target: self.target.role(role_id),
517        }
518    }
519
520    /// Masked to the base permissions that can change the outcome of
521    /// [`channel_permissions`], so that equivalent roles collapse into one
522    /// [`RoleGrant`] and [`Self::reachable_grants`] stays small.
523    fn base_of(&self, role_id: Id<RoleMarker>) -> Permissions {
524        self.role_perms
525            .get(&role_id)
526            .copied()
527            .unwrap_or_else(Permissions::empty)
528            & (Permissions::ADMINISTRATOR | self.read_source | self.read_target)
529    }
530
531    /// Closes `@everyone`'s grant under union with every other role's grant.
532    ///
533    /// Why not enumerate role subsets: that is exponential in the number of
534    /// roles, while the masked grants have only a few bits, so the closure stays
535    /// small no matter how many roles the guild has.
536    ///
537    /// Roles named only by an overwrite are included too: a role created after
538    /// the role cache was filled still restricts whoever holds it.
539    fn reachable_grants(&self) -> HashSet<RoleGrant> {
540        let roles: HashSet<RoleGrant> = self
541            .role_perms
542            .keys()
543            .chain(self.source.roles.keys())
544            .chain(self.target.roles.keys())
545            .filter(|&&id| id != self.everyone_role_id)
546            .map(|&id| self.role_grant(id))
547            .collect();
548
549        let start = self.everyone_grant();
550        let mut reachable = HashSet::from([start]);
551        let mut pending = vec![start];
552        while let Some(grant) = pending.pop() {
553            for &role in &roles {
554                let next = grant.union(role);
555                if reachable.insert(next) {
556                    pending.push(next);
557                }
558            }
559        }
560        reachable
561    }
562
563    fn source_permissions(&self, grant: RoleGrant, member: OverwritePair) -> Permissions {
564        channel_permissions(grant.base, self.source.everyone, grant.source, member)
565    }
566
567    fn target_permissions(&self, grant: RoleGrant, member: OverwritePair) -> Permissions {
568        channel_permissions(grant.base, self.target.everyone, grant.target, member)
569    }
570
571    /// Whether a member with `grant` and the given personal overwrites can read
572    /// the source but not the target.
573    fn leaks(
574        &self,
575        grant: RoleGrant,
576        source_member: OverwritePair,
577        target_member: OverwritePair,
578    ) -> bool {
579        self.source_permissions(grant, source_member)
580            .contains(self.read_source)
581            && !self
582                .target_permissions(grant, target_member)
583                .contains(self.read_target)
584    }
585
586    /// Whether no combination of roles lets a member read the source but not the
587    /// target, for members without personal overwrites.
588    fn roles_preserve_visibility(&self) -> bool {
589        self.reachable
590            .iter()
591            .all(|&grant| !self.leaks(grant, NO_OVERWRITE, NO_OVERWRITE))
592    }
593
594    /// Members whose personal overwrites could let them read the source but not
595    /// the target, sorted by id.
596    ///
597    /// A member is listed only when some role combination, together with their
598    /// personal overwrites, leaks; for anyone else the outcome is the same
599    /// whatever roles they actually hold, so looking them up is wasted.
600    fn members_to_verify(&self) -> Vec<Id<UserMarker>> {
601        let users: HashSet<Id<UserMarker>> = self
602            .source
603            .members
604            .keys()
605            .chain(self.target.members.keys())
606            .copied()
607            .collect();
608        let mut users: Vec<_> = users
609            .into_iter()
610            .filter(|&user| {
611                let (source_member, target_member) =
612                    (self.source.member(user), self.target.member(user));
613                self.reachable
614                    .iter()
615                    .any(|&grant| self.leaks(grant, source_member, target_member))
616            })
617            .collect();
618        users.sort_unstable();
619        users
620    }
621
622    /// Whether `user`, holding `roles`, cannot read the source without also being
623    /// able to read the target.
624    fn member_preserves_visibility(&self, user: Id<UserMarker>, roles: &[Id<RoleMarker>]) -> bool {
625        let grant = roles
626            .iter()
627            .filter(|&&id| id != self.everyone_role_id)
628            .fold(self.everyone_grant(), |grant, &id| {
629                grant.union(self.role_grant(id))
630            });
631        !self.leaks(grant, self.source.member(user), self.target.member(user))
632    }
633}
634
635/// Resolves the channel that carries the properties a thread inherits — its
636/// permission overwrites and its NSFW flag.
637///
638/// Threads hold neither of their own, so for any thread the parent channel is
639/// fetched and returned. Non-thread channels are returned unchanged. A thread
640/// without a `parent_id` is treated as an error.
641#[cfg_attr(coverage_nightly, coverage(off))]
642async fn permission_channel(
643    channel: &Channel,
644    guild_id: Id<GuildMarker>,
645    ctx: &BotContext,
646) -> Result<Channel, PreviewError> {
647    if !is_thread(channel.kind) {
648        return Ok(channel.clone());
649    }
650
651    let parent_id = channel.parent_id.ok_or(PreviewError::Permission)?;
652    CacheArgs {
653        guild_id,
654        channel_id: parent_id,
655    }
656    .get(&ctx.http)
657    .await
658    .map_err(|_| PreviewError::Cache)
659}
660
661/// Most members [`check_visibility`] looks up for a single link.
662///
663/// Each lookup is an API request made on every expansion, since the result
664/// cannot be cached (see [`member_roles`]). Past this many, the link is refused
665/// rather than spending that much rate limit on it.
666const MAX_MEMBER_LOOKUPS: usize = 10;
667
668/// Fetches the roles of `user_id`, or `None` when they are not in the guild.
669///
670/// Why not cached: without the privileged `GUILD_MEMBERS` intent no event
671/// reports a member's role changes, so a cached entry could never be
672/// invalidated.
673#[cfg_attr(coverage_nightly, coverage(off))]
674async fn member_roles(
675    ctx: &BotContext,
676    guild_id: Id<GuildMarker>,
677    user_id: Id<UserMarker>,
678) -> Result<Option<Vec<Id<RoleMarker>>>, PreviewError> {
679    match ctx.http.guild_member(guild_id, user_id).await {
680        Ok(response) => Ok(Some(response.model().await?.roles)),
681        Err(e) if matches!(e.kind(), ErrorType::Response { status, .. } if status.get() == 404) => {
682            Ok(None)
683        }
684        Err(e) => Err(e.into()),
685    }
686}
687
688/// Validates that everyone who can read `source_channel` could also read the
689/// linked message in `channel`.
690///
691/// The expanded content is posted as a single message that all members of
692/// `source_channel` can read, so the linked channel must be at least as
693/// readable as the source channel to avoid leaking restricted content.
694/// "Readable" means what [`read_source_requirement`] asks for on the source,
695/// and what [`read_target_requirement`] asks for on the target; a link back
696/// into `source_channel` is judged with that channel as both. Permissions are
697/// evaluated by [`Visibility`] the way Discord does, so roles, role
698/// combinations, per-member overwrites and `ADMINISTRATOR` need no special
699/// cases.
700///
701/// What remains is refused because it cannot be evaluated:
702///
703/// - Links into another guild, refused by [`Preview::get`] before this runs:
704///   roles and overwrites are guild-local, and the bot may not be in that guild.
705/// - Private threads (and DMs), unless quoted from within the same private
706///   thread (see [`has_unlisted_readers`]).
707/// - Overwrites of a kind this library does not know.
708/// - More than [`MAX_MEMBER_LOOKUPS`] members needing a lookup.
709///
710/// Threads have no overwrites of their own and are judged by their parent. For
711/// a public thread that is exact; for a private thread used as the source it
712/// over-approximates the readers, which can only cause a refusal.
713/// `dest_perm` is `channel` resolved by [`permission_channel`].
714#[cfg_attr(coverage_nightly, coverage(off))]
715async fn check_visibility(
716    channel: &Channel,
717    dest_perm: &Channel,
718    source_channel: &Channel,
719    guild_id: Id<GuildMarker>,
720    ctx: &BotContext,
721) -> Result<(), PreviewError> {
722    let same_channel = channel.id == source_channel.id;
723    if has_unlisted_readers(channel.kind, same_channel) {
724        tracing::debug!(kind = ?channel.kind, "rejected: private channel or thread");
725        return Err(PreviewError::Permission);
726    }
727
728    let source_perm = permission_channel(source_channel, guild_id, ctx).await?;
729
730    if has_unknown_overwrite(overwrites(dest_perm))
731        || has_unknown_overwrite(overwrites(&source_perm))
732    {
733        tracing::debug!("rejected: overwrite of unknown kind");
734        return Err(PreviewError::Permission);
735    }
736
737    let role_perms = crate::cache::role_permissions(&ctx.http, guild_id)
738        .await
739        .map_err(|_| PreviewError::Cache)?;
740    let visibility = Visibility::new(
741        overwrites(&source_perm),
742        overwrites(dest_perm),
743        read_source_requirement(channel.kind, same_channel),
744        read_target_requirement(channel.kind),
745        role_perms,
746        guild_id.cast(),
747    );
748
749    if !visibility.roles_preserve_visibility() {
750        tracing::debug!("rejected: a role combination can read the source but not the target");
751        return Err(PreviewError::Permission);
752    }
753
754    let users = visibility.members_to_verify();
755    if users.len() > MAX_MEMBER_LOOKUPS {
756        tracing::debug!(
757            members = users.len(),
758            "rejected: too many members with personal overwrites to verify"
759        );
760        return Err(PreviewError::Permission);
761    }
762
763    let roles = try_join_all(users.iter().map(|&user| member_roles(ctx, guild_id, user))).await?;
764    for (&user, roles) in users.iter().zip(roles) {
765        if let Some(roles) = roles
766            && !visibility.member_preserves_visibility(user, &roles)
767        {
768            tracing::debug!(%user, "rejected: member can read the source but not the target");
769            return Err(PreviewError::Permission);
770        }
771    }
772
773    Ok(())
774}
775
776impl Preview {
777    /// Retrieves a preview for the given message link.
778    ///
779    /// Every rule deciding whether a link may be expanded lives here. In order,
780    /// the link must point into `guild_id` — the guild of `source_channel` —
781    /// and the linked channel must not be NSFW, must not be a DM or a private
782    /// thread other than `source_channel`, and must be readable by everyone who
783    /// can view `source_channel`. The expanded content is posted as a single
784    /// message that all members of `source_channel` can read, so the linked channel must be at least as
785    /// visible as the source channel to avoid leaking restricted content. Public
786    /// and news threads are judged by their parent channel, which holds both the
787    /// permission overwrites and the NSFW flag they inherit.
788    ///
789    /// The guild boundary is checked before the channel is resolved. Roles and
790    /// permission overwrites are guild-local, so a link into another guild
791    /// cannot be judged at all, and resolving it would spend rate limit on a
792    /// guild the bot may not even be in.
793    ///
794    /// A link back into `source_channel` is not exempt: its readers may lack
795    /// `READ_MESSAGE_HISTORY` there, and the reply would show them an older
796    /// message.
797    #[cfg_attr(coverage_nightly, coverage(off))]
798    #[tracing::instrument(
799        skip(args, ctx, guild_id, source_channel),
800        fields(
801            guild_id = %args.guild_id,
802            channel_id = %args.channel_id,
803            message_id = %args.message_id,
804        )
805    )]
806    async fn get(
807        args: &MessageLinkIDs,
808        ctx: &BotContext,
809        guild_id: Id<GuildMarker>,
810        source_channel: &Channel,
811    ) -> Result<Preview, PreviewError> {
812        if is_cross_guild(args.guild_id, guild_id) {
813            tracing::debug!(link_guild_id = %args.guild_id, "rejected: cross-guild link");
814            return Err(PreviewError::CrossGuild);
815        }
816
817        let caches = CacheArgs {
818            // Not `args.guild_id`: that is the value the URL claims. It equals
819            // the source guild after the check above, so take the one Discord
820            // reported for the request and keep guild scoping sourced from it.
821            guild_id,
822            channel_id: args.channel_id,
823        };
824
825        let channel = caches
826            .get(&ctx.http)
827            .await
828            .map_err(|_| PreviewError::Cache)?;
829        tracing::debug!(kind = ?channel.kind, nsfw = ?channel.nsfw, "resolved target channel");
830
831        // Judged on the parent for threads, not on `channel.nsfw` directly:
832        // Discord omits `nsfw` from thread objects because threads inherit it,
833        // and twilight leaves the absent field `None`, so every thread under an
834        // NSFW channel would otherwise slip past this gate.
835        let age_gate = permission_channel(&channel, guild_id, ctx).await?;
836        if age_gate.nsfw.unwrap_or(false) {
837            tracing::debug!("rejected: target channel is NSFW");
838            return Err(PreviewError::Nsfw);
839        }
840
841        check_visibility(&channel, &age_gate, source_channel, guild_id, ctx).await?;
842
843        let started = std::time::Instant::now();
844        let message = ctx
845            .http
846            .message(channel.id, args.message_id)
847            .await?
848            .model()
849            .await?;
850        tracing::debug!(
851            elapsed_ms = started.elapsed().as_millis(),
852            "fetched linked message"
853        );
854        Ok(Preview { message, channel })
855    }
856}
857
858#[cfg(test)]
859mod tests {
860    use super::*;
861
862    #[test]
863    fn parse_standard_link() {
864        let text = "https://discord.com/channels/123456789/987654321/111111111";
865        let results = MessageLinkIDs::parse_all(text);
866        assert_eq!(results.len(), 1);
867        assert_eq!(results[0].guild_id, Id::new(123456789));
868        assert_eq!(results[0].channel_id, Id::new(987654321));
869        assert_eq!(results[0].message_id, Id::new(111111111));
870    }
871
872    #[test]
873    fn parse_ptb_link() {
874        let text = "https://ptb.discord.com/channels/123/456/789";
875        let results = MessageLinkIDs::parse_all(text);
876        assert_eq!(results.len(), 1);
877        assert_eq!(results[0].guild_id, Id::new(123));
878    }
879
880    #[test]
881    fn parse_canary_link() {
882        let text = "https://canary.discord.com/channels/123/456/789";
883        let results = MessageLinkIDs::parse_all(text);
884        assert_eq!(results.len(), 1);
885        assert_eq!(results[0].guild_id, Id::new(123));
886    }
887
888    #[test]
889    fn parse_multiple_links() {
890        let text = "https://discord.com/channels/1/2/3 and https://discord.com/channels/4/5/6";
891        let results = MessageLinkIDs::parse_all(text);
892        assert_eq!(results.len(), 2);
893        assert_eq!(results[0].guild_id, Id::new(1));
894        assert_eq!(results[1].guild_id, Id::new(4));
895    }
896
897    #[test]
898    fn parse_deduplicates() {
899        let text = "https://discord.com/channels/1/2/3 https://discord.com/channels/1/2/3";
900        let results = MessageLinkIDs::parse_all(text);
901        assert_eq!(results.len(), 1);
902    }
903
904    #[test]
905    fn parse_limits_to_three() {
906        let text = "\
907            https://discord.com/channels/1/2/3 \
908            https://discord.com/channels/4/5/6 \
909            https://discord.com/channels/7/8/9 \
910            https://discord.com/channels/10/11/12";
911        let results = MessageLinkIDs::parse_all(text);
912        assert_eq!(results.len(), 3);
913    }
914
915    #[test]
916    fn parse_ignores_zero_ids() {
917        for text in [
918            "https://discord.com/channels/0/1/2",
919            "https://discord.com/channels/1/0/2",
920            "https://discord.com/channels/1/2/0",
921        ] {
922            assert!(MessageLinkIDs::parse_all(text).is_empty(), "{text}");
923        }
924    }
925
926    #[test]
927    fn parse_no_match() {
928        let text = "Just some regular text";
929        let results = MessageLinkIDs::parse_all(text);
930        assert!(results.is_empty());
931    }
932
933    #[test]
934    fn parse_ignores_invalid_url() {
935        // Non-discord domain should not match (regex anchors to discord.com)
936        let text = "https://notdiscord.com/channels/1/2/3";
937        let results = MessageLinkIDs::parse_all(text);
938        assert!(results.is_empty());
939    }
940
941    #[test]
942    fn parse_ignores_angle_bracket_link() {
943        let text = "<https://discord.com/channels/123/456/789>";
944        let results = MessageLinkIDs::parse_all(text);
945        assert!(results.is_empty());
946    }
947
948    #[test]
949    fn parse_mixed_with_text() {
950        let text = "Hey check this out https://discord.com/channels/1/2/3 pretty cool right?";
951        let results = MessageLinkIDs::parse_all(text);
952        assert_eq!(results.len(), 1);
953        assert_eq!(results[0].message_id, Id::new(3));
954    }
955
956    // --- Privacy / permission resolution ---
957
958    /// Builds a role VIEW_CHANNEL overwrite.
959    fn role_ow(id: u64, allow_view: bool, deny_view: bool) -> PermissionOverwrite {
960        PermissionOverwrite {
961            allow: if allow_view {
962                Permissions::VIEW_CHANNEL
963            } else {
964                Permissions::empty()
965            },
966            deny: if deny_view {
967                Permissions::VIEW_CHANNEL
968            } else {
969                Permissions::empty()
970            },
971            id: Id::new(id),
972            kind: PermissionOverwriteType::Role,
973        }
974    }
975
976    /// Builds a per-member overwrite allowing and/or denying VIEW_CHANNEL.
977    fn member_ow(id: u64, allow_view: bool, deny_view: bool) -> PermissionOverwrite {
978        let bit = |set: bool| {
979            if set {
980                Permissions::VIEW_CHANNEL
981            } else {
982                Permissions::empty()
983            }
984        };
985        PermissionOverwrite {
986            allow: bit(allow_view),
987            deny: bit(deny_view),
988            id: Id::new(id),
989            kind: PermissionOverwriteType::Member,
990        }
991    }
992
993    const EVERYONE: Id<RoleMarker> = Id::new(1);
994    const MEMBER: Id<RoleMarker> = Id::new(100);
995    const SPECIAL: Id<RoleMarker> = Id::new(200);
996    const ADMIN: Id<RoleMarker> = Id::new(300);
997
998    #[test]
999    fn thread_kinds_detected() {
1000        assert!(is_thread(ChannelType::PublicThread));
1001        assert!(is_thread(ChannelType::AnnouncementThread));
1002        assert!(is_thread(ChannelType::PrivateThread));
1003        assert!(!is_thread(ChannelType::GuildText));
1004        assert!(!is_thread(ChannelType::GuildVoice));
1005    }
1006
1007    #[test]
1008    fn unknown_overwrite_kind_is_detected() {
1009        let unknown = PermissionOverwrite {
1010            allow: Permissions::empty(),
1011            deny: Permissions::empty(),
1012            id: Id::new(5),
1013            kind: PermissionOverwriteType::Unknown(9),
1014        };
1015        assert!(has_unknown_overwrite(&[role_ow(1, true, false), unknown]));
1016        assert!(!has_unknown_overwrite(&[
1017            role_ow(1, true, false),
1018            member_ow(5, false, true)
1019        ]));
1020        assert!(!has_unknown_overwrite(&[]));
1021    }
1022
1023    #[test]
1024    fn dms_are_never_judged() {
1025        assert!(has_unlisted_readers(ChannelType::Private, false));
1026        assert!(has_unlisted_readers(ChannelType::Private, true));
1027    }
1028
1029    #[test]
1030    fn private_threads_are_judged_only_when_quoted_from_within() {
1031        assert!(has_unlisted_readers(ChannelType::PrivateThread, false));
1032        assert!(!has_unlisted_readers(ChannelType::PrivateThread, true));
1033        assert!(!has_unlisted_readers(ChannelType::PublicThread, false));
1034        assert!(!has_unlisted_readers(ChannelType::GuildText, false));
1035    }
1036
1037    #[test]
1038    fn cross_guild_links_are_rejected() {
1039        let guild = Id::new(7);
1040        // A link into the guild it was posted in may be judged further.
1041        assert!(!is_cross_guild(guild, guild));
1042        // A link from any other guild is refused outright.
1043        assert!(is_cross_guild(Id::new(8), guild));
1044    }
1045
1046    #[test]
1047    fn only_visibility_rejections_count_as_policy() {
1048        // Expected outcomes of the visibility policy: logged at debug.
1049        assert!(PreviewError::CrossGuild.is_policy_rejection());
1050        assert!(PreviewError::Nsfw.is_policy_rejection());
1051        assert!(PreviewError::Permission.is_policy_rejection());
1052        // Genuine failures: logged at error.
1053        assert!(!PreviewError::Cache.is_policy_rejection());
1054        assert!(
1055            !PreviewError::Discord(Box::new(std::io::Error::other("boom"))).is_policy_rejection()
1056        );
1057    }
1058
1059    // --- Visibility ---
1060
1061    const ROLE_A: Id<RoleMarker> = Id::new(400);
1062    const ROLE_B: Id<RoleMarker> = Id::new(500);
1063    const USER: Id<UserMarker> = Id::new(5);
1064
1065    /// Builds an overwrite with arbitrary permissions.
1066    fn overwrite(
1067        kind: PermissionOverwriteType,
1068        id: u64,
1069        allow: Permissions,
1070        deny: Permissions,
1071    ) -> PermissionOverwrite {
1072        PermissionOverwrite {
1073            allow,
1074            deny,
1075            id: Id::new(id),
1076            kind,
1077        }
1078    }
1079
1080    /// Role permissions where `@everyone` can view channels and read their history
1081    /// by default, as in a freshly created guild, and every other role adds nothing.
1082    fn default_roles(others: &[Id<RoleMarker>]) -> HashMap<Id<RoleMarker>, Permissions> {
1083        let mut roles = HashMap::from([(EVERYONE, READ_TARGET)]);
1084        roles.extend(others.iter().map(|&id| (id, Permissions::empty())));
1085        roles
1086    }
1087
1088    fn visibility(
1089        source: &[PermissionOverwrite],
1090        target: &[PermissionOverwrite],
1091        roles: &HashMap<Id<RoleMarker>, Permissions>,
1092    ) -> Visibility {
1093        Visibility::new(
1094            source,
1095            target,
1096            READ_SOURCE,
1097            READ_TARGET,
1098            roles.clone(),
1099            EVERYONE,
1100        )
1101    }
1102
1103    /// `@everyone` denied, `role` allowed: a channel only `role` can view.
1104    fn gated_to(role: Id<RoleMarker>) -> [PermissionOverwrite; 2] {
1105        [
1106            role_ow(EVERYONE.get(), false, true),
1107            role_ow(role.get(), true, false),
1108        ]
1109    }
1110
1111    #[test]
1112    fn public_channels_preserve_visibility() {
1113        let v = visibility(&[], &[], &default_roles(&[MEMBER]));
1114        assert!(v.roles_preserve_visibility());
1115        assert!(v.members_to_verify().is_empty());
1116    }
1117
1118    #[test]
1119    fn equally_gated_channels_preserve_visibility() {
1120        let gate = gated_to(MEMBER);
1121        let v = visibility(&gate, &gate, &default_roles(&[MEMBER]));
1122        assert!(v.roles_preserve_visibility());
1123    }
1124
1125    #[test]
1126    fn target_gated_to_another_role_is_rejected() {
1127        let v = visibility(
1128            &gated_to(MEMBER),
1129            &gated_to(SPECIAL),
1130            &default_roles(&[MEMBER, SPECIAL]),
1131        );
1132        assert!(!v.roles_preserve_visibility());
1133    }
1134
1135    #[test]
1136    fn narrower_source_may_quote_wider_target() {
1137        let v = visibility(&gated_to(SPECIAL), &[], &default_roles(&[SPECIAL]));
1138        assert!(v.roles_preserve_visibility());
1139    }
1140
1141    #[test]
1142    fn member_granted_source_by_one_role_and_denied_target_by_another_is_rejected() {
1143        // GHSA-9857-rwch-jhw6: each role alone views both channels or neither, but a
1144        // member holding A and B views the source (B's allow follows A's deny) and
1145        // not the target (A's deny is its only role overwrite).
1146        let source = [
1147            role_ow(ROLE_A.get(), false, true),
1148            role_ow(ROLE_B.get(), true, false),
1149        ];
1150        let target = [role_ow(ROLE_A.get(), false, true)];
1151        let v = visibility(&source, &target, &default_roles(&[ROLE_A, ROLE_B]));
1152        assert!(!v.roles_preserve_visibility());
1153    }
1154
1155    #[test]
1156    fn role_denied_on_target_held_alongside_role_gating_source_is_rejected() {
1157        // A member holding A views the gated source; adding B, denied on the
1158        // otherwise public target, takes the target away.
1159        let target = [role_ow(ROLE_B.get(), false, true)];
1160        let v = visibility(
1161            &gated_to(ROLE_A),
1162            &target,
1163            &default_roles(&[ROLE_A, ROLE_B]),
1164        );
1165        assert!(!v.roles_preserve_visibility());
1166    }
1167
1168    #[test]
1169    fn role_allow_on_target_outweighs_another_roles_deny() {
1170        // Role allows are applied after role denies, so holding B as well cannot
1171        // take the target away from a member who holds A.
1172        let target = [
1173            role_ow(ROLE_B.get(), false, true),
1174            role_ow(ROLE_A.get(), true, false),
1175        ];
1176        let v = visibility(
1177            &gated_to(ROLE_A),
1178            &target,
1179            &default_roles(&[ROLE_A, ROLE_B]),
1180        );
1181        assert!(v.roles_preserve_visibility());
1182    }
1183
1184    #[test]
1185    fn target_without_read_message_history_is_rejected() {
1186        let target = [overwrite(
1187            PermissionOverwriteType::Role,
1188            EVERYONE.get(),
1189            Permissions::empty(),
1190            Permissions::READ_MESSAGE_HISTORY,
1191        )];
1192        let v = visibility(&[], &target, &default_roles(&[]));
1193        assert!(!v.roles_preserve_visibility());
1194    }
1195
1196    #[test]
1197    fn source_without_read_message_history_still_counts_its_viewers() {
1198        // The reply is a new message, so viewing the source is enough to read it.
1199        let source = [overwrite(
1200            PermissionOverwriteType::Role,
1201            EVERYONE.get(),
1202            Permissions::empty(),
1203            Permissions::READ_MESSAGE_HISTORY,
1204        )];
1205        let restricted_target = gated_to(MEMBER);
1206        let v = visibility(&source, &restricted_target, &default_roles(&[MEMBER]));
1207        assert!(!v.roles_preserve_visibility());
1208    }
1209
1210    #[test]
1211    fn voice_and_stage_targets_also_require_connect() {
1212        for kind in [ChannelType::GuildVoice, ChannelType::GuildStageVoice] {
1213            assert_eq!(
1214                read_target_requirement(kind),
1215                READ_TARGET | Permissions::CONNECT
1216            );
1217        }
1218        assert_eq!(read_target_requirement(ChannelType::GuildText), READ_TARGET);
1219        assert_eq!(
1220            read_target_requirement(ChannelType::PublicThread),
1221            READ_TARGET
1222        );
1223    }
1224
1225    #[test]
1226    fn voice_target_viewable_but_not_connectable_is_rejected() {
1227        // A locked voice channel: everyone sees it, only ROLE_A may connect and
1228        // so read its text chat.
1229        let mut roles = default_roles(&[ROLE_A]);
1230        roles.insert(EVERYONE, READ_TARGET | Permissions::CONNECT);
1231        let target = [
1232            overwrite(
1233                PermissionOverwriteType::Role,
1234                EVERYONE.get(),
1235                Permissions::empty(),
1236                Permissions::CONNECT,
1237            ),
1238            overwrite(
1239                PermissionOverwriteType::Role,
1240                ROLE_A.get(),
1241                Permissions::CONNECT,
1242                Permissions::empty(),
1243            ),
1244        ];
1245        let read_voice = read_target_requirement(ChannelType::GuildVoice);
1246        let v = Visibility::new(
1247            &[],
1248            &target,
1249            READ_SOURCE,
1250            read_voice,
1251            roles.clone(),
1252            EVERYONE,
1253        );
1254        assert!(!v.roles_preserve_visibility());
1255
1256        let v = Visibility::new(
1257            &gated_to(ROLE_A),
1258            &target,
1259            READ_SOURCE,
1260            read_voice,
1261            roles,
1262            EVERYONE,
1263        );
1264        assert!(v.roles_preserve_visibility());
1265    }
1266
1267    // --- Links back into the source channel ---
1268
1269    #[test]
1270    fn reply_in_another_channel_needs_only_view_channel() {
1271        for kind in [ChannelType::GuildText, ChannelType::GuildVoice] {
1272            assert_eq!(read_source_requirement(kind, false), READ_SOURCE);
1273        }
1274    }
1275
1276    #[test]
1277    fn reply_in_the_linked_channel_needs_what_reading_it_does_except_history() {
1278        for kind in [ChannelType::GuildText, ChannelType::PrivateThread] {
1279            assert_eq!(
1280                read_source_requirement(kind, true),
1281                Permissions::VIEW_CHANNEL
1282            );
1283        }
1284        for kind in [ChannelType::GuildVoice, ChannelType::GuildStageVoice] {
1285            assert_eq!(
1286                read_source_requirement(kind, true),
1287                Permissions::VIEW_CHANNEL | Permissions::CONNECT
1288            );
1289        }
1290    }
1291
1292    /// A link back into the channel of `kind` it is posted in, whose overwrites
1293    /// are `channel` (its parent's, for a thread).
1294    fn same_channel(
1295        kind: ChannelType,
1296        channel: &[PermissionOverwrite],
1297        roles: &HashMap<Id<RoleMarker>, Permissions>,
1298    ) -> Visibility {
1299        Visibility::new(
1300            channel,
1301            channel,
1302            read_source_requirement(kind, true),
1303            read_target_requirement(kind),
1304            roles.clone(),
1305            EVERYONE,
1306        )
1307    }
1308
1309    fn history_denied(kind: PermissionOverwriteType, id: u64) -> PermissionOverwrite {
1310        overwrite(
1311            kind,
1312            id,
1313            Permissions::empty(),
1314            Permissions::READ_MESSAGE_HISTORY,
1315        )
1316    }
1317
1318    #[test]
1319    fn same_channel_without_read_message_history_for_everyone_is_rejected() {
1320        let channel = [history_denied(
1321            PermissionOverwriteType::Role,
1322            EVERYONE.get(),
1323        )];
1324        let v = same_channel(ChannelType::GuildText, &channel, &default_roles(&[]));
1325        assert!(!v.roles_preserve_visibility());
1326    }
1327
1328    #[test]
1329    fn same_channel_without_read_message_history_for_a_role_is_rejected() {
1330        let channel = [history_denied(PermissionOverwriteType::Role, ROLE_A.get())];
1331        let v = same_channel(ChannelType::GuildText, &channel, &default_roles(&[ROLE_A]));
1332        assert!(!v.roles_preserve_visibility());
1333    }
1334
1335    #[test]
1336    fn same_channel_without_read_message_history_for_a_member_looks_them_up_and_is_rejected() {
1337        let channel = [history_denied(PermissionOverwriteType::Member, USER.get())];
1338        let v = same_channel(ChannelType::GuildText, &channel, &default_roles(&[]));
1339        assert!(v.roles_preserve_visibility());
1340        assert_eq!(v.members_to_verify(), [USER]);
1341        assert!(!v.member_preserves_visibility(USER, &[]));
1342    }
1343
1344    #[test]
1345    fn same_channel_whose_viewers_all_read_history_needs_no_lookup() {
1346        let roles = default_roles(&[MEMBER]);
1347        let opened_to_a_member = [
1348            role_ow(EVERYONE.get(), false, true),
1349            member_ow(USER.get(), true, false),
1350        ];
1351        for channel in [&[][..], &gated_to(MEMBER), &opened_to_a_member] {
1352            let v = same_channel(ChannelType::GuildText, channel, &roles);
1353            assert!(v.roles_preserve_visibility());
1354            assert!(v.members_to_verify().is_empty());
1355        }
1356    }
1357
1358    #[test]
1359    fn private_thread_quoted_from_within_is_judged_by_its_parent() {
1360        let roles = default_roles(&[]);
1361        let v = same_channel(ChannelType::PrivateThread, &[], &roles);
1362        assert!(v.roles_preserve_visibility());
1363
1364        let parent = [history_denied(
1365            PermissionOverwriteType::Role,
1366            EVERYONE.get(),
1367        )];
1368        let v = same_channel(ChannelType::PrivateThread, &parent, &roles);
1369        assert!(!v.roles_preserve_visibility());
1370    }
1371
1372    /// Role permissions where `@everyone` may also connect to voice channels.
1373    fn voice_roles() -> HashMap<Id<RoleMarker>, Permissions> {
1374        let mut roles = default_roles(&[ROLE_A]);
1375        roles.insert(EVERYONE, READ_TARGET | Permissions::CONNECT);
1376        roles
1377    }
1378
1379    /// A locked voice channel: `@everyone` is denied `CONNECT` and `denied`,
1380    /// ROLE_A is allowed `CONNECT` and `allowed`.
1381    fn locked_voice(denied: Permissions, allowed: Permissions) -> [PermissionOverwrite; 2] {
1382        [
1383            overwrite(
1384                PermissionOverwriteType::Role,
1385                EVERYONE.get(),
1386                Permissions::empty(),
1387                Permissions::CONNECT | denied,
1388            ),
1389            overwrite(
1390                PermissionOverwriteType::Role,
1391                ROLE_A.get(),
1392                Permissions::CONNECT | allowed,
1393                Permissions::empty(),
1394            ),
1395        ]
1396    }
1397
1398    #[test]
1399    fn locked_voice_channel_quoted_from_within_counts_only_members_who_connect() {
1400        let history = Permissions::READ_MESSAGE_HISTORY;
1401        for kind in [ChannelType::GuildVoice, ChannelType::GuildStageVoice] {
1402            let v = same_channel(
1403                kind,
1404                &locked_voice(Permissions::empty(), Permissions::empty()),
1405                &voice_roles(),
1406            );
1407            assert!(v.roles_preserve_visibility());
1408
1409            // Members who cannot connect lack the history too, but never see
1410            // the reply.
1411            let v = same_channel(kind, &locked_voice(history, history), &voice_roles());
1412            assert!(v.roles_preserve_visibility());
1413        }
1414    }
1415
1416    #[test]
1417    fn voice_channel_quoted_from_within_by_members_without_history_is_rejected() {
1418        let history = Permissions::READ_MESSAGE_HISTORY;
1419        for kind in [ChannelType::GuildVoice, ChannelType::GuildStageVoice] {
1420            let v = same_channel(
1421                kind,
1422                &locked_voice(history, Permissions::empty()),
1423                &voice_roles(),
1424            );
1425            assert!(!v.roles_preserve_visibility());
1426        }
1427    }
1428
1429    #[test]
1430    fn role_missing_from_role_permissions_still_restricts_its_holders() {
1431        // ROLE_A is newer than the cached role permissions but already denied on
1432        // the target.
1433        let target = [role_ow(ROLE_A.get(), false, true)];
1434        let v = visibility(&[], &target, &default_roles(&[]));
1435        assert!(!v.roles_preserve_visibility());
1436    }
1437
1438    #[test]
1439    fn administrator_reads_any_target() {
1440        let mut roles = default_roles(&[]);
1441        roles.insert(ADMIN, Permissions::ADMINISTRATOR);
1442        let nobody = [role_ow(EVERYONE.get(), false, true)];
1443        // Only administrators view the source, and they read everything.
1444        let v = visibility(&nobody, &[role_ow(ADMIN.get(), false, true)], &roles);
1445        assert!(v.roles_preserve_visibility());
1446    }
1447
1448    #[test]
1449    fn missing_everyone_role_grants_no_base_permissions() {
1450        // Nobody can view the source without a base grant, so nothing can leak.
1451        let roles = HashMap::from([(MEMBER, Permissions::empty())]);
1452        let v = visibility(&[], &gated_to(SPECIAL), &roles);
1453        assert!(v.roles_preserve_visibility());
1454    }
1455
1456    #[test]
1457    fn reachable_grants_stay_bounded_with_many_roles() {
1458        let ids: Vec<Id<RoleMarker>> = (1000..1200).map(Id::new).collect();
1459        let source: Vec<_> = ids
1460            .iter()
1461            .step_by(2)
1462            .map(|id| role_ow(id.get(), true, false))
1463            .collect();
1464        let target: Vec<_> = ids
1465            .iter()
1466            .step_by(3)
1467            .map(|id| role_ow(id.get(), false, true))
1468            .collect();
1469        let v = visibility(&source, &target, &default_roles(&ids));
1470        // Base, source and target bits: 3 + 2 + 4.
1471        assert!(v.reachable.len() <= 1 << 9);
1472    }
1473
1474    #[test]
1475    fn member_granted_source_quoting_public_target_needs_no_lookup() {
1476        let source = [
1477            role_ow(EVERYONE.get(), false, true),
1478            member_ow(USER.get(), true, false),
1479        ];
1480        let v = visibility(&source, &[], &default_roles(&[MEMBER]));
1481        assert!(v.roles_preserve_visibility());
1482        assert!(v.members_to_verify().is_empty());
1483    }
1484
1485    #[test]
1486    fn member_granted_source_quoting_restricted_target_looks_the_member_up() {
1487        let source = [
1488            role_ow(EVERYONE.get(), false, true),
1489            member_ow(USER.get(), true, false),
1490        ];
1491        let v = visibility(&source, &gated_to(MEMBER), &default_roles(&[MEMBER]));
1492        assert!(v.roles_preserve_visibility());
1493        assert_eq!(v.members_to_verify(), [USER]);
1494
1495        // Judged on the roles they actually hold.
1496        assert!(v.member_preserves_visibility(USER, &[MEMBER]));
1497        assert!(!v.member_preserves_visibility(USER, &[]));
1498    }
1499
1500    #[test]
1501    fn member_denied_on_target_is_looked_up_and_rejected_if_they_view_the_source() {
1502        let target = [member_ow(USER.get(), false, true)];
1503        let v = visibility(&[], &target, &default_roles(&[]));
1504        assert_eq!(v.members_to_verify(), [USER]);
1505        assert!(!v.member_preserves_visibility(USER, &[]));
1506    }
1507
1508    #[test]
1509    fn member_denied_on_target_who_cannot_view_the_source_is_fine() {
1510        let v = visibility(
1511            &gated_to(MEMBER),
1512            &[member_ow(USER.get(), false, true)],
1513            &default_roles(&[MEMBER]),
1514        );
1515        assert_eq!(v.members_to_verify(), [USER]);
1516        assert!(v.member_preserves_visibility(USER, &[]));
1517        assert!(!v.member_preserves_visibility(USER, &[MEMBER]));
1518    }
1519
1520    #[test]
1521    fn member_shut_out_of_source_needs_no_lookup() {
1522        let source = [member_ow(USER.get(), false, true)];
1523        let target = [member_ow(USER.get(), false, true)];
1524        let v = visibility(&source, &target, &default_roles(&[]));
1525        assert!(v.members_to_verify().is_empty());
1526    }
1527
1528    #[test]
1529    fn member_allowed_only_on_target_needs_no_lookup() {
1530        let v = visibility(
1531            &gated_to(MEMBER),
1532            &[
1533                role_ow(EVERYONE.get(), false, true),
1534                member_ow(USER.get(), true, false),
1535            ],
1536            &default_roles(&[MEMBER]),
1537        );
1538        // MEMBER views the source but not the target, whatever USER can do.
1539        assert!(!v.roles_preserve_visibility());
1540        assert!(v.members_to_verify().is_empty());
1541    }
1542
1543    #[test]
1544    fn member_granted_both_channels_needs_no_lookup() {
1545        // A restricted channel quoted from one made private by adding the same
1546        // members individually: their personal grant already covers the target.
1547        let source = [
1548            role_ow(EVERYONE.get(), false, true),
1549            member_ow(USER.get(), true, false),
1550        ];
1551        let target = [
1552            role_ow(EVERYONE.get(), false, true),
1553            member_ow(USER.get(), true, false),
1554        ];
1555        let v = visibility(&source, &target, &default_roles(&[MEMBER]));
1556        assert!(v.roles_preserve_visibility());
1557        assert!(v.members_to_verify().is_empty());
1558    }
1559
1560    #[test]
1561    fn member_overwrite_outweighs_role_overwrites() {
1562        // A personal allow is applied last, so it restores what a role denied.
1563        let target = [
1564            role_ow(MEMBER.get(), false, true),
1565            overwrite(
1566                PermissionOverwriteType::Member,
1567                USER.get(),
1568                READ_TARGET,
1569                Permissions::empty(),
1570            ),
1571        ];
1572        let v = visibility(
1573            &[member_ow(USER.get(), true, false)],
1574            &target,
1575            &default_roles(&[MEMBER]),
1576        );
1577        assert!(v.member_preserves_visibility(USER, &[MEMBER]));
1578    }
1579
1580    // --- Preview embed rendering ---
1581
1582    // `Message` and `Channel` have no `Default` and dozens of fields, so build
1583    // them from JSON.
1584    fn message_with(avatar: Option<&str>) -> Message {
1585        serde_json::from_value(serde_json::json!({
1586            "id": "1",
1587            "channel_id": "2",
1588            "type": 0,
1589            "author": {"id": "3", "username": "author", "discriminator": "0", "avatar": avatar},
1590            "content": "quoted content",
1591            "timestamp": "2024-01-01T00:00:00+00:00",
1592            "edited_timestamp": null,
1593            "tts": false,
1594            "mention_everyone": false,
1595            "mentions": [],
1596            "mention_roles": [],
1597            "attachments": [],
1598            "embeds": [],
1599            "pinned": false,
1600        }))
1601        .unwrap()
1602    }
1603
1604    fn channel_named(name: Option<&str>) -> Channel {
1605        serde_json::from_value(serde_json::json!({"id": "2", "type": 0, "name": name})).unwrap()
1606    }
1607
1608    #[test]
1609    fn embed_carries_the_quoted_message_and_its_origin() {
1610        let message = message_with(None);
1611
1612        let embed = preview_embed(&message, &channel_named(Some("general")));
1613
1614        assert_eq!(
1615            embed,
1616            EmbedBuilder::new()
1617                .description("quoted content")
1618                .author(EmbedAuthorBuilder::new("author"))
1619                .timestamp(message.timestamp)
1620                .color(PREVIEW_EMBED_COLOUR)
1621                .footer(EmbedFooterBuilder::new("general"))
1622                .build()
1623        );
1624    }
1625
1626    #[test]
1627    fn a_channel_without_a_name_gets_no_footer() {
1628        let embed = preview_embed(&message_with(None), &channel_named(None));
1629
1630        assert!(embed.footer.is_none());
1631    }
1632
1633    #[test]
1634    fn an_author_without_an_avatar_gets_no_icon_url() {
1635        let channel = channel_named(Some("general"));
1636        let without_avatar = preview_embed(&message_with(None), &channel);
1637
1638        let with_avatar = preview_embed(
1639            &message_with(Some("a_00000000000000000000000000000000")),
1640            &channel,
1641        );
1642
1643        assert_ne!(without_avatar, with_avatar);
1644        assert!(format!("{with_avatar:?}").contains("a_00000000000000000000000000000000"));
1645    }
1646
1647    fn attachment(url: &str) -> serde_json::Value {
1648        serde_json::json!({
1649            "id": "4",
1650            "filename": "image.png",
1651            "proxy_url": url,
1652            "size": 1,
1653            "url": url,
1654        })
1655    }
1656
1657    #[test]
1658    fn the_first_attachment_becomes_the_embed_image() {
1659        let mut message = message_with(None);
1660        message.attachments = serde_json::from_value(serde_json::json!([
1661            attachment("https://cdn.discordapp.com/attachments/1/2/first.png"),
1662            attachment("https://cdn.discordapp.com/attachments/1/2/second.png"),
1663        ]))
1664        .unwrap();
1665
1666        let embed = preview_embed(&message, &channel_named(Some("general")));
1667
1668        assert_eq!(
1669            embed.image.map(|image| image.url),
1670            Some("https://cdn.discordapp.com/attachments/1/2/first.png".to_string())
1671        );
1672    }
1673
1674    #[test]
1675    fn a_message_without_attachments_gets_no_embed_image() {
1676        let embed = preview_embed(&message_with(None), &channel_named(Some("general")));
1677
1678        assert!(embed.image.is_none());
1679    }
1680
1681    #[test]
1682    fn a_static_avatar_is_served_as_webp() {
1683        let author = message_with(Some("00000000000000000000000000000000")).author;
1684
1685        assert_eq!(
1686            avatar_url(&author).as_deref(),
1687            Some(
1688                "https://cdn.discordapp.com/avatars/3/00000000000000000000000000000000.webp?size=1024"
1689            )
1690        );
1691    }
1692
1693    #[test]
1694    fn an_animated_avatar_is_served_as_gif() {
1695        let author = message_with(Some("a_00000000000000000000000000000000")).author;
1696
1697        assert_eq!(
1698            avatar_url(&author).as_deref(),
1699            Some(
1700                "https://cdn.discordapp.com/avatars/3/a_00000000000000000000000000000000.gif?size=1024"
1701            )
1702        );
1703    }
1704
1705    #[test]
1706    fn an_author_without_an_avatar_has_no_avatar_url() {
1707        assert_eq!(avatar_url(&message_with(None).author), None);
1708    }
1709
1710    #[test]
1711    fn a_channel_without_overwrites_has_none() {
1712        assert!(overwrites(&channel_named(Some("general"))).is_empty());
1713    }
1714
1715    #[test]
1716    fn a_channel_exposes_its_overwrites() {
1717        let channel: Channel = serde_json::from_value(serde_json::json!({
1718            "id": "2",
1719            "type": 0,
1720            "permission_overwrites": [
1721                {"id": "1", "type": 0, "allow": "0", "deny": "1024"},
1722            ],
1723        }))
1724        .unwrap();
1725
1726        assert_eq!(overwrites(&channel), [role_ow(1, false, true)]);
1727    }
1728}