OXYGENHUB
# 170bb436e1d5 oxygen / crates / oxy-strata / src / lib.rs
23.6 KiB · Rust · last changed Cloud stores take credentials handed over 1 month ago source blame history raw
8d803563 Andy McCall ↶ 1
//! Oxygen Strata: repositories kept on cloud object storage (docs/stores.md).
2
//!
3
//! This crate gives `oxy` the stores that need an HTTP client and the
4
//! providers' signing: Amazon S3 (`s3://BUCKET/PREFIX`), Google Cloud
5
//! Storage (`gs://BUCKET/PREFIX`) and Azure Blob Storage
6
//! (`az://ACCOUNT/CONTAINER/PREFIX`), each as a [`Store`] over the
7
//! `object_store` crate. Credentials come from each provider's standard
8
//! places, with nothing oxy-specific to set up; a URL may carry settings
9
//! as query parameters (`?profile=work&region=eu-west-2`), which is where
10
//! `oxy remote add --profile` keeps them.
11
//!
12
//! [`register`] hands these stores to oxy-core's remote opener; a program
13
//! that links this crate calls it once at start.
14
15
mod aws;
16
mod azure;
17
mod gcp;
2cd40ea1 Andy McCall ↶ 18
mod http;
8d803563 Andy McCall ↶ 19
mod ini;
20
21
use futures::TryStreamExt;
22
use object_store::path::Path as ObjectPath;
23
use object_store::{
24
    GetOptions, ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload, UpdateVersion,
25
};
26
use oxy_core::strata::{check_key, Entry, Error, Result, Store, Version};
27
use std::collections::BTreeMap;
28
use std::future::Future;
29
use std::ops::Range;
30
use std::sync::{Arc, Mutex};
31
32
/// Make the cloud stores available to `oxy_core::protocol::open_remote`.
33
/// Safe to call more than once.
34
pub fn register() {
35
    // object_store's reqwest is built with rustls and no bundled crypto
36
    // provider; oxy links ring already, so that is the one to install.
37
    let _ = rustls::crypto::ring::default_provider().install_default();
38
    oxy_core::protocol::register_store_opener(open_url);
39
}
40
41
fn open_url(
42
    url: &str,
43
    _options: &oxy_core::protocol::RemoteOptions,
44
) -> Option<Result<Box<dyn Store>>> {
45
    let scheme = url.split_once("://")?.0;
46
    if !matches!(scheme, "s3" | "gs" | "az") {
47
        return None;
48
    }
7026bd7d Andy McCall ↶ 49
    let lookup = *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner());
50
    let given = lookup.and_then(|f| f(url));
51
    Some(CloudStore::open_with(url, given.as_ref()).map(|s| Box::new(s) as Box<dyn Store>))
8d803563 Andy McCall ↶ 52
}
53
7026bd7d Andy McCall ↶ 54
/// Credentials a program keeps itself and hands over, instead of the
55
/// provider's usual places: a hub keeps each repository's sealed. When a
56
/// store is opened with them, nothing from the environment or the
57
/// provider's files is used.
58
#[derive(Clone, PartialEq, Eq)]
59
pub enum Credentials {
60
    /// An S3 access key.
61
    Aws {
62
        access_key_id: String,
63
        secret_access_key: String,
64
        session_token: Option<String>,
65
    },
66
    /// A Google Cloud service account key, as the JSON Google issues.
67
    Gcp { service_account_key: String },
68
    /// An Azure service principal.
69
    Azure {
70
        tenant_id: String,
71
        client_id: String,
72
        client_secret: String,
73
    },
74
}
75
76
impl std::fmt::Debug for Credentials {
77
    /// Names the kind and the public part only: never the secret.
78
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79
        match self {
80
            Credentials::Aws { access_key_id, .. } => {
81
                write!(f, "Aws({access_key_id}, secret hidden)")
82
            }
83
            Credentials::Gcp { .. } => write!(f, "Gcp(service account key hidden)"),
84
            Credentials::Azure { client_id, .. } => write!(f, "Azure({client_id}, secret hidden)"),
85
        }
86
    }
87
}
88
89
impl Credentials {
90
    /// The scheme of the stores these are for.
91
    pub fn scheme(&self) -> &'static str {
92
        match self {
93
            Credentials::Aws { .. } => "s3",
94
            Credentials::Gcp { .. } => "gs",
95
            Credentials::Azure { .. } => "az",
96
        }
97
    }
