| 1 | use std::net::Ipv4Addr; |
| 2 | |
| 3 | use chatsvc::{LinkInfo, is_link_image_url}; |
| 4 | use scraper::{Html, Selector}; |
| 5 | use serde_json::{Value, json}; |
| 6 | use store::MessageRecord; |
| 7 | |
| 8 | use crate::stored::ImageRef; |
| 9 | |
| 10 | pub const EMPTY_LINKS: &str = "[]"; |
| 11 | |
| 12 | const HYPERLINK_TYPE: &str = "http://schema.skype.com/HyperLink"; |
| 13 | const INTERNAL_HOSTS: [&str; 8] = [ |
| 14 | "sharepoint.com", |
| 15 | "onedrive.com", |
| 16 | "1drv.ms", |
| 17 | "teams.microsoft.com", |
| 18 | "teams.cloud.microsoft", |
| 19 | "teams.live.com", |
| 20 | "office.com", |
| 21 | "microsoft365.com", |
| 22 | ]; |
| 23 | |
| 24 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 25 | pub struct LinkPreview { |
| 26 | pub url: String, |
| 27 | pub title: Option<String>, |
| 28 | pub description: Option<String>, |
| 29 | pub image_url: Option<String>, |
| 30 | pub image_width: Option<u32>, |
| 31 | pub image_height: Option<u32>, |
| 32 | } |
| 33 | |
| 34 | impl LinkPreview { |
| 35 | pub fn from_info(url: &str, info: &LinkInfo) -> Option<LinkPreview> { |
| 36 | let preview = LinkPreview { |
| 37 | url: url.to_owned(), |
| 38 | title: info.title.clone(), |
| 39 | description: info.description.clone(), |
| 40 | image_url: info |
| 41 | .thumbnail |
| 42 | .clone() |
| 43 | .filter(|thumbnail| is_link_image_url(thumbnail)), |
| 44 | image_width: info.thumbnail_width, |
| 45 | image_height: info.thumbnail_height, |
| 46 | }; |
| 47 | preview.is_showable().then_some(preview) |
| 48 | } |
| 49 | |
| 50 | pub fn domain(&self) -> String { |
| 51 | let host = link_host(&self.url).unwrap_or_default(); |
| 52 | host.strip_prefix("www.").unwrap_or(&host).to_owned() |
| 53 | } |
| 54 | |
| 55 | pub fn image(&self) -> Option<ImageRef> { |
| 56 | Some(ImageRef { |
| 57 | id: String::new(), |
| 58 | url: self.image_url.clone()?, |
| 59 | width: self.image_width, |
| 60 | height: self.image_height, |
| 61 | alt: None, |
| 62 | }) |
| 63 | } |
| 64 | |
| 65 | pub fn links_json(&self) -> String { |
| 66 | let mut preview = serde_json::Map::new(); |
| 67 | if let Some(image_url) = &self.image_url { |
| 68 | preview.insert("previewurl".into(), json!(image_url)); |
| 69 | } |
| 70 | if let Some((width, height)) = self.image_width.zip(self.image_height) { |
| 71 | preview.insert( |
| 72 | "previewmeta".into(), |
| 73 | json!({"height": height, "width": width}), |
| 74 | ); |
| 75 | } |
| 76 | if let Some(title) = &self.title { |
| 77 | preview.insert("title".into(), json!(title)); |
| 78 | } |
| 79 | if let Some(description) = &self.description { |
| 80 | preview.insert("description".into(), json!(description)); |
| 81 | } |
| 82 | json!([{ |
| 83 | "@type": HYPERLINK_TYPE, |
| 84 | "itemid": "0", |
| 85 | "url": self.url, |
| 86 | "preview": preview, |
| 87 | "previewenabled": true, |
| 88 | }]) |
| 89 | .to_string() |
| 90 | } |
| 91 | |
| 92 | fn is_showable(&self) -> bool { |
| 93 | self.title.is_some() || self.image_url.is_some() |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub fn has_links_markup(record: &MessageRecord) -> bool { |
| 98 | !record.deleted && record.body_html.contains("<a ") |
| 99 | } |
| 100 | |
| 101 | pub fn has_stored_links(links_json: &str) -> bool { |
| 102 | !matches!(links_json, "" | EMPTY_LINKS) |
| 103 | } |
| 104 | |
| 105 | pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> { |
| 106 | if record.deleted { |
| 107 | return None; |
| 108 | } |
| 109 | select_preview(&record.links_json) |
| 110 | } |
| 111 | |
| 112 | pub fn select_preview(links_json: &str) -> Option<LinkPreview> { |
| 113 | let entries: Vec<Value> = serde_json::from_str(links_json).ok()?; |
| 114 | entries.iter().find_map(entry_preview) |
| 115 | } |
| 116 | |
| 117 | fn entry_preview(entry: &Value) -> Option<LinkPreview> { |
| 118 | if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) { |
| 119 | return None; |
| 120 | } |
| 121 | let url = entry.get("url")?.as_str()?; |
| 122 | if !is_public_link(url) { |
| 123 | return None; |
| 124 | } |
| 125 | let preview = entry.get("preview").filter(|preview| preview.is_object())?; |
| 126 | let text = |key: &str| { |
| 127 | preview |
| 128 | .get(key) |
| 129 | .and_then(Value::as_str) |
| 130 | .map(str::trim) |
| 131 | .filter(|value| !value.is_empty()) |
| 132 | .map(str::to_owned) |
| 133 | }; |
| 134 | let meta = ["previewmeta", "previewMetadata"] |
| 135 | .into_iter() |
| 136 | .find_map(|key| preview.get(key).filter(|meta| meta.is_object())); |
| 137 | let size = |key: &str| { |
| 138 | meta.and_then(|meta| meta.get(key)) |
| 139 | .and_then(Value::as_u64) |
| 140 | .and_then(|value| u32::try_from(value).ok()) |
| 141 | .filter(|value| *value > 0) |
| 142 | }; |
| 143 | let candidate = LinkPreview { |
| 144 | url: url.to_owned(), |
| 145 | title: text("title"), |
| 146 | description: text("description"), |
| 147 | image_url: text("previewurl").filter(|image_url| is_link_image_url(image_url)), |
| 148 | image_width: size("width"), |
| 149 | image_height: size("height"), |
| 150 | }; |
| 151 | candidate.is_showable().then_some(candidate) |
| 152 | } |
| 153 | |
| 154 | pub fn first_public_link(html: &str) -> Option<String> { |
| 155 | let selector = Selector::parse("a[href]").ok()?; |
| 156 | Html::parse_fragment(html) |
| 157 | .select(&selector) |
| 158 | .filter_map(|anchor| anchor.value().attr("href")) |
| 159 | .find(|href| is_public_link(href)) |
| 160 | .map(str::to_owned) |
| 161 | } |
| 162 | |
| 163 | pub fn public_links(record: &MessageRecord) -> Vec<String> { |
| 164 | let Ok(selector) = Selector::parse("a[href]") else { |
| 165 | return Vec::new(); |
| 166 | }; |
| 167 | if record.deleted { |
| 168 | return Vec::new(); |
| 169 | } |
| 170 | let mut links: Vec<String> = Vec::new(); |
| 171 | for anchor in Html::parse_fragment(&record.body_html).select(&selector) { |
| 172 | let Some(href) = anchor |
| 173 | .value() |
| 174 | .attr("href") |
| 175 | .filter(|href| is_public_link(href)) |
| 176 | else { |
| 177 | continue; |
| 178 | }; |
| 179 | if !links.iter().any(|known| known == href) { |
| 180 | links.push(href.to_owned()); |
| 181 | } |
| 182 | } |
| 183 | links |
| 184 | } |
| 185 | |
| 186 | pub fn is_public_link(url: &str) -> bool { |
| 187 | let lower = url.to_ascii_lowercase(); |
| 188 | if !(lower.starts_with("http://") || lower.starts_with("https://")) { |
| 189 | return false; |
| 190 | } |
| 191 | let Some(host) = link_host(url) else { |
| 192 | return false; |
| 193 | }; |
| 194 | if host.starts_with('[') || host == "localhost" || !host.contains('.') { |
| 195 | return false; |
| 196 | } |
| 197 | if INTERNAL_HOSTS |
| 198 | .iter() |
| 199 | .any(|internal| host == *internal || host.ends_with(&format!(".{internal}"))) |
| 200 | { |
| 201 | return false; |
| 202 | } |
| 203 | host.parse::<Ipv4Addr>().map_or(true, |address| { |
| 204 | !(address.is_private() |
| 205 | || address.is_loopback() |
| 206 | || address.is_link_local() |
| 207 | || address.is_unspecified()) |
| 208 | }) |
| 209 | } |
| 210 | |
| 211 | fn link_host(url: &str) -> Option<String> { |
| 212 | let (_, rest) = url.split_once("://")?; |
| 213 | let authority = rest.split(['/', '?', '#']).next()?; |
| 214 | let host_port = authority |
| 215 | .rsplit_once('@') |
| 216 | .map_or(authority, |(_, host)| host); |
| 217 | let host = if host_port.starts_with('[') { |
| 218 | host_port |
| 219 | } else { |
| 220 | host_port.split(':').next()? |
| 221 | }; |
| 222 | let host = host.trim_end_matches('.').to_ascii_lowercase(); |
| 223 | (!host.is_empty()).then_some(host) |
| 224 | } |
| 225 | |
| 226 | #[cfg(test)] |
| 227 | mod tests { |
| 228 | use super::*; |
| 229 | |
| 230 | const THUMBNAIL: &str = |
| 231 | "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x"; |
| 232 | |
| 233 | fn links(entries: Value) -> String { |
| 234 | entries.to_string() |
| 235 | } |
| 236 | |
| 237 | #[test] |
| 238 | fn public_links_lists_each_external_link_once() { |
| 239 | let record = MessageRecord { |
| 240 | body_html: "<p><a href=\"https://a.example/x\">x</a> <a href=\"https://contoso.sharepoint.com/f\">f</a> <a href=\"https://a.example/x\">again</a> <a href=\"https://b.example\">b</a></p>".to_owned(), |
| 241 | ..demo_record() |
| 242 | }; |
| 243 | assert_eq!( |
| 244 | public_links(&record), |
| 245 | ["https://a.example/x", "https://b.example"] |
| 246 | ); |
| 247 | } |
| 248 | |
| 249 | fn demo_record() -> MessageRecord { |
| 250 | MessageRecord { |
| 251 | conversation_id: "c".to_owned(), |
| 252 | message_id: "m".to_owned(), |
| 253 | reply_to_id: None, |
| 254 | sender_id: None, |
| 255 | sender_name: None, |
| 256 | created_at: chrono::Utc::now(), |
| 257 | edited_at: None, |
| 258 | deleted: false, |
| 259 | body_html: String::new(), |
| 260 | attachments_json: "[]".to_owned(), |
| 261 | reactions_json: "[]".to_owned(), |
| 262 | mentions_json: "[]".to_owned(), |
| 263 | sender_application_id: None, |
| 264 | links_json: "[]".to_owned(), |
| 265 | subject: None, |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | #[test] |
| 270 | fn picks_the_first_public_link_with_a_title() { |
| 271 | let preview = select_preview(&links(json!([ |
| 272 | {"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true}, |
| 273 | {"url": "https://a.example/x", "preview": {}, "previewenabled": true}, |
| 274 | {"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}}, |
| 275 | {"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true}, |
| 276 | ]))) |
| 277 | .unwrap(); |
| 278 | assert_eq!(preview.url, "https://b.example/y"); |
| 279 | assert_eq!(preview.title.as_deref(), Some("B")); |
| 280 | assert_eq!(preview.description.as_deref(), Some("About B")); |
| 281 | assert_eq!(preview.domain(), "b.example"); |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn an_image_alone_is_enough() { |
| 286 | let preview = select_preview(&links(json!([ |
| 287 | {"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null}, |
| 288 | ]))) |
| 289 | .unwrap(); |
| 290 | assert_eq!(preview.title, None); |
| 291 | assert_eq!(preview.image_url.as_deref(), Some(THUMBNAIL)); |
| 292 | assert_eq!( |
| 293 | (preview.image_width, preview.image_height), |
| 294 | (Some(320), Some(160)) |
| 295 | ); |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn reads_the_camel_case_meta_and_null_meta() { |
| 300 | let preview = select_preview(&links(json!([ |
| 301 | {"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}}, |
| 302 | {"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}}, |
| 303 | ]))) |
| 304 | .unwrap(); |
| 305 | assert_eq!( |
| 306 | (preview.image_width, preview.image_height), |
| 307 | (Some(20), Some(10)) |
| 308 | ); |
| 309 | let second = select_preview(&links(json!([ |
| 310 | {"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}}, |
| 311 | ]))) |
| 312 | .unwrap(); |
| 313 | assert_eq!(second.image_width, None); |
| 314 | } |
| 315 | |
| 316 | #[test] |
| 317 | fn a_removed_preview_is_not_shown() { |
| 318 | assert_eq!( |
| 319 | select_preview(&links(json!([ |
| 320 | {"url": "https://a.example", "preview": {"title": "A"}, "previewenabled": false}, |
| 321 | ]))), |
| 322 | None |
| 323 | ); |
| 324 | } |
| 325 | |
| 326 | #[test] |
| 327 | fn images_outside_the_preview_service_are_dropped() { |
| 328 | assert_eq!( |
| 329 | select_preview(&links(json!([ |
| 330 | {"url": "https://a.example", "preview": {"previewurl": "https://evil.example/i.png"}}, |
| 331 | ]))), |
| 332 | None |
| 333 | ); |
| 334 | } |
| 335 | |
| 336 | #[test] |
| 337 | fn garbage_and_empty_lists_have_no_preview() { |
| 338 | assert_eq!(select_preview("[]"), None); |
| 339 | assert_eq!(select_preview(""), None); |
| 340 | assert_eq!(select_preview("{}"), None); |
| 341 | assert_eq!(select_preview("[{\"url\": 3}]"), None); |
| 342 | } |
| 343 | |
| 344 | #[test] |
| 345 | fn internal_and_private_hosts_are_skipped() { |
| 346 | for url in [ |
| 347 | "https://contoso.sharepoint.com/a", |
| 348 | "https://contoso-my.sharepoint.com/a", |
| 349 | "https://onedrive.com/a", |
| 350 | "https://1drv.ms/a", |
| 351 | "https://teams.microsoft.com/l/x", |
| 352 | "https://teams.cloud.microsoft/x", |
| 353 | "https://teams.live.com/x", |
| 354 | "https://www.office.com/x", |
| 355 | "https://m365.microsoft365.com/x", |
| 356 | "https://localhost/x", |
| 357 | "https://intranet/x", |
| 358 | "http://192.168.1.2/x", |
| 359 | "http://127.0.0.1:8080/x", |
| 360 | "ftp://a.example/x", |
| 361 | "mailto:a@b.example", |
| 362 | ] { |
| 363 | assert!(!is_public_link(url), "{url}"); |
| 364 | } |
| 365 | for url in [ |
| 366 | "https://github.com/rust-lang/rust", |
| 367 | "http://a.example:8080/x", |
| 368 | "https://notsharepoint.com/x", |
| 369 | "https://user@example.org/x", |
| 370 | ] { |
| 371 | assert!(is_public_link(url), "{url}"); |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | #[test] |
| 376 | fn finds_the_first_public_anchor_in_html() { |
| 377 | let html = "<p><a href=\"https://contoso.sharepoint.com/x\">f</a> \ |
| 378 | <a href=\"https://a.example/?q=1&r=2\">a</a> <a href=\"https://b.example\">b</a></p>"; |
| 379 | assert_eq!( |
| 380 | first_public_link(html).as_deref(), |
| 381 | Some("https://a.example/?q=1&r=2") |
| 382 | ); |
| 383 | assert_eq!(first_public_link("<p>no link</p>"), None); |
| 384 | } |
| 385 | |
| 386 | #[test] |
| 387 | fn outgoing_json_reads_back_as_the_same_preview() { |
| 388 | let preview = LinkPreview { |
| 389 | url: "https://github.com/rust-lang/rust".into(), |
| 390 | title: Some("Rust".into()), |
| 391 | description: Some("Empowering".into()), |
| 392 | image_url: Some(THUMBNAIL.into()), |
| 393 | image_width: Some(320), |
| 394 | image_height: Some(160), |
| 395 | }; |
| 396 | let json: Value = serde_json::from_str(&preview.links_json()).unwrap(); |
| 397 | assert_eq!(json[0]["@type"], HYPERLINK_TYPE); |
| 398 | assert_eq!(json[0]["itemid"], "0"); |
| 399 | assert_eq!(json[0]["previewenabled"], true); |
| 400 | assert_eq!(json[0]["preview"]["previewurl"], THUMBNAIL); |
| 401 | assert_eq!(select_preview(&preview.links_json()), Some(preview)); |
| 402 | } |
| 403 | |
| 404 | #[test] |
| 405 | fn info_without_title_or_usable_image_makes_no_preview() { |
| 406 | let info = LinkInfo { |
| 407 | url: "https://a.example".into(), |
| 408 | description: Some("only text".into()), |
| 409 | thumbnail: Some("https://evil.example/i.png".into()), |
| 410 | ..LinkInfo::default() |
| 411 | }; |
| 412 | assert_eq!(LinkPreview::from_info("https://a.example", &info), None); |
| 413 | } |
| 414 | |
| 415 | #[test] |
| 416 | fn deleted_messages_show_no_preview() { |
| 417 | let record = MessageRecord { |
| 418 | deleted: true, |
| 419 | links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])), |
| 420 | ..MessageRecord::default() |
| 421 | }; |
| 422 | assert_eq!(link_preview(&record), None); |
| 423 | } |
| 424 | } |