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
230
231
232
233
234
235
236
237
238
239
240
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::path::Path;
use std::sync::Arc;

use async_trait::async_trait;
use wildland_corex::dfs::interface::{DirEntry, FsStat, SpaceUsage};

use super::interface::EncryptionModule;
use crate::storage_backends::models::*;
use crate::storage_backends::StorageBackend;
use crate::{IStream, OStream, ProgressReporter, UnixTimestamp, WlPermissions};

pub struct EncryptStorageDriver {
    inner: Arc<dyn StorageBackend>,
    encryption_module: Arc<dyn EncryptionModule + Send + Sync>,
}

impl EncryptStorageDriver {
    pub fn new(
        inner: Arc<dyn StorageBackend>,
        encryption_module: Arc<dyn EncryptionModule + Send + Sync>,
    ) -> Self {
        Self {
            inner,
            encryption_module,
        }
    }
}

fn map_to_storage_backend_error(err: impl Into<anyhow::Error>) -> StorageBackendError {
    StorageBackendError::Generic {
        backend_type: "EncryptionDriver".into(),
        inner: err.into(),
    }
}

#[async_trait]
impl StorageBackend for EncryptStorageDriver {
    async fn read_dir(&self, path: &Path) -> Result<ReadDirResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;
        let response = self.inner.read_dir(path.as_path()).await;

        match response {
            Ok(ReadDirResponse::Entries(entries)) => Ok(ReadDirResponse::Entries(
                entries
                    .into_iter()
                    .map(|entry| {
                        Ok(DirEntry {
                            item_name: self
                                .encryption_module
                                .decode_plain(entry.item_name)
                                .map_err(map_to_storage_backend_error)?,
                            stat: entry.stat,
                        })
                    })
                    .collect::<Result<_, _>>()?,
            )),
            Ok(ReadDirResponse::NoSuchPath) => Ok(ReadDirResponse::NoSuchPath),
            Ok(ReadDirResponse::NotADirectory) => Ok(ReadDirResponse::NotADirectory),
            Err(e) => Err(e),
        }
    }

    async fn metadata(&self, path: &Path) -> Result<MetadataResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;
        self.inner.metadata(path.as_path()).await
    }

    async fn create_dir(&self, path: &Path) -> Result<CreateDirResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;
        self.inner.create_dir(path.as_path()).await
    }

    async fn set_wildland_object_id(
        &self,
        path: &Path,
        new_wildland_object_id: String,
    ) -> Result<SetWildlandObjectIdResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;

        self.inner
            .set_wildland_object_id(path.as_path(), new_wildland_object_id)
            .await
    }

    async fn remove_dir(
        &self,
        path: &Path,
        is_recursive: bool,
    ) -> Result<RemoveDirResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;

        self.inner.remove_dir(path.as_path(), is_recursive).await
    }

    async fn path_exists(&self, path: &Path) -> Result<bool, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;

        self.inner.path_exists(path.as_path()).await
    }

    async fn remove_file(&self, path: &Path) -> Result<RemoveFileResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;

        self.inner.remove_file(path.as_path()).await
    }

    async fn rename(
        &self,
        oldpath: &Path,
        newpath: &Path,
    ) -> Result<RenameResponse, StorageBackendError> {
        let oldpath = self
            .encryption_module
            .encode_path(oldpath)
            .map_err(map_to_storage_backend_error)?;
        let newpath = self
            .encryption_module
            .encode_path(newpath)
            .map_err(map_to_storage_backend_error)?;
        self.inner
            .rename(oldpath.as_path(), newpath.as_path())
            .await
    }

    async fn set_permissions(
        &self,
        path: &Path,
        permissions: WlPermissions,
    ) -> Result<SetPermissionsResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;
        self.inner
            .set_permissions(path.as_path(), permissions)
            .await
    }

    async fn mount(&self) -> Result<(), StorageBackendError> {
        self.inner.mount().await
    }

    async fn get_space_usage(&self) -> Result<SpaceUsage, StorageBackendError> {
        self.inner.get_space_usage().await
    }

    async fn download(
        &self,
        path: &Path,
        output_stream: Box<dyn OStream>,
        progress_reporter: Box<dyn ProgressReporter>,
    ) -> Result<DownloadResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;
        let transition_stream = self.encryption_module.wrap_ostream(output_stream);

        self.inner
            .download(path.as_path(), transition_stream, progress_reporter)
            .await
    }

    async fn upload(
        &self,
        path: &Path,
        input_stream: Box<dyn IStream>,
        progress_reporter: Box<dyn ProgressReporter>,
        creation_time: Option<UnixTimestamp>,
    ) -> Result<UploadResponse, StorageBackendError> {
        let path = self
            .encryption_module
            .encode_path(path)
            .map_err(map_to_storage_backend_error)?;

        let transition_stream = self.encryption_module.wrap_istream(input_stream);

        self.inner
            .upload(
                path.as_path(),
                transition_stream,
                progress_reporter,
                creation_time,
            )
            .await
    }

    async fn get_path_by_uuid(&self, uuid: String) -> Result<GetInfoResponse, StorageBackendError> {
        self.inner.get_path_by_uuid(uuid).await.map(|v| match v {
            GetInfoResponse::Found(out) => Ok(GetInfoResponse::Found(
                self.encryption_module
                    .decode_path(&out)
                    .map_err(map_to_storage_backend_error)?,
            )),
            GetInfoResponse::NotFound => Ok(GetInfoResponse::NotFound),
        })?
    }

    async fn stat_fs(&self) -> Result<FsStat, StorageBackendError> {
        self.inner.stat_fs().await
    }
}