uv-auth 0.0.103

This is an internal component crate of uv
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use std::fmt::{self, Display, Formatter};
use std::hash::BuildHasherDefault;
use std::sync::Arc;
use std::sync::RwLock;

use rustc_hash::{FxHashMap, FxHasher};
use tracing::trace;

use uv_once_map::OnceMap;
use uv_redacted::SafeUrl;

use crate::credentials::{Authentication, CredentialsFromUrlError, Username};
use crate::{Credentials, Realm};

type FxOnceMap<K, V> = OnceMap<K, V, BuildHasherDefault<FxHasher>>;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum FetchUrl {
    /// A full index URL
    Index(SafeUrl),
    /// A realm URL
    Realm(Realm),
}

impl Display for FetchUrl {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            Self::Index(index) => Display::fmt(index, f),
            Self::Realm(realm) => Display::fmt(realm, f),
        }
    }
}

#[derive(Debug)] // All internal types are redacted.
pub struct CredentialsCache {
    /// A cache per realm and username
    realms: RwLock<FxHashMap<(Realm, Username), Arc<Authentication>>>,
    /// A cache tracking the result of realm or index URL fetches from external services
    pub(crate) fetches: FxOnceMap<(FetchUrl, Username), Option<Arc<Authentication>>>,
    /// A cache per URL, uses a trie for efficient prefix queries.
    urls: RwLock<UrlTrie<Arc<Authentication>>>,
}

impl Default for CredentialsCache {
    fn default() -> Self {
        Self::new()
    }
}

impl CredentialsCache {
    /// Create a new cache.
    pub fn new() -> Self {
        Self {
            fetches: FxOnceMap::default(),
            realms: RwLock::new(FxHashMap::default()),
            urls: RwLock::new(UrlTrie::new()),
        }
    }

