BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / realtime / event.rs

event.rs

event.rs 14.5 KiB Download Raw
1use chrono::{DateTime, Utc};
2use serde::Deserialize;
3
4use super::host::is_trouter_host;
5use crate::error::{Error, Result};
6
7const MAX_FIELD_LENGTH: usize = 256;
8const ORGID_PREFIX: &str = "8:orgid:";
9const HTTPS_PREFIX: &str = "https://";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum EventKind {
14 NewMessage,
15 MessageUpdate,
16 ThreadUpdate,
17 Typing,
18 ReadReceipt,
19 ThreadActivity,
20 Control,
21 #[serde(other)]
22 Other,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct MessageEvent {
27 pub resource_type: String,
28 pub kind: EventKind,
29 pub conversation_id: Option<String>,
30 pub message_id: Option<String>,
31 pub received_at: DateTime<Utc>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct TypingEvent {
36 pub conversation_id: String,
37 pub user_id: String,
38 pub display_name: String,
39 pub active: bool,
40 pub received_at: DateTime<Utc>,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum StatusKind {
46 Connected,
47 Disconnected,
48 MessageLoss,
49 Error,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct StatusEvent {
54 pub kind: StatusKind,
55 pub detail: String,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PresenceUpdate {
60 pub user_id: String,
61 pub availability: String,
62 pub activity: Option<String>,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct TrouterEndpoint {
67 pub endpoint_id: String,
68 pub trouter_uri: String,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum RealtimeEvent {
73 Message(MessageEvent),
74 Typing(TypingEvent),
75 Status(StatusEvent),
76 Presence(Vec<PresenceUpdate>),
77 Endpoint(TrouterEndpoint),
78}
79
80#[derive(Deserialize)]
81struct WirePresence {
82 mri: String,
83 availability: String,
84 #[serde(default)]
85 activity: Option<String>,
86}
87
88#[derive(Deserialize)]
89#[serde(tag = "channel", rename_all = "snake_case")]
90enum Wire {
91 Event {
92 #[serde(rename = "resourceType")]
93 resource_type: String,
94 #[serde(rename = "eventKind")]
95 event_kind: EventKind,
96 #[serde(rename = "conversationId", default)]
97 conversation_id: Option<String>,
98 #[serde(rename = "messageId", default)]
99 message_id: Option<String>,
100 #[serde(rename = "receivedAt")]
101 received_at: i64,
102 #[serde(default)]
103 typing: Option<String>,
104 #[serde(rename = "senderId", default)]
105 sender_id: Option<String>,
106 #[serde(rename = "senderName", default)]
107 sender_name: Option<String>,
108 },
109 Status {
110 kind: StatusKind,
111 #[serde(default)]
112 detail: String,
113 },
114 Presence {
115 entries: Vec<WirePresence>,
116 },
117 Endpoint {
118 #[serde(rename = "endpointId")]
119 endpoint_id: String,
120 #[serde(rename = "trouterUri")]
121 trouter_uri: String,
122 },
123}
124
125pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
126 let wire: Wire =
127 serde_json::from_str(payload).map_err(|error| Error::Decode(error.to_string()))?;
128 match wire {
129 Wire::Event {
130 resource_type,
131 event_kind,
132 conversation_id,
133 message_id,
134 received_at,
135 typing,
136 sender_id,
137 sender_name,
138 } => {
139 let received_at = DateTime::from_timestamp_millis(received_at)
140 .ok_or_else(|| Error::Decode("receivedAt out of range".into()))?;
141 let conversation_id = conversation_id
142 .map(bounded)
143 .filter(|value| !value.is_empty());
144 if event_kind == EventKind::Typing
145 && let Some(event) = typing_event(
146 conversation_id.clone(),
147 typing.as_deref(),
148 sender_id,
149 sender_name,
150 received_at,
151 )
152 {
153 return Ok(RealtimeEvent::Typing(event));
154 }
155 Ok(RealtimeEvent::Message(MessageEvent {
156 resource_type: bounded(resource_type),
157 kind: event_kind,
158 conversation_id,
159 message_id: message_id.map(bounded).filter(|value| !value.is_empty()),
160 received_at,
161 }))
162 }
163 Wire::Status { kind, detail } => Ok(RealtimeEvent::Status(StatusEvent {
164 kind,
165 detail: bounded(detail),
166 })),
167 Wire::Presence { entries } => Ok(RealtimeEvent::Presence(
168 entries
169 .into_iter()
170 .filter_map(|entry| {
171 let user_id = entry.mri.strip_prefix(ORGID_PREFIX)?;
172 Some(PresenceUpdate {
173 user_id: bounded(user_id.to_owned()),
174 availability: bounded(entry.availability),
175 activity: entry
176 .activity
177 .map(bounded)
178 .filter(|value| !value.is_empty()),
179 })
180 })
181 .collect(),
182 )),
183 Wire::Endpoint {
184 endpoint_id,
185 trouter_uri,
186 } => {
187 let host = trouter_uri
188 .strip_prefix(HTTPS_PREFIX)
189 .and_then(|rest| rest.split('/').next())
190 .map(without_port)
191 .filter(|host| is_trouter_host(host));
192 if host.is_none() || endpoint_id.is_empty() {
193 return Err(Error::Decode("endpoint rejected".into()));
194 }
195 Ok(RealtimeEvent::Endpoint(TrouterEndpoint {
196 endpoint_id: bounded(endpoint_id),
197 trouter_uri,
198 }))
199 }
200 }
201}
202
203fn typing_event(
204 conversation_id: Option<String>,
205 signal: Option<&str>,
206 sender_id: Option<String>,
207 sender_name: Option<String>,
208 received_at: DateTime<Utc>,
209) -> Option<TypingEvent> {
210 let active = match signal? {
211 "start" => true,
212 "clear" => false,
213 _ => return None,
214 };
215 let user_id = bounded(sender_id?);
216 if user_id.is_empty() {
217 return None;
218 }
219 Some(TypingEvent {
220 conversation_id: conversation_id?,
221 user_id,
222 display_name: bounded(sender_name.unwrap_or_default()),
223 active,
224 received_at,
225 })
226}
227
228fn without_port(authority: &str) -> &str {
229 match authority.rsplit_once(':') {
230 Some((host, port))
231 if !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit()) =>
232 {
233 host
234 }
235 _ => authority,
236 }
237}
238
239fn bounded(value: String) -> String {
240 value.chars().take(MAX_FIELD_LENGTH).collect()
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246
247 #[test]
248 fn decodes_message_event() {
249 let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"new_message",
250 "conversationId":"19:abc@thread.v2","messageId":"1791368146075","receivedAt":1791368146999}"#;
251 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
252 panic!("expected message")
253 };
254 assert_eq!(event.kind, EventKind::NewMessage);
255 assert_eq!(event.resource_type, "NewMessage");
256 assert_eq!(event.conversation_id.as_deref(), Some("19:abc@thread.v2"));
257 assert_eq!(event.message_id.as_deref(), Some("1791368146075"));
258 assert_eq!(event.received_at.timestamp_millis(), 1791368146999);
259 }
260
261 #[test]
262 fn null_and_empty_ids_become_none() {
263 let payload = r#"{"channel":"event","resourceType":"typing","eventKind":"typing",
264 "conversationId":null,"messageId":"","receivedAt":1}"#;
265 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
266 panic!("expected message")
267 };
268 assert_eq!(event.conversation_id, None);
269 assert_eq!(event.message_id, None);
270 }
271
272 #[test]
273 fn unknown_event_kind_is_other() {
274 let payload =
275 r#"{"channel":"event","resourceType":"X","eventKind":"brand_new","receivedAt":1}"#;
276 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
277 panic!("expected message")
278 };
279 assert_eq!(event.kind, EventKind::Other);
280 }
281
282 fn typing_payload(extra: &str) -> String {
283 format!(
284 r#"{{"channel":"event","resourceType":"NewMessage","eventKind":"typing",
285 "conversationId":"19:abc@thread.v2","messageId":null,"receivedAt":5{extra}}}"#
286 )
287 }
288
289 #[test]
290 fn decodes_typing_start_and_clear() {
291 for (signal, active) in [("start", true), ("clear", false)] {
292 let payload = typing_payload(&format!(
293 r#","typing":"{signal}","senderId":"abc-1","senderName":"Ada Lovelace""#
294 ));
295 assert_eq!(
296 decode_payload(&payload).unwrap(),
297 RealtimeEvent::Typing(TypingEvent {
298 conversation_id: "19:abc@thread.v2".into(),
299 user_id: "abc-1".into(),
300 display_name: "Ada Lovelace".into(),
301 active,
302 received_at: DateTime::from_timestamp_millis(5).unwrap(),
303 })
304 );
305 }
306 }
307
308 #[test]
309 fn typing_without_a_name_keeps_an_empty_name_and_cuts_long_ones() {
310 let RealtimeEvent::Typing(event) =
311 decode_payload(&typing_payload(r#","typing":"start","senderId":"a""#)).unwrap()
312 else {
313 panic!("expected typing")
314 };
315 assert_eq!(event.display_name, "");
316 let long = typing_payload(&format!(
317 r#","typing":"start","senderId":"a","senderName":"{}""#,
318 "n".repeat(1000)
319 ));
320 let RealtimeEvent::Typing(event) = decode_payload(&long).unwrap() else {
321 panic!("expected typing")
322 };
323 assert_eq!(event.display_name.chars().count(), MAX_FIELD_LENGTH);
324 }
325
326 #[test]
327 fn typing_without_a_valid_sender_or_signal_stays_a_plain_message() {
328 for extra in [
329 "",
330 r#","typing":"start""#,
331 r#","typing":"start","senderId":null"#,
332 r##","typing":"start","senderId":"""##,
333 r#","typing":"bogus","senderId":"a""#,
334 r#","senderId":"a""#,
335 ] {
336 let RealtimeEvent::Message(event) = decode_payload(&typing_payload(extra)).unwrap()
337 else {
338 panic!("expected message for {extra}")
339 };
340 assert_eq!(event.kind, EventKind::Typing);
341 }
342 }
343
344 #[test]
345 fn typing_without_a_conversation_stays_a_plain_message() {
346 let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"typing",
347 "conversationId":null,"receivedAt":5,"typing":"start","senderId":"a"}"#;
348 assert!(matches!(
349 decode_payload(payload).unwrap(),
350 RealtimeEvent::Message(_)
351 ));
352 }
353
354 #[test]
355 fn decodes_every_status_kind() {
356 for (name, kind) in [
357 ("connected", StatusKind::Connected),
358 ("disconnected", StatusKind::Disconnected),
359 ("message_loss", StatusKind::MessageLoss),
360 ("error", StatusKind::Error),
361 ] {
362 let payload = format!(r#"{{"channel":"status","kind":"{name}","detail":"d"}}"#);
363 assert_eq!(
364 decode_payload(&payload).unwrap(),
365 RealtimeEvent::Status(StatusEvent {
366 kind,
367 detail: "d".into()
368 })
369 );
370 }
371 }
372
373 #[test]
374 fn status_detail_is_optional() {
375 let RealtimeEvent::Status(status) =
376 decode_payload(r#"{"channel":"status","kind":"connected"}"#).unwrap()
377 else {
378 panic!("expected status")
379 };
380 assert_eq!(status.detail, "");
381 }
382
383 #[test]
384 fn long_fields_are_cut() {
385 let payload = format!(
386 r#"{{"channel":"status","kind":"error","detail":"{}"}}"#,
387 "x".repeat(1000)
388 );
389 let RealtimeEvent::Status(status) = decode_payload(&payload).unwrap() else {
390 panic!("expected status")
391 };
392 assert_eq!(status.detail.chars().count(), MAX_FIELD_LENGTH);
393 }
394
395 #[test]
396 fn decodes_presence_and_skips_foreign_mris() {
397 let payload = r#"{"channel":"presence","entries":[
398 {"mri":"8:orgid:abc","availability":"Busy","activity":"InACall"},
399 {"mri":"8:orgid:def","availability":"Away","activity":""},
400 {"mri":"4:+4912345","availability":"Offline"}]}"#;
401 let RealtimeEvent::Presence(updates) = decode_payload(payload).unwrap() else {
402 panic!("expected presence")
403 };
404 assert_eq!(
405 updates,
406 vec![
407 PresenceUpdate {
408 user_id: "abc".into(),
409 availability: "Busy".into(),
410 activity: Some("InACall".into()),
411 },
412 PresenceUpdate {
413 user_id: "def".into(),
414 availability: "Away".into(),
415 activity: None,
416 },
417 ]
418 );
419 }
420
421 #[test]
422 fn decodes_endpoint_on_a_trouter_host() {
423 let payload = r#"{"channel":"endpoint","endpointId":"e1",
424 "trouterUri":"https://pub-ent-sece-04-f.trouter.teams.microsoft.com:3443/v4/f/x/unifiedPresenceService"}"#;
425 let RealtimeEvent::Endpoint(endpoint) = decode_payload(payload).unwrap() else {
426 panic!("expected endpoint")
427 };
428 assert_eq!(endpoint.endpoint_id, "e1");
429 assert!(endpoint.trouter_uri.ends_with("/unifiedPresenceService"));
430 }
431
432 #[test]
433 fn rejects_endpoints_off_trouter_or_without_https() {
434 for uri in [
435 "https://evil.example/unifiedPresenceService",
436 "http://go-eu.trouter.teams.microsoft.com/x",
437 "https://go-eu.trouter.teams.microsoft.com.evil.com/x",
438 "https://a@go-eu.trouter.teams.microsoft.com/x",
439 "https://go-eu.trouter.teams.microsoft.com:x/x",
440 "go-eu.trouter.teams.microsoft.com/x",
441 ] {
442 let payload =
443 format!(r#"{{"channel":"endpoint","endpointId":"e1","trouterUri":"{uri}"}}"#);
444 assert!(decode_payload(&payload).is_err(), "{uri}");
445 }
446 }
447
448 #[test]
449 fn rejects_garbage() {
450 assert!(decode_payload("not json").is_err());
451 assert!(decode_payload(r#"{"channel":"other"}"#).is_err());
452 assert!(decode_payload(r#"{"channel":"status","kind":"weird"}"#).is_err());
453 assert!(decode_payload(r#"{"channel":"event","resourceType":"x","eventKind":"typing","receivedAt":9223372036854775807}"#).is_err());
454 }
455}