BlueGit

ict rusty-teams

Files

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

native.rs

native.rs 10.7 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 { client, tokens: Mutex::new(HashMap::new()), max_bytes })
53 }
54
55 pub(crate) fn forget(&self, scope: &Scope) {
56 self.tokens.lock().expect("token lock").remove(&TokenKey::of(scope));
57 }
58
59 fn held(&self, scope: &Scope) -> Option<(App, String)> {
60 let tokens = self.tokens.lock().expect("token lock");
61 let held = tokens.get(&TokenKey::of(scope))?;
62 (Instant::now() < held.usable_until).then(|| (held.app, held.token.clone()))
63 }
64
65 /// `None` hands the batch to the page path, which waits for sign-in, reloads and explains failures.
66 pub(crate) async fn run(&self, session: &Session, requests: &[&Request], scope: &Scope, force_refresh: bool) -> Option<Vec<ApiResponse>> {
67 if !requests.iter().all(|request| eligible(request)) {
68 return None;
69 }
70 let credential = if requests.iter().all(|request| request.anonymous) {
71 None
72 } else {
73 Some(self.token(session, scope, force_refresh).await?)
74 };
75 let mut answers = Vec::with_capacity(requests.len());
76 for chunk in requests.chunks(CONCURRENCY) {
77 let mut pending = Vec::with_capacity(chunk.len());
78 for request in chunk {
79 pending.push(self.execute(request, credential.as_ref()));
80 }
81 answers.extend(join_all(pending).await);
82 }
83 if answers.iter().any(|answer| answer.status == 401) {
84 self.forget(scope);
85 }
86 Some(answers)
87 }
88
89 async fn token(&self, session: &Session, scope: &Scope, force_refresh: bool) -> Option<(App, String)> {
90 if !force_refresh && let Some(held) = self.held(scope) {
91 return Some(held);
92 }
93 for app in scope.tab_order() {
94 let Ok(Value::String(token)) = session.run_with_token(app, scope, TOKEN_BODY, &json!({}), force_refresh).await else {
95 continue;
96 };
97 let usable_until = usable_until(&token, session.config.refresh_margin)?;
98 self.tokens
99 .lock()
100 .expect("token lock")
101 .insert(TokenKey::of(scope), HeldToken { app, token: token.clone(), usable_until });
102 return Some((app, token));
103 }
104 None
105 }
106
107 async fn execute(&self, request: &Request, credential: Option<&(App, String)>) -> ApiResponse {
108 match self.exchange(request, credential).await {
109 Ok(response) => response,
110 Err(error) => ApiResponse { status: 0, body: Value::String(error.without_url().to_string()), retry_after: None },
111 }
112 }
113
114 async fn exchange(&self, request: &Request, credential: Option<&(App, String)>) -> reqwest::Result<ApiResponse> {
115 let mut builder = self.client.request(method(request.method), &request.url);
116 let mut has_content_type = false;
117 for (name, value) in &request.headers {
118 has_content_type |= name.eq_ignore_ascii_case("content-type");
119 builder = builder.header(name, value);
120 }
121 if let Some((app, token)) = credential.filter(|_| !request.anonymous) {
122 builder = builder.bearer_auth(token).header("Origin", app.origins()[0]);
123 }
124 if let Some(encoded) = &request.body_base64 {
125 builder = builder.body(STANDARD.decode(encoded).unwrap_or_default());
126 } else if let Some(body) = &request.body {
127 if !has_content_type {
128 builder = builder.header("Content-Type", "application/json");
129 }
130 builder = builder.body(body.to_string());
131 } else if request.method != Method::Get {
132 // Some Teams fronts answer a bodyless DELETE or POST with 411 Length Required.
133 builder = builder.header(reqwest::header::CONTENT_LENGTH, 0);
134 }
135 let response = builder.send().await?;
136 let status = response.status().as_u16();
137 let retry_after = response.headers().get("Retry-After").and_then(|value| value.to_str().ok()).map(str::to_owned);
138 if request.binary && response.status().is_success() {
139 let content_type = response.headers().get("Content-Type").and_then(|value| value.to_str().ok()).map(str::to_owned);
140 let bytes = response.bytes().await?;
141 if bytes.len() as u64 > self.max_bytes {
142 let body = format!("download is {} bytes, over the {} limit", bytes.len(), self.max_bytes);
143 return Ok(ApiResponse { status: 413, body: Value::String(body), retry_after: None });
144 }
145 let body = json!({"base64": STANDARD.encode(&bytes), "contentType": content_type});
146 return Ok(ApiResponse { status, body, retry_after });
147 }
148 let text = response.text().await?;
149 let body = if text.is_empty() { Value::Null } else { serde_json::from_str(&text).unwrap_or(Value::String(text)) };
150 Ok(ApiResponse { status, body, retry_after })
151 }
152}
153
154const TEAMS_BEARER_PATHS: [&str; 2] = ["/api/", "/registrar/"];
155
156/// Both rustls providers end up compiled in through dependencies, and then rustls refuses to pick one on its own.
157pub fn ensure_crypto_provider() {
158 if rustls::crypto::CryptoProvider::get_default().is_none() {
159 let _ = rustls::crypto::ring::default_provider().install_default();
160 }
161}
162
163/// Page-only: websocket exchanges, tokens spliced into bodies, and app-origin calls that may rely on its cookies.
164fn eligible(request: &Request) -> bool {
165 request.signalr.is_none()
166 && request.augloop.is_none()
167 && request.body_tokens.is_empty()
168 && request.url.starts_with("https://")
169 && !needs_page_cookies(&request.url)
170}
171
172fn needs_page_cookies(url: &str) -> bool {
173 App::ALL.iter().any(|&app| {
174 app.origins().iter().any(|origin| {
175 same_origin(url, origin)
176 && !(app == App::Teams && TEAMS_BEARER_PATHS.iter().any(|path| url[origin.len()..].starts_with(path)))
177 })
178 })
179}
180
181fn same_origin(url: &str, origin: &str) -> bool {
182 url.strip_prefix(origin).is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
183}
184
185fn method(method: Method) -> reqwest::Method {
186 match method {
187 Method::Get => reqwest::Method::GET,
188 Method::Post => reqwest::Method::POST,
189 Method::Put => reqwest::Method::PUT,
190 Method::Patch => reqwest::Method::PATCH,
191 Method::Delete => reqwest::Method::DELETE,
192 }
193}
194
195fn expires_at(token: &str) -> Option<u64> {
196 let payload = token.split('.').nth(1)?;
197 let claims: Value = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?).ok()?;
198 claims.get("exp")?.as_u64()
199}
200
201fn usable_until(token: &str, margin: Duration) -> Option<Instant> {
202 let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
203 let left = expires_at(token)?.checked_sub(now)?.checked_sub(margin.as_secs())?;
204 Some(Instant::now() + Duration::from_secs(left))
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210
211 fn token_expiring_at(exp: u64) -> String {
212 format!("e30.{}.sig", URL_SAFE_NO_PAD.encode(format!("{{\"exp\":{exp}}}")))
213 }
214
215 #[test]
216 fn a_token_is_used_until_the_margin_before_it_expires() {
217 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
218 let until = usable_until(&token_expiring_at(now + 3600), Duration::from_secs(120)).unwrap();
219 let left = until.saturating_duration_since(Instant::now()).as_secs();
220 assert!((3470..=3480).contains(&left), "{left}");
221 assert!(usable_until(&token_expiring_at(now + 60), Duration::from_secs(120)).is_none());
222 assert!(usable_until("not-a-jwt", Duration::from_secs(120)).is_none());
223 }
224
225 #[tokio::test]
226 async fn a_bodyless_delete_says_its_length_is_zero() {
227 use tokio::io::{AsyncReadExt, AsyncWriteExt};
228 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
229 let url = format!("http://{}/messages/1?behavior=softDelete", listener.local_addr().unwrap());
230 let server = tokio::spawn(async move {
231 let (mut socket, _) = listener.accept().await.unwrap();
232 let mut head = vec![0; 4096];
233 let read = socket.read(&mut head).await.unwrap();
234 socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").await.unwrap();
235 String::from_utf8_lossy(&head[..read]).to_lowercase()
236 });
237 let http = NativeHttp::new(Duration::from_secs(5), 1024).unwrap();
238 let answer = http.exchange(&Request::delete(&url), None).await.unwrap();
239 assert_eq!(answer.status, 200);
240 assert!(server.await.unwrap().contains("content-length: 0"));
241 }
242
243 #[test]
244 fn only_plain_cross_origin_requests_leave_the_page() {
245 assert!(eligible(&Request::get("https://graph.microsoft.com/v1.0/me")));
246 assert!(eligible(&Request::anonymous_binary_get("https://media.giphy.com/x.gif", Vec::new())));
247 assert!(eligible(&Request::get("https://teams.cloud.microsoft/api/mt/emea/beta/users")));
248 assert!(!eligible(&Request::get("https://teams.cloud.microsoft/v2/")));
249 assert!(!eligible(&Request::get("https://outlook.office.com/api/v2.0/me/messages")));
250 assert!(!eligible(&Request::get("http://graph.microsoft.com/v1.0/me")));
251 let spliced = Request::with_body(Method::Post, "https://x.example/", json!({"t": "@@t@@"})).with_body_token("https://r", "s", "@@t@@");
252 assert!(!eligible(&spliced));
253 }
254}