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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! persistence manager for entry storage

use crate::*;
use entry::LairEntry;
use futures::future::FutureExt;
use lair_keystore_api::{actor::*, internal::*};
use std::collections::HashMap;

ghost_actor::ghost_chan! {
    /// persistence manager for entry storage
    pub chan EntryStore<LairError> {
        /// generate a new tls cert entry && save it && return it
        fn tls_cert_self_signed_new_from_entropy(
            options: TlsCertOptions,
        ) -> (KeystoreIndex, Arc<LairEntry>);

        /// generate a new signature ed25519 keypair entry && save it && return it
        fn sign_ed25519_keypair_new_from_entropy() ->
            (KeystoreIndex, Arc<LairEntry>);

        /// add a new signature ed25519 keypair entry that is passed && save it && return it
        fn add_initial_sign_ed25519_keypair(
            keypair: lair_keystore_api::entry::EntrySignEd25519
        ) ->
            (KeystoreIndex, Arc<LairEntry>);

        /// generate a new x25519 keypair entry && save it && return it
        fn x25519_keypair_new_from_entropy() -> (KeystoreIndex, Arc<LairEntry>);

        /// fetch the highest / most recently added keystore_index
        fn get_last_entry_index() -> KeystoreIndex;

        /// fetch an entry from the store by keystore index
        fn get_entry_by_index(index: KeystoreIndex) -> Arc<LairEntry>;

        /// fetch an entry by its 32 byte public identifier
        /// for kepair, this is the pub key
        /// for tls cert, this is the digest
        fn get_entry_by_pub_id(id: Arc<Vec<u8>>) -> (KeystoreIndex, Arc<LairEntry>);

        /// get a tls cert entry by sni
        fn get_entry_by_sni(sni: CertSni) -> (KeystoreIndex, Arc<LairEntry>);
    }
}

ghost_actor::ghost_chan! {
    chan EntryStoreInternal<LairError> {
        fn finalize_new_entry(
            entry_index: KeystoreIndex,
            entry: Arc<LairEntry>,
        ) -> ();
    }
}

/// Spawn a new entry store actor.
pub async fn spawn_entry_store_actor(
    config: Arc<Config>,
    db_key: sodoken::BufReadSized<32>,
) -> LairResult<ghost_actor::GhostSender<EntryStore>> {
    let builder = ghost_actor::actor_builder::GhostActorBuilder::new();

    let sender = builder
        .channel_factory()
        .create_channel::<EntryStore>()
        .await?;

    let i_s = builder
        .channel_factory()
        .create_channel::<EntryStoreInternal>()
        .await?;

    tokio::task::spawn(
        builder.spawn(EntryStoreImpl::new(i_s, config, db_key).await?),
    );

    Ok(sender)
}

// -- internal -- //

#[allow(dead_code)]
mod store_sqlite;
use store_sqlite::SqlPool;

struct EntryStoreImpl {
    i_s: ghost_actor::GhostSender<EntryStoreInternal>,
    #[allow(dead_code)]
    config: Arc<Config>,
    db: SqlPool,
    last_entry_index: KeystoreIndex,
    entries_by_index: HashMap<KeystoreIndex, Arc<LairEntry>>,
    #[allow(clippy::rc_buffer)]
    entries_by_pub_id: HashMap<Arc<Vec<u8>>, (KeystoreIndex, Arc<LairEntry>)>,
    entries_by_sni: HashMap<CertSni, (KeystoreIndex, Arc<LairEntry>)>,
}

