Skip to main content

ostrya_remote/s3/
address.rs

1//! The address of a bucket repository: `s3://BUCKET[/PREFIX]`.
2
3use std::fmt;
4use std::net::Ipv4Addr;
5use std::str::FromStr;
6
7use crate::{Error, Result};
8
9/// The scheme of an S3 address.
10const SCHEME: &str = "s3://";
11
12/// The address of a bucket repository: a bucket and a key prefix.
13///
14/// The form is `s3://BUCKET[/PREFIX]`.
15///
16/// - `BUCKET` is 3 to 63 characters: lowercase ASCII letters, digits, `.`,
17///   and `-`. It starts and ends with a letter or a digit. It holds no `..`,
18///   and it is not four decimal numbers that `.` separates, as an IPv4
19///   address is.
20/// - `PREFIX` is one or more segments that `/` separates. Each segment is
21///   not empty, is not `.` or `..`, and holds the characters `A-Z`, `a-z`,
22///   `0-9`, `-`, `.`, `_`, and `~` alone. One trailing `/` is dropped.
23/// - The address holds no userinfo, no port, no query, and no fragment.
24///
25/// The keys of the repository start with `PREFIX/`. With no prefix, they
26/// start at the root of the bucket and have no leading `/`.
27///
28/// The [`Display`](fmt::Display) output is the canonical form, with no
29/// trailing `/`.
30///
31/// # Examples
32///
33/// ```
34/// use ostrya_remote::s3::Address;
35/// # fn main() -> ostrya_remote::Result<()> {
36/// let address = Address::parse("s3://builds/exampleos/")?;
37/// assert_eq!(address.bucket(), "builds");
38/// assert_eq!(address.prefix(), "exampleos");
39/// assert_eq!(address.to_string(), "s3://builds/exampleos");
40/// assert!(Address::parse("s3://Builds").is_err());
41/// # Ok(()) }
42/// ```
43#[derive(Clone, Debug, PartialEq, Eq, Hash)]
44pub struct Address {
45    bucket: String,
46    prefix: String,
47}
48
49impl Address {
50    /// Parses `address` in the form `s3://BUCKET[/PREFIX]`.
51    ///
52    /// # Errors
53    ///
54    /// [`Error::InvalidInput`] if `address` does not have the form that
55    /// [`Address`] states. The message names the part that is refused. It
56    /// holds no userinfo.
57    pub fn parse(address: &str) -> Result<Address> {
58        let rest = address
59            .strip_prefix(SCHEME)
60            .ok_or_else(|| refused("an S3 address starts with s3://, in lowercase".to_owned()))?;
61        // Each of these characters is outside the alphabet of a bucket and
62        // of a prefix. The message names the part that the character starts.
63        for (found, part) in [
64            ('@', "userinfo"),
65            (':', "a port"),
66            ('?', "a query"),
67            ('#', "a fragment"),
68        ] {
69            if rest.contains(found) {
70                return Err(refused(format!(
71                    "an S3 address holds no {part}, and this one holds '{found}'"
72                )));
73            }
74        }
75        let (bucket, prefix) = rest.split_once('/').unwrap_or((rest, ""));
76        check_bucket(bucket)?;
77        let prefix = prefix.strip_suffix('/').unwrap_or(prefix);
78        if !prefix.is_empty() {
79            for segment in prefix.split('/') {
80                check_segment(segment)?;
81            }
82        }
83        Ok(Address {
84            bucket: bucket.to_owned(),
85            prefix: prefix.to_owned(),
86        })
87    }
88
89    /// Returns the name of the bucket.
90    pub fn bucket(&self) -> &str {
91        &self.bucket
92    }
93
94    /// Returns the prefix of the keys, with no leading `/` and no trailing
95    /// `/`. It is empty for an address with no prefix.
96    pub fn prefix(&self) -> &str {
97        &self.prefix
98    }
99}
100
101impl fmt::Display for Address {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        write!(f, "{SCHEME}{}", self.bucket)?;
104        if !self.prefix.is_empty() {
105            write!(f, "/{}", self.prefix)?;
106        }
107        Ok(())
108    }
109}
110
111impl FromStr for Address {
112    type Err = Error;
113
114    fn from_str(address: &str) -> Result<Address> {
115        Address::parse(address)
116    }
117}
118
119/// Returns the refusal of an address with `why`.
120fn refused(why: String) -> Error {
121    Error::InvalidInput(format!("S3 address: {why}"))
122}
123
124/// Checks the name of a bucket.
125fn check_bucket(bucket: &str) -> Result<()> {
126    if !(3..=63).contains(&bucket.len()) {
127        return Err(refused(format!(
128            "the bucket name {bucket:?} is not 3 to 63 characters long"
129        )));
130    }
131    if !bucket
132        .bytes()
133        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'-'))
134    {
135        return Err(refused(format!(
136            "the bucket name {bucket:?} holds a character other than a lowercase letter, a \
137             digit, '.', or '-'"
138        )));
139    }
140    let edge = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit());
141    if !edge(bucket.as_bytes().first()) || !edge(bucket.as_bytes().last()) {
142        return Err(refused(format!(
143            "the bucket name {bucket:?} does not start and end with a letter or a digit"
144        )));
145    }
146    if bucket.contains("..") {
147        return Err(refused(format!("the bucket name {bucket:?} holds '..'")));
148    }
149    if bucket.parse::<Ipv4Addr>().is_ok() {
150        return Err(refused(format!(
151            "the bucket name {bucket:?} has the form of an IPv4 address"
152        )));
153    }
154    Ok(())
155}
156
157/// Checks one segment of a prefix.
158fn check_segment(segment: &str) -> Result<()> {
159    if segment.is_empty() {
160        return Err(refused("the prefix holds an empty segment".to_owned()));
161    }
162    if segment == "." || segment == ".." {
163        return Err(refused(format!("the prefix holds the segment {segment:?}")));
164    }
165    if !segment
166        .bytes()
167        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~'))
168    {
169        return Err(refused(format!(
170            "the prefix segment {segment:?} holds a character other than A-Z, a-z, 0-9, '-', \
171             '.', '_', or '~'"
172        )));
173    }
174    Ok(())
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    fn parts(address: &str) -> (String, String) {
182        let address = Address::parse(address).unwrap_or_else(|e| panic!("{address}: {e}"));
183        (address.bucket().to_owned(), address.prefix().to_owned())
184    }
185
186    fn refusal(address: &str) -> String {
187        match Address::parse(address) {
188            Ok(parsed) => panic!("{address} parsed as {parsed:?}"),
189            Err(Error::InvalidInput(message)) => message,
190            Err(other) => panic!("{address}: {other}"),
191        }
192    }
193
194    #[test]
195    fn an_address_gives_its_bucket_and_prefix() {
196        let cases = [
197            ("s3://abc", "abc", ""),
198            ("s3://abc/", "abc", ""),
199            ("s3://a.b-c/p", "a.b-c", "p"),
200            ("s3://bucket/a/b/c/", "bucket", "a/b/c"),
201            ("s3://bucket/A-z_0.9~", "bucket", "A-z_0.9~"),
202            ("s3://0bucket9", "0bucket9", ""),
203            (
204                "s3://a23456789012345678901234567890123456789012345678901234567890123",
205                "a23456789012345678901234567890123456789012345678901234567890123",
206                "",
207            ),
208        ];
209        for (address, bucket, prefix) in cases {
210            assert_eq!(parts(address), (bucket.into(), prefix.into()), "{address}");
211        }
212    }
213
214    #[test]
215    fn a_bucket_name_out_of_the_rule_is_refused() {
216        for address in [
217            "s3://ab",
218            "s3://a234567890123456789012345678901234567890123456789012345678901234",
219            "s3://Bucket",
220            "s3://buck_et",
221            "s3://-bucket",
222            "s3://bucket-",
223            "s3://.bucket",
224            "s3://bucket.",
225            "s3://buc..ket",
226            "s3://192.168.1.10",
227            "s3://",
228            "s3:///prefix",
229        ] {
230            assert!(refusal(address).contains("bucket name"), "{address}");
231        }
232    }
233
234    #[test]
235    fn a_prefix_out_of_the_rule_is_refused() {
236        for address in [
237            "s3://bucket//p",
238            "s3://bucket/p//q",
239            "s3://bucket/p/./q",
240            "s3://bucket/..",
241            "s3://bucket/p q",
242            "s3://bucket/p+q",
243            "s3://bucket/p%41",
244            "s3://bucket/ΓΌ",
245            "s3://bucket/p//",
246        ] {
247            assert!(refusal(address).contains("prefix"), "{address}");
248        }
249    }
250
251    #[test]
252    fn userinfo_a_port_a_query_and_a_fragment_are_refused_by_name() {
253        let cases = [
254            ("s3://key:secret@bucket/p", "userinfo"),
255            ("s3://bucket:9000/p", "a port"),
256            ("s3://bucket/p?x=1", "a query"),
257            ("s3://bucket/p#f", "a fragment"),
258        ];
259        for (address, part) in cases {
260            let message = refusal(address);
261            assert!(message.contains(part), "{address}: {message}");
262            assert!(!message.contains("secret"), "{message}");
263        }
264    }
265
266    #[test]
267    fn another_scheme_is_refused() {
268        for address in ["S3://bucket", "s3:/bucket", "https://bucket", "bucket/p"] {
269            assert!(refusal(address).contains("s3://"), "{address}");
270        }
271    }
272
273    #[test]
274    fn the_display_is_the_canonical_form() {
275        for (address, shown) in [
276            ("s3://bucket", "s3://bucket"),
277            ("s3://bucket/", "s3://bucket"),
278            ("s3://bucket/a/b/", "s3://bucket/a/b"),
279        ] {
280            let parsed = Address::parse(address).unwrap();
281            assert_eq!(parsed.to_string(), shown);
282            assert_eq!(shown.parse::<Address>().unwrap(), parsed);
283        }
284    }
285}