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