impl EntryStoreImpl {
    pub async fn new(
        i_s: ghost_actor::GhostSender<EntryStoreInternal>,
        config: Arc<Config>,
        db_key: sodoken::BufReadSized<32>,
    ) -> LairResult<Self> {
        let sql_db_file = config.get_store_path().to_owned();
        let db = SqlPool::new(sql_db_file, db_key).await?;

        match db.init_load_unlock().await? {
            None => {
                // write a STUB unlock entry of all zeroes for now
                let unlock_entry = vec![0_u8; entry::ENTRY_SIZE];
                db.write_unlock(unlock_entry).await?;
            }
            Some(_unlock_entry) => {
                // someday, do some crypto stuff to read other entries
            }
        }

        let mut out = Self {
            i_s,
            config,
            db,
            last_entry_index: 0.into(),
            entries_by_index: HashMap::new(),
            entries_by_pub_id: HashMap::new(),
            entries_by_sni: HashMap::new(),
        };

        // load / decode all entries
        for (entry_index, entry) in out.db.load_all_entries().await? {
            let entry = Arc::new(entry::LairEntry::decode(&entry)?);
            out.track_new_entry(entry_index, entry);
            if entry_index.0 > out.last_entry_index.0 {
                out.last_entry_index = entry_index;
            }
        }

        Ok(out)
    }

    fn track_new_entry(
        &mut self,
        entry_index: KeystoreIndex,
        entry: Arc<LairEntry>,
    ) {
        self.entries_by_index.insert(entry_index, entry.clone());

        match &*entry {
            LairEntry::TlsCert(e) => {
                self.entries_by_sni
                    .insert(e.sni.clone(), (entry_index, entry.clone()));
                self.entries_by_pub_id
                    .insert(e.cert_digest.0.clone(), (entry_index, entry));
            }
            LairEntry::SignEd25519(e) => {
                self.entries_by_pub_id
                    .insert(e.pub_key.0.clone(), (entry_index, entry));
            }
            LairEntry::X25519(e) => {
                self.entries_by_pub_id.insert(
                    Arc::new(e.pub_key.to_bytes().to_vec()),
                    (entry_index, entry),
                );
            }
            _ => {
                tracing::warn!(
                    "silently ignoring unhandled entry type {:?}",
                    entry
                );
            }
        }

        if entry_index.0 > self.last_entry_index.0 {
            self.last_entry_index = entry_index;
        }
    }
}

impl ghost_actor::GhostControlHandler for EntryStoreImpl {}

impl ghost_actor::GhostHandler<EntryStore> for EntryStoreImpl {}

impl EntryStoreHandler for EntryStoreImpl {
    fn handle_tls_cert_self_signed_new_from_entropy(
        &mut self,
        options: TlsCertOptions,
    ) -> EntryStoreHandlerResult<(KeystoreIndex, Arc<LairEntry>)> {
        Ok(new_tls_cert(self.i_s.clone(), self.db.clone(), options)
            .boxed()
            .into())
    }

    fn handle_sign_ed25519_keypair_new_from_entropy(
        &mut self,
    ) -> EntryStoreHandlerResult<(KeystoreIndex, Arc<LairEntry>)> {
        Ok(new_sign_ed25519_keypair(self.i_s.clone(), self.db.clone())
            .boxed()
            .into())
    }

    fn handle_add_initial_sign_ed25519_keypair(
        &mut self,
        keypair: lair_keystore_api::entry::EntrySignEd25519,
    ) -> EntryStoreHandlerResult<(KeystoreIndex, Arc<LairEntry>)> {
        Ok(add_initial_sign_ed25519_keypair(
            keypair,
            self.i_s.clone(),
            self.db.clone(),
        )
        .boxed()
        .into())
    }

    fn handle_x25519_keypair_new_from_entropy(
        &mut self,
    ) -> EntryStoreHandlerResult<(KeystoreIndex, Arc<LairEntry>)> {
        Ok(new_x25519_keypair(self.i_s.clone(), self.db.clone())
            .boxed()
            .into())
    }

    fn handle_get_last_entry_index(
        &mut self,
    ) -> EntryStoreHandlerResult<KeystoreIndex> {
        let idx = self.last_entry_index;
        Ok(async move { Ok(idx) }.boxed().into())
    }

    fn handle_get_entry_by_index(
        &mut self,
        index: KeystoreIndex,
    ) -> EntryStoreHandlerResult<Arc<LairEntry>> {
        match self.entries_by_index.get(&index) {
            Some(entry) => {
                let entry = entry.clone();
                Ok(async move { Ok(entry) }.boxed().into())
            }
            None => Err(format!("invalid KeystoreIndex: {}", index).into()),
        }
    }

