-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Add a uv auth helper --protocol bazel command
#16886
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2bbb10a
add credential helper
zsol b890a10
Add a `get` subcommand
zsol 0db7c27
Rename credential-helper -> helper
zsol a60e823
Add a --protocol required argument
zsol c5514bf
Address code review feedback
zsol 181978f
More review feedback
zsol 122b73c
Even more review feedback
zsol 4469013
Add a preview flag
zsol File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| use std::collections::HashMap; | ||
| use std::fmt::Write; | ||
| use std::io::Read; | ||
|
|
||
| use anyhow::{Context, Result, bail}; | ||
| use serde::{Deserialize, Serialize}; | ||
| use tracing::debug; | ||
|
|
||
| use uv_auth::{AuthBackend, Credentials, PyxTokenStore}; | ||
| use uv_client::BaseClientBuilder; | ||
| use uv_preview::{Preview, PreviewFeatures}; | ||
| use uv_redacted::DisplaySafeUrl; | ||
| use uv_warnings::warn_user; | ||
|
|
||
| use crate::{commands::ExitStatus, printer::Printer, settings::NetworkSettings}; | ||
|
|
||
| /// Request format for the Bazel credential helper protocol. | ||
| #[derive(Debug, Deserialize)] | ||
| struct BazelCredentialRequest { | ||
| uri: DisplaySafeUrl, | ||
| } | ||
|
|
||
| impl BazelCredentialRequest { | ||
| fn from_str(s: &str) -> Result<Self> { | ||
| serde_json::from_str(s).context("Failed to parse credential request as JSON") | ||
| } | ||
|
|
||
| fn from_stdin() -> Result<Self> { | ||
| let mut buffer = String::new(); | ||
| std::io::stdin() | ||
| .read_to_string(&mut buffer) | ||
| .context("Failed to read from stdin")?; | ||
|
|
||
| Self::from_str(&buffer) | ||
| } | ||
| } | ||
|
|
||
| /// Response format for the Bazel credential helper protocol. | ||
| #[derive(Debug, Serialize, Default)] | ||
| struct BazelCredentialResponse { | ||
| headers: HashMap<String, Vec<String>>, | ||
| } | ||
|
|
||
| impl TryFrom<Credentials> for BazelCredentialResponse { | ||
| fn try_from(creds: Credentials) -> Result<Self> { | ||
| let header_str = creds | ||
| .to_header_value() | ||
| .to_str() | ||
| // TODO: this is infallible in practice | ||
| .context("Failed to convert header value to string")? | ||
| .to_owned(); | ||
|
|
||
| Ok(Self { | ||
| headers: HashMap::from([("Authorization".to_owned(), vec![header_str])]), | ||
| }) | ||
| } | ||
|
|
||
| type Error = anyhow::Error; | ||
| } | ||
|
|
||
| async fn credentials_for_url( | ||
| url: &DisplaySafeUrl, | ||
| preview: Preview, | ||
| network_settings: &NetworkSettings, | ||
| ) -> Result<Option<Credentials>> { | ||
| let pyx_store = PyxTokenStore::from_settings()?; | ||
|
|
||
| // Use only the username from the URL, if present - discarding the password | ||
zsol marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| let url_credentials = Credentials::from_url(url); | ||
| let username = url_credentials.as_ref().and_then(|c| c.username()); | ||
| if url_credentials | ||
| .as_ref() | ||
| .map(|c| c.password().is_some()) | ||
| .unwrap_or(false) | ||
| { | ||
| debug!("URL '{url}' contain a password; ignoring"); | ||
| } | ||
|
|
||
| if pyx_store.is_known_domain(url) { | ||
| if username.is_some() { | ||
| bail!( | ||
| "Cannot specify a username for URLs under {}", | ||
| url.host() | ||
| .map(|host| host.to_string()) | ||
| .unwrap_or(url.to_string()) | ||
| ); | ||
| } | ||
| let client = BaseClientBuilder::new( | ||
zsol marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| network_settings.connectivity, | ||
| network_settings.native_tls, | ||
| network_settings.allow_insecure_host.clone(), | ||
| preview, | ||
| network_settings.timeout, | ||
| network_settings.retries, | ||
| ) | ||
| .auth_integration(uv_client::AuthIntegration::NoAuthMiddleware) | ||
| .build(); | ||
| let token = pyx_store | ||
| .access_token(client.for_host(pyx_store.api()).raw_client(), 0) | ||
| .await | ||
| .context("Authentication failure")? | ||
| .context("No access token found")?; | ||
| return Ok(Some(Credentials::bearer(token.into_bytes()))); | ||
| } | ||
| let backend = AuthBackend::from_settings(preview).await?; | ||
| let credentials = match &backend { | ||
| AuthBackend::System(provider) => provider.fetch(url, username).await, | ||
| AuthBackend::TextStore(store, _lock) => store.get_credentials(url, username).cloned(), | ||
| }; | ||
| Ok(credentials) | ||
| } | ||
|
|
||
| /// Implement the Bazel credential helper protocol. | ||
| /// | ||
| /// Reads a JSON request from stdin containing a URI, looks up credentials | ||
| /// for that URI using uv's authentication backends, and writes a JSON response | ||
| /// to stdout containing HTTP headers (if credentials are found). | ||
| /// | ||
| /// Protocol specification TLDR: | ||
| /// - Input (stdin): `{"uri": "https://example.com/path"}` | ||
| /// - Output (stdout): `{"headers": {"Authorization": ["Basic ..."]}}` or `{"headers": {}}` | ||
| /// - Errors: Written to stderr with non-zero exit code | ||
| /// | ||
| /// Full spec is [available here](https://github.com/bazelbuild/proposals/blob/main/designs/2022-06-07-bazel-credential-helpers.md) | ||
| pub(crate) async fn helper( | ||
| preview: Preview, | ||
| network_settings: &NetworkSettings, | ||
| printer: Printer, | ||
| ) -> Result<ExitStatus> { | ||
zsol marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if !preview.is_enabled(PreviewFeatures::AUTH_HELPER) { | ||
| warn_user!( | ||
| "The `uv auth helper` command is experimental and may change without warning. Pass `--preview-features {}` to disable this warning", | ||
| PreviewFeatures::AUTH_HELPER | ||
| ); | ||
| } | ||
|
|
||
| let request = BazelCredentialRequest::from_stdin()?; | ||
|
|
||
| // TODO: make this logic generic over the protocol by providing `request.uri` from a | ||
| // trait - that should help with adding new protocols | ||
| let credentials = credentials_for_url(&request.uri, preview, network_settings).await?; | ||
|
|
||
| let response = serde_json::to_string( | ||
| &credentials | ||
| .map(BazelCredentialResponse::try_from) | ||
| .unwrap_or_else(|| Ok(BazelCredentialResponse::default()))?, | ||
| ) | ||
| .context("Failed to serialize response as JSON")?; | ||
| writeln!(printer.stdout_important(), "{response}")?; | ||
| Ok(ExitStatus::Success) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| pub(crate) mod dir; | ||
| pub(crate) mod helper; | ||
| pub(crate) mod login; | ||
| pub(crate) mod logout; | ||
| pub(crate) mod token; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.