holochain_keystore 0.7.0-dev.4

keystore for libsodium keypairs
Documentation
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
use holo_hash::AgentPubKey;
use holochain_zome_types::prelude::*;
use lair_keystore::dependencies::lair_keystore_api;
use lair_keystore_api::prelude::{X25519PubKey, *};
pub use lair_keystore_api::LairResult;
use parking_lot::Mutex;
use std::future::Future;
use std::sync::Arc;

const TIME_CHECK_FREQ: std::time::Duration = std::time::Duration::from_secs(5);
const CON_CHECK_STUB_TAG: &str = "HC_CON_CHK_STUB";
const RECON_INIT_MS: u64 = 100;
const RECON_MAX_MS: u64 = 5000;

type Esnd = tokio::sync::mpsc::UnboundedSender<()>;

/// Abstraction around runtime switching/upgrade of lair keystore / client.
#[derive(Clone)]
pub struct MetaLairClient(pub(crate) Arc<Mutex<LairClient>>, pub(crate) Esnd);

/// A lair error could indicate a connection problem or user error.
/// If we get any error state, we send a signal to our connection validation
/// task indicating it should check our connection health.
macro_rules! echk {
    ($esnd:ident, $code:expr) => {{
        match $code {
            Err(err) => {
                let _ = $esnd.send(());
                return Err(err);
            }
            Ok(r) => r,
        }
    }};
}

impl MetaLairClient {
    pub(crate) async fn new(
        connection_url: url2::Url2,
        passphrase: SharedLockedArray,
    ) -> LairResult<Self> {
        use lair_keystore_api::ipc_keystore::*;
        let opts = IpcKeystoreClientOptions {
            connection_url: connection_url.clone().into(),
            passphrase: passphrase.clone(),
            exact_client_server_version_match: true,
        };

        let client = ipc_keystore_connect_options(opts).await?;
        let inner = Arc::new(Mutex::new(client));

        let (c_check_send, mut c_check_recv) = tokio::sync::mpsc::unbounded_channel();
        // initial check
        let _ = c_check_send.send(());

        // setup timeout for connection check
        {
            let c_check_send = c_check_send.clone();
            tokio::task::spawn(async move {
                loop {
                    tokio::time::sleep(TIME_CHECK_FREQ).await;
                    if c_check_send.send(()).is_err() {
                        break;
                    }
                }
            });
        }

        // setup the connection check logic
        {
            let inner = inner.clone();
            let stub_tag: Arc<str> = CON_CHECK_STUB_TAG.to_string().into();
            tokio::task::spawn(async move {
                use tokio::sync::mpsc::error::TryRecvError;
                'top_loop: while c_check_recv.recv().await.is_some() {
                    'drain_queue: loop {
                        match c_check_recv.try_recv() {
                            Ok(_) => (),
                            Err(TryRecvError::Empty) => break 'drain_queue,
                            Err(TryRecvError::Disconnected) => break 'top_loop,
                        }
                    }

                    let client = inner.lock().clone();

                    // optimistic check - most often the stub will be there
                    if client.get_entry(stub_tag.clone()).await.is_ok() {
                        continue;
                    }

                    // on the first run of a new install we need to create
                    let _ = client.new_seed(stub_tag.clone(), None, false).await;

                    // then we can exit early again
                    if client.get_entry(stub_tag.clone()).await.is_ok() {
                        continue;
                    }

                    // we couldn't fetch the stub, enter our reconnect loop
                    let mut backoff_ms = RECON_INIT_MS;
                    'reconnect: loop {
                        'drain_queue2: loop {
                            match c_check_recv.try_recv() {
                                Ok(_) => (),
                                Err(TryRecvError::Empty) => break 'drain_queue2,
                                Err(TryRecvError::Disconnected) => break 'top_loop,
                            }
                        }

                        backoff_ms *= 2;
                        if backoff_ms >= RECON_MAX_MS {
                            backoff_ms = RECON_MAX_MS;
                        }
                        tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)).await;
                        let opts = IpcKeystoreClientOptions {
                            connection_url: connection_url.clone().into(),
                            passphrase: passphrase.clone(),
                            exact_client_server_version_match: true,
                        };

                        tracing::warn!("lair connection lost, attempting reconnect");

