Validate token on publish.

This commit is contained in:
Eric Huss 2023-04-09 12:15:40 -07:00
parent 1b2de2169b
commit 35f5862979
2 changed files with 52 additions and 11 deletions

View File

@ -219,6 +219,15 @@ impl Registry {
self.token = token;
}
fn token(&self) -> Result<&str> {
let token = match self.token.as_ref() {
Some(s) => s,
None => bail!("no upload token found, please run `cargo login`"),
};
check_token(token)?;
Ok(token)
}
pub fn host(&self) -> &str {
&self.host
}
@ -278,16 +287,12 @@ impl Registry {
let url = format!("{}/api/v1/crates/new", self.host);
let token = match self.token.as_ref() {
Some(s) => s,
None => bail!("no upload token found, please run `cargo login`"),
};
self.handle.put(true)?;
self.handle.url(&url)?;
self.handle.in_filesize(size as u64)?;
let mut headers = List::new();
headers.append("Accept: application/json")?;
headers.append(&format!("Authorization: {}", token))?;
headers.append(&format!("Authorization: {}", self.token()?))?;
self.handle.http_headers(headers)?;
let started = Instant::now();
@ -390,12 +395,7 @@ impl Registry {
headers.append("Content-Type: application/json")?;
if self.auth_required || authorized == Auth::Authorized {
let token = match self.token.as_ref() {
Some(s) => s,
None => bail!("no upload token found, please run `cargo login`"),
};
check_token(token)?;
headers.append(&format!("Authorization: {}", token))?;
headers.append(&format!("Authorization: {}", self.token()?))?;
}
self.handle.http_headers(headers)?;
match body {

View File

@ -2908,3 +2908,44 @@ You may press ctrl-c to skip waiting; the crate should be available shortly.
p.cargo("check").with_status(0).run();
}
#[cargo_test]
fn invalid_token() {
// Checks publish behavior with an invalid token.
let registry = RegistryBuilder::new().http_api().http_index().build();
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
license = "MIT"
description = "foo"
documentation = "foo"
"#,
)
.file("src/main.rs", "fn main() {}")
.build();
p.cargo("publish --no-verify")
.replace_crates_io(registry.index_url())
.env("CARGO_REGISTRY_TOKEN", "\x16")
.with_stderr(
"\
[UPDATING] crates.io index
[PACKAGING] foo v0.0.1 ([ROOT]/foo)
[PACKAGED] 4 files, [..]
[UPLOADING] foo v0.0.1 ([ROOT]/foo)
error: failed to publish to registry at http://127.0.0.1:[..]/
Caused by:
token contains invalid characters.
Only printable ISO-8859-1 characters are allowed as it is sent in a HTTPS header.
",
)
.with_status(101)
.run();
}