Skip to content

Commit

Permalink
Error on invalid alphanumeric token for crates.io
Browse files Browse the repository at this point in the history
When using `cargo login` and calling an api which requires
authentification there will be an error if the given token
is not a valid alphanumerical string.
This check is only enabled for crates.io because
only for that registry we can be certain, that the generated token
should have been alphanumeric.
  • Loading branch information
Akida31 committed Jan 19, 2023
1 parent 23424fd commit be38179
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions crates/crates-io/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,9 @@ impl Registry {
Some(s) => s,
None => bail!("no upload token found, please run `cargo login`"),
};
if self.host_is_crates_io() && token.chars().any(|c| !c.is_alphanumeric()) {
bail!("malformed token: Token must be alphanumeric");
}
headers.append(&format!("Authorization: {}", token))?;
}
self.handle.http_headers(headers)?;
Expand Down
3 changes: 3 additions & 0 deletions src/cargo/ops/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,9 @@ pub fn registry_login(
if tok.is_empty() {
bail!("please provide a non-empty token");
}
if source_ids.original.is_crates_io() && tok.chars().any(|c| !c.is_alphanumeric()) {
bail!("malformed token: Token must be alphanumeric");
}
}
}
if &reg_cfg == &new_token {
Expand Down
33 changes: 33 additions & 0 deletions tests/testsuite/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,39 @@ fn empty_login_token() {
.run();
}

#[cargo_test]
fn malformed_login_token() {
let registry = RegistryBuilder::new()
.no_configure_registry()
.no_configure_token()
.build();
setup_new_credentials();

cargo_process("login")
.replace_crates_io(registry.index_url())
.with_stdout("please paste the token found on [..]/me below")
.with_stdin("😄;>!\t\n")
.with_stderr(
"\
[UPDATING] crates.io index
[ERROR] malformed token: Token must be alphanumeric
",
)
.with_status(101)
.run();

cargo_process("login")
.replace_crates_io(registry.index_url())
.arg("")
.with_stderr(
"\
[ERROR] please provide a non-empty token
",
)
.with_status(101)
.run();
}

#[cargo_test]
fn bad_asymmetric_token_args() {
// These cases are kept brief as the implementation is covered by clap, so this is only smoke testing that we have clap configured correctly.
Expand Down

0 comments on commit be38179

Please sign in to comment.