98
99
    /// As JSON, for keeping (sealed) and reading back with [`Credentials::from_json`].
100
    pub fn to_json(&self) -> String {
101
        let v = match self {
102
            Credentials::Aws {
103
                access_key_id,
104
                secret_access_key,
105
                session_token,
106
            } => serde_json::json!({
107
                "kind": "aws", "access_key_id": access_key_id, "secret_access_key": secret_access_key,
108
                "session_token": session_token,
109
            }),
110
            Credentials::Gcp {
111
                service_account_key,
112
            } => {
113
                serde_json::json!({ "kind": "gcp", "service_account_key": service_account_key })
114
            }
115
            Credentials::Azure {
116
                tenant_id,
117
                client_id,
118
                client_secret,
119
            } => serde_json::json!({
120
                "kind": "azure", "tenant_id": tenant_id, "client_id": client_id, "client_secret": client_secret,
121
            }),
122
        };
123
        v.to_string()
124
    }
125
126
    pub fn from_json(text: &str) -> Result<Credentials> {
127
        let v: serde_json::Value = serde_json::from_str(text)
128
            .map_err(|e| Error::Backend(format!("credentials are not JSON: {e}")))?;
129
        let field = |k: &str| -> Result<String> {
130
            v.get(k)
131
                .and_then(|x| x.as_str())
132
                .filter(|x| !x.trim().is_empty())
133
                .map(|x| x.trim().to_string())
134
                .ok_or_else(|| Error::Backend(format!("credentials need {k}")))
135
        };
136
        match v.get("kind").and_then(|k| k.as_str()) {
137
            Some("aws") => Ok(Credentials::Aws {
138
                access_key_id: field("access_key_id")?,
139
                secret_access_key: field("secret_access_key")?,
140
                session_token: field("session_token").ok(),
141
            }),
142
            Some("gcp") => {
143
                let key = field("service_account_key")?;
144
                let parsed: serde_json::Value = serde_json::from_str(&key).map_err(|_| {
145
                    Error::Backend("the service account key is not the JSON Google issues".into())
146
                })?;
147
                if parsed.get("type").and_then(|t| t.as_str()) != Some("service_account") {
148
                    return Err(Error::Backend(
149
                        "the key is not a service account key (its type is not service_account)"
150
                            .into(),
151
                    ));
152
                }
153
                Ok(Credentials::Gcp {
154
                    service_account_key: key,
155
                })
156
            }
157
            Some("azure") => Ok(Credentials::Azure {
158
                tenant_id: field("tenant_id")?,
159
                client_id: field("client_id")?,
160
                client_secret: field("client_secret")?,
161
            }),
162
            _ => Err(Error::Backend(
163
                "credentials need a kind: aws, gcp or azure".into(),
164
            )),
165
        }
166
    }
167
}
168
169
/// Finds the credentials a program keeps for a store URL.
170
pub type CredentialsLookup = fn(&str) -> Option<Credentials>;
171
172
static CREDENTIALS: Mutex<Option<CredentialsLookup>> = Mutex::new(None);
173
174
/// Have stores opened by URL (as a repository's `storage.url` is) use the
175
/// credentials `lookup` finds for it, where it finds any.
176
pub fn set_credentials_lookup(lookup: CredentialsLookup) {
177
    *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner()) = Some(lookup);
178
}
179
8d803563 Andy McCall ↶ 180
/// A parsed store URL: `SCHEME://HOST/PATH?PARAMS`.
181
#[derive(Clone, Debug, PartialEq, Eq)]
182
pub struct StoreUrl {
183
    pub scheme: String,
184
    /// The bucket (S3, GCS) or the storage account (Azure).
185
    pub host: String,
186
    /// The path under the host, without leading or trailing slashes; for
187
    /// Azure the container is its first segment.
188
    pub path: String,
189
    pub params: BTreeMap<String, String>,
190
}
191
192
impl StoreUrl {
193
    pub fn parse(url: &str) -> Result<StoreUrl> {
194
        let bad = |why: &str| Error::Backend(format!("{url}: {why}"));
195
        let (scheme, rest) = url.split_once("://").ok_or_else(|| bad("not a URL"))?;
196
        let (rest, query) = match rest.split_once('?') {
197
            Some((r, q)) => (r, Some(q)),
198
            None => (rest, None),
199
        };
200
        let (host, path) = match rest.split_once('/') {
201
            Some((h, p)) => (h, p.trim_matches('/')),
202
            None => (rest, ""),
203
        };
204
        if host.is_empty() {
205
            return Err(bad("names no bucket"));
206
        }
207
        let mut params = BTreeMap::new();
208
        for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
209
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
210
            params.insert(k.to_string(), percent_decode(v));
211
        }
212
        Ok(StoreUrl {
213
            scheme: scheme.to_string(),
214
            host: host.to_string(),
215
            path: path.to_string(),
216
            params,
217
        })
218
    }
