aboutsummaryrefslogtreecommitdiff
path: root/lockchain-files/src/lib.rs
blob: 97912be3d47fa5122284739cfc9efa3e821b8acf (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
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
//! A persistence layer for lockchain vaults based on files
//!
//! This crate provides a filesystem backend
//! which relies on keeping records in discrete files
//! and folder structures.
//!
//! This is great if a vault needs to be easily syncable
//! or indexable by another tool.
//! No clear-text secrets are ever written to disk.
//! But might be held in memory cache
//! for a period of time.
//!
//! This backend is comparibly slow
//! and should be avoided
//! for performance critical applications.
//! For such applications
//! the blockstore is much more suited
//! which represents a vault
//! in a binary blob
//! independant of the used filesystem.
//!
//! Part of the performance problems
//! comes from locking the entire vault
//! when doing operations,
//! meaning that only
//! one instance
//! of a lockchain library
//! can operate on it
//! at the time
//!
//! ```
//! my_vault/
//!   config.toml
//!   Lockfile
//!   metadata/
//!     userstore.meta
//!     registry.meta
//!   records/
//!     <base64 hash 1>.rec
//!     <base64 hash 2>.rec
//!     <base64 hash 3>.rec
//!   hashsums/
//!     <base64 hash 1>.sum
//!     <base64 hash 2>.sum
//!     <base64 hash 3>.sum
//! ```
#![feature(non_modrs_mods)]

extern crate lockchain_core as lcc;
extern crate semver;
extern crate toml;

#[macro_use]
extern crate serde_derive;
extern crate serde;

use lcc::traits::{Body, LoadRecord, Vault};
use lcc::{
    initialise::Generator,
    users::{Access, Token},
    MetaDomain, Payload, Record, VaultMetadata,
};
use std::collections::HashMap;

mod config;
mod fs;
mod utils;

pub use config::{ConfigError, VaultConfig};
use fs::{FileType, Filesystem};

/// Persistence mapper to a folder and file structure
///
/// Implements the `Vault` API in full,
/// replicating all functionality in memory
/// and never writing clear text data to disk.
///
/// The internal layout should not be assumed
/// and isn't stabilised with the crate version
/// (i.e. minor crate bumps can break vault compatibility
/// as long as they remain API compatible).
///
/// The version of a vault is written in it's coniguration
/// (which won't change – ever).
///
/// The vault folder is safe to copy around –
/// all vault metadata is kept inside it.
#[derive(Debug)]
pub struct DataVault<T: Body> {
    meta_info: (String, String),
    config: VaultConfig,
    records: HashMap<String, Record<T>>,
    metadata: HashMap<String, MetaDomain>,
    fs: Filesystem,
}

impl<T: Body> DataVault<T> {
    /// Small utility function to setup file structure
    fn initialize(self) -> Self {
        self.fs.scaffold();
        self.config.save(&self.fs.root).unwrap();
        self
    }

    fn load(mut self) -> Option<Box<Self>> {
        self.config = match VaultConfig::load(&self.fs.root) {
            Ok(cfg) => cfg,
            _ => return None,
        };

        Some(Box::new(self))
    }
}

impl<T: Body> LoadRecord<T> for DataVault<T> {}

impl<T: Body> Vault<T> for DataVault<T> {
    fn new(gen: Generator) -> DataVault<T> {
        Self {
            meta_info: (
                gen.name.clone().unwrap().into(),
                gen.location.clone().unwrap().into(),
            ),
            records: HashMap::new(),
            config: VaultConfig::new(),
            metadata: HashMap::new(),
            fs: Filesystem::new(&gen.location.unwrap(), &gen.name.unwrap()),
        }.initialize()
    }

    fn create_user(
        &mut self,
        token: Token,
        username: &str,
        secret: &str,
        access: Vec<Access>,
    ) -> Result<(), ()> {
        unimplemented!()
    }

    fn delete_user(&mut self, token: Token, username: &str) {}

    // Checking if a vault exists is basically checking it's config
    // against the compatible version of this library.
    //
    // If it's compatible we can open the vault into memory
    // (loading all required paths into the struct), then return it
    fn load(name: &str, location: &str) -> Option<Box<Self>> {
        Self {
            meta_info: (name.into(), location.into()),
            records: HashMap::new(),
            config: VaultConfig::new(),
            metadata: HashMap::new(),
            fs: Filesystem::new(location, name),
        }.load()
    }

    fn authenticate(&mut self, username: &str, secret: &str) -> Token {
        unimplemented!()
    }

    fn deauthenticate(&mut self, username: &str, _: Token) {
        unimplemented!()
    }

    fn metadata(&self) -> VaultMetadata {
        VaultMetadata {
            name: self.meta_info.0.clone(),
            location: self.meta_info.1.clone(),
            size: self.records.len(),
        }
    }

    /// Caches all files from disk to memory
    fn fetch(&mut self) {
        self.records.clear();
        self.metadata.clear();

        self.fs
            .fetch::<Record<T>>(FileType::Record)
            .unwrap()
            .into_iter()
            .map(|rec| (rec.header.name.clone(), rec))
            .for_each(|x| {
                self.records.insert(x.0, x.1);
            });

        self.fs
            .fetch::<MetaDomain>(FileType::Metadata)
            .unwrap()
            .into_iter()
            .map(|rec| (rec.name().into(), rec))
            .for_each(|x| {
                self.metadata.insert(x.0, x.1);
            });
    }

    /// Make sure a single record is loaded
    fn pull(&mut self, name: &str) {
        self.records.remove(name);
        self.records.insert(
            name.to_owned(),
            self.fs.pull::<Record<T>>(FileType::Record, name).unwrap(),
        );
    }

    fn sync(&mut self) {
        self.fs
            .sync::<Record<T>>(&self.records, FileType::Record)
            .unwrap();
        self.fs
            .sync::<MetaDomain>(&self.metadata, FileType::Metadata)
            .unwrap();
    }

    fn get_record(&self, name: &str) -> Option<&Record<T>> {
        self.records.get(name)
    }

    fn contains(&self, name: &str) -> bool {
        self.records.contains_key(name)
    }

    fn add_record(&mut self, key: &str, category: &str, tags: Vec<&str>) {
        self.records
            .insert(key.to_owned(), Record::new(key, category, tags));
    }

    fn delete_record(&mut self, record: &str) -> Option<Record<T>> {
        self.records.remove(record)
    }

    fn add_data(&mut self, record: &str, key: &str, data: Payload) -> Option<()> {
        self.records.get_mut(record)?.add_data(key, data)
    }

    fn get_data(&self, record: &str, key: &str) -> Option<&Payload> {
        self.records.get(record)?.get_data(key)
    }

    fn meta_add_domain(&mut self, domain: &str) -> Option<()> {
        if self.metadata.contains_key(domain) {
            None
        } else {
            self.metadata.insert(domain.into(), MetaDomain::new(domain));
            Some(())
        }
    }

    fn meta_pull_domain(&self, domain: &str) -> Option<&MetaDomain> {
        self.metadata.get(domain)
    }

    fn meta_push_domain(&mut self, domain: MetaDomain) -> Option<()> {
        self.metadata
            .insert(domain.name().into(), domain)
            .map_or((), |_| ()) // We don't care about `None`
            .into()
    }

    fn meta_set(&mut self, domain: &str, name: &str, data: Payload) -> Option<()> {
        self.metadata.get_mut(domain)?.set_field(name, data)
    }

    fn meta_get(&mut self, domain: &str, name: &str) -> Option<Payload> {
        Some(self.metadata.get(domain)?.get_field(name)?.clone())
    }

    fn meta_exists(&self, domain: &str) -> bool {
        self.metadata.contains_key(domain)
    }
}