|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::fmt::Write; |
| 3 | +use std::io::Read; |
| 4 | + |
| 5 | +use anyhow::{Context, Result, bail}; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | +use tracing::debug; |
| 8 | + |
| 9 | +use uv_auth::{AuthBackend, Credentials, PyxTokenStore}; |
| 10 | +use uv_client::BaseClientBuilder; |
| 11 | +use uv_preview::{Preview, PreviewFeatures}; |
| 12 | +use uv_redacted::DisplaySafeUrl; |
| 13 | +use uv_warnings::warn_user; |
| 14 | + |
| 15 | +use crate::{commands::ExitStatus, printer::Printer, settings::NetworkSettings}; |
| 16 | + |
| 17 | +/// Request format for the Bazel credential helper protocol. |
| 18 | +#[derive(Debug, Deserialize)] |
| 19 | +struct BazelCredentialRequest { |
| 20 | + uri: DisplaySafeUrl, |
| 21 | +} |
| 22 | + |
| 23 | +impl BazelCredentialRequest { |
| 24 | + fn from_str(s: &str) -> Result<Self> { |
| 25 | + serde_json::from_str(s).context("Failed to parse credential request as JSON") |
| 26 | + } |
| 27 | + |
| 28 | + fn from_stdin() -> Result<Self> { |
| 29 | + let mut buffer = String::new(); |
| 30 | + std::io::stdin() |
| 31 | + .read_to_string(&mut buffer) |
| 32 | + .context("Failed to read from stdin")?; |
| 33 | + |
| 34 | + Self::from_str(&buffer) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +/// Response format for the Bazel credential helper protocol. |
| 39 | +#[derive(Debug, Serialize, Default)] |
| 40 | +struct BazelCredentialResponse { |
| 41 | + headers: HashMap<String, Vec<String>>, |
| 42 | +} |
| 43 | + |
| 44 | +impl TryFrom<Credentials> for BazelCredentialResponse { |
| 45 | + fn try_from(creds: Credentials) -> Result<Self> { |
| 46 | + let header_str = creds |
| 47 | + .to_header_value() |
| 48 | + .to_str() |
| 49 | + // TODO: this is infallible in practice |
| 50 | + .context("Failed to convert header value to string")? |
| 51 | + .to_owned(); |
| 52 | + |
| 53 | + Ok(Self { |
| 54 | + headers: HashMap::from([("Authorization".to_owned(), vec![header_str])]), |
| 55 | + }) |
| 56 | + } |
| 57 | + |
| 58 | + type Error = anyhow::Error; |
| 59 | +} |
| 60 | + |
| 61 | +async fn credentials_for_url( |
| 62 | + url: &DisplaySafeUrl, |
| 63 | + preview: Preview, |
| 64 | + network_settings: &NetworkSettings, |
| 65 | +) -> Result<Option<Credentials>> { |
| 66 | + let pyx_store = PyxTokenStore::from_settings()?; |
| 67 | + |
| 68 | + // Use only the username from the URL, if present - discarding the password |
| 69 | + let url_credentials = Credentials::from_url(url); |
| 70 | + let username = url_credentials.as_ref().and_then(|c| c.username()); |
| 71 | + if url_credentials |
| 72 | + .as_ref() |
| 73 | + .map(|c| c.password().is_some()) |
| 74 | + .unwrap_or(false) |
| 75 | + { |
| 76 | + debug!("URL '{url}' contain a password; ignoring"); |
| 77 | + } |
| 78 | + |
| 79 | + if pyx_store.is_known_domain(url) { |
| 80 | + if username.is_some() { |
| 81 | + bail!( |
| 82 | + "Cannot specify a username for URLs under {}", |
| 83 | + url.host() |
| 84 | + .map(|host| host.to_string()) |
| 85 | + .unwrap_or(url.to_string()) |
| 86 | + ); |
| 87 | + } |
| 88 | + let client = BaseClientBuilder::new( |
| 89 | + network_settings.connectivity, |
| 90 | + network_settings.native_tls, |
| 91 | + network_settings.allow_insecure_host.clone(), |
| 92 | + preview, |
| 93 | + network_settings.timeout, |
| 94 | + network_settings.retries, |
| 95 | + ) |
| 96 | + .auth_integration(uv_client::AuthIntegration::NoAuthMiddleware) |
| 97 | + .build(); |
| 98 | + let token = pyx_store |
| 99 | + .access_token(client.for_host(pyx_store.api()).raw_client(), 0) |
| 100 | + .await |
| 101 | + .context("Authentication failure")? |
| 102 | + .context("No access token found")?; |
| 103 | + return Ok(Some(Credentials::bearer(token.into_bytes()))); |
| 104 | + } |
| 105 | + let backend = AuthBackend::from_settings(preview).await?; |
| 106 | + let credentials = match &backend { |
| 107 | + AuthBackend::System(provider) => provider.fetch(url, username).await, |
| 108 | + AuthBackend::TextStore(store, _lock) => store.get_credentials(url, username).cloned(), |
| 109 | + }; |
| 110 | + Ok(credentials) |
| 111 | +} |
| 112 | + |
| 113 | +/// Implement the Bazel credential helper protocol. |
| 114 | +/// |
| 115 | +/// Reads a JSON request from stdin containing a URI, looks up credentials |
| 116 | +/// for that URI using uv's authentication backends, and writes a JSON response |
| 117 | +/// to stdout containing HTTP headers (if credentials are found). |
| 118 | +/// |
| 119 | +/// Protocol specification TLDR: |
| 120 | +/// - Input (stdin): `{"uri": "https://example.com/path"}` |
| 121 | +/// - Output (stdout): `{"headers": {"Authorization": ["Basic ..."]}}` or `{"headers": {}}` |
| 122 | +/// - Errors: Written to stderr with non-zero exit code |
| 123 | +/// |
| 124 | +/// Full spec is [available here](https://github.com/bazelbuild/proposals/blob/main/designs/2022-06-07-bazel-credential-helpers.md) |
| 125 | +pub(crate) async fn helper( |
| 126 | + preview: Preview, |
| 127 | + network_settings: &NetworkSettings, |
| 128 | + printer: Printer, |
| 129 | +) -> Result<ExitStatus> { |
| 130 | + if !preview.is_enabled(PreviewFeatures::AUTH_HELPER) { |
| 131 | + warn_user!( |
| 132 | + "The `uv auth helper` command is experimental and may change without warning. Pass `--preview-features {}` to disable this warning", |
| 133 | + PreviewFeatures::AUTH_HELPER |
| 134 | + ); |
| 135 | + } |
| 136 | + |
| 137 | + let request = BazelCredentialRequest::from_stdin()?; |
| 138 | + |
| 139 | + // TODO: make this logic generic over the protocol by providing `request.uri` from a |
| 140 | + // trait - that should help with adding new protocols |
| 141 | + let credentials = credentials_for_url(&request.uri, preview, network_settings).await?; |
| 142 | + |
| 143 | + let response = serde_json::to_string( |
| 144 | + &credentials |
| 145 | + .map(BazelCredentialResponse::try_from) |
| 146 | + .unwrap_or_else(|| Ok(BazelCredentialResponse::default()))?, |
| 147 | + ) |
| 148 | + .context("Failed to serialize response as JSON")?; |
| 149 | + writeln!(printer.stdout_important(), "{response}")?; |
| 150 | + Ok(ExitStatus::Success) |
| 151 | +} |
0 commit comments