BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / links.rs

links.rs

links.rs 18.5 KiB Download Raw
1use std::net::Ipv4Addr;
2
3use chatsvc::{LinkInfo, is_link_image_url};
4use scraper::{Html, Selector};
5use serde_json::{Value, json};
6use store::MessageRecord;
7
8use crate::stored::{AttachmentInfo, ImageRef, attachments};
9
10pub const EMPTY_LINKS: &str = "[]";
11
12const HYPERLINK_TYPE: &str = "http://schema.skype.com/HyperLink";
13const 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)]
25pub 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
34impl 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 let parts = [
94 self.image_url.is_some(),
95 self.title.is_some(),
96 self.description.is_some(),
97 ];
98 parts.into_iter().filter(|present| *present).count() >= 2
99 }
100}
101
102pub fn has_links_markup(record: &MessageRecord) -> bool {
103 !record.deleted && record.body_html.contains("<a ")
104}
105
106pub fn has_stored_links(links_json: &str) -> bool {
107 !matches!(links_json, "" | EMPTY_LINKS)
108}
109
110pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {
111 if record.deleted || has_link_unfurl_card(record) {
112 return None;
113 }
114 let first_link = first_link(&record.body_html)?;
115 select_preview(&record.links_json).filter(|preview| same_link(&preview.url, &first_link))
116}
117
118pub fn select_preview(links_json: &str) -> Option<LinkPreview> {
119 let entries: Vec<Value> = serde_json::from_str(links_json).ok()?;
120 entries.iter().find_map(entry_preview)
121}
122
123fn has_link_unfurl_card(record: &MessageRecord) -> bool {
124 attachments(record)
125 .iter()
126 .any(AttachmentInfo::is_link_unfurl_card)
127}
128
129fn first_link(html: &str) -> Option<String> {
130 let selector = Selector::parse("a[href]").ok()?;
131 Html::parse_fragment(html)
132 .select(&selector)
133 .find_map(|anchor| anchor.value().attr("href"))
134 .map(str::to_owned)
135}
136
137fn same_link(first: &str, second: &str) -> bool {
138 let normalize = |url: &str| url.trim().trim_end_matches('/').to_ascii_lowercase();
139 normalize(first) == normalize(second)
140}
141
142fn entry_preview(entry: &Value) -> Option<LinkPreview> {
143 if entry.get("previewenabled").and_then(Value::as_bool) != Some(true) {
144 return None;
145 }
146 let url = entry.get("url")?.as_str()?;
147 if !is_public_link(url) {
148 return None;
149 }
150 let preview = entry.get("preview").filter(|preview| preview.is_object())?;
151 let text = |key: &str| {
152 preview
153 .get(key)
154 .and_then(Value::as_str)
155 .map(str::trim)
156 .filter(|value| !value.is_empty())
157 .map(str::to_owned)
158 };
159 let meta = ["previewmeta", "previewMetadata"]
160 .into_iter()
161 .find_map(|key| preview.get(key).filter(|meta| meta.is_object()));
162 let size = |key: &str| {
163 meta.and_then(|meta| meta.get(key))
164 .and_then(Value::as_u64)
165 .and_then(|value| u32::try_from(value).ok())
166 .filter(|value| *value > 0)
167 };
168 let candidate = LinkPreview {
169 url: url.to_owned(),
170 title: text("title"),
171 description: text("description"),
172 image_url: text("previewurl").filter(|image_url| is_link_image_url(image_url)),
173 image_width: size("width"),
174 image_height: size("height"),
175 };
176 candidate.is_showable().then_some(candidate)
177}
178
179pub fn first_public_link(html: &str) -> Option<String> {
180 let selector = Selector::parse("a[href]").ok()?;
181 Html::parse_fragment(html)
182 .select(&selector)
183 .filter_map(|anchor| anchor.value().attr("href"))
184 .find(|href| is_public_link(href))
185 .map(str::to_owned)
186}
187
188pub fn public_links(record: &MessageRecord) -> Vec<String> {
189 let Ok(selector) = Selector::parse("a[href]") else {
190 return Vec::new();
191 };
192 if record.deleted {
193 return Vec::new();
194 }
195 let mut links: Vec<String> = Vec::new();
196 for anchor in Html::parse_fragment(&record.body_html).select(&selector) {
197 let Some(href) = anchor
198 .value()
199 .attr("href")
200 .filter(|href| is_public_link(href))
201 else {
202 continue;
203 };
204 if !links.iter().any(|known| known == href) {
205 links.push(href.to_owned());
206 }
207 }
208 links
209}
210
211pub fn is_public_link(url: &str) -> bool {
212 let lower = url.to_ascii_lowercase();
213 if !(lower.starts_with("http://") || lower.starts_with("https://")) {
214 return false;
215 }
216 let Some(host) = link_host(url) else {
217 return false;
218 };
219 if host.starts_with('[') || host == "localhost" || !host.contains('.') {
220 return false;
221 }
222 if INTERNAL_HOSTS
223 .iter()
224 .any(|internal| host == *internal || host.ends_with(&format!(".{internal}")))
225 {
226 return false;
227 }
228 host.parse::<Ipv4Addr>().map_or(true, |address| {
229 !(address.is_private()
230 || address.is_loopback()
231 || address.is_link_local()
232 || address.is_unspecified())
233 })
234}
235
236fn link_host(url: &str) -> Option<String> {
237 let (_, rest) = url.split_once("://")?;
238 let authority = rest.split(['/', '?', '#']).next()?;
239 let host_port = authority
240 .rsplit_once('@')
241 .map_or(authority, |(_, host)| host);
242 let host = if host_port.starts_with('[') {
243 host_port
244 } else {
245 host_port.split(':').next()?
246 };
247 let host = host.trim_end_matches('.').to_ascii_lowercase();
248 (!host.is_empty()).then_some(host)
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 const THUMBNAIL: &str =
256 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x";
257
258 fn links(entries: Value) -> String {
259 entries.to_string()
260 }
261
262 #[test]
263 fn public_links_lists_each_external_link_once() {
264 let record = MessageRecord {
265 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(),
266 ..demo_record()
267 };
268 assert_eq!(
269 public_links(&record),
270 ["https://a.example/x", "https://b.example"]
271 );
272 }
273
274 fn demo_record() -> MessageRecord {
275 MessageRecord {
276 conversation_id: "c".to_owned(),
277 message_id: "m".to_owned(),
278 reply_to_id: None,
279 sender_id: None,
280 sender_name: None,
281 created_at: chrono::Utc::now(),
282 edited_at: None,
283 deleted: false,
284 body_html: String::new(),
285 attachments_json: "[]".to_owned(),
286 reactions_json: "[]".to_owned(),
287 mentions_json: "[]".to_owned(),
288 sender_application_id: None,
289 links_json: "[]".to_owned(),
290 subject: None,
291 call_event_json: None,
292 }
293 }
294
295 #[test]
296 fn picks_the_first_enabled_public_link_with_two_parts() {
297 let preview = select_preview(&links(json!([
298 {"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File", "description": "F"}, "previewenabled": true},
299 {"url": "https://a.example/x", "preview": {}, "previewenabled": true},
300 {"url": "https://n.example/x", "preview": {"title": "N", "description": "No flag"}},
301 {"url": "https://t.example/x", "preview": {"title": "Title only"}, "previewenabled": true},
302 {"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}, "previewenabled": true},
303 ])))
304 .unwrap();
305 assert_eq!(preview.url, "https://b.example/y");
306 assert_eq!(preview.title.as_deref(), Some("B"));
307 assert_eq!(preview.description.as_deref(), Some("About B"));
308 assert_eq!(preview.domain(), "b.example");
309 }
310
311 #[test]
312 fn an_image_needs_a_title_or_description() {
313 assert_eq!(
314 select_preview(&links(json!([
315 {"url": "https://a.example", "preview": {"previewurl": THUMBNAIL}, "previewenabled": true},
316 ]))),
317 None
318 );
319 let preview = select_preview(&links(json!([
320 {"url": "https://a.example", "preview": {"description": "D", "previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": true},
321 ])))
322 .unwrap();
323 assert_eq!(preview.title, None);
324 assert_eq!(preview.image_url.as_deref(), Some(THUMBNAIL));
325 assert_eq!(
326 (preview.image_width, preview.image_height),
327 (Some(320), Some(160))
328 );
329 }
330
331 #[test]
332 fn reads_the_camel_case_meta_and_null_meta() {
333 let preview = select_preview(&links(json!([
334 {"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}, "previewenabled": true},
335 ])))
336 .unwrap();
337 assert_eq!(
338 (preview.image_width, preview.image_height),
339 (Some(20), Some(10))
340 );
341 let second = select_preview(&links(json!([
342 {"url": "https://b.example", "preview": {"title": "B", "description": "D", "previewmeta": null}, "previewenabled": true},
343 ])))
344 .unwrap();
345 assert_eq!(second.image_width, None);
346 }
347
348 fn linked_record(body_html: &str, links_json: Value, attachments_json: Value) -> MessageRecord {
349 MessageRecord {
350 body_html: body_html.to_owned(),
351 links_json: links(links_json),
352 attachments_json: attachments_json.to_string(),
353 ..demo_record()
354 }
355 }
356
357 fn video_link_entry(previewenabled: Value) -> Value {
358 json!([{
359 "@type": HYPERLINK_TYPE,
360 "itemid": "0",
361 "url": "https://www.youtube.com/watch?v=video_id_01",
362 "preview": {"title": "Sample video", "description": "1K views", "previewurl": THUMBNAIL},
363 "previewenabled": previewenabled,
364 }])
365 }
366
367 fn unfurl_card(id: &str, teams_app_id: Option<&str>) -> Value {
368 let content = json!({
369 "type": "AdaptiveCard",
370 "version": "1.5",
371 "body": [
372 {"type": "Media", "sources": [{"mimeType": "video/mp4", "url": "https://www.youtube.com/watch?v=video_id_01"}]},
373 {"type": "TextBlock", "text": "Sample video"},
374 {"type": "TextBlock", "text": "Sample channel"},
375 ],
376 "actions": [{"type": "Action.OpenUrl", "title": "Open", "url": "https://www.youtube.com/watch?v=video_id_01"}],
377 });
378 json!([{
379 "content_type": "application/vnd.microsoft.card.adaptive",
380 "name": null,
381 "url": null,
382 "text": null,
383 "id": id,
384 "content": content.to_string(),
385 "teams_app_id": teams_app_id,
386 }])
387 }
388
389 const VIDEO_BODY: &str = "<p><a href=\"https://www.youtube.com/watch?v=video_id_01\">https://www.youtube.com/watch?v=video_id_01</a></p>";
390
391 #[test]
392 fn a_video_link_with_its_unfurl_card_shows_only_the_card() {
393 let teams_sent = linked_record(
394 VIDEO_BODY,
395 video_link_entry(json!(false)),
396 unfurl_card("app-preview-card-1", None),
397 );
398 assert_eq!(link_preview(&teams_sent), None);
399 let flagged_on = linked_record(
400 VIDEO_BODY,
401 video_link_entry(json!(true)),
402 unfurl_card(
403 "74d20c7f34aa4a7f",
404 Some("4623dd0c-d55c-4c95-9290-ad31619b577a"),
405 ),
406 );
407 assert_eq!(link_preview(&flagged_on), None);
408 let by_card_id = linked_record(
409 VIDEO_BODY,
410 video_link_entry(json!(true)),
411 unfurl_card("app-preview-card-2", None),
412 );
413 assert_eq!(link_preview(&by_card_id), None);
414 let cards = crate::stored::adaptive_cards(&flagged_on);
415 assert_eq!(cards.len(), 1);
416 }
417
418 #[test]
419 fn a_video_link_without_a_card_keeps_its_preview() {
420 let record = linked_record(VIDEO_BODY, video_link_entry(json!(true)), json!([]));
421 let preview = link_preview(&record).unwrap();
422 assert_eq!(preview.domain(), "youtube.com");
423 let missing_flag = linked_record(VIDEO_BODY, video_link_entry(Value::Null), json!([]));
424 assert_eq!(link_preview(&missing_flag), None);
425 }
426
427 #[test]
428 fn only_the_first_link_of_the_message_gets_a_preview() {
429 let body = "<p><a href=\"https://other.example/\">other</a> <a href=\"https://www.youtube.com/watch?v=video_id_01\">video</a></p>";
430 let record = linked_record(body, video_link_entry(json!(true)), json!([]));
431 assert_eq!(link_preview(&record), None);
432 assert!(same_link("https://A.example/x/", "https://a.example/x"));
433 }
434
435 #[test]
436 fn a_removed_preview_is_not_shown() {
437 assert_eq!(
438 select_preview(&links(json!([
439 {"url": "https://a.example", "preview": {"title": "A"}, "previewenabled": false},
440 ]))),
441 None
442 );
443 }
444
445 #[test]
446 fn images_outside_the_preview_service_are_dropped() {
447 assert_eq!(
448 select_preview(&links(json!([
449 {"url": "https://a.example", "preview": {"previewurl": "https://evil.example/i.png"}},
450 ]))),
451 None
452 );
453 }
454
455 #[test]
456 fn garbage_and_empty_lists_have_no_preview() {
457 assert_eq!(select_preview("[]"), None);
458 assert_eq!(select_preview(""), None);
459 assert_eq!(select_preview("{}"), None);
460 assert_eq!(select_preview("[{\"url\": 3}]"), None);
461 }
462
463 #[test]
464 fn internal_and_private_hosts_are_skipped() {
465 for url in [
466 "https://contoso.sharepoint.com/a",
467 "https://contoso-my.sharepoint.com/a",
468 "https://onedrive.com/a",
469 "https://1drv.ms/a",
470 "https://teams.microsoft.com/l/x",
471 "https://teams.cloud.microsoft/x",
472 "https://teams.live.com/x",
473 "https://www.office.com/x",
474 "https://m365.microsoft365.com/x",
475 "https://localhost/x",
476 "https://intranet/x",
477 "http://192.168.1.2/x",
478 "http://127.0.0.1:8080/x",
479 "ftp://a.example/x",
480 "mailto:a@b.example",
481 ] {
482 assert!(!is_public_link(url), "{url}");
483 }
484 for url in [
485 "https://github.com/rust-lang/rust",
486 "http://a.example:8080/x",
487 "https://notsharepoint.com/x",
488 "https://user@example.org/x",
489 ] {
490 assert!(is_public_link(url), "{url}");
491 }
492 }
493
494 #[test]
495 fn finds_the_first_public_anchor_in_html() {
496 let html = "<p><a href=\"https://contoso.sharepoint.com/x\">f</a> \
497 <a href=\"https://a.example/?q=1&amp;r=2\">a</a> <a href=\"https://b.example\">b</a></p>";
498 assert_eq!(
499 first_public_link(html).as_deref(),
500 Some("https://a.example/?q=1&r=2")
501 );
502 assert_eq!(first_public_link("<p>no link</p>"), None);
503 }
504
505 #[test]
506 fn outgoing_json_reads_back_as_the_same_preview() {
507 let preview = LinkPreview {
508 url: "https://github.com/rust-lang/rust".into(),
509 title: Some("Rust".into()),
510 description: Some("Empowering".into()),
511 image_url: Some(THUMBNAIL.into()),
512 image_width: Some(320),
513 image_height: Some(160),
514 };
515 let json: Value = serde_json::from_str(&preview.links_json()).unwrap();
516 assert_eq!(json[0]["@type"], HYPERLINK_TYPE);
517 assert_eq!(json[0]["itemid"], "0");
518 assert_eq!(json[0]["previewenabled"], true);
519 assert_eq!(json[0]["preview"]["previewurl"], THUMBNAIL);
520 assert_eq!(select_preview(&preview.links_json()), Some(preview));
521 }
522
523 #[test]
524 fn info_without_title_or_usable_image_makes_no_preview() {
525 let info = LinkInfo {
526 url: "https://a.example".into(),
527 description: Some("only text".into()),
528 thumbnail: Some("https://evil.example/i.png".into()),
529 ..LinkInfo::default()
530 };
531 assert_eq!(LinkPreview::from_info("https://a.example", &info), None);
532 }
533
534 #[test]
535 fn deleted_messages_show_no_preview() {
536 let record = MessageRecord {
537 deleted: true,
538 body_html: "<p><a href=\"https://a.example\">a</a></p>".to_owned(),
539 links_json: links(
540 json!([{"url": "https://a.example", "preview": {"title": "A", "description": "D"}, "previewenabled": true}]),
541 ),
542 ..MessageRecord::default()
543 };
544 assert_eq!(link_preview(&record), None);
545 }
546}