BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / src / native.rs

native.rs

native.rs 12.3 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::Mutex;
3use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
4
5use base64::Engine as _;
6use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
7use futures_util::future::join_all;
8use serde_json::{Value, json};
9
10use crate::app::App;
11use crate::request::{ApiResponse, Method, Request};
12use crate::scope::Scope;
13use crate::session::Session;
14
15const TOKEN_BODY: &str = "return token;";
16const CONCURRENCY: usize = 6;
17
18#[derive(Debug, Clone, PartialEq, Eq, Hash)]
19struct TokenKey {
20 resource: String,
21 name: String,
22 nested_client: Option<&'static str>,
23}
24
25impl TokenKey {
26 fn of(scope: &Scope) -> Self {
27 TokenKey {
28 resource: scope.resource.to_string(),
29 name: scope.name.to_string(),
30 nested_client: scope.nested_app.map(|app| app.client_id),
31 }
32 }
33}
34
35struct HeldToken {
36 app: App,
37 token: String,
38 usable_until: Instant,
39}
40
41/// Sends requests from Rust; the app tab is asked only for an access token, which stays in memory until shortly before it expires.
42pub(crate) struct NativeHttp {
43 client: reqwest::Client,
44 tokens: Mutex<HashMap<TokenKey, HeldToken>>,
45 max_bytes: u64,
46}
47
48impl NativeHttp {
49 pub(crate) fn new(timeout: Duration, max_bytes: u64) -> Option<Self> {
50 ensure_crypto_provider();
51 let client = reqwest::Client::builder().timeout(timeout).build().ok()?;
52 Some(NativeHttp {
53 client,
54 tokens: Mutex::new(HashMap::new()),
55 max_bytes,
56 })
57 }
58
59 pub(crate) fn forget(&self, scope: &Scope) {
60 self.tokens
61 .lock()
62 .expect("token lock")
63 .remove(&TokenKey::of(scope));
64 }
65
66 fn held(&self, scope: &Scope) -> Option<(App, String)> {
67 let tokens = self.tokens.lock().expect("token lock");
68 let held = tokens.get(&TokenKey::of(scope))?;
69 (Instant::now() < held.usable_until).then(|| (held.app, held.token.clone()))
70 }
71
72 /// `None` hands the batch to the page path, which waits for sign-in, reloads and explains failures.
73 pub(crate) async fn run(
74 &self,
75 session: &Session,
76 requests: &[&Request],
77 scope: &Scope,
78 force_refresh: bool,
79 ) -> Option<Vec<ApiResponse>> {
80 if !requests.iter().all(|request| eligible(request)) {
81 return None;
82 }
83 let credential = if requests.iter().all(|request| request.anonymous) {
84 None
85 } else {
86 Some(self.token(session, scope, force_refresh).await?)
87 };
88 let mut answers = Vec::with_capacity(requests.len());
89 for chunk in requests.chunks(CONCURRENCY) {
90 let mut pending = Vec::with_capacity(chunk.len());
91 for request in chunk {
92 pending.push(self.execute(request, credential.as_ref()));
93 }
94 answers.extend(join_all(pending).await);
95 }
96 if answers.iter().any(|answer| answer.status == 401) {
97 self.forget(scope);
98 }
99 Some(answers)
100 }
101
102 async fn token(
103 &self,
104 session: &Session,
105 scope: &Scope,
106 force_refresh: bool,
107 ) -> Option<(App, String)> {
108 if !force_refresh && let Some(held) = self.held(scope) {
109 return Some(held);
110 }
111 for app in App::ALL {
112 let Ok(Value::String(token)) = session
113 .run_with_token(app, scope, TOKEN_BODY, &json!({}), force_refresh)
114 .await
115 else {
116 continue;
117 };
118 let usable_until = usable_until(&token, session.config.refresh_margin)?;
119 self.tokens.lock().expect("token lock").insert(
120 TokenKey::of(scope),
121 HeldToken {
122 app,
123 token: token.clone(),
124 usable_until,
125 },
126 );
127 return Some((app, token));
128 }
129 None
130 }
131
132 async fn execute(&self, request: &Request, credential: Option<&(App, String)>) -> ApiResponse {
133 match self.exchange(request, credential).await {
134 Ok(response) => response,
135 Err(error) => ApiResponse {
136 status: 0,
137 body: Value::String(error.without_url().to_string()),
138 retry_after: None,
139 },
140 }
141 }
142
143 async fn exchange(
144 &self,
145 request: &Request,
146 credential: Option<&(App, String)>,
147 ) -> reqwest::Result<ApiResponse> {
148 let mut builder = self.client.request(method(request.method), &request.url);
149 let mut has_content_type = false;
150 for (name, value) in &request.headers {
151 has_content_type |= name.eq_ignore_ascii_case("content-type");
152 builder = builder.header(name, value);
153 }
154 if let Some((app, token)) = credential.filter(|_| !request.anonymous) {
155 builder = builder
156 .bearer_auth(token)
157 .header("Origin", app.origins()[0]);
158 }
159 if let Some(encoded) = &request.body_base64 {
160 builder = builder.body(STANDARD.decode(encoded).unwrap_or_default());
161 } else if let Some(body) = &request.body {
162 if !has_content_type {
163 builder = builder.header("Content-Type", "application/json");
164 }
165 builder = builder.body(body.to_string());
166 } else if request.method != Method::Get {
167 // Some Teams fronts answer a bodyless DELETE or POST with 411 Length Required.
168 builder = builder.header(reqwest::header::CONTENT_LENGTH, 0);
169 }
170 let response = builder.send().await?;
171 let status = response.status().as_u16();
172 let retry_after = response
173 .headers()
174 .get("Retry-After")
175 .and_then(|value| value.to_str().ok())
176 .map(str::to_owned);
177 if request.binary && response.status().is_success() {
178 let content_type = response
179 .headers()
180 .get("Content-Type")
181 .and_then(|value| value.to_str().ok())
182 .map(str::to_owned);
183 let bytes = response.bytes().await?;
184 if bytes.len() as u64 > self.max_bytes {
185 let body = format!(
186 "download is {} bytes, over the {} limit",
187 bytes.len(),
188 self.max_bytes
189 );
190 return Ok(ApiResponse {
191 status: 413,
192 body: Value::String(body),
193 retry_after: None,
194 });
195 }
196 let body = json!({"base64": STANDARD.encode(&bytes), "contentType": content_type});
197 return Ok(ApiResponse {
198 status,
199 body,
200 retry_after,
201 });
202 }
203 let location = response
204 .headers()
205 .get("Location")
206 .and_then(|value| value.to_str().ok())
207 .map(str::to_owned);
208 let text = response.text().await?;
209 let mut body = if text.is_empty() {
210 Value::Null
211 } else {
212 serde_json::from_str(&text).unwrap_or(Value::String(text))
213 };
214 if let Some(location) = location {
215 match &mut body {
216 Value::Null => body = json!({ "location": location }),
217 Value::Object(map) if !map.contains_key("location") => {
218 map.insert("location".into(), Value::String(location));
219 }
220 _ => {}
221 }
222 }
223 Ok(ApiResponse {
224 status,
225 body,
226 retry_after,
227 })
228 }
229}
230
231const TEAMS_BEARER_PATHS: [&str; 2] = ["/api/", "/registrar/"];
232
233/// Both rustls providers end up compiled in through dependencies, and then rustls refuses to pick one on its own.
234pub fn ensure_crypto_provider() {
235 if rustls::crypto::CryptoProvider::get_default().is_none() {
236 let _ = rustls::crypto::ring::default_provider().install_default();
237 }
238}
239
240/// Page-only: websocket exchanges, tokens spliced into bodies, and app-origin calls that may rely on its cookies.
241fn eligible(request: &Request) -> bool {
242 request.signalr.is_none()
243 && request.augloop.is_none()
244 && request.body_tokens.is_empty()
245 && request.url.starts_with("https://")
246 && !needs_page_cookies(&request.url)
247}
248
249fn needs_page_cookies(url: &str) -> bool {
250 App::ALL.iter().any(|&app| {
251 app.origins().iter().any(|origin| {
252 same_origin(url, origin)
253 && !(app == App::Teams
254 && TEAMS_BEARER_PATHS
255 .iter()
256 .any(|path| url[origin.len()..].starts_with(path)))
257 })
258 })
259}
260
261fn same_origin(url: &str, origin: &str) -> bool {
262 url.strip_prefix(origin)
263 .is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
264}
265
266fn method(method: Method) -> reqwest::Method {
267 match method {
268 Method::Get => reqwest::Method::GET,
269 Method::Post => reqwest::Method::POST,
270 Method::Put => reqwest::Method::PUT,
271 Method::Patch => reqwest::Method::PATCH,
272 Method::Delete => reqwest::Method::DELETE,
273 }
274}
275
276fn expires_at(token: &str) -> Option<u64> {
277 let payload = token.split('.').nth(1)?;
278 let claims: Value =
279 serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?)
280 .ok()?;
281 claims.get("exp")?.as_u64()
282}
283
284fn usable_until(token: &str, margin: Duration) -> Option<Instant> {
285 let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
286 let left = expires_at(token)?
287 .checked_sub(now)?
288 .checked_sub(margin.as_secs())?;
289 Some(Instant::now() + Duration::from_secs(left))
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295
296 fn token_expiring_at(exp: u64) -> String {
297 format!(
298 "e30.{}.sig",
299 URL_SAFE_NO_PAD.encode(format!("{{\"exp\":{exp}}}"))
300 )
301 }
302
303 #[test]
304 fn a_token_is_used_until_the_margin_before_it_expires() {
305 let now = SystemTime::now()
306 .duration_since(UNIX_EPOCH)
307 .unwrap()
308 .as_secs();
309 let until = usable_until(&token_expiring_at(now + 3600), Duration::from_secs(120)).unwrap();
310 let left = until.saturating_duration_since(Instant::now()).as_secs();
311 assert!((3470..=3480).contains(&left), "{left}");
312 assert!(usable_until(&token_expiring_at(now + 60), Duration::from_secs(120)).is_none());
313 assert!(usable_until("not-a-jwt", Duration::from_secs(120)).is_none());
314 }
315
316 #[tokio::test]
317 async fn a_bodyless_delete_says_its_length_is_zero() {
318 use tokio::io::{AsyncReadExt, AsyncWriteExt};
319 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
320 let url = format!(
321 "http://{}/messages/1?behavior=softDelete",
322 listener.local_addr().unwrap()
323 );
324 let server = tokio::spawn(async move {
325 let (mut socket, _) = listener.accept().await.unwrap();
326 let mut head = vec![0; 4096];
327 let read = socket.read(&mut head).await.unwrap();
328 socket
329 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
330 .await
331 .unwrap();
332 String::from_utf8_lossy(&head[..read]).to_lowercase()
333 });
334 let http = NativeHttp::new(Duration::from_secs(5), 1024).unwrap();
335 let answer = http.exchange(&Request::delete(&url), None).await.unwrap();
336 assert_eq!(answer.status, 200);
337 assert!(server.await.unwrap().contains("content-length: 0"));
338 }
339
340 #[test]
341 fn only_plain_cross_origin_requests_leave_the_page() {
342 assert!(eligible(&Request::get(
343 "https://graph.microsoft.com/v1.0/me"
344 )));
345 assert!(eligible(&Request::anonymous_binary_get(
346 "https://media.giphy.com/x.gif",
347 Vec::new()
348 )));
349 assert!(eligible(&Request::get(
350 "https://teams.cloud.microsoft/api/mt/emea/beta/users"
351 )));
352 assert!(!eligible(&Request::get(
353 "https://teams.cloud.microsoft/v2/"
354 )));
355 assert!(!eligible(&Request::get(
356 "http://graph.microsoft.com/v1.0/me"
357 )));
358 let spliced = Request::with_body(Method::Post, "https://x.example/", json!({"t": "@@t@@"}))
359 .with_body_token("https://r", "s", "@@t@@");
360 assert!(!eligible(&spliced));
361 }
362}