Fix GitHub token auto discovery (#1335)

* Fix GitHub token auto discovery

Fixed #1333

 - Rm dep `gh-token` since it is broken and we can simply run
   `gh auth token` in `cargo-binstall` instead.
 - binstalk-downloader: Make sure GitHub token is at least 40B long
   and other than the `_`, composes of only alphanumeric characters.
 - Warn on failure to read `git/credential` files
 - Optimize `try_from_home` to avoid heap allocation of `PathBuf`

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>

* Fix typo and clippy

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>

* Simplify `is_valid_gh_token` & `is_ascii_alphanumeric` impl

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>

* Improve err msg in `get_inner`

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>

* Improve err msg of `cargo_binstall::gh_token::get`

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>

---------

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2023-09-01 11:14:59 +10:00 committed by GitHub
parent 0ca38ab0e3
commit 8a08cdda6f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 85 additions and 53 deletions

View file

@ -132,19 +132,29 @@ struct Inner {
#[derive(Clone, Debug)]
pub struct GhApiClient(Arc<Inner>);
fn gh_prefixed(token: &str) -> bool {
matches!((token.get(0..2), token.get(3..4)), (Some("gh"), Some("_")))
|| token.starts_with("github_")
fn is_ascii_alphanumeric(s: &[u8]) -> bool {
s.iter().all(|byte| byte.is_ascii_alphanumeric())
}
fn is_valid_gh_token(token: &str) -> bool {
let token = token.as_bytes();
token.len() >= 40
&& ((&token[0..2] == b"gh"
&& token[2].is_ascii_alphanumeric()
&& token[3] == b'_'
&& is_ascii_alphanumeric(&token[4..]))
|| (token.starts_with(b"github_") && is_ascii_alphanumeric(&token[7..])))
}
impl GhApiClient {
pub fn new(client: remote::Client, auth_token: Option<CompactString>) -> Self {
let auth_token = auth_token.and_then(|auth_token| {
if gh_prefixed(&auth_token) {
if is_valid_gh_token(&auth_token) {
debug!("Using gh api token");
Some(auth_token)
} else {
warn!("Invalid auth_token, expected 'gh*_' or `github_*`, fallback to unauthorized mode");
warn!("Invalid auth_token, expected 'gh*_' or `github_*` with [A-Za-z0-9], fallback to unauthorized mode");
None
}
});