vfs-https 0.1.0

Exposes a Virtual File Systems (VFS) via HTTPS
Documentation
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use hyper::header::WWW_AUTHENTICATE;
use hyper::StatusCode;
use reqwest::blocking::Client;
use std::fmt::{Debug, Formatter};
use std::io::{Read, Seek, Write};
use vfs::{FileSystem, SeekAndRead, VfsError, VfsMetadata, VfsResult};

use crate::error::AuthError;
use crate::error::HttpsFSError;
use crate::error::HttpsFSResult;

use crate::protocol::*;

type CredentialProvider = Option<fn(realm: &str) -> (String, String)>;

/// A file system exposed over https
pub struct HttpsFS {
    addr: String,
    client: std::sync::Arc<reqwest::blocking::Client>,
    /// Will be called to get login credentials for the authentication process.
    /// Return value is a tuple: The first part is the user name, the second part the password.
    credentials: CredentialProvider,
}

/// Helper struct for building [HttpsFS] structs
pub struct HttpsFSBuilder {
    port: u16,
    domain: String,
    root_certs: Vec<reqwest::Certificate>,
    credentials: CredentialProvider,
}

struct WritableFile {
    client: std::sync::Arc<reqwest::blocking::Client>,
    addr: String,
    file_name: String,
    position: u64,
}

struct ReadableFile {
    client: std::sync::Arc<reqwest::blocking::Client>,
    addr: String,
    file_name: String,
    position: u64,
}

impl Debug for HttpsFS {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("Over Https Exposed File System.")
    }
}

impl HttpsFS {
    /// Returns a builder to create a [HttpsFS]
    pub fn builder(domain: &str) -> HttpsFSBuilder {
        HttpsFSBuilder::new(domain)
    }

    fn load_certificate(filename: &str) -> HttpsFSResult<reqwest::Certificate> {
        let mut buf = Vec::new();
        std::fs::File::open(filename)?.read_to_end(&mut buf)?;
        let cert = reqwest::Certificate::from_pem(&buf)?;
        Ok(cert)
    }

    fn exec_command(&self, cmd: &Command) -> HttpsFSResult<CommandResponse> {
        let req = serde_json::to_string(&cmd)?;
        let mut result = self.client.post(&self.addr).body(req).send()?;
        if result.status() == StatusCode::UNAUTHORIZED {
            let req = serde_json::to_string(&cmd)?;
            result = self
                .authorize(&result, self.client.post(&self.addr).body(req))?
                .send()?;
            if result.status() != StatusCode::OK {
                return Err(HttpsFSError::Auth(AuthError::Failed));
            }
        }
        let result = result.text()?;
        let result: CommandResponse = serde_json::from_str(&result)?;
        Ok(result)
    }

    fn authorize(
        &self,
        prev_response: &reqwest::blocking::Response,
        new_request: reqwest::blocking::RequestBuilder,
    ) -> HttpsFSResult<reqwest::blocking::RequestBuilder> {
        if self.credentials.is_none() {
            return Err(HttpsFSError::Auth(AuthError::NoCredentialSource));
        }
        let prev_headers = prev_response.headers();
        let auth_method = prev_headers
            .get(WWW_AUTHENTICATE)
            .ok_or(HttpsFSError::Auth(AuthError::NoMethodSpecified))?;
        let auth_method = String::from(
            auth_method
                .to_str()
                .map_err(|_| HttpsFSError::InvalidHeader(WWW_AUTHENTICATE.to_string()))?,
        );
        // TODO: this is a fix hack since we currently only support one method. If we start to
        // support more than one authentication method, we have to properly parse this header.
        // Furthermore, currently only the 'PME'-Realm is supported.
        let start_with = "Basic realm=\"PME\"";
        if !auth_method.starts_with(start_with) {
            return Err(HttpsFSError::Auth(AuthError::MethodNotSupported));
        }
        let get_cred = self.credentials.unwrap();
        let (username, password) = get_cred(&"PME");
        let new_request = new_request.basic_auth(username, Some(password));
        Ok(new_request)
    }
}

