1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Types and traits related to the capabilities that a widget can request from
//! a client.

use std::fmt;

use async_trait::async_trait;
use ruma::{events::AnyTimelineEvent, serde::Raw};
use serde::{ser::SerializeSeq, Deserialize, Deserializer, Serialize, Serializer};
use tracing::{debug, error};

use super::{
    filter::MatrixEventFilterInput, EventFilter, MessageLikeEventFilter, StateEventFilter,
};

/// Must be implemented by a component that provides functionality of deciding
/// whether a widget is allowed to use certain capabilities (typically by
/// providing a prompt to the user).
#[async_trait]
pub trait CapabilitiesProvider: Send + Sync + 'static {
    /// Receives a request for given capabilities and returns the actual
    /// capabilities that the clients grants to a given widget (usually by
    /// prompting the user).
    async fn acquire_capabilities(&self, capabilities: Capabilities) -> Capabilities;
}

/// Capabilities that a widget can request from a client.
#[derive(Clone, Debug, Default)]
#[cfg_attr(test, derive(PartialEq))]
pub struct Capabilities {
    /// Types of the messages that a widget wants to be able to fetch.
    pub read: Vec<EventFilter>,
    /// Types of the messages that a widget wants to be able to send.
    pub send: Vec<EventFilter>,
    /// If this capability is requested by the widget, it can not operate
    /// separately from the matrix client.
    ///
    /// This means clients should not offer to open the widget in a separate
    /// browser/tab/webview that is not connected to the postmessage widget-api.
    pub requires_client: bool,
    /// This allows the widget to ask the client to update delayed events.
    pub update_delayed_event: bool,
    /// This allows the widget to send events with a delay.
    pub send_delayed_event: bool,
}

impl Capabilities {
    /// Tells if a given raw event matches the read filter.
    pub fn raw_event_matches_read_filter(&self, raw: &Raw<AnyTimelineEvent>) -> bool {
        let filter_in = match raw.deserialize_as::<MatrixEventFilterInput>() {
            Ok(filter) => filter,
            Err(err) => {
                error!("Failed to deserialize raw event as MatrixEventFilterInput: {err}");
                return false;
            }
        };

        self.read.iter().any(|f| f.matches(&filter_in))
    }
}

const SEND_EVENT: &str = "org.matrix.msc2762.send.event";
const READ_EVENT: &str = "org.matrix.msc2762.receive.event";
const SEND_STATE: &str = "org.matrix.msc2762.send.state_event";
const READ_STATE: &str = "org.matrix.msc2762.receive.state_event";
const REQUIRES_CLIENT: &str = "io.element.requires_client";
pub(super) const SEND_DELAYED_EVENT: &str = "org.matrix.msc4157.send.delayed_event";
pub(super) const UPDATE_DELAYED_EVENT: &str = "org.matrix.msc4157.update_delayed_event";

impl Serialize for Capabilities {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        struct PrintEventFilter<'a>(&'a EventFilter);
        impl fmt::Display for PrintEventFilter<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self.0 {
                    EventFilter::MessageLike(filter) => PrintMessageLikeEventFilter(filter).fmt(f),
                    EventFilter::State(filter) => PrintStateEventFilter(filter).fmt(f),
                }
            }
        }

        struct PrintMessageLikeEventFilter<'a>(&'a MessageLikeEventFilter);
        impl fmt::Display for PrintMessageLikeEventFilter<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self.0 {
                    MessageLikeEventFilter::WithType(event_type) => {
                        // TODO: escape `#` as `\#` and `\` as `\\` in event_type
                        write!(f, "{event_type}")
                    }
                    MessageLikeEventFilter::RoomMessageWithMsgtype(msgtype) => {
                        write!(f, "m.room.message#{msgtype}")
                    }
                }
            }
        }

        struct PrintStateEventFilter<'a>(&'a StateEventFilter);
        impl fmt::Display for PrintStateEventFilter<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                // TODO: escape `#` as `\#` and `\` as `\\` in event_type
                match self.0 {
                    StateEventFilter::WithType(event_type) => write!(f, "{event_type}"),
                    StateEventFilter::WithTypeAndStateKey(event_type, state_key) => {
                        write!(f, "{event_type}#{state_key}")
                    }
                }
            }
        }

        let mut seq = serializer.serialize_seq(None)?;

        if self.requires_client {
            seq.serialize_element(REQUIRES_CLIENT)?;
        }
        if self.update_delayed_event {
            seq.serialize_element(UPDATE_DELAYED_EVENT)?;
        }
        if self.send_delayed_event {
            seq.serialize_element(SEND_DELAYED_EVENT)?;
        }
        for filter in &self.read {
            let name = match filter {
                EventFilter::MessageLike(_) => READ_EVENT,
                EventFilter::State(_) => READ_STATE,
            };
            seq.serialize_element(&format!("{name}:{}", PrintEventFilter(filter)))?;
        }
        for filter in &self.send {
            let name = match filter {
                EventFilter::MessageLike(_) => SEND_EVENT,
                EventFilter::State(_) => SEND_STATE,
            };
            seq.serialize_element(&format!("{name}:{}", PrintEventFilter(filter)))?;
        }

        seq.end()
    }
}

impl<'de> Deserialize<'de> for Capabilities {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Permission {
            RequiresClient,
            UpdateDelayedEvent,
            SendDelayedEvent,
            Read(EventFilter),
            Send(EventFilter),
            Unknown,
        }