219
220
    /// The URL without its parameters, for messages.
221
    pub fn plain(&self) -> String {
222
        if self.path.is_empty() {
223
            format!("{}://{}", self.scheme, self.host)
224
        } else {
225
            format!("{}://{}/{}", self.scheme, self.host, self.path)
226
        }
227
    }
228
229
    pub fn param(&self, name: &str) -> Option<&str> {
230
        self.params.get(name).map(String::as_str)
231
    }
232
}
233
234
fn percent_decode(s: &str) -> String {
235
    let bytes = s.as_bytes();
236
    let mut out = Vec::with_capacity(bytes.len());
237
    let mut i = 0;
238
    while i < bytes.len() {
239
        if bytes[i] == b'%' && i + 2 < bytes.len() {
240
            if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
241
                out.push(v);
242
                i += 3;
243
                continue;
244
            }
245
        }
246
        out.push(bytes[i]);
247
        i += 1;
248
    }
249
    String::from_utf8_lossy(&out).into_owned()
250
}
251
252
/// A store on a cloud provider: the provider's client, the prefix every
253
/// key goes under, and a runtime to run the client on.
254
pub struct CloudStore {
255
    inner: Arc<dyn ObjectStore>,
256
    prefix: String,
257
    name: String,
258
    hint: &'static str,
259
    runtime: tokio::runtime::Runtime,
260
    /// One call at a time: the runtime runs on the calling thread.
261
    turn: Mutex<()>,
262
}
263
264
impl CloudStore {
265
    /// Open the store a URL names. Nothing is sent yet: credentials are
266
    /// resolved here, but the bucket is first spoken to on the first call.
267
    pub fn open(url: &str) -> Result<CloudStore> {
7026bd7d Andy McCall ↶ 268
        Self::open_with(url, None)
269
    }
270
271
    /// [`CloudStore::open`] with credentials given, which must be for
272
    /// the URL's kind of store; then only they are used.
273
    pub fn open_with(url: &str, given: Option<&Credentials>) -> Result<CloudStore> {
8d803563 Andy McCall ↶ 274
        let parsed = StoreUrl::parse(url)?;
7026bd7d Andy McCall ↶ 275
        if let Some(c) = given.filter(|c| c.scheme() != parsed.scheme) {
276
            return Err(Error::Backend(format!(
277
                "{}: the credentials given are for {}:// stores",
278
                parsed.plain(),
279
                c.scheme()
280
            )));
281
        }
282
        let aws_keys = match given {
283
            Some(Credentials::Aws {
284
                access_key_id,
285
                secret_access_key,
286
                session_token,
287
            }) => Some((
288
                access_key_id.as_str(),
289
                secret_access_key.as_str(),
290
                session_token.as_deref(),
291
            )),
292
            _ => None,
293
        };
294
        let gcp_key = match given {
295
            Some(Credentials::Gcp {
296
                service_account_key,
297
            }) => Some(service_account_key.as_str()),
298
            _ => None,
299
        };
300
        let principal = match given {
301
            Some(Credentials::Azure {
302
                tenant_id,
303
                client_id,
304
                client_secret,
305
            }) => Some((
306
                tenant_id.as_str(),
307
                client_id.as_str(),
308
                client_secret.as_str(),
309
            )),
310
            _ => None,
311
        };
8d803563 Andy McCall ↶ 312
        let runtime = tokio::runtime::Builder::new_current_thread()
313
            .enable_all()
314
            .build()
315
            .map_err(|e| Error::Backend(format!("starting the HTTP runtime: {e}")))?;
316
        let (inner, prefix, hint): (Arc<dyn ObjectStore>, String, &'static str) =
317
            match parsed.scheme.as_str() {
318
                "s3" => (
7026bd7d Andy McCall ↶ 319
                    Arc::new(aws::open(&parsed, aws_keys)?),
8d803563 Andy McCall ↶ 320
                    parsed.path.clone(),
321
                    aws::HINT,
322
                ),
323
                "gs" => (
7026bd7d Andy McCall ↶ 324
                    Arc::new(gcp::open(&parsed, gcp_key)?),
8d803563 Andy McCall ↶ 325
                    parsed.path.clone(),
326
                    gcp::HINT,
327
                ),
328
                "az" => {
7026bd7d Andy McCall ↶ 329
                    let (store, prefix) = azure::open(&parsed, principal)?;
8d803563 Andy McCall ↶ 330
                    (Arc::new(store), prefix, azure::HINT)
331
                }
332
                other => {
333
                    return Err(Error::Backend(format!(
334
                        "{url}: {other}:// is not a store oxy knows (s3://, gs://, az://, dir://)"
335
                    )))
336
                }
337
            };
338
        Ok(CloudStore {
339
            inner,
340
            prefix,
341
            name: parsed.plain(),
342
            hint,
343
            runtime,
344
            turn: Mutex::new(()),
345
        })
346
    }
347
348
    fn block<F: Future>(&self, f: F) -> F::Output {
349
        let _turn = self.turn.lock().unwrap_or_else(|p| p.into_inner());
350
        self.runtime.block_on(f)
351
    }
352
353
    fn path(&self, key: &str) -> Result<ObjectPath> {
354
        check_key(key)?;
355
        let full = if self.prefix.is_empty() {
356
            key.to_string()
357
        } else {
358
            format!("{}/{key}", self.prefix)
359
        };
360
        ObjectPath::parse(&full).map_err(|e| Error::Backend(format!("{full}: {e}")))
361
    }
362
363
    /// Our error for the provider's, with what to do next where it helps.
364
    fn map(&self, e: object_store::Error, key: &str) -> Error {
365
        use object_store::Error as E;
366
        match e {
367
            E::NotFound { .. } => Error::NotFound(key.to_string()),
368
            E::AlreadyExists { .. } => Error::Exists(key.to_string()),
369
            E::Precondition { .. } | E::NotModified { .. } => Error::Conflict(key.to_string()),
370
            other => {
371
                let text = other.to_string();
372
                let lower = text.to_ascii_lowercase();
373
                let advice = if lower.contains("403")
374
                    || lower.contains("accessdenied")
375
                    || lower.contains("forbidden")
376
                    || lower.contains("authorizationpermissionmismatch")
377
                {
378
                    format!(
379
                        ": access denied; the credentials in use may not do this on {}: {}",
380
                        self.name, self.hint
381
                    )
382
                } else if lower.contains("credential") || lower.contains("no valid credentials") {
383
                    format!(": no usable credentials: {}", self.hint)
384
                } else if lower.contains("nosuchbucket")
385
                    || lower.contains("bucketnotfound")
386
                    || lower.contains("containernotfound")
387
                {
388
                    format!(
389
                        ": {} does not exist, or the credentials cannot see it",
390
                        self.name
391
                    )
392
                } else if lower.contains("dns")
393
                    || lower.contains("connect")
394
                    || lower.contains("timed out")
395
                {
396
                    ": cannot reach the service; check the network, the endpoint and the region"
397
                        .to_string()
398
                } else {
399
                    String::new()
400
                };
401
                Error::Backend(format!("{}: {text}{advice}", self.name))
402
            }
403
        }
404
    }
405
406
    fn version_of(e_tag: Option<String>, version: Option<String>) -> Version {
407
        Version(format!(
408
            "{}\t{}",
409
            e_tag.unwrap_or_default(),
410
            version.unwrap_or_default()
411
        ))
412
    }
413
414
    fn update_version(v: &Version) -> UpdateVersion {
415
        let (e_tag, version) = v.0.split_once('\t').unwrap_or((v.0.as_str(), ""));
416
        UpdateVersion {
417
            e_tag: (!e_tag.is_empty()).then(|| e_tag.to_string()),
418
            version: (!version.is_empty()).then(|| version.to_string()),
419
        }
420
    }
421
}
422
423
impl Store for CloudStore {
424
    fn describe(&self) -> String {
425
        self.name.clone()
426
    }
427
428
    fn has(&self, key: &str) -> Result<bool> {
429
        let path = self.path(key)?;
430
        match self.block(self.inner.head(&path)) {
431
            Ok(_) => Ok(true),
432
            Err(object_store::Error::NotFound { .. }) => Ok(false),
433
            Err(e) => Err(self.map(e, key)),
434
        }
435
    }
436
437
    fn get(&self, key: &str) -> Result<Vec<u8>> {
438
        let path = self.path(key)?;
439
        self.block(async {
440
            let r = self.inner.get(&path).await?;
441
            r.bytes().await
442
        })
443
        .map(|b| b.to_vec())
444
        .map_err(|e| self.map(e, key))
445
    }
446
447
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
448
        let path = self.path(key)?;
449
        if range.start > range.end {
450
            return Err(Error::Backend(format!(
451
                "{key}: bytes {}..{} is not a range",
452
                range.start, range.end
453
            )));
454
        }
455
        if range.is_empty() {
456
            return Ok(Vec::new());
457
        }
458
        let want = (range.end - range.start) as usize;
459
        let bytes = self
460
            .block(self.inner.get_range(&path, range.clone()))
461
            .map_err(|e| self.map(e, key))?;
462
        if bytes.len() != want {
463
            return Err(Error::Backend(format!(
464
                "{key}: bytes {}..{} asked, {} returned: the object is shorter",
465
                range.start,
466
                range.end,
467
                bytes.len()
468
            )));
469
        }
470
        Ok(bytes.to_vec())
471
    }
472
473
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
474
        let path = self.path(key)?;
475
        let opts = PutOptions {
476
            mode: PutMode::Create,
477
            ..Default::default()
478
        };
479
        self.block(
480
            self.inner
481
                .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
482
        )
483
        .map(|_| ())
484
        .map_err(|e| self.map(e, key))
485
    }
