2017-10-02 10:04:02 +00:00
|
|
|
use std::collections::BTreeMap;
|
2016-04-02 01:06:20 +00:00
|
|
|
use std::fs::File;
|
2015-02-27 01:04:25 +00:00
|
|
|
use std::io::prelude::*;
|
2020-12-05 22:10:29 +00:00
|
|
|
use std::io::{Cursor, SeekFrom};
|
2019-05-13 20:18:42 +00:00
|
|
|
use std::time::Instant;
|
2014-09-27 04:14:46 +00:00
|
|
|
|
2020-01-08 03:58:45 +00:00
|
|
|
use curl::easy::{Easy, List};
|
2019-07-24 14:42:14 +00:00
|
|
|
use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
|
2018-12-12 21:20:44 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
2019-05-14 16:20:54 +00:00
|
|
|
use url::Url;
|
2016-03-07 08:19:40 +00:00
|
|
|
|
2023-06-25 08:42:26 +00:00
|
|
|
pub type Result<T> = std::result::Result<T, Error>;
|
|
|
|
|
2014-09-27 04:14:46 +00:00
|
|
|
pub struct Registry {
|
2018-12-20 01:40:01 +00:00
|
|
|
/// The base URL for issuing API requests.
|
2014-09-27 04:14:46 +00:00
|
|
|
host: String,
|
2018-12-20 01:40:01 +00:00
|
|
|
/// Optional authorization token.
|
|
|
|
/// If None, commands requiring authorization will fail.
|
2014-11-22 14:36:14 +00:00
|
|
|
token: Option<String>,
|
2018-12-20 01:40:01 +00:00
|
|
|
/// Curl handle for issuing requests.
|
2016-05-18 17:01:40 +00:00
|
|
|
handle: Easy,
|
2022-10-31 16:44:01 +00:00
|
|
|
/// Whether to include the authorization token with all requests.
|
|
|
|
auth_required: bool,
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
|
|
|
|
2015-04-05 07:00:01 +00:00
|
|
|
#[derive(PartialEq, Clone, Copy)]
|
2014-11-22 14:36:14 +00:00
|
|
|
pub enum Auth {
|
|
|
|
Authorized,
|
2014-09-27 04:14:46 +00:00
|
|
|
Unauthorized,
|
2016-05-18 17:01:40 +00:00
|
|
|
}
|
|
|
|
|
2017-02-10 20:01:52 +00:00
|
|
|
#[derive(Deserialize)]
|
2014-11-22 14:36:14 +00:00
|
|
|
pub struct Crate {
|
|
|
|
pub name: String,
|
|
|
|
pub description: Option<String>,
|
2017-05-24 04:35:54 +00:00
|
|
|
pub max_version: String,
|
2014-11-22 14:36:14 +00:00
|
|
|
}
|
|
|
|
|
2023-10-06 12:03:48 +00:00
|
|
|
/// This struct is serialized as JSON and sent as metadata ahead of the crate
|
|
|
|
/// tarball when publishing crates to a crate registry like crates.io.
|
|
|
|
///
|
|
|
|
/// see <https://doc.rust-lang.org/cargo/reference/registry-web-api.html#publish>
|
2022-09-22 16:00:49 +00:00
|
|
|
#[derive(Serialize, Deserialize)]
|
2014-09-27 04:14:46 +00:00
|
|
|
pub struct NewCrate {
|
|
|
|
pub name: String,
|
|
|
|
pub vers: String,
|
|
|
|
pub deps: Vec<NewCrateDependency>,
|
2017-10-02 10:04:02 +00:00
|
|
|
pub features: BTreeMap<String, Vec<String>>,
|
2014-09-27 04:14:46 +00:00
|
|
|
pub authors: Vec<String>,
|
|
|
|
pub description: Option<String>,
|
|
|
|
pub documentation: Option<String>,
|
|
|
|
pub homepage: Option<String>,
|
|
|
|
pub readme: Option<String>,
|
2017-10-17 05:04:33 +00:00
|
|
|
pub readme_file: Option<String>,
|
2014-09-27 04:14:46 +00:00
|
|
|
pub keywords: Vec<String>,
|
2016-11-18 21:49:55 +00:00
|
|
|
pub categories: Vec<String>,
|
2014-09-27 04:14:46 +00:00
|
|
|
pub license: Option<String>,
|
2014-11-25 06:18:54 +00:00
|
|
|
pub license_file: Option<String>,
|
2014-09-27 04:14:46 +00:00
|
|
|
pub repository: Option<String>,
|
2017-10-02 10:04:02 +00:00
|
|
|
pub badges: BTreeMap<String, BTreeMap<String, String>>,
|
2018-12-20 01:40:01 +00:00
|
|
|
pub links: Option<String>,
|
2023-03-24 20:46:59 +00:00
|
|
|
pub rust_version: Option<String>,
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
|
|
|
|
2022-09-22 16:00:49 +00:00
|
|
|
#[derive(Serialize, Deserialize)]
|
2014-09-27 04:14:46 +00:00
|
|
|
pub struct NewCrateDependency {
|
|
|
|
pub optional: bool,
|
|
|
|
pub default_features: bool,
|
|
|
|
pub name: String,
|
|
|
|
pub features: Vec<String>,
|
|
|
|
pub version_req: String,
|
|
|
|
pub target: Option<String>,
|
2014-11-21 02:17:31 +00:00
|
|
|
pub kind: String,
|
2018-09-07 16:37:06 +00:00
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
|
|
pub registry: Option<String>,
|
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
|
|
pub explicit_name_in_toml: Option<String>,
|
2023-07-30 17:52:22 +00:00
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
|
|
pub artifact: Option<Vec<String>>,
|
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
|
|
pub bindep_target: Option<String>,
|
|
|
|
#[serde(default, skip_serializing_if = "is_false")]
|
|
|
|
pub lib: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_false(x: &bool) -> bool {
|
|
|
|
*x == false
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
|
|
|
|
2017-02-10 20:01:52 +00:00
|
|
|
#[derive(Deserialize)]
|
2014-11-13 06:15:41 +00:00
|
|
|
pub struct User {
|
2015-01-13 16:41:04 +00:00
|
|
|
pub id: u32,
|
2014-11-13 06:15:41 +00:00
|
|
|
pub login: String,
|
2015-08-05 18:33:56 +00:00
|
|
|
pub avatar: Option<String>,
|
2014-11-13 06:15:41 +00:00
|
|
|
pub email: Option<String>,
|
|
|
|
pub name: Option<String>,
|
|
|
|
}
|
|
|
|
|
2016-12-05 17:36:44 +00:00
|
|
|
pub struct Warnings {
|
|
|
|
pub invalid_categories: Vec<String>,
|
2017-01-01 20:14:34 +00:00
|
|
|
pub invalid_badges: Vec<String>,
|
2018-10-31 12:34:04 +00:00
|
|
|
pub other: Vec<String>,
|
2016-12-05 17:36:44 +00:00
|
|
|
}
|
|
|
|
|
2018-03-14 15:17:44 +00:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct R {
|
|
|
|
ok: bool,
|
|
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct OwnerResponse {
|
|
|
|
ok: bool,
|
|
|
|
msg: String,
|
|
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct ApiErrorList {
|
|
|
|
errors: Vec<ApiError>,
|
|
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct ApiError {
|
|
|
|
detail: String,
|
|
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
|
|
struct OwnersReq<'a> {
|
|
|
|
users: &'a [&'a str],
|
|
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Users {
|
|
|
|
users: Vec<User>,
|
|
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct TotalCrates {
|
|
|
|
total: u32,
|
|
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Crates {
|
|
|
|
crates: Vec<Crate>,
|
|
|
|
meta: TotalCrates,
|
|
|
|
}
|
2021-01-28 20:39:51 +00:00
|
|
|
|
2023-06-25 09:58:35 +00:00
|
|
|
/// Error returned when interacting with a registry.
|
2023-06-25 13:27:58 +00:00
|
|
|
#[derive(Debug, thiserror::Error)]
|
2023-07-06 12:36:23 +00:00
|
|
|
pub enum Error {
|
2023-06-25 09:58:35 +00:00
|
|
|
/// Error from libcurl.
|
2023-06-25 13:27:58 +00:00
|
|
|
#[error(transparent)]
|
|
|
|
Curl(#[from] curl::Error),
|
2023-06-25 09:58:35 +00:00
|
|
|
|
2023-09-19 20:28:38 +00:00
|
|
|
/// Error from seriailzing the request payload and deserializing the
|
2023-06-25 09:58:35 +00:00
|
|
|
/// response body (like response body didn't match expected structure).
|
2023-06-25 13:27:58 +00:00
|
|
|
#[error(transparent)]
|
|
|
|
Json(#[from] serde_json::Error),
|
2023-06-25 09:58:35 +00:00
|
|
|
|
|
|
|
/// Error from IO. Mostly from reading the tarball to upload.
|
2023-06-25 13:27:58 +00:00
|
|
|
#[error("failed to seek tarball")]
|
|
|
|
Io(#[from] std::io::Error),
|
2023-06-25 09:58:35 +00:00
|
|
|
|
|
|
|
/// Response body was not valid utf8.
|
2023-06-25 13:27:58 +00:00
|
|
|
#[error("invalid response body from server")]
|
|
|
|
Utf8(#[from] std::string::FromUtf8Error),
|
2023-06-25 09:58:35 +00:00
|
|
|
|
|
|
|
/// Error from API response containing JSON field `errors.details`.
|
2023-06-25 13:27:58 +00:00
|
|
|
#[error(
|
|
|
|
"the remote server responded with an error{}: {}",
|
|
|
|
status(*code),
|
|
|
|
errors.join(", "),
|
|
|
|
)]
|
2021-01-28 20:39:51 +00:00
|
|
|
Api {
|
|
|
|
code: u32,
|
2023-07-06 10:55:02 +00:00
|
|
|
headers: Vec<String>,
|
2021-01-28 20:39:51 +00:00
|
|
|
errors: Vec<String>,
|
|
|
|
},
|
2023-06-25 09:58:35 +00:00
|
|
|
|
|
|
|
/// Error from API response which didn't have pre-programmed `errors.details`.
|
2023-06-25 13:27:58 +00:00
|
|
|
#[error(
|
|
|
|
"failed to get a 200 OK response, got {code}\nheaders:\n\t{}\nbody:\n{body}",
|
|
|
|
headers.join("\n\t"),
|
|
|
|
)]
|
2021-01-28 20:39:51 +00:00
|
|
|
Code {
|
|
|
|
code: u32,
|
|
|
|
headers: Vec<String>,
|
|
|
|
body: String,
|
|
|
|
},
|
2023-06-25 09:58:35 +00:00
|
|
|
|
|
|
|
/// Reason why the token was invalid.
|
2023-06-25 13:27:58 +00:00
|
|
|
#[error("{0}")]
|
2023-06-25 09:58:35 +00:00
|
|
|
InvalidToken(&'static str),
|
|
|
|
|
|
|
|
/// Server was unavailable and timeouted. Happened when uploading a way
|
|
|
|
/// too large tarball to crates.io.
|
2023-06-25 13:27:58 +00:00
|
|
|
#[error(
|
|
|
|
"Request timed out after 30 seconds. If you're trying to \
|
|
|
|
upload a crate it may be too large. If the crate is under \
|
|
|
|
10MB in size, you can email help@crates.io for assistance.\n\
|
|
|
|
Total size was {0}."
|
|
|
|
)]
|
2023-06-25 09:58:35 +00:00
|
|
|
Timeout(u64),
|
2021-01-28 20:39:51 +00:00
|
|
|
}
|
|
|
|
|
2014-09-27 04:14:46 +00:00
|
|
|
impl Registry {
|
2021-01-22 19:06:51 +00:00
|
|
|
/// Creates a new `Registry`.
|
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use curl::easy::Easy;
|
|
|
|
/// use crates_io::Registry;
|
|
|
|
///
|
|
|
|
/// let mut handle = Easy::new();
|
|
|
|
/// // If connecting to crates.io, a user-agent is required.
|
|
|
|
/// handle.useragent("my_crawler (example.com/info)");
|
2023-04-28 09:08:04 +00:00
|
|
|
/// let mut reg = Registry::new_handle(String::from("https://crates.io"), None, handle, true);
|
2021-01-22 19:06:51 +00:00
|
|
|
/// ```
|
2022-10-31 16:44:01 +00:00
|
|
|
pub fn new_handle(
|
|
|
|
host: String,
|
|
|
|
token: Option<String>,
|
|
|
|
handle: Easy,
|
|
|
|
auth_required: bool,
|
|
|
|
) -> Registry {
|
2014-09-27 04:14:46 +00:00
|
|
|
Registry {
|
2018-02-23 23:27:53 +00:00
|
|
|
host,
|
|
|
|
token,
|
|
|
|
handle,
|
2022-10-31 16:44:01 +00:00
|
|
|
auth_required,
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-12 17:49:22 +00:00
|
|
|
pub fn set_token(&mut self, token: Option<String>) {
|
|
|
|
self.token = token;
|
|
|
|
}
|
|
|
|
|
2023-04-09 19:15:40 +00:00
|
|
|
fn token(&self) -> Result<&str> {
|
2023-06-25 09:58:35 +00:00
|
|
|
let token = self.token.as_ref().ok_or_else(|| {
|
|
|
|
Error::InvalidToken("no upload token found, please run `cargo login`")
|
|
|
|
})?;
|
2023-04-09 19:15:40 +00:00
|
|
|
check_token(token)?;
|
|
|
|
Ok(token)
|
|
|
|
}
|
|
|
|
|
2018-12-20 01:40:01 +00:00
|
|
|
pub fn host(&self) -> &str {
|
|
|
|
&self.host
|
|
|
|
}
|
|
|
|
|
2019-05-14 16:20:54 +00:00
|
|
|
pub fn host_is_crates_io(&self) -> bool {
|
2020-03-07 01:29:12 +00:00
|
|
|
is_url_crates_io(&self.host)
|
2019-05-14 16:20:54 +00:00
|
|
|
}
|
|
|
|
|
2017-09-26 21:01:50 +00:00
|
|
|
pub fn add_owners(&mut self, krate: &str, owners: &[&str]) -> Result<String> {
|
2017-02-10 20:01:52 +00:00
|
|
|
let body = serde_json::to_string(&OwnersReq { users: owners })?;
|
2018-07-20 19:39:05 +00:00
|
|
|
let body = self.put(&format!("/crates/{}/owners", krate), body.as_bytes())?;
|
2017-09-28 19:23:48 +00:00
|
|
|
assert!(serde_json::from_str::<OwnerResponse>(&body)?.ok);
|
|
|
|
Ok(serde_json::from_str::<OwnerResponse>(&body)?.msg)
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn remove_owners(&mut self, krate: &str, owners: &[&str]) -> Result<()> {
|
2017-02-10 20:01:52 +00:00
|
|
|
let body = serde_json::to_string(&OwnersReq { users: owners })?;
|
2018-07-20 19:39:05 +00:00
|
|
|
let body = self.delete(&format!("/crates/{}/owners", krate), Some(body.as_bytes()))?;
|
2017-09-28 19:23:48 +00:00
|
|
|
assert!(serde_json::from_str::<OwnerResponse>(&body)?.ok);
|
2014-09-27 04:14:46 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2014-11-13 06:15:41 +00:00
|
|
|
pub fn list_owners(&mut self, krate: &str) -> Result<Vec<User>> {
|
2018-07-20 19:39:05 +00:00
|
|
|
let body = self.get(&format!("/crates/{}/owners", krate))?;
|
2017-02-10 20:01:52 +00:00
|
|
|
Ok(serde_json::from_str::<Users>(&body)?.users)
|
2014-11-13 06:15:41 +00:00
|
|
|
}
|
|
|
|
|
2020-12-05 22:10:29 +00:00
|
|
|
pub fn publish(&mut self, krate: &NewCrate, mut tarball: &File) -> Result<Warnings> {
|
2017-02-10 20:01:52 +00:00
|
|
|
let json = serde_json::to_string(krate)?;
|
2014-09-27 04:14:46 +00:00
|
|
|
// Prepare the body. The format of the upload request is:
|
|
|
|
//
|
|
|
|
// <le u32 of json>
|
|
|
|
// <json request> (metadata for the package)
|
|
|
|
// <le u32 of tarball>
|
|
|
|
// <source tarball>
|
2020-12-05 22:10:29 +00:00
|
|
|
|
|
|
|
// NOTE: This can be replaced with `stream_len` if it is ever stabilized.
|
|
|
|
//
|
|
|
|
// This checks the length using seeking instead of metadata, because
|
|
|
|
// on some filesystems, getting the metadata will fail because
|
|
|
|
// the file was renamed in ops::package.
|
2023-06-25 09:58:35 +00:00
|
|
|
let tarball_len = tarball.seek(SeekFrom::End(0))?;
|
|
|
|
tarball.seek(SeekFrom::Start(0))?;
|
2014-09-27 04:14:46 +00:00
|
|
|
let header = {
|
2015-02-27 01:04:25 +00:00
|
|
|
let mut w = Vec::new();
|
2020-11-09 22:23:46 +00:00
|
|
|
w.extend(&(json.len() as u32).to_le_bytes());
|
2018-04-04 21:06:26 +00:00
|
|
|
w.extend(json.as_bytes().iter().cloned());
|
2020-12-05 22:10:29 +00:00
|
|
|
w.extend(&(tarball_len as u32).to_le_bytes());
|
2015-02-27 01:04:25 +00:00
|
|
|
w
|
2014-09-27 04:14:46 +00:00
|
|
|
};
|
2020-12-05 22:10:29 +00:00
|
|
|
let size = tarball_len as usize + header.len();
|
2015-02-27 01:04:25 +00:00
|
|
|
let mut body = Cursor::new(header).chain(tarball);
|
2014-09-27 04:14:46 +00:00
|
|
|
|
|
|
|
let url = format!("{}/api/v1/crates/new", self.host);
|
2014-11-22 14:36:14 +00:00
|
|
|
|
2016-11-11 13:25:20 +00:00
|
|
|
self.handle.put(true)?;
|
|
|
|
self.handle.url(&url)?;
|
|
|
|
self.handle.in_filesize(size as u64)?;
|
2016-05-18 17:01:40 +00:00
|
|
|
let mut headers = List::new();
|
2016-11-11 13:25:20 +00:00
|
|
|
headers.append("Accept: application/json")?;
|
2023-04-09 19:15:40 +00:00
|
|
|
headers.append(&format!("Authorization: {}", self.token()?))?;
|
2016-11-11 13:25:20 +00:00
|
|
|
self.handle.http_headers(headers)?;
|
2016-05-18 17:01:40 +00:00
|
|
|
|
2021-01-28 20:39:51 +00:00
|
|
|
let started = Instant::now();
|
|
|
|
let body = self
|
|
|
|
.handle(&mut |buf| body.read(buf).unwrap_or(0))
|
|
|
|
.map_err(|e| match e {
|
2023-07-06 12:36:23 +00:00
|
|
|
Error::Code { code, .. }
|
2021-01-28 20:39:51 +00:00
|
|
|
if code == 503
|
|
|
|
&& started.elapsed().as_secs() >= 29
|
|
|
|
&& self.host_is_crates_io() =>
|
|
|
|
{
|
2023-06-25 09:58:35 +00:00
|
|
|
Error::Timeout(tarball_len)
|
2021-01-28 20:39:51 +00:00
|
|
|
}
|
|
|
|
_ => e.into(),
|
|
|
|
})?;
|
2017-01-01 20:14:34 +00:00
|
|
|
|
2018-04-04 21:06:26 +00:00
|
|
|
let response = if body.is_empty() {
|
2017-02-10 20:01:52 +00:00
|
|
|
"{}".parse()?
|
2018-04-04 21:06:26 +00:00
|
|
|
} else {
|
|
|
|
body.parse::<serde_json::Value>()?
|
2016-11-29 21:09:00 +00:00
|
|
|
};
|
2017-01-01 20:14:34 +00:00
|
|
|
|
2017-05-24 04:35:54 +00:00
|
|
|
let invalid_categories: Vec<String> = response
|
|
|
|
.get("warnings")
|
|
|
|
.and_then(|j| j.get("invalid_categories"))
|
|
|
|
.and_then(|j| j.as_array())
|
|
|
|
.map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect())
|
|
|
|
.unwrap_or_else(Vec::new);
|
|
|
|
|
|
|
|
let invalid_badges: Vec<String> = response
|
|
|
|
.get("warnings")
|
|
|
|
.and_then(|j| j.get("invalid_badges"))
|
|
|
|
.and_then(|j| j.as_array())
|
|
|
|
.map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect())
|
|
|
|
.unwrap_or_else(Vec::new);
|
2017-01-01 20:14:34 +00:00
|
|
|
|
2018-10-31 12:34:04 +00:00
|
|
|
let other: Vec<String> = response
|
|
|
|
.get("warnings")
|
|
|
|
.and_then(|j| j.get("other"))
|
|
|
|
.and_then(|j| j.as_array())
|
|
|
|
.map(|x| x.iter().flat_map(|j| j.as_str()).map(Into::into).collect())
|
|
|
|
.unwrap_or_else(Vec::new);
|
|
|
|
|
2017-01-01 20:14:34 +00:00
|
|
|
Ok(Warnings {
|
2018-02-23 23:27:53 +00:00
|
|
|
invalid_categories,
|
|
|
|
invalid_badges,
|
2018-10-31 12:34:04 +00:00
|
|
|
other,
|
2017-01-01 20:14:34 +00:00
|
|
|
})
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
|
|
|
|
2018-03-10 14:42:08 +00:00
|
|
|
pub fn search(&mut self, query: &str, limit: u32) -> Result<(Vec<Crate>, u32)> {
|
2019-07-24 14:42:14 +00:00
|
|
|
let formatted_query = percent_encode(query.as_bytes(), NON_ALPHANUMERIC);
|
2016-11-11 13:25:20 +00:00
|
|
|
let body = self.req(
|
2018-07-20 19:39:05 +00:00
|
|
|
&format!("/crates?q={}&per_page={}", formatted_query, limit),
|
2018-03-14 15:17:44 +00:00
|
|
|
None,
|
|
|
|
Auth::Unauthorized,
|
2016-11-11 13:25:20 +00:00
|
|
|
)?;
|
2014-11-22 14:36:14 +00:00
|
|
|
|
2017-02-10 20:01:52 +00:00
|
|
|
let crates = serde_json::from_str::<Crates>(&body)?;
|
2016-03-07 08:19:40 +00:00
|
|
|
Ok((crates.crates, crates.meta.total))
|
2014-11-22 14:36:14 +00:00
|
|
|
}
|
|
|
|
|
2014-09-27 04:14:46 +00:00
|
|
|
pub fn yank(&mut self, krate: &str, version: &str) -> Result<()> {
|
2018-07-20 19:39:05 +00:00
|
|
|
let body = self.delete(&format!("/crates/{}/{}/yank", krate, version), None)?;
|
2017-02-10 20:01:52 +00:00
|
|
|
assert!(serde_json::from_str::<R>(&body)?.ok);
|
2014-09-27 04:14:46 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn unyank(&mut self, krate: &str, version: &str) -> Result<()> {
|
2018-07-20 19:39:05 +00:00
|
|
|
let body = self.put(&format!("/crates/{}/{}/unyank", krate, version), &[])?;
|
2017-02-10 20:01:52 +00:00
|
|
|
assert!(serde_json::from_str::<R>(&body)?.ok);
|
2014-09-27 04:14:46 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2018-07-20 19:39:05 +00:00
|
|
|
fn put(&mut self, path: &str, b: &[u8]) -> Result<String> {
|
2016-11-11 13:25:20 +00:00
|
|
|
self.handle.put(true)?;
|
2016-05-18 17:01:40 +00:00
|
|
|
self.req(path, Some(b), Auth::Authorized)
|
2014-11-13 06:15:41 +00:00
|
|
|
}
|
|
|
|
|
2018-07-20 19:39:05 +00:00
|
|
|
fn get(&mut self, path: &str) -> Result<String> {
|
2016-11-11 13:25:20 +00:00
|
|
|
self.handle.get(true)?;
|
2016-05-18 17:01:40 +00:00
|
|
|
self.req(path, None, Auth::Authorized)
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
|
|
|
|
2018-07-20 19:39:05 +00:00
|
|
|
fn delete(&mut self, path: &str, b: Option<&[u8]>) -> Result<String> {
|
2016-11-11 13:25:20 +00:00
|
|
|
self.handle.custom_request("DELETE")?;
|
2016-05-18 17:01:40 +00:00
|
|
|
self.req(path, b, Auth::Authorized)
|
2014-11-13 06:15:41 +00:00
|
|
|
}
|
|
|
|
|
2018-07-20 19:39:05 +00:00
|
|
|
fn req(&mut self, path: &str, body: Option<&[u8]>, authorized: Auth) -> Result<String> {
|
2016-11-11 13:25:20 +00:00
|
|
|
self.handle.url(&format!("{}/api/v1{}", self.host, path))?;
|
2016-05-18 17:01:40 +00:00
|
|
|
let mut headers = List::new();
|
2016-11-11 13:25:20 +00:00
|
|
|
headers.append("Accept: application/json")?;
|
2024-01-08 16:29:27 +00:00
|
|
|
if body.is_some() {
|
|
|
|
headers.append("Content-Type: application/json")?;
|
|
|
|
}
|
2014-11-22 14:36:14 +00:00
|
|
|
|
2022-10-31 16:44:01 +00:00
|
|
|
if self.auth_required || authorized == Auth::Authorized {
|
2023-04-09 19:15:40 +00:00
|
|
|
headers.append(&format!("Authorization: {}", self.token()?))?;
|
2014-11-22 14:36:14 +00:00
|
|
|
}
|
2016-11-11 13:25:20 +00:00
|
|
|
self.handle.http_headers(headers)?;
|
2014-11-13 06:15:41 +00:00
|
|
|
match body {
|
2016-05-18 17:01:40 +00:00
|
|
|
Some(mut body) => {
|
2016-11-11 13:25:20 +00:00
|
|
|
self.handle.upload(true)?;
|
|
|
|
self.handle.in_filesize(body.len() as u64)?;
|
2019-05-14 16:20:54 +00:00
|
|
|
self.handle(&mut |buf| body.read(buf).unwrap_or(0))
|
2021-01-28 20:39:51 +00:00
|
|
|
.map_err(|e| e.into())
|
2016-05-18 17:01:40 +00:00
|
|
|
}
|
2021-01-28 20:39:51 +00:00
|
|
|
None => self.handle(&mut |_| 0).map_err(|e| e.into()),
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
|
|
|
}
|
2016-05-18 17:01:40 +00:00
|
|
|
|
2023-06-25 08:42:26 +00:00
|
|
|
fn handle(&mut self, read: &mut dyn FnMut(&mut [u8]) -> usize) -> Result<String> {
|
2019-05-14 16:20:54 +00:00
|
|
|
let mut headers = Vec::new();
|
|
|
|
let mut body = Vec::new();
|
|
|
|
{
|
|
|
|
let mut handle = self.handle.transfer();
|
|
|
|
handle.read_function(|buf| Ok(read(buf)))?;
|
|
|
|
handle.write_function(|data| {
|
|
|
|
body.extend_from_slice(data);
|
|
|
|
Ok(data.len())
|
|
|
|
})?;
|
|
|
|
handle.header_function(|data| {
|
2021-01-28 20:39:51 +00:00
|
|
|
// Headers contain trailing \r\n, trim them to make it easier
|
|
|
|
// to work with.
|
|
|
|
let s = String::from_utf8_lossy(data).trim().to_string();
|
2023-07-06 12:25:34 +00:00
|
|
|
// Don't let server sneak extra lines anywhere.
|
|
|
|
if s.contains('\n') {
|
|
|
|
return true;
|
|
|
|
}
|
2021-01-28 20:39:51 +00:00
|
|
|
headers.push(s);
|
2019-05-14 16:20:54 +00:00
|
|
|
true
|
|
|
|
})?;
|
|
|
|
handle.perform()?;
|
2019-05-13 20:18:42 +00:00
|
|
|
}
|
2019-05-14 16:20:54 +00:00
|
|
|
|
2023-06-25 09:58:35 +00:00
|
|
|
let body = String::from_utf8(body)?;
|
2019-06-22 22:29:52 +00:00
|
|
|
let errors = serde_json::from_str::<ApiErrorList>(&body)
|
|
|
|
.ok()
|
|
|
|
.map(|s| s.errors.into_iter().map(|s| s.detail).collect::<Vec<_>>());
|
2019-05-14 16:20:54 +00:00
|
|
|
|
|
|
|
match (self.handle.response_code()?, errors) {
|
2023-12-12 12:32:57 +00:00
|
|
|
(0, None) => Ok(body),
|
|
|
|
(code, None) if is_success(code) => Ok(body),
|
2023-07-06 12:36:23 +00:00
|
|
|
(code, Some(errors)) => Err(Error::Api {
|
2023-07-06 12:25:34 +00:00
|
|
|
code,
|
|
|
|
headers,
|
|
|
|
errors,
|
|
|
|
}),
|
2023-07-06 12:36:23 +00:00
|
|
|
(code, None) => Err(Error::Code {
|
2019-06-22 22:29:52 +00:00
|
|
|
code,
|
2021-01-28 20:39:51 +00:00
|
|
|
headers,
|
2019-06-22 22:29:52 +00:00
|
|
|
body,
|
2021-01-28 20:39:51 +00:00
|
|
|
}),
|
Always nicely show errors from crates.io if possible
Currently if Cargo ever gets a non-200 response, it will either not show
the error at all (if it was a 403 or 404), or spit out the entire
response body. Historically crates.io has served a 200 for most errors
to work around this, but we've stopped doing this as it causes problems
for other clients.
Additionally, we're starting to server more errors that have semantic
meaning (429 for rate limiting, 503 when we're in read only mode). If
the request specifies "Accept: application/json", we should ideally
return the errors formatted nicely. This isn't always true, but it's
what we'd like to do going forward.
While the output that Cargo puts out at least contains the actual
message, it's buried under a ton of useless info. This changes the
behavior so that if the response was valid JSON in the format that Cargo
expects, it just shows that (along with a description of the response
status), and only falls back to spitting out everything if it can't
parse the response body.
I'd love to add some more tests for this, but I've had trouble finding
anywhere in the test suite that exercises these paths.
2019-03-21 18:10:43 +00:00
|
|
|
}
|
2019-05-14 16:20:54 +00:00
|
|
|
}
|
2014-09-27 04:14:46 +00:00
|
|
|
}
|
2019-09-19 18:48:34 +00:00
|
|
|
|
2023-12-12 12:32:57 +00:00
|
|
|
fn is_success(code: u32) -> bool {
|
|
|
|
code >= 200 && code < 300
|
|
|
|
}
|
|
|
|
|
2023-06-25 13:27:58 +00:00
|
|
|
fn status(code: u32) -> String {
|
2023-12-12 12:32:57 +00:00
|
|
|
if is_success(code) {
|
2023-06-25 13:27:58 +00:00
|
|
|
String::new()
|
|
|
|
} else {
|
|
|
|
let reason = reason(code);
|
|
|
|
format!(" (status {code} {reason})")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-19 18:48:34 +00:00
|
|
|
fn reason(code: u32) -> &'static str {
|
|
|
|
// Taken from https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
|
|
|
|
match code {
|
|
|
|
100 => "Continue",
|
|
|
|
101 => "Switching Protocol",
|
|
|
|
103 => "Early Hints",
|
|
|
|
200 => "OK",
|
|
|
|
201 => "Created",
|
|
|
|
202 => "Accepted",
|
|
|
|
203 => "Non-Authoritative Information",
|
|
|
|
204 => "No Content",
|
|
|
|
205 => "Reset Content",
|
|
|
|
206 => "Partial Content",
|
|
|
|
300 => "Multiple Choice",
|
|
|
|
301 => "Moved Permanently",
|
|
|
|
302 => "Found",
|
|
|
|
303 => "See Other",
|
|
|
|
304 => "Not Modified",
|
|
|
|
307 => "Temporary Redirect",
|
|
|
|
308 => "Permanent Redirect",
|
|
|
|
400 => "Bad Request",
|
|
|
|
401 => "Unauthorized",
|
|
|
|
402 => "Payment Required",
|
|
|
|
403 => "Forbidden",
|
|
|
|
404 => "Not Found",
|
|
|
|
405 => "Method Not Allowed",
|
|
|
|
406 => "Not Acceptable",
|
|
|
|
407 => "Proxy Authentication Required",
|
|
|
|
408 => "Request Timeout",
|
|
|
|
409 => "Conflict",
|
|
|
|
410 => "Gone",
|
|
|
|
411 => "Length Required",
|
|
|
|
412 => "Precondition Failed",
|
|
|
|
413 => "Payload Too Large",
|
|
|
|
414 => "URI Too Long",
|
|
|
|
415 => "Unsupported Media Type",
|
|
|
|
416 => "Request Range Not Satisfiable",
|
|
|
|
417 => "Expectation Failed",
|
|
|
|
429 => "Too Many Requests",
|
|
|
|
431 => "Request Header Fields Too Large",
|
|
|
|
500 => "Internal Server Error",
|
|
|
|
501 => "Not Implemented",
|
|
|
|
502 => "Bad Gateway",
|
|
|
|
503 => "Service Unavailable",
|
|
|
|
504 => "Gateway Timeout",
|
|
|
|
_ => "<unknown>",
|
|
|
|
}
|
|
|
|
}
|
2020-03-07 01:29:12 +00:00
|
|
|
|
|
|
|
/// Returns `true` if the host of the given URL is "crates.io".
|
|
|
|
pub fn is_url_crates_io(url: &str) -> bool {
|
|
|
|
Url::parse(url)
|
|
|
|
.map(|u| u.host_str() == Some("crates.io"))
|
|
|
|
.unwrap_or(false)
|
|
|
|
}
|
2023-02-16 15:42:30 +00:00
|
|
|
|
|
|
|
/// Checks if a token is valid or malformed.
|
|
|
|
///
|
|
|
|
/// This check is necessary to prevent sending tokens which create an invalid HTTP request.
|
|
|
|
/// It would be easier to check just for alphanumeric tokens, but we can't be sure that all
|
|
|
|
/// registries only create tokens in that format so that is as less restricted as possible.
|
|
|
|
pub fn check_token(token: &str) -> Result<()> {
|
2023-02-16 18:12:46 +00:00
|
|
|
if token.is_empty() {
|
2023-06-25 09:58:35 +00:00
|
|
|
return Err(Error::InvalidToken("please provide a non-empty token"));
|
2023-02-16 18:12:46 +00:00
|
|
|
}
|
|
|
|
if token.bytes().all(|b| {
|
2023-04-09 18:53:46 +00:00
|
|
|
// This is essentially the US-ASCII limitation of
|
|
|
|
// https://www.rfc-editor.org/rfc/rfc9110#name-field-values. That is,
|
|
|
|
// visible ASCII characters (0x21-0x7e), space, and tab. We want to be
|
|
|
|
// able to pass this in an HTTP header without encoding.
|
|
|
|
b >= 32 && b < 127 || b == b'\t'
|
2023-02-16 18:12:46 +00:00
|
|
|
}) {
|
2023-02-16 15:42:30 +00:00
|
|
|
Ok(())
|
|
|
|
} else {
|
2023-06-25 09:58:35 +00:00
|
|
|
Err(Error::InvalidToken(
|
2023-02-16 18:12:46 +00:00
|
|
|
"token contains invalid characters.\nOnly printable ISO-8859-1 characters \
|
2023-06-25 09:58:35 +00:00
|
|
|
are allowed as it is sent in a HTTPS header.",
|
|
|
|
))
|
2023-02-16 15:42:30 +00:00
|
|
|
}
|
|
|
|
}
|