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
/*
    Copyright Michael Lodder. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0
*/
use secret_service::{EncryptionType, SecretService};

use super::*;
use crate::error::KeyRingError;

use std::collections::BTreeMap;

pub struct LinuxOsKeyRing<'a> {
    keychain: SecretService<'a>,
    service: String,
    username: String,
}

unsafe impl<'a> Send for LinuxOsKeyRing<'a> {}

unsafe impl<'a> Sync for LinuxOsKeyRing<'a> {}

impl<'a> DynKeyRing for LinuxOsKeyRing<'a> {
    fn get_secret(&mut self, id: &str) -> Result<KeyRingSecret> {
        let collection = self
            .keychain
            .get_default_collection()
            .map_err(KeyRingError::from)?;
        if collection.is_locked().map_err(KeyRingError::from)? {
            collection.unlock().map_err(KeyRingError::from)?
        }
        let attributes = maplit::hashmap![
            "application" => "lox",
            "service" => &self.service,
            "username" => &self.username,
            "id" => id,
        ];
        let search = collection
            .search_items(attributes)
            .map_err(KeyRingError::from)?;
        let item = search.get(0).ok_or(KeyRingError::ItemNotFound)?;
        let secret = item.get_secret().map_err(KeyRingError::from)?;
        Ok(KeyRingSecret(secret))
    }

    fn set_secret(&mut self, id: &str, secret: &[u8]) -> Result<()> {
        let collection = self
            .keychain
            .get_default_collection()
            .map_err(KeyRingError::from)?;
        if collection.is_locked().map_err(KeyRingError::from)? {
            collection.unlock().map_err(KeyRingError::from)?
        }
        let attributes = maplit::hashmap![
            "application" => "lox",
            "service" => &self.service,
            "username" => &self.username,
            "id" => id,
        ];
        collection
            .create_item(
                &format!("Secret for {}", id),
                attributes,
                secret,
                true,
                "text/plain",
            )
            .map_err(KeyRingError::from)?;
        Ok(())
    }

    fn delete_secret(&mut self, id: &str) -> Result<()> {
        let collection = self
            .keychain
            .get_default_collection()
            .map_err(KeyRingError::from)?;
        if collection.is_locked().map_err(KeyRingError::from)? {
            collection.unlock().map_err(KeyRingError::from)?
        }
        let attributes = maplit::hashmap![
            "application" => "lox",
            "service" => &self.service,
            "username" => &self.username,
            "id" => id,
        ];
        let search = collection
            .search_items(attributes)
            .map_err(KeyRingError::from)?;
        let item = search
            .get(0)
            .ok_or_else(|| KeyRingError::from("No secret found"))?;
        item.delete().map_err(KeyRingError::from)
    }
}

impl<'a> NewKeyRing for LinuxOsKeyRing<'a> {
    fn new<S: AsRef<str>>(service: S) -> Result<Self> {
        Ok(LinuxOsKeyRing {
            keychain: SecretService::new(EncryptionType::Dh)?,
            service: service.as_ref().to_string(),
            username: get_username(),
        })
    }
}

impl<'a> PeekableKeyRing for LinuxOsKeyRing<'a> {
    fn peek_secret<S: AsRef<str>>(id: S) -> Result<Vec<(String, KeyRingSecret)>> {
        let id = id.as_ref();
        let key_chain = SecretService::new(EncryptionType::Dh).map_err(KeyRingError::from)?;
        let collection = key_chain
            .get_default_collection()
            .map_err(KeyRingError::from)?;
        if collection.is_locked().map_err(KeyRingError::from)? {
            collection.unlock().map_err(KeyRingError::from)?
        }
        let attributes = parse_peek_criteria(id);

        let items = collection.get_all_items().map_err(KeyRingError::from)?;
        let mut out = Vec::new();

        for item in &items {
            match item.get_attributes() {
                Ok(atts) => {
                    let mut matches = true;
                    for (k, v) in &attributes {
                        if atts.contains_key(k) {
                            matches = atts[k] == v.as_str();
                        } else {
                            matches = false;
                        }
                        if !matches {
                            break;
                        }
                    }
                    if matches || id.is_empty() {
                        let secret = item.get_secret().map_err(KeyRingError::from)?;
                        out.push((format!("{:?}", atts), KeyRingSecret(secret)));
                    }
                }
                Err(e) => {
                    if !out.is_empty() {
                        return Ok(out);
                    } else {
                        return Err(KeyRingError::from(e));
                    }
                }
            }
        }

        Ok(out)
    }
}

impl<'a> ListKeyRing for LinuxOsKeyRing<'a> {
    fn list_secrets() -> Result<Vec<BTreeMap<String, String>>> {
        let key_chain = SecretService::new(EncryptionType::Dh).map_err(KeyRingError::from)?;
        let collection = key_chain
            .get_default_collection()
            .map_err(KeyRingError::from)?;
        if collection.is_locked().map_err(KeyRingError::from)? {
            collection.unlock().map_err(KeyRingError::from)?
        }
        let items = collection.get_all_items().map_err(KeyRingError::from)?;
        let mut out = Vec::new();
        for item in &items {
            match item.get_attributes() {
                Ok(atts) => {
                    out.push(BTreeMap::from_iter(atts.into_iter()));
                }
                Err(e) => {
                    if !out.is_empty() {
                        return Ok(out);
                    } else {
                        return Err(KeyRingError::from(e));
                    }
                }
            }
        }

        Ok(out)
    }
}