BlueGit

ict rusty-teams

Files

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

event.rs

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