BlueGit

ict rusty-teams

Files

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

native.rs

native.rs 12.0 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 body = if text.is_empty() {
210 location.map_or(Value::Null, |location| json!({ "location": location }))
211 } else {
212 serde_json::from_str(&text).unwrap_or(Value::String(text))
213 };
214 Ok(ApiResponse {
215 status,
216 body,
217 retry_after,
218 })
219 }
220}
221
222const TEAMS_BEARER_PATHS: [&str; 2] = ["/api/", "/registrar/"];
223
224/// Both rustls providers end up compiled in through dependencies, and then rustls refuses to pick one on its own.
225pub fn ensure_crypto_provider() {
226 if rustls::crypto::CryptoProvider::get_default().is_none() {
227 let _ = rustls::crypto::ring::default_provider().install_default();
228 }
229}
230
231/// Page-only: websocket exchanges, tokens spliced into bodies, and app-origin calls that may rely on its cookies.
232fn eligible(request: &Request) -> bool {
233 request.signalr.is_none()
234 && request.augloop.is_none()
235 && request.body_tokens.is_empty()
236 && request.url.starts_with("https://")
237 && !needs_page_cookies(&request.url)
238}
239
240fn needs_page_cookies(url: &str) -> bool {
241 App::ALL.iter().any(|&app| {
242 app.origins().iter().any(|origin| {
243 same_origin(url, origin)
244 && !(app == App::Teams
245 && TEAMS_BEARER_PATHS
246 .iter()
247 .any(|path| url[origin.len()..].starts_with(path)))
248 })
249 })
250}
251
252fn same_origin(url: &str, origin: &str) -> bool {
253 url.strip_prefix(origin)
254 .is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
255}
256
257fn method(method: Method) -> reqwest::Method {
258 match method {
259 Method::Get => reqwest::Method::GET,
260 Method::Post => reqwest::Method::POST,
261 Method::Put => reqwest::Method::PUT,
262 Method::Patch => reqwest::Method::PATCH,
263 Method::Delete => reqwest::Method::DELETE,
264 }
265}
266
267fn expires_at(token: &str) -> Option<u64> {
268 let payload = token.split('.').nth(1)?;
269 let claims: Value =
270 serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?)
271 .ok()?;
272 claims.get("exp")?.as_u64()
273}
274
275fn usable_until(token: &str, margin: Duration) -> Option<Instant> {
276 let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
277 let left = expires_at(token)?
278 .checked_sub(now)?
279 .checked_sub(margin.as_secs())?;
280 Some(Instant::now() + Duration::from_secs(left))
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 fn token_expiring_at(exp: u64) -> String {
288 format!(
289 "e30.{}.sig",
290 URL_SAFE_NO_PAD.encode(format!("{{\"exp\":{exp}}}"))
291 )
292 }
293
294 #[test]
295 fn a_token_is_used_until_the_margin_before_it_expires() {
296 let now = SystemTime::now()
297 .duration_since(UNIX_EPOCH)
298 .unwrap()
299 .as_secs();
300 let until = usable_until(&token_expiring_at(now + 3600), Duration::from_secs(120)).unwrap();
301 let left = until.saturating_duration_since(Instant::now()).as_secs();
302 assert!((3470..=3480).contains(&left), "{left}");
303 assert!(usable_until(&token_expiring_at(now + 60), Duration::from_secs(120)).is_none());
304 assert!(usable_until("not-a-jwt", Duration::from_secs(120)).is_none());
305 }
306
307 #[tokio::test]
308 async fn a_bodyless_delete_says_its_length_is_zero() {
309 use tokio::io::{AsyncReadExt, AsyncWriteExt};
310 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
311 let url = format!(
312 "http://{}/messages/1?behavior=softDelete",
313 listener.local_addr().unwrap()
314 );
315 let server = tokio::spawn(async move {
316 let (mut socket, _) = listener.accept().await.unwrap();
317 let mut head = vec![0; 4096];
318 let read = socket.read(&mut head).await.unwrap();
319 socket
320 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
321 .await
322 .unwrap();
323 String::from_utf8_lossy(&head[..read]).to_lowercase()
324 });
325 let http = NativeHttp::new(Duration::from_secs(5), 1024).unwrap();
326 let answer = http.exchange(&Request::delete(&url), None).await.unwrap();
327 assert_eq!(answer.status, 200);
328 assert!(server.await.unwrap().contains("content-length: 0"));
329 }
330
331 #[test]
332 fn only_plain_cross_origin_requests_leave_the_page() {
333 assert!(eligible(&Request::get(
334 "https://graph.microsoft.com/v1.0/me"
335 )));
336 assert!(eligible(&Request::anonymous_binary_get(
337 "https://media.giphy.com/x.gif",
338 Vec::new()
339 )));
340 assert!(eligible(&Request::get(
341 "https://teams.cloud.microsoft/api/mt/emea/beta/users"
342 )));
343 assert!(!eligible(&Request::get(
344 "https://teams.cloud.microsoft/v2/"
345 )));
346 assert!(!eligible(&Request::get(
347 "http://graph.microsoft.com/v1.0/me"
348 )));
349 let spliced = Request::with_body(Method::Post, "https://x.example/", json!({"t": "@@t@@"}))
350 .with_body_token("https://r", "s", "@@t@@");
351 assert!(!eligible(&spliced));
352 }
353}