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
//
// 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/>.

mod stream;

use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use base64::engine::GeneralPurpose;
use base64::Engine;
use stream::{EncryptingIStream, EncryptingOStream};
use wildland_corex::dfs::interface::{IStream, OStream};

use crate::encryption::interface::{EncryptionModule, EncryptionModuleError};

const CIPHER_ENCRYPTION_EXPANSION_RATE: f64 = 4.0 / 3.0;
const CIPHER_DECRYPTION_SHRINKAGE_RATE: f64 = 3.0 / 4.0;

#[derive(Clone)]
pub struct Core {
    engine: Arc<GeneralPurpose>,
}

impl Default for Core {
    fn default() -> Self {
        Self {
            engine: Arc::new(base64::engine::general_purpose::STANDARD_NO_PAD),
        }
    }
}

impl EncryptionModule for Core {
    fn wrap_istream(&self, istream: Box<dyn IStream>) -> Box<dyn IStream> {
        Box::new(EncryptingIStream::new(istream, self.clone()))
    }

    fn wrap_ostream(&self, ostream: Box<dyn OStream>) -> Box<dyn OStream> {
        Box::new(EncryptingOStream::new(ostream, self.clone()))
    }

    #[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
    fn encode_data(&self, input: &[u8]) -> Result<Vec<u8>, EncryptionModuleError> {
        Ok(self.engine.encode(input).as_bytes().into())
    }

    #[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
    fn decode_data(&self, input: &[u8]) -> Result<Vec<u8>, EncryptionModuleError> {
        Ok(self.engine.decode(input)?)
    }

    #[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
    fn encode_path(&self, input: &Path) -> Result<PathBuf, EncryptionModuleError> {
        Ok(PathBuf::from(
            input
                .components()
                .map(|c| match c {
                    Component::Normal(c) => self.engine.encode(c.to_string_lossy().as_bytes()),
                    v => v.as_os_str().to_string_lossy().to_string(),
                })
                .collect::<Vec<String>>()
                .join("/"),
        ))
    }

    #[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
    fn decode_path(&self, input: &Path) -> Result<PathBuf, EncryptionModuleError> {
        input
            .components()
            .map(|component| {
                Ok(match component {
                    Component::Normal(c) => PathBuf::from(
                        String::from_utf8_lossy(
                            &self.engine.decode(c.to_string_lossy().as_bytes())?,
                        )
                        .to_string(),
                    ),
                    v => PathBuf::from(v.as_os_str()),
                })
            })
            .collect::<Result<PathBuf, EncryptionModuleError>>()
    }

    #[tracing::instrument(level = "debug", err(Debug), skip(input, self))]
    fn decode_plain(&self, input: String) -> Result<String, EncryptionModuleError> {
        let out = String::from_utf8_lossy(&self.engine.decode(input).unwrap()).to_string();
        Ok(out)
    }
}