Skip to main content

hashiverse_cli/
unlock.rs

1//! Deciding how to unlock an identity, and then unlocking it.
2//!
3//! Everything comes from the environment; the CLI never prompts for secrets.
4//!
5//! Resolution (see [`resolve_unlock_method`]):
6//! - Neither `HASHIVERSE_KEYPHRASE` nor `HASHIVERSE_PROFILE` set → read-only guest (the empty
7//!   keyphrase, [`GUEST_CLIENT_ID`]). Reading posts and trending hashtags needs no identity;
8//!   [`crate::commands::post`] refuses for guests.
9//! - Both set → error: they name potentially different identities.
10//! - Exactly one set → `HASHIVERSE_PASSWORD` must also be set (an empty value is allowed, but
11//!   the variable must exist), otherwise it is an error.
12//!   - `HASHIVERSE_KEYPHRASE` → derive the key from the keyphrase and save it
13//!     to the data dir encrypted with the password, so later runs can use `HASHIVERSE_PROFILE`.
14//!   - `HASHIVERSE_PROFILE` / `--profile` → load that stored key, decrypting with the password.
15
16use anyhow::{anyhow, Result};
17use hashiverse_client_rust::{Hashiverse, HashiverseBuilder};
18use hashiverse_lib::client::hashiverse_client::HashiverseClient;
19use hashiverse_lib::client::key_locker::key_locker::GUEST_CLIENT_ID;
20
21use crate::cli_args::{CliArgs, ENV_KEYPHRASE, ENV_PASSWORD, ENV_PROFILE};
22
23#[derive(Debug, PartialEq, Eq)]
24pub enum UnlockMethod {
25    Keyphrase { key_phrase: String, password: String },
26    StoredKey { client_id_hex: String, password: String },
27    Guest,
28}
29
30pub fn is_guest(hashiverse_client: &HashiverseClient) -> bool {
31    hashiverse_client.client_id().id_hex() == GUEST_CLIENT_ID
32}
33
34fn non_empty_trimmed(value: Option<String>) -> Option<String> {
35    value.map(|value| value.trim().to_string()).filter(|value| !value.is_empty())
36}
37
38pub fn resolve_unlock_method(profile: Option<String>, keyphrase_env: Option<String>, password_env: Option<String>) -> Result<UnlockMethod> {
39    let keyphrase_env = non_empty_trimmed(keyphrase_env);
40    let profile = non_empty_trimmed(profile);
41
42    if keyphrase_env.is_none() && profile.is_none() {
43        return Ok(UnlockMethod::Guest);
44    }
45    if keyphrase_env.is_some() && profile.is_some() {
46        return Err(anyhow!("set only one of {} or {}, not both", ENV_KEYPHRASE, ENV_PROFILE));
47    }
48
49    // Passwords are not trimmed (surrounding whitespace may be deliberate) and may be empty;
50    // only an absent variable is an error.
51    let password = password_env.ok_or_else(|| anyhow!("{} must be set when {} or {} is set", ENV_PASSWORD, ENV_KEYPHRASE, ENV_PROFILE))?;
52
53    match (keyphrase_env, profile) {
54        (Some(key_phrase), None) => Ok(UnlockMethod::Keyphrase { key_phrase, password }),
55        (None, Some(client_id_hex)) => Ok(UnlockMethod::StoredKey { client_id_hex, password }),
56        _ => unreachable!("guest and both-set cases handled above"),
57    }
58}
59
60/// Builds a [`Hashiverse`] client for the resolved identity.
61pub async fn unlock(cli_args: &CliArgs, unlock_method: UnlockMethod) -> Result<Hashiverse> {
62    let mut hashiverse_builder = HashiverseBuilder::new();
63    if let Some(data_dir) = &cli_args.data_dir {
64        hashiverse_builder = hashiverse_builder.data_dir(data_dir.clone());
65    }
66    if !cli_args.bootstrap.is_empty() {
67        hashiverse_builder = hashiverse_builder.bootstrap(cli_args.bootstrap.clone());
68    }
69
70    match unlock_method {
71        UnlockMethod::Keyphrase { key_phrase, password } => hashiverse_builder.passphrase(password).build_with_keyphrase(key_phrase).await,
72        UnlockMethod::StoredKey { client_id_hex, password } => hashiverse_builder.passphrase(password).build_from_stored_key(client_id_hex).await,
73        UnlockMethod::Guest => hashiverse_builder.build_with_keyphrase("").await,
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    fn some(value: &str) -> Option<String> {
82        Some(value.to_string())
83    }
84
85    #[test]
86    fn nothing_supplied_is_guest() {
87        assert_eq!(resolve_unlock_method(None, None, None).unwrap(), UnlockMethod::Guest);
88    }
89
90    #[test]
91    fn password_alone_is_still_guest() {
92        assert_eq!(resolve_unlock_method(None, None, some("pw")).unwrap(), UnlockMethod::Guest);
93    }
94
95    #[test]
96    fn blank_keyphrase_and_profile_are_guest() {
97        assert_eq!(resolve_unlock_method(some("  "), some(""), None).unwrap(), UnlockMethod::Guest);
98    }
99
100    #[test]
101    fn keyphrase_with_password() {
102        assert_eq!(resolve_unlock_method(None, some("correct horse"), some("pw")).unwrap(), UnlockMethod::Keyphrase { key_phrase: "correct horse".to_string(), password: "pw".to_string() });
103    }
104
105    #[test]
106    fn profile_with_password() {
107        assert_eq!(resolve_unlock_method(some(" abcd "), None, some("pw")).unwrap(), UnlockMethod::StoredKey { client_id_hex: "abcd".to_string(), password: "pw".to_string() });
108    }
109
110    #[test]
111    fn keyphrase_and_profile_together_error() {
112        let error = resolve_unlock_method(some("abcd"), some("correct horse"), some("pw")).unwrap_err();
113        assert!(error.to_string().contains(ENV_KEYPHRASE) && error.to_string().contains(ENV_PROFILE));
114        // The conflict is reported even without a password, rather than the missing password.
115        let error = resolve_unlock_method(some("abcd"), some("correct horse"), None).unwrap_err();
116        assert!(error.to_string().contains("not both"));
117    }
118
119    #[test]
120    fn password_is_not_trimmed() {
121        assert_eq!(resolve_unlock_method(some("abcd"), None, some(" pw ")).unwrap(), UnlockMethod::StoredKey { client_id_hex: "abcd".to_string(), password: " pw ".to_string() });
122    }
123
124    #[test]
125    fn keyphrase_without_password_errors() {
126        let error = resolve_unlock_method(None, some("correct horse"), None).unwrap_err();
127        assert!(error.to_string().contains(ENV_PASSWORD));
128    }
129
130    #[test]
131    fn profile_without_password_errors() {
132        let error = resolve_unlock_method(some("abcd"), None, None).unwrap_err();
133        assert!(error.to_string().contains(ENV_PASSWORD));
134    }
135
136    #[test]
137    fn empty_password_is_allowed_when_set() {
138        assert_eq!(resolve_unlock_method(some("abcd"), None, some("")).unwrap(), UnlockMethod::StoredKey { client_id_hex: "abcd".to_string(), password: String::new() });
139        assert_eq!(resolve_unlock_method(None, some("correct horse"), some("")).unwrap(), UnlockMethod::Keyphrase { key_phrase: "correct horse".to_string(), password: String::new() });
140    }
141
142    #[tokio::test]
143    async fn empty_keyphrase_is_the_guest_identity() {
144        use hashiverse_lib::client::key_locker::disk_key_locker::DiskKeyLockerManager;
145        use hashiverse_lib::client::key_locker::key_locker::{KeyLocker, KeyLockerManager};
146
147        let (_temp_dir, temp_dir_path) = hashiverse_lib::tools::tools::get_temp_dir().unwrap();
148        let key_locker_manager = DiskKeyLockerManager::with_data_dir(std::path::PathBuf::from(temp_dir_path), String::new()).unwrap();
149        let guest_key_locker = key_locker_manager.create(String::new()).await.unwrap();
150        assert_eq!(guest_key_locker.client_id().id_hex(), GUEST_CLIENT_ID);
151        assert!(key_locker_manager.list().await.unwrap().is_empty(), "guest key must not show up as a stored profile");
152    }
153
154    // Exercises the real on-disk key locker: a keyphrase unlock stores the key, and a
155    // subsequent stored-key unlock with the same password recovers the same identity.
156    #[tokio::test]
157    async fn keyphrase_then_stored_key_roundtrip_on_disk() {
158        use hashiverse_lib::client::key_locker::disk_key_locker::DiskKeyLockerManager;
159        use hashiverse_lib::client::key_locker::key_locker::{KeyLocker, KeyLockerManager};
160
161        let (_temp_dir, temp_dir_path) = hashiverse_lib::tools::tools::get_temp_dir().unwrap();
162        let data_dir = std::path::PathBuf::from(temp_dir_path);
163
164        let key_locker_manager = DiskKeyLockerManager::with_data_dir(data_dir.clone(), "pw".to_string()).unwrap();
165        let created_key_locker = key_locker_manager.create("correct horse battery staple".to_string()).await.unwrap();
166        let client_id_hex = created_key_locker.client_id().id_hex();
167
168        let reloaded_key_locker_manager = DiskKeyLockerManager::with_data_dir(data_dir.clone(), "pw".to_string()).unwrap();
169        let reloaded_key_locker = reloaded_key_locker_manager.switch(client_id_hex.clone()).await.unwrap();
170        assert_eq!(reloaded_key_locker.client_id().id_hex(), client_id_hex);
171
172        let wrong_password_key_locker_manager = DiskKeyLockerManager::with_data_dir(data_dir, "wrong".to_string()).unwrap();
173        assert!(wrong_password_key_locker_manager.switch(client_id_hex).await.is_err());
174    }
175}