Welcome to mirror list, hosted at ThFree Co, Russian Federation.

s3url.rs « src « rusoto « net - gitlab.freedesktop.org/gstreamer/gst-plugins-rs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c059f96fb00526c1ee26a45ae576846e62543cb4 (plain)
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
// Copyright (C) 2017 Author: Arun Raghavan <arun@arunraghavan.net>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::str::FromStr;

use percent_encoding::{percent_decode, percent_encode, AsciiSet, CONTROLS};
use rusoto_core::Region;
use url::Url;

#[derive(Clone)]
pub struct GstS3Url {
    pub region: Region,
    pub bucket: String,
    pub object: String,
    pub version: Option<String>,
}

// FIXME: Copied from the url crate, see https://github.com/servo/rust-url/issues/529
// https://url.spec.whatwg.org/#fragment-percent-encode-set
const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
// https://url.spec.whatwg.org/#path-percent-encode-set
const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'%');

impl ToString for GstS3Url {
    fn to_string(&self) -> String {
        format!(
            "s3://{}/{}/{}{}",
            self.region.name(),
            self.bucket,
            percent_encode(self.object.as_bytes(), PATH_SEGMENT),
            if self.version.is_some() {
                format!("?version={}", self.version.clone().unwrap())
            } else {
                "".to_string()
            }
        )
    }
}

pub fn parse_s3_url(url_str: &str) -> Result<GstS3Url, String> {
    let url = Url::parse(url_str).map_err(|err| format!("Parse error: {}", err))?;

    if url.scheme() != "s3" {
        return Err(format!("Unsupported URI '{}'", url.scheme()));
    }

    if !url.has_host() {
        return Err(format!("Invalid host in uri '{}'", url));
    }

    let host = url.host_str().unwrap();
    let region = Region::from_str(host).map_err(|_| format!("Invalid region '{}'", host))?;

    let mut path = url
        .path_segments()
        .ok_or_else(|| format!("Invalid uri '{}'", url))?;

    let bucket = path.next().unwrap().to_string();

    let o = path
        .next()
        .ok_or_else(|| format!("Invalid empty object/bucket '{}'", url))?;

    let mut object = percent_decode(o.as_bytes())
        .decode_utf8()
        .unwrap()
        .to_string();
    if o.is_empty() {
        return Err(format!("Invalid empty object/bucket '{}'", url));
    }

    object = path.fold(object, |o, p| format!("{}/{}", o, p));

    let mut q = url.query_pairs();
    let v = q.next();
    let version;

    match v {
        Some((ref k, ref v)) if k == "version" => version = Some((*v).to_string()),
        None => version = None,
        Some(_) => return Err("Bad query, only 'version' is supported".to_owned()),
    }

    if q.next() != None {
        return Err("Extra query terms, only 'version' is supported".to_owned());
    }

    Ok(GstS3Url {
        region,
        bucket,
        object,
        version,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cannot_be_base() {
        assert!(parse_s3_url("data:something").is_err());
    }

    #[test]
    fn invalid_scheme() {
        assert!(parse_s3_url("file:///dev/zero").is_err());
    }

    #[test]
    fn bad_region() {
        assert!(parse_s3_url("s3://atlantis-1/i-hope-we/dont-find-this").is_err());
    }

    #[test]
    fn no_bucket() {
        assert!(parse_s3_url("s3://ap-south-1").is_err());
        assert!(parse_s3_url("s3://ap-south-1/").is_err());
    }

    #[test]
    fn no_object() {
        assert!(parse_s3_url("s3://ap-south-1/my-bucket").is_err());
        assert!(parse_s3_url("s3://ap-south-1/my-bucket/").is_err());
    }

    #[test]
    fn valid_simple() {
        assert!(parse_s3_url("s3://ap-south-1/my-bucket/my-object").is_ok());
    }

    #[test]
    fn extraneous_query() {
        assert!(parse_s3_url("s3://ap-south-1/my-bucket/my-object?foo=bar").is_err());
    }

    #[test]
    fn valid_version() {
        assert!(parse_s3_url("s3://ap-south-1/my-bucket/my-object?version=one").is_ok());
    }

    #[test]
    fn trailing_slash() {
        // Slashes are valid at the end of the object key
        assert_eq!(
            parse_s3_url("s3://ap-south-1/my-bucket/my-object/")
                .unwrap()
                .object,
            "my-object/"
        );
    }

    #[test]
    fn percent_encoding() {
        assert_eq!(
            parse_s3_url("s3://ap-south-1/my-bucket/my%20object")
                .unwrap()
                .object,
            "my object"
        );
    }

    #[test]
    fn percent_decoding() {
        assert_eq!(
            parse_s3_url("s3://ap-south-1/my-bucket/my object")
                .unwrap()
                .to_string(),
            "s3://ap-south-1/my-bucket/my%20object"
        );
    }
}