impl HttpsFSBuilder {
    /// Creates a new builder for a [HttpsFS].
    ///
    /// Takes a domain name to which the HttpsFS will connect.
    pub fn new(domain: &str) -> Self {
        HttpsFSBuilder {
            port: 443,
            domain: String::from(domain),
            root_certs: Vec::new(),
            credentials: None,
        }
    }

    /// Set the port, to which the HttpsFS will connect.
    ///
    /// Default is 443.
    pub fn set_port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Overwrites the domain name, which was set while creating the builder.
    pub fn set_domain(mut self, domain: &str) -> Self {
        self.domain = String::from(domain);
        self
    }

    /// Adds an additional root certificate.
    ///
    /// If a self signed certificate is used during, the development,
    /// than the certificate has to be added with this call, otherwise
    /// the [HttpsFS] fails to connect to the [crate::HttpsFSServer].
    pub fn add_root_certificate(mut self, cert: &str) -> Self {
        let cert = HttpsFS::load_certificate(cert).unwrap();
        self.root_certs.push(cert);
        self
    }

    /// If the [crate::HttpsFSServer] request a authentication, than this function will
    /// be called to get the credentials. The first value of the returned tuple
    /// is the user name and the second value is the password.
    pub fn set_credential_provider(
        mut self,
        c_provider: fn(realm: &str) -> (String, String),
    ) -> Self {
        self.credentials = Some(c_provider);
        self
    }

    /// Generates a HttpsFS with the set configuration
    ///
    /// # Error
    ///
    /// Returns an error, if the credential provider was not set.
    pub fn build(self) -> HttpsFSResult<HttpsFS> {
        if self.credentials.is_none() {
            return Err(HttpsFSError::Other {
                message: "HttpsFSBuilder: No credential provider set.".to_string(),
            });
        }
        let mut client = Client::builder().https_only(true).cookie_store(true);
        for cert in self.root_certs {
            client = client.add_root_certificate(cert);
        }

        let client = client.build()?;
        Ok(HttpsFS {
            client: std::sync::Arc::new(client),
            addr: format!("https://{}:{}/", self.domain, self.port),
            credentials: self.credentials,
        })
    }
}

impl Write for WritableFile {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let req = Command::Write(CommandWrite {
            path: self.file_name.clone(),
            pos: self.position,
            len: buf.len() as u64,
            data: base64::encode(buf),
        });
        let req = serde_json::to_string(&req)?;
        let result = self.client.post(&self.addr).body(req).send();
        if let Err(e) = result {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("{:?}", e),
            ));
        }
        let result = result.unwrap();
        let result = result.text();
        if let Err(e) = result {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("{:?}", e),
            ));
        }
        let result = result.unwrap();
        let result: CommandResponse = serde_json::from_str(&result)?;
        match result {
            CommandResponse::Write(result) => match result {
                Ok(size) => {
                    self.position += size as u64;
                    Ok(size)
                }
                Err(e) => Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("{:?}", e),
                )),
            },
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                String::from("Result doesn't match the request!"),
            )),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        todo!("flush()");
    }
}

impl Read for ReadableFile {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let req = Command::Read(CommandRead {
            path: self.file_name.clone(),
            pos: self.position,
            len: buf.len() as u64,
        });
        let req = serde_json::to_string(&req)?;
        let result = self.client.post(&self.addr).body(req).send();
        if let Err(e) = result {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("{:?}", e),
            ));
        }
        let result = result.unwrap();
        let result = result.text();
        if let Err(e) = result {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("{:?}", e),
            ));
        }
        let result = result.unwrap();
        let result: CommandResponse = serde_json::from_str(&result)?;
        match result {
            CommandResponse::Read(result) => match result {
                Ok((size, data)) => {
                    self.position += size as u64;
                    let decoded_data = base64::decode(data);
                    let mut result = Err(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        String::from("Faild to decode data"),
                    ));
                    if let Ok(data) = decoded_data {
                        buf[..size].copy_from_slice(&data.as_slice()[..size]);
                        result = Ok(size);
                    }
                    result
                }
                Err(e) => Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("{:?}", e),
                )),
            },
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                String::from("Result doesn't match the request!"),
            )),
        }
    }
}

