-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
lib.rs
458 lines (383 loc) · 13.9 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
#![feature(async_closure)]
#![feature(error_generic_member_access)]
#![deny(clippy::all)]
use std::{backtrace::Backtrace, env};
use lazy_static::lazy_static;
use regex::Regex;
pub use reqwest::Response;
use reqwest::{Method, RequestBuilder, StatusCode};
use turborepo_ci::{is_ci, Vendor};
use turborepo_vercel_api::{
APIError, CachingStatus, CachingStatusResponse, PreflightResponse, SpacesResponse, Team,
TeamsResponse, UserResponse, VerificationResponse, VerifiedSsoUser,
};
use url::Url;
pub use crate::error::{Error, Result};
mod error;
mod retry;
lazy_static! {
static ref AUTHORIZATION_REGEX: Regex =
Regex::new(r"(?i)(?:^|,) *authorization *(?:,|$)").unwrap();
}
pub struct APIClient {
client: reqwest::Client,
base_url: String,
user_agent: String,
use_preflight: bool,
}
impl APIClient {
pub async fn get_user(&self, token: &str) -> Result<UserResponse> {
let url = self.make_url("/v2/user");
let request_builder = self
.client
.get(url)
.header("User-Agent", self.user_agent.clone())
.header("Authorization", format!("Bearer {}", token))
.header("Content-Type", "application/json");
let response = retry::make_retryable_request(request_builder)
.await?
.error_for_status()?;
Ok(response.json().await?)
}
pub async fn get_teams(&self, token: &str) -> Result<TeamsResponse> {
let request_builder = self
.client
.get(self.make_url("/v2/teams?limit=100"))
.header("User-Agent", self.user_agent.clone())
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", token));
let response = retry::make_retryable_request(request_builder)
.await?
.error_for_status()?;
Ok(response.json().await?)
}
pub async fn get_team(&self, token: &str, team_id: &str) -> Result<Option<Team>> {
let response = self
.client
.get(self.make_url("/v2/team"))
.query(&[("teamId", team_id)])
.header("User-Agent", self.user_agent.clone())
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", token))
.send()
.await?
.error_for_status()?;
Ok(response.json().await?)
}
fn add_ci_header(mut request_builder: RequestBuilder) -> RequestBuilder {
if is_ci() {
if let Some(vendor_constant) = Vendor::get_constant() {
request_builder = request_builder.header("x-artifact-client-ci", vendor_constant);
}
}
request_builder
}
fn add_team_params(
mut request_builder: RequestBuilder,
team_id: &str,
team_slug: Option<&str>,
) -> RequestBuilder {
if let Some(slug) = team_slug {
request_builder = request_builder.query(&[("teamSlug", slug)]);
}
if team_id.starts_with("team_") {
request_builder = request_builder.query(&[("teamId", team_id)]);
}
request_builder
}
pub async fn get_caching_status(
&self,
token: &str,
team_id: &str,
team_slug: Option<&str>,
) -> Result<CachingStatusResponse> {
let request_builder = self
.client
.get(self.make_url("/v8/artifacts/status"))
.header("User-Agent", self.user_agent.clone())
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", token));
let request_builder = Self::add_team_params(request_builder, team_id, team_slug);
let response = retry::make_retryable_request(request_builder)
.await?
.error_for_status()?;
Ok(response.json().await?)
}
pub async fn get_spaces(&self, token: &str, team_id: Option<&str>) -> Result<SpacesResponse> {
// create url with teamId if provided
let endpoint = match team_id {
Some(team_id) => format!("/v0/spaces?limit=100&teamId={}", team_id),
None => "/v0/spaces?limit=100".to_string(),
};
let request_builder = self
.client
.get(self.make_url(endpoint.as_str()))
.header("User-Agent", self.user_agent.clone())
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", token));
let response = retry::make_retryable_request(request_builder)
.await?
.error_for_status()?;
Ok(response.json().await?)
}
pub async fn verify_sso_token(&self, token: &str, token_name: &str) -> Result<VerifiedSsoUser> {
let request_builder = self
.client
.get(self.make_url("/registration/verify"))
.query(&[("token", token), ("tokenName", token_name)])
.header("User-Agent", self.user_agent.clone());
let response = retry::make_retryable_request(request_builder)
.await?
.error_for_status()?;
let verification_response: VerificationResponse = response.json().await?;
Ok(VerifiedSsoUser {
token: verification_response.token,
team_id: verification_response.team_id,
})
}
pub async fn put_artifact(
&self,
hash: &str,
artifact_body: &[u8],
duration: u64,
tag: Option<&str>,
token: &str,
) -> Result<()> {
let mut request_url = self.make_url(&format!("/v8/artifacts/{}", hash));
let mut allow_auth = true;
if self.use_preflight {
let preflight_response = self
.do_preflight(
token,
&request_url,
"PUT",
"Authorization, Content-Type, User-Agent, x-artifact-duration, x-artifact-tag",
)
.await?;
allow_auth = preflight_response.allow_authorization_header;
request_url = preflight_response.location.to_string();
}
let mut request_builder = self
.client
.put(&request_url)
.header("Content-Type", "application/octet-stream")
.header("x-artifact-duration", duration.to_string())
.header("User-Agent", self.user_agent.clone())
.body(artifact_body.to_vec());
if allow_auth {
request_builder = request_builder.header("Authorization", format!("Bearer {}", token));
}
request_builder = Self::add_ci_header(request_builder);
if let Some(tag) = tag {
request_builder = request_builder.header("x-artifact-tag", tag);
}
let response = retry::make_retryable_request(request_builder).await?;
if response.status() == StatusCode::FORBIDDEN {
return Err(Self::handle_403(response).await);
}
response.error_for_status()?;
Ok(())
}
async fn handle_403(response: Response) -> Error {
let api_error: APIError = match response.json().await {
Ok(api_error) => api_error,
Err(e) => return Error::ReqwestError(e),
};
if let Some(status_string) = api_error.code.strip_prefix("remote_caching_") {
let status = match status_string {
"disabled" => CachingStatus::Disabled,
"enabled" => CachingStatus::Enabled,
"over_limit" => CachingStatus::OverLimit,
"paused" => CachingStatus::Paused,
_ => {
return Error::UnknownCachingStatus(
status_string.to_string(),
Backtrace::capture(),
)
}
};
Error::CacheDisabled {
status,
message: api_error.message,
}
} else {
Error::UnknownStatus {
code: api_error.code,
message: api_error.message,
backtrace: Backtrace::capture(),
}
}
}
pub async fn fetch_artifact(
&self,
hash: &str,
token: &str,
team_id: &str,
team_slug: Option<&str>,
) -> Result<Response> {
self.get_artifact(hash, token, team_id, team_slug, Method::GET)
.await
}
pub async fn artifact_exists(
&self,
hash: &str,
token: &str,
team_id: &str,
team_slug: Option<&str>,
) -> Result<Response> {
self.get_artifact(hash, token, team_id, team_slug, Method::HEAD)
.await
}
async fn get_artifact(
&self,
hash: &str,
token: &str,
team_id: &str,
team_slug: Option<&str>,
method: Method,
) -> Result<Response> {
let mut request_url = self.make_url(&format!("/v8/artifacts/{}", hash));
let mut allow_auth = true;
if self.use_preflight {
let preflight_response = self
.do_preflight(token, &request_url, "GET", "Authorization, User-Agent")
.await?;
allow_auth = preflight_response.allow_authorization_header;
request_url = preflight_response.location.to_string();
};
let mut request_builder = self
.client
.request(method, request_url)
.header("User-Agent", self.user_agent.clone());
if allow_auth {
request_builder = request_builder.header("Authorization", format!("Bearer {}", token));
}
request_builder = Self::add_team_params(request_builder, team_id, team_slug);
let response = retry::make_retryable_request(request_builder).await?;
if response.status() == StatusCode::FORBIDDEN {
Err(Self::handle_403(response).await)
} else {
Ok(response.error_for_status()?)
}
}
pub async fn do_preflight(
&self,
token: &str,
request_url: &str,
request_method: &str,
request_headers: &str,
) -> Result<PreflightResponse> {
let request_builder = self
.client
.request(Method::OPTIONS, request_url)
.header("User-Agent", self.user_agent.clone())
.header("Access-Control-Request-Method", request_method)
.header("Access-Control-Request-Headers", request_headers)
.header("Authorization", format!("Bearer {}", token));
let response = retry::make_retryable_request(request_builder).await?;
let headers = response.headers();
let location = if let Some(location) = headers.get("Location") {
let location = location.to_str()?;
match Url::parse(location) {
Ok(location_url) => location_url,
Err(url::ParseError::RelativeUrlWithoutBase) => {
Url::parse(&self.base_url)?.join(location)?
}
Err(e) => return Err(e.into()),
}
} else {
response.url().clone()
};
let allowed_headers = headers
.get("Access-Control-Allow-Headers")
.map_or("", |h| h.to_str().unwrap_or(""));
let allow_auth = AUTHORIZATION_REGEX.is_match(allowed_headers);
Ok(PreflightResponse {
location,
allow_authorization_header: allow_auth,
})
}
pub fn new(
base_url: impl AsRef<str>,
timeout: u64,
version: &str,
use_preflight: bool,
) -> Result<Self> {
let client = if timeout != 0 {
reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(timeout))
.build()?
} else {
reqwest::Client::builder().build()?
};
let user_agent = format!(
"turbo {} {} {} {}",
version,
rustc_version_runtime::version(),
env::consts::OS,
env::consts::ARCH
);
Ok(APIClient {
client,
base_url: base_url.as_ref().to_string(),
user_agent,
use_preflight,
})
}
fn make_url(&self, endpoint: &str) -> String {
format!("{}{}", self.base_url, endpoint)
}
}
#[cfg(test)]
mod test {
use anyhow::Result;
use turborepo_vercel_api_mock::start_test_server;
use crate::APIClient;
#[tokio::test]
async fn test_do_preflight() -> Result<()> {
let port = port_scanner::request_open_port().unwrap();
let handle = tokio::spawn(start_test_server(port));
let base_url = format!("http://localhost:{}", port);
let client = APIClient::new(&base_url, 200, "2.0.0", true)?;
let response = client
.do_preflight(
"",
&format!("{}/preflight/absolute-location", base_url),
"GET",
"Authorization, User-Agent",
)
.await;
assert!(response.is_ok());
let response = client
.do_preflight(
"",
&format!("{}/preflight/relative-location", base_url),
"GET",
"Authorization, User-Agent",
)
.await;
// Since PreflightResponse returns a Url,
// do_preflight would error if the Url is relative
assert!(response.is_ok());
let response = client
.do_preflight(
"",
&format!("{}/preflight/allow-auth", base_url),
"GET",
"Authorization, User-Agent",
)
.await?;
assert!(response.allow_authorization_header);
let response = client
.do_preflight(
"",
&format!("{}/preflight/no-allow-auth", base_url),
"GET",
"Authorization, User-Agent",
)
.await?;
assert!(!response.allow_authorization_header);
handle.abort();
Ok(())
}
}