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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
use async_trait::async_trait;
use shuttle_service::{
    error::{CustomError, Error as ShuttleError},
    Factory, ResourceBuilder,
};
use std::{
    fs::rename,
    path::{Path, PathBuf},
};
use tokio::runtime::Runtime;

pub struct StaticFolder<'a> {
    /// The folder to reach at runtime. Defaults to `static`
    folder: &'a str,
}

pub enum Error {
    AbsolutePath,
    TransversedUp,
}

impl<'a> StaticFolder<'a> {
    pub fn folder(mut self, folder: &'a str) -> Self {
        self.folder = folder;

        self
    }
}

#[async_trait]
impl<'a> ResourceBuilder<PathBuf> for StaticFolder<'a> {
    fn new() -> Self {
        Self { folder: "static" }
    }

    async fn build(
        self,
        factory: &mut dyn Factory,
        _runtime: &Runtime,
    ) -> Result<PathBuf, shuttle_service::Error> {
        let folder = Path::new(self.folder);

        // Prevent users from users from reading anything outside of their crate's build folder
        if folder.is_absolute() {
            return Err(Error::AbsolutePath)?;
        }

        let input_dir = factory.get_build_path()?.join(self.folder);

        match input_dir.canonicalize() {
            Ok(canonical_path) if canonical_path != input_dir => return Err(Error::TransversedUp)?,
            Ok(_) => {
                // The path did not change to outside the crate's build folder
            }
            Err(err) => return Err(err)?,
        }

        let output_dir = factory.get_storage_path()?.join(self.folder);

        rename(input_dir, output_dir.clone())?;

        Ok(output_dir)
    }
}

impl From<Error> for shuttle_service::Error {
    fn from(error: Error) -> Self {
        let msg = match error {
            Error::AbsolutePath => "Cannot use an absolute path for a static folder",
            Error::TransversedUp => "Cannot transverse out of crate for a static folder",
        };

        ShuttleError::Custom(CustomError::msg(msg))
    }
}

#[cfg(test)]
mod tests {
    use std::fs::{self};
    use std::path::PathBuf;

    use async_trait::async_trait;
    use shuttle_service::{Factory, ResourceBuilder};
    use tempdir::TempDir;

    use crate::StaticFolder;

    struct MockFactory {
        temp_dir: TempDir,
    }

    // Will have this tree across all the tests
    // .
    // ├── build
    // │   └── static
    // │       └── note.txt
    // ├── storage
    // │   └── static
    // │       └── note.txt
    // └── escape
    //     └── passwd
    impl MockFactory {
        fn new() -> Self {
            Self {
                temp_dir: TempDir::new("static_folder").unwrap(),
            }
        }

        fn build_path(&self) -> PathBuf {
            self.get_path("build")
        }

        fn storage_path(&self) -> PathBuf {
            self.get_path("storage")
        }

        fn escape_path(&self) -> PathBuf {
            self.get_path("escape")
        }

        fn get_path(&self, folder: &str) -> PathBuf {
            let path = self.temp_dir.path().join(folder);

            if !path.exists() {
                fs::create_dir(&path).unwrap();
            }

            path
        }
    }

    #[async_trait]
    impl Factory for MockFactory {
        async fn get_db_connection_string(
            &mut self,
            _db_type: shuttle_service::database::Type,
        ) -> Result<String, shuttle_service::Error> {
            panic!("no static folder test should try to get a db connection string")
        }

        async fn get_secrets(
            &mut self,
        ) -> Result<std::collections::BTreeMap<String, String>, shuttle_service::Error> {
            panic!("no static folder test should try to get secrets")
        }

        fn get_service_name(&self) -> shuttle_service::ServiceName {
            panic!("no static folder test should try to get the service name")
        }

        fn get_build_path(&self) -> Result<std::path::PathBuf, shuttle_service::Error> {
            Ok(self.build_path())
        }

        fn get_storage_path(&self) -> Result<std::path::PathBuf, shuttle_service::Error> {
            Ok(self.storage_path())
        }
    }

    #[tokio::test]
    async fn copies_folder() {
        let mut factory = MockFactory::new();

        let input_file_path = factory.build_path().join("static").join("note.txt");
        fs::create_dir_all(input_file_path.parent().unwrap()).unwrap();
        fs::write(input_file_path, "Hello, test!").unwrap();

        let expected_file = factory.storage_path().join("static").join("note.txt");
        assert!(!expected_file.exists(), "input file should not exist yet");

        // Call plugin
        let static_folder = StaticFolder::new();

        let runtime = tokio::runtime::Runtime::new().unwrap();
        let actual_folder = static_folder.build(&mut factory, &runtime).await.unwrap();

        assert_eq!(
            actual_folder,
            factory.storage_path().join("static"),
            "expect path to the static folder"
        );
        assert!(expected_file.exists(), "expected input file to be created");
        assert_eq!(
            fs::read_to_string(expected_file).unwrap(),
            "Hello, test!",
            "expected file content to match"
        );

        runtime.shutdown_background();
    }

    #[tokio::test]
    #[should_panic(expected = "Cannot use an absolute path for a static folder")]
    async fn cannot_use_absolute_path() {
        let mut factory = MockFactory::new();
        let static_folder = StaticFolder::new();
        let runtime = tokio::runtime::Runtime::new().unwrap();

        let _ = static_folder
            .folder("/etc")
            .build(&mut factory, &runtime)
            .await
            .unwrap();

        runtime.shutdown_background();
    }

    #[tokio::test]
    #[should_panic(expected = "Cannot transverse out of crate for a static folder")]
    async fn cannot_transverse_up() {
        let mut factory = MockFactory::new();

        let password_file_path = factory.escape_path().join("passwd");
        fs::create_dir_all(password_file_path.parent().unwrap()).unwrap();
        fs::write(password_file_path, "qwerty").unwrap();

        // Call plugin
        let static_folder = StaticFolder::new();

        let runtime = tokio::runtime::Runtime::new().unwrap();
        let _ = static_folder
            .folder("../escape")
            .build(&mut factory, &runtime)
            .await
            .unwrap();

        runtime.shutdown_background();
    }
}