    fn handle_get_entry_by_pub_id(
        &mut self,
        id: Arc<Vec<u8>>,
    ) -> EntryStoreHandlerResult<(KeystoreIndex, Arc<LairEntry>)> {
        match self.entries_by_pub_id.get(&id) {
            Some(entry) => {
                let entry = entry.clone();
                Ok(async move { Ok(entry) }.boxed().into())
            }
            None => Err(format!("invalid pub id: {:?}", id).into()),
        }
    }

    fn handle_get_entry_by_sni(
        &mut self,
        sni: CertSni,
    ) -> EntryStoreHandlerResult<(KeystoreIndex, Arc<LairEntry>)> {
        match self.entries_by_sni.get(&sni) {
            Some(entry) => {
                let entry = entry.clone();
                Ok(async move { Ok(entry) }.boxed().into())
            }
            None => Err(format!("invalid sni: {:?}", sni).into()),
        }
    }
}

impl ghost_actor::GhostHandler<EntryStoreInternal> for EntryStoreImpl {}

impl EntryStoreInternalHandler for EntryStoreImpl {
    fn handle_finalize_new_entry(
        &mut self,
        entry_index: KeystoreIndex,
        entry: Arc<LairEntry>,
    ) -> EntryStoreInternalHandlerResult<()> {
        self.track_new_entry(entry_index, entry);
        Ok(async move { Ok(()) }.boxed().into())
    }
}

async fn new_tls_cert(
    i_s: ghost_actor::GhostSender<EntryStoreInternal>,
    db: SqlPool,
    options: TlsCertOptions,
) -> LairResult<(KeystoreIndex, Arc<LairEntry>)> {
    let cert = Arc::new(LairEntry::TlsCert(
        tls::tls_cert_self_signed_new_from_entropy(options).await?,
    ));
    let encoded_cert = cert.encode()?;
    let entry_index = db.write_next_entry(encoded_cert).await?;
    i_s.finalize_new_entry(entry_index, cert.clone()).await?;
    Ok((entry_index, cert))
}

async fn new_sign_ed25519_keypair(
    i_s: ghost_actor::GhostSender<EntryStoreInternal>,
    db: SqlPool,
) -> LairResult<(KeystoreIndex, Arc<LairEntry>)> {
    let entry = Arc::new(LairEntry::SignEd25519(
        sign_ed25519::sign_ed25519_keypair_new_from_entropy().await?,
    ));
    let encoded_entry = entry.encode()?;
    let entry_index = db.write_next_entry(encoded_entry).await?;
    i_s.finalize_new_entry(entry_index, entry.clone()).await?;
    Ok((entry_index, entry))
}

async fn add_initial_sign_ed25519_keypair(
    keypair: lair_keystore_api::entry::EntrySignEd25519,
    i_s: ghost_actor::GhostSender<EntryStoreInternal>,
    db: SqlPool,
) -> LairResult<(KeystoreIndex, Arc<LairEntry>)> {
    println!("#Adding pub-key :{:?}", keypair.pub_key);
    let entry = Arc::new(LairEntry::SignEd25519(keypair));
    let encoded_entry = entry.encode()?;
    let entry_index = db.write_next_entry(encoded_entry).await?;
    i_s.finalize_new_entry(entry_index, entry.clone()).await?;
    Ok((entry_index, entry))
}

