| 1 | use serde::{Deserialize, Serialize}; |
| 2 | use serde_json::Value; |
| 3 | |
| 4 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 5 | pub enum Method { |
| 6 | Get, |
| 7 | Post, |
| 8 | Put, |
| 9 | Patch, |
| 10 | Delete, |
| 11 | } |
| 12 | |
| 13 | impl 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)] |
| 26 | pub struct BodyToken { |
| 27 | pub resource: String, |
| 28 | pub scope: String, |
| 29 | pub placeholder: String, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone)] |
| 33 | pub 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 | |
| 44 | impl 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)] |
| 118 | pub struct ApiResponse { |
| 119 | pub status: u16, |
| 120 | pub body: Value, |
| 121 | pub retry_after: Option<String>, |
| 122 | } |
| 123 | |
| 124 | impl ApiResponse { |
| 125 | pub fn is_success(&self) -> bool { |
| 126 | (200..400).contains(&self.status) |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | #[derive(Debug, Serialize)] |
| 131 | pub(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 | |
| 144 | impl<'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)] |
| 168 | pub(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)] |
| 177 | pub(crate) struct Outcome { |
| 178 | pub results: Option<Vec<WireResult>>, |
| 179 | #[serde(default, rename = "refreshError")] |
| 180 | pub refresh_error: Option<String>, |
| 181 | #[serde(default)] |
| 182 | pub page: Option<PageState>, |
| 183 | } |
| 184 | |
| 185 | /// What the page held when it had no token, to tell an unreadable cache apart from a missing sign-in. |
| 186 | #[derive(Debug, Deserialize)] |
| 187 | pub(crate) struct PageState { |
| 188 | pub visibility: String, |
| 189 | pub plain: usize, |
| 190 | pub sealed: usize, |
| 191 | #[serde(default)] |
| 192 | pub opened: usize, |
| 193 | } |
| 194 | |
| 195 | impl std::fmt::Display for PageState { |
| 196 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 197 | write!( |
| 198 | formatter, |
| 199 | "page {}, {} plain / {} sealed cache entries ({} opened)", |
| 200 | self.visibility, self.plain, self.sealed, self.opened |
| 201 | ) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | impl From<WireResult> for ApiResponse { |
| 206 | fn from(wire: WireResult) -> Self { |
| 207 | ApiResponse { |
| 208 | status: wire.status, |
| 209 | body: wire.body, |
| 210 | retry_after: wire.retry_after, |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | #[cfg(test)] |
| 216 | mod tests { |
| 217 | use serde_json::json; |
| 218 | |
| 219 | use super::*; |
| 220 | |
| 221 | #[test] |
| 222 | fn json_body_gets_content_type() { |
| 223 | let request = Request::with_body(Method::Post, "https://graph.microsoft.com/v1.0/x", json!({"a": 1})); |
| 224 | let wire = WireRequest::from(&request); |
| 225 | assert_eq!(wire.method, "POST"); |
| 226 | assert_eq!(wire.body.as_deref(), Some(r#"{"a":1}"#)); |
| 227 | assert_eq!(wire.headers["Content-Type"], "application/json"); |
| 228 | } |
| 229 | |
| 230 | #[test] |
| 231 | fn explicit_content_type_is_kept() { |
| 232 | let mut request = Request::with_body(Method::Post, "u", json!({})); |
| 233 | request.headers.push(("content-type".into(), "text/plain".into())); |
| 234 | let wire = WireRequest::from(&request); |
| 235 | assert_eq!(wire.headers.len(), 1); |
| 236 | } |
| 237 | |
| 238 | #[test] |
| 239 | fn binary_get_is_flagged_on_the_wire() { |
| 240 | let request = Request::binary_get("u"); |
| 241 | assert!(WireRequest::from(&request).binary); |
| 242 | assert!(!WireRequest::from(&Request::get("u")).binary); |
| 243 | } |
| 244 | |
| 245 | #[test] |
| 246 | fn anonymous_bytes_travel_as_base64_without_a_content_type() { |
| 247 | let request = Request::anonymous_bytes( |
| 248 | Method::Put, |
| 249 | "https://upload.example/session", |
| 250 | vec![("Content-Range".into(), "bytes 0-2/3".into())], |
| 251 | "AQID".into(), |
| 252 | ); |
| 253 | let wire = serde_json::to_value(WireRequest::from(&request)).unwrap(); |
| 254 | assert_eq!(wire["method"], "PUT"); |
| 255 | assert_eq!(wire["anonymous"], true); |
| 256 | assert_eq!(wire["bodyBase64"], "AQID"); |
| 257 | assert_eq!(wire["body"], Value::Null); |
| 258 | assert!(wire["headers"].get("Content-Type").is_none()); |
| 259 | assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3"); |
| 260 | } |
| 261 | |
| 262 | #[test] |
| 263 | fn anonymous_binary_get_keeps_range_header_and_flags() { |
| 264 | let request = Request::anonymous_binary_get("https://download.example/file", vec![("Range".into(), "bytes=0-9".into())]); |
| 265 | let wire = serde_json::to_value(WireRequest::from(&request)).unwrap(); |
| 266 | assert_eq!(wire["method"], "GET"); |
| 267 | assert_eq!(wire["anonymous"], true); |
| 268 | assert_eq!(wire["binary"], true); |
| 269 | assert_eq!(wire["bodyBase64"], Value::Null); |
| 270 | assert_eq!(wire["headers"]["Range"], "bytes=0-9"); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn body_tokens_travel_as_placeholders() { |
| 275 | let request = Request::with_body(Method::Post, "u", json!({"token": "@@t@@"})) |
| 276 | .with_body_token( |
| 277 | "https://api.spaces.skype.com", |
| 278 | "user_impersonation", |
| 279 | "@@t@@", |
| 280 | ); |
| 281 | let wire = serde_json::to_value(WireRequest::from(&request)).unwrap(); |
| 282 | assert_eq!( |
| 283 | wire["bodyTokens"][0]["resource"], |
| 284 | "https://api.spaces.skype.com" |
| 285 | ); |
| 286 | assert_eq!(wire["bodyTokens"][0]["placeholder"], "@@t@@"); |
| 287 | assert_eq!(wire["body"], r#"{"token":"@@t@@"}"#); |
| 288 | } |
| 289 | |
| 290 | #[test] |
| 291 | fn get_has_no_body() { |
| 292 | let request = Request::get("u"); |
| 293 | let wire = WireRequest::from(&request); |
| 294 | assert!(wire.body.is_none() && wire.headers.is_empty()); |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn parses_results_outcome() { |
| 299 | let outcome: Outcome = serde_json::from_value(json!({ |
| 300 | "results": [{"status": 200, "retryAfter": null, "body": {"value": []}}, {"status": 429, "retryAfter": "4", "body": "slow"}] |
| 301 | })) |
| 302 | .unwrap(); |
| 303 | let responses: Vec<ApiResponse> = outcome.results.unwrap().into_iter().map(Into::into).collect(); |
| 304 | assert_eq!(responses[0].status, 200); |
| 305 | assert_eq!(responses[1].retry_after.as_deref(), Some("4")); |
| 306 | assert!(!responses[1].is_success()); |
| 307 | } |
| 308 | |
| 309 | #[test] |
| 310 | fn parses_no_token_outcome() { |
| 311 | let outcome: Outcome = |
| 312 | serde_json::from_value(json!({"noToken": true, "refreshError": "invalid_grant"})).unwrap(); |
| 313 | assert!(outcome.results.is_none()); |
| 314 | assert_eq!(outcome.refresh_error.as_deref(), Some("invalid_grant")); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn describes_the_page_state_of_a_no_token_outcome() { |
| 319 | let outcome: Outcome = serde_json::from_value(json!({ |
| 320 | "noToken": true, |
| 321 | "page": {"visibility": "hidden", "plain": 3, "sealed": 40, "opened": 38}, |
| 322 | })) |
| 323 | .unwrap(); |
| 324 | assert_eq!( |
| 325 | outcome.page.unwrap().to_string(), |
| 326 | "page hidden, 3 plain / 40 sealed cache entries (38 opened)" |
| 327 | ); |
| 328 | } |
| 329 | } |