Skip to content

Commit de7c863

Browse files
committed
AccessToken: Implement FromStr trait and update parsing usages
All of our users at this point have `&str` anyway, so we might as well operate on strings.
1 parent 92464de commit de7c863

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

crates/crates_io_trustpub/src/access_token.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use rand::distr::{Alphanumeric, SampleString};
22
use secrecy::{ExposeSecret, SecretString};
33
use sha2::digest::Output;
44
use sha2::{Digest, Sha256};
5+
use std::str::FromStr;
56

67
/// A temporary access token used to publish crates to crates.io using
78
/// the "Trusted Publishing" feature.
@@ -77,6 +78,17 @@ impl AccessToken {
7778
}
7879
}
7980

81+
impl FromStr for AccessToken {
82+
type Err = AccessTokenError;
83+
84+
/// Parse a string into an access token.
85+
///
86+
/// This is equivalent to `AccessToken::from_byte_str`.
87+
fn from_str(s: &str) -> Result<Self, Self::Err> {
88+
Self::from_byte_str(s.as_bytes())
89+
}
90+
}
91+
8092
/// The error type for parsing access tokens.
8193
#[derive(Debug, Clone, PartialEq, Eq)]
8294
pub enum AccessTokenError {

src/controllers/krate/publish.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ pub async fn publish(app: AppState, req: Parts, body: Body) -> AppResult<Json<Go
155155
return None;
156156
}
157157

158-
Some(AccessToken::from_byte_str(token.as_bytes()).map_err(|_| {
158+
Some(token.parse::<AccessToken>().map_err(|_| {
159159
let message = "Invalid `Authorization` header: Failed to parse token";
160160
custom(StatusCode::UNAUTHORIZED, message)
161161
}))

src/controllers/trustpub/tokens/revoke/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ mod tests;
2424
)]
2525
pub async fn revoke_trustpub_token(app: AppState, auth: AuthHeader) -> AppResult<StatusCode> {
2626
let token = auth.token().expose_secret();
27-
let Ok(token) = AccessToken::from_byte_str(token.as_bytes()) else {
27+
let Ok(token) = token.parse::<AccessToken>() else {
2828
let message = "Invalid `Authorization` header: Failed to parse token";
2929
return Err(custom(StatusCode::UNAUTHORIZED, message));
3030
};

0 commit comments

Comments
 (0)