impl Seek for ReadableFile {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        match pos {
            std::io::SeekFrom::Start(offset) => self.position = offset,
            std::io::SeekFrom::Current(offset) => {
                self.position = (self.position as i64 + offset) as u64
            }
            std::io::SeekFrom::End(offset) => {
                let fs = HttpsFS {
                    addr: self.addr.clone(),
                    client: self.client.clone(),
                    credentials: None,
                };
                let meta = fs.metadata(&self.file_name);
                if let Err(e) = meta {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("{:?}", e),
                    ));
                }
                let meta = meta.unwrap();
                self.position = (meta.len as i64 + offset) as u64
            }
        }
        Ok(self.position)
    }
}

impl FileSystem for HttpsFS {
    fn read_dir(&self, path: &str) -> VfsResult<Box<dyn Iterator<Item = String>>> {
        let req = Command::ReadDir(CommandReadDir {
            path: String::from(path),
        });
        let result = self.exec_command(&req)?;
        let result = match result {
            CommandResponse::ReadDir(value) => value,
            _ => {
                return Err(VfsError::Other {
                    message: String::from("Result doesn't match the request!"),
                });
            }
        };
        match result.result {
            Err(e) => Err(VfsError::Other { message: e }),
            Ok(value) => Ok(Box::new(value.into_iter())),
        }
    }

    fn create_dir(&self, path: &str) -> VfsResult<()> {
        let req = Command::CreateDir(CommandCreateDir {
            path: String::from(path),
        });
        let result = self.exec_command(&req)?;
        let result = match result {
            CommandResponse::CreateDir(value) => value,
            _ => {
                return Err(VfsError::Other {
                    message: String::from("Result doesn't match the request!"),
                });
            }
        };

        match result {
            CommandResponseCreateDir::Failed => Err(VfsError::Other {
                message: String::from("Result doesn't match the request!"),
            }),
            CommandResponseCreateDir::Success => Ok(()),
        }
    }

    fn open_file(&self, path: &str) -> VfsResult<Box<dyn SeekAndRead>> {
        if !self.exists(path)? {
            return Err(VfsError::FileNotFound {
                path: path.to_string(),
            });
        }

        Ok(Box::new(ReadableFile {
            client: self.client.clone(),
            addr: self.addr.clone(),
            file_name: String::from(path),
            position: 0,
        }))
    }

    fn create_file(&self, path: &str) -> VfsResult<Box<dyn Write>> {
        let req = Command::CreateFile(CommandCreateFile {
            path: String::from(path),
        });
        let result = self.exec_command(&req)?;
        let result = match result {
            CommandResponse::CreateFile(value) => value,
            _ => {
                return Err(VfsError::Other {
                    message: String::from("Result doesn't match the request!"),
                });
            }
        };

        match result {
            CommandResponseCreateFile::Failed => Err(VfsError::Other {
                message: String::from("Faild to create file!"),
            }),
            CommandResponseCreateFile::Success => Ok(Box::new(WritableFile {
                client: self.client.clone(),
                addr: self.addr.clone(),
                file_name: String::from(path),
                position: 0,
            })),
        }
    }

    fn append_file(&self, path: &str) -> VfsResult<Box<dyn Write>> {
        let meta = self.metadata(path)?;
        Ok(Box::new(WritableFile {
            client: self.client.clone(),
            addr: self.addr.clone(),
            file_name: String::from(path),
            position: meta.len,
        }))
    }

