BlueGit

ict rusty-teams

Files

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

request.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
request.rs 12.3 KiB Download Raw
1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Method {
6 Get,
7 Post,
8 Put,
9 Patch,
10 Delete,
11}
12
13impl Method {
14 pub fn as_str(self) -> &'static str {
15 match self {
16 Method::Get => "GET",
17 Method::Post => "POST",
18 Method::Put => "PUT",
19 Method::Patch => "PATCH",
20 Method::Delete => "DELETE",
21 }
22 }
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
26pub struct BodyToken {
27 pub resource: String,
28 pub scope: String,
29 pub placeholder: String,
30}
31
32/// A SignalR JSON-protocol exchange over a WebSocket opened in the page with the token in the query.
33/// The answer body is the list of received messages, up to the first whose type is in `done_types`.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
35pub struct SignalrExchange {
36 pub handshake: String,
37 pub invocations: Vec<String>,
38 #[serde(rename = "doneTypes")]
39 pub done_types: Vec<u8>,
40 #[serde(rename = "timeoutMs")]
41 pub timeout_ms: u64,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45pub struct AugloopStage {
46 pub send: Vec<String>,
47 #[serde(rename = "awaitMessageId")]
48 pub await_message_id: Option<String>,
49}
50
51/// An AugLoop conversation over a WebSocket opened in the page. Each stage is sent once the previous stage's
52/// awaited answer arrives; `placeholder` in a message becomes the token. The answer body is every received message,
53/// up to the first one containing `done_marker`.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
55pub struct AugloopExchange {
56 pub stages: Vec<AugloopStage>,
57 pub placeholder: String,
58 #[serde(rename = "doneMarker")]
59 pub done_marker: String,
60 #[serde(rename = "timeoutMs")]
61 pub timeout_ms: u64,
62 #[serde(rename = "keepaliveMs")]
63 pub keepalive_ms: u64,
64}
65
66#[derive(Debug, Clone)]
67pub struct Request {
68 pub method: Method,
69 pub url: String,
70 pub headers: Vec<(String, String)>,
71 pub body: Option<Value>,
72 pub binary: bool,
73 pub anonymous: bool,
74 pub body_base64: Option<String>,
75 pub body_tokens: Vec<BodyToken>,
76 pub signalr: Option<SignalrExchange>,
77 pub augloop: Option<AugloopExchange>,
78}
79
80impl Request {
81 pub fn augloop(url: impl Into<String>, exchange: AugloopExchange) -> Self {
82 Request {
83 augloop: Some(exchange),
84 ..Request::get(url)
85 }
86 }
87
88 pub fn signalr(url: impl Into<String>, exchange: SignalrExchange) -> Self {
89 Request {
90 signalr: Some(exchange),
91 ..Request::get(url)
92 }
93 }
94
95 /// A successful answer carries `{"base64": .., "contentType": ..}` as its body.
96 pub fn binary_get(url: impl Into<String>) -> Self {
97 Request {
98 binary: true,
99 ..Request::get(url)
100 }
101 }
102
103 pub fn get(url: impl Into<String>) -> Self {
104 Request {
105 method: Method::Get,
106 url: url.into(),
107 headers: Vec::new(),
108 body: None,
109 binary: false,
110 anonymous: false,
111 body_base64: None,
112 body_tokens: Vec::new(),
113 signalr: None,
114 augloop: None,
115 }
116 }
117
118 /// Replaces `placeholder` in the body with a token for `resource` inside the page, so the token never leaves it.
119 pub fn with_body_token(mut self, resource: &str, scope: &str, placeholder: &str) -> Self {
120 self.body_tokens.push(BodyToken {
121 resource: resource.to_owned(),
122 scope: scope.to_owned(),
123 placeholder: placeholder.to_owned(),
124 });
125 self
126 }
127
128 /// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.
129 pub fn anonymous_bytes(
130 method: Method,
131 url: impl Into<String>,
132 headers: Vec<(String, String)>,
133 body_base64: String,
134 ) -> Self {
135 Request {
136 method,
137 headers,
138 anonymous: true,
139 body_base64: Some(body_base64),
140 ..Request::get(url)
141 }
142 }
143
144 /// Sent without an Authorization header; a successful answer carries `{"base64": .., "contentType": ..}`.
145 pub fn anonymous_binary_get(url: impl Into<String>, headers: Vec<(String, String)>) -> Self {
146 Request {
147 headers,
148 anonymous: true,
149 ..Request::binary_get(url)
150 }
151 }
152
153 pub fn delete(url: impl Into<String>) -> Self {
154 Request {
155 method: Method::Delete,
156 ..Request::get(url)
157 }
158 }
159
160 pub fn with_body(method: Method, url: impl Into<String>, body: Value) -> Self {
161 Request {
162 method,
163 url: url.into(),
164 headers: Vec::new(),
165 body: Some(body),
166 binary: false,
167 anonymous: false,
168 body_base64: None,
169 body_tokens: Vec::new(),
170 signalr: None,
171 augloop: None,
172 }
173 }
174}
175
176#[derive(Debug, Clone)]
177pub struct ApiResponse {
178 pub status: u16,
179 pub body: Value,
180 pub retry_after: Option<String>,
181}
182
183impl ApiResponse {
184 pub fn is_success(&self) -> bool {
185 (200..400).contains(&self.status)
186 }
187}
188
189#[derive(Debug, Serialize)]
190pub(crate) struct WireRequest<'a> {
191 pub method: &'static str,
192 pub url: &'a str,
193 pub headers: serde_json::Map<String, Value>,
194 pub body: Option<String>,
195 #[serde(rename = "bodyBase64")]
196 pub body_base64: Option<&'a str>,
197 pub binary: bool,
198 pub anonymous: bool,
199 #[serde(rename = "bodyTokens")]
200 pub body_tokens: &'a [BodyToken],
201 pub signalr: Option<&'a SignalrExchange>,
202 pub augloop: Option<&'a AugloopExchange>,
203}
204
205impl<'a> From<&'a Request> for WireRequest<'a> {
206 fn from(request: &'a Request) -> Self {
207 let mut headers: serde_json::Map<String, Value> = request
208 .headers
209 .iter()
210 .map(|(name, value)| (name.clone(), Value::String(value.clone())))
211 .collect();
212 if request.body.is_some()
213 && !headers
214 .keys()
215 .any(|name| name.eq_ignore_ascii_case("content-type"))
216 {
217 headers.insert("Content-Type".into(), "application/json".into());
218 }
219 WireRequest {
220 method: request.method.as_str(),
221 url: &request.url,
222 headers,
223 body: request.body.as_ref().map(Value::to_string),
224 body_base64: request.body_base64.as_deref(),
225 binary: request.binary,
226 anonymous: request.anonymous,
227 body_tokens: &request.body_tokens,
228 signalr: request.signalr.as_ref(),
229 augloop: request.augloop.as_ref(),
230 }
231 }
232}
233
234#[derive(Debug, Deserialize)]
235pub(crate) struct WireResult {
236 pub status: u16,
237 #[serde(default)]
238 pub body: Value,
239 #[serde(default, rename = "retryAfter")]
240 pub retry_after: Option<String>,
241}
242
243#[derive(Debug, Deserialize)]
244pub(crate) struct Outcome {
245 pub results: Option<Vec<WireResult>>,
246 #[serde(default, rename = "refreshError")]
247 pub refresh_error: Option<String>,
248 #[serde(default)]
249 pub page: Option<PageState>,
250}
251
252/// What the page held when it had no token, to tell an unreadable cache apart from a missing sign-in.
253#[derive(Debug, Deserialize)]
254pub(crate) struct PageState {
255 pub visibility: String,
256 pub plain: usize,
257 pub sealed: usize,
258 #[serde(default)]
259 pub opened: usize,
260}
261
262impl std::fmt::Display for PageState {
263 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264 write!(
265 formatter,
266 "page {}, {} plain / {} sealed cache entries ({} opened)",
267 self.visibility, self.plain, self.sealed, self.opened
268 )
269 }
270}
271
272impl From<WireResult> for ApiResponse {
273 fn from(wire: WireResult) -> Self {
274 ApiResponse {
275 status: wire.status,
276 body: wire.body,
277 retry_after: wire.retry_after,
278 }
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use serde_json::json;
285
286 use super::*;
287
288 #[test]
289 fn json_body_gets_content_type() {
290 let request = Request::with_body(
291 Method::Post,
292 "https://graph.microsoft.com/v1.0/x",
293 json!({"a": 1}),
294 );
295 let wire = WireRequest::from(&request);
296 assert_eq!(wire.method, "POST");
297 assert_eq!(wire.body.as_deref(), Some(r#"{"a":1}"#));
298 assert_eq!(wire.headers["Content-Type"], "application/json");
299 }
300
301 #[test]
302 fn explicit_content_type_is_kept() {
303 let mut request = Request::with_body(Method::Post, "u", json!({}));
304 request
305 .headers
306 .push(("content-type".into(), "text/plain".into()));
307 let wire = WireRequest::from(&request);
308 assert_eq!(wire.headers.len(), 1);
309 }
310
311 #[test]
312 fn binary_get_is_flagged_on_the_wire() {
313 let request = Request::binary_get("u");
314 assert!(WireRequest::from(&request).binary);
315 assert!(!WireRequest::from(&Request::get("u")).binary);
316 }
317
318 #[test]
319 fn anonymous_bytes_travel_as_base64_without_a_content_type() {
320 let request = Request::anonymous_bytes(
321 Method::Put,
322 "https://upload.example/session",
323 vec![("Content-Range".into(), "bytes 0-2/3".into())],
324 "AQID".into(),
325 );
326 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
327 assert_eq!(wire["method"], "PUT");
328 assert_eq!(wire["anonymous"], true);
329 assert_eq!(wire["bodyBase64"], "AQID");
330 assert_eq!(wire["body"], Value::Null);
331 assert!(wire["headers"].get("Content-Type").is_none());
332 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
333 }
334
335 #[test]
336 fn anonymous_binary_get_keeps_range_header_and_flags() {
337 let request = Request::anonymous_binary_get(
338 "https://download.example/file",
339 vec![("Range".into(), "bytes=0-9".into())],
340 );
341 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
342 assert_eq!(wire["method"], "GET");
343 assert_eq!(wire["anonymous"], true);
344 assert_eq!(wire["binary"], true);
345 assert_eq!(wire["bodyBase64"], Value::Null);
346 assert_eq!(wire["headers"]["Range"], "bytes=0-9");
347 }
348
349 #[test]
350 fn body_tokens_travel_as_placeholders() {
351 let request = Request::with_body(Method::Post, "u", json!({"token": "@@t@@"}))
352 .with_body_token(
353 "https://api.spaces.skype.com",
354 "user_impersonation",
355 "@@t@@",
356 );
357 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
358 assert_eq!(
359 wire["bodyTokens"][0]["resource"],
360 "https://api.spaces.skype.com"
361 );
362 assert_eq!(wire["bodyTokens"][0]["placeholder"], "@@t@@");
363 assert_eq!(wire["body"], r#"{"token":"@@t@@"}"#);
364 }
365
366 #[test]
367 fn get_has_no_body() {
368 let request = Request::get("u");
369 let wire = WireRequest::from(&request);
370 assert!(wire.body.is_none() && wire.headers.is_empty());
371 }
372
373 #[test]
374 fn parses_results_outcome() {
375 let outcome: Outcome = serde_json::from_value(json!({
376 "results": [{"status": 200, "retryAfter": null, "body": {"value": []}}, {"status": 429, "retryAfter": "4", "body": "slow"}]
377 }))
378 .unwrap();
379 let responses: Vec<ApiResponse> = outcome
380 .results
381 .unwrap()
382 .into_iter()
383 .map(Into::into)
384 .collect();
385 assert_eq!(responses[0].status, 200);
386 assert_eq!(responses[1].retry_after.as_deref(), Some("4"));
387 assert!(!responses[1].is_success());
388 }
389
390 #[test]
391 fn parses_no_token_outcome() {
392 let outcome: Outcome =
393 serde_json::from_value(json!({"noToken": true, "refreshError": "invalid_grant"}))
394 .unwrap();
395 assert!(outcome.results.is_none());
396 assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant"));
397 }
398
399 #[test]
400 fn describes_the_page_state_of_a_no_token_outcome() {
401 let outcome: Outcome = serde_json::from_value(json!({
402 "noToken": true,
403 "page": {"visibility": "hidden", "plain": 3, "sealed": 40, "opened": 38},
404 }))
405 .unwrap();
406 assert_eq!(
407 outcome.page.unwrap().to_string(),
408 "page hidden, 3 plain / 40 sealed cache entries (38 opened)"
409 );
410 }
411}