486
487
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
488
        // Providers list by whole path segments; the asked prefix may end
489
        // mid-segment, so list its directory and filter here.
490
        let dir = prefix.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
491
        let full_dir = match (self.prefix.as_str(), dir) {
492
            ("", "") => None,
493
            ("", d) => Some(d.to_string()),
494
            (p, "") => Some(p.to_string()),
495
            (p, d) => Some(format!("{p}/{d}")),
496
        };
497
        let full_dir = full_dir
498
            .map(|d| ObjectPath::parse(&d).map_err(|e| Error::Backend(format!("{d}: {e}"))))
499
            .transpose()?;
500
        let metas: Vec<object_store::ObjectMeta> = self
501
            .block(self.inner.list(full_dir.as_ref()).try_collect())
502
            .map_err(|e| self.map(e, prefix))?;
503
        let strip = if self.prefix.is_empty() {
504
            String::new()
505
        } else {
506
            format!("{}/", self.prefix)
507
        };
508
        let mut out: Vec<Entry> = metas
509
            .into_iter()
510
            .filter_map(|m| {
511
                let loc = m.location.to_string();
512
                let key = loc.strip_prefix(&strip)?;
513
                key.starts_with(prefix).then(|| Entry {
514
                    key: key.to_string(),
515
                    size: m.size,
64818938 Andy McCall ↶ 516
                    modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
8d803563 Andy McCall ↶ 517
                })
518
            })
