From 3b7d95bd5af66d68436b66e174a64f4a3496540d Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Sun, 8 Nov 2026 04:46:33 +0000 Subject: [PATCH 1/2] Key logins by the registry without its trailing slash A login was stored under the registry URL exactly as given, so `lpm login --registry https://lpm.dev/` saved a session that a later command for https://lpm.dev didn't see, and `/api/cli/exchange` and the refresh were requested at `//api/...`. The trailing slash couldn't simply be trimmed when the CLI started, since that would have hidden logins already stored under the slashed spelling. lpm-auth now derives every credential key without trailing slashes: the keychain accounts, the encrypted-file keys, the credential authority records, the session lock and the expiry and OTP metadata. When a read finds nothing under that key, it reads the slashed spelling as earlier releases keyed it, and moves what it finds, with its expiry metadata, to the new key under the same store lock. Logout clears both spellings. With that, the CLI trims the registry once when it starts, and the session manager trims what it's given, which fixes every `/api/...` URL built from it. The MCP server derives the same keychain account names and changes with this (lpm-dev/mcp-server). Co-Authored-By: Claude Opus 5.5 --- crates/lpm-auth/src/credential_authority.rs | 3 +- crates/lpm-auth/src/lib.rs | 227 ++++++++++++++++++-- crates/lpm-auth/src/session.rs | 5 +- crates/lpm-cli/src/cli/dispatch.rs | 6 +- tests/workflows/tests/auth_lifecycle.rs | 39 ++++ 5 files changed, 264 insertions(+), 16 deletions(-) diff --git a/crates/lpm-auth/src/credential_authority.rs b/crates/lpm-auth/src/credential_authority.rs index 09acf48d8..d701a0c26 100644 --- a/crates/lpm-auth/src/credential_authority.rs +++ b/crates/lpm-auth/src/credential_authority.rs @@ -20,6 +20,7 @@ impl CredentialKind { } pub(super) fn file_key(self, registry: &str) -> String { + let registry = super::registry_key(registry); match self { Self::Access => registry.to_owned(), Self::Refresh => format!("refresh:{registry}"), @@ -212,7 +213,7 @@ fn credential_id(registry: &str, kind: CredentialKind) -> String { let mut digest = Sha256::new(); digest.update(kind.label().as_bytes()); digest.update([0]); - digest.update(registry.as_bytes()); + digest.update(super::registry_key(registry).as_bytes()); hex::encode(digest.finalize()) } diff --git a/crates/lpm-auth/src/lib.rs b/crates/lpm-auth/src/lib.rs index da7caf1fa..1d95ef832 100644 --- a/crates/lpm-auth/src/lib.rs +++ b/crates/lpm-auth/src/lib.rs @@ -632,7 +632,17 @@ pub(crate) fn clear_login_state_unlocked(registry_url: &str) -> Result<(), Strin let access_result = clear_stored_access_token_unlocked(registry_url); let refresh_result = clear_stored_refresh_token_unlocked(registry_url); let expiry_result = clear_token_expiry_checked(registry_url); - combine_credential_results([access_result, refresh_result, expiry_result]) + // A login that an earlier release stored under the registry's + // trailing-slash spelling, and that nothing has read since, goes too. + let slashed = slashed_registry(registry_url); + let slashed_result = with_slashed_registry_keys(|| { + combine_credential_results([ + clear_stored_access_token_unlocked(&slashed), + clear_stored_refresh_token_unlocked(&slashed), + clear_token_expiry_checked(&slashed), + ]) + }); + combine_credential_results([access_result, refresh_result, expiry_result, slashed_result]) } /// Clear all local login state for a registry. @@ -936,10 +946,107 @@ fn get_stored_credential_with_backend_result( notice: impl FnOnce(), ) -> Result, CredentialReadError> { with_credential_store_lock(|| { - get_stored_credential_with_backend_unlocked(registry, kind, notice) + match get_stored_credential_with_backend_unlocked(registry, kind, notice)? { + Some(stored) => Ok(Some(stored)), + None => move_slashed_login_credential_unlocked(registry, kind), + } }) } +thread_local! { + /// Set while this thread reads or clears a login stored before + /// credentials were keyed without the registry's trailing slash. + static SLASHED_REGISTRY_KEYS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The spelling of `registry` that credentials and their metadata are keyed +/// by: without trailing slashes, so `https://lpm.dev/` and `https://lpm.dev` +/// name one login. +pub(crate) fn registry_key(registry: &str) -> &str { + if SLASHED_REGISTRY_KEYS.with(std::cell::Cell::get) { + registry + } else { + registry.trim_end_matches('/') + } +} + +/// Runs `action` with credential keys derived from the registry exactly as +/// given, as releases did before keys dropped the trailing slash. +fn with_slashed_registry_keys(action: impl FnOnce() -> T) -> T { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + SLASHED_REGISTRY_KEYS.with(|slashed| slashed.set(false)); + } + } + SLASHED_REGISTRY_KEYS.with(|slashed| slashed.set(true)); + let _restore = Restore; + action() +} + +/// How a login from `registry` was keyed when it was stored under its +/// trailing-slash spelling. +fn slashed_registry(registry: &str) -> String { + format!("{}/", registry.trim_end_matches('/')) +} + +/// Moves a credential that a login with a trailing-slash registry stored +/// before keys dropped the slash, with its expiry metadata, to the key the +/// registry has now. The caller holds the credential store lock. +fn move_slashed_login_credential_unlocked( + registry: &str, + kind: CredentialKind, +) -> Result, CredentialReadError> { + let slashed = slashed_registry(registry); + let Some(stored) = with_slashed_registry_keys(|| { + get_stored_credential_with_backend_unlocked(&slashed, kind, || {}) + })? + else { + return Ok(None); + }; + let canonical = registry.trim_end_matches('/'); + let written = set_credential_with_keychain_writer_unlocked( + canonical, + kind, + &stored.token, + || match kind { + CredentialKind::Access => set_token_in_keychain(canonical, &stored.token), + CredentialKind::Refresh => { + set_password_in_keychain_account(&scoped_refresh_account(canonical), &stored.token) + } + }, + ); + let backend = match written { + Ok(backend) => backend, + Err(error) => { + tracing::warn!("could not move a login stored under {slashed}: {error}"); + return Ok(Some(stored)); + } + }; + if let Err(error) = mutate_token_expiries(HomeWrite::AddsNothing, |expiries| { + match expiries.remove(&slashed) { + Some(metadata) => { + expiries.entry(canonical.to_owned()).or_insert(metadata); + true + } + None => false, + } + }) { + tracing::warn!("could not move the session metadata stored under {slashed}: {error}"); + } + let cleared = with_slashed_registry_keys(|| match kind { + CredentialKind::Access => clear_stored_access_token_under_store_lock(&slashed), + CredentialKind::Refresh => clear_stored_refresh_token_under_store_lock(&slashed), + }); + if let Err(error) = cleared { + tracing::warn!("could not remove the login stored under {slashed}: {error}"); + } + Ok(Some(StoredToken { + token: stored.token, + backend, + })) +} + fn get_stored_credential_with_backend_unlocked( registry: &str, kind: CredentialKind, @@ -1525,7 +1632,9 @@ pub fn read_token_expiries() -> std::collections::HashMap { /// Store a token expiry reminder. pub fn set_token_expiry(registry: &str, expires: &str) { if let Err(error) = mutate_token_expiries(HomeWrite::Adds, |expiries| { - let entry = expiries.entry(registry.to_string()).or_default(); + let entry = expiries + .entry(registry_key(registry).to_owned()) + .or_default(); entry.expires = expires.to_string(); entry.reminded_7d = false; entry.reminded_1d = false; @@ -1548,7 +1657,9 @@ pub(crate) fn set_session_access_token_expiry_checked( expires_at: &str, ) -> Result<(), String> { mutate_token_expiries(HomeWrite::Adds, |expiries| { - let entry = expiries.entry(registry.to_string()).or_default(); + let entry = expiries + .entry(registry_key(registry).to_owned()) + .or_default(); entry.session_access_expires_at = Some(expires_at.to_string()); entry.expires.clear(); entry.reminded_7d = false; @@ -1560,7 +1671,7 @@ pub(crate) fn set_session_access_token_expiry_checked( fn session_access_token_expiry(registry: &str) -> Option> { let expiries = read_token_expiries(); let expiry = expiries - .get(registry)? + .get(registry_key(registry))? .session_access_expires_at .as_deref()?; @@ -1602,7 +1713,7 @@ pub fn clear_token_expiry(registry: &str) { /// Remove token-expiry metadata and report storage failures to the caller. pub fn clear_token_expiry_checked(registry: &str) -> Result<(), String> { mutate_token_expiries(HomeWrite::AddsNothing, |expiries| { - expiries.remove(registry).is_some() + expiries.remove(registry_key(registry)).is_some() }) } @@ -1663,14 +1774,16 @@ pub struct TokenExpiry { /// Check if a registry has OTP/2FA enabled (set during login). pub fn is_otp_required(registry: &str) -> bool { read_token_expiries() - .get(registry) + .get(registry_key(registry)) .is_some_and(|e| e.otp_required) } /// Set the OTP/2FA preference for a registry. pub fn set_otp_required(registry: &str, required: bool) { if let Err(error) = mutate_token_expiries(HomeWrite::Adds, |expiries| { - let entry = expiries.entry(registry.to_string()).or_default(); + let entry = expiries + .entry(registry_key(registry).to_owned()) + .or_default(); entry.otp_required = required; true }) { @@ -1686,14 +1799,14 @@ const REFRESH_ACCOUNT_PREFIX: &str = "lpm-refresh"; fn scoped_refresh_account(registry_url: &str) -> String { use sha2::{Digest, Sha256}; - let hash = Sha256::digest(registry_url.as_bytes()); + let hash = Sha256::digest(registry_key(registry_url).as_bytes()); format!("{}:{}", REFRESH_ACCOUNT_PREFIX, hex::encode(&hash[..8])) } pub(crate) fn session_lock_path(registry_url: &str) -> Result { use sha2::{Digest, Sha256}; - let hash = Sha256::digest(registry_url.as_bytes()); + let hash = Sha256::digest(registry_key(registry_url).as_bytes()); let lpm_dir = lpm_dir()?; let lock_dir = lpm_dir.join("locks"); std::fs::create_dir_all(&lock_dir).map_err(|error| format!("lock mkdir error: {error}"))?; @@ -1825,7 +1938,7 @@ pub async fn store_rotated_access_token_if_current( || set_token_in_keychain(registry, replacement), )?; mutate_token_expiries(HomeWrite::Adds, |expiries| { - let entry = expiries.entry(registry.to_owned()).or_default(); + let entry = expiries.entry(registry_key(registry).to_owned()).or_default(); entry.reminded_7d = false; entry.reminded_1d = false; if refresh.is_some() { @@ -2067,7 +2180,7 @@ fn is_npmjs_token_key(key: &str) -> bool { fn scoped_account(registry_url: &str) -> String { use sha2::{Digest, Sha256}; - let hash = Sha256::digest(registry_url.as_bytes()); + let hash = Sha256::digest(registry_key(registry_url).as_bytes()); format!("{}:{}", KEYCHAIN_ACCOUNT_PREFIX, hex::encode(&hash[..8])) } @@ -2993,6 +3106,86 @@ mod tests { }); } + #[test] + fn both_spellings_of_a_registry_name_one_login() { + with_temp_home(|_| { + let _env = LocalEnvGuard::update([("LPM_FORCE_FILE_AUTH", Some("1".into()))]); + + set_token("https://registry.example/", "access").unwrap(); + set_refresh_token("https://registry.example/", "refresh").unwrap(); + set_session_access_token_expiry("https://registry.example/", "2099-01-01T00:00:00Z"); + + assert_eq!( + get_token("https://registry.example").as_deref(), + Some("access") + ); + assert_eq!( + get_refresh_token("https://registry.example").as_deref(), + Some("refresh") + ); + assert!(!should_refresh_session_access_token( + "https://registry.example" + )); + }); + } + + #[test] + fn a_login_stored_under_a_trailing_slash_moves_to_the_registry_key() { + with_temp_home(|_| { + let _env = LocalEnvGuard::update([("LPM_FORCE_FILE_AUTH", Some("1".into()))]); + // As a release that keyed logins by the exact spelling stored it. + with_slashed_registry_keys(|| { + set_token("https://registry.example/", "access").unwrap(); + set_refresh_token("https://registry.example/", "refresh").unwrap(); + set_session_access_token_expiry( + "https://registry.example/", + "2099-01-01T00:00:00Z", + ); + }); + + assert_eq!( + get_token("https://registry.example").as_deref(), + Some("access") + ); + assert_eq!( + get_refresh_token("https://registry.example").as_deref(), + Some("refresh") + ); + assert!(!should_refresh_session_access_token( + "https://registry.example" + )); + assert_eq!( + with_slashed_registry_keys(|| get_stored_access_token("https://registry.example/")), + None, + "the slashed copy is removed once moved" + ); + assert_eq!( + get_token("https://registry.example/").as_deref(), + Some("access") + ); + }); + } + + #[test] + fn logging_out_also_clears_a_login_stored_under_a_trailing_slash() { + with_temp_home(|_| { + let _env = LocalEnvGuard::update([("LPM_FORCE_FILE_AUTH", Some("1".into()))]); + with_slashed_registry_keys(|| { + set_token("https://registry.example/", "access").unwrap(); + set_refresh_token("https://registry.example/", "refresh").unwrap(); + }); + + clear_login_state("https://registry.example").unwrap(); + + assert_eq!( + with_slashed_registry_keys(|| get_stored_access_token("https://registry.example/")), + None + ); + assert_eq!(get_token("https://registry.example"), None); + assert_eq!(get_refresh_token("https://registry.example"), None); + }); + } + #[test] fn credential_update_preserves_unreadable_encrypted_store() { with_temp_home(|_| { @@ -4074,9 +4267,11 @@ mod tests { #[test] fn scoped_account_matches_mcp_known_answer_vectors() { + // Both spellings of a registry share one account; the MCP server + // derives the same names to read the login. for (registry_url, expected_account) in [ ("https://lpm.dev", "auth-token:bd90fc32d95766d5"), - ("https://lpm.dev/", "auth-token:89f54e26677b97ec"), + ("https://lpm.dev/", "auth-token:bd90fc32d95766d5"), ("http://localhost:3000", "auth-token:f1de9e489ba88cb1"), ("http://127.0.0.1:8787", "auth-token:b1a61bf29a38ff36"), ( @@ -4086,6 +4281,12 @@ mod tests { ] { assert_eq!(scoped_account(registry_url), expected_account); } + // The account a release before canonical keys used for the slashed + // spelling, which the MCP server still tries for such logins. + assert_eq!( + with_slashed_registry_keys(|| scoped_account("https://lpm.dev/")), + "auth-token:89f54e26677b97ec" + ); } #[cfg(target_os = "macos")] diff --git a/crates/lpm-auth/src/session.rs b/crates/lpm-auth/src/session.rs index 9c186d2d1..16b76378c 100644 --- a/crates/lpm-auth/src/session.rs +++ b/crates/lpm-auth/src/session.rs @@ -261,7 +261,10 @@ impl SessionManager { /// SessionManager itself reads `LPM_TOKEN` so that the source can /// be classified correctly. pub fn new(registry_url: impl Into, explicit_flag_token: Option) -> Self { - let registry_url = registry_url.into(); + let mut registry_url = registry_url.into(); + // Requests such as the refresh append `/api/...`, and stored logins + // are keyed without the slash. + registry_url.truncate(registry_url.trim_end_matches('/').len()); // Eager classification is limited to env/flag. Keychain reads are // deferred to `ensure_classified`, called on the first method that // actually needs the cached value. On macOS the keychain IPC costs diff --git a/crates/lpm-cli/src/cli/dispatch.rs b/crates/lpm-cli/src/cli/dispatch.rs index 8a217509c..92738135e 100644 --- a/crates/lpm-cli/src/cli/dispatch.rs +++ b/crates/lpm-cli/src/cli/dispatch.rs @@ -319,10 +319,14 @@ async fn async_main(cli: Cli) -> Result<()> { // thinking it means `warn` would get the fail-closed posture // they did NOT ask for, with no signal that their intent // didn't take effect. + // Paths such as `/api/cli/exchange` are appended to it, and stored logins + // are keyed without the trailing slash. let registry_url = cli .registry .as_deref() - .unwrap_or(lpm_common::DEFAULT_REGISTRY_URL); + .map_or(lpm_common::DEFAULT_REGISTRY_URL, |url| { + url.trim_end_matches('/') + }); let setup_ci_target = match preflight_setup_ci( &command, diff --git a/tests/workflows/tests/auth_lifecycle.rs b/tests/workflows/tests/auth_lifecycle.rs index e541c2f85..bb35a216f 100644 --- a/tests/workflows/tests/auth_lifecycle.rs +++ b/tests/workflows/tests/auth_lifecycle.rs @@ -221,6 +221,45 @@ async fn assert_targeted_builtin_logout_preserves_primary_session( ); } +#[tokio::test] +async fn a_login_stored_under_a_trailing_slash_url_is_found_without_it() { + let project = TempProject::empty(r#"{"name":"auth-slash-test","version":"1.0.0"}"#); + let mock = MockRegistry::start().await; + mock.with_authenticated_whoami("slashed-access", "testuser", "test@example.com") + .await; + // As `lpm login --registry /` stored it before logins were keyed + // without the trailing slash. + let slashed = format!("{}/", mock.url()); + seed_sessions( + project.home(), + &[SessionSeed { + registry_url: &slashed, + access_token: Some("slashed-access"), + refresh_token: Some("slashed-refresh"), + session_access_expires_at: Some("2099-01-01T00:00:00Z"), + }], + ); + + let output = lpm_with_registry(&project, &mock.url()) + .args(["whoami", "--json"]) + .output() + .expect("failed to run lpm whoami"); + + assert!( + output.status.success(), + "whoami missed the slashed login:\nstdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + assert_eq!(parse_json_output(&output.stdout)["username"], "testuser"); + let credentials = read_credentials(project.home()); + assert_eq!(credentials[&mock.url()], "slashed-access"); + assert!( + credentials.get(&slashed).is_none(), + "the slashed copy is moved, not left behind: {credentials:?}" + ); +} + #[tokio::test] async fn whoami_recovers_session_from_refresh_token_only() { let project = TempProject::empty(r#"{"name":"auth-refresh-test","version":"1.0.0"}"#); From a534b6400da46e7d776e09621e6199cddfc00a1e Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Sun, 8 Nov 2026 05:29:06 +0000 Subject: [PATCH 2/2] Move a slashed login only into an unused registry key The move took an access and a refresh credential separately, so one login's access token could pair with another's refresh token, and a login cleared under the registry key made room for the slashed one to return. A slashed login now moves whole, with its session metadata and undone on a partial failure, only while the registry key has no credential or authority record. Clearing a credential under the registry key retires the slashed login. Co-Authored-By: Claude Opus 5.5 --- crates/lpm-auth/src/credential_authority.rs | 7 + crates/lpm-auth/src/lib.rs | 315 +++++++++++++++----- 2 files changed, 243 insertions(+), 79 deletions(-) diff --git a/crates/lpm-auth/src/credential_authority.rs b/crates/lpm-auth/src/credential_authority.rs index d701a0c26..05a30862d 100644 --- a/crates/lpm-auth/src/credential_authority.rs +++ b/crates/lpm-auth/src/credential_authority.rs @@ -19,6 +19,13 @@ impl CredentialKind { } } + pub(super) fn other(self) -> Self { + match self { + Self::Access => Self::Refresh, + Self::Refresh => Self::Access, + } + } + pub(super) fn file_key(self, registry: &str) -> String { let registry = super::registry_key(registry); match self { diff --git a/crates/lpm-auth/src/lib.rs b/crates/lpm-auth/src/lib.rs index 1d95ef832..7dad36454 100644 --- a/crates/lpm-auth/src/lib.rs +++ b/crates/lpm-auth/src/lib.rs @@ -479,6 +479,17 @@ fn clear_stored_credential_under_store_lock( registry: &str, kind: CredentialKind, keychain_clear: impl FnOnce() -> Result<(), String>, +) -> Result<(), String> { + let cleared = clear_credential_spelling_under_store_lock(registry, kind, keychain_clear); + combine_credential_results([cleared, retire_slashed_login_under_store_lock(registry)]) +} + +/// Clears the `kind` credential stored under exactly this spelling of the +/// registry, leaving a login under its trailing-slash spelling alone. +fn clear_credential_spelling_under_store_lock( + registry: &str, + kind: CredentialKind, + keychain_clear: impl FnOnce() -> Result<(), String>, ) -> Result<(), String> { let file_key = kind.file_key(registry); // A failed delete must leave surviving backend bytes unreadable. @@ -488,6 +499,50 @@ fn clear_stored_credential_under_store_lock( credential_authority::clear(registry, kind) } +/// Removes a login an earlier release stored under the registry's +/// trailing-slash spelling. Once a credential under the registry key is +/// cleared, that login would otherwise look like the one to move there. +fn retire_slashed_login_under_store_lock(registry: &str) -> Result<(), String> { + if SLASHED_REGISTRY_KEYS.with(std::cell::Cell::get) { + return Ok(()); + } + let slashed = slashed_registry(registry); + with_slashed_registry_keys(|| { + combine_credential_results([ + clear_credential_spelling_under_store_lock(&slashed, CredentialKind::Access, || { + clear_credential_from_keychain(&slashed, CredentialKind::Access) + }), + clear_credential_spelling_under_store_lock(&slashed, CredentialKind::Refresh, || { + clear_credential_from_keychain(&slashed, CredentialKind::Refresh) + }), + clear_token_expiry_checked(&slashed), + ]) + }) +} + +#[cfg_attr( + test, + expect( + clippy::unnecessary_wraps, + reason = "tests keep the system keychain untouched" + ) +)] +fn clear_credential_from_keychain(registry: &str, kind: CredentialKind) -> Result<(), String> { + #[cfg(test)] + { + let _ = (registry, kind); + Ok(()) + } + + #[cfg(not(test))] + match kind { + CredentialKind::Access => clear_token_from_keychain(registry), + CredentialKind::Refresh => { + clear_password_from_keychain_account(&scoped_refresh_account(registry)) + } + } +} + fn with_credential_store_lock>( operation: impl FnOnce() -> Result, ) -> Result { @@ -554,17 +609,9 @@ pub(crate) fn clear_stored_access_token_unlocked(registry_url: &str) -> Result<( } fn clear_stored_access_token_under_store_lock(registry_url: &str) -> Result<(), String> { - #[cfg(test)] - { - clear_stored_credential_under_store_lock(registry_url, CredentialKind::Access, || Ok(())) - } - - #[cfg(not(test))] - { - clear_stored_credential_under_store_lock(registry_url, CredentialKind::Access, || { - clear_token_from_keychain(registry_url) - }) - } + clear_stored_credential_under_store_lock(registry_url, CredentialKind::Access, || { + clear_credential_from_keychain(registry_url, CredentialKind::Access) + }) } pub(crate) fn clear_stored_refresh_token_unlocked(registry_url: &str) -> Result<(), String> { @@ -572,18 +619,9 @@ pub(crate) fn clear_stored_refresh_token_unlocked(registry_url: &str) -> Result< } fn clear_stored_refresh_token_under_store_lock(registry_url: &str) -> Result<(), String> { - #[cfg(test)] - { - clear_stored_credential_under_store_lock(registry_url, CredentialKind::Refresh, || Ok(())) - } - - #[cfg(not(test))] - { - let account = scoped_refresh_account(registry_url); - clear_stored_credential_under_store_lock(registry_url, CredentialKind::Refresh, || { - clear_password_from_keychain_account(&account) - }) - } + clear_stored_credential_under_store_lock(registry_url, CredentialKind::Refresh, || { + clear_credential_from_keychain(registry_url, CredentialKind::Refresh) + }) } pub(crate) fn clear_rejected_refresh_session_if_current( @@ -632,17 +670,7 @@ pub(crate) fn clear_login_state_unlocked(registry_url: &str) -> Result<(), Strin let access_result = clear_stored_access_token_unlocked(registry_url); let refresh_result = clear_stored_refresh_token_unlocked(registry_url); let expiry_result = clear_token_expiry_checked(registry_url); - // A login that an earlier release stored under the registry's - // trailing-slash spelling, and that nothing has read since, goes too. - let slashed = slashed_registry(registry_url); - let slashed_result = with_slashed_registry_keys(|| { - combine_credential_results([ - clear_stored_access_token_unlocked(&slashed), - clear_stored_refresh_token_unlocked(&slashed), - clear_token_expiry_checked(&slashed), - ]) - }); - combine_credential_results([access_result, refresh_result, expiry_result, slashed_result]) + combine_credential_results([access_result, refresh_result, expiry_result]) } /// Clear all local login state for a registry. @@ -700,18 +728,7 @@ pub fn clear_rejected_legacy_session_if_current( } let expiry_result = clear_token_expiry_checked(registry_url); - #[cfg(test)] - let access_result = clear_stored_credential_under_store_lock( - registry_url, - CredentialKind::Access, - || Ok(()), - ); - #[cfg(not(test))] - let access_result = clear_stored_credential_under_store_lock( - registry_url, - CredentialKind::Access, - || clear_token_from_keychain(registry_url), - ); + let access_result = clear_stored_access_token_under_store_lock(registry_url); combine_credential_results([access_result, expiry_result])?; Ok(true) }) @@ -948,7 +965,7 @@ fn get_stored_credential_with_backend_result( with_credential_store_lock(|| { match get_stored_credential_with_backend_unlocked(registry, kind, notice)? { Some(stored) => Ok(Some(stored)), - None => move_slashed_login_credential_unlocked(registry, kind), + None => move_slashed_login_unlocked(registry, kind), } }) } @@ -973,14 +990,13 @@ pub(crate) fn registry_key(registry: &str) -> &str { /// Runs `action` with credential keys derived from the registry exactly as /// given, as releases did before keys dropped the trailing slash. fn with_slashed_registry_keys(action: impl FnOnce() -> T) -> T { - struct Restore; + struct Restore(bool); impl Drop for Restore { fn drop(&mut self) { - SLASHED_REGISTRY_KEYS.with(|slashed| slashed.set(false)); + SLASHED_REGISTRY_KEYS.with(|slashed| slashed.set(self.0)); } } - SLASHED_REGISTRY_KEYS.with(|slashed| slashed.set(true)); - let _restore = Restore; + let _restore = Restore(SLASHED_REGISTRY_KEYS.with(|slashed| slashed.replace(true))); action() } @@ -990,63 +1006,102 @@ fn slashed_registry(registry: &str) -> String { format!("{}/", registry.trim_end_matches('/')) } -/// Moves a credential that a login with a trailing-slash registry stored -/// before keys dropped the slash, with its expiry metadata, to the key the -/// registry has now. The caller holds the credential store lock. -fn move_slashed_login_credential_unlocked( +/// Moves a login that a release keying credentials by the registry's exact +/// spelling stored under its trailing-slash spelling to the key the registry +/// has now, and returns its `kind` credential. The access and refresh tokens +/// move together with the session metadata, and only while the registry key +/// holds no login of its own, so credentials from two logins never pair up. +/// The caller holds the credential store lock and found no `kind` credential +/// under the registry key. +fn move_slashed_login_unlocked( registry: &str, kind: CredentialKind, ) -> Result, CredentialReadError> { let slashed = slashed_registry(registry); - let Some(stored) = with_slashed_registry_keys(|| { - get_stored_credential_with_backend_unlocked(&slashed, kind, || {}) - })? - else { + let read_slashed = |kind| { + with_slashed_registry_keys(|| { + get_stored_credential_with_backend_unlocked(&slashed, kind, || {}) + }) + }; + let Some(requested) = read_slashed(kind)? else { return Ok(None); }; let canonical = registry.trim_end_matches('/'); - let written = set_credential_with_keychain_writer_unlocked( - canonical, - kind, - &stored.token, - || match kind { - CredentialKind::Access => set_token_in_keychain(canonical, &stored.token), - CredentialKind::Refresh => { - set_password_in_keychain_account(&scoped_refresh_account(canonical), &stored.token) - } - }, - ); - let backend = match written { + // A record under the registry key, even a revocation a failed clear left, + // means that key's login was in use, so the slashed one isn't adopted. + for kind in [kind, kind.other()] { + if credential_authority::read(canonical, kind)?.is_some() { + return Ok(None); + } + } + if get_stored_credential_with_backend_unlocked(canonical, kind.other(), || {})?.is_some() { + return Ok(None); + } + let other = read_slashed(kind.other())?; + + let backend = match write_moved_credential_unlocked(canonical, kind, &requested.token) { Ok(backend) => backend, Err(error) => { - tracing::warn!("could not move a login stored under {slashed}: {error}"); - return Ok(Some(stored)); + tracing::warn!("could not move the login stored under {slashed}: {error}"); + return Ok(Some(requested)); } }; + if let Some(other) = &other + && let Err(error) = write_moved_credential_unlocked(canonical, kind.other(), &other.token) + { + tracing::warn!("could not move the login stored under {slashed}: {error}"); + if let Err(error) = clear_credential_spelling(canonical, kind) { + tracing::warn!( + "could not undo a partial move of the login stored under {slashed}: {error}" + ); + } + return Ok(Some(requested)); + } if let Err(error) = mutate_token_expiries(HomeWrite::AddsNothing, |expiries| { match expiries.remove(&slashed) { Some(metadata) => { - expiries.entry(canonical.to_owned()).or_insert(metadata); + expiries.insert(canonical.to_owned(), metadata); true } - None => false, + None => expiries.remove(canonical).is_some(), } }) { tracing::warn!("could not move the session metadata stored under {slashed}: {error}"); } - let cleared = with_slashed_registry_keys(|| match kind { - CredentialKind::Access => clear_stored_access_token_under_store_lock(&slashed), - CredentialKind::Refresh => clear_stored_refresh_token_under_store_lock(&slashed), + let cleared = with_slashed_registry_keys(|| { + combine_credential_results([ + clear_credential_spelling(&slashed, kind), + clear_credential_spelling(&slashed, kind.other()), + ]) }); if let Err(error) = cleared { tracing::warn!("could not remove the login stored under {slashed}: {error}"); } Ok(Some(StoredToken { - token: stored.token, + token: requested.token, backend, })) } +fn write_moved_credential_unlocked( + registry: &str, + kind: CredentialKind, + token: &str, +) -> Result { + set_credential_with_keychain_writer_unlocked(registry, kind, token, || match kind { + CredentialKind::Access => set_token_in_keychain(registry, token), + CredentialKind::Refresh => { + set_password_in_keychain_account(&scoped_refresh_account(registry), token) + } + }) +} + +fn clear_credential_spelling(registry: &str, kind: CredentialKind) -> Result<(), String> { + clear_credential_spelling_under_store_lock(registry, kind, || { + clear_credential_from_keychain(registry, kind) + }) +} + fn get_stored_credential_with_backend_unlocked( registry: &str, kind: CredentialKind, @@ -3166,6 +3221,108 @@ mod tests { }); } + #[test] + fn a_trailing_slash_login_is_not_merged_into_the_login_under_the_registry_key() { + with_temp_home(|_| { + let _env = LocalEnvGuard::update([("LPM_FORCE_FILE_AUTH", Some("1".into()))]); + set_token("https://registry.example", "account-a-access").unwrap(); + with_slashed_registry_keys(|| { + set_token("https://registry.example/", "account-b-access").unwrap(); + set_refresh_token("https://registry.example/", "account-b-refresh").unwrap(); + }); + + assert_eq!(get_refresh_token("https://registry.example"), None); + assert_eq!( + get_token("https://registry.example").as_deref(), + Some("account-a-access") + ); + assert_eq!(get_refresh_token("https://registry.example"), None); + }); + } + + #[test] + fn a_trailing_slash_login_moves_its_tokens_and_session_metadata_together() { + with_temp_home(|_| { + let _env = LocalEnvGuard::update([("LPM_FORCE_FILE_AUTH", Some("1".into()))]); + set_session_access_token_expiry("https://registry.example", "2000-01-01T00:00:00Z"); + with_slashed_registry_keys(|| { + set_token("https://registry.example/", "access").unwrap(); + set_refresh_token("https://registry.example/", "refresh").unwrap(); + set_session_access_token_expiry( + "https://registry.example/", + "2099-01-01T00:00:00Z", + ); + }); + + assert_eq!( + get_refresh_token("https://registry.example").as_deref(), + Some("refresh") + ); + + assert_eq!( + with_slashed_registry_keys(|| ( + get_stored_access_token("https://registry.example/"), + get_refresh_token("https://registry.example/"), + )), + (None, None), + "both slashed tokens move with the first read" + ); + assert_eq!( + get_token("https://registry.example").as_deref(), + Some("access") + ); + assert!(!should_refresh_session_access_token( + "https://registry.example" + )); + }); + } + + #[test] + fn a_trailing_slash_login_does_not_return_once_the_newer_login_is_rejected() { + with_temp_home(|_| { + let _env = LocalEnvGuard::update([("LPM_FORCE_FILE_AUTH", Some("1".into()))]); + with_slashed_registry_keys(|| { + set_token("https://registry.example/", "account-a-access").unwrap(); + set_refresh_token("https://registry.example/", "account-a-refresh").unwrap(); + }); + set_token("https://registry.example", "account-b-access").unwrap(); + set_refresh_token("https://registry.example", "account-b-refresh").unwrap(); + + clear_rejected_refresh_session_if_current( + "https://registry.example", + Some("account-b-access"), + "account-b-refresh", + || {}, + || {}, + ) + .unwrap(); + + assert_eq!(get_token("https://registry.example"), None); + assert_eq!(get_refresh_token("https://registry.example"), None); + }); + } + + #[test] + fn a_trailing_slash_login_does_not_replace_a_revoked_credential() { + with_temp_home(|_| { + let _env = LocalEnvGuard::update([("LPM_FORCE_FILE_AUTH", Some("1".into()))]); + with_slashed_registry_keys(|| { + set_token("https://registry.example/", "account-a-access").unwrap(); + set_refresh_token("https://registry.example/", "account-a-refresh").unwrap(); + }); + // As a clear that failed after recording the revocation leaves it. + credential_authority::set( + "https://registry.example", + CredentialKind::Access, + credential_authority::CredentialAuthority::Revoked, + ) + .unwrap(); + + assert_eq!(get_token("https://registry.example"), None); + assert_eq!(get_refresh_token("https://registry.example"), None); + }); + } + #[test] fn logging_out_also_clears_a_login_stored_under_a_trailing_slash() { with_temp_home(|_| {