Skip to content

Commit 4b0a4da

Browse files
authored
Fix bug where username from authentication cache could be ignored (#8345)
Basically, if username-only authentication came from the _cache_ instead of being present on the _request URL_ to start, we'd end up ignoring it during password lookups which breaks keyring. Includes some cosmetic changes to the logging and commentary in the middleware, because I was confused when reading the code and logs.
1 parent e26eed1 commit 4b0a4da

File tree

3 files changed

+152
-35
lines changed

3 files changed

+152
-35
lines changed

crates/uv-auth/src/middleware.rs

+49-30
Original file line numberDiff line numberDiff line change
@@ -131,25 +131,7 @@ impl Middleware for AuthMiddleware {
131131

132132
// In the middleware, existing credentials are already moved from the URL
133133
// to the headers so for display purposes we restore some information
134-
let url = if tracing::enabled!(tracing::Level::DEBUG) {
135-
let mut url = request.url().clone();
136-
if let Some(username) = credentials
137-
.as_ref()
138-
.and_then(|credentials| credentials.username())
139-
{
140-
let _ = url.set_username(username);
141-
};
142-
if credentials
143-
.as_ref()
144-
.and_then(|credentials| credentials.password())
145-
.is_some()
146-
{
147-
let _ = url.set_password(Some("****"));
148-
};
149-
url.to_string()
150-
} else {
151-
request.url().to_string()
152-
};
134+
let url = tracing_url(&request, credentials.as_ref());
153135
trace!("Handling request for {url}");
154136

155137
if let Some(credentials) = credentials {
@@ -198,13 +180,20 @@ impl Middleware for AuthMiddleware {
198180
// We have no credentials
199181
trace!("Request for {url} is unauthenticated, checking cache");
200182

201-
// Check the cache for a URL match
183+
// Check the cache for a URL match first, this can save us from making a failing request
202184
let credentials = self.cache().get_url(request.url(), &Username::none());
203185
if let Some(credentials) = credentials.as_ref() {
204186
request = credentials.authenticate(request);
187+
188+
// If it's fully authenticated, finish the request
205189
if credentials.password().is_some() {
190+
trace!("Request for {url} is fully authenticated");
206191
return self.complete_request(None, request, extensions, next).await;
207192
}
193+
194+
// If we just found a username, we'll make the request then look for password elsewhere
195+
// if it fails
196+
trace!("Found username for {url} in cache, attempting request");
208197
}
209198
let attempt_has_username = credentials
210199
.as_ref()
@@ -216,8 +205,12 @@ impl Middleware for AuthMiddleware {
216205
trace!("Checking for credentials for {url}");
217206
(request, None)
218207
} else {
219-
// Otherwise, attempt an anonymous request
220-
trace!("Attempting unauthenticated request for {url}");
208+
let url = tracing_url(&request, credentials.as_deref());
209+
if credentials.is_none() {
210+
trace!("Attempting unauthenticated request for {url}");
211+
} else {
212+
trace!("Attempting partially authenticated request for {url}");
213+
}
221214

222215
// <https://github.com/TrueLayer/reqwest-middleware/blob/abdf1844c37092d323683c2396b7eefda1418d3c/reqwest-retry/src/middleware.rs#L141-L149>
223216
// Clone the request so we can retry it on authentication failure
@@ -247,13 +240,17 @@ impl Middleware for AuthMiddleware {
247240
(retry_request, Some(response))
248241
};
249242

250-
// Check in the cache first
251-
let credentials = self.cache().get_realm(
252-
Realm::from(retry_request.url()),
253-
credentials
254-
.map(|credentials| credentials.to_username())
255-
.unwrap_or(Username::none()),
256-
);
243+
// Check if there are credentials in the realm-level cache
244+
let credentials = self
245+
.cache()
246+
.get_realm(
247+
Realm::from(retry_request.url()),
248+
credentials
249+
.as_ref()
250+
.map(|credentials| credentials.to_username())
251+
.unwrap_or(Username::none()),
252+
)
253+
.or(credentials);
257254
if let Some(credentials) = credentials.as_ref() {
258255
if credentials.password().is_some() {
259256
trace!("Retrying request for {url} with credentials from cache {credentials:?}");
@@ -265,7 +262,7 @@ impl Middleware for AuthMiddleware {
265262
}
266263

267264
// Then, fetch from external services.
268-
// Here we use the username from the cache if present.
265+
// Here, we use the username from the cache if present.
269266
if let Some(credentials) = self
270267
.fetch_credentials(credentials.as_deref(), retry_request.url())
271268
.await
@@ -406,5 +403,27 @@ impl AuthMiddleware {
406403
}
407404
}
408405

406+
fn tracing_url(request: &Request, credentials: Option<&Credentials>) -> String {
407+
if tracing::enabled!(tracing::Level::DEBUG) {
408+
let mut url = request.url().clone();
409+
if let Some(username) = credentials
410+
.as_ref()
411+
.and_then(|credentials| credentials.username())
412+
{
413+
let _ = url.set_username(username);
414+
};
415+
if credentials
416+
.as_ref()
417+
.and_then(|credentials| credentials.password())
418+
.is_some()
419+
{
420+
let _ = url.set_password(Some("****"));
421+
};
422+
url.to_string()
423+
} else {
424+
request.url().to_string()
425+
}
426+
}
427+
409428
#[cfg(test)]
410429
mod tests;

crates/uv-auth/src/middleware/tests.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -505,8 +505,8 @@ async fn test_credentials_in_keyring_seed() -> Result<(), Error> {
505505
let base_url = Url::parse(&server.uri())?;
506506
let cache = CredentialsCache::new();
507507

508-
// Seed _just_ the username. This cache entry should be ignored and we should
509-
// still find a password via the keyring.
508+
// Seed _just_ the username. We should pull the username from the cache if not present on the
509+
// URL.
510510
cache.insert(
511511
&base_url,
512512
Arc::new(Credentials::new(Some(username.to_string()), None)),
@@ -530,8 +530,8 @@ async fn test_credentials_in_keyring_seed() -> Result<(), Error> {
530530

531531
assert_eq!(
532532
client.get(server.uri()).send().await?.status(),
533-
401,
534-
"Credentials are not pulled from the keyring without a username"
533+
200,
534+
"The username is pulled from the cache, and the password from the keyring"
535535
);
536536

537537
let mut url = base_url.clone();

crates/uv/tests/it/lock.rs

+99-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use url::Url;
88

99
use crate::common::{
1010
self, build_vendor_links_url, decode_token, download_to_disk, packse_index_url, uv_snapshot,
11-
TestContext,
11+
venv_bin_path, TestContext,
1212
};
1313
use uv_fs::Simplified;
1414
use uv_static::EnvVars;
@@ -14689,6 +14689,104 @@ fn lock_change_requires_python() -> Result<()> {
1468914689
Ok(())
1469014690
}
1469114691

14692+
/// Pass credentials for a named index via environment variables.
14693+
#[test]
14694+
fn lock_keyring_credentials() -> Result<()> {
14695+
let keyring_context = TestContext::new("3.12");
14696+
14697+
// Install our keyring plugin
14698+
keyring_context
14699+
.pip_install()
14700+
.arg(
14701+
keyring_context
14702+
.workspace_root
14703+
.join("scripts")
14704+
.join("packages")
14705+
.join("keyring_test_plugin"),
14706+
)
14707+
.assert()
14708+
.success();
14709+
14710+
let context = TestContext::new("3.12");
14711+
14712+
let pyproject_toml = context.temp_dir.child("pyproject.toml");
14713+
pyproject_toml.write_str(
14714+
r#"
14715+
[project]
14716+
name = "foo"
14717+
version = "0.1.0"
14718+
requires-python = ">=3.12"
14719+
dependencies = ["iniconfig"]
14720+
14721+
[build-system]
14722+
requires = ["setuptools>=42"]
14723+
build-backend = "setuptools.build_meta"
14724+
14725+
[tool.uv]
14726+
keyring-provider = "subprocess"
14727+
14728+
[[tool.uv.index]]
14729+
name = "proxy"
14730+
url = "https://pypi-proxy.fly.dev/basic-auth/simple"
14731+
default = true
14732+
"#,
14733+
)?;
14734+
14735+
// Provide credentials via environment variables.
14736+
uv_snapshot!(context.filters(), context.lock()
14737+
.env(EnvVars::index_username("PROXY"), "public")
14738+
.env(EnvVars::KEYRING_TEST_CREDENTIALS, r#"{"pypi-proxy.fly.dev": {"public": "heron"}}"#)
14739+
.env(EnvVars::PATH, venv_bin_path(&keyring_context.venv)), @r###"
14740+
success: true
14741+
exit_code: 0
14742+
----- stdout -----
14743+
14744+
----- stderr -----
14745+
Request for public@https://pypi-proxy.fly.dev/basic-auth/simple/iniconfig/
14746+
Request for [email protected]
14747+
Resolved 2 packages in [TIME]
14748+
"###);
14749+
14750+
let lock = fs_err::read_to_string(context.temp_dir.join("uv.lock")).unwrap();
14751+
14752+
// The lockfile shout omit the credentials.
14753+
insta::with_settings!({
14754+
filters => context.filters(),
14755+
}, {
14756+
assert_snapshot!(
14757+
lock, @r###"
14758+
version = 1
14759+
requires-python = ">=3.12"
14760+
14761+
[options]
14762+
exclude-newer = "2024-03-25T00:00:00Z"
14763+
14764+
[[package]]
14765+
name = "foo"
14766+
version = "0.1.0"
14767+
source = { editable = "." }
14768+
dependencies = [
14769+
{ name = "iniconfig" },
14770+
]
14771+
14772+
[package.metadata]
14773+
requires-dist = [{ name = "iniconfig" }]
14774+
14775+
[[package]]
14776+
name = "iniconfig"
14777+
version = "2.0.0"
14778+
source = { registry = "https://pypi-proxy.fly.dev/basic-auth/simple" }
14779+
sdist = { url = "https://pypi-proxy.fly.dev/basic-auth/files/packages/d7/4b/cbd8e699e64a6f16ca3a8220661b5f83792b3017d0f79807cb8708d33913/iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3", size = 4646 }
14780+
wheels = [
14781+
{ url = "https://pypi-proxy.fly.dev/basic-auth/files/packages/ef/a6/62565a6e1cf69e10f5727360368e451d4b7f58beeac6173dc9db836a5b46/iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374", size = 5892 },
14782+
]
14783+
"###
14784+
);
14785+
});
14786+
14787+
Ok(())
14788+
}
14789+
1469214790
#[test]
1469314791
fn lock_multiple_sources() -> Result<()> {
1469414792
let context = TestContext::new("3.12");

0 commit comments

Comments
 (0)