Skip to main content

matrix_sdk/widget/
capabilities.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Types and traits related to the capabilities that a widget can request from
16//! a client.
17
18use std::{fmt, future::Future};
19
20use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
21use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeSeq};
22use tracing::{debug, warn};
23
24use super::{
25    MessageLikeEventFilter, StateEventFilter,
26    filter::{Filter, FilterInput, ToDeviceEventFilter},
27};
28
29/// Must be implemented by a component that provides functionality of deciding
30/// whether a widget is allowed to use certain capabilities (typically by
31/// providing a prompt to the user).
32pub trait CapabilitiesProvider: SendOutsideWasm + SyncOutsideWasm + 'static {
33    /// Receives a request for given capabilities and returns the actual
34    /// capabilities that the clients grants to a given widget (usually by
35    /// prompting the user).
36    fn acquire_capabilities(
37        &self,
38        capabilities: Capabilities,
39    ) -> impl Future<Output = Capabilities> + SendOutsideWasm;
40}
41
42/// Capabilities that a widget can request from a client.
43#[derive(Clone, Debug, Default)]
44#[cfg_attr(test, derive(PartialEq))]
45pub struct Capabilities {
46    /// Types of the messages that a widget wants to be able to fetch.
47    pub read: Vec<Filter>,
48    /// Types of the messages that a widget wants to be able to send.
49    pub send: Vec<Filter>,
50    /// If this capability is requested by the widget, it can not operate
51    /// separately from the Matrix client.
52    ///
53    /// This means clients should not offer to open the widget in a separate
54    /// browser/tab/webview that is not connected to the postmessage widget-api.
55    pub requires_client: bool,
56    /// This allows the widget to ask the client to update delayed events.
57    pub update_delayed_event: bool,
58    /// This allows the widget to send events with a delay.
59    pub send_delayed_event: bool,
60
61    /// This allows the widget to download files as per MSC4039.
62    pub download_file: bool,
63
64    /// This allows the widget to discover the RTC transports advertised by the
65    /// homeserver as per MSC4515.
66    pub rtc_transports: bool,
67
68    /// This allows the widget to obtain a token to authenticate with a LiveKit
69    /// SFU from the homeserver as per MSC4533.
70    pub rtc_livekit_get_token: bool,
71
72    /// This allows the widget to hand the delayed leave event of a MatrixRTC
73    /// session over to the homeserver as per MSC4533.
74    pub rtc_livekit_delegate_delayed_leave: bool,
75
76    /// This allows the widget to send sticky events (MSC4354) by setting a
77    /// `sticky_duration_ms` on a `send_event` request, as per MSC4407.
78    ///
79    /// The event type must be covered by a `send` filter.
80    #[cfg(feature = "unstable-msc4354")]
81    pub send_sticky_event: bool,
82
83    /// This allows the widget to receive the sticky events (MSC4354) that are
84    /// live when the capabilities are negotiated, as per MSC4407.
85    ///
86    /// Only sticky events whose type is covered by a `read` filter are pushed.
87    #[cfg(feature = "unstable-msc4354")]
88    pub receive_sticky_event: bool,
89}
90
91impl Capabilities {
92    /// Checks if a given event is allowed to be forwarded to the widget.
93    ///
94    /// - `event_filter_input` is a minimized event representation that contains
95    ///   only the information needed to check if the widget is allowed to
96    ///   receive the event. (See [`FilterInput`])
97    pub(super) fn allow_reading<'a>(
98        &self,
99        event_filter_input: impl TryInto<FilterInput<'a>>,
100    ) -> bool {
101        match &event_filter_input.try_into() {
102            Err(_) => {
103                warn!("Failed to convert event into filter input for `allow_reading`.");
104                false
105            }
106            Ok(filter_input) => self.read.iter().any(|f| f.matches(filter_input)),
107        }
108    }
109
110    /// Checks if a given event is allowed to be sent by the widget.
111    ///
112    /// - `event_filter_input` is a minimized event representation that contains
113    ///   only the information needed to check if the widget is allowed to send
114    ///   the event to a matrix room. (See [`FilterInput`])
115    pub(super) fn allow_sending<'a>(
116        &self,
117        event_filter_input: impl TryInto<FilterInput<'a>>,
118    ) -> bool {
119        match &event_filter_input.try_into() {
120            Err(_) => {
121                warn!("Failed to convert event into filter input for `allow_sending`.");
122                false
123            }
124            Ok(filter_input) => self.send.iter().any(|f| f.matches(filter_input)),
125        }
126    }
127
128    /// Checks if a filter exists for the given event type, useful for
129    /// optimization. Avoids unnecessary read event requests when no matching
130    /// filter is present.
131    pub(super) fn has_read_filter_for_type(&self, event_type: &str) -> bool {
132        self.read.iter().any(|f| f.filter_event_type() == event_type)
133    }
134}
135
136pub(super) const SEND_EVENT: &str = "org.matrix.msc2762.send.event";
137pub(super) const READ_EVENT: &str = "org.matrix.msc2762.receive.event";
138pub(super) const SEND_STATE: &str = "org.matrix.msc2762.send.state_event";
139pub(super) const READ_STATE: &str = "org.matrix.msc2762.receive.state_event";
140pub(super) const SEND_TODEVICE: &str = "org.matrix.msc3819.send.to_device";
141pub(super) const READ_TODEVICE: &str = "org.matrix.msc3819.receive.to_device";
142pub(super) const REQUIRES_CLIENT: &str = "io.element.requires_client";
143pub(super) const SEND_DELAYED_EVENT: &str = "org.matrix.msc4157.send.delayed_event";
144pub(super) const UPDATE_DELAYED_EVENT: &str = "org.matrix.msc4157.update_delayed_event";
145
146pub(super) const DOWNLOAD_FILE: &str = "org.matrix.msc4039.download_file";
147
148pub(super) const RTC_TRANSPORTS: &str = "org.matrix.msc4515.rtc_transports";
149
150pub(super) const RTC_LIVEKIT_GET_TOKEN: &str = "org.matrix.msc4533.rtc_livekit_get_token";
151pub(super) const RTC_LIVEKIT_DELEGATE_DELAYED_LEAVE: &str =
152    "org.matrix.msc4533.rtc_livekit_delegate_delayed_leave";
153
154#[cfg(feature = "unstable-msc4354")]
155pub(super) const SEND_STICKY_EVENT: &str = "org.matrix.msc4407.send.sticky_event";
156#[cfg(feature = "unstable-msc4354")]
157pub(super) const RECEIVE_STICKY_EVENT: &str = "org.matrix.msc4407.receive.sticky_event";
158
159impl Serialize for Capabilities {
160    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
161    where
162        S: Serializer,
163    {
164        struct PrintEventFilter<'a>(&'a Filter);
165        impl fmt::Display for PrintEventFilter<'_> {
166            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167                match self.0 {
168                    Filter::MessageLike(filter) => PrintMessageLikeEventFilter(filter).fmt(f),
169                    Filter::State(filter) => PrintStateEventFilter(filter).fmt(f),
170                    Filter::ToDevice(filter) => {
171                        // As per MSC 3819
172                        // https://github.com/matrix-org/matrix-spec-proposals/pull/3819
173                        // ToDevice capabilities is in the form of
174                        // `m.send.to_device:<event type>` or
175                        // `m.receive.to_device:<event type>`
176                        write!(f, "{}", filter.event_type)
177                    }
178                }
179            }
180        }
181
182        struct PrintMessageLikeEventFilter<'a>(&'a MessageLikeEventFilter);
183        impl fmt::Display for PrintMessageLikeEventFilter<'_> {
184            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185                match self.0 {
186                    MessageLikeEventFilter::WithType(event_type) => {
187                        // TODO: escape `#` as `\#` and `\` as `\\` in
188                        // event_type
189                        write!(f, "{event_type}")
190                    }
191                    MessageLikeEventFilter::RoomMessageWithMsgtype(msgtype) => {
192                        write!(f, "m.room.message#{msgtype}")
193                    }
194                }
195            }
196        }
197
198        struct PrintStateEventFilter<'a>(&'a StateEventFilter);
199        impl fmt::Display for PrintStateEventFilter<'_> {
200            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201                // TODO: escape `#` as `\#` and `\` as `\\` in event_type
202                match self.0 {
203                    StateEventFilter::WithType(event_type) => write!(f, "{event_type}"),
204                    StateEventFilter::WithTypeAndStateKey(event_type, state_key) => {
205                        write!(f, "{event_type}#{state_key}")
206                    }
207                }
208            }
209        }
210
211        let mut seq = serializer.serialize_seq(None)?;
212
213        if self.requires_client {
214            seq.serialize_element(REQUIRES_CLIENT)?;
215        }
216        if self.update_delayed_event {
217            seq.serialize_element(UPDATE_DELAYED_EVENT)?;
218        }
219        if self.send_delayed_event {
220            seq.serialize_element(SEND_DELAYED_EVENT)?;
221        }
222        if self.download_file {
223            seq.serialize_element(DOWNLOAD_FILE)?;
224        }
225        if self.rtc_transports {
226            seq.serialize_element(RTC_TRANSPORTS)?;
227        }
228        if self.rtc_livekit_get_token {
229            seq.serialize_element(RTC_LIVEKIT_GET_TOKEN)?;
230        }
231        if self.rtc_livekit_delegate_delayed_leave {
232            seq.serialize_element(RTC_LIVEKIT_DELEGATE_DELAYED_LEAVE)?;
233        }
234        #[cfg(feature = "unstable-msc4354")]
235        if self.send_sticky_event {
236            seq.serialize_element(SEND_STICKY_EVENT)?;
237        }
238        #[cfg(feature = "unstable-msc4354")]
239        if self.receive_sticky_event {
240            seq.serialize_element(RECEIVE_STICKY_EVENT)?;
241        }
242        for filter in &self.read {
243            let name = match filter {
244                Filter::MessageLike(_) => READ_EVENT,
245                Filter::State(_) => READ_STATE,
246                Filter::ToDevice(_) => READ_TODEVICE,
247            };
248            seq.serialize_element(&format!("{name}:{}", PrintEventFilter(filter)))?;
249        }
250        for filter in &self.send {
251            let name = match filter {
252                Filter::MessageLike(_) => SEND_EVENT,
253                Filter::State(_) => SEND_STATE,
254                Filter::ToDevice(_) => SEND_TODEVICE,
255            };
256            seq.serialize_element(&format!("{name}:{}", PrintEventFilter(filter)))?;
257        }
258
259        seq.end()
260    }
261}
262
263impl<'de> Deserialize<'de> for Capabilities {
264    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
265    where
266        D: Deserializer<'de>,
267    {
268        enum Permission {
269            RequiresClient,
270            UpdateDelayedEvent,
271            SendDelayedEvent,
272            DownloadFile,
273            RtcTransports,
274            RtcLivekitGetToken,
275            RtcLivekitDelegateDelayedLeave,
276            #[cfg(feature = "unstable-msc4354")]
277            SendStickyEvent,
278            #[cfg(feature = "unstable-msc4354")]
279            ReceiveStickyEvent,
280            Read(Filter),
281            Send(Filter),
282            Unknown,
283        }
284
285        impl<'de> Deserialize<'de> for Permission {
286            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
287            where
288                D: Deserializer<'de>,
289            {
290                let s = ruma::serde::deserialize_cow_str(deserializer)?;
291                if s == REQUIRES_CLIENT {
292                    return Ok(Self::RequiresClient);
293                }
294                if s == UPDATE_DELAYED_EVENT {
295                    return Ok(Self::UpdateDelayedEvent);
296                }
297                if s == SEND_DELAYED_EVENT {
298                    return Ok(Self::SendDelayedEvent);
299                }
300                if s == DOWNLOAD_FILE {
301                    return Ok(Self::DownloadFile);
302                }
303                if s == RTC_TRANSPORTS {
304                    return Ok(Self::RtcTransports);
305                }
306                if s == RTC_LIVEKIT_GET_TOKEN {
307                    return Ok(Self::RtcLivekitGetToken);
308                }
309                if s == RTC_LIVEKIT_DELEGATE_DELAYED_LEAVE {
310                    return Ok(Self::RtcLivekitDelegateDelayedLeave);
311                }
312                #[cfg(feature = "unstable-msc4354")]
313                if s == SEND_STICKY_EVENT {
314                    return Ok(Self::SendStickyEvent);
315                }
316                #[cfg(feature = "unstable-msc4354")]
317                if s == RECEIVE_STICKY_EVENT {
318                    return Ok(Self::ReceiveStickyEvent);
319                }
320
321                match s.split_once(':') {
322                    Some((READ_EVENT, filter_s)) => Ok(Permission::Read(Filter::MessageLike(
323                        parse_message_event_filter(filter_s),
324                    ))),
325                    Some((SEND_EVENT, filter_s)) => Ok(Permission::Send(Filter::MessageLike(
326                        parse_message_event_filter(filter_s),
327                    ))),
328                    Some((READ_STATE, filter_s)) => {
329                        Ok(Permission::Read(Filter::State(parse_state_event_filter(filter_s))))
330                    }
331                    Some((SEND_STATE, filter_s)) => {
332                        Ok(Permission::Send(Filter::State(parse_state_event_filter(filter_s))))
333                    }
334                    Some((READ_TODEVICE, filter_s)) => Ok(Permission::Read(Filter::ToDevice(
335                        parse_to_device_event_filter(filter_s),
336                    ))),
337                    Some((SEND_TODEVICE, filter_s)) => Ok(Permission::Send(Filter::ToDevice(
338                        parse_to_device_event_filter(filter_s),
339                    ))),
340                    _ => {
341                        debug!("Unknown capability `{s}`");
342                        Ok(Self::Unknown)
343                    }
344                }
345            }
346        }
347
348        fn parse_message_event_filter(s: &str) -> MessageLikeEventFilter {
349            match s.strip_prefix("m.room.message#") {
350                Some(msgtype) => MessageLikeEventFilter::RoomMessageWithMsgtype(msgtype.to_owned()),
351                // TODO: Replace `\\` by `\` and `\#` by `#`, enforce no unescaped `#`
352                None => MessageLikeEventFilter::WithType(s.into()),
353            }
354        }
355
356        fn parse_state_event_filter(s: &str) -> StateEventFilter {
357            // TODO: Search for un-escaped `#` only, replace `\\` by `\` and
358            // `\#` by `#`
359            match s.split_once('#') {
360                Some((event_type, state_key)) => {
361                    StateEventFilter::WithTypeAndStateKey(event_type.into(), state_key.to_owned())
362                }
363                None => StateEventFilter::WithType(s.into()),
364            }
365        }
366
367        fn parse_to_device_event_filter(s: &str) -> ToDeviceEventFilter {
368            ToDeviceEventFilter::new(s.into())
369        }
370
371        let mut capabilities = Capabilities::default();
372        for capability in Vec::<Permission>::deserialize(deserializer)? {
373            match capability {
374                Permission::RequiresClient => capabilities.requires_client = true,
375                Permission::Read(filter) => capabilities.read.push(filter),
376                Permission::Send(filter) => capabilities.send.push(filter),
377                // ignore unknown capabilities
378                Permission::Unknown => {}
379                Permission::UpdateDelayedEvent => capabilities.update_delayed_event = true,
380                Permission::SendDelayedEvent => capabilities.send_delayed_event = true,
381                Permission::DownloadFile => capabilities.download_file = true,
382                Permission::RtcTransports => capabilities.rtc_transports = true,
383                Permission::RtcLivekitGetToken => capabilities.rtc_livekit_get_token = true,
384                Permission::RtcLivekitDelegateDelayedLeave => {
385                    capabilities.rtc_livekit_delegate_delayed_leave = true
386                }
387                #[cfg(feature = "unstable-msc4354")]
388                Permission::SendStickyEvent => capabilities.send_sticky_event = true,
389                #[cfg(feature = "unstable-msc4354")]
390                Permission::ReceiveStickyEvent => capabilities.receive_sticky_event = true,
391            }
392        }
393
394        Ok(capabilities)
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use ruma::events::StateEventType;
401
402    use super::*;
403    use crate::widget::filter::ToDeviceEventFilter;
404
405    #[test]
406    fn deserialization_of_no_capabilities() {
407        let capabilities_str = r#"[]"#;
408
409        let parsed = serde_json::from_str::<Capabilities>(capabilities_str).unwrap();
410        let expected = Capabilities::default();
411
412        assert_eq!(parsed, expected);
413    }
414
415    #[test]
416    fn deserialization_of_capabilities() {
417        let capabilities_str = r#"[
418            "m.always_on_screen",
419            "io.element.requires_client",
420            "org.matrix.msc2762.receive.event:org.matrix.rageshake_request",
421            "org.matrix.msc2762.receive.state_event:m.room.member",
422            "org.matrix.msc2762.receive.state_event:org.matrix.msc3401.call.member",
423            "org.matrix.msc3819.receive.to_device:io.element.call.encryption_keys",
424            "org.matrix.msc2762.send.event:org.matrix.rageshake_request",
425            "org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@user:matrix.server",
426            "org.matrix.msc3819.send.to_device:io.element.call.encryption_keys",
427            "org.matrix.msc4157.send.delayed_event",
428            "org.matrix.msc4157.update_delayed_event",
429            "org.matrix.msc4039.download_file",
430            "org.matrix.msc4515.rtc_transports",
431            "org.matrix.msc4533.rtc_livekit_get_token",
432            "org.matrix.msc4533.rtc_livekit_delegate_delayed_leave",
433            "org.matrix.msc4407.send.sticky_event",
434            "org.matrix.msc4407.receive.sticky_event"
435        ]"#;
436
437        let parsed = serde_json::from_str::<Capabilities>(capabilities_str).unwrap();
438        let expected = Capabilities {
439            read: vec![
440                Filter::MessageLike(MessageLikeEventFilter::WithType(
441                    "org.matrix.rageshake_request".into(),
442                )),
443                Filter::State(StateEventFilter::WithType(StateEventType::RoomMember)),
444                Filter::State(StateEventFilter::WithType("org.matrix.msc3401.call.member".into())),
445                Filter::ToDevice(ToDeviceEventFilter::new(
446                    "io.element.call.encryption_keys".into(),
447                )),
448            ],
449            send: vec![
450                Filter::MessageLike(MessageLikeEventFilter::WithType(
451                    "org.matrix.rageshake_request".into(),
452                )),
453                Filter::State(StateEventFilter::WithTypeAndStateKey(
454                    "org.matrix.msc3401.call.member".into(),
455                    "@user:matrix.server".into(),
456                )),
457                Filter::ToDevice(ToDeviceEventFilter::new(
458                    "io.element.call.encryption_keys".into(),
459                )),
460            ],
461            requires_client: true,
462            update_delayed_event: true,
463            send_delayed_event: true,
464            download_file: true,
465            rtc_transports: true,
466            rtc_livekit_get_token: true,
467            rtc_livekit_delegate_delayed_leave: true,
468            #[cfg(feature = "unstable-msc4354")]
469            send_sticky_event: true,
470            #[cfg(feature = "unstable-msc4354")]
471            receive_sticky_event: true,
472        };
473
474        assert_eq!(parsed, expected);
475    }
476
477    #[test]
478    fn serialization_and_deserialization_are_symmetrical() {
479        let capabilities = Capabilities {
480            read: vec![
481                Filter::MessageLike(MessageLikeEventFilter::WithType("io.element.custom".into())),
482                Filter::State(StateEventFilter::WithType(StateEventType::RoomMember)),
483                Filter::State(StateEventFilter::WithTypeAndStateKey(
484                    "org.matrix.msc3401.call.member".into(),
485                    "@user:matrix.server".into(),
486                )),
487                Filter::ToDevice(ToDeviceEventFilter::new(
488                    "io.element.call.encryption_keys".into(),
489                )),
490            ],
491            send: vec![
492                Filter::MessageLike(MessageLikeEventFilter::WithType("io.element.custom".into())),
493                Filter::State(StateEventFilter::WithTypeAndStateKey(
494                    "org.matrix.msc3401.call.member".into(),
495                    "@user:matrix.server".into(),
496                )),
497                Filter::ToDevice(ToDeviceEventFilter::new("my.org.other.to_device_event".into())),
498            ],
499            requires_client: true,
500            update_delayed_event: false,
501            send_delayed_event: false,
502            download_file: false,
503            rtc_transports: true,
504            rtc_livekit_get_token: true,
505            rtc_livekit_delegate_delayed_leave: false,
506            #[cfg(feature = "unstable-msc4354")]
507            send_sticky_event: true,
508            #[cfg(feature = "unstable-msc4354")]
509            receive_sticky_event: false,
510        };
511
512        let capabilities_str = serde_json::to_string(&capabilities).unwrap();
513        let parsed = serde_json::from_str::<Capabilities>(&capabilities_str).unwrap();
514        assert_eq!(parsed, capabilities);
515    }
516}