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
#![deny(missing_docs)]
#![deny(warnings)]
//! client connector to secret lair private keystore

include!(concat!(env!("OUT_DIR"), "/ver.rs"));

use lair_keystore_api::actor::*;
use lair_keystore_api::*;
use std::sync::Arc;
use tracing::*;

pub mod internal;

macro_rules! e {
    ($e:expr) => {{
        match $e {
            Ok(r) => Ok(r),
            Err(e) => {
                error!(
                    error = ?e,
                    file = file!(),
                    line = line!(),
                );
                Err(e)
            }
        }
    }};
}

/// If a lair executable is already running, connect to it.
/// If it is not, attempt to run and disown one into the background.
/// Note, it is still preferable for lair to be executed / managed
/// as a system service, but this provides a quick up-and-running
/// experience.
pub async fn assert_running_lair_and_connect(
    config: Arc<Config>,
    passphrase: sodoken::BufRead,
) -> LairResult<ghost_actor::GhostSender<LairClientApi>> {
    // step 1 - just try to connect
    if let Ok(r) =
        e!(check_ipc_connect(config.clone(), passphrase.clone()).await)
    {
        trace!("first try check Ok");
        return Ok(r);
    }

    // step 2 - try to execute the lair executable
    if let Ok(mut proc) =
        e!(internal::run_lair_executable(config.clone()).await)
    {
        // step 2.1 - if the executable ran, try to connect to it.
        if let Ok(r) =
            e!(check_ipc_connect(config.clone(), passphrase.clone()).await)
        {
            trace!("second try (run executable) check Ok");
            return Ok(r);
        }

        // couldn't connect... kill it
        proc.kill().map_err(LairError::other)?;
    }

    // step 3 - try to build the lair executable using cargo
    e!(internal::cargo_build_lair_executable())?;

    // step 3.1 - now run it
    let mut proc = internal::run_lair_executable(config.clone()).await?;

    // step 3.2 - if the executable ran, try to connect to it.
    if let Ok(r) = e!(check_ipc_connect(config, passphrase.clone()).await) {
        trace!("third try (build executable) check Ok");
        return Ok(r);
    }

    // couldn't connect... kill it
    proc.kill().map_err(LairError::other)?;

    Err("could not execute / connect to lair process".into())
}

async fn check_ipc_connect(
    config: Arc<Config>,
    passphrase: sodoken::BufRead,
) -> LairResult<ghost_actor::GhostSender<LairClientApi>> {
    let api = ipc::spawn_client_ipc(config, passphrase).await?;

    trace!("send check server info");
    let srv_info = api.lair_get_server_info().await?;
    trace!(?srv_info, "got check server info");

    if srv_info.version != LAIR_VER {
        return Err(format!(
            "version mismatch, expected {}, got {}",
            LAIR_VER, srv_info.version,
        )
        .into());
    }

    Ok(api)
}

#[cfg(test)]
#[cfg(feature = "bin-tests")]
mod bin_tests {
    use super::*;

    fn init_tracing() {
        let _ = subscriber::set_global_default(
            tracing_subscriber::FmtSubscriber::builder()
                .with_env_filter(
                    tracing_subscriber::EnvFilter::from_default_env(),
                )
                .finish(),
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn basic_running_connect() -> LairResult<()> {
        init_tracing();

        let tmpdir = tempfile::tempdir().unwrap();
        std::env::set_var("LAIR_DIR", tmpdir.path());

        trace!(lair_dir = ?tmpdir.path(), "RUNNING WITH LAIR_DIR");

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

        trace!("running executable...");
        let mut child = internal::run_lair_executable(config.clone()).await?;
        trace!("executable running.");

        let passphrase = sodoken::BufRead::new_no_lock(b"passphrase");

        trace!("connecting...");
        let api = assert_running_lair_and_connect(config, passphrase).await?;
        trace!("connected.");

        trace!("checking version...");
        let srv_info = api.lair_get_server_info().await?;
        assert_eq!(LAIR_VER, srv_info.version);
        trace!("version checked.");

        trace!("killing executable...");
        child.kill().unwrap();
        trace!("executable killed.");

        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn restart_server_encryption_checks() -> LairResult<()> {
        init_tracing();

        let tmpdir = tempfile::tempdir().unwrap();
        std::env::set_var("LAIR_DIR", tmpdir.path());

        trace!(lair_dir = ?tmpdir.path(), "RUNNING WITH LAIR_DIR");

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

        let passphrase_good = sodoken::BufRead::new_no_lock(b"passphrase");
        let passphrase_bad = sodoken::BufRead::new_no_lock(b"passphr4se");

        let check = |passphrase| async {
            let api =
                assert_running_lair_and_connect(config.clone(), passphrase)
                    .await?;
            api.sign_ed25519_new_from_entropy().await?;
            let this_key = api.sign_ed25519_get(1.into()).await?;

            LairResult::Ok(this_key)
        };

        let run_and_check = |passphrase: sodoken::BufRead,
                             mut check_key: Option<
            lair_keystore_api::internal::sign_ed25519::SignEd25519PubKey,
        >| async move {
            println!("--start lair server--");
            let mut child =
                internal::run_lair_executable(config.clone()).await.unwrap();
            println!("--lair server started--");

            let mut all = Vec::new();
            for _ in 0..3 {
                all.push(check(passphrase.clone()));
            }
            for key in futures::future::try_join_all(all).await.unwrap() {
                if check_key.is_none() {
                    check_key = Some(key);
                } else {
                    assert_eq!(check_key.as_ref().unwrap(), &key);
                }
            }

            println!("--kill lair server--");
            child.kill().unwrap();
            println!("--lair server killed--");

            check_key
        };

        println!("--first check--");
        run_and_check(passphrase_good.clone(), None).await;
        println!("--second check--");
        run_and_check(passphrase_good.clone(), None).await;
        println!("--done--");

        println!("--start lair server--");
        let mut child =
            internal::run_lair_executable(config.clone()).await.unwrap();
        println!("--lair server started--");
        assert!(check_ipc_connect(config.clone(), passphrase_bad)
            .await
            .is_err());
        println!("--kill lair server--");
        child.kill().unwrap();
        println!("--lair server killed--");

        Ok(())
    }
}