    fn metadata(&self, path: &str) -> VfsResult<VfsMetadata> {
        let req = Command::Metadata(CommandMetadata {
            path: String::from(path),
        });
        let result = self.exec_command(&req)?;
        match result {
            CommandResponse::Metadata(value) => meta_res_convert_cmd_vfs(value),
            _ => Err(VfsError::Other {
                message: String::from("Result doesn't match the request!"),
            }),
        }
    }

    fn exists(&self, path: &str) -> VfsResult<bool> {
        // TODO: Add more logging
        // TODO: try to change return type to VfsResult<bool>
        //       At the moment 'false' does not mean, that the file either does not exist
        //       or that an error has occurred. An developer does not expect this.
        let req = Command::Exists(CommandExists {
            path: String::from(path),
        });
        let result = self.exec_command(&req)?;
        let result = match result {
            CommandResponse::Exists(value) => value,
            _ => {
                return Err(VfsError::Other {
                    message: String::from("Result doesn't match the request!"),
                });
            }
        };
        match result {
            Err(e) => Err(VfsError::Other {
                message: format!("{:?}", e),
            }),
            Ok(val) => Ok(val),
        }
    }

    fn remove_file(&self, path: &str) -> VfsResult<()> {
        let req = Command::RemoveFile(CommandRemoveFile {
            path: String::from(path),
        });
        let result = self.exec_command(&req)?;
        let result = match result {
            CommandResponse::RemoveFile(value) => value,
            _ => {
                return Err(VfsError::Other {
                    message: String::from("Result doesn't match the request!"),
                });
            }
        };

        match result {
            Err(e) => Err(VfsError::Other {
                message: format!("{:?}", e),
            }),
            Ok(_) => Ok(()),
        }
    }

    fn remove_dir(&self, path: &str) -> VfsResult<()> {
        let req = Command::RemoveDir(CommandRemoveDir {
            path: String::from(path),
        });
        let result = self.exec_command(&req)?;
        let result = match result {
            CommandResponse::RemoveDir(value) => value,
            _ => {
                return Err(VfsError::Other {
                    message: String::from("Result doesn't match the request!"),
                });
            }
        };

        match result {
            Err(e) => Err(VfsError::Other {
                message: format!("{:?}", e),
            }),
            Ok(_) => Ok(()),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{HttpsFS, HttpsFSServer};
    use lazy_static::lazy_static;
    use std::sync::{Arc, Mutex};
    use vfs::{test_vfs, MemoryFS};

    // Since we create a HttpsFSServer for each unit test, which are all executed
    // in parallel we have to ensure, that each server is listening on a different
    // port. This is done with this shared variable.
    // WARNING: It will not be tested, whether a port is already used by another
    //          program. In such a case, the corresponding unit test most likely
    //          fails.
    lazy_static! {
        static ref PORT: Arc<Mutex<u16>> = Arc::new(Mutex::new(8344));
    }

    test_vfs!({
        let server_port;
        match PORT.lock() {
            Ok(mut x) => {
                println!("Number: {}", *x);
                server_port = *x;
                *x += 1;
            }
            Err(e) => panic!("Error: {:?}", e),
        }
        std::thread::spawn(move || {
            let fs = MemoryFS::new();
            let server = HttpsFSServer::builder(fs)
                .set_port(server_port)
                .load_certificates("examples/cert/cert.crt")
                .load_private_key("examples/cert/private-key.key")
                .set_credential_validator(|username: &str, password: &str| {
                    username == "user" && password == "pass"
                });
            let result = server.run();
            if let Err(e) = result {
                println!("WARNING: {:?}", e);
            }
        });

        // make sure, that the server is ready for the unit tests
        let duration = std::time::Duration::from_millis(10);
        std::thread::sleep(duration);

        HttpsFS::builder("localhost")
            .set_port(server_port)
            // load self signed certificate
            // WARNING: When the certificate expire, than the unit tests will frail.
            //          In this case, a new certificate hast to be generated.
            .add_root_certificate("examples/cert/cert.crt")
            .set_credential_provider(|_| (String::from("user"), String::from("pass")))
            .build()
            .unwrap()
    });
}