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