Skip to main content

ostrya_remote/s3/
location.rs

1//! The endpoint, the region, and the addressing style of a bucket
2//! repository.
3
4use std::net::Ipv4Addr;
5
6use super::sigv4::{region_refusal, valid_region};
7use super::{Address, Addressing, Resolved};
8use crate::{Error, Result};
9
10/// The place of a bucket repository: its address, the region of the
11/// signature, the endpoint, and the addressing style.
12///
13/// [`Location::new`] applies these rules:
14///
15/// - With no endpoint, the endpoint is AWS: `https://s3.REGION.amazonaws.com`.
16/// - An endpoint is an `http://` or an `https://` URL with no path, no
17///   query, no fragment, and no userinfo. One trailing `/` is allowed.
18/// - Path style puts the bucket in the path: `ENDPOINT/BUCKET/PREFIX/...`.
19///   Virtual-host style puts the bucket in the host:
20///   `https://BUCKET.HOST/PREFIX/...`.
21/// - The default style is virtual-host for AWS, and path for an endpoint of
22///   the caller. A bucket name that holds a `.` gets path style by default.
23///   A style that the caller sets wins.
24/// - Virtual-host style is refused for a bucket name that holds a `.` over
25///   `https`, because the certificate of the endpoint does not match such a
26///   host. It is also refused for an endpoint whose host is an IP address.
27///
28/// An `http://` endpoint needs
29/// [`allow_cleartext_credentials`](ostrya_fetch::FetcherOptions::allow_cleartext_credentials)
30/// in the options of the bucket client, because the signature is a
31/// credential.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct Location {
34    address: Address,
35    region: String,
36    /// The endpoint in use, with no trailing `/`.
37    endpoint: String,
38    addressing: Addressing,
39}
40
41impl Location {
42    /// Returns the location of `address` with the region `region`, the
43    /// endpoint `endpoint`, and the addressing style `addressing`.
44    ///
45    /// `None` for `endpoint` is AWS, and `None` for `addressing` is the
46    /// default style. [`Location`] states the rules.
47    ///
48    /// # Errors
49    ///
50    /// [`Error::InvalidInput`] in these cases:
51    ///
52    /// - `region` is refused by [`SigV4::new`](super::SigV4::new)
53    /// - [`check_base_url`](ostrya_fetch::check_base_url) refuses `endpoint`,
54    ///   or `endpoint` has a path. The message holds no userinfo.
55    /// - virtual-host style with a bucket name that holds a `.` over `https`
56    /// - virtual-host style with an endpoint whose host is an IP address.
57    pub fn new(
58        address: Address,
59        region: &str,
60        endpoint: Option<&str>,
61        addressing: Option<Addressing>,
62    ) -> Result<Location> {
63        if !valid_region(region) {
64            return Err(Error::InvalidInput(region_refusal(region, "S3 location")));
65        }
66        let aws = endpoint.is_none();
67        let endpoint = match endpoint {
68            Some(endpoint) => checked_endpoint(endpoint)?,
69            None => format!("https://s3.{region}.amazonaws.com"),
70        };
71        let addressing = addressing.unwrap_or(if aws && !address.bucket().contains('.') {
72            Addressing::Virtual
73        } else {
74            Addressing::Path
75        });
76        let location = Location {
77            address,
78            region: region.to_owned(),
79            endpoint,
80            addressing,
81        };
82        if location.addressing == Addressing::Virtual {
83            location.check_virtual()?;
84        }
85        Ok(location)
86    }
87
88    /// Returns the location of `address` with the region, the endpoint, and
89    /// the addressing style of `resolved`.
90    ///
91    /// # Errors
92    ///
93    /// The errors of [`Location::new`]. A refused endpoint names the source
94    /// of the endpoint.
95    pub fn from_resolved(address: Address, resolved: &Resolved) -> Result<Location> {
96        let endpoint = resolved.endpoint.as_ref();
97        Location::new(
98            address,
99            &resolved.region.value,
100            endpoint.map(|endpoint| endpoint.value.as_str()),
101            resolved.addressing.as_ref().map(|style| style.value),
102        )
103        .map_err(|e| match (e, endpoint) {
104            (Error::InvalidInput(message), Some(endpoint)) if message.contains("endpoint") => {
105                Error::InvalidInput(format!("{message} (from {})", endpoint.origin))
106            }
107            (e, _) => e,
108        })
109    }
110
111    /// Returns the address of the bucket repository.
112    pub fn address(&self) -> &Address {
113        &self.address
114    }
115
116    /// Returns the region of the signature.
117    pub fn region(&self) -> &str {
118        &self.region
119    }
120
121    /// Returns the addressing style in use.
122    pub fn addressing(&self) -> Addressing {
123        self.addressing
124    }
125
126    /// Returns the endpoint in use, with no trailing `/`: the endpoint of the
127    /// caller, or `https://s3.REGION.amazonaws.com`.
128    pub fn endpoint(&self) -> &str {
129        &self.endpoint
130    }
131
132    /// Returns the URL of the bucket: `ENDPOINT/BUCKET` for path style, and
133    /// `SCHEME://BUCKET.HOST[:PORT]` for virtual-host style.
134    ///
135    /// The bucket client sends each request under this URL.
136    pub fn bucket_url(&self) -> String {
137        let bucket = self.address.bucket();
138        match self.addressing {
139            Addressing::Path => format!("{}/{bucket}", self.endpoint),
140            Addressing::Virtual => {
141                let (scheme, authority) = split_scheme(&self.endpoint);
142                format!("{scheme}://{bucket}.{authority}")
143            }
144        }
145    }
146
147    /// Returns the base URL of the repository: the URL of the bucket, then
148    /// `/` and the prefix if the address has one.
149    pub fn repository_url(&self) -> String {
150        let prefix = self.address.prefix();
151        if prefix.is_empty() {
152            self.bucket_url()
153        } else {
154            format!("{}/{prefix}", self.bucket_url())
155        }
156    }
157
158    /// Refuses virtual-host style where the host of the bucket cannot carry
159    /// it.
160    fn check_virtual(&self) -> Result<()> {
161        let (scheme, authority) = split_scheme(&self.endpoint);
162        if scheme.eq_ignore_ascii_case("https") && self.address.bucket().contains('.') {
163            return Err(Error::InvalidInput(format!(
164                "S3 location: the bucket name {:?} holds a '.', so virtual-host style over \
165                 https names a host that the certificate of the endpoint does not match: use \
166                 path style",
167                self.address.bucket()
168            )));
169        }
170        let host = match authority.rfind(':') {
171            Some(at) if !authority.ends_with(']') => &authority[..at],
172            _ => authority,
173        };
174        if host.starts_with('[') || host.parse::<Ipv4Addr>().is_ok() {
175            return Err(Error::InvalidInput(format!(
176                "S3 location: the endpoint host {host} is an IP address, so it cannot carry the \
177                 bucket name in virtual-host style: use path style"
178            )));
179        }
180        Ok(())
181    }
182}
183
184/// Checks the endpoint URL `endpoint` and returns it with no trailing `/`.
185fn checked_endpoint(endpoint: &str) -> Result<String> {
186    ostrya_fetch::check_base_url(endpoint)
187        .map_err(|e| Error::InvalidInput(format!("S3 endpoint: {e}")))?;
188    let (_, rest) = endpoint
189        .split_once("://")
190        .expect("a checked base URL has a scheme");
191    let path = rest.find('/').map_or("", |at| &rest[at..]);
192    if !path.is_empty() && path != "/" {
193        return Err(Error::InvalidInput(format!(
194            "S3 endpoint: the endpoint {endpoint} has the path {path}: an endpoint has no path"
195        )));
196    }
197    Ok(endpoint.strip_suffix('/').unwrap_or(endpoint).to_owned())
198}
199
200/// Splits `url` into its scheme and the rest after `://`.
201fn split_scheme(url: &str) -> (&str, &str) {
202    url.split_once("://").unwrap_or(("https", url))
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    fn location(
210        address: &str,
211        endpoint: Option<&str>,
212        addressing: Option<Addressing>,
213    ) -> Result<Location> {
214        Location::new(
215            Address::parse(address).unwrap(),
216            "eu-central-1",
217            endpoint,
218            addressing,
219        )
220    }
221
222    fn refusal(address: &str, endpoint: Option<&str>, addressing: Option<Addressing>) -> String {
223        match location(address, endpoint, addressing) {
224            Ok(found) => panic!("{address} {endpoint:?}: {found:?}"),
225            Err(Error::InvalidInput(message)) => message,
226            Err(other) => panic!("{other}"),
227        }
228    }
229
230    #[test]
231    fn aws_is_the_endpoint_when_none_is_set() {
232        let aws = location("s3://bucket/repo", None, None).unwrap();
233        assert_eq!(aws.endpoint(), "https://s3.eu-central-1.amazonaws.com");
234        assert_eq!(aws.addressing(), Addressing::Virtual);
235        assert_eq!(
236            aws.bucket_url(),
237            "https://bucket.s3.eu-central-1.amazonaws.com"
238        );
239        assert_eq!(
240            aws.repository_url(),
241            "https://bucket.s3.eu-central-1.amazonaws.com/repo"
242        );
243
244        let path = location("s3://bucket/repo", None, Some(Addressing::Path)).unwrap();
245        assert_eq!(
246            path.bucket_url(),
247            "https://s3.eu-central-1.amazonaws.com/bucket"
248        );
249        assert_eq!(
250            path.repository_url(),
251            "https://s3.eu-central-1.amazonaws.com/bucket/repo"
252        );
253    }
254
255    #[test]
256    fn the_default_style_follows_the_endpoint_and_the_bucket_name() {
257        let cases = [
258            ("s3://bucket", None, None, Addressing::Virtual),
259            ("s3://my.bucket", None, None, Addressing::Path),
260            (
261                "s3://bucket",
262                Some("http://127.0.0.1:9000"),
263                None,
264                Addressing::Path,
265            ),
266            (
267                "s3://bucket",
268                Some("https://s3.example.com/"),
269                None,
270                Addressing::Path,
271            ),
272            (
273                "s3://bucket",
274                Some("https://s3.example.com"),
275                Some(Addressing::Virtual),
276                Addressing::Virtual,
277            ),
278            (
279                "s3://bucket",
280                None,
281                Some(Addressing::Path),
282                Addressing::Path,
283            ),
284            (
285                "s3://my.bucket",
286                Some("http://s3.example.com"),
287                Some(Addressing::Virtual),
288                Addressing::Virtual,
289            ),
290        ];
291        for (address, endpoint, set, style) in cases {
292            let found = location(address, endpoint, set).unwrap();
293            assert_eq!(found.addressing(), style, "{address} {endpoint:?} {set:?}");
294        }
295    }
296
297    #[test]
298    fn the_urls_of_an_endpoint_of_the_caller() {
299        let path = location("s3://b-1", Some("http://127.0.0.1:9000/"), None).unwrap();
300        assert_eq!(path.endpoint(), "http://127.0.0.1:9000");
301        assert_eq!(path.bucket_url(), "http://127.0.0.1:9000/b-1");
302        assert_eq!(path.repository_url(), "http://127.0.0.1:9000/b-1");
303
304        let virtual_host = location(
305            "s3://b-1/a/b",
306            Some("https://s3.example.com:8443"),
307            Some(Addressing::Virtual),
308        )
309        .unwrap();
310        assert_eq!(virtual_host.bucket_url(), "https://b-1.s3.example.com:8443");
311        assert_eq!(
312            virtual_host.repository_url(),
313            "https://b-1.s3.example.com:8443/a/b"
314        );
315    }
316
317    #[test]
318    fn an_endpoint_out_of_the_rule_is_refused() {
319        for endpoint in [
320            "ftp://s3.example.com",
321            "https://s3.example.com/path",
322            "https://s3.example.com/?x=1",
323            "https://key:secret@s3.example.com",
324            "https://s3.example.com/#f",
325            "https://",
326            "s3.example.com",
327        ] {
328            let message = refusal("s3://bucket", Some(endpoint), None);
329            assert!(message.contains("S3 endpoint"), "{endpoint}: {message}");
330            assert!(!message.contains("secret"), "{message}");
331        }
332    }
333
334    #[test]
335    fn virtual_host_style_is_refused_where_the_host_cannot_carry_it() {
336        let dotted = refusal(
337            "s3://my.bucket",
338            Some("https://s3.example.com"),
339            Some(Addressing::Virtual),
340        );
341        assert!(dotted.contains("certificate"), "{dotted}");
342        let dotted_aws = refusal("s3://my.bucket", None, Some(Addressing::Virtual));
343        assert!(dotted_aws.contains("certificate"), "{dotted_aws}");
344        for endpoint in [
345            "http://127.0.0.1:9000",
346            "http://[::1]:9000",
347            "http://10.0.0.1",
348        ] {
349            let message = refusal("s3://bucket", Some(endpoint), Some(Addressing::Virtual));
350            assert!(message.contains("IP address"), "{endpoint}: {message}");
351        }
352    }
353
354    #[test]
355    fn a_region_out_of_the_rule_is_refused() {
356        let address = Address::parse("s3://bucket").unwrap();
357        for region in ["", "eu central", "eu/central"] {
358            let err = Location::new(address.clone(), region, None, None).unwrap_err();
359            assert!(matches!(err, Error::InvalidInput(_)), "{err}");
360        }
361    }
362}