| 1 | use base64::Engine as _; |
| 2 | use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; |
| 3 | use serde_json::{Value, json}; |
| 4 | use session::trusted_url::{HostRule, trusted_https_url}; |
| 5 | use session::{Method, Request}; |
| 6 | use url::Url; |
| 7 | |
| 8 | use crate::error::{Error, Result}; |
| 9 | use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success}; |
| 10 | |
| 11 | const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url"; |
| 12 | pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com"; |
| 13 | const LIST_VIEW: &str = "msnp24Equivalent"; |
| 14 | const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/"; |
| 15 | const HOSTED_URL_KEY: &str = ",url="; |
| 16 | const LINK_PROXY_HOSTS: [HostRule; 1] = [HostRule::Domain("asyncgw.teams.microsoft.com")]; |
| 17 | const AMS_HOSTS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")]; |
| 18 | const AMS_OBJECT_HOSTS: [HostRule; 2] = [AMS_HOSTS[0], LINK_PROXY_HOSTS[0]]; |
| 19 | const OBJECTS_PATH: &str = "/v1/objects/"; |
| 20 | const VIEWS_SEGMENT: &str = "/views/"; |
| 21 | const FULL_SIZE_VIEW_PREFIX: &str = "imgpsh_fullsize"; |
| 22 | /// The view Teams opens in its image viewer; `_anim` keeps animated GIFs moving. |
| 23 | const FULL_SIZE_VIEW: &str = "imgpsh_fullsize_anim"; |
| 24 | |
| 25 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 26 | pub struct MessageLinks { |
| 27 | pub message_id: String, |
| 28 | pub links_json: String, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 32 | pub struct LinkInfo { |
| 33 | pub url: String, |
| 34 | pub title: Option<String>, |
| 35 | pub description: Option<String>, |
| 36 | pub site: Option<String>, |
| 37 | pub thumbnail: Option<String>, |
| 38 | pub thumbnail_width: Option<u32>, |
| 39 | pub thumbnail_height: Option<u32>, |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 43 | pub struct LinkImage { |
| 44 | pub bytes: Vec<u8>, |
| 45 | pub content_type: String, |
| 46 | } |
| 47 | |
| 48 | pub fn is_link_image_url(url: &str) -> bool { |
| 49 | trusted_https_url(url, &LINK_PROXY_HOSTS).is_some() |
| 50 | } |
| 51 | |
| 52 | /// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`. |
| 53 | pub fn hosted_content_image_url(graph_url: &str) -> Option<String> { |
| 54 | let (_, url) = hosted_content_fields(graph_url)?; |
| 55 | (is_link_image_url(&url) || is_ams_image_url(&url)) |
| 56 | .then(|| Url::parse(&url).ok()) |
| 57 | .flatten() |
| 58 | .map(String::from) |
| 59 | } |
| 60 | |
| 61 | /// The `id=` value from a Graph `hostedContents` link, used when `url=` is empty |
| 62 | /// (custom emoji reactions). |
| 63 | pub fn hosted_content_object_id(graph_url: &str) -> Option<String> { |
| 64 | let (id, url) = hosted_content_fields(graph_url)?; |
| 65 | if is_ams_object_id(&id) { |
| 66 | return Some(id); |
| 67 | } |
| 68 | object_id_from_ams_path(&url).map(str::to_owned) |
| 69 | } |
| 70 | |
| 71 | fn hosted_content_fields(graph_url: &str) -> Option<(String, String)> { |
| 72 | let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?; |
| 73 | let encoded = after.split('/').next()?; |
| 74 | let bytes = STANDARD |
| 75 | .decode(encoded) |
| 76 | .or_else(|_| URL_SAFE_NO_PAD.decode(encoded)) |
| 77 | .ok()?; |
| 78 | let decoded = String::from_utf8(bytes).ok()?; |
| 79 | let id = decoded |
| 80 | .strip_prefix("id=")? |
| 81 | .split(',') |
| 82 | .next() |
| 83 | .filter(|id| !id.is_empty())? |
| 84 | .to_owned(); |
| 85 | let url = decoded |
| 86 | .split_once(HOSTED_URL_KEY) |
| 87 | .map(|(_, url)| url.to_owned()) |
| 88 | .unwrap_or_default(); |
| 89 | Some((id, url)) |
| 90 | } |
| 91 | |
| 92 | pub(crate) fn is_ams_object_id(object_id: &str) -> bool { |
| 93 | !object_id.is_empty() |
| 94 | && object_id.contains('-') |
| 95 | && object_id |
| 96 | .chars() |
| 97 | .all(|character| character.is_ascii_alphanumeric() || character == '-') |
| 98 | } |
| 99 | |
| 100 | pub(crate) fn object_id_from_ams_path(url: &str) -> Option<&str> { |
| 101 | let path = url.split_once("/v1/objects/")?.1; |
| 102 | let id = path.split(['/', '?', '#']).next()?; |
| 103 | is_ams_object_id(id).then_some(id) |
| 104 | } |
| 105 | |
| 106 | /// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages. |
| 107 | pub fn is_ams_image_url(url: &str) -> bool { |
| 108 | trusted_ams_image_url(url).is_some() |
| 109 | } |
| 110 | |
| 111 | pub fn trusted_ams_image_url(url: &str) -> Option<Url> { |
| 112 | trusted_https_url(url, &AMS_HOSTS).filter(|parsed| parsed.path().starts_with(OBJECTS_PATH)) |
| 113 | } |
| 114 | |
| 115 | /// The full-resolution view of the AMS image at `url` (a plain AMS view or a Graph `hostedContents` link to one). |
| 116 | /// Messages carry the compressed `imgo` view; Teams swaps to this view when the image is opened. |
| 117 | /// `None` for other images, video clips and thumbnails, and views that already are full size. |
| 118 | pub fn ams_full_size_url(url: &str) -> Option<String> { |
| 119 | let decoded = hosted_content_image_url(url); |
| 120 | let url = decoded.as_deref().unwrap_or(url); |
| 121 | let parsed = trusted_https_url(url, &AMS_OBJECT_HOSTS) |
| 122 | .filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))?; |
| 123 | let (object, view) = parsed.as_str().rsplit_once(VIEWS_SEGMENT)?; |
| 124 | let still_picture = view.starts_with("img") && !view.contains(['/', '?', '#']); |
| 125 | (still_picture && !view.starts_with(FULL_SIZE_VIEW_PREFIX)) |
| 126 | .then(|| format!("{object}{VIEWS_SEGMENT}{FULL_SIZE_VIEW}")) |
| 127 | } |
| 128 | |
| 129 | pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> { |
| 130 | body.get("messages") |
| 131 | .and_then(Value::as_array) |
| 132 | .into_iter() |
| 133 | .flatten() |
| 134 | .filter_map(|message| { |
| 135 | let message_id = message.get("id")?.as_str()?.to_owned(); |
| 136 | let links_json = match message.pointer("/properties/links")? { |
| 137 | Value::String(text) => text.clone(), |
| 138 | array @ Value::Array(_) => array.to_string(), |
| 139 | _ => return None, |
| 140 | }; |
| 141 | Some(MessageLinks { |
| 142 | message_id, |
| 143 | links_json, |
| 144 | }) |
| 145 | }) |
| 146 | .collect() |
| 147 | } |
| 148 | |
| 149 | pub fn parse_link_info(body: &Value) -> LinkInfo { |
| 150 | let text = |key: &str| { |
| 151 | body.get(key) |
| 152 | .and_then(Value::as_str) |
| 153 | .map(str::trim) |
| 154 | .filter(|value| !value.is_empty()) |
| 155 | .map(str::to_owned) |
| 156 | }; |
| 157 | let size = |key: &str| { |
| 158 | body.pointer(&format!("/thumbnail_meta/{key}")) |
| 159 | .and_then(Value::as_u64) |
| 160 | .and_then(|value| u32::try_from(value).ok()) |
| 161 | .filter(|value| *value > 0) |
| 162 | }; |
| 163 | LinkInfo { |
| 164 | url: text("target_url") |
| 165 | .or_else(|| text("url")) |
| 166 | .unwrap_or_default(), |
| 167 | title: text("title"), |
| 168 | description: text("description"), |
| 169 | site: text("site"), |
| 170 | thumbnail: text("thumbnail"), |
| 171 | thumbnail_width: size("width"), |
| 172 | thumbnail_height: size("height"), |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | impl<T: MessageTransport> Messages<T> { |
| 177 | pub async fn list_message_links( |
| 178 | &self, |
| 179 | conversation: &ConversationRef, |
| 180 | page_size: usize, |
| 181 | ) -> Result<Vec<MessageLinks>> { |
| 182 | let url = format!( |
| 183 | "{}/{}/messages?view={LIST_VIEW}&pageSize={page_size}", |
| 184 | self.base_url, |
| 185 | encode(&conversation.conversation_id()) |
| 186 | ); |
| 187 | let answer = self.transport.send(Request::get(&url)).await?; |
| 188 | ensure_success(&answer)?; |
| 189 | Ok(parse_message_links(&answer.body)) |
| 190 | } |
| 191 | |
| 192 | pub async fn set_links( |
| 193 | &self, |
| 194 | conversation: &ConversationRef, |
| 195 | message_id: &str, |
| 196 | links_json: &str, |
| 197 | ) -> Result<()> { |
| 198 | let url = format!( |
| 199 | "{}/properties?name=links", |
| 200 | self.message_url(conversation, message_id) |
| 201 | ); |
| 202 | let body = json!({"links": links_json}); |
| 203 | let answer = self |
| 204 | .transport |
| 205 | .send(Request::with_body(Method::Put, url, body)) |
| 206 | .await?; |
| 207 | ensure_success(&answer) |
| 208 | } |
| 209 | |
| 210 | pub async fn link_info(&self, url: &str) -> Result<LinkInfo> { |
| 211 | let request_url = format!("{URLP_BASE}/info?url={}", encode(url)); |
| 212 | let answer = self.transport.send(Request::get(&request_url)).await?; |
| 213 | ensure_success(&answer)?; |
| 214 | Ok(parse_link_info(&answer.body)) |
| 215 | } |
| 216 | |
| 217 | pub async fn link_image(&self, url: &str) -> Result<LinkImage> { |
| 218 | let Some(url) = trusted_https_url(url, &LINK_PROXY_HOSTS) else { |
| 219 | return Err(Error::UnexpectedAnswer(format!( |
| 220 | "not a link preview image url: {url}" |
| 221 | ))); |
| 222 | }; |
| 223 | let answer = self |
| 224 | .transport |
| 225 | .send(Request::binary_get(url.as_str())) |
| 226 | .await?; |
| 227 | ensure_success(&answer)?; |
| 228 | decoded_image(&answer.body) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /// An image answer shaped `{base64, contentType}`. |
| 233 | pub(crate) fn decoded_image(body: &Value) -> Result<LinkImage> { |
| 234 | let encoded = body |
| 235 | .get("base64") |
| 236 | .and_then(Value::as_str) |
| 237 | .unwrap_or_default(); |
| 238 | let bytes = STANDARD |
| 239 | .decode(encoded.as_bytes()) |
| 240 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 241 | let content_type = body |
| 242 | .get("contentType") |
| 243 | .and_then(Value::as_str) |
| 244 | .unwrap_or_default() |
| 245 | .to_owned(); |
| 246 | Ok(LinkImage { |
| 247 | bytes, |
| 248 | content_type, |
| 249 | }) |
| 250 | } |
| 251 | |
| 252 | #[cfg(test)] |
| 253 | mod tests { |
| 254 | use super::*; |
| 255 | |
| 256 | #[test] |
| 257 | fn hosted_content_ids_carry_the_ams_url() { |
| 258 | let ams = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d1-abc/views/imgo"; |
| 259 | let id = STANDARD.encode(format!("id=x_0-weu-d1-abc,type=1,url={ams}")); |
| 260 | let graph = format!( |
| 261 | "https://graph.microsoft.com/v1.0/chats/19:a/messages/1/hostedContents/{id}/$value" |
| 262 | ); |
| 263 | assert_eq!(hosted_content_image_url(&graph).as_deref(), Some(ams)); |
| 264 | let foreign = STANDARD.encode("id=x,type=1,url=https://evil.example/a"); |
| 265 | assert_eq!( |
| 266 | hosted_content_image_url(&format!( |
| 267 | "https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/{foreign}/$value" |
| 268 | )), |
| 269 | None |
| 270 | ); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn custom_emoji_hosted_content_ids_carry_the_object_id_when_url_is_empty() { |
| 275 | let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"; |
| 276 | let id = STANDARD.encode(format!("id={object_id},type=1,url=")); |
| 277 | let graph = format!( |
| 278 | "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value" |
| 279 | ); |
| 280 | assert_eq!(hosted_content_image_url(&graph), None); |
| 281 | assert_eq!(hosted_content_object_id(&graph).as_deref(), Some(object_id)); |
| 282 | assert_eq!( |
| 283 | hosted_content_object_id("https://example.com/not-hosted"), |
| 284 | None |
| 285 | ); |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn ams_object_views_are_recognized_inside_hosted_content_ids() { |
| 290 | let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo"; |
| 291 | assert!(is_ams_image_url(ams)); |
| 292 | let id = STANDARD.encode(format!("id=x_0-frca-d14-abc,type=1,url={ams}")); |
| 293 | assert_eq!( |
| 294 | hosted_content_image_url(&format!( |
| 295 | "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value" |
| 296 | )) |
| 297 | .as_deref(), |
| 298 | Some(ams) |
| 299 | ); |
| 300 | assert!(!is_ams_image_url( |
| 301 | "https://evil.example/v1/objects/a/views/imgo" |
| 302 | )); |
| 303 | assert!(!is_ams_image_url( |
| 304 | "https://eu-api.asm.skype.com/v1/users/me" |
| 305 | )); |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn an_inline_ams_image_opens_in_its_full_size_view() { |
| 310 | assert_eq!( |
| 311 | ams_full_size_url("https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo") |
| 312 | .as_deref(), |
| 313 | Some("https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgpsh_fullsize_anim") |
| 314 | ); |
| 315 | assert_eq!( |
| 316 | ams_full_size_url( |
| 317 | "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d4-abc/views/imgo" |
| 318 | ) |
| 319 | .as_deref(), |
| 320 | Some( |
| 321 | "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d4-abc/views/imgpsh_fullsize_anim" |
| 322 | ) |
| 323 | ); |
| 324 | let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo"; |
| 325 | let id = STANDARD.encode(format!("id=x_0-frca-d14-abc,type=1,url={ams}")); |
| 326 | assert_eq!( |
| 327 | ams_full_size_url(&format!( |
| 328 | "https://graph.microsoft.com/v1.0/chats/19:a/messages/1/hostedContents/{id}/$value" |
| 329 | )) |
| 330 | .as_deref(), |
| 331 | Some( |
| 332 | "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgpsh_fullsize_anim" |
| 333 | ) |
| 334 | ); |
| 335 | } |
| 336 | |
| 337 | #[test] |
| 338 | fn full_size_and_non_picture_views_have_no_separate_full_size() { |
| 339 | for url in [ |
| 340 | "https://eu-api.asm.skype.com/v1/objects/a/views/imgpsh_fullsize", |
| 341 | "https://eu-api.asm.skype.com/v1/objects/a/views/imgpsh_fullsize_anim", |
| 342 | "https://eu-api.asm.skype.com/v1/objects/a/views/video", |
| 343 | "https://eu-api.asm.skype.com/v1/objects/a/views/thumbnail", |
| 344 | "https://eu-api.asm.skype.com/v1/objects/a", |
| 345 | "https://evil.example/v1/objects/a/views/imgo", |
| 346 | "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=x/views/imgo", |
| 347 | "https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aGk=/$value", |
| 348 | ] { |
| 349 | assert_eq!(ams_full_size_url(url), None, "{url}"); |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn parses_link_info_with_target_url_and_thumbnail_size() { |
| 355 | let info = parse_link_info(&json!({ |
| 356 | "title": " Rust ", |
| 357 | "description": "", |
| 358 | "site": "GitHub", |
| 359 | "thumbnail": "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x", |
| 360 | "thumbnail_meta": {"height": 160, "width": 320}, |
| 361 | "url": "https://github.com/a", |
| 362 | "target_url": "https://github.com/rust-lang/rust", |
| 363 | })); |
| 364 | assert_eq!(info.url, "https://github.com/rust-lang/rust"); |
| 365 | assert_eq!(info.title.as_deref(), Some("Rust")); |
| 366 | assert_eq!(info.description, None); |
| 367 | assert_eq!(info.site.as_deref(), Some("GitHub")); |
| 368 | assert_eq!( |
| 369 | (info.thumbnail_width, info.thumbnail_height), |
| 370 | (Some(320), Some(160)) |
| 371 | ); |
| 372 | } |
| 373 | |
| 374 | #[test] |
| 375 | fn link_info_tolerates_missing_fields() { |
| 376 | let info = parse_link_info(&json!({"url": "https://a.example", "thumbnail_meta": null})); |
| 377 | assert_eq!(info.url, "https://a.example"); |
| 378 | assert_eq!(info.title, None); |
| 379 | assert_eq!(info.thumbnail, None); |
| 380 | assert_eq!(info.thumbnail_width, None); |
| 381 | } |
| 382 | |
| 383 | #[test] |
| 384 | fn reads_links_as_string_or_array_and_skips_messages_without() { |
| 385 | let links = parse_message_links(&json!({"messages": [ |
| 386 | {"id": "1", "properties": {"links": "[{\"url\":\"https://a\"}]"}}, |
| 387 | {"id": "2", "properties": {"links": [{"url": "https://b"}]}}, |
| 388 | {"id": "3", "properties": {}}, |
| 389 | {"id": "4"}, |
| 390 | {"properties": {"links": "[]"}}, |
| 391 | ]})); |
| 392 | assert_eq!( |
| 393 | links, |
| 394 | vec![ |
| 395 | MessageLinks { |
| 396 | message_id: "1".into(), |
| 397 | links_json: "[{\"url\":\"https://a\"}]".into() |
| 398 | }, |
| 399 | MessageLinks { |
| 400 | message_id: "2".into(), |
| 401 | links_json: "[{\"url\":\"https://b\"}]".into() |
| 402 | }, |
| 403 | ] |
| 404 | ); |
| 405 | } |
| 406 | |
| 407 | #[test] |
| 408 | fn only_asyncgw_hosts_receive_the_token() { |
| 409 | assert!(is_link_image_url( |
| 410 | "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x" |
| 411 | )); |
| 412 | assert!(!is_link_image_url( |
| 413 | "https://evil.example/?a=.asyncgw.teams.microsoft.com" |
| 414 | )); |
| 415 | assert!(!is_link_image_url( |
| 416 | "http://de-prod.asyncgw.teams.microsoft.com/x" |
| 417 | )); |
| 418 | for bypass in [ |
| 419 | "https://evil.example\\.asyncgw.teams.microsoft.com/x", |
| 420 | "https://de-prod.asyncgw.teams.microsoft.com:x@evil.example/", |
| 421 | ] { |
| 422 | assert!(!is_link_image_url(bypass), "{bypass}"); |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | #[test] |
| 427 | fn ams_checks_see_the_host_the_request_goes_to() { |
| 428 | for bypass in [ |
| 429 | "https://evil.example#.asm.skype.com/v1/objects/a", |
| 430 | "https://evil.example?.asm.skype.com/v1/objects/a", |
| 431 | "https://evil.example\\.asm.skype.com/v1/objects/a", |
| 432 | "https://eu-api.asm.skype.com@evil.example/v1/objects/a", |
| 433 | ] { |
| 434 | assert!(!is_ams_image_url(bypass), "{bypass}"); |
| 435 | assert_eq!(ams_full_size_url(&format!("{bypass}/views/imgo")), None); |
| 436 | } |
| 437 | } |
| 438 | } |