async fn new_x25519_keypair(
    i_s: ghost_actor::GhostSender<EntryStoreInternal>,
    db: SqlPool,
) -> LairResult<(KeystoreIndex, Arc<LairEntry>)> {
    let entry = Arc::new(LairEntry::X25519(
        x25519::x25519_keypair_new_from_entropy().await?,
    ));
    let encoded_entry = entry.encode()?;
    let entry_index = db.write_next_entry(encoded_entry).await?;
    i_s.finalize_new_entry(entry_index, entry.clone()).await?;
    Ok((entry_index, entry))
}

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

    macro_rules! as_cert {
        ($e:ident) => {
            let $e = match &*$e {
                LairEntry::TlsCert(e) => e,
                _ => panic!("unexpected"),
            };
        };
    }

    macro_rules! as_sign {
        ($e:ident) => {
            let $e = match &*$e {
                LairEntry::SignEd25519(e) => e,
                _ => panic!("unexpected"),
            };
        };
    }

    macro_rules! as_x25519 {
        ($e:ident) => {
            let $e = match &*$e {
                LairEntry::X25519(e) => e,
                _ => panic!("unexpected"),
            };
        };
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn it_can_store_and_retrieve_entries_from_disk() {
        let tmpdir = tempfile::tempdir().unwrap();

        let (cert, sign, x25519) = {
            let config = Config::builder().set_root_path(tmpdir.path()).build();

            let db_key = sodoken::BufReadSized::new_no_lock([0; 32]);
            let store = spawn_entry_store_actor(config, db_key).await.unwrap();

            let (cert_index, cert) =
                store
                    .tls_cert_self_signed_new_from_entropy(
                        TlsCertOptions::default(),
                    )
                    .await
                    .unwrap();
            assert_eq!(1, cert_index.0);

            let (sign_index, sign) =
                store.sign_ed25519_keypair_new_from_entropy().await.unwrap();
            assert_eq!(2, sign_index.0);

            let (x25519_index, x25519) =
                store.x25519_keypair_new_from_entropy().await.unwrap();
            assert_eq!(3, x25519_index.0);

            use ghost_actor::GhostControlSender;
            store.ghost_actor_shutdown().await.unwrap();
            drop(store);

            (cert, sign, x25519)
        };
        as_cert!(cert);
        as_sign!(sign);
        as_x25519!(x25519);

        let config = Config::builder().set_root_path(tmpdir.path()).build();

        let db_key = sodoken::BufReadSized::new_no_lock([0; 32]);
        let store = spawn_entry_store_actor(config, db_key).await.unwrap();

        let r_cert = store.get_entry_by_index(1.into()).await.unwrap();
        let r_sign = store.get_entry_by_index(2.into()).await.unwrap();
        let r_x25519 = store.get_entry_by_index(3.into()).await.unwrap();
        as_cert!(r_cert);
        as_sign!(r_sign);
        as_x25519!(r_x25519);

        assert_eq!(cert.cert_digest, r_cert.cert_digest);
        assert_eq!(sign.pub_key, r_sign.pub_key);
        assert_eq!(x25519.pub_key, r_x25519.pub_key);

        let (r_cert_index, r_cert) = store
            .get_entry_by_pub_id(cert.cert_digest.0.clone())
            .await
            .unwrap();
        as_cert!(r_cert);
        assert_eq!(1, r_cert_index.0);
        assert_eq!(cert.cert_digest, r_cert.cert_digest);

        let (r_sign_index, r_sign) = store
            .get_entry_by_pub_id(sign.pub_key.0.clone())
            .await
            .unwrap();
        as_sign!(r_sign);
        assert_eq!(2, r_sign_index.0);
        assert_eq!(sign.pub_key, r_sign.pub_key);

        let (r_x25519_index, r_x25519) = store
            .get_entry_by_pub_id(Arc::new(x25519.pub_key.to_bytes().to_vec()))
            .await
            .unwrap();
        as_x25519!(r_x25519);
        assert_eq!(3, r_x25519_index.0);
        assert_eq!(x25519.pub_key, r_x25519.pub_key);

        let (r_cert_index, r_cert) =
            store.get_entry_by_sni(cert.sni.clone()).await.unwrap();
        as_cert!(r_cert);
        assert_eq!(1, r_cert_index.0);
        assert_eq!(cert.cert_digest, r_cert.cert_digest);

        use ghost_actor::GhostControlSender;
        store.ghost_actor_shutdown().await.unwrap();
        drop(store);
        drop(tmpdir);
    }
}