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
//! This module contains an in-memory implementation of a [CredStore] called [InMemCredStore].
//! A static instance of this struct called [TEST_STORE] can be used to get credentials during
//! testing. The root password for this credential store is defined in [TEST_STORE_ROOT_PASSWORD].

use std::{
    sync::{Arc, RwLock},
    time::Duration,
};

use btlib::{
    bterr,
    crypto::{AsymKeyPub, ConcreteCreds, CredStore, CredStoreMut, Creds, Encrypt, Error},
    error::DisplayErr,
    Epoch, Result,
};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};

/// The root password to use with the [static@TEST_STORE] static credential store.
pub const TEST_STORE_ROOT_PASSWORD: &str = "shubawumba";

lazy_static! {
    /// A static instance of [InMemCredStore] for use in tests.
    pub static ref TEST_STORE: InMemCredStore = {
        let store = InMemCredStore::new().unwrap();
        let expires = Epoch::now() + Duration::from_secs(7200);
        let root_creds = store.provision_root(TEST_STORE_ROOT_PASSWORD, expires).unwrap();
        let node_principal = store.provision_node_start().unwrap();
        let writecap = root_creds
            .issue_writecap(node_principal, &mut std::iter::empty(), expires)
            .unwrap();
        store.provision_node_finish(writecap).unwrap();
        store
    };
}

/// A credential store that keeps all credential in memory. Thus these credentials will be
/// lost when this struct is dropped.
pub struct InMemCredStore {
    node_creds: RwLock<Arc<ConcreteCreds>>,
    root_creds: RwLock<Option<RootInfo>>,
    storage_key: AsymKeyPub<Encrypt>,
}

impl InMemCredStore {
    pub fn new() -> Result<Self> {
        let node_creds = ConcreteCreds::generate()?;
        let root_creds = RwLock::new(None);
        // Using the node credentials like this is bad practice, but for testing it's fine.
        // For production code a separate key pair for storage must be used.
        let storage_key = node_creds.encrypt_pair().public().clone();
        let node_creds = RwLock::new(Arc::new(node_creds));
        Ok(Self {
            node_creds,
            root_creds,
            storage_key,
        })
    }
}

impl CredStore for InMemCredStore {
    type CredHandle = Arc<ConcreteCreds>;
    type ExportedCreds = ExportedCreds;

    fn node_creds(&self) -> btlib::Result<Self::CredHandle> {
        let guard = self.node_creds.read().display_err()?;
        Ok(guard.clone())
    }

    fn root_creds(&self, password: &str) -> btlib::Result<Self::CredHandle> {
        let guard = self.root_creds.read().display_err()?;
        if let Some(info) = guard.as_ref() {
            if info.password == password {
                Ok(info.creds.clone())
            } else {
                Err(bterr!(Error::WrongRootPassword))
            }
        } else {
            Err(bterr!("root credentials have not been generated"))
        }
    }

    fn storage_key(&self) -> Result<AsymKeyPub<Encrypt>> {
        Ok(self.storage_key.clone())
    }

    fn export_root_creds(
        &self,
        root_creds: &Self::CredHandle,
        _password: &str,
        _new_parent: &AsymKeyPub<Encrypt>,
    ) -> Result<Self::ExportedCreds> {
        Ok(ExportedCreds {
            password: _password.to_string(),
            creds: root_creds.as_ref().clone(),
        })
    }
}

impl CredStoreMut for InMemCredStore {
    fn gen_root_creds(&self, password: &str) -> Result<Self::CredHandle> {
        {
            let guard = self.root_creds.read().display_err()?;
            if guard.is_some() {
                return Err(bterr!("root creds have already been generated"));
            }
        }

        let mut guard = self.root_creds.write().display_err()?;
        let creds = Arc::new(ConcreteCreds::generate()?);
        *guard = Some(RootInfo {
            password: password.to_owned(),
            creds: creds.clone(),
        });
        Ok(creds)
    }

    fn import_root_creds(
        &self,
        password: &str,
        exported: Self::ExportedCreds,
    ) -> Result<Self::CredHandle> {
        if exported.password != password {
            return Err(Error::WrongRootPassword.into());
        }
        let creds = Arc::new(exported.creds);
        let mut guard = self.root_creds.write().display_err()?;
        *guard = Some(RootInfo {
            password: password.to_owned(),
            creds: creds.clone(),
        });
        Ok(creds)
    }

    fn assign_node_writecap(
        &self,
        handle: &mut Self::CredHandle,
        writecap: btlib::Writecap,
    ) -> Result<()> {
        let creds = Arc::make_mut(handle);
        creds.set_writecap(writecap)?;
        let mut guard = self.node_creds.write().display_err()?;
        *guard = handle.clone();
        Ok(())
    }

    fn assign_root_writecap(
        &self,
        handle: &mut Self::CredHandle,
        writecap: btlib::Writecap,
    ) -> Result<()> {
        let creds = Arc::make_mut(handle);
        creds.set_writecap(writecap)?;
        let mut guard = self.root_creds.write().display_err()?;
        if let Some(info) = guard.as_mut() {
            info.creds = handle.clone();
            Ok(())
        } else {
            Err(bterr!("no root creds have been generated"))
        }
    }
}

struct RootInfo {
    password: String,
    creds: Arc<ConcreteCreds>,
}

#[derive(Serialize, Deserialize)]
pub struct ExportedCreds {
    password: String,
    creds: ConcreteCreds,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cred_store_test_cases;

    cred_store_test_cases!(InMemCredStore::new().unwrap());
}