Skip to main content

ruma_client_api/rtc/livekit/
get_token.rs

1//! `POST /_matrix/client/*/rtc/livekit/get_token`
2//!
3//! Get a token to authenticate with a LiveKit SFU for a MatrixRTC slot.
4
5pub mod v1 {
6    //! `/v1/` ([MSC], not yet documented in spec)
7    //!
8    //! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195
9
10    use ruma_common::{
11        OwnedRoomId, OwnedServerName,
12        api::{auth_scheme::AccessToken, request, response},
13        metadata,
14    };
15
16    metadata! {
17        method: POST,
18        rate_limited: true,
19        authentication: AccessToken,
20        history: {
21            unstable => "/_matrix/client/unstable/io.element.msc4195/rtc/livekit/get_token",
22            stable("org.matrix.msc4195.stable") => "/_matrix/client/v1/rtc/livekit/get_token",
23        }
24    }
25
26    /// Request type for the `get_token` endpoint.
27    #[request]
28    pub struct Request {
29        /// The server name of the sender of the `m.rtc.member` event.
30        ///
31        /// If this is `None`, the homeserver uses its own server name.
32        #[serde(skip_serializing_if = "Option::is_none")]
33        pub server_name: Option<OwnedServerName>,
34
35        /// The WebSocket URL of the LiveKit SFU.
36        pub url: String,
37
38        /// The room where the `m.rtc.member` event is present.
39        pub room_id: OwnedRoomId,
40
41        /// The slot ID from the `m.rtc.member` event.
42        pub slot_id: String,
43
44        /// The `member.id` property of the requesting user's own `m.rtc.member` event.
45        pub member_id: String,
46    }
47
48    impl Request {
49        /// Creates a new `Request` with the given SFU URL, room ID, slot ID and member ID.
50        ///
51        /// The `server_name` field is set to `None`, which means that the homeserver uses its own
52        /// server name.
53        pub fn new(url: String, room_id: OwnedRoomId, slot_id: String, member_id: String) -> Self {
54            Self { server_name: None, url, room_id, slot_id, member_id }
55        }
56    }
57
58    /// Response type for the `get_token` endpoint.
59    #[response]
60    pub struct Response {
61        /// The JWT token to use for authentication with the SFU.
62        pub jwt: String,
63    }
64
65    impl Response {
66        /// Creates a new `Response` with the given JWT token. The corresponding SFU url is already
67        /// known via the request params.
68        pub fn new(jwt: String) -> Self {
69            Self { jwt }
70        }
71    }
72
73    #[cfg(all(test, feature = "client"))]
74    mod tests {
75        use std::{borrow::Cow, collections::BTreeSet};
76
77        use ruma_common::{
78            api::{
79                FeatureFlag, OutgoingRequestExt as _, SupportedVersions,
80                auth_scheme::SendAccessToken,
81            },
82            owned_room_id, owned_server_name,
83        };
84        use serde_json::{Value as JsonValue, json};
85
86        use super::Request;
87
88        fn serialize_request(request: Request) -> (http::request::Parts, JsonValue) {
89            serialize_request_with(request, Default::default())
90        }
91
92        fn serialize_request_with(
93            request: Request,
94            features: BTreeSet<FeatureFlag>,
95        ) -> (http::request::Parts, JsonValue) {
96            let supported = SupportedVersions { versions: Default::default(), features };
97
98            let (parts, body) = request
99                .try_into_http_request::<Vec<u8>>(
100                    "https://homeserver.tld",
101                    SendAccessToken::IfRequired("auth_tok"),
102                    Cow::Owned(supported),
103                )
104                .unwrap()
105                .into_parts();
106
107            (parts, serde_json::from_slice(&body).unwrap())
108        }
109
110        #[test]
111        fn serialize_request_without_server_name() {
112            let request = Request::new(
113                "wss://livekit.example.com".to_owned(),
114                owned_room_id!("!tDLCaLXijNtYcJZEey:example.com"),
115                "the_id".to_owned(),
116                "xyzABCDEF10123".to_owned(),
117            );
118
119            let (parts, body) = serialize_request(request);
120
121            assert_eq!("POST", parts.method.as_str());
122            assert_eq!(
123                "https://homeserver.tld/_matrix/client/unstable/io.element.msc4195/rtc/livekit/get_token",
124                parts.uri.to_string()
125            );
126            assert_eq!(
127                body,
128                json!({
129                    "url": "wss://livekit.example.com",
130                    "room_id": "!tDLCaLXijNtYcJZEey:example.com",
131                    "slot_id": "the_id",
132                    "member_id": "xyzABCDEF10123",
133                })
134            );
135        }
136
137        #[test]
138        fn serialize_request_with_server_name() {
139            let mut request = Request::new(
140                "wss://livekit.example.com".to_owned(),
141                owned_room_id!("!tDLCaLXijNtYcJZEey:example.com"),
142                "the_id".to_owned(),
143                "xyzABCDEF10123".to_owned(),
144            );
145            request.server_name = Some(owned_server_name!("example.com"));
146
147            let (_parts, body) = serialize_request(request);
148
149            assert_eq!(
150                body,
151                json!({
152                    "server_name": "example.com",
153                    "url": "wss://livekit.example.com",
154                    "room_id": "!tDLCaLXijNtYcJZEey:example.com",
155                    "slot_id": "the_id",
156                    "member_id": "xyzABCDEF10123",
157                })
158            );
159        }
160
161        #[test]
162        fn serialize_request_stable() {
163            let request = Request::new(
164                "wss://livekit.example.com".to_owned(),
165                owned_room_id!("!tDLCaLXijNtYcJZEey:example.com"),
166                "the_id".to_owned(),
167                "xyzABCDEF10123".to_owned(),
168            );
169
170            let (parts, body) =
171                serialize_request_with(request, BTreeSet::from([FeatureFlag::Msc4195Stable]));
172
173            assert_eq!("POST", parts.method.as_str());
174            assert_eq!(
175                "https://homeserver.tld/_matrix/client/v1/rtc/livekit/get_token",
176                parts.uri.to_string()
177            );
178            assert_eq!(
179                body,
180                json!({
181                    "url": "wss://livekit.example.com",
182                    "room_id": "!tDLCaLXijNtYcJZEey:example.com",
183                    "slot_id": "the_id",
184                    "member_id": "xyzABCDEF10123",
185                })
186            );
187        }
188    }
189
190    #[cfg(all(test, feature = "server"))]
191    mod server_tests {
192        use ruma_common::api::IncomingRequestExt as _;
193
194        use super::Request;
195
196        fn deserialize_request(uri: &str) -> Request {
197            let request = http::Request::builder()
198                .method("POST")
199                .uri(uri)
200                .body(
201                    br#"{
202                        "url": "wss://livekit.example.org",
203                        "room_id": "!tDLCaLXijNtYcJZEey:example.org",
204                        "slot_id": "the_id",
205                        "member_id": "xyzABCDEF10123"
206                    }"# as &[u8],
207                )
208                .unwrap();
209
210            Request::try_from_http_request(request, &[] as &[&str]).unwrap()
211        }
212
213        fn assert_request(request: &Request) {
214            assert_eq!(request.server_name, None);
215            assert_eq!(request.url, "wss://livekit.example.org");
216            assert_eq!(request.room_id, "!tDLCaLXijNtYcJZEey:example.org");
217            assert_eq!(request.slot_id, "the_id");
218            assert_eq!(request.member_id, "xyzABCDEF10123");
219        }
220
221        #[test]
222        fn deserialize_request_unstable() {
223            let request = deserialize_request(
224                "/_matrix/client/unstable/io.element.msc4195/rtc/livekit/get_token",
225            );
226            assert_request(&request);
227        }
228
229        #[test]
230        fn deserialize_request_stable() {
231            let request = deserialize_request("/_matrix/client/v1/rtc/livekit/get_token");
232            assert_request(&request);
233        }
234    }
235}