| 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 | |
| 11 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] |
| 12 | #[serde(rename_all = "snake_case")] |
| 13 | pub 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)] |
| 26 | pub 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, Copy, PartialEq, Eq, Deserialize)] |
| 35 | #[serde(rename_all = "snake_case")] |
| 36 | pub enum StatusKind { |
| 37 | Connected, |
| 38 | Disconnected, |
| 39 | MessageLoss, |
| 40 | Error, |
| 41 | } |
| 42 | |
| 43 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 44 | pub struct StatusEvent { |
| 45 | pub kind: StatusKind, |
| 46 | pub detail: String, |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 50 | pub struct PresenceUpdate { |
| 51 | pub user_id: String, |
| 52 | pub availability: String, |
| 53 | pub activity: Option<String>, |
| 54 | } |
| 55 | |
| 56 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 57 | pub struct TrouterEndpoint { |
| 58 | pub endpoint_id: String, |
| 59 | pub trouter_uri: String, |
| 60 | } |
| 61 | |
| 62 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 63 | pub enum RealtimeEvent { |
| 64 | Message(MessageEvent), |
| 65 | Status(StatusEvent), |
| 66 | Presence(Vec<PresenceUpdate>), |
| 67 | Endpoint(TrouterEndpoint), |
| 68 | } |
| 69 | |
| 70 | #[derive(Deserialize)] |
| 71 | struct WirePresence { |
| 72 | mri: String, |
| 73 | availability: String, |
| 74 | #[serde(default)] |
| 75 | activity: Option<String>, |
| 76 | } |
| 77 | |
| 78 | #[derive(Deserialize)] |
| 79 | #[serde(tag = "channel", rename_all = "snake_case")] |
| 80 | enum Wire { |
| 81 | Event { |
| 82 | #[serde(rename = "resourceType")] |
| 83 | resource_type: String, |
| 84 | #[serde(rename = "eventKind")] |
| 85 | event_kind: EventKind, |
| 86 | #[serde(rename = "conversationId", default)] |
| 87 | conversation_id: Option<String>, |
| 88 | #[serde(rename = "messageId", default)] |
| 89 | message_id: Option<String>, |
| 90 | #[serde(rename = "receivedAt")] |
| 91 | received_at: i64, |
| 92 | }, |
| 93 | Status { |
| 94 | kind: StatusKind, |
| 95 | #[serde(default)] |
| 96 | detail: String, |
| 97 | }, |
| 98 | Presence { |
| 99 | entries: Vec<WirePresence>, |
| 100 | }, |
| 101 | Endpoint { |
| 102 | #[serde(rename = "endpointId")] |
| 103 | endpoint_id: String, |
| 104 | #[serde(rename = "trouterUri")] |
| 105 | trouter_uri: String, |
| 106 | }, |
| 107 | } |
| 108 | |
| 109 | pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> { |
| 110 | let wire: Wire = |
| 111 | serde_json::from_str(payload).map_err(|error| Error::Decode(error.to_string()))?; |
| 112 | match wire { |
| 113 | Wire::Event { |
| 114 | resource_type, |
| 115 | event_kind, |
| 116 | conversation_id, |
| 117 | message_id, |
| 118 | received_at, |
| 119 | } => { |
| 120 | let received_at = DateTime::from_timestamp_millis(received_at) |
| 121 | .ok_or_else(|| Error::Decode("receivedAt out of range".into()))?; |
| 122 | Ok(RealtimeEvent::Message(MessageEvent { |
| 123 | resource_type: bounded(resource_type), |
| 124 | kind: event_kind, |
| 125 | conversation_id: conversation_id |
| 126 | .map(bounded) |
| 127 | .filter(|value| !value.is_empty()), |
| 128 | message_id: message_id.map(bounded).filter(|value| !value.is_empty()), |
| 129 | received_at, |
| 130 | })) |
| 131 | } |
| 132 | Wire::Status { kind, detail } => Ok(RealtimeEvent::Status(StatusEvent { |
| 133 | kind, |
| 134 | detail: bounded(detail), |
| 135 | })), |
| 136 | Wire::Presence { entries } => Ok(RealtimeEvent::Presence( |
| 137 | entries |
| 138 | .into_iter() |
| 139 | .filter_map(|entry| { |
| 140 | let user_id = entry.mri.strip_prefix(ORGID_PREFIX)?; |
| 141 | Some(PresenceUpdate { |
| 142 | user_id: bounded(user_id.to_owned()), |
| 143 | availability: bounded(entry.availability), |
| 144 | activity: entry |
| 145 | .activity |
| 146 | .map(bounded) |
| 147 | .filter(|value| !value.is_empty()), |
| 148 | }) |
| 149 | }) |
| 150 | .collect(), |
| 151 | )), |
| 152 | Wire::Endpoint { |
| 153 | endpoint_id, |
| 154 | trouter_uri, |
| 155 | } => { |
| 156 | let host = trouter_uri |
| 157 | .strip_prefix(HTTPS_PREFIX) |
| 158 | .and_then(|rest| rest.split('/').next()) |
| 159 | .map(without_port) |
| 160 | .filter(|host| is_trouter_host(host)); |
| 161 | if host.is_none() || endpoint_id.is_empty() { |
| 162 | return Err(Error::Decode("endpoint rejected".into())); |
| 163 | } |
| 164 | Ok(RealtimeEvent::Endpoint(TrouterEndpoint { |
| 165 | endpoint_id: bounded(endpoint_id), |
| 166 | trouter_uri, |
| 167 | })) |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | fn without_port(authority: &str) -> &str { |
| 173 | match authority.rsplit_once(':') { |
| 174 | Some((host, port)) |
| 175 | if !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit()) => |
| 176 | { |
| 177 | host |
| 178 | } |
| 179 | _ => authority, |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | fn bounded(value: String) -> String { |
| 184 | value.chars().take(MAX_FIELD_LENGTH).collect() |
| 185 | } |
| 186 | |
| 187 | #[cfg(test)] |
| 188 | mod tests { |
| 189 | use super::*; |
| 190 | |
| 191 | #[test] |
| 192 | fn decodes_message_event() { |
| 193 | let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"new_message", |
| 194 | "conversationId":"19:abc@thread.v2","messageId":"1791368146075","receivedAt":1791368146999}"#; |
| 195 | let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else { |
| 196 | panic!("expected message") |
| 197 | }; |
| 198 | assert_eq!(event.kind, EventKind::NewMessage); |
| 199 | assert_eq!(event.resource_type, "NewMessage"); |
| 200 | assert_eq!(event.conversation_id.as_deref(), Some("19:abc@thread.v2")); |
| 201 | assert_eq!(event.message_id.as_deref(), Some("1791368146075")); |
| 202 | assert_eq!(event.received_at.timestamp_millis(), 1791368146999); |
| 203 | } |
| 204 | |
| 205 | #[test] |
| 206 | fn null_and_empty_ids_become_none() { |
| 207 | let payload = r#"{"channel":"event","resourceType":"typing","eventKind":"typing", |
| 208 | "conversationId":null,"messageId":"","receivedAt":1}"#; |
| 209 | let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else { |
| 210 | panic!("expected message") |
| 211 | }; |
| 212 | assert_eq!(event.conversation_id, None); |
| 213 | assert_eq!(event.message_id, None); |
| 214 | } |
| 215 | |
| 216 | #[test] |
| 217 | fn unknown_event_kind_is_other() { |
| 218 | let payload = |
| 219 | r#"{"channel":"event","resourceType":"X","eventKind":"brand_new","receivedAt":1}"#; |
| 220 | let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else { |
| 221 | panic!("expected message") |
| 222 | }; |
| 223 | assert_eq!(event.kind, EventKind::Other); |
| 224 | } |
| 225 | |
| 226 | #[test] |
| 227 | fn decodes_every_status_kind() { |
| 228 | for (name, kind) in [ |
| 229 | ("connected", StatusKind::Connected), |
| 230 | ("disconnected", StatusKind::Disconnected), |
| 231 | ("message_loss", StatusKind::MessageLoss), |
| 232 | ("error", StatusKind::Error), |
| 233 | ] { |
| 234 | let payload = format!(r#"{{"channel":"status","kind":"{name}","detail":"d"}}"#); |
| 235 | assert_eq!( |
| 236 | decode_payload(&payload).unwrap(), |
| 237 | RealtimeEvent::Status(StatusEvent { |
| 238 | kind, |
| 239 | detail: "d".into() |
| 240 | }) |
| 241 | ); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | #[test] |
| 246 | fn status_detail_is_optional() { |
| 247 | let RealtimeEvent::Status(status) = |
| 248 | decode_payload(r#"{"channel":"status","kind":"connected"}"#).unwrap() |
| 249 | else { |
| 250 | panic!("expected status") |
| 251 | }; |
| 252 | assert_eq!(status.detail, ""); |
| 253 | } |
| 254 | |
| 255 | #[test] |
| 256 | fn long_fields_are_cut() { |
| 257 | let payload = format!( |
| 258 | r#"{{"channel":"status","kind":"error","detail":"{}"}}"#, |
| 259 | "x".repeat(1000) |
| 260 | ); |
| 261 | let RealtimeEvent::Status(status) = decode_payload(&payload).unwrap() else { |
| 262 | panic!("expected status") |
| 263 | }; |
| 264 | assert_eq!(status.detail.chars().count(), MAX_FIELD_LENGTH); |
| 265 | } |
| 266 | |
| 267 | #[test] |
| 268 | fn decodes_presence_and_skips_foreign_mris() { |
| 269 | let payload = r#"{"channel":"presence","entries":[ |
| 270 | {"mri":"8:orgid:abc","availability":"Busy","activity":"InACall"}, |
| 271 | {"mri":"8:orgid:def","availability":"Away","activity":""}, |
| 272 | {"mri":"4:+4912345","availability":"Offline"}]}"#; |
| 273 | let RealtimeEvent::Presence(updates) = decode_payload(payload).unwrap() else { |
| 274 | panic!("expected presence") |
| 275 | }; |
| 276 | assert_eq!( |
| 277 | updates, |
| 278 | vec![ |
| 279 | PresenceUpdate { |
| 280 | user_id: "abc".into(), |
| 281 | availability: "Busy".into(), |
| 282 | activity: Some("InACall".into()), |
| 283 | }, |
| 284 | PresenceUpdate { |
| 285 | user_id: "def".into(), |
| 286 | availability: "Away".into(), |
| 287 | activity: None, |
| 288 | }, |
| 289 | ] |
| 290 | ); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn decodes_endpoint_on_a_trouter_host() { |
| 295 | let payload = r#"{"channel":"endpoint","endpointId":"e1", |
| 296 | "trouterUri":"https://pub-ent-sece-04-f.trouter.teams.microsoft.com:3443/v4/f/x/unifiedPresenceService"}"#; |
| 297 | let RealtimeEvent::Endpoint(endpoint) = decode_payload(payload).unwrap() else { |
| 298 | panic!("expected endpoint") |
| 299 | }; |
| 300 | assert_eq!(endpoint.endpoint_id, "e1"); |
| 301 | assert!(endpoint.trouter_uri.ends_with("/unifiedPresenceService")); |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn rejects_endpoints_off_trouter_or_without_https() { |
| 306 | for uri in [ |
| 307 | "https://evil.example/unifiedPresenceService", |
| 308 | "http://go-eu.trouter.teams.microsoft.com/x", |
| 309 | "https://go-eu.trouter.teams.microsoft.com.evil.com/x", |
| 310 | "https://a@go-eu.trouter.teams.microsoft.com/x", |
| 311 | "https://go-eu.trouter.teams.microsoft.com:x/x", |
| 312 | "go-eu.trouter.teams.microsoft.com/x", |
| 313 | ] { |
| 314 | let payload = |
| 315 | format!(r#"{{"channel":"endpoint","endpointId":"e1","trouterUri":"{uri}"}}"#); |
| 316 | assert!(decode_payload(&payload).is_err(), "{uri}"); |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | #[test] |
| 321 | fn rejects_garbage() { |
| 322 | assert!(decode_payload("not json").is_err()); |
| 323 | assert!(decode_payload(r#"{"channel":"other"}"#).is_err()); |
| 324 | assert!(decode_payload(r#"{"channel":"status","kind":"weird"}"#).is_err()); |
| 325 | assert!(decode_payload(r#"{"channel":"event","resourceType":"x","eventKind":"typing","receivedAt":9223372036854775807}"#).is_err()); |
| 326 | } |
| 327 | } |