Diffinery

homeflare/celldpublic

celld/crates/ltx/src/replica_url.rs
719 lines · 24.0 KBRaw History
1//! replica_url.rs — parse `s3://` and `file://` replica URLs + S3 endpoint
2//! detection helpers.
3//!
4//! Ported from [email protected] `replica_url.go`. Scope is the KEEP set (D-7):
5//! the pure URL-parsing and endpoint-detection functions for the **s3** and
6//! **file** schemes. The `RegisterReplicaClientFactory` registry and the
7//! `NewReplicaClientFromURL` *client construction* path are deferred to the
8//! client tasks (T5/T6/T7) — they cannot exist before the clients do — as are
9//! the dropped schemes (gs/abs/oss/sftp/webdav, PLAN.md §2).
10
11use crate::error::{Error, Result};
12
13fn url_err(msg: impl Into<String>) -> Error {
14 Error::Other(msg.into().into())
15}
16
17// ── Query (a tiny ordered multimap, like Go's url.Values) ─────────────────────
18
19/// Parsed query parameters. Mirrors `url.Values`: ordered, allows duplicate
20/// keys, and `get` returns the first value for a key.
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
22pub struct Query(Vec<(String, String)>);
23
24impl Query {
25 pub fn is_empty(&self) -> bool {
26 self.0.is_empty()
27 }
28
29 /// First value for `key`, or `""` if absent (matches Go `url.Values.Get`).
30 pub fn get(&self, key: &str) -> &str {
31 self.0
32 .iter()
33 .find(|(k, _)| k == key)
34 .map(|(_, v)| v.as_str())
35 .unwrap_or("")
36 }
37
38 pub fn contains(&self, key: &str) -> bool {
39 self.0.iter().any(|(k, _)| k == key)
40 }
41}
42
43/// Parses an `a=b&c=d` query string with percent-decoding, like
44/// `url.ParseQuery`. `+` decodes to a space (form semantics).
45fn parse_query(s: &str) -> Query {
46 let mut out = Vec::new();
47 for pair in s.split('&') {
48 if pair.is_empty() {
49 continue;
50 }
51 let (k, v) = match pair.split_once('=') {
52 Some((k, v)) => (k, v),
53 None => (pair, ""),
54 };
55 out.push((percent_decode(k), percent_decode(v)));
56 }
57 Query(out)
58}
59
60/// Minimal `application/x-www-form-urlencoded` decode: `+` → space and
61/// `%XX` → byte. Invalid escapes are left verbatim (best effort).
62fn percent_decode(s: &str) -> String {
63 let bytes = s.as_bytes();
64 let mut out = Vec::with_capacity(bytes.len());
65 let mut i = 0;
66 while i < bytes.len() {
67 match bytes[i] {
68 b'+' => {
69 out.push(b' ');
70 i += 1;
71 }
72 b'%' if i + 2 < bytes.len() => {
73 let hi = (bytes[i + 1] as char).to_digit(16);
74 let lo = (bytes[i + 2] as char).to_digit(16);
75 if let (Some(h), Some(l)) = (hi, lo) {
76 out.push((h * 16 + l) as u8);
77 i += 3;
78 } else {
79 out.push(bytes[i]);
80 i += 1;
81 }
82 }
83 b => {
84 out.push(b);
85 i += 1;
86 }
87 }
88 }
89 String::from_utf8_lossy(&out).into_owned()
90}
91
92// ── Scheme + URL parsing ──────────────────────────────────────────────────────
93
94/// The fields parsed from a replica URL.
95#[derive(Debug, Clone, Default, PartialEq, Eq)]
96pub struct ParsedReplicaUrl {
97 pub scheme: String,
98 pub host: String,
99 pub path: String,
100 pub query: Query,
101 /// `user[:password]` userinfo, if present.
102 pub userinfo: Option<String>,
103}
104
105/// Extracts and lowercases the URL scheme (matching Go `net/url`, which
106/// lowercases schemes). Returns `("", s)` when there is no valid leading
107/// `scheme:` (e.g. `"invalid"`, `"relative/path"`).
108fn parse_scheme(s: &str) -> (String, &str) {
109 let bytes = s.as_bytes();
110 for (i, &c) in bytes.iter().enumerate() {
111 match c {
112 b'a'..=b'z' | b'A'..=b'Z' => {}
113 b'0'..=b'9' | b'+' | b'-' | b'.' if i > 0 => {}
114 b':' if i > 0 => return (s[..i].to_ascii_lowercase(), &s[i + 1..]),
115 _ => return (String::new(), s),
116 }
117 }
118 (String::new(), s)
119}
120
121/// Parses a replica URL into scheme/host/path/query/userinfo.
122///
123/// Ported from `ParseReplicaURLWithQuery` (replica_url.go:79-104). The
124/// `s3://arn:` Access-Point form is handled specially because a raw ARN is not
125/// a parseable authority.
126pub fn parse_replica_url_with_query(s: &str) -> Result<ParsedReplicaUrl> {
127 if s.to_ascii_lowercase().starts_with("s3://arn:") {
128 let (scheme, host, path, query) = parse_s3_access_point_url(s)?;
129 return Ok(ParsedReplicaUrl {
130 scheme,
131 host,
132 path,
133 query,
134 userinfo: None,
135 });
136 }
137
138 let (scheme, rest) = parse_scheme(s);
139 if scheme.is_empty() {
140 return Err(url_err(format!("replica url scheme required: {s}")));
141 }
142
143 if scheme == "file" {
144 // Go blanks the scheme + query and returns path.Clean(u.String()).
145 let no_query = rest.split('?').next().unwrap_or(rest);
146 let (_, host, path, _) = split_authority(no_query);
147 let reconstructed = if host.is_empty() {
148 path
149 } else {
150 format!("//{host}{path}")
151 };
152 return Ok(ParsedReplicaUrl {
153 scheme,
154 host: String::new(),
155 path: crate::path_clean(&reconstructed),
156 query: Query::default(),
157 userinfo: None,
158 });
159 }
160
161 // Default (s3, …): scheme://[userinfo@]host[/path][?query].
162 let (q_str, before_q) = match rest.split_once('?') {
163 Some((a, b)) => (Some(b), a),
164 None => (None, rest),
165 };
166 let (userinfo, host, path, _) = split_authority(before_q);
167 let query = q_str.map(parse_query).unwrap_or_default();
168 Ok(ParsedReplicaUrl {
169 scheme,
170 host,
171 // strings.TrimPrefix(path.Clean(u.Path), "/")
172 path: crate::path_clean(&path)
173 .strip_prefix('/')
174 .map(str::to_string)
175 .unwrap_or_else(|| crate::path_clean(&path)),
176 query,
177 userinfo,
178 })
179}
180
181/// Splits a post-scheme remainder of the form `//[user@]host[/path]` into
182/// `(userinfo, host, path)`. The leading `//` is optional/tolerated; `path`
183/// keeps its leading slash. `query` is always returned empty here (callers
184/// split it off first).
185fn split_authority(rest: &str) -> (Option<String>, String, String, Query) {
186 let r = rest.strip_prefix("//").unwrap_or(rest);
187 let (authority, path) = match r.find('/') {
188 Some(i) => (&r[..i], &r[i..]),
189 None => (r, ""),
190 };
191 let (userinfo, host) = match authority.rfind('@') {
192 Some(i) => (Some(authority[..i].to_string()), &authority[i + 1..]),
193 None => (None, authority),
194 };
195 (
196 userinfo,
197 host.to_string(),
198 path.to_string(),
199 Query::default(),
200 )
201}
202
203/// Parses a replica URL into scheme/host/path (no query/userinfo).
204///
205/// Ported from `ParseReplicaURL` (replica_url.go:68-76).
206pub fn parse_replica_url(s: &str) -> Result<(String, String, String)> {
207 let p = parse_replica_url_with_query(s)?;
208 Ok((p.scheme, p.host, p.path))
209}
210
211/// Returns the replica backend type from a URL (`""` if no scheme).
212/// `webdavs` normalizes to `webdav`. Ported from replica_url.go:56-65.
213pub fn replica_type_from_url(s: &str) -> String {
214 let (scheme, _) = parse_scheme(s);
215 if scheme.is_empty() {
216 return String::new();
217 }
218 if scheme == "webdavs" {
219 return "webdav".to_string();
220 }
221 scheme
222}
223
224/// `true` if `s` looks like a URL (`^\w+://`). Ported from replica_url.go:364-369.
225pub fn is_url(s: &str) -> bool {
226 if let Some(idx) = s.find("://") {
227 idx > 0
228 && s[..idx]
229 .bytes()
230 .all(|b| b.is_ascii_alphanumeric() || b == b'_')
231 } else {
232 false
233 }
234}
235
236// ── S3 Access Point ARN parsing ───────────────────────────────────────────────
237
238/// Parses an `s3://arn:…:accesspoint/<name>[/key]` URL.
239/// Ported from `parseS3AccessPointURL` (replica_url.go:107-136).
240fn parse_s3_access_point_url(s: &str) -> Result<(String, String, String, Query)> {
241 const PREFIX: &str = "s3://";
242 if !s.to_ascii_lowercase().starts_with(PREFIX) {
243 return Err(url_err(format!("invalid s3 access point url: {s}")));
244 }
245 let arn_with_path = &s[PREFIX.len()..];
246
247 let (arn_with_path, query_str) = match arn_with_path.find('?') {
248 Some(idx) => (&arn_with_path[..idx], Some(&arn_with_path[idx + 1..])),
249 None => (arn_with_path, None),
250 };
251
252 let (bucket, key) = split_s3_access_point_arn(arn_with_path)?;
253 let query = query_str.map(parse_query).unwrap_or_default();
254 Ok((
255 "s3".to_string(),
256 bucket,
257 clean_replica_url_path(&key),
258 query,
259 ))
260}
261
262/// Splits an S3 Access Point ARN into `(bucket, key)`.
263/// Ported from `splitS3AccessPointARN` (replica_url.go:139-162).
264fn split_s3_access_point_arn(s: &str) -> Result<(String, String)> {
265 const MARKER: &str = ":accesspoint/";
266 let lower = s.to_ascii_lowercase();
267 let idx = lower
268 .find(MARKER)
269 .ok_or_else(|| url_err(format!("invalid s3 access point arn: {s}")))?;
270 let name_start = idx + MARKER.len();
271 if name_start >= s.len() {
272 return Err(url_err(format!("invalid s3 access point arn: {s}")));
273 }
274 let remainder = &s[name_start..];
275 match remainder.find('/') {
276 None => Ok((s.to_string(), String::new())),
277 Some(slash_idx) => {
278 let bucket_end = name_start + slash_idx;
279 Ok((
280 s[..bucket_end].to_string(),
281 remainder[slash_idx + 1..].to_string(),
282 ))
283 }
284 }
285}
286
287/// Cleans a URL path for replica storage. Ported from replica_url.go:165-175.
288pub fn clean_replica_url_path(p: &str) -> String {
289 if p.is_empty() {
290 return String::new();
291 }
292 let cleaned = crate::path_clean(&format!("/{p}"));
293 let cleaned = cleaned.strip_prefix('/').unwrap_or(&cleaned);
294 if cleaned == "." {
295 return String::new();
296 }
297 cleaned.to_string()
298}
299
300/// Extracts the region from an S3 ARN (`arn:aws:s3:<region>:…`).
301/// Ported from replica_url.go:178-184.
302pub fn region_from_s3_arn(arn: &str) -> String {
303 let parts: Vec<&str> = arn.splitn(6, ':').collect();
304 if parts.len() >= 4 {
305 parts[3].to_string()
306 } else {
307 String::new()
308 }
309}
310
311/// Reads a boolean from query params, checking `keys` in order. Returns `None`
312/// when no key is set (Go's `ok == false`); an unrecognized value yields
313/// `Some(false)`. Ported from `BoolQueryValue` (replica_url.go:188-205).
314pub fn bool_query_value(query: Option<&Query>, keys: &[&str]) -> Option<bool> {
315 let query = query?;
316 for key in keys {
317 let raw = query.get(key);
318 if !raw.is_empty() {
319 return Some(matches!(
320 raw.to_ascii_lowercase().as_str(),
321 "true" | "1" | "t" | "yes"
322 ));
323 }
324 }
325 None
326}
327
328// ── Endpoint detection (S3 provider/local heuristics) ─────────────────────────
329
330/// Extracts the host from an endpoint URL, or returns it as-is.
331/// Ported from `extractEndpointHost` (replica_url.go:351-362).
332fn extract_endpoint_host(endpoint: &str) -> String {
333 let endpoint = endpoint.trim().to_ascii_lowercase();
334 if endpoint.is_empty() {
335 return String::new();
336 }
337 for scheme in ["http://", "https://"] {
338 if let Some(rest) = endpoint.strip_prefix(scheme) {
339 let host = rest.split('/').next().unwrap_or(rest);
340 if !host.is_empty() {
341 return host.to_string();
342 }
343 return endpoint;
344 }
345 }
346 endpoint
347}
348
349fn host_has_suffix(endpoint: &str, suffix: &str) -> bool {
350 let host = extract_endpoint_host(endpoint);
351 !host.is_empty() && host.ends_with(suffix)
352}
353
354pub fn is_tigris_endpoint(endpoint: &str) -> bool {
355 let host = extract_endpoint_host(endpoint);
356 host == "fly.storage.tigris.dev" || host == "t3.storage.dev"
357}
358pub fn is_hetzner_endpoint(endpoint: &str) -> bool {
359 host_has_suffix(endpoint, ".your-objectstorage.com")
360}
361pub fn is_digitalocean_endpoint(endpoint: &str) -> bool {
362 host_has_suffix(endpoint, ".digitaloceanspaces.com")
363}
364pub fn is_backblaze_endpoint(endpoint: &str) -> bool {
365 host_has_suffix(endpoint, ".backblazeb2.com")
366}
367pub fn is_filebase_endpoint(endpoint: &str) -> bool {
368 extract_endpoint_host(endpoint) == "s3.filebase.com"
369}
370pub fn is_scaleway_endpoint(endpoint: &str) -> bool {
371 host_has_suffix(endpoint, ".scw.cloud")
372}
373pub fn is_cloudflare_r2_endpoint(endpoint: &str) -> bool {
374 host_has_suffix(endpoint, ".r2.cloudflarestorage.com")
375}
376pub fn is_supabase_endpoint(endpoint: &str) -> bool {
377 host_has_suffix(endpoint, ".supabase.co")
378}
379
380/// `true` if the endpoint looks like MinIO (a custom `host:port` that is not a
381/// known cloud). Ported from `IsMinIOEndpoint` (replica_url.go:278-301).
382pub fn is_minio_endpoint(endpoint: &str) -> bool {
383 let host = extract_endpoint_host(endpoint);
384 if host.is_empty() || !host.contains(':') {
385 return false;
386 }
387 const KNOWN: [&str; 9] = [
388 ".amazonaws.com",
389 ".digitaloceanspaces.com",
390 ".backblazeb2.com",
391 ".filebase.com",
392 ".scw.cloud",
393 ".r2.cloudflarestorage.com",
394 "tigris.dev",
395 "t3.storage.dev",
396 ".supabase.co",
397 ];
398 !KNOWN.iter().any(|k| host.contains(k))
399}
400
401/// `true` for localhost / loopback / RFC1918 / `.local` endpoints.
402/// Ported from `IsLocalEndpoint` (replica_url.go:306-329).
403pub fn is_local_endpoint(endpoint: &str) -> bool {
404 let mut host = extract_endpoint_host(endpoint);
405 if host.is_empty() {
406 return false;
407 }
408 if let Some(idx) = host.rfind(':') {
409 host = host[..idx].to_string();
410 }
411 host == "localhost"
412 || host == "127.0.0.1"
413 || host.starts_with("192.168.")
414 || host.starts_with("10.")
415 || host.starts_with("172.16.")
416 || host.starts_with("172.17.")
417 || host.starts_with("172.18.")
418 || host.starts_with("172.19.")
419 || host.starts_with("172.2")
420 || host.starts_with("172.30.")
421 || host.starts_with("172.31.")
422 || host.ends_with(".local")
423 || host.ends_with(".localhost")
424}
425
426/// Ensures an endpoint has an http(s) scheme: local → `http://`, else
427/// `https://`. Returns `(endpoint, scheme_was_added)`.
428/// Ported from `EnsureEndpointScheme` (replica_url.go:335-347).
429pub fn ensure_endpoint_scheme(endpoint: &str) -> (String, bool) {
430 if endpoint.is_empty() {
431 return (String::new(), false);
432 }
433 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
434 return (endpoint.to_string(), false);
435 }
436 if is_local_endpoint(endpoint) {
437 (format!("http://{endpoint}"), true)
438 } else {
439 (format!("https://{endpoint}"), true)
440 }
441}
442
443// ── Tests (ported tables from replica_url_test.go) ────────────────────────────
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448
449 #[test]
450 fn replica_type_from_url() {
451 for (url, want) in [
452 ("s3://bucket/path", "s3"),
453 ("gs://bucket/path", "gs"),
454 ("abs://container/path", "abs"),
455 ("file:///path/to/replica", "file"),
456 ("sftp://host/path", "sftp"),
457 ("webdav://host/path", "webdav"),
458 ("webdavs://host/path", "webdav"),
459 ("nats://host/bucket", "nats"),
460 ("oss://bucket/path", "oss"),
461 ("", ""),
462 ("invalid", ""),
463 ] {
464 assert_eq!(super::replica_type_from_url(url), want, "url={url:?}");
465 }
466 }
467
468 #[test]
469 fn is_url() {
470 for (s, want) in [
471 ("s3://bucket/path", true),
472 ("file:///path", true),
473 ("https://example.com", true),
474 ("/path/to/file", false),
475 ("relative/path", false),
476 ("", false),
477 ] {
478 assert_eq!(super::is_url(s), want, "s={s:?}");
479 }
480 }
481
482 #[test]
483 fn parse_s3_and_file_scheme_host_path() {
484 let p = parse_replica_url_with_query("s3://bucket/path/to/db").unwrap();
485 assert_eq!(p.scheme, "s3");
486 assert_eq!(p.host, "bucket");
487 assert_eq!(p.path, "path/to/db");
488
489 let p = parse_replica_url_with_query("s3://bucket/path?region=us-east-1").unwrap();
490 assert_eq!(p.host, "bucket");
491 assert_eq!(p.path, "path");
492 assert_eq!(p.query.get("region"), "us-east-1");
493
494 let p = parse_replica_url_with_query("s3://user:secret@bucket/p").unwrap();
495 assert_eq!(p.host, "bucket");
496 assert_eq!(p.userinfo.as_deref(), Some("user:secret"));
497
498 let p = parse_replica_url_with_query("file:///var/lib/state.db").unwrap();
499 assert_eq!(p.scheme, "file");
500 assert_eq!(p.host, "");
501 assert_eq!(p.path, "/var/lib/state.db");
502
503 assert!(parse_replica_url_with_query("invalid").is_err());
504 }
505
506 #[test]
507 fn bool_query_value() {
508 for v in ["true", "True", "TRUE", "1", "t", "yes"] {
509 let q = parse_query(&format!("key={v}"));
510 assert_eq!(
511 super::bool_query_value(Some(&q), &["key"]),
512 Some(true),
513 "v={v}"
514 );
515 }
516 for v in ["false", "False", "FALSE", "0", "f", "no"] {
517 let q = parse_query(&format!("key={v}"));
518 assert_eq!(
519 super::bool_query_value(Some(&q), &["key"]),
520 Some(false),
521 "v={v}"
522 );
523 }
524 // missing key → None (not ok)
525 let q = parse_query("other=true");
526 assert_eq!(super::bool_query_value(Some(&q), &["key"]), None);
527 // multiple keys → finds the second
528 let q = parse_query("key2=true");
529 assert_eq!(
530 super::bool_query_value(Some(&q), &["key1", "key2"]),
531 Some(true)
532 );
533 // nil query → None
534 assert_eq!(super::bool_query_value(None, &["key"]), None);
535 // invalid value → Some(false) (ok, but not true)
536 let q = parse_query("key=invalid");
537 assert_eq!(super::bool_query_value(Some(&q), &["key"]), Some(false));
538 }
539
540 #[test]
541 fn region_from_s3_arn() {
542 for (arn, want) in [
543 (
544 "arn:aws:s3:us-east-1:123456789012:accesspoint/db-access",
545 "us-east-1",
546 ),
547 (
548 "arn:aws:s3:eu-west-1:123456789012:accesspoint/db-access",
549 "eu-west-1",
550 ),
551 (
552 "arn:aws:s3:ap-southeast-2:123456789012:accesspoint/db-access",
553 "ap-southeast-2",
554 ),
555 ("arn:aws:s3::123456789012:accesspoint/db-access", ""),
556 ("invalid-arn", ""),
557 ("", ""),
558 ("arn:aws:s3", ""),
559 ] {
560 assert_eq!(super::region_from_s3_arn(arn), want, "arn={arn:?}");
561 }
562 }
563
564 #[test]
565 fn clean_replica_url_path() {
566 for (p, want) in [
567 ("", ""),
568 ("path", "path"),
569 ("/path", "path"),
570 ("path/", "path"),
571 ("/path/", "path"),
572 ("path/to/db", "path/to/db"),
573 ("/path/to/db", "path/to/db"),
574 ("//path//to//db", "path/to/db"),
575 (".", ""),
576 ("/.", ""),
577 ("./path", "path"),
578 ] {
579 assert_eq!(super::clean_replica_url_path(p), want, "p={p:?}");
580 }
581 }
582
583 #[test]
584 fn parse_s3_access_point_url() {
585 let p = parse_replica_url_with_query(
586 "s3://arn:aws:s3:us-east-1:123456789012:accesspoint/my-access-point",
587 )
588 .unwrap();
589 assert_eq!(p.scheme, "s3");
590 assert_eq!(
591 p.host,
592 "arn:aws:s3:us-east-1:123456789012:accesspoint/my-access-point"
593 );
594 assert_eq!(p.path, "");
595 assert!(p.query.is_empty());
596
597 let p = parse_replica_url_with_query(
598 "s3://arn:aws:s3:us-east-1:123456789012:accesspoint/my-access-point/backups/db",
599 )
600 .unwrap();
601 assert_eq!(
602 p.host,
603 "arn:aws:s3:us-east-1:123456789012:accesspoint/my-access-point"
604 );
605 assert_eq!(p.path, "backups/db");
606
607 let p = parse_replica_url_with_query(
608 "s3://arn:aws:s3:us-east-1:123456789012:accesspoint/my-access-point?sign-payload=false&region=us-west-2",
609 )
610 .unwrap();
611 assert_eq!(p.query.get("sign-payload"), "false");
612 assert_eq!(p.query.get("region"), "us-west-2");
613
614 // Case-insensitive scheme.
615 let p = parse_replica_url_with_query(
616 "S3://arn:aws:s3:us-east-1:123456789012:accesspoint/my-access-point",
617 )
618 .unwrap();
619 assert_eq!(p.scheme, "s3");
620
621 // Path + query together.
622 let p = parse_replica_url_with_query(
623 "s3://arn:aws:s3:us-east-1:123456789012:accesspoint/my-access-point/backups?sign-payload=true",
624 )
625 .unwrap();
626 assert_eq!(p.path, "backups");
627 assert_eq!(p.query.get("sign-payload"), "true");
628 }
629
630 #[test]
631 fn endpoint_detection() {
632 assert!(is_tigris_endpoint("fly.storage.tigris.dev"));
633 assert!(is_tigris_endpoint("HTTPS://T3.STORAGE.DEV"));
634 assert!(!is_tigris_endpoint("s3.amazonaws.com"));
635 assert!(is_digitalocean_endpoint(
636 "https://sfo3.digitaloceanspaces.com"
637 ));
638 assert!(is_backblaze_endpoint("s3.us-west-000.backblazeb2.com"));
639 assert!(is_filebase_endpoint("s3.filebase.com"));
640 assert!(is_scaleway_endpoint("s3.fr-par.scw.cloud"));
641 assert!(is_cloudflare_r2_endpoint("abcdef.r2.cloudflarestorage.com"));
642 assert!(is_supabase_endpoint("project.supabase.co"));
643 assert!(is_hetzner_endpoint("nbg1.your-objectstorage.com"));
644 }
645
646 #[test]
647 fn is_minio_endpoint() {
648 for (ep, want) in [
649 ("http://localhost:9000", true),
650 ("http://192.168.1.100:9000", true),
651 ("minio.local:9000", true),
652 ("https://s3.amazonaws.com", false),
653 ("https://s3.filebase.com", false),
654 ("https://sfo3.digitaloceanspaces.com", false),
655 ("s3.filebase.com", false),
656 ("", false),
657 ] {
658 assert_eq!(super::is_minio_endpoint(ep), want, "ep={ep:?}");
659 }
660 }
661
662 #[test]
663 fn is_local_endpoint() {
664 for (ep, want) in [
665 ("localhost", true),
666 ("localhost:9000", true),
667 ("http://localhost:9000", true),
668 ("127.0.0.1:9000", true),
669 ("192.168.1.100", true),
670 ("10.0.0.1:9000", true),
671 ("172.16.0.1", true),
672 ("172.31.255.255", true),
673 ("minio.local", true),
674 ("dev.localhost", true),
675 ("test.localhost:8080", true),
676 ("s3.amazonaws.com", false),
677 ("abcdef.r2.cloudflarestorage.com", false),
678 ("fly.storage.tigris.dev", false),
679 ("", false),
680 ] {
681 assert_eq!(super::is_local_endpoint(ep), want, "ep={ep:?}");
682 }
683 }
684
685 #[test]
686 fn ensure_endpoint_scheme() {
687 for (input, want, added) in [
688 ("https://example.com", "https://example.com", false),
689 ("http://localhost:9000", "http://localhost:9000", false),
690 ("localhost:9000", "http://localhost:9000", true),
691 ("127.0.0.1:9000", "http://127.0.0.1:9000", true),
692 ("192.168.1.100:9000", "http://192.168.1.100:9000", true),
693 ("minio.local:9000", "http://minio.local:9000", true),
694 (
695 "abcdef.r2.cloudflarestorage.com",
696 "https://abcdef.r2.cloudflarestorage.com",
697 true,
698 ),
699 (
700 "s3.us-west-000.backblazeb2.com",
701 "https://s3.us-west-000.backblazeb2.com",
702 true,
703 ),
704 (
705 "fly.storage.tigris.dev",
706 "https://fly.storage.tigris.dev",
707 true,
708 ),
709 ("s3.fr-par.scw.cloud", "https://s3.fr-par.scw.cloud", true),
710 ("", "", false),
711 ] {
712 assert_eq!(
713 super::ensure_endpoint_scheme(input),
714 (want.to_string(), added),
715 "input={input:?}"
716 );
717 }
718 }
719}