rattler_networking 0.28.1

Authenticated requests in the conda ecosystem
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Storage and access of authentication information

use anyhow::{Result, anyhow};
use reqwest::IntoUrl;
use std::{
    collections::{BTreeMap, HashMap},
    sync::{Arc, Mutex},
};
use url::Url;

use crate::authentication_storage::{AuthenticationStorageError, backends::file::FileStorage};

use super::{StorageBackend, authentication::Authentication};

#[cfg(feature = "netrc-rs")]
use super::backends::netrc::NetRcStorage;

#[cfg(feature = "keyring")]
use crate::authentication_storage::backends::keyring::KeyringAuthenticationStorageError;

#[cfg(feature = "keyring")]
use super::backends::keyring::KeyringAuthenticationStorage;

/// A single entry returned by [`AuthenticationStorage::list_with_sources`].
/// Carries the host and credential along with the backend's display name and
/// a flag indicating whether this is the entry [`get`](AuthenticationStorage::get)
/// would actually return (the first backend that knows the host wins).
#[derive(Debug, Clone)]
pub struct ListedEntry {
    /// The host this credential is stored under.
    pub host: String,
    /// The credential itself.
    pub auth: Authentication,
    /// Human-readable name of the backend the entry came from (see
    /// [`StorageBackend::name`]).
    pub source: String,
    /// `true` if this is the entry `get(host)` would return — i.e. the first
    /// backend (in priority order) that holds credentials for `host`. Later
    /// backends with the same host are "shadowed" and have `active = false`.
    pub active: bool,
}

#[derive(Debug, Clone)]
/// This struct implements storage and access of authentication
/// information backed by multiple storage backends
/// (e.g. keyring and file storage)
/// Credentials are stored and retrieved from the backends in the
/// order they are added to the storage
pub struct AuthenticationStorage {
    /// Authentication backends
    pub backends: Vec<Arc<dyn StorageBackend + Send + Sync>>,
    cache: Arc<Mutex<HashMap<String, Option<Authentication>>>>,
}

