Skip to main content

uv_auth/
store.rs

1#[cfg(unix)]
2use std::fs::Permissions;
3#[cfg(unix)]
4use std::os::unix::fs::PermissionsExt;
5use std::path::{Path, PathBuf};
6
7use fs_err as fs;
8#[cfg(unix)]
9use fs_err::os::unix::fs::OpenOptionsExt;
10use rustc_hash::FxHashMap;
11use serde::{Deserialize, Serialize};
12use thiserror::Error;
13use uv_fs::{LockedFile, LockedFileError, LockedFileMode};
14use uv_preview::{Preview, PreviewFeature};
15use uv_redacted::SafeUrl;
16
17use uv_state::{StateBucket, StateStore};
18use uv_static::EnvVars;
19
20use crate::credentials::{Password, Token, Username};
21use crate::index::is_path_prefix;
22use crate::realm::Realm;
23use crate::service::Service;
24use crate::{Credentials, KeyringProvider};
25
26/// The storage backend to use in `uv auth` commands.
27#[derive(Debug)]
28pub enum AuthBackend {
29    // TODO(zanieb): Right now, we're using a keyring provider for the system store but that's just
30    // where the native implementation is living at the moment. We should consider refactoring these
31    // into a shared API in the future.
32    System(KeyringProvider),
33    TextStore(TextCredentialStore, LockedFile),
34}
35
36impl AuthBackend {
37    pub async fn from_settings(preview: Preview) -> Result<Self, TomlCredentialError> {
38        // If preview is enabled, we'll use the system-native store
39        if preview.is_enabled(PreviewFeature::NativeAuth) {
40            return Ok(Self::System(KeyringProvider::native()));
41        }
42
43        // Otherwise, we'll use the plaintext credential store
44        let path = TextCredentialStore::default_file()?;
45        match TextCredentialStore::read(&path).await {
46            Ok((store, lock)) => Ok(Self::TextStore(store, lock)),
47            Err(err)
48                if err
49                    .as_io_error()
50                    .is_some_and(|err| err.kind() == std::io::ErrorKind::NotFound) =>
51            {
52                Ok(Self::TextStore(
53                    TextCredentialStore::default(),
54                    TextCredentialStore::lock(&path).await?,
55                ))
56            }
57            Err(err) => Err(err),
58        }
59    }
60}
61
62/// Authentication scheme to use.
63#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(rename_all = "lowercase")]
65enum AuthScheme {
66    /// HTTP Basic Authentication
67    ///
68    /// Uses a username and password.
69    #[default]
70    Basic,
71    /// Bearer token authentication.
72    ///
73    /// Uses a token provided as `Bearer <token>` in the `Authorization` header.
74    Bearer,
75}
76
77/// Errors that can occur when working with TOML credential storage.
78#[derive(Debug, Error)]
79pub enum TomlCredentialError {
80    #[error(transparent)]
81    Io(#[from] std::io::Error),
82    #[error(transparent)]
83    LockedFile(#[from] LockedFileError),
84    #[error("Failed to parse TOML credential file: {0}")]
85    ParseError(#[from] toml::de::Error),
86    #[error("Failed to serialize credentials to TOML")]
87    SerializeError(#[from] toml::ser::Error),
88    #[error(transparent)]
89    BasicAuthError(#[from] BasicAuthError),
90    #[error(transparent)]
91    BearerAuthError(#[from] BearerAuthError),
92    #[error("Failed to determine credentials directory")]
93    CredentialsDirError,
94    #[error("Token is not valid unicode")]
95    TokenNotUnicode(#[from] std::string::FromUtf8Error),
96}
97
98impl TomlCredentialError {
99    pub(crate) fn as_io_error(&self) -> Option<&std::io::Error> {
100        match self {
101            Self::Io(err) => Some(err),
102            Self::LockedFile(err) => err.as_io_error(),
103            Self::ParseError(_)
104            | Self::SerializeError(_)
105            | Self::BasicAuthError(_)
106            | Self::BearerAuthError(_)
107            | Self::CredentialsDirError
108            | Self::TokenNotUnicode(_) => None,
109        }
110    }
111}
112
113#[derive(Debug, Error)]
114pub enum BasicAuthError {
115    #[error("`username` is required with `scheme = basic`")]
116    MissingUsername,
117    #[error("`token` cannot be provided with `scheme = basic`")]
118    UnexpectedToken,
119}
120
121#[derive(Debug, Error)]
122pub enum BearerAuthError {
123    #[error("`token` is required with `scheme = bearer`")]
124    MissingToken,
125    #[error("`username` cannot be provided with `scheme = bearer`")]
126    UnexpectedUsername,
127    #[error("`password` cannot be provided with `scheme = bearer`")]
128    UnexpectedPassword,
129}
130
131#[derive(Debug, Error, PartialEq)]
132pub enum LookupError {
133    #[error("Multiple credentials found for URL `{0}`, specify which username to use")]
134    AmbiguousUsername(SafeUrl),
135}
136
137/// A single credential entry in a TOML credentials file.
138#[derive(Debug, Clone, Serialize, Deserialize)]
139#[serde(try_from = "TomlCredentialWire", into = "TomlCredentialWire")]
140struct TomlCredential {
141    /// The service URL for this credential.
142    service: Service,
143    /// The credentials for this entry.
144    credentials: Credentials,
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize)]
148struct TomlCredentialWire {
149    /// The service URL for this credential.
150    service: Service,
151    /// The username to use. Only allowed with [`AuthScheme::Basic`].
152    username: Username,
153    /// The authentication scheme.
154    #[serde(default)]
155    scheme: AuthScheme,
156    /// The password to use. Only allowed with [`AuthScheme::Basic`].
157    password: Option<Password>,
158    /// The token to use. Only allowed with [`AuthScheme::Bearer`].
159    token: Option<String>,
160}
161
162impl From<TomlCredential> for TomlCredentialWire {
163    fn from(value: TomlCredential) -> Self {
164        match value.credentials {
165            Credentials::Basic { username, password } => Self {
166                service: value.service,
167                username,
168                scheme: AuthScheme::Basic,
169                password,
170                token: None,
171            },
172            Credentials::Bearer { token } => Self {
173                service: value.service,
174                username: Username::new(None),
175                scheme: AuthScheme::Bearer,
176                password: None,
177                token: Some(String::from_utf8(token.into_bytes()).expect("Token is valid UTF-8")),
178            },
179        }
180    }
181}
182
183impl TryFrom<TomlCredentialWire> for TomlCredential {
184    type Error = TomlCredentialError;
185
186    fn try_from(value: TomlCredentialWire) -> Result<Self, Self::Error> {
187        match value.scheme {
188            AuthScheme::Basic => {
189                if value.username.as_deref().is_none() {
190                    return Err(TomlCredentialError::BasicAuthError(
191                        BasicAuthError::MissingUsername,
192                    ));
193                }
194                if value.token.is_some() {
195                    return Err(TomlCredentialError::BasicAuthError(
196                        BasicAuthError::UnexpectedToken,
197                    ));
198                }
199                let credentials = Credentials::Basic {
200                    username: value.username,
201                    password: value.password,
202                };
203                Ok(Self {
204                    service: value.service,
205                    credentials,
206                })
207            }
208            AuthScheme::Bearer => {
209                if value.username.is_some() {
210                    return Err(TomlCredentialError::BearerAuthError(
211                        BearerAuthError::UnexpectedUsername,
212                    ));
213                }
214                if value.password.is_some() {
215                    return Err(TomlCredentialError::BearerAuthError(
216                        BearerAuthError::UnexpectedPassword,
217                    ));
218                }
219                if value.token.is_none() {
220                    return Err(TomlCredentialError::BearerAuthError(
221                        BearerAuthError::MissingToken,
222                    ));
223                }
224                let credentials = Credentials::Bearer {
225                    token: Token::new(value.token.unwrap().into_bytes()),
226                };
227                Ok(Self {
228                    service: value.service,
229                    credentials,
230                })
231            }
232        }
233    }
234}
235
236#[derive(Debug, Clone, Serialize, Deserialize, Default)]
237struct TomlCredentials {
238    /// Array of credential entries.
239    #[serde(default, rename = "credential")]
240    credentials: Vec<TomlCredential>,
241}
242
243/// A credential store with a plain text storage backend.
244#[derive(Debug, Default)]
245pub struct TextCredentialStore {
246    credentials: FxHashMap<(Service, Username), Credentials>,
247}
248
249impl TextCredentialStore {
250    /// Return the directory for storing credentials.
251    pub fn directory_path() -> Result<PathBuf, TomlCredentialError> {
252        if let Some(dir) = std::env::var_os(EnvVars::UV_CREDENTIALS_DIR)
253            .filter(|s| !s.is_empty())
254            .map(PathBuf::from)
255        {
256            return Ok(dir);
257        }
258
259        Ok(StateStore::from_settings(None)?.bucket(StateBucket::Credentials))
260    }
261
262    /// Return the standard file path for storing credentials.
263    pub fn default_file() -> Result<PathBuf, TomlCredentialError> {
264        let dir = Self::directory_path()?;
265        Ok(dir.join("credentials.toml"))
266    }
267
268    /// Acquire a lock on the credentials file at the given path.
269    async fn lock(path: &Path) -> Result<LockedFile, TomlCredentialError> {
270        if let Some(parent) = path.parent() {
271            let mut builder = fs::tokio::DirBuilder::new();
272            #[cfg(unix)]
273            {
274                // Only the credentials directory needs owner-only permissions.
275                if let Some(base) = parent.parent() {
276                    fs::tokio::create_dir_all(base).await?;
277                }
278                builder.mode(0o700);
279            }
280            builder.recursive(true).create(parent).await?;
281        }
282        let mut options = fs::OpenOptions::new();
283        #[cfg(unix)]
284        options.mode(0o600);
285        let file = options
286            .read(true)
287            .write(true)
288            .create(true)
289            .truncate(false)
290            .open(path.with_added_extension("lock"))?;
291        #[cfg(unix)]
292        file.set_permissions(Permissions::from_mode(0o600))?;
293        Ok(LockedFile::lock_file(file, LockedFileMode::Exclusive, "credentials store").await?)
294    }
295
296    /// Read credentials from a file.
297    fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, TomlCredentialError> {
298        let content = fs::read_to_string(path)?;
299        let credentials: TomlCredentials = toml::from_str(&content)?;
300
301        let credentials: FxHashMap<(Service, Username), Credentials> = credentials
302            .credentials
303            .into_iter()
304            .map(|credential| {
305                let username = match &credential.credentials {
306                    Credentials::Basic { username, .. } => username.clone(),
307                    Credentials::Bearer { .. } => Username::none(),
308                };
309                (
310                    (credential.service.clone(), username),
311                    credential.credentials,
312                )
313            })
314            .collect();
315
316        Ok(Self { credentials })
317    }
318
319    /// Read credentials from a file.
320    ///
321    /// Returns [`TextCredentialStore`] and a [`LockedFile`] to hold if mutating the store.
322    ///
323    /// If the store will not be written to following the read, the lock can be dropped.
324    pub(crate) async fn read<P: AsRef<Path>>(
325        path: P,
326    ) -> Result<(Self, LockedFile), TomlCredentialError> {
327        let lock = Self::lock(path.as_ref()).await?;
328        let store = Self::from_file(path)?;
329        Ok((store, lock))
330    }
331
332    /// Persist credentials to a file.
333    ///
334    /// Requires a [`LockedFile`] from [`TextCredentialStore::lock`] or
335    /// [`TextCredentialStore::read`] to ensure exclusive access.
336    pub async fn write<P: AsRef<Path>>(
337        self,
338        path: P,
339        _lock: LockedFile,
340    ) -> Result<(), TomlCredentialError> {
341        let credentials = self
342            .credentials
343            .into_iter()
344            .map(|((service, _username), credentials)| TomlCredential {
345                service,
346                credentials,
347            })
348            .collect::<Vec<_>>();
349
350        let toml_creds = TomlCredentials { credentials };
351        let content = toml::to_string_pretty(&toml_creds)?;
352        let path = path.as_ref();
353        #[cfg(unix)]
354        {
355            let parent = path
356                .parent()
357                .ok_or(TomlCredentialError::CredentialsDirError)?;
358            // Only tighten the directory uv manages. UV_CREDENTIALS_DIR can point anywhere.
359            if parent == StateStore::from_settings(None)?.bucket(StateBucket::Credentials)
360                && fs::symlink_metadata(parent)?.is_dir()
361            {
362                fs::set_permissions(parent, Permissions::from_mode(0o700))?;
363            }
364            let permissions = Some(Permissions::from_mode(0o600));
365            uv_fs::write_atomic_with_permissions(path, content.as_bytes(), permissions).await?;
366        }
367        #[cfg(not(unix))]
368        fs::tokio::write(path, content).await?;
369        Ok(())
370    }
371
372    /// Get credentials for a given URL and username.
373    ///
374    /// The most specific URL prefix match in the same [`Realm`] is returned, if any.
375    pub fn get_credentials(
376        &self,
377        url: &SafeUrl,
378        username: Option<&str>,
379    ) -> Result<Option<&Credentials>, LookupError> {
380        let request_realm = Realm::from(url);
381
382        // Perform an exact lookup first
383        // TODO(zanieb): Consider adding `SafeUrlRef` so we can avoid this clone
384        // TODO(zanieb): We could also return early here if we can't normalize to a `Service`
385        if let Ok(url_service) = Service::try_from(url.clone()) {
386            if let Some(credential) = self
387                .credentials
388                .get(&(url_service, Username::from(username.map(str::to_string))))
389            {
390                return Ok(Some(credential));
391            }
392        }
393
394        // If that fails, iterate through to find a prefix match
395        let mut best: Option<(usize, &Service, &Credentials)> = None;
396
397        for ((service, stored_username), credential) in &self.credentials {
398            let service_realm = Realm::from(service.url());
399
400            // Only consider services in the same realm
401            if service_realm != request_realm {
402                continue;
403            }
404
405            // Service path must be a prefix of the request path.
406            if !is_path_prefix(service.url().path(), url.path()) {
407                continue;
408            }
409
410            // If a username is provided, it must match
411            if let Some(request_username) = username {
412                if Some(request_username) != stored_username.as_deref() {
413                    continue;
414                }
415            }
416
417            // Update our best matching credential based on prefix length
418            let specificity = service.url().path().len();
419            if best.is_none_or(|(best_specificity, _, _)| specificity > best_specificity) {
420                best = Some((specificity, service, credential));
421            } else if best.is_some_and(|(best_specificity, _, _)| specificity == best_specificity) {
422                return Err(LookupError::AmbiguousUsername(url.clone()));
423            }
424        }
425
426        // Return the most specific match
427        if let Some((_, _, credential)) = best {
428            return Ok(Some(credential));
429        }
430
431        Ok(None)
432    }
433
434    /// Store credentials for a given service.
435    pub fn insert(&mut self, service: Service, credentials: Credentials) -> Option<Credentials> {
436        let username = match &credentials {
437            Credentials::Basic { username, .. } => username.clone(),
438            Credentials::Bearer { .. } => Username::none(),
439        };
440        self.credentials.insert((service, username), credentials)
441    }
442
443    /// Remove credentials for a given service.
444    pub fn remove(&mut self, service: Service, username: Username) -> Option<Credentials> {
445        // Remove the specific credential for this service and username
446        self.credentials.remove(&(service, username))
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use std::io::Write;
453    use std::str::FromStr;
454
455    use tempfile::NamedTempFile;
456
457    use super::*;
458
459    #[test]
460    fn test_toml_serialization() {
461        let credentials = TomlCredentials {
462            credentials: vec![
463                TomlCredential {
464                    service: Service::from_str("https://example.com").unwrap(),
465                    credentials: Credentials::Basic {
466                        username: Username::new(Some("user1".to_string())),
467                        password: Some(Password::new("pass1".to_string())),
468                    },
469                },
470                TomlCredential {
471                    service: Service::from_str("https://test.org").unwrap(),
472                    credentials: Credentials::Basic {
473                        username: Username::new(Some("user2".to_string())),
474                        password: Some(Password::new("pass2".to_string())),
475                    },
476                },
477            ],
478        };
479
480        let toml_str = toml::to_string_pretty(&credentials).unwrap();
481        let parsed: TomlCredentials = toml::from_str(&toml_str).unwrap();
482
483        assert_eq!(parsed.credentials.len(), 2);
484        assert_eq!(
485            parsed.credentials[0].service.to_string(),
486            "https://example.com/"
487        );
488        assert_eq!(
489            parsed.credentials[1].service.to_string(),
490            "https://test.org/"
491        );
492    }
493
494    #[test]
495    fn test_credential_store_operations() {
496        let mut store = TextCredentialStore::default();
497        let credentials = Credentials::basic(Some("user".to_string()), Some("pass".to_string()));
498
499        let service = Service::from_str("https://example.com").unwrap();
500        store.insert(service.clone(), credentials.clone());
501        let url = SafeUrl::parse("https://example.com/").unwrap();
502        assert!(store.get_credentials(&url, None).unwrap().is_some());
503
504        let url = SafeUrl::parse("https://example.com/path").unwrap();
505        let retrieved = store.get_credentials(&url, None).unwrap().unwrap();
506        assert_eq!(retrieved.username(), Some("user"));
507        assert_eq!(retrieved.password(), Some("pass"));
508
509        assert!(
510            store
511                .remove(service, Username::from(Some("user".to_string())))
512                .is_some()
513        );
514        let url = SafeUrl::parse("https://example.com/").unwrap();
515        assert!(store.get_credentials(&url, None).unwrap().is_none());
516    }
517
518    #[tokio::test]
519    async fn test_file_operations() {
520        let mut temp_file = NamedTempFile::new().unwrap();
521        writeln!(
522            temp_file,
523            r#"
524[[credential]]
525service = "https://example.com"
526username = "testuser"
527scheme = "basic"
528password = "testpass"
529
530[[credential]]
531service = "https://test.org"
532username = "user2"
533password = "pass2"
534"#
535        )
536        .unwrap();
537
538        let store = TextCredentialStore::from_file(temp_file.path()).unwrap();
539
540        let url = SafeUrl::parse("https://example.com/").unwrap();
541        assert!(store.get_credentials(&url, None).unwrap().is_some());
542        let url = SafeUrl::parse("https://test.org/").unwrap();
543        assert!(store.get_credentials(&url, None).unwrap().is_some());
544
545        let url = SafeUrl::parse("https://example.com").unwrap();
546        let cred = store.get_credentials(&url, None).unwrap().unwrap();
547        assert_eq!(cred.username(), Some("testuser"));
548        assert_eq!(cred.password(), Some("testpass"));
549
550        // Test saving
551        let temp_output = NamedTempFile::new().unwrap();
552        store
553            .write(
554                temp_output.path(),
555                TextCredentialStore::lock(temp_output.path()).await.unwrap(),
556            )
557            .await
558            .unwrap();
559
560        let content = fs::read_to_string(temp_output.path()).unwrap();
561        assert!(content.contains("example.com"));
562        assert!(content.contains("testuser"));
563    }
564
565    #[test]
566    fn test_prefix_matching() {
567        let mut store = TextCredentialStore::default();
568        let credentials = Credentials::basic(Some("user".to_string()), Some("pass".to_string()));
569
570        // Store credentials for a specific path prefix
571        let service = Service::from_str("https://example.com/api").unwrap();
572        store.insert(service.clone(), credentials.clone());
573
574        // Should match URLs that are prefixes of the stored service
575        let matching_urls = [
576            "https://example.com/api",
577            "https://example.com/api/v1",
578            "https://example.com/api/v1/users",
579        ];
580
581        for url_str in matching_urls {
582            let url = SafeUrl::parse(url_str).unwrap();
583            let cred = store.get_credentials(&url, None).unwrap();
584            assert!(cred.is_some(), "Failed to match URL with prefix: {url_str}");
585        }
586
587        // Should NOT match URLs that are not prefixes
588        let non_matching_urls = [
589            "https://example.com/different",
590            "https://example.com/ap", // Not a complete path segment match
591            "https://example.com/apiary", // Not a complete path segment match
592            "https://example.com/api-v2", // Not a complete path segment match
593            "https://example.com",    // Shorter than the stored prefix
594        ];
595
596        for url_str in non_matching_urls {
597            let url = SafeUrl::parse(url_str).unwrap();
598            let cred = store.get_credentials(&url, None).unwrap();
599            assert!(cred.is_none(), "Should not match non-prefix URL: {url_str}");
600        }
601    }
602
603    #[test]
604    fn test_realm_based_matching() {
605        let mut store = TextCredentialStore::default();
606        let credentials = Credentials::basic(Some("user".to_string()), Some("pass".to_string()));
607
608        // Store by full URL (realm)
609        let service = Service::from_str("https://example.com").unwrap();
610        store.insert(service.clone(), credentials.clone());
611
612        // Should match URLs in the same realm
613        let matching_urls = [
614            "https://example.com",
615            "https://example.com/path",
616            "https://example.com/different/path",
617            "https://example.com:443/path", // Default HTTPS port
618        ];
619
620        for url_str in matching_urls {
621            let url = SafeUrl::parse(url_str).unwrap();
622            let cred = store.get_credentials(&url, None).unwrap();
623            assert!(
624                cred.is_some(),
625                "Failed to match URL in same realm: {url_str}"
626            );
627        }
628
629        // Should NOT match URLs in different realms
630        let non_matching_urls = [
631            "http://example.com",       // Different scheme
632            "https://different.com",    // Different host
633            "https://example.com:8080", // Different port
634        ];
635
636        for url_str in non_matching_urls {
637            let url = SafeUrl::parse(url_str).unwrap();
638            let cred = store.get_credentials(&url, None).unwrap();
639            assert!(
640                cred.is_none(),
641                "Should not match URL in different realm: {url_str}"
642            );
643        }
644    }
645
646    #[test]
647    fn test_most_specific_prefix_matching() {
648        let mut store = TextCredentialStore::default();
649        let general_cred =
650            Credentials::basic(Some("general".to_string()), Some("pass1".to_string()));
651        let specific_cred =
652            Credentials::basic(Some("specific".to_string()), Some("pass2".to_string()));
653
654        // Store credentials with different prefix lengths
655        let general_service = Service::from_str("https://example.com/api").unwrap();
656        let specific_service = Service::from_str("https://example.com/api/v1").unwrap();
657        store.insert(general_service.clone(), general_cred);
658        store.insert(specific_service.clone(), specific_cred);
659
660        // Should match the most specific prefix
661        let url = SafeUrl::parse("https://example.com/api/v1/users").unwrap();
662        let cred = store.get_credentials(&url, None).unwrap().unwrap();
663        assert_eq!(cred.username(), Some("specific"));
664
665        // Should match the general prefix for non-specific paths
666        let url = SafeUrl::parse("https://example.com/api/v2").unwrap();
667        let cred = store.get_credentials(&url, None).unwrap().unwrap();
668        assert_eq!(cred.username(), Some("general"));
669    }
670
671    #[test]
672    fn test_username_exact_url_match() {
673        let mut store = TextCredentialStore::default();
674        let url = SafeUrl::parse("https://example.com").unwrap();
675        let service = Service::from_str("https://example.com").unwrap();
676        let user1_creds = Credentials::basic(Some("user1".to_string()), Some("pass1".to_string()));
677        store.insert(service.clone(), user1_creds.clone());
678
679        // Should return credentials when username matches
680        let result = store.get_credentials(&url, Some("user1")).unwrap();
681        assert!(result.is_some());
682        assert_eq!(result.unwrap().username(), Some("user1"));
683        assert_eq!(result.unwrap().password(), Some("pass1"));
684
685        // Should not return credentials when username doesn't match
686        let result = store.get_credentials(&url, Some("user2")).unwrap();
687        assert!(result.is_none());
688
689        // Should return credentials when no username is specified
690        let result = store.get_credentials(&url, None).unwrap();
691        assert!(result.is_some());
692        assert_eq!(result.unwrap().username(), Some("user1"));
693    }
694
695    #[test]
696    fn test_username_prefix_url_match() {
697        let mut store = TextCredentialStore::default();
698
699        // Add credentials with different usernames for overlapping URL prefixes
700        let general_service = Service::from_str("https://example.com/api").unwrap();
701        let specific_service = Service::from_str("https://example.com/api/v1").unwrap();
702
703        let general_creds = Credentials::basic(
704            Some("general_user".to_string()),
705            Some("general_pass".to_string()),
706        );
707        let specific_creds = Credentials::basic(
708            Some("specific_user".to_string()),
709            Some("specific_pass".to_string()),
710        );
711
712        store.insert(general_service, general_creds);
713        store.insert(specific_service, specific_creds);
714
715        let url = SafeUrl::parse("https://example.com/api/v1/users").unwrap();
716
717        // Should match specific credentials when username matches
718        let result = store.get_credentials(&url, Some("specific_user")).unwrap();
719        assert!(result.is_some());
720        assert_eq!(result.unwrap().username(), Some("specific_user"));
721
722        // Should match the general credentials when requesting general_user (falls back to less specific prefix)
723        let result = store.get_credentials(&url, Some("general_user")).unwrap();
724        assert!(
725            result.is_some(),
726            "Should match general_user from less specific prefix"
727        );
728        assert_eq!(result.unwrap().username(), Some("general_user"));
729
730        // Should match most specific when no username specified
731        let result = store.get_credentials(&url, None).unwrap();
732        assert!(result.is_some());
733        assert_eq!(result.unwrap().username(), Some("specific_user"));
734    }
735
736    #[test]
737    fn test_ambiguous_username_error() {
738        let mut store = TextCredentialStore::default();
739
740        // Add two credentials for the same service with different usernames
741        let service = Service::from_str("https://example.com/api").unwrap();
742        let user1_creds = Credentials::basic(Some("user1".to_string()), Some("pass1".to_string()));
743        let user2_creds = Credentials::basic(Some("user2".to_string()), Some("pass2".to_string()));
744
745        store.insert(service.clone(), user1_creds);
746        store.insert(service.clone(), user2_creds);
747
748        let url = SafeUrl::parse("https://example.com/api/v1").unwrap();
749
750        // When no username is specified, should return an error because there are multiple matches with same specificity
751        let result = store.get_credentials(&url, None);
752        assert!(result.is_err());
753        assert_eq!(result, Err(LookupError::AmbiguousUsername(url.clone())));
754
755        // When a specific username is provided, should return the correct credentials
756        let result = store.get_credentials(&url, Some("user1")).unwrap();
757        assert!(result.is_some());
758        assert_eq!(result.unwrap().username(), Some("user1"));
759
760        let result = store.get_credentials(&url, Some("user2")).unwrap();
761        assert!(result.is_some());
762        assert_eq!(result.unwrap().username(), Some("user2"));
763    }
764}