BlueGit

ict rusty-teams

Files

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

request.rs

request.rs 9.0 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#[derive(Debug, Clone)]
33pub struct Request {
34 pub method: Method,
35 pub url: String,
36 pub headers: Vec<(String, String)>,
37 pub body: Option<Value>,
38 pub binary: bool,
39 pub anonymous: bool,
40 pub body_base64: Option<String>,
41 pub body_tokens: Vec<BodyToken>,
42}
43
44impl Request {
45 /// A successful answer carries `{"base64": .., "contentType": ..}` as its body.
46 pub fn binary_get(url: impl Into<String>) -> Self {
47 Request {
48 binary: true,
49 ..Request::get(url)
50 }
51 }
52
53 pub fn get(url: impl Into<String>) -> Self {
54 Request {
55 method: Method::Get,
56 url: url.into(),
57 headers: Vec::new(),
58 body: None,
59 binary: false,
60 anonymous: false,
61 body_base64: None,
62 body_tokens: Vec::new(),
63 }
64 }
65
66 /// Replaces `placeholder` in the body with a token for `resource` inside the page, so the token never leaves it.
67 pub fn with_body_token(mut self, resource: &str, scope: &str, placeholder: &str) -> Self {
68 self.body_tokens.push(BodyToken {
69 resource: resource.to_owned(),
70 scope: scope.to_owned(),
71 placeholder: placeholder.to_owned(),
72 });
73 self
74 }
75
76 /// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.
77 pub fn anonymous_bytes(method: Method, url: impl Into<String>, headers: Vec<(String, String)>, body_base64: String) -> Self {
78 Request {
79 method,
80 headers,
81 anonymous: true,
82 body_base64: Some(body_base64),
83 ..Request::get(url)
84 }
85 }
86
87 /// Sent without an Authorization header; a successful answer carries `{"base64": .., "contentType": ..}`.
88 pub fn anonymous_binary_get(url: impl Into<String>, headers: Vec<(String, String)>) -> Self {
89 Request {
90 headers,
91 anonymous: true,
92 ..Request::binary_get(url)
93 }
94 }
95
96 pub fn delete(url: impl Into<String>) -> Self {
97 Request {
98 method: Method::Delete,
99 ..Request::get(url)
100 }
101 }
102
103 pub fn with_body(method: Method, url: impl Into<String>, body: Value) -> Self {
104 Request {
105 method,
106 url: url.into(),
107 headers: Vec::new(),
108 body: Some(body),
109 binary: false,
110 anonymous: false,
111 body_base64: None,
112 body_tokens: Vec::new(),
113 }
114 }
115}
116
117#[derive(Debug, Clone)]
118pub struct ApiResponse {
119 pub status: u16,
120 pub body: Value,
121 pub retry_after: Option<String>,
122}
123
124impl ApiResponse {
125 pub fn is_success(&self) -> bool {
126 (200..400).contains(&self.status)
127 }
128}
129
130#[derive(Debug, Serialize)]
131pub(crate) struct WireRequest<'a> {
132 pub method: &'static str,
133 pub url: &'a str,
134 pub headers: serde_json::Map<String, Value>,
135 pub body: Option<String>,
136 #[serde(rename = "bodyBase64")]
137 pub body_base64: Option<&'a str>,
138 pub binary: bool,
139 pub anonymous: bool,
140 #[serde(rename = "bodyTokens")]
141 pub body_tokens: &'a [BodyToken],
142}
143
144impl<'a> From<&'a Request> for WireRequest<'a> {
145 fn from(request: &'a Request) -> Self {
146 let mut headers: serde_json::Map<String, Value> = request
147 .headers
148 .iter()
149 .map(|(name, value)| (name.clone(), Value::String(value.clone())))
150 .collect();
151 if request.body.is_some() && !headers.keys().any(|name| name.eq_ignore_ascii_case("content-type")) {
152 headers.insert("Content-Type".into(), "application/json".into());
153 }
154 WireRequest {
155 method: request.method.as_str(),
156 url: &request.url,
157 headers,
158 body: request.body.as_ref().map(Value::to_string),
159 body_base64: request.body_base64.as_deref(),
160 binary: request.binary,
161 anonymous: request.anonymous,
162 body_tokens: &request.body_tokens,
163 }
164 }
165}
166
167#[derive(Debug, Deserialize)]
168pub(crate) struct WireResult {
169 pub status: u16,
170 #[serde(default)]
171 pub body: Value,
172 #[serde(default, rename = "retryAfter")]
173 pub retry_after: Option<String>,
174}
175
176#[derive(Debug, Deserialize)]
177pub(crate) struct Outcome {
178 pub results: Option<Vec<WireResult>>,
179 #[serde(default, rename = "refreshError")]
180 pub refresh_error: Option<String>,
181}
182
183impl From<WireResult> for ApiResponse {
184 fn from(wire: WireResult) -> Self {
185 ApiResponse {
186 status: wire.status,
187 body: wire.body,
188 retry_after: wire.retry_after,
189 }
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use serde_json::json;
196
197 use super::*;
198
199 #[test]
200 fn json_body_gets_content_type() {
201 let request = Request::with_body(Method::Post, "https://graph.microsoft.com/v1.0/x", json!({"a": 1}));
202 let wire = WireRequest::from(&request);
203 assert_eq!(wire.method, "POST");
204 assert_eq!(wire.body.as_deref(), Some(r#"{"a":1}"#));
205 assert_eq!(wire.headers["Content-Type"], "application/json");
206 }
207
208 #[test]
209 fn explicit_content_type_is_kept() {
210 let mut request = Request::with_body(Method::Post, "u", json!({}));
211 request.headers.push(("content-type".into(), "text/plain".into()));
212 let wire = WireRequest::from(&request);
213 assert_eq!(wire.headers.len(), 1);
214 }
215
216 #[test]
217 fn binary_get_is_flagged_on_the_wire() {
218 let request = Request::binary_get("u");
219 assert!(WireRequest::from(&request).binary);
220 assert!(!WireRequest::from(&Request::get("u")).binary);
221 }
222
223 #[test]
224 fn anonymous_bytes_travel_as_base64_without_a_content_type() {
225 let request = Request::anonymous_bytes(
226 Method::Put,
227 "https://upload.example/session",
228 vec![("Content-Range".into(), "bytes 0-2/3".into())],
229 "AQID".into(),
230 );
231 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
232 assert_eq!(wire["method"], "PUT");
233 assert_eq!(wire["anonymous"], true);
234 assert_eq!(wire["bodyBase64"], "AQID");
235 assert_eq!(wire["body"], Value::Null);
236 assert!(wire["headers"].get("Content-Type").is_none());
237 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
238 }
239
240 #[test]
241 fn anonymous_binary_get_keeps_range_header_and_flags() {
242 let request = Request::anonymous_binary_get("https://download.example/file", vec![("Range".into(), "bytes=0-9".into())]);
243 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
244 assert_eq!(wire["method"], "GET");
245 assert_eq!(wire["anonymous"], true);
246 assert_eq!(wire["binary"], true);
247 assert_eq!(wire["bodyBase64"], Value::Null);
248 assert_eq!(wire["headers"]["Range"], "bytes=0-9");
249 }
250
251 #[test]
252 fn body_tokens_travel_as_placeholders() {
253 let request = Request::with_body(Method::Post, "u", json!({"token": "@@t@@"}))
254 .with_body_token(
255 "https://api.spaces.skype.com",
256 "user_impersonation",
257 "@@t@@",
258 );
259 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
260 assert_eq!(
261 wire["bodyTokens"][0]["resource"],
262 "https://api.spaces.skype.com"
263 );
264 assert_eq!(wire["bodyTokens"][0]["placeholder"], "@@t@@");
265 assert_eq!(wire["body"], r#"{"token":"@@t@@"}"#);
266 }
267
268 #[test]
269 fn get_has_no_body() {
270 let request = Request::get("u");
271 let wire = WireRequest::from(&request);
272 assert!(wire.body.is_none() && wire.headers.is_empty());
273 }
274
275 #[test]
276 fn parses_results_outcome() {
277 let outcome: Outcome = serde_json::from_value(json!({
278 "results": [{"status": 200, "retryAfter": null, "body": {"value": []}}, {"status": 429, "retryAfter": "4", "body": "slow"}]
279 }))
280 .unwrap();
281 let responses: Vec<ApiResponse> = outcome.results.unwrap().into_iter().map(Into::into).collect();
282 assert_eq!(responses[0].status, 200);
283 assert_eq!(responses[1].retry_after.as_deref(), Some("4"));
284 assert!(!responses[1].is_success());
285 }
286
287 #[test]
288 fn parses_no_token_outcome() {
289 let outcome: Outcome =
290 serde_json::from_value(json!({"noToken": true, "refreshError": "invalid_grant"})).unwrap();
291 assert!(outcome.results.is_none());
292 assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant"));
293 }
294}