summaryrefslogtreecommitdiffstats
path: root/atuin-client/src/kv.rs
blob: 74db27071573e1419a423324d896bf25e461a779 (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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::collections::{BTreeMap, HashMap};
use std::sync::{Mutex, OnceLock};

use atuin_common::record::{DecryptedData, HostId};
use eyre::{bail, ensure, eyre, ContextCompat, Result};
use rusty_paserk::{Key, KeyId, Public, Secret, V4};

use crate::record::encryption::PASETO_V4;
use crate::record::key_mgmt;
use crate::record::key_mgmt::key::KeyStore;
use crate::record::key_mgmt::paseto_seal::PASETO_V4_SEAL;
use crate::record::store::Store;

const KV_VERSION: &str = "v1";
const KV_TAG: &str = "kv";
const KV_VAL_MAX_LEN: usize = 100 * 1024;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KvRecord {
    pub namespace: String,
    pub key: String,
    pub value: String,
}

impl KvRecord {
    pub fn serialize(&self) -> Result<DecryptedData> {
        use rmp::encode;

        let mut output = vec![];

        // INFO: ensure this is updated when adding new fields
        encode::write_array_len(&mut output, 3)?;

        encode::write_str(&mut output, &self.namespace)?;
        encode::write_str(&mut output, &self.key)?;
        encode::write_str(&mut output, &self.value)?;

        Ok(DecryptedData(output))
    }

    pub fn deserialize(data: &DecryptedData, version: &str) -> Result<Self> {
        use rmp::decode;

        fn error_report<E: std::fmt::Debug>(err: E) -> eyre::Report {
            eyre!("{err:?}")
        }

        match version {
            "v0" | "v1" => {
                let mut bytes = decode::Bytes::new(&data.0);

                let nfields = decode::read_array_len(&mut bytes).map_err(error_report)?;
                ensure!(nfields == 3, "too many entries in v0 kv record");

                let bytes = bytes.remaining_slice();

                let (namespace, bytes) =
                    decode::read_str_from_slice(bytes).map_err(error_report)?;
                let (key, bytes) = decode::read_str_from_slice(bytes).map_err(error_report)?;
                let (value, bytes) = decode::read_str_from_slice(bytes).map_err(error_report)?;

                if !bytes.is_empty() {
                    bail!("trailing bytes in encoded kvrecord. malformed")
                }

                Ok(KvRecord {
                    namespace: namespace.to_owned(),
                    key: key.to_owned(),
                    value: value.to_owned(),
                })
            }
            _ => {
                bail!("unknown version {version:?}")
            }
        }
    }
}

pub struct KvStore {
    key_store: KeyStore,
    v1_public_key: OnceLock<Key<V4, Public>>,
    v1_secret_keys: Mutex<HashMap<KeyId<V4, Public>, Key<V4, Secret>>>,
}

impl Default for KvStore {
    fn default() -> Self {
        Self::new()
    }
}

impl KvStore {
    // will want to init the actual kv store when that is done
    pub fn new() -> KvStore {
        let key_store = KeyStore::new("atuin-kv");
        KvStore {
            key_store,
            v1_public_key: OnceLock::new(),
            v1_secret_keys: Mutex::new(HashMap::new()),
        }
    }

    pub async fn set(
        &self,
        store: &mut (impl Store + Send + Sync),
        encryption_key: &[u8; 32],
        host_id: HostId,
        namespace: &str,
        key: &str,
        value: &str,
    ) -> Result<()> {
        if value.len() > KV_VAL_MAX_LEN {
            return Err(eyre!(
                "kv value too large: max len {} bytes",
                KV_VAL_MAX_LEN
            ));
        }

        let record = KvRecord {
            namespace: namespace.to_string(),
            key: key.to_string(),
            value: value.to_string(),
        };

        let bytes = record.serialize()?;

        let parent = store.tail(host_id, KV_TAG).await?.map(|entry| entry.id);

        let record = atuin_common::record::Record::builder()
            .host(host_id)
            .version(KV_VERSION.to_string())
            .tag(KV_TAG.to_string())
            .parent(parent)
            .data(bytes)
            .build();

        let key = self
            .key_store
            .get_encryption_key(store)
            .await?
            .context("no key")?;

        store.push(&record.encrypt::<PASETO_V4_SEAL>(&key)).await?;

        Ok(())
    }

    fn get_v1_decryption_key(
        &self,
        store: &impl Store,
        id: KeyId<V4, Public>,
    ) -> Result<Option<Key<V4, Secret>>> {
        // self.v1_secret_keys.lock().unwrap().get()

        todo!()
    }

    // TODO: setup an actual kv store, rebuild func, and do not pass the main store in here as
    // well.
    pub async fn get(
        &self,
        store: &impl Store,
        encryption_key: &[u8; 32],
        namespace: &str,
        key: &str,
    ) -> Result<Option<KvRecord>> {
        // Currently, this is O(n). When we have an actual KV store, it can be better
        // Just a poc for now!

        // iterate records to find the value we want
        // start at the end, so we get the most recent version
        let tails = store.tag_tails(KV_TAG).await?;

        if tails.is_empty() {
            return Ok(None);
        }

        // first, decide on a record.
        // try getting the newest first
        // we always need a way of deciding the "winner" of a write
        // TODO(ellie): something better than last-write-wins, what if two write at the same time?
        let mut record = tails.iter().max_by_key(|r| r.timestamp).unwrap().clone();

        loop {
            let decrypted = match record.version.as_str() {
                "v0" => record.decrypt::<PASETO_V4>(encryption_key)?,
                "v1" => {
                    let id = serde_json::from_str::<key_mgmt::paseto_seal::AtuinFooter>(
                        &record.data.content_encryption_key,
                    )?
                    .kid;
                    let key = self
                        .get_v1_decryption_key(store, id)?
                        .context("missing key")?;
                    record.decrypt::<PASETO_V4_SEAL>(&key)?
                }
                version => bail!("unknown version {version:?}"),
            };

            let kv = KvRecord::deserialize(&decrypted.data, &decrypted.version)?;
            if kv.key == key && kv.namespace == namespace {
                return Ok(Some(kv));
            }

            if let Some(parent) = decrypted.parent {
                record = store.get(parent).await?;
            } else {
                break;
            }
        }

        // if we get here, then... we didn't find the record with that key :(
        Ok(None)
    }

    // Build a kv map out of the linked list kv store
    // Map is Namespace -> Key -> Value
    // TODO(ellie): "cache" this into a real kv structure, which we can
    // use as a write-through cache to avoid constant rebuilds.
    pub async fn build_kv(
        &self,
        store: &impl Store,
        encryption_key: &[u8; 32],
    ) -> Result<BTreeMap<String, BTreeMap<String, String>>> {
        let mut map = BTreeMap::new();
        let tails = store.tag_tails(KV_TAG).await?;

        if tails.is_empty() {
            return Ok(map);
        }

        let mut record = tails.iter().max_by_key(|r| r.timestamp).unwrap().clone();

        loop {
            let decrypted = match record.version.as_str() {
                KV_VERSION => record.decrypt::<PASETO_V4&g