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
use crate::errors::*;

use crate::engine::Module;
use crate::hlua::AnyLuaValue;
use crate::json::LuaJsonValue;
use crate::paths;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::fmt;
use std::str::FromStr;
use std::path::{Path, PathBuf};
use sn0int_common::ModuleID;


#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyName {
    pub namespace: String,
    pub name: String,
}

impl KeyName {
    pub fn new<I: Into<String>, J: Into<String>>(namespace: I, name: J) -> KeyName {
        KeyName {
            namespace: namespace.into(),
            name: name.into(),
        }
    }

    pub fn for_each(k: &str, v: &HashMap<String, Option<String>>) -> Vec<KeyName> {
        v.iter()
            .map(move |(x, _)| KeyName::new(k, x.as_str()))
            .collect()
    }
}

impl FromStr for KeyName {
    type Err = Error;

    fn from_str(x: &str) -> Result<KeyName> {
        if let Some(idx) = x.find(':') {
            let (namespace, name) = x.split_at(idx);
            let namespace = namespace.to_string();
            let name = name[1..].to_string();

            if namespace.is_empty() {
                bail!("Namespace can not be empty");
            }

            if name.is_empty() {
                bail!("Name can not be empty");
            }

            Ok(KeyName {
                namespace,
                name,
            })
        } else {
            bail!("Missing namespace")
        }
    }
}

impl fmt::Display for KeyName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.namespace, self.name)
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct KeyRing {
    keys: HashMap<String, HashMap<String, Option<String>>>,
    grants: HashMap<String, HashSet<ModuleID>>,
}

impl KeyRing {
    pub fn path() -> Result<PathBuf> {
        let path = paths::data_dir()?;
        let path = path.join("keyring.json");
        Ok(path)
    }

    pub fn init() -> Result<KeyRing> {
        let path = Self::path()?;

        if path.exists() {
            Self::load(&path)
        } else {
            Ok(KeyRing {
                keys: HashMap::new(),
                grants: HashMap::new(),
            })
        }
    }

    pub fn load(path: &Path) -> Result<KeyRing> {
        let buf = fs::read(&path)?;
        serde_json::from_slice(&buf)
            .map_err(Error::from)
    }

    pub fn save(&self) -> Result<()> {
        let path = Self::path()?;
        let buf = serde_json::to_string(&self)?;
        fs::write(&path, buf)?;
        Ok(())
    }

    pub fn insert(&mut self, key: KeyName, secret: Option<String>) -> Result<()> {
        // get the namespace or create a new one
        let mut x = self.keys.remove(&key.namespace)
            .unwrap_or_else(HashMap::new);
        // insert key into namespace
        x.insert(key.name, secret);
        // add namespace backinto keyring
        self.keys.insert(key.namespace, x);
        // save keyring
        self.save()
    }

    pub fn delete(&mut self, key: KeyName) -> Result<()> {
        if let Some(mut x) = self.keys.remove(&key.namespace) {
            // remove the key we want to delete
            x.remove(&key.name);

            // if there are still keys left in the namespace
            if !x.is_empty() {
                self.keys.insert(key.namespace, x);
            }

            // save keyring
            self.save()
        } else {
            Ok(())
        }
    }

    pub fn list(&self) -> Vec<KeyName> {
        self.keys.iter()
            .flat_map(|(k, v)| KeyName::for_each(k, v))
            .collect()
    }

    pub fn list_for(&self, namespace: &str) -> Vec<KeyName> {
        self.keys.iter()
            .filter(|(k, _)| k.as_str() == namespace)
            .flat_map(|(k, v)| KeyName::for_each(k, v))
            .collect()
    }

    pub fn get(&self, key: &KeyName) -> Option<KeyRingEntry> {
        let x = self.keys.get(&key.namespace)?;
        let secret_key = x.get(&key.name)?;

        Some(KeyRingEntry {
            namespace: key.namespace.to_owned(),
            access_key: key.name.to_owned(),
            secret_key: secret_key.to_owned(),
        })
    }

    pub fn get_all_for(&self, namespace: &str) -> Vec<KeyRingEntry> {
        self.list_for(namespace)
            .into_iter()
            .flat_map(|x| self.get(&x))
            .collect()
    }

    pub fn unauthorized_namespaces<'a>(&self, module: &'a Module) -> Vec<&'a String> {
        module.keyring_access().iter()
            .filter(|namespace| !self.is_access_granted(&module, &namespace))
            .collect()
    }

    pub fn grant_access(&mut self, module: &Module, namespace: String) {
        let mut grants = self.grants.remove(&namespace)
            .unwrap_or_else(HashSet::new);
        grants.insert(module.id());
        self.grants.insert(namespace, grants);
    }

    pub fn is_access_granted(&self, module: &Module, namespace: &str) -> bool {
        if let Some(grants) = self.grants.get(namespace) {
            grants.contains(&module.id())
        } else {
            false
        }
    }

    pub fn request_keys(&self, module: &Module) -> Vec<KeyRingEntry> {
        // TODO: we probably want to randomize the order
        module.keyring_access().iter()
            .filter(|namespace| self.is_access_granted(&module, &namespace))
            .flat_map(|namespace| self.list_for(namespace))
            .flat_map(|x| self.get(&x))
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KeyRingEntry {
    pub namespace: String,
    pub access_key: String,
    pub secret_key: Option<String>,
}

impl KeyRingEntry {
    pub fn to_lua(&self) -> Result<AnyLuaValue> {
        let v = serde_json::to_value(&self)?;
        let v = LuaJsonValue::from(v).into();
        Ok(v)
    }

    pub fn matches(&self, query: &str) -> bool {
        if let Some(idx) = query.find(':') {
            let (namespace, access_key) = query.split_at(idx);
            let access_key = &access_key[1..];

            self.namespace == namespace && self.access_key == access_key
        } else {
            self.namespace == query
        }
    }
}

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

    #[test]
    fn test_valid_keyname() {
        let x = KeyName::from_str("a:b").unwrap();
        assert_eq!(x, KeyName {
            namespace: "a".into(),
            name: "b".into(),
        });
    }

    #[test]
    fn test_invalid_keyname() {
        assert!(KeyName::from_str("a:").is_err());
        assert!(KeyName::from_str(":a").is_err());
        assert!(KeyName::from_str(":").is_err());
        assert!(KeyName::from_str("a").is_err());
        assert!(KeyName::from_str("").is_err());
    }
}