BlueGit

ict rusty-teams

Files

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

links.rs

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