impl AuthenticationStorage {
    /// Create a new authentication storage with no backends
    pub fn empty() -> Self {
        Self {
            backends: vec![],
            cache: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Create a new authentication storage with the default backends
    /// Following order:
    /// - file storage from `RATTLER_AUTH_FILE` (if set)
    /// - keyring storage
    /// - file storage from the default location
    /// - netrc storage
    pub fn from_env_and_defaults() -> Result<Self, AuthenticationStorageError> {
        let mut storage = Self::empty();

        if let Ok(auth_file) = std::env::var("RATTLER_AUTH_FILE") {
            let path = std::path::Path::new(&auth_file);
            tracing::info!(
                "\"RATTLER_AUTH_FILE\" environment variable set, using file storage at {}",
                auth_file
            );
            storage.add_backend(Arc::from(FileStorage::from_path(path.into())?));
        }
        #[cfg(feature = "keyring")]
        storage.add_backend(Arc::from(KeyringAuthenticationStorage::default()));
        #[cfg(feature = "dirs")]
        storage.add_backend(Arc::from(FileStorage::new()?));
        #[cfg(feature = "netrc-rs")]
        storage.add_backend(Arc::from(NetRcStorage::from_env().unwrap_or_else(
            |(path, err)| {
                tracing::warn!("error reading netrc file from {}: {}", path.display(), err);
                NetRcStorage::default()
            },
        )));

        Ok(storage)
    }

    /// Add a new storage backend to the authentication storage
    /// (backends are tried in the order they are added)
    pub fn add_backend(&mut self, backend: Arc<dyn StorageBackend + Send + Sync>) {
        self.backends.push(backend);
    }

    /// Store the given authentication information for the given host
    pub fn store(&self, host: &str, authentication: &Authentication) -> Result<()> {
        {
            let mut cache = self.cache.lock().unwrap();
            cache.insert(host.to_string(), Some(authentication.clone()));
        }

        for backend in &self.backends {
            #[allow(unused_variables)]
            if let Err(error) = backend.store(host, authentication) {
                #[cfg(feature = "keyring")]
                if matches!(
                    error,
                    AuthenticationStorageError::KeyringStorageError(
                        KeyringAuthenticationStorageError::StorageError(_)
                            | KeyringAuthenticationStorageError::UnsupportedTarget { .. }
                    )
                ) {
                    tracing::debug!("Error storing credentials in keyring: {}", error);
                } else {
                    tracing::warn!("Error storing credentials from backend: {}", error);
                }
            } else {
                return Ok(());
            }
        }

        Err(anyhow!(
            "All backends failed to store credentials. Checked the following backends: {:?}",
            self.backends
        ))
    }

    /// Retrieve the authentication information for the given host
    pub fn get(&self, host: &str) -> Result<Option<Authentication>> {
        {
            let cache = self.cache.lock().unwrap();
            if let Some(auth) = cache.get(host) {
                return Ok(auth.clone());
            }
        }

        for backend in &self.backends {
            match backend.get(host) {
                Ok(Some(auth)) => {
                    let mut cache = self.cache.lock().unwrap();
                    cache.insert(host.to_string(), Some(auth.clone()));
                    return Ok(Some(auth));
                }
                Ok(None) => {}
                Err(_e) => {
                    #[cfg(feature = "keyring")]
                    if matches!(
                        _e,
                        AuthenticationStorageError::KeyringStorageError(
                            KeyringAuthenticationStorageError::StorageError(_)
                                | KeyringAuthenticationStorageError::UnsupportedTarget { .. }
                        )
                    ) {
                        tracing::trace!("Error storing credentials in keyring: {}", _e);
                    } else {
                        tracing::warn!("Error retrieving credentials from backend: {}", _e);
                    }
                }
            }
        }

        // Cache the negative result to avoid repeated backend lookups
        // (especially important for keyring which uses D-Bus IPC on Linux).
        let mut cache = self.cache.lock().unwrap();
        cache.insert(host.to_string(), None);

        Ok(None)
    }

    /// List authentication entries known to the configured backends.
    ///
    /// Entries are deduplicated by host using backend priority, matching the
    /// lookup behavior of [`get`](Self::get).
    pub fn list(&self) -> Result<Vec<(String, Authentication)>> {
        let mut entries: BTreeMap<String, Authentication> = BTreeMap::new();

        for backend in &self.backends {
            match backend.list() {
                Ok(backend_entries) => {
                    for (host, auth) in backend_entries {
                        entries.entry(host).or_insert(auth);
                    }
                }
                Err(error) => {
                    tracing::warn!("Error listing credentials from backend: {}", error);
                }
            }
        }

        Ok(entries.into_iter().collect())
    }

    /// Like [`list`](Self::list), but reports every entry from every backend
    /// (not deduplicated) along with the backend's human-readable name (see
    /// [`StorageBackend::name`]) and whether it's the entry that `get()` would
    /// return for that host. Used by `auth status` so users can see what's
    /// stored where, including shadowed entries.
    pub fn list_with_sources(&self) -> Result<Vec<ListedEntry>> {
        let mut entries: Vec<ListedEntry> = Vec::new();
        let mut seen_hosts: std::collections::HashSet<String> = std::collections::HashSet::new();

        for backend in &self.backends {
            match backend.list() {
                Ok(backend_entries) => {
                    let source = backend.name();
                    for (host, auth) in backend_entries {
                        let active = seen_hosts.insert(host.clone());
                        entries.push(ListedEntry {
                            host,
                            auth,
                            source: source.clone(),
                            active,
                        });
                    }
                }
                Err(error) => {
                    tracing::warn!("Error listing credentials from backend: {}", error);
                }
            }
        }

        entries.sort_by(|a, b| a.host.cmp(&b.host));
        Ok(entries)
    }

    /// Retrieve the authentication information for the given URL, along with the
    /// storage key that matched (exact host or wildcard).
    ///
    /// This is useful when the caller needs to store updated credentials back
    /// under the same key (e.g. after an OAuth token refresh).
    ///
    /// Returns `(url, Some((matched_key, auth)))` or `(url, None)`.
    pub fn get_by_url_with_host<U: IntoUrl>(
        &self,
        url: U,
    ) -> Result<(Url, Option<(String, Authentication)>), reqwest::Error> {
        let url = url.into_url()?;
        let host = match url.host_str() {
            Some(h) => h.to_string(),
            None => return Ok((url, None)),
        };

        match self.get(&host) {
            Ok(None) => {}
            Err(_) => return Ok((url, None)),
            Ok(Some(credentials)) => {
                return Ok((url, Some((host, credentials))));
            }
        };

        // S3 protocol URLs need to be treated separately since they follow a different schema
        if url.scheme() == "s3" {
            let mut current_url = url.clone();
            loop {
                match self.get(current_url.as_str()) {
                    Ok(None) => {
                        let possible_rest =
                            current_url.as_str().rsplit_once('/').map(|(rest, _)| rest);

                        match possible_rest {
                            Some(rest) => {
                                if let Ok(new_url) = Url::parse(rest) {
                                    current_url = new_url;
                                } else {
                                    return Ok((url, None));
                                }
                            }
                            _ => return Ok((url, None)), // No more sub-paths to check
                        }
                    }
                    Ok(Some(credentials)) => {
                        return Ok((url, Some((current_url.as_str().to_string(), credentials))));
                    }
                    Err(_) => return Ok((url, None)),
                }
            }
        }

        // Check for credentials under e.g. `*.prefix.dev`
        let Some(mut domain) = url.domain() else {
            return Ok((url, None));
        };

        loop {
            let wildcard_host = format!("*.{domain}");

            let Ok(credentials) = self.get(&wildcard_host) else {
                return Ok((url, None));
            };

            if let Some(credentials) = credentials {
                return Ok((url, Some((wildcard_host, credentials))));
            }

            let possible_rest = domain.split_once('.').map(|(_, rest)| rest);

            match possible_rest {
                Some(rest) => {
                    domain = rest;
                }
                _ => return Ok((url, None)), // No more subdomains to check
            }
        }
    }

    /// Retrieve the authentication information for the given URL
    /// (including the authentication information for the wildcard
    /// host if no credentials are found for the given host)
    ///
    /// E.g. if credentials are stored for `*.prefix.dev` and the
    /// given URL is `https://repo.prefix.dev`, the credentials
    /// for `*.prefix.dev` will be returned.
    pub fn get_by_url<U: IntoUrl>(
        &self,
        url: U,
    ) -> Result<(Url, Option<Authentication>), reqwest::Error> {
        let (url, auth) = self.get_by_url_with_host(url)?;
        Ok((url, auth.map(|(_, credentials)| credentials)))
    }

    /// Like [`get_by_url`](Self::get_by_url), but additionally refreshes
    /// expired OAuth access tokens via the provider's token endpoint
    /// before returning. Refreshed credentials are written back to the
    /// storage so subsequent calls see the new token.
    ///
    /// Non-OAuth credentials (bearer tokens, basic auth, S3, etc.) are
    /// returned unchanged.
    pub async fn get_by_url_refreshed<U: IntoUrl>(
        &self,
        url: U,
    ) -> Result<(Url, Option<Authentication>), reqwest::Error> {
        let (url, auth_with_key) = self.get_by_url_with_host(url)?;
        let auth = match auth_with_key {
            // `maybe_refresh_oauth` is a no-op for non-OAuth variants and
            // returns them as-is, so this branch covers every auth type.
            Some((matched_key, auth)) => {
                crate::oauth_refresh::maybe_refresh_oauth(self, auth, &matched_key).await
            }
            None => None,
        };
        Ok((url, auth))
    }

    /// Delete the authentication information for the given host
    pub fn delete(&self, host: &str) -> Result<()> {
        {
            let mut cache = self.cache.lock().unwrap();
            cache.insert(host.to_string(), None);
        }

        let mut all_failed = true;

        for backend in &self.backends {
            #[allow(unused_variables)]
            if let Err(error) = backend.delete(host) {
                #[cfg(feature = "keyring")]
                if matches!(
                    error,
                    AuthenticationStorageError::KeyringStorageError(
                        KeyringAuthenticationStorageError::StorageError(_)
                            | KeyringAuthenticationStorageError::UnsupportedTarget { .. }
                    )
                ) {
                    tracing::debug!("Error deleting credentials in keyring: {}", error);
                } else {
                    tracing::warn!("Error deleting credentials from backend: {}", error);
                }
            } else {
                all_failed = false;
            }
        }

        if all_failed {
            Err(anyhow!("All backends failed to delete credentials"))
        } else {
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::authentication_storage::backends::memory::MemoryStorage;

    fn storage_with(host: &str, auth: Authentication) -> AuthenticationStorage {
        let mut storage = AuthenticationStorage::empty();
        storage.add_backend(Arc::new(MemoryStorage::new()));
        storage.store(host, &auth).unwrap();
        storage
    }

    /// Non-OAuth credentials must pass through `get_by_url_refreshed`
    /// unchanged — the refresh path only applies to OAuth.
    #[tokio::test]
    async fn get_by_url_refreshed_passes_through_non_oauth() {
        let cases = [
            Authentication::BearerToken("bearer".into()),
            Authentication::CondaToken("conda".into()),
            Authentication::BasicHTTP {
                username: "u".into(),
                password: "p".into(),
            },
            Authentication::S3Credentials {
                access_key_id: "k".into(),
                secret_access_key: "s".into(),
                session_token: None,
            },
        ];

        for auth in cases {
            let storage = storage_with("example.com", auth.clone());
            let (_, retrieved) = storage
                .get_by_url_refreshed("https://example.com/foo")
                .await
                .unwrap();
            assert_eq!(retrieved, Some(auth));
        }
    }

    #[test]
    fn list_returns_entries_from_backends() {
        let mut storage = AuthenticationStorage::empty();
        storage.add_backend(Arc::new(MemoryStorage::new()));
        storage
            .store(
                "example.com",
                &Authentication::BearerToken("token".to_string()),
            )
            .unwrap();

        assert_eq!(
            storage.list().unwrap(),
            vec![(
                "example.com".to_string(),
                Authentication::BearerToken("token".to_string())
            )]
        );
    }
}