    /// Populate the global authentication store with credentials on a URL, if there are any.
    ///
    /// Returns `true` if the store was updated.
    pub fn store_credentials_from_url(
        &self,
        url: &SafeUrl,
    ) -> Result<bool, CredentialsFromUrlError> {
        if let Some(credentials) = Credentials::from_url(url)? {
            trace!("Caching credentials for `{url}`");
            self.insert(url, Arc::new(Authentication::from(credentials)));
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Populate the global authentication store with credentials on a URL, if there are any.
    ///
    /// Returns `true` if the store was updated.
    pub fn store_credentials(&self, url: &SafeUrl, credentials: Credentials) {
        trace!("Caching credentials for `{url}`");
        self.insert(url, Arc::new(Authentication::from(credentials)));
    }

    /// Return the credentials that should be used for a realm and username, if any.
    pub(crate) fn get_realm(
        &self,
        realm: Realm,
        username: Username,
    ) -> Option<Arc<Authentication>> {
        let realms = self.realms.read().unwrap();
        let given_username = username.is_some();
        let key = (realm, username);
        let realm_username = fmt::from_fn(|f| {
            let (realm, username) = &key;
            if let Some(username) = username.as_deref() {
                write!(f, "{username}@{realm}")
            } else {
                write!(f, "{realm}")
            }
        });

        let Some(credentials) = realms.get(&key).cloned() else {
            trace!("No credentials in cache for realm {realm_username}");
            return None;
        };

        if given_username && credentials.password().is_none() {
            // If given a username, don't return password-less credentials
            trace!("No password in cache for realm {realm_username}");
            return None;
        }

        trace!("Found cached credentials for realm {realm_username}");
        Some(credentials)
    }

    /// Return the cached credentials for a URL and username, if any.
    ///
    /// Note we do not cache per username, but if a username is passed we will confirm that the
    /// cached credentials have a username equal to the provided one — otherwise `None` is returned.
    /// If multiple usernames are used per URL, the realm cache should be queried instead.
    pub(crate) fn get_url(
        &self,
        url: &SafeUrl,
        username: &Username,
    ) -> Option<Arc<Authentication>> {
        let urls = self.urls.read().unwrap();
        let credentials = urls.get(url);
        if let Some(credentials) = credentials {
            if username.is_none() || username.as_deref() == credentials.username() {
                if username.is_some() && credentials.password().is_none() {
                    // If given a username, don't return password-less credentials
                    trace!("No password in cache for URL `{url}`");
                    return None;
                }
                trace!("Found cached credentials for URL `{url}`");
                return Some(credentials.clone());
            }
        }
        trace!("No credentials in cache for URL `{url}`");
        None
    }

    /// Update the cache with the given credentials.
    pub(crate) fn insert(&self, url: &SafeUrl, credentials: Arc<Authentication>) {
        // Do not cache empty credentials
        if credentials.is_empty() {
            return;
        }

        // Insert an entry for requests including the username
        let username = credentials.to_username();
        if username.is_some() {
            let realm = (Realm::from(url), username);
            self.insert_realm(realm, &credentials);
        }

        // Insert an entry for requests with no username
        self.insert_realm((Realm::from(url), Username::none()), &credentials);

        // Insert an entry for the URL
        let mut urls = self.urls.write().unwrap();
        urls.insert(url, credentials);
    }

    /// Private interface to update a realm cache entry.
    ///
    /// Returns replaced credentials, if any.
    fn insert_realm(
        &self,
        key: (Realm, Username),
        credentials: &Arc<Authentication>,
    ) -> Option<Arc<Authentication>> {
        // Do not cache empty credentials
        if credentials.is_empty() {
            return None;
        }

        let mut realms = self.realms.write().unwrap();

        // Always replace existing entries if we have a password or token
        if credentials.is_authenticated() {
            return realms.insert(key, credentials.clone());
        }

        // If we only have a username, add a new entry or replace an existing entry if it doesn't have a password
        let existing = realms.get(&key);
        if existing.is_none_or(|credentials| credentials.password().is_none()) {
            return realms.insert(key, credentials.clone());
        }

        None
    }
}

#[derive(Debug)]
struct UrlTrie<T> {
    states: Vec<TrieState<T>>,
}

#[derive(Debug)]
struct TrieState<T> {
    children: Vec<(String, usize)>,
    value: Option<T>,
}

impl<T> Default for TrieState<T> {
    fn default() -> Self {
        Self {
            children: vec![],
            value: None,
        }
    }
}

impl<T> UrlTrie<T> {
    fn new() -> Self {
        let mut trie = Self { states: vec![] };
        trie.alloc();
        trie
    }

    /// Return the value for the longest matching path prefix in the same realm.
    fn get(&self, url: &SafeUrl) -> Option<&T> {
        let segments = url.path_segments()?;
        let mut state = 0;
        let mut longest_match = None;
        let realm = Realm::from(url).to_string();
        for component in [realm.as_str()]
            .into_iter()
            .chain(segments.filter(|item| !item.is_empty()))
        {
            let Some(next) = self.states[state].get(component) else {
                break;
            };
            state = next;
            if let Some(value) = &self.states[state].value {
                longest_match = Some(value);
            }
        }
        longest_match
    }

    fn insert(&mut self, url: &SafeUrl, value: T) {
        // Opaque URLs have no path hierarchy for prefix matching.
        let Some(segments) = url.path_segments() else {
            return;
        };
        let mut state = 0;
        let realm = Realm::from(url).to_string();
        for component in [realm.as_str()]
            .into_iter()
            .chain(segments.filter(|item| !item.is_empty()))
        {
            match self.states[state].index(component) {
                Ok(i) => state = self.states[state].children[i].1,
                Err(i) => {
                    let new_state = self.alloc();
                    self.states[state]
                        .children
                        .insert(i, (component.to_string(), new_state));
                    state = new_state;
                }
            }
        }
        self.states[state].value = Some(value);
    }

    fn alloc(&mut self) -> usize {
        let id = self.states.len();
        self.states.push(TrieState::default());
        id
    }
}

impl<T> TrieState<T> {
    fn get(&self, component: &str) -> Option<usize> {
        let i = self.index(component).ok()?;
        Some(self.children[i].1)
    }

    fn index(&self, component: &str) -> Result<usize, usize> {
        self.children
            .binary_search_by(|(label, _)| label.as_str().cmp(component))
    }
}

#[cfg(test)]
mod tests {
    use uv_redacted::SafeUrlError;

    use crate::Credentials;
    use crate::credentials::Password;

    use super::*;

    #[test]
    fn test_trie() {
        let credentials1 =
            Credentials::basic(Some("username1".to_string()), Some("password1".to_string()));
        let credentials2 =
            Credentials::basic(Some("username2".to_string()), Some("password2".to_string()));
        let credentials3 =
            Credentials::basic(Some("username3".to_string()), Some("password3".to_string()));
        let credentials4 =
            Credentials::basic(Some("username4".to_string()), Some("password4".to_string()));

        let mut trie = UrlTrie::new();
        trie.insert(
            &SafeUrl::parse("https://burntsushi.net").unwrap(),
            credentials1.clone(),
        );
        trie.insert(
            &SafeUrl::parse("https://astral.sh").unwrap(),
            credentials2.clone(),
        );
        trie.insert(
            &SafeUrl::parse("https://example.com/foo").unwrap(),
            credentials3.clone(),
        );
        trie.insert(
            &SafeUrl::parse("https://example.com/bar").unwrap(),
            credentials4.clone(),
        );

        let url = SafeUrl::parse("https://burntsushi.net/regex-internals").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials1));

        let url = SafeUrl::parse("https://burntsushi.net/").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials1));

        let url = SafeUrl::parse("https://astral.sh/about").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials2));

        let url = SafeUrl::parse("https://example.com/foo").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials3));

        let url = SafeUrl::parse("https://example.com/foo/").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials3));

        let url = SafeUrl::parse("https://example.com/foo/bar").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials3));

        let url = SafeUrl::parse("https://example.com/bar").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials4));

        let url = SafeUrl::parse("https://example.com/bar/").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials4));

        let url = SafeUrl::parse("https://example.com/bar/foo").unwrap();
        assert_eq!(trie.get(&url), Some(&credentials4));

        let url = SafeUrl::parse("https://example.com/about").unwrap();
        assert_eq!(trie.get(&url), None);

        let url = SafeUrl::parse("https://example.com/foobar").unwrap();
        assert_eq!(trie.get(&url), None);
    }

    #[test]
    fn test_trie_longest_prefix() -> Result<(), SafeUrlError> {
        let parent = SafeUrl::parse("https://example.com/team")?;
        let child = SafeUrl::parse("https://example.com/team/private/simple")?;
        let parent_credentials =
            Credentials::basic(Some("team".to_string()), Some("password1".to_string()));
        let child_credentials =
            Credentials::basic(Some("private".to_string()), Some("password2".to_string()));

        let mut trie = UrlTrie::new();
        trie.insert(&parent, parent_credentials.clone());
        trie.insert(&child, child_credentials.clone());

        assert_eq!(trie.get(&child), Some(&child_credentials));

        let url = SafeUrl::parse("https://example.com/team/private/simple/anyio")?;
        assert_eq!(trie.get(&url), Some(&child_credentials));

        let url = SafeUrl::parse("https://example.com/team/private/files")?;
        assert_eq!(trie.get(&url), Some(&parent_credentials));

        Ok(())
    }

    #[test]
    fn test_trie_opaque_url() -> Result<(), SafeUrlError> {
        let mut trie = UrlTrie::new();
        let url = SafeUrl::parse("git+https:foo")?;
        let credentials =
            Credentials::basic(Some("username".to_string()), Some("password".to_string()));

        assert_eq!(trie.get(&url), None);
        trie.insert(&url, credentials.clone());
        assert_eq!(trie.get(&url), None);

        // Opaque URLs must not share credentials with hierarchical URLs in the same realm.
        let base_url = SafeUrl::parse("git+https:/")?;
        assert_eq!(trie.get(&base_url), None);
        trie.insert(&base_url, credentials.clone());
        assert_eq!(trie.get(&url), None);
        assert_eq!(trie.get(&base_url), Some(&credentials));

        Ok(())
    }

    #[test]
    fn test_url_with_credentials() {
        let username = Username::new(Some(String::from("username")));
        let password = Password::new(String::from("password"));
        let credentials = Arc::new(Authentication::from(Credentials::Basic {
            username: username.clone(),
            password: Some(password),
        }));
        let cache = CredentialsCache::default();
        // Insert with URL with credentials and get with redacted URL.
        let url = SafeUrl::parse("https://username:password@example.com/foobar").unwrap();
        cache.insert(&url, credentials.clone());
        assert_eq!(cache.get_url(&url, &username), Some(credentials.clone()));
        // Insert with redacted URL and get with URL with credentials.
        let url = SafeUrl::parse("https://username:password@second-example.com/foobar").unwrap();
        cache.insert(&url, credentials.clone());
        assert_eq!(cache.get_url(&url, &username), Some(credentials.clone()));
    }
}