BlueGit

ict rusty-teams

Files

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

event.rs

event.rs 15.4 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.activity.map(bounded).filter(|value| !value.is_empty())
184 },
185 })
186 })
187 .collect(),
188 )),
189 Wire::Endpoint {
190 endpoint_id,
191 trouter_uri,
192 } => {
193 let host = trouter_uri
194 .strip_prefix(HTTPS_PREFIX)
195 .and_then(|rest| rest.split('/').next())
196 .map(without_port)
197 .filter(|host| is_trouter_host(host));
198 if host.is_none() || endpoint_id.is_empty() {
199 return Err(Error::Decode("endpoint rejected".into()));
200 }
201 Ok(RealtimeEvent::Endpoint(TrouterEndpoint {
202 endpoint_id: bounded(endpoint_id),
203 trouter_uri,
204 }))
205 }
206 }
207}
208
209fn typing_event(
210 conversation_id: Option<String>,
211 signal: Option<&str>,
212 sender_id: Option<String>,
213 sender_name: Option<String>,
214 received_at: DateTime<Utc>,
215) -> Option<TypingEvent> {
216 let active = match signal? {
217 "start" => true,
218 "clear" => false,
219 _ => return None,
220 };
221 let user_id = bounded(sender_id?);
222 if user_id.is_empty() {
223 return None;
224 }
225 Some(TypingEvent {
226 conversation_id: conversation_id?,
227 user_id,
228 display_name: bounded(sender_name.unwrap_or_default()),
229 active,
230 received_at,
231 })
232}
233
234fn without_port(authority: &str) -> &str {
235 match authority.rsplit_once(':') {
236 Some((host, port))
237 if !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit()) =>
238 {
239 host
240 }
241 _ => authority,
242 }
243}
244
245fn bounded(value: String) -> String {
246 value.chars().take(MAX_FIELD_LENGTH).collect()
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 #[test]
254 fn decodes_message_event() {
255 let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"new_message",
256 "conversationId":"19:abc@thread.v2","messageId":"1791368146075","receivedAt":1791368146999}"#;
257 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
258 panic!("expected message")
259 };
260 assert_eq!(event.kind, EventKind::NewMessage);
261 assert_eq!(event.resource_type, "NewMessage");
262 assert_eq!(event.conversation_id.as_deref(), Some("19:abc@thread.v2"));
263 assert_eq!(event.message_id.as_deref(), Some("1791368146075"));
264 assert_eq!(event.received_at.timestamp_millis(), 1791368146999);
265 }
266
267 #[test]
268 fn decodes_pins_changed_kind() {
269 let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"pins_changed",
270 "conversationId":"19:abc@thread.v2","receivedAt":1}"#;
271 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
272 panic!("expected message")
273 };
274 assert_eq!(event.kind, EventKind::PinsChanged);
275 }
276
277 #[test]
278 fn null_and_empty_ids_become_none() {
279 let payload = r#"{"channel":"event","resourceType":"typing","eventKind":"typing",
280 "conversationId":null,"messageId":"","receivedAt":1}"#;
281 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
282 panic!("expected message")
283 };
284 assert_eq!(event.conversation_id, None);
285 assert_eq!(event.message_id, None);
286 }
287
288 #[test]
289 fn unknown_event_kind_is_other() {
290 let payload =
291 r#"{"channel":"event","resourceType":"X","eventKind":"brand_new","receivedAt":1}"#;
292 let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
293 panic!("expected message")
294 };
295 assert_eq!(event.kind, EventKind::Other);
296 }
297
298 fn typing_payload(extra: &str) -> String {
299 format!(
300 r#"{{"channel":"event","resourceType":"NewMessage","eventKind":"typing",
301 "conversationId":"19:abc@thread.v2","messageId":null,"receivedAt":5{extra}}}"#
302 )
303 }
304
305 #[test]
306 fn decodes_typing_start_and_clear() {
307 for (signal, active) in [("start", true), ("clear", false)] {
308 let payload = typing_payload(&format!(
309 r#","typing":"{signal}","senderId":"abc-1","senderName":"Ada Lovelace""#
310 ));
311 assert_eq!(
312 decode_payload(&payload).unwrap(),
313 RealtimeEvent::Typing(TypingEvent {
314 conversation_id: "19:abc@thread.v2".into(),
315 user_id: "abc-1".into(),
316 display_name: "Ada Lovelace".into(),
317 active,
318 received_at: DateTime::from_timestamp_millis(5).unwrap(),
319 })
320 );
321 }
322 }
323
324 #[test]
325 fn typing_without_a_name_keeps_an_empty_name_and_cuts_long_ones() {
326 let RealtimeEvent::Typing(event) =
327 decode_payload(&typing_payload(r#","typing":"start","senderId":"a""#)).unwrap()
328 else {
329 panic!("expected typing")
330 };
331 assert_eq!(event.display_name, "");
332 let long = typing_payload(&format!(
333 r#","typing":"start","senderId":"a","senderName":"{}""#,
334 "n".repeat(1000)
335 ));
336 let RealtimeEvent::Typing(event) = decode_payload(&long).unwrap() else {
337 panic!("expected typing")
338 };
339 assert_eq!(event.display_name.chars().count(), MAX_FIELD_LENGTH);
340 }
341
342 #[test]
343 fn typing_without_a_valid_sender_or_signal_stays_a_plain_message() {
344 for extra in [
345 "",
346 r#","typing":"start""#,
347 r#","typing":"start","senderId":null"#,
348 r##","typing":"start","senderId":"""##,
349 r#","typing":"bogus","senderId":"a""#,
350 r#","senderId":"a""#,
351 ] {
352 let RealtimeEvent::Message(event) = decode_payload(&typing_payload(extra)).unwrap()
353 else {
354 panic!("expected message for {extra}")
355 };
356 assert_eq!(event.kind, EventKind::Typing);
357 }
358 }
359
360 #[test]
361 fn typing_without_a_conversation_stays_a_plain_message() {
362 let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"typing",
363 "conversationId":null,"receivedAt":5,"typing":"start","senderId":"a"}"#;
364 assert!(matches!(
365 decode_payload(payload).unwrap(),
366 RealtimeEvent::Message(_)
367 ));
368 }
369
370 #[test]
371 fn decodes_every_status_kind() {
372 for (name, kind) in [
373 ("connected", StatusKind::Connected),
374 ("disconnected", StatusKind::Disconnected),
375 ("message_loss", StatusKind::MessageLoss),
376 ("error", StatusKind::Error),
377 ] {
378 let payload = format!(r#"{{"channel":"status","kind":"{name}","detail":"d"}}"#);
379 assert_eq!(
380 decode_payload(&payload).unwrap(),
381 RealtimeEvent::Status(StatusEvent {
382 kind,
383 detail: "d".into()
384 })
385 );
386 }
387 }
388
389 #[test]
390 fn status_detail_is_optional() {
391 let RealtimeEvent::Status(status) =
392 decode_payload(r#"{"channel":"status","kind":"connected"}"#).unwrap()
393 else {
394 panic!("expected status")
395 };
396 assert_eq!(status.detail, "");
397 }
398
399 #[test]
400 fn long_fields_are_cut() {
401 let payload = format!(
402 r#"{{"channel":"status","kind":"error","detail":"{}"}}"#,
403 "x".repeat(1000)
404 );
405 let RealtimeEvent::Status(status) = decode_payload(&payload).unwrap() else {
406 panic!("expected status")
407 };
408 assert_eq!(status.detail.chars().count(), MAX_FIELD_LENGTH);
409 }
410
411 #[test]
412 fn decodes_presence_and_skips_foreign_mris() {
413 let payload = r#"{"channel":"presence","entries":[
414 {"mri":"8:orgid:abc","availability":"Busy","activity":"InACall"},
415 {"mri":"8:orgid:def","availability":"Away","activity":""},
416 {"mri":"8:orgid:ooo","availability":"Offline","activity":"OffWork","outOfOffice":true},
417 {"mri":"4:+4912345","availability":"Offline"}]}"#;
418 let RealtimeEvent::Presence(updates) = decode_payload(payload).unwrap() else {
419 panic!("expected presence")
420 };
421 assert_eq!(
422 updates,
423 vec![
424 PresenceUpdate {
425 user_id: "abc".into(),
426 availability: "Busy".into(),
427 activity: Some("InACall".into()),
428 },
429 PresenceUpdate {
430 user_id: "def".into(),
431 availability: "Away".into(),
432 activity: None,
433 },
434 PresenceUpdate {
435 user_id: "ooo".into(),
436 availability: "Offline".into(),
437 activity: Some("OutOfOffice".into()),
438 },
439 ]
440 );
441 }
442
443 #[test]
444 fn decodes_endpoint_on_a_trouter_host() {
445 let payload = r#"{"channel":"endpoint","endpointId":"e1",
446 "trouterUri":"https://pub-ent-sece-04-f.trouter.teams.microsoft.com:3443/v4/f/x/unifiedPresenceService"}"#;
447 let RealtimeEvent::Endpoint(endpoint) = decode_payload(payload).unwrap() else {
448 panic!("expected endpoint")
449 };
450 assert_eq!(endpoint.endpoint_id, "e1");
451 assert!(endpoint.trouter_uri.ends_with("/unifiedPresenceService"));
452 }
453
454 #[test]
455 fn rejects_endpoints_off_trouter_or_without_https() {
456 for uri in [
457 "https://evil.example/unifiedPresenceService",
458 "http://go-eu.trouter.teams.microsoft.com/x",
459 "https://go-eu.trouter.teams.microsoft.com.evil.com/x",
460 "https://a@go-eu.trouter.teams.microsoft.com/x",
461 "https://go-eu.trouter.teams.microsoft.com:x/x",
462 "go-eu.trouter.teams.microsoft.com/x",
463 ] {
464 let payload =
465 format!(r#"{{"channel":"endpoint","endpointId":"e1","trouterUri":"{uri}"}}"#);
466 assert!(decode_payload(&payload).is_err(), "{uri}");
467 }
468 }
469
470 #[test]
471 fn rejects_garbage() {
472 assert!(decode_payload("not json").is_err());
473 assert!(decode_payload(r#"{"channel":"other"}"#).is_err());
474 assert!(decode_payload(r#"{"channel":"status","kind":"weird"}"#).is_err());
475 assert!(decode_payload(r#"{"channel":"event","resourceType":"x","eventKind":"typing","receivedAt":9223372036854775807}"#).is_err());
476 }
477}