Skip to main content

cargo/util/auth/
mod.rs

1//! Registry authentication support.
2
3use crate::{
4    context::ConfigKey,
5    util::{CargoResult, GlobalContext},
6    workspace::features::cargo_docs_link,
7};
8use anyhow::{Context as _, bail};
9use cargo_credential::{
10    Action, CacheControl, Credential, CredentialResponse, LoginOptions, Operation, RegistryInfo,
11    Secret,
12};
13
14use core::fmt;
15use std::error::Error;
16use time::{Duration, OffsetDateTime};
17use url::Url;
18
19use crate::context::Value;
20use crate::util::credential::adaptor::BasicProcessCredential;
21use crate::workspace::SourceId;
22
23use super::{credential::process::CredentialProcessCredential, credential::token::TokenCredential};
24use crate::context::{CredentialCacheValue, PathAndArgs, RegistryConfig};
25
26/// Get the list of credential providers for a registry source.
27fn credential_provider(
28    gctx: &GlobalContext,
29    sid: &SourceId,
30    require_cred_provider_config: bool,
31    show_warnings: bool,
32) -> CargoResult<Vec<Vec<String>>> {
33    let warn = |message: String| {
34        if show_warnings {
35            gctx.shell().warn(message)
36        } else {
37            Ok(())
38        }
39    };
40
41    let cfg = gctx.registry_config(sid)?;
42    let token = gctx.registry_credentials(sid)?.and_then(|c| c.token);
43    let mut global_provider_defined = true;
44    let default_providers = || {
45        global_provider_defined = false;
46        vec![vec!["cargo:token".to_string()]]
47    };
48    let global_providers = gctx
49        .get::<Option<Vec<Value<String>>>>(["registry", "global-credential-providers"])?
50        .filter(|p| !p.is_empty())
51        .map(|p| {
52            p.iter()
53                .rev()
54                .map(PathAndArgs::from_whitespace_separated_string)
55                .map(|p| resolve_credential_alias(gctx, p))
56                .collect()
57        })
58        .unwrap_or_else(default_providers);
59    tracing::debug!(?global_providers);
60
61    match (cfg, token) {
62        // If there's a specific provider configured for this registry, use it.
63        (
64            Some(RegistryConfig {
65                credential_provider: Some(provider),
66                ..
67            }),
68            token,
69        ) => {
70            let provider = resolve_credential_alias(gctx, provider);
71            if let Some(token) = token {
72                if provider[0] != "cargo:token" {
73                    warn(format!(
74                        "{sid} has a token configured in {} that will be ignored \
75                        because this registry is configured to use credential-provider `{}`",
76                        token.definition, provider[0],
77                    ))?;
78                }
79            }
80            return Ok(vec![provider]);
81        }
82
83        // Check if a `token` is configured that will be ignored.
84        (_, Some(token)) => {
85            if !global_providers
86                .iter()
87                .any(|p| p.first().map(String::as_str) == Some("cargo:token"))
88            {
89                warn(format!(
90                    "{sid} has a token configured in {} that will be ignored \
91                    because the `cargo:token` credential provider is not listed in \
92                    `registry.global-credential-providers`",
93                    token.definition
94                ))?;
95            }
96        }
97
98        // If we couldn't find a registry-specific provider, use the fallback provider list.
99        _ => {}
100    };
101    if !global_provider_defined && require_cred_provider_config {
102        bail!(
103            "authenticated registries require a credential-provider to be configured\n\
104        see {} for details",
105            cargo_docs_link("reference/registry-authentication.html")
106        );
107    }
108    Ok(global_providers)
109}
110
111/// Use the `[credential-alias]` table to see if the provider name has been aliased.
112fn resolve_credential_alias(gctx: &GlobalContext, mut provider: PathAndArgs) -> Vec<String> {
113    if provider.args.is_empty() {
114        let name = provider.path.raw_value();
115        let key = format!("credential-alias.{name}");
116        if let Ok(alias) = gctx.get::<Value<PathAndArgs>>(["credential-alias", name]) {
117            tracing::debug!("resolving credential alias '{key}' -> '{alias:?}'");
118            if BUILT_IN_PROVIDERS.contains(&name) {
119                let _ = gctx.shell().warn(format!(
120                    "credential-alias `{name}` (defined in `{}`) will be \
121                    ignored because it would shadow a built-in credential-provider",
122                    alias.definition
123                ));
124            } else {
125                provider = alias.val;
126            }
127        }
128    }
129    provider.args.insert(
130        0,
131        provider
132            .path
133            .resolve_program(gctx)
134            .to_str()
135            .unwrap()
136            .to_string(),
137    );
138    provider.args
139}
140
141#[derive(Debug, PartialEq)]
142pub enum AuthorizationErrorReason {
143    TokenMissing,
144    TokenRejected,
145}
146
147impl fmt::Display for AuthorizationErrorReason {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match self {
150            AuthorizationErrorReason::TokenMissing => write!(f, "no token found"),
151            AuthorizationErrorReason::TokenRejected => write!(f, "token rejected"),
152        }
153    }
154}
155
156/// An authorization error from accessing a registry.
157#[derive(Debug)]
158pub struct AuthorizationError {
159    /// Url that was attempted
160    sid: SourceId,
161    /// The `registry.default` config value.
162    default_registry: Option<String>,
163    /// Url where the user could log in.
164    pub login_url: Option<Url>,
165    /// Specific reason indicating what failed
166    reason: AuthorizationErrorReason,
167    /// Should `cargo login` and the `_TOKEN` env var be included when displaying this error?
168    supports_cargo_token_credential_provider: bool,
169    /// Whether the cached token appears to lack an authentication scheme (no space found).
170    token_lacks_scheme: Option<bool>,
171}
172
173impl AuthorizationError {
174    pub fn new(
175        gctx: &GlobalContext,
176        sid: SourceId,
177        login_url: Option<Url>,
178        reason: AuthorizationErrorReason,
179    ) -> CargoResult<Self> {
180        // Only display the _TOKEN environment variable suggestion if the `cargo:token` credential
181        // provider is available for the source. Otherwise setting the environment variable will
182        // have no effect.
183        let supports_cargo_token_credential_provider =
184            credential_provider(gctx, &sid, false, false)?
185                .iter()
186                .any(|p| p.first().map(String::as_str) == Some("cargo:token"));
187        let cache = gctx.credential_cache();
188        let token_lacks_scheme = cache
189            .get(sid.canonical_url())
190            .map(|entry| !entry.token_value.as_deref().expose().contains(' '));
191        Ok(AuthorizationError {
192            sid,
193            default_registry: gctx.default_registry()?,
194            login_url,
195            reason,
196            supports_cargo_token_credential_provider,
197            token_lacks_scheme,
198        })
199    }
200}
201
202impl Error for AuthorizationError {}
203impl fmt::Display for AuthorizationError {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        if self.sid.is_crates_io() {
206            let args = if self.default_registry.is_some() {
207                " --registry crates-io"
208            } else {
209                ""
210            };
211            write!(f, "{}, please run `cargo login{args}`", self.reason)?;
212            if self.supports_cargo_token_credential_provider {
213                write!(f, "\nor use environment variable CARGO_REGISTRY_TOKEN")?;
214            }
215            Ok(())
216        } else if let Some(name) = self.sid.alt_registry_key() {
217            write!(
218                f,
219                "{} for `{}`",
220                self.reason,
221                self.sid.display_registry_name()
222            )?;
223            if self.supports_cargo_token_credential_provider {
224                let key = ConfigKey::from_str(&format!("registries.{name}.token"));
225                write!(
226                    f,
227                    ", please run `cargo login --registry {name}`\n\
228                    or use environment variable {}",
229                    key.as_env_key()
230                )?;
231            } else {
232                write!(
233                    f,
234                    "\nYou may need to log in using this registry's credential provider"
235                )?;
236            }
237
238            if self.reason == AuthorizationErrorReason::TokenRejected {
239                if self.token_lacks_scheme == Some(true) {
240                    write!(
241                        f,
242                        "\nnote: the token does not include an authentication scheme"
243                    )?;
244                }
245            }
246            Ok(())
247        } else if self.reason == AuthorizationErrorReason::TokenMissing {
248            write!(
249                f,
250                r#"{} for `{}`
251consider setting up an alternate registry in Cargo's configuration
252as described by https://doc.rust-lang.org/cargo/reference/registries.html
253
254[registries]
255my-registry = {{ index = "{}" }}
256"#,
257                self.reason,
258                self.sid.display_registry_name(),
259                self.sid.url()
260            )
261        } else {
262            write!(
263                f,
264                r#"{} for `{}`"#,
265                self.reason,
266                self.sid.display_registry_name(),
267            )
268        }
269    }
270}
271
272/// Store a token in the cache for future calls.
273pub fn cache_token_from_commandline(gctx: &GlobalContext, sid: &SourceId, token: Secret<&str>) {
274    let url = sid.canonical_url();
275    gctx.credential_cache().insert(
276        url.clone(),
277        CredentialCacheValue {
278            token_value: token.to_owned(),
279            expiration: None,
280            operation_independent: true,
281        },
282    );
283}
284
285/// List of credential providers built-in to Cargo.
286/// Keep in sync with the `match` in `credential_action`.
287static BUILT_IN_PROVIDERS: &[&'static str] = &[
288    "cargo:token",
289    "cargo:token-from-stdout",
290    "cargo:wincred",
291    "cargo:macos-keychain",
292    "cargo:libsecret",
293];
294
295/// Retrieves a cached instance of `LibSecretCredential`.
296/// Must be cached to avoid repeated load/unload cycles, which are not supported by `glib`.
297#[cfg(target_os = "linux")]
298fn get_credential_libsecret()
299-> CargoResult<&'static cargo_credential_libsecret::LibSecretCredential> {
300    static CARGO_CREDENTIAL_LIBSECRET: std::sync::OnceLock<
301        cargo_credential_libsecret::LibSecretCredential,
302    > = std::sync::OnceLock::new();
303    // Unfortunately `get_or_try_init` is not yet stable. This workaround is not threadsafe but
304    // loading libsecret twice will only temporary increment the ref counter, which is decrement
305    // again when `drop` is called.
306    match CARGO_CREDENTIAL_LIBSECRET.get() {
307        Some(lib) => Ok(lib),
308        None => {
309            let _ = CARGO_CREDENTIAL_LIBSECRET
310                .set(cargo_credential_libsecret::LibSecretCredential::new()?);
311            Ok(CARGO_CREDENTIAL_LIBSECRET.get().unwrap())
312        }
313    }
314}
315
316fn credential_action(
317    gctx: &GlobalContext,
318    sid: &SourceId,
319    action: Action<'_>,
320    headers: Vec<String>,
321    args: &[&str],
322    require_cred_provider_config: bool,
323) -> CargoResult<CredentialResponse> {
324    let name = sid.alt_registry_key();
325    let registry = RegistryInfo {
326        index_url: sid.url().as_str(),
327        name,
328        headers,
329    };
330    let providers = credential_provider(gctx, sid, require_cred_provider_config, true)?;
331    let mut any_not_found = false;
332    for provider in providers {
333        let args: Vec<&str> = provider
334            .iter()
335            .map(String::as_str)
336            .chain(args.iter().copied())
337            .collect();
338        let process = args[0];
339        tracing::debug!("attempting credential provider: {args:?}");
340        // If the available built-in providers are changed, update the `BUILT_IN_PROVIDERS` list.
341        let provider: Box<dyn Credential> = match process {
342            "cargo:token" => Box::new(TokenCredential::new(gctx)),
343            "cargo:token-from-stdout" => Box::new(BasicProcessCredential {}),
344            #[cfg(windows)]
345            "cargo:wincred" => Box::new(cargo_credential_wincred::WindowsCredential {}),
346            #[cfg(target_os = "macos")]
347            "cargo:macos-keychain" => Box::new(cargo_credential_macos_keychain::MacKeychain {}),
348            #[cfg(target_os = "linux")]
349            "cargo:libsecret" => Box::new(get_credential_libsecret()?),
350            name if BUILT_IN_PROVIDERS.contains(&name) => {
351                Box::new(cargo_credential::UnsupportedCredential {})
352            }
353            process => Box::new(CredentialProcessCredential::new(process)),
354        };
355        gctx.shell().verbose(|c| {
356            c.status(
357                "Credential",
358                format!(
359                    "{} {action} {}",
360                    args.join(" "),
361                    sid.display_registry_name()
362                ),
363            )
364        })?;
365        match provider.perform(&registry, &action, &args[1..]) {
366            Ok(response) => return Ok(response),
367            Err(cargo_credential::Error::UrlNotSupported) => {}
368            Err(cargo_credential::Error::NotFound) => any_not_found = true,
369            e => {
370                return e.with_context(|| {
371                    format!(
372                        "credential provider `{}` failed action `{action}`",
373                        args.join(" ")
374                    )
375                });
376            }
377        }
378    }
379    if any_not_found {
380        Err(cargo_credential::Error::NotFound.into())
381    } else {
382        anyhow::bail!("no credential providers could handle the request")
383    }
384}
385
386/// Returns the token to use for the given registry.
387/// If a `login_url` is provided and a token is not available, the
388/// `login_url` will be included in the returned error.
389pub fn auth_token(
390    gctx: &GlobalContext,
391    sid: &SourceId,
392    login_url: Option<&Url>,
393    operation: Operation<'_>,
394    headers: Vec<String>,
395    require_cred_provider_config: bool,
396) -> CargoResult<String> {
397    match auth_token_optional(gctx, sid, operation, headers, require_cred_provider_config)? {
398        Some(token) => Ok(token.expose()),
399        None => Err(AuthorizationError::new(
400            gctx,
401            *sid,
402            login_url.cloned(),
403            AuthorizationErrorReason::TokenMissing,
404        )?
405        .into()),
406    }
407}
408
409/// Returns the token to use for the given registry.
410fn auth_token_optional(
411    gctx: &GlobalContext,
412    sid: &SourceId,
413    operation: Operation<'_>,
414    headers: Vec<String>,
415    require_cred_provider_config: bool,
416) -> CargoResult<Option<Secret<String>>> {
417    tracing::trace!("token requested for {}", sid.display_registry_name());
418    let mut cache = gctx.credential_cache();
419    let url = sid.canonical_url();
420    if let Some(cached_token) = cache.get(url) {
421        if cached_token
422            .expiration
423            .map(|exp| OffsetDateTime::now_utc() + Duration::minutes(1) < exp)
424            .unwrap_or(true)
425        {
426            if cached_token.operation_independent || matches!(operation, Operation::Read) {
427                tracing::trace!("using token from in-memory cache");
428                return Ok(Some(cached_token.token_value.clone()));
429            }
430        } else {
431            // Remove expired token from the cache
432            cache.remove(url);
433        }
434    }
435
436    let credential_response = credential_action(
437        gctx,
438        sid,
439        Action::Get(operation),
440        headers,
441        &[],
442        require_cred_provider_config,
443    );
444    if let Some(e) = credential_response.as_ref().err() {
445        if let Some(e) = e.downcast_ref::<cargo_credential::Error>() {
446            if matches!(e, cargo_credential::Error::NotFound) {
447                return Ok(None);
448            }
449        }
450    }
451    let credential_response = credential_response?;
452
453    let CredentialResponse::Get {
454        token,
455        cache: cache_control,
456        operation_independent,
457    } = credential_response
458    else {
459        bail!(
460            "credential provider produced unexpected response for `get` request: {credential_response:?}"
461        )
462    };
463    let token = Secret::from(token);
464    tracing::trace!("found token");
465    let expiration = match cache_control {
466        CacheControl::Expires { expiration } => Some(expiration),
467        CacheControl::Session => None,
468        CacheControl::Never | _ => return Ok(Some(token)),
469    };
470
471    cache.insert(
472        url.clone(),
473        CredentialCacheValue {
474            token_value: token.clone(),
475            expiration,
476            operation_independent,
477        },
478    );
479    Ok(Some(token))
480}
481
482/// Log out from the given registry.
483pub fn logout(gctx: &GlobalContext, sid: &SourceId) -> CargoResult<()> {
484    let credential_response = credential_action(gctx, sid, Action::Logout, vec![], &[], false);
485    if let Some(e) = credential_response.as_ref().err() {
486        if let Some(e) = e.downcast_ref::<cargo_credential::Error>() {
487            if matches!(e, cargo_credential::Error::NotFound) {
488                gctx.shell().status(
489                    "Logout",
490                    format!(
491                        "not currently logged in to `{}`",
492                        sid.display_registry_name()
493                    ),
494                )?;
495                return Ok(());
496            }
497        }
498    }
499    let credential_response = credential_response?;
500    let CredentialResponse::Logout = credential_response else {
501        bail!(
502            "credential provider produced unexpected response for `logout` request: {credential_response:?}"
503        )
504    };
505    Ok(())
506}
507
508/// Log in to the given registry.
509pub fn login(
510    gctx: &GlobalContext,
511    sid: &SourceId,
512    options: LoginOptions<'_>,
513    args: &[&str],
514) -> CargoResult<()> {
515    let credential_response =
516        credential_action(gctx, sid, Action::Login(options), vec![], args, false)?;
517    let CredentialResponse::Login = credential_response else {
518        bail!(
519            "credential provider produced unexpected response for `login` request: {credential_response:?}"
520        )
521    };
522    Ok(())
523}