| 1 | use std::collections::HashMap; |
| 2 | use std::sync::Mutex; |
| 3 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 4 | |
| 5 | use base64::Engine as _; |
| 6 | use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; |
| 7 | use futures_util::future::join_all; |
| 8 | use serde_json::{Value, json}; |
| 9 | |
| 10 | use crate::app::{App, is_on_origin}; |
| 11 | use crate::request::{ApiResponse, Method, Request}; |
| 12 | use crate::scope::Scope; |
| 13 | use crate::session::Session; |
| 14 | |
| 15 | const TOKEN_BODY: &str = "return token;"; |
| 16 | const CONCURRENCY: usize = 6; |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 19 | struct TokenKey { |
| 20 | resource: String, |
| 21 | name: String, |
| 22 | nested_client: Option<&'static str>, |
| 23 | } |
| 24 | |
| 25 | impl 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 | |
| 35 | struct 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. |
| 42 | pub(crate) struct NativeHttp { |
| 43 | client: reqwest::Client, |
| 44 | tokens: Mutex<HashMap<TokenKey, HeldToken>>, |
| 45 | max_bytes: u64, |
| 46 | } |
| 47 | |
| 48 | impl 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 | |
| 231 | const 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. |
| 234 | pub 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. |
| 241 | fn 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 | |
| 249 | fn needs_page_cookies(url: &str) -> bool { |
| 250 | App::ALL.iter().any(|&app| { |
| 251 | app.origins().iter().any(|origin| { |
| 252 | is_on_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 | |
| 261 | fn method(method: Method) -> reqwest::Method { |
| 262 | match method { |
| 263 | Method::Get => reqwest::Method::GET, |
| 264 | Method::Post => reqwest::Method::POST, |
| 265 | Method::Put => reqwest::Method::PUT, |
| 266 | Method::Patch => reqwest::Method::PATCH, |
| 267 | Method::Delete => reqwest::Method::DELETE, |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | fn expires_at(token: &str) -> Option<u64> { |
| 272 | let payload = token.split('.').nth(1)?; |
| 273 | let claims: Value = |
| 274 | serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?) |
| 275 | .ok()?; |
| 276 | claims.get("exp")?.as_u64() |
| 277 | } |
| 278 | |
| 279 | fn usable_until(token: &str, margin: Duration) -> Option<Instant> { |
| 280 | let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs(); |
| 281 | let left = expires_at(token)? |
| 282 | .checked_sub(now)? |
| 283 | .checked_sub(margin.as_secs())?; |
| 284 | Some(Instant::now() + Duration::from_secs(left)) |
| 285 | } |
| 286 | |
| 287 | #[cfg(test)] |
| 288 | mod tests { |
| 289 | use super::*; |
| 290 | |
| 291 | fn token_expiring_at(exp: u64) -> String { |
| 292 | format!( |
| 293 | "e30.{}.sig", |
| 294 | URL_SAFE_NO_PAD.encode(format!("{{\"exp\":{exp}}}")) |
| 295 | ) |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn a_token_is_used_until_the_margin_before_it_expires() { |
| 300 | let now = SystemTime::now() |
| 301 | .duration_since(UNIX_EPOCH) |
| 302 | .unwrap() |
| 303 | .as_secs(); |
| 304 | let until = usable_until(&token_expiring_at(now + 3600), Duration::from_secs(120)).unwrap(); |
| 305 | let left = until.saturating_duration_since(Instant::now()).as_secs(); |
| 306 | assert!((3470..=3480).contains(&left), "{left}"); |
| 307 | assert!(usable_until(&token_expiring_at(now + 60), Duration::from_secs(120)).is_none()); |
| 308 | assert!(usable_until("not-a-jwt", Duration::from_secs(120)).is_none()); |
| 309 | } |
| 310 | |
| 311 | #[tokio::test] |
| 312 | async fn a_bodyless_delete_says_its_length_is_zero() { |
| 313 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 314 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 315 | let url = format!( |
| 316 | "http://{}/messages/1?behavior=softDelete", |
| 317 | listener.local_addr().unwrap() |
| 318 | ); |
| 319 | let server = tokio::spawn(async move { |
| 320 | let (mut socket, _) = listener.accept().await.unwrap(); |
| 321 | let mut head = vec![0; 4096]; |
| 322 | let read = socket.read(&mut head).await.unwrap(); |
| 323 | socket |
| 324 | .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") |
| 325 | .await |
| 326 | .unwrap(); |
| 327 | String::from_utf8_lossy(&head[..read]).to_lowercase() |
| 328 | }); |
| 329 | let http = NativeHttp::new(Duration::from_secs(5), 1024).unwrap(); |
| 330 | let answer = http.exchange(&Request::delete(&url), None).await.unwrap(); |
| 331 | assert_eq!(answer.status, 200); |
| 332 | assert!(server.await.unwrap().contains("content-length: 0")); |
| 333 | } |
| 334 | |
| 335 | #[test] |
| 336 | fn only_plain_cross_origin_requests_leave_the_page() { |
| 337 | assert!(eligible(&Request::get( |
| 338 | "https://graph.microsoft.com/v1.0/me" |
| 339 | ))); |
| 340 | assert!(eligible(&Request::anonymous_binary_get( |
| 341 | "https://media.giphy.com/x.gif", |
| 342 | Vec::new() |
| 343 | ))); |
| 344 | assert!(eligible(&Request::get( |
| 345 | "https://teams.cloud.microsoft/api/mt/emea/beta/users" |
| 346 | ))); |
| 347 | assert!(!eligible(&Request::get( |
| 348 | "https://teams.cloud.microsoft/v2/" |
| 349 | ))); |
| 350 | assert!(!eligible(&Request::get( |
| 351 | "http://graph.microsoft.com/v1.0/me" |
| 352 | ))); |
| 353 | let spliced = Request::with_body(Method::Post, "https://x.example/", json!({"t": "@@t@@"})) |
| 354 | .with_body_token("https://r", "s", "@@t@@"); |
| 355 | assert!(!eligible(&spliced)); |
| 356 | } |
| 357 | } |