BlueGit

ict rusty-teams

Files

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

native.rs

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