                        let client = match ipc_keystore_connect_options(opts).await {
                            Err(err) => {
                                tracing::error!(?err, "lair connect error");
                                continue 'reconnect;
                            }
                            Ok(client) => client,
                        };

                        *inner.lock() = client;

                        tracing::info!("lair reconnect success");

                        break 'reconnect;
                    }
                }
            });
        }

        Ok(MetaLairClient(inner, c_check_send))
    }

    /// Create a MetaLairClient from a LairClient
    pub async fn from_client(client: LairClient) -> LairResult<Self> {
        let inner = Arc::new(Mutex::new(client));
        let (c_check_send, _) = tokio::sync::mpsc::unbounded_channel();
        Ok(MetaLairClient(inner, c_check_send))
    }

    /// Get the raw underlying lair client instance.
    pub fn lair_client(&self) -> LairClient {
        self.0.lock().clone()
    }

    pub(crate) fn cli(&self) -> (LairClient, Esnd) {
        (self.0.lock().clone(), self.1.clone())
    }

    /// Shutdown this keystore client
    pub fn shutdown(&self) -> impl Future<Output = LairResult<()>> + 'static + Send {
        let (client, _esnd) = self.cli();
        async move { client.shutdown().await }
    }

    /// Construct a new randomized signature keypair
    pub fn new_sign_keypair_random(
        &self,
    ) -> impl Future<Output = LairResult<holo_hash::AgentPubKey>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            let tag = nanoid::nanoid!();
            let info = echk!(esnd, client.new_seed(tag.into(), None, false).await);
            let pub_key = holo_hash::AgentPubKey::from_raw_32(info.ed25519_pub_key.0.to_vec());
            Ok(pub_key)
        }
    }

    /// Generate a new signature for given keypair / data
    #[cfg_attr(feature = "instrument", tracing::instrument(skip(self, data)))]
    pub fn sign(
        &self,
        pub_key: holo_hash::AgentPubKey,
        data: Arc<[u8]>,
    ) -> impl Future<Output = LairResult<Signature>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            tokio::time::timeout(std::time::Duration::from_secs(30), async move {
                let mut pub_key_2 = [0; 32];
                pub_key_2.copy_from_slice(pub_key.get_raw_32());
                let sig = echk!(
                    esnd,
                    client.sign_by_pub_key(pub_key_2.into(), None, data).await
                );
                Ok(Signature(*sig.0))
            })
            .await
            .map_err(one_err::OneErr::new)?
        }
    }

    /// Construct a new randomized shared secret, associated with given tag
    pub fn new_shared_secret(
        &self,
        tag: Arc<str>,
    ) -> impl Future<Output = LairResult<()>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            // shared secrets are exportable
            // (it's hard to make them useful otherwise : )
            let exportable = true;
            let _info = echk!(esnd, client.new_seed(tag, None, exportable).await);
            Ok(())
        }
    }

    /// Export a shared secret identified by `tag` using box encryption.
    pub fn shared_secret_export(
        &self,
        tag: Arc<str>,
        sender_pub_key: X25519PubKey,
        recipient_pub_key: X25519PubKey,
    ) -> impl Future<Output = LairResult<([u8; 24], Arc<[u8]>)>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            Ok(echk!(
                esnd,
                client
                    .export_seed_by_tag(tag, sender_pub_key, recipient_pub_key, None)
                    .await
            ))
        }
    }

    /// Retrieve a list of the AgentPubKey values which are stored
    /// in the keystore available for use.
    pub fn list_public_keys(
        &self,
    ) -> impl Future<Output = LairResult<Vec<AgentPubKey>>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            let seed_infos = echk!(esnd, client.list_entries().await);
            Ok(seed_infos
                .into_iter()
                .filter_map(|lair_entry_info| {
                    if let LairEntryInfo::Seed { tag: _, seed_info } = lair_entry_info {
                        Some(AgentPubKey::from_raw_32(seed_info.ed25519_pub_key.to_vec()))
                    } else {
                        None
                    }
                })
                .collect())
        }
    }

    /// Import a shared secret to be indentified by `tag` using box decryption.
    pub fn shared_secret_import(
        &self,
        sender_pub_key: X25519PubKey,
        recipient_pub_key: X25519PubKey,
        nonce: [u8; 24],
        cipher: Arc<[u8]>,
        tag: Arc<str>,
    ) -> impl Future<Output = LairResult<()>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            // shared secrets are exportable
            // (it's hard to make them useful otherwise : )
            let exportable = true;
            let _info = echk!(
                esnd,
                client
                    .import_seed(
                        sender_pub_key,
                        recipient_pub_key,
                        None,
                        nonce,
                        cipher,
                        tag,
                        exportable,
                    )
                    .await
            );
            Ok(())
        }
    }

    /// Encrypt using a shared secret / xsalsa20poly1305 secretbox.
    pub fn shared_secret_encrypt(
        &self,
        tag: Arc<str>,
        data: Arc<[u8]>,
    ) -> impl Future<Output = LairResult<([u8; 24], Arc<[u8]>)>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            Ok(echk!(
                esnd,
                client.secretbox_xsalsa_by_tag(tag, None, data).await
            ))
        }
    }

    /// Decrypt using a shared secret / xsalsa20poly1305 secretbox.
    pub fn shared_secret_decrypt(
        &self,
        tag: Arc<str>,
        nonce: [u8; 24],
        cipher: Arc<[u8]>,
    ) -> impl Future<Output = LairResult<Arc<[u8]>>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            Ok(echk!(
                esnd,
                client
                    .secretbox_xsalsa_open_by_tag(tag, None, nonce, cipher)
                    .await
            ))
        }
    }

    /// Construct a new randomized encryption keypair
    pub fn new_x25519_keypair_random(
        &self,
    ) -> impl Future<Output = LairResult<X25519PubKey>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            let tag = nanoid::nanoid!();
            let info = echk!(esnd, client.new_seed(tag.into(), None, false).await);
            let pub_key = info.x25519_pub_key;
            Ok(pub_key)
        }
    }

    /// Encrypt an authenticated "box"ed message to a specific recipient.
    pub fn crypto_box_xsalsa(
        &self,
        sender_pub_key: X25519PubKey,
        recipient_pub_key: X25519PubKey,
        data: Arc<[u8]>,
    ) -> impl Future<Output = LairResult<([u8; 24], Arc<[u8]>)>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            Ok(echk!(
                esnd,
                client
                    .crypto_box_xsalsa_by_pub_key(sender_pub_key, recipient_pub_key, None, data)
                    .await
            ))
        }
    }

    /// Decrypt an authenticated "box"ed message from a specific sender.
    pub fn crypto_box_xsalsa_open(
        &self,
        sender_pub_key: X25519PubKey,
        recipient_pub_key: X25519PubKey,
        nonce: [u8; 24],
        data: Arc<[u8]>,
    ) -> impl Future<Output = LairResult<Arc<[u8]>>> + 'static + Send {
        let (client, esnd) = self.cli();
        async move {
            Ok(echk!(
                esnd,
                client
                    .crypto_box_xsalsa_open_by_pub_key(
                        sender_pub_key,
                        recipient_pub_key,
                        None,
                        nonce,
                        data,
                    )
                    .await
            ))
        }
    }

    /// Get a tls cert from lair for use in conductor
    pub fn get_or_create_tls_cert_by_tag(
        &self,
        tag: Arc<str>,
    ) -> impl Future<Output = LairResult<(CertDigest, Arc<[u8]>, sodoken::LockedArray)>> + 'static + Send
    {
        let (client, esnd) = self.cli();
        async move {
            // don't echk! this top one, it may be a valid error
            let info = match client.get_entry(tag.clone()).await {
                Ok(info) => match info {
                    LairEntryInfo::WkaTlsCert { cert_info, .. } => cert_info,
                    oth => {
                        return Err(
                            format!("invalid entry type, expecting wka tls cert: {oth:?}").into(),
                        )
                    }
                },
                Err(_) => {
                    let esnd = esnd.clone();
                    echk!(esnd, client.new_wka_tls_cert(tag.clone()).await)
                }
            };
            let pk = echk!(esnd, client.get_wka_tls_cert_priv_key(tag).await);

            Ok((info.digest, info.cert.to_vec().into(), pk))
        }
    }
}