        impl<'de> Deserialize<'de> for Permission {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                let s = ruma::serde::deserialize_cow_str(deserializer)?;
                if s == REQUIRES_CLIENT {
                    return Ok(Self::RequiresClient);
                }
                if s == UPDATE_DELAYED_EVENT {
                    return Ok(Self::UpdateDelayedEvent);
                }
                if s == SEND_DELAYED_EVENT {
                    return Ok(Self::SendDelayedEvent);
                }

                match s.split_once(':') {
                    Some((READ_EVENT, filter_s)) => Ok(Permission::Read(EventFilter::MessageLike(
                        parse_message_event_filter(filter_s),
                    ))),
                    Some((SEND_EVENT, filter_s)) => Ok(Permission::Send(EventFilter::MessageLike(
                        parse_message_event_filter(filter_s),
                    ))),
                    Some((READ_STATE, filter_s)) => {
                        Ok(Permission::Read(EventFilter::State(parse_state_event_filter(filter_s))))
                    }
                    Some((SEND_STATE, filter_s)) => {
                        Ok(Permission::Send(EventFilter::State(parse_state_event_filter(filter_s))))
                    }
                    _ => {
                        debug!("Unknown capability `{s}`");
                        Ok(Self::Unknown)
                    }
                }
            }
        }

        fn parse_message_event_filter(s: &str) -> MessageLikeEventFilter {
            match s.strip_prefix("m.room.message#") {
                Some(msgtype) => MessageLikeEventFilter::RoomMessageWithMsgtype(msgtype.to_owned()),
                // TODO: Replace `\\` by `\` and `\#` by `#`, enforce no unescaped `#`
                None => MessageLikeEventFilter::WithType(s.into()),
            }
        }

        fn parse_state_event_filter(s: &str) -> StateEventFilter {
            // TODO: Search for un-escaped `#` only, replace `\\` by `\` and `\#` by `#`
            match s.split_once('#') {
                Some((event_type, state_key)) => {
                    StateEventFilter::WithTypeAndStateKey(event_type.into(), state_key.to_owned())
                }
                None => StateEventFilter::WithType(s.into()),
            }
        }

        let mut capabilities = Capabilities::default();
        for capability in Vec::<Permission>::deserialize(deserializer)? {
            match capability {
                Permission::RequiresClient => capabilities.requires_client = true,
                Permission::Read(filter) => capabilities.read.push(filter),
                Permission::Send(filter) => capabilities.send.push(filter),
                // ignore unknown capabilities
                Permission::Unknown => {}
                Permission::UpdateDelayedEvent => capabilities.update_delayed_event = true,
                Permission::SendDelayedEvent => capabilities.send_delayed_event = true,
            }
        }

        Ok(capabilities)
    }
}

#[cfg(test)]
mod tests {
    use ruma::events::StateEventType;

    use super::*;

    #[test]
    fn deserialization_of_no_capabilities() {
        let capabilities_str = r#"[]"#;

        let parsed = serde_json::from_str::<Capabilities>(capabilities_str).unwrap();
        let expected = Capabilities::default();

        assert_eq!(parsed, expected);
    }

    #[test]
    fn deserialization_of_capabilities() {
        let capabilities_str = r#"[
            "m.always_on_screen",
            "io.element.requires_client",
            "org.matrix.msc2762.receive.event:org.matrix.rageshake_request",
            "org.matrix.msc2762.receive.state_event:m.room.member",
            "org.matrix.msc2762.receive.state_event:org.matrix.msc3401.call.member",
            "org.matrix.msc2762.send.event:org.matrix.rageshake_request",
            "org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@user:matrix.server",
            "org.matrix.msc4157.send.delayed_event",
            "org.matrix.msc4157.update_delayed_event"
        ]"#;

        let parsed = serde_json::from_str::<Capabilities>(capabilities_str).unwrap();
        let expected = Capabilities {
            read: vec![
                EventFilter::MessageLike(MessageLikeEventFilter::WithType(
                    "org.matrix.rageshake_request".into(),
                )),
                EventFilter::State(StateEventFilter::WithType(StateEventType::RoomMember)),
                EventFilter::State(StateEventFilter::WithType(
                    "org.matrix.msc3401.call.member".into(),
                )),
            ],
            send: vec![
                EventFilter::MessageLike(MessageLikeEventFilter::WithType(
                    "org.matrix.rageshake_request".into(),
                )),
                EventFilter::State(StateEventFilter::WithTypeAndStateKey(
                    "org.matrix.msc3401.call.member".into(),
                    "@user:matrix.server".into(),
                )),
            ],
            requires_client: true,
            update_delayed_event: true,
            send_delayed_event: true,
        };

        assert_eq!(parsed, expected);
    }

    #[test]
    fn serialization_and_deserialization_are_symmetrical() {
        let capabilities = Capabilities {
            read: vec![
                EventFilter::MessageLike(MessageLikeEventFilter::WithType(
                    "io.element.custom".into(),
                )),
                EventFilter::State(StateEventFilter::WithType(StateEventType::RoomMember)),
                EventFilter::State(StateEventFilter::WithTypeAndStateKey(
                    "org.matrix.msc3401.call.member".into(),
                    "@user:matrix.server".into(),
                )),
            ],
            send: vec![
                EventFilter::MessageLike(MessageLikeEventFilter::WithType(
                    "io.element.custom".into(),
                )),
                EventFilter::State(StateEventFilter::WithTypeAndStateKey(
                    "org.matrix.msc3401.call.member".into(),
                    "@user:matrix.server".into(),
                )),
            ],
            requires_client: true,
            update_delayed_event: false,
            send_delayed_event: false,
        };

        let capabilities_str = serde_json::to_string(&capabilities).unwrap();
        let parsed = serde_json::from_str::<Capabilities>(&capabilities_str).unwrap();
        assert_eq!(parsed, capabilities);
    }
}