Skip to main content

uv_auth/
cache.rs

1use std::fmt::{self, Display, Formatter};
2use std::hash::BuildHasherDefault;
3use std::sync::Arc;
4use std::sync::RwLock;
5
6use rustc_hash::{FxHashMap, FxHasher};
7use tracing::trace;
8
9use uv_once_map::OnceMap;
10use uv_redacted::SafeUrl;
11
12use crate::credentials::{Authentication, CredentialsFromUrlError, Username};
13use crate::{Credentials, Realm};
14
15type FxOnceMap<K, V> = OnceMap<K, V, BuildHasherDefault<FxHasher>>;
16
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18pub(crate) enum FetchUrl {
19    /// A full index URL
20    Index(SafeUrl),
21    /// A realm URL
22    Realm(Realm),
23}
24
25impl Display for FetchUrl {
26    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
27        match self {
28            Self::Index(index) => Display::fmt(index, f),
29            Self::Realm(realm) => Display::fmt(realm, f),
30        }
31    }
32}
33
34#[derive(Debug)] // All internal types are redacted.
35pub struct CredentialsCache {
36    /// A cache per realm and username
37    realms: RwLock<FxHashMap<(Realm, Username), Arc<Authentication>>>,
38    /// A cache tracking the result of realm or index URL fetches from external services
39    pub(crate) fetches: FxOnceMap<(FetchUrl, Username), Option<Arc<Authentication>>>,
40    /// A cache per URL, uses a trie for efficient prefix queries.
41    urls: RwLock<UrlTrie<Arc<Authentication>>>,
42}
43
44impl Default for CredentialsCache {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl CredentialsCache {
51    /// Create a new cache.
52    pub fn new() -> Self {
53        Self {
54            fetches: FxOnceMap::default(),
55            realms: RwLock::new(FxHashMap::default()),
56            urls: RwLock::new(UrlTrie::new()),
57        }
58    }
59
60    /// Populate the global authentication store with credentials on a URL, if there are any.
61    ///
62    /// Returns `true` if the store was updated.
63    pub fn store_credentials_from_url(
64        &self,
65        url: &SafeUrl,
66    ) -> Result<bool, CredentialsFromUrlError> {
67        if let Some(credentials) = Credentials::from_url(url)? {
68            trace!("Caching credentials for `{url}`");
69            self.insert(url, Arc::new(Authentication::from(credentials)));
70            Ok(true)
71        } else {
72            Ok(false)
73        }
74    }
75
76    /// Populate the global authentication store with credentials on a URL, if there are any.
77    ///
78    /// Returns `true` if the store was updated.
79    pub fn store_credentials(&self, url: &SafeUrl, credentials: Credentials) {
80        trace!("Caching credentials for `{url}`");
81        self.insert(url, Arc::new(Authentication::from(credentials)));
82    }
83
84    /// Return the credentials that should be used for a realm and username, if any.
85    pub(crate) fn get_realm(
86        &self,
87        realm: Realm,
88        username: Username,
89    ) -> Option<Arc<Authentication>> {
90        let realms = self.realms.read().unwrap();
91        let given_username = username.is_some();
92        let key = (realm, username);
93        let realm_username = fmt::from_fn(|f| {
94            let (realm, username) = &key;
95            if let Some(username) = username.as_deref() {
96                write!(f, "{username}@{realm}")
97            } else {
98                write!(f, "{realm}")
99            }
100        });
101
102        let Some(credentials) = realms.get(&key).cloned() else {
103            trace!("No credentials in cache for realm {realm_username}");
104            return None;
105        };
106
107        if given_username && credentials.password().is_none() {
108            // If given a username, don't return password-less credentials
109            trace!("No password in cache for realm {realm_username}");
110            return None;
111        }
112
113        trace!("Found cached credentials for realm {realm_username}");
114        Some(credentials)
115    }
116
117    /// Return the cached credentials for a URL and username, if any.
118    ///
119    /// Note we do not cache per username, but if a username is passed we will confirm that the
120    /// cached credentials have a username equal to the provided one — otherwise `None` is returned.
121    /// If multiple usernames are used per URL, the realm cache should be queried instead.
122    pub(crate) fn get_url(
123        &self,
124        url: &SafeUrl,
125        username: &Username,
126    ) -> Option<Arc<Authentication>> {
127        let urls = self.urls.read().unwrap();
128        let credentials = urls.get(url);
129        if let Some(credentials) = credentials {
130            if username.is_none() || username.as_deref() == credentials.username() {
131                if username.is_some() && credentials.password().is_none() {
132                    // If given a username, don't return password-less credentials
133                    trace!("No password in cache for URL `{url}`");
134                    return None;
135                }
136                trace!("Found cached credentials for URL `{url}`");
137                return Some(credentials.clone());
138            }
139        }
140        trace!("No credentials in cache for URL `{url}`");
141        None
142    }
143
144    /// Update the cache with the given credentials.
145    pub(crate) fn insert(&self, url: &SafeUrl, credentials: Arc<Authentication>) {
146        // Do not cache empty credentials
147        if credentials.is_empty() {
148            return;
149        }
150
151        // Insert an entry for requests including the username
152        let username = credentials.to_username();
153        if username.is_some() {
154            let realm = (Realm::from(url), username);
155            self.insert_realm(realm, &credentials);
156        }
157
158        // Insert an entry for requests with no username
159        self.insert_realm((Realm::from(url), Username::none()), &credentials);
160
161        // Insert an entry for the URL
162        let mut urls = self.urls.write().unwrap();
163        urls.insert(url, credentials);
164    }
165
166    /// Private interface to update a realm cache entry.
167    ///
168    /// Returns replaced credentials, if any.
169    fn insert_realm(
170        &self,
171        key: (Realm, Username),
172        credentials: &Arc<Authentication>,
173    ) -> Option<Arc<Authentication>> {
174        // Do not cache empty credentials
175        if credentials.is_empty() {
176            return None;
177        }
178
179        let mut realms = self.realms.write().unwrap();
180
181        // Always replace existing entries if we have a password or token
182        if credentials.is_authenticated() {
183            return realms.insert(key, credentials.clone());
184        }
185
186        // If we only have a username, add a new entry or replace an existing entry if it doesn't have a password
187        let existing = realms.get(&key);
188        if existing.is_none_or(|credentials| credentials.password().is_none()) {
189            return realms.insert(key, credentials.clone());
190        }
191
192        None
193    }
194}
195
196#[derive(Debug)]
197struct UrlTrie<T> {
198    states: Vec<TrieState<T>>,
199}
200
201#[derive(Debug)]
202struct TrieState<T> {
203    children: Vec<(String, usize)>,
204    value: Option<T>,
205}
206
207impl<T> Default for TrieState<T> {
208    fn default() -> Self {
209        Self {
210            children: vec![],
211            value: None,
212        }
213    }
214}
215
216impl<T> UrlTrie<T> {
217    fn new() -> Self {
218        let mut trie = Self { states: vec![] };
219        trie.alloc();
220        trie
221    }
222
223    /// Return the value for the longest matching path prefix in the same realm.
224    fn get(&self, url: &SafeUrl) -> Option<&T> {
225        let segments = url.path_segments()?;
226        let mut state = 0;
227        let mut longest_match = None;
228        let realm = Realm::from(url).to_string();
229        for component in [realm.as_str()]
230            .into_iter()
231            .chain(segments.filter(|item| !item.is_empty()))
232        {
233            let Some(next) = self.states[state].get(component) else {
234                break;
235            };
236            state = next;
237            if let Some(value) = &self.states[state].value {
238                longest_match = Some(value);
239            }
240        }
241        longest_match
242    }
243
244    fn insert(&mut self, url: &SafeUrl, value: T) {
245        // Opaque URLs have no path hierarchy for prefix matching.
246        let Some(segments) = url.path_segments() else {
247            return;
248        };
249        let mut state = 0;
250        let realm = Realm::from(url).to_string();
251        for component in [realm.as_str()]
252            .into_iter()
253            .chain(segments.filter(|item| !item.is_empty()))
254        {
255            match self.states[state].index(component) {
256                Ok(i) => state = self.states[state].children[i].1,
257                Err(i) => {
258                    let new_state = self.alloc();
259                    self.states[state]
260                        .children
261                        .insert(i, (component.to_string(), new_state));
262                    state = new_state;
263                }
264            }
265        }
266        self.states[state].value = Some(value);
267    }
268
269    fn alloc(&mut self) -> usize {
270        let id = self.states.len();
271        self.states.push(TrieState::default());
272        id
273    }
274}
275
276impl<T> TrieState<T> {
277    fn get(&self, component: &str) -> Option<usize> {
278        let i = self.index(component).ok()?;
279        Some(self.children[i].1)
280    }
281
282    fn index(&self, component: &str) -> Result<usize, usize> {
283        self.children
284            .binary_search_by(|(label, _)| label.as_str().cmp(component))
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use uv_redacted::SafeUrlError;
291
292    use crate::Credentials;
293    use crate::credentials::Password;
294
295    use super::*;
296
297    #[test]
298    fn test_trie() {
299        let credentials1 =
300            Credentials::basic(Some("username1".to_string()), Some("password1".to_string()));
301        let credentials2 =
302            Credentials::basic(Some("username2".to_string()), Some("password2".to_string()));
303        let credentials3 =
304            Credentials::basic(Some("username3".to_string()), Some("password3".to_string()));
305        let credentials4 =
306            Credentials::basic(Some("username4".to_string()), Some("password4".to_string()));
307
308        let mut trie = UrlTrie::new();
309        trie.insert(
310            &SafeUrl::parse("https://burntsushi.net").unwrap(),
311            credentials1.clone(),
312        );
313        trie.insert(
314            &SafeUrl::parse("https://astral.sh").unwrap(),
315            credentials2.clone(),
316        );
317        trie.insert(
318            &SafeUrl::parse("https://example.com/foo").unwrap(),
319            credentials3.clone(),
320        );
321        trie.insert(
322            &SafeUrl::parse("https://example.com/bar").unwrap(),
323            credentials4.clone(),
324        );
325
326        let url = SafeUrl::parse("https://burntsushi.net/regex-internals").unwrap();
327        assert_eq!(trie.get(&url), Some(&credentials1));
328
329        let url = SafeUrl::parse("https://burntsushi.net/").unwrap();
330        assert_eq!(trie.get(&url), Some(&credentials1));
331
332        let url = SafeUrl::parse("https://astral.sh/about").unwrap();
333        assert_eq!(trie.get(&url), Some(&credentials2));
334
335        let url = SafeUrl::parse("https://example.com/foo").unwrap();
336        assert_eq!(trie.get(&url), Some(&credentials3));
337
338        let url = SafeUrl::parse("https://example.com/foo/").unwrap();
339        assert_eq!(trie.get(&url), Some(&credentials3));
340
341        let url = SafeUrl::parse("https://example.com/foo/bar").unwrap();
342        assert_eq!(trie.get(&url), Some(&credentials3));
343
344        let url = SafeUrl::parse("https://example.com/bar").unwrap();
345        assert_eq!(trie.get(&url), Some(&credentials4));
346
347        let url = SafeUrl::parse("https://example.com/bar/").unwrap();
348        assert_eq!(trie.get(&url), Some(&credentials4));
349
350        let url = SafeUrl::parse("https://example.com/bar/foo").unwrap();
351        assert_eq!(trie.get(&url), Some(&credentials4));
352
353        let url = SafeUrl::parse("https://example.com/about").unwrap();
354        assert_eq!(trie.get(&url), None);
355
356        let url = SafeUrl::parse("https://example.com/foobar").unwrap();
357        assert_eq!(trie.get(&url), None);
358    }
359
360    #[test]
361    fn test_trie_longest_prefix() -> Result<(), SafeUrlError> {
362        let parent = SafeUrl::parse("https://example.com/team")?;
363        let child = SafeUrl::parse("https://example.com/team/private/simple")?;
364        let parent_credentials =
365            Credentials::basic(Some("team".to_string()), Some("password1".to_string()));
366        let child_credentials =
367            Credentials::basic(Some("private".to_string()), Some("password2".to_string()));
368
369        let mut trie = UrlTrie::new();
370        trie.insert(&parent, parent_credentials.clone());
371        trie.insert(&child, child_credentials.clone());
372
373        assert_eq!(trie.get(&child), Some(&child_credentials));
374
375        let url = SafeUrl::parse("https://example.com/team/private/simple/anyio")?;
376        assert_eq!(trie.get(&url), Some(&child_credentials));
377
378        let url = SafeUrl::parse("https://example.com/team/private/files")?;
379        assert_eq!(trie.get(&url), Some(&parent_credentials));
380
381        Ok(())
382    }
383
384    #[test]
385    fn test_trie_opaque_url() -> Result<(), SafeUrlError> {
386        let mut trie = UrlTrie::new();
387        let url = SafeUrl::parse("git+https:foo")?;
388        let credentials =
389            Credentials::basic(Some("username".to_string()), Some("password".to_string()));
390
391        assert_eq!(trie.get(&url), None);
392        trie.insert(&url, credentials.clone());
393        assert_eq!(trie.get(&url), None);
394
395        // Opaque URLs must not share credentials with hierarchical URLs in the same realm.
396        let base_url = SafeUrl::parse("git+https:/")?;
397        assert_eq!(trie.get(&base_url), None);
398        trie.insert(&base_url, credentials.clone());
399        assert_eq!(trie.get(&url), None);
400        assert_eq!(trie.get(&base_url), Some(&credentials));
401
402        Ok(())
403    }
404
405    #[test]
406    fn test_url_with_credentials() {
407        let username = Username::new(Some(String::from("username")));
408        let password = Password::new(String::from("password"));
409        let credentials = Arc::new(Authentication::from(Credentials::Basic {
410            username: username.clone(),
411            password: Some(password),
412        }));
413        let cache = CredentialsCache::default();
414        // Insert with URL with credentials and get with redacted URL.
415        let url = SafeUrl::parse("https://username:password@example.com/foobar").unwrap();
416        cache.insert(&url, credentials.clone());
417        assert_eq!(cache.get_url(&url, &username), Some(credentials.clone()));
418        // Insert with redacted URL and get with URL with credentials.
419        let url = SafeUrl::parse("https://username:password@second-example.com/foobar").unwrap();
420        cache.insert(&url, credentials.clone());
421        assert_eq!(cache.get_url(&url, &username), Some(credentials.clone()));
422    }
423}