uv_auth/
cache.rs

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