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 importance: Default::default(),
293 }
294 }
295
296 #[test]
297 fn picks_the_first_enabled_public_link_with_two_parts() {
298 let preview = select_preview(&links(json!([
299 {"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File", "description": "F"}, "previewenabled": true},
300 {"url": "https://a.example/x", "preview": {}, "previewenabled": true},
301 {"url": "https://n.example/x", "preview": {"title": "N", "description": "No flag"}},
302 {"url": "https://t.example/x", "preview": {"title": "Title only"}, "previewenabled": true},
303 {"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}, "previewenabled": true},
304 ])))
305 .unwrap();
306 assert_eq!(preview.url, "https://b.example/y");
307 assert_eq!(preview.title.as_deref(), Some("B"));
308 assert_eq!(preview.description.as_deref(), Some("About B"));
309 assert_eq!(preview.domain(), "b.example");
310 }
311
312 #[test]
313 fn an_image_needs_a_title_or_description() {
314 assert_eq!(
315 select_preview(&links(json!([
316 {"url": "https://a.example", "preview": {"previewurl": THUMBNAIL}, "previewenabled": true},
317 ]))),
318 None
319 );
320 let preview = select_preview(&links(json!([
321 {"url": "https://a.example", "preview": {"description": "D", "previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": true},
322 ])))
323 .unwrap();
324 assert_eq!(preview.title, None);
325 assert_eq!(preview.image_url.as_deref(), Some(THUMBNAIL));
326 assert_eq!(
327 (preview.image_width, preview.image_height),
328 (Some(320), Some(160))
329 );
330 }
331
332 #[test]
333 fn reads_the_camel_case_meta_and_null_meta() {
334 let preview = select_preview(&links(json!([
335 {"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}, "previewenabled": true},
336 ])))
337 .unwrap();
338 assert_eq!(
339 (preview.image_width, preview.image_height),
340 (Some(20), Some(10))
341 );
342 let second = select_preview(&links(json!([
343 {"url": "https://b.example", "preview": {"title": "B", "description": "D", "previewmeta": null}, "previewenabled": true},
344 ])))
345 .unwrap();
346 assert_eq!(second.image_width, None);
347 }
348
349 fn linked_record(body_html: &str, links_json: Value, attachments_json: Value) -> MessageRecord {
350 MessageRecord {
351 body_html: body_html.to_owned(),
352 links_json: links(links_json),
353 attachments_json: attachments_json.to_string(),
354 ..demo_record()
355 }
356 }
357
358 fn video_link_entry(previewenabled: Value) -> Value {
359 json!([{
360 "@type": HYPERLINK_TYPE,
361 "itemid": "0",
362 "url": "https://www.youtube.com/watch?v=video_id_01",
363 "preview": {"title": "Sample video", "description": "1K views", "previewurl": THUMBNAIL},
364 "previewenabled": previewenabled,
365 }])
366 }
367
368 fn unfurl_card(id: &str, teams_app_id: Option<&str>) -> Value {
369 let content = json!({
370 "type": "AdaptiveCard",
371 "version": "1.5",
372 "body": [
373 {"type": "Media", "sources": [{"mimeType": "video/mp4", "url": "https://www.youtube.com/watch?v=video_id_01"}]},
374 {"type": "TextBlock", "text": "Sample video"},
375 {"type": "TextBlock", "text": "Sample channel"},
376 ],
377 "actions": [{"type": "Action.OpenUrl", "title": "Open", "url": "https://www.youtube.com/watch?v=video_id_01"}],
378 });
379 json!([{
380 "content_type": "application/vnd.microsoft.card.adaptive",
381 "name": null,
382 "url": null,
383 "text": null,
384 "id": id,
385 "content": content.to_string(),
386 "teams_app_id": teams_app_id,
387 }])
388 }
389
390 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>";
391
392 #[test]
393 fn a_video_link_with_its_unfurl_card_shows_only_the_card() {
394 let teams_sent = linked_record(
395 VIDEO_BODY,
396 video_link_entry(json!(false)),
397 unfurl_card("app-preview-card-1", None),
398 );
399 assert_eq!(link_preview(&teams_sent), None);
400 let flagged_on = linked_record(
401 VIDEO_BODY,
402 video_link_entry(json!(true)),
403 unfurl_card(
404 "74d20c7f34aa4a7f",
405 Some("4623dd0c-d55c-4c95-9290-ad31619b577a"),
406 ),
407 );
408 assert_eq!(link_preview(&flagged_on), None);
409 let by_card_id = linked_record(
410 VIDEO_BODY,
411 video_link_entry(json!(true)),
412 unfurl_card("app-preview-card-2", None),
413 );
414 assert_eq!(link_preview(&by_card_id), None);
415 let cards = crate::stored::adaptive_cards(&flagged_on);
416 assert_eq!(cards.len(), 1);
417 }
418
419 #[test]
420 fn a_video_link_without_a_card_keeps_its_preview() {
421 let record = linked_record(VIDEO_BODY, video_link_entry(json!(true)), json!([]));
422 let preview = link_preview(&record).unwrap();
423 assert_eq!(preview.domain(), "youtube.com");
424 let missing_flag = linked_record(VIDEO_BODY, video_link_entry(Value::Null), json!([]));
425 assert_eq!(link_preview(&missing_flag), None);
426 }
427
428 #[test]
429 fn only_the_first_link_of_the_message_gets_a_preview() {
430 let body = "<p><a href=\"https://other.example/\">other</a> <a href=\"https://www.youtube.com/watch?v=video_id_01\">video</a></p>";
431 let record = linked_record(body, video_link_entry(json!(true)), json!([]));
432 assert_eq!(link_preview(&record), None);
433 assert!(same_link("https://A.example/x/", "https://a.example/x"));
434 }
435
436 #[test]
437 fn a_removed_preview_is_not_shown() {
438 assert_eq!(
439 select_preview(&links(json!([
440 {"url": "https://a.example", "preview": {"title": "A"}, "previewenabled": false},
441 ]))),
442 None
443 );
444 }
445
446 #[test]
447 fn images_outside_the_preview_service_are_dropped() {
448 assert_eq!(
449 select_preview(&links(json!([
450 {"url": "https://a.example", "preview": {"previewurl": "https://evil.example/i.png"}},
451 ]))),
452 None
453 );
454 }
455
456 #[test]
457 fn garbage_and_empty_lists_have_no_preview() {
458 assert_eq!(select_preview("[]"), None);
459 assert_eq!(select_preview(""), None);
460 assert_eq!(select_preview("{}"), None);
461 assert_eq!(select_preview("[{\"url\": 3}]"), None);
462 }
463
464 #[test]
465 fn internal_and_private_hosts_are_skipped() {
466 for url in [
467 "https://contoso.sharepoint.com/a",
468 "https://contoso-my.sharepoint.com/a",
469 "https://onedrive.com/a",
470 "https://1drv.ms/a",
471 "https://teams.microsoft.com/l/x",
472 "https://teams.cloud.microsoft/x",
473 "https://teams.live.com/x",
474 "https://www.office.com/x",
475 "https://m365.microsoft365.com/x",
476 "https://localhost/x",
477 "https://intranet/x",
478 "http://192.168.1.2/x",
479 "http://127.0.0.1:8080/x",
480 "ftp://a.example/x",
481 "mailto:a@b.example",
482 ] {
483 assert!(!is_public_link(url), "{url}");
484 }
485 for url in [
486 "https://github.com/rust-lang/rust",
487 "http://a.example:8080/x",
488 "https://notsharepoint.com/x",
489 "https://user@example.org/x",
490 ] {
491 assert!(is_public_link(url), "{url}");
492 }
493 }
494
495 #[test]
496 fn finds_the_first_public_anchor_in_html() {
497 let html = "<p><a href=\"https://contoso.sharepoint.com/x\">f</a> \
498 <a href=\"https://a.example/?q=1&amp;r=2\">a</a> <a href=\"https://b.example\">b</a></p>";
499 assert_eq!(
500 first_public_link(html).as_deref(),
501 Some("https://a.example/?q=1&r=2")
502 );
503 assert_eq!(first_public_link("<p>no link</p>"), None);
504 }
505
506 #[test]
507 fn outgoing_json_reads_back_as_the_same_preview() {
508 let preview = LinkPreview {
509 url: "https://github.com/rust-lang/rust".into(),
510 title: Some("Rust".into()),
511 description: Some("Empowering".into()),
512 image_url: Some(THUMBNAIL.into()),
513 image_width: Some(320),
514 image_height: Some(160),
515 };
516 let json: Value = serde_json::from_str(&preview.links_json()).unwrap();
517 assert_eq!(json[0]["@type"], HYPERLINK_TYPE);
518 assert_eq!(json[0]["itemid"], "0");
519 assert_eq!(json[0]["previewenabled"], true);
520 assert_eq!(json[0]["preview"]["previewurl"], THUMBNAIL);
521 assert_eq!(select_preview(&preview.links_json()), Some(preview));
522 }
523
524 #[test]
525 fn info_without_title_or_usable_image_makes_no_preview() {
526 let info = LinkInfo {
527 url: "https://a.example".into(),
528 description: Some("only text".into()),
529 thumbnail: Some("https://evil.example/i.png".into()),
530 ..LinkInfo::default()
531 };
532 assert_eq!(LinkPreview::from_info("https://a.example", &info), None);
533 }
534
535 #[test]
536 fn deleted_messages_show_no_preview() {
537 let record = MessageRecord {
538 deleted: true,
539 body_html: "<p><a href=\"https://a.example\">a</a></p>".to_owned(),
540 links_json: links(
541 json!([{"url": "https://a.example", "preview": {"title": "A", "description": "D"}, "previewenabled": true}]),
542 ),
543 ..MessageRecord::default()
544 };
545 assert_eq!(link_preview(&record), None);
546 }
547}