519
            .collect();
520
        out.sort_by(|a, b| a.key.cmp(&b.key));
521
        Ok(out)
522
    }
523
524
    fn delete(&self, key: &str) -> Result<()> {
525
        let path = self.path(key)?;
526
        match self.block(self.inner.delete(&path)) {
527
            Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
528
            Err(e) => Err(self.map(e, key)),
529
        }
530
    }
531
532
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
533
        let path = self.path(key)?;
534
        let got = self.block(async {
535
            let r = self.inner.get_opts(&path, GetOptions::default()).await?;
536
            let meta = r.meta.clone();
537
            let bytes = r.bytes().await?;
538
            Ok::<_, object_store::Error>((bytes, meta))
539
        });
540
        match got {
541
            Ok((bytes, meta)) => Ok(Some((
542
                bytes.to_vec(),
543
                Self::version_of(meta.e_tag, meta.version),
544
            ))),
545
            Err(object_store::Error::NotFound { .. }) => Ok(None),
546
            Err(e) => Err(self.map(e, key)),
547
        }
548
    }
549
550
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
551
        let path = self.path(key)?;
552
        let mode = match expected {
553
            None => PutMode::Create,
554
            Some(v) => PutMode::Update(Self::update_version(v)),
555
        };
556
        let opts = PutOptions {
557
            mode,
558
            ..Default::default()
559
        };
560
        let put = self
561
            .block(
562
                self.inner
563
                    .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
564
            )
565
            .map_err(|e| match self.map(e, key) {
566
                // A record that exists when none was expected is a lost
567
                // race too, not a misuse of put_new.
568
                Error::Exists(k) => Error::Conflict(k),
569
                other => other,
570
            })?;
571
        Ok(Self::version_of(put.e_tag, put.version))
572
    }
573
}
574
575
#[cfg(test)]
576
mod tests {
7026bd7d Andy McCall ↶ 577
    #[test]
578
    fn credentials_round_trip_and_never_show_their_secret() {
579
        let aws = Credentials::Aws {
580
            access_key_id: "AKIDEXAMPLE".into(),
581
            secret_access_key: "wJalrXUtnFEMI".into(),
582
            session_token: None,
583
        };
584
        assert_eq!(Credentials::from_json(&aws.to_json()).unwrap(), aws);
585
        assert_eq!(format!("{aws:?}"), "Aws(AKIDEXAMPLE, secret hidden)");
586
        let az = Credentials::Azure {
587
            tenant_id: "t".into(),
588
            client_id: "c".into(),
589
            client_secret: "s3cr3t".into(),
590
        };
591
        assert_eq!(Credentials::from_json(&az.to_json()).unwrap(), az);
592
        assert!(!format!("{az:?}").contains("s3cr3t"));
593
        let key = r#"{"type":"service_account","client_email":"x@y","private_key":"k"}"#;
594
        let gcp = Credentials::Gcp {
595
            service_account_key: key.into(),
596
        };
597
        assert_eq!(Credentials::from_json(&gcp.to_json()).unwrap(), gcp);
598
        assert!(!format!("{gcp:?}").contains("private_key"));
599
        for (bad, why) in [
600
            (r#"{"kind":"aws","access_key_id":"a"}"#, "secret_access_key"),
601
            (
602
                r#"{"kind":"gcp","service_account_key":"{\"type\":\"authorized_user\"}"}"#,
603
                "not a service account key",
604
            ),
605
            (r#"{"kind":"ftp"}"#, "aws, gcp or azure"),
606
            ("nope", "not JSON"),
607
        ] {
608
            let e = Credentials::from_json(bad).unwrap_err().to_string();
609
            assert!(e.contains(why), "{bad}: {e}");
610
        }
611
        let e = CloudStore::open_with("gs://bucket/p", Some(&aws))
612
            .err()
613
            .unwrap()
614
            .to_string();
615
        assert!(e.contains("are for s3:// stores"), "{e}");
616
    }
617
8d803563 Andy McCall ↶ 618
    use super::*;
619
620
    #[test]
621
    fn urls_parse_with_their_parameters() {
622
        let u =
623
            StoreUrl::parse("s3://my-bucket/repos/oxygen?profile=work&region=eu-west-2").unwrap();
624
        assert_eq!(u.scheme, "s3");
625
        assert_eq!(u.host, "my-bucket");
626
        assert_eq!(u.path, "repos/oxygen");
627
        assert_eq!(u.param("profile"), Some("work"));
628
        assert_eq!(u.param("region"), Some("eu-west-2"));
629
        assert_eq!(u.plain(), "s3://my-bucket/repos/oxygen");
630
        let u = StoreUrl::parse("gs://bucket").unwrap();
631
        assert_eq!((u.host.as_str(), u.path.as_str()), ("bucket", ""));
632
        assert_eq!(u.plain(), "gs://bucket");
633
        let u = StoreUrl::parse("az://acct/container/a/b/?endpoint=http%3A%2F%2F127.0.0.1%3A10000")
634
            .unwrap();
635
        assert_eq!(u.path, "container/a/b");
636
        assert_eq!(u.param("endpoint"), Some("http://127.0.0.1:10000"));
637
        assert!(StoreUrl::parse("s3://").is_err());
638
        assert!(StoreUrl::parse("nonsense").is_err());
639
    }
640
641
    #[test]
642
    fn versions_carry_both_an_etag_and_a_generation() {
643
        let v = CloudStore::version_of(Some("\"abc\"".into()), Some("17".into()));
644
        let u = CloudStore::update_version(&v);
645
        assert_eq!(u.e_tag.as_deref(), Some("\"abc\""));
646
        assert_eq!(u.version.as_deref(), Some("17"));
647
        let u = CloudStore::update_version(&CloudStore::version_of(None, Some("3".into())));
648
        assert_eq!((u.e_tag, u.version.as_deref()), (None, Some("3")));
649
    }
650
}