BlueGit

ict rusty-teams

Files

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

native.rs

native.rs 9.5 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 }
132 let response = builder.send().await?;
133 let status = response.status().as_u16();
134 let retry_after = response.headers().get("Retry-After").and_then(|value| value.to_str().ok()).map(str::to_owned);
135 if request.binary && response.status().is_success() {
136 let content_type = response.headers().get("Content-Type").and_then(|value| value.to_str().ok()).map(str::to_owned);
137 let bytes = response.bytes().await?;
138 if bytes.len() as u64 > self.max_bytes {
139 let body = format!("download is {} bytes, over the {} limit", bytes.len(), self.max_bytes);
140 return Ok(ApiResponse { status: 413, body: Value::String(body), retry_after: None });
141 }
142 let body = json!({"base64": STANDARD.encode(&bytes), "contentType": content_type});
143 return Ok(ApiResponse { status, body, retry_after });
144 }
145 let text = response.text().await?;
146 let body = if text.is_empty() { Value::Null } else { serde_json::from_str(&text).unwrap_or(Value::String(text)) };
147 Ok(ApiResponse { status, body, retry_after })
148 }
149}
150
151const TEAMS_BEARER_PATHS: [&str; 2] = ["/api/", "/registrar/"];
152
153/// Both rustls providers end up compiled in through dependencies, and then rustls refuses to pick one on its own.
154pub fn ensure_crypto_provider() {
155 if rustls::crypto::CryptoProvider::get_default().is_none() {
156 let _ = rustls::crypto::ring::default_provider().install_default();
157 }
158}
159
160/// Page-only: websocket exchanges, tokens spliced into bodies, and app-origin calls that may rely on its cookies.
161fn eligible(request: &Request) -> bool {
162 request.signalr.is_none()
163 && request.augloop.is_none()
164 && request.body_tokens.is_empty()
165 && request.url.starts_with("https://")
166 && !needs_page_cookies(&request.url)
167}
168
169fn needs_page_cookies(url: &str) -> bool {
170 App::ALL.iter().any(|&app| {
171 app.origins().iter().any(|origin| {
172 same_origin(url, origin)
173 && !(app == App::Teams && TEAMS_BEARER_PATHS.iter().any(|path| url[origin.len()..].starts_with(path)))
174 })
175 })
176}
177
178fn same_origin(url: &str, origin: &str) -> bool {
179 url.strip_prefix(origin).is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
180}
181
182fn method(method: Method) -> reqwest::Method {
183 match method {
184 Method::Get => reqwest::Method::GET,
185 Method::Post => reqwest::Method::POST,
186 Method::Put => reqwest::Method::PUT,
187 Method::Patch => reqwest::Method::PATCH,
188 Method::Delete => reqwest::Method::DELETE,
189 }
190}
191
192fn expires_at(token: &str) -> Option<u64> {
193 let payload = token.split('.').nth(1)?;
194 let claims: Value = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?).ok()?;
195 claims.get("exp")?.as_u64()
196}
197
198fn usable_until(token: &str, margin: Duration) -> Option<Instant> {
199 let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
200 let left = expires_at(token)?.checked_sub(now)?.checked_sub(margin.as_secs())?;
201 Some(Instant::now() + Duration::from_secs(left))
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 fn token_expiring_at(exp: u64) -> String {
209 format!("e30.{}.sig", URL_SAFE_NO_PAD.encode(format!("{{\"exp\":{exp}}}")))
210 }
211
212 #[test]
213 fn a_token_is_used_until_the_margin_before_it_expires() {
214 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
215 let until = usable_until(&token_expiring_at(now + 3600), Duration::from_secs(120)).unwrap();
216 let left = until.saturating_duration_since(Instant::now()).as_secs();
217 assert!((3470..=3480).contains(&left), "{left}");
218 assert!(usable_until(&token_expiring_at(now + 60), Duration::from_secs(120)).is_none());
219 assert!(usable_until("not-a-jwt", Duration::from_secs(120)).is_none());
220 }
221
222 #[test]
223 fn only_plain_cross_origin_requests_leave_the_page() {
224 assert!(eligible(&Request::get("https://graph.microsoft.com/v1.0/me")));
225 assert!(eligible(&Request::anonymous_binary_get("https://media.giphy.com/x.gif", Vec::new())));
226 assert!(eligible(&Request::get("https://teams.cloud.microsoft/api/mt/emea/beta/users")));
227 assert!(!eligible(&Request::get("https://teams.cloud.microsoft/v2/")));
228 assert!(!eligible(&Request::get("https://outlook.office.com/api/v2.0/me/messages")));
229 assert!(!eligible(&Request::get("http://graph.microsoft.com/v1.0/me")));
230 let spliced = Request::with_body(Method::Post, "https://x.example/", json!({"t": "@@t@@"})).with_body_token("https://r", "s", "@@t@@");
231 assert!(!eligible(&spliced));
232 }
233}