Skip to main content

solvela_client_cli_args/
lib.rs

1//! Shared CLI argument structs and wallet loading for `SolvelaClient` binaries.
2//!
3//! Provides reusable [`clap::Args`] groups (`WalletArgs`, `GatewayArgs`, `RpcArgs`)
4//! and helper functions for wallet file I/O so that the proxy and CLI binaries
5//! share identical wallet-loading logic.
6
7use std::path::PathBuf;
8
9use clap::Args;
10
11use solvela_client::Wallet;
12
13/// CLI arguments for wallet configuration.
14#[derive(Debug, Clone, Args)]
15pub struct WalletArgs {
16    /// Environment variable containing a base58-encoded keypair.
17    #[arg(long, default_value = "SOLVELA_WALLET_KEY")]
18    pub wallet_env: String,
19
20    /// Path to wallet keypair file (Solana CLI JSON byte-array format).
21    #[arg(long, default_value = "~/.solvela/wallet.json")]
22    pub wallet_file: String,
23}
24
25/// CLI arguments for gateway connection.
26#[derive(Debug, Clone, Args)]
27pub struct GatewayArgs {
28    /// Gateway URL to forward requests to.
29    #[arg(short = 'g', long, default_value = "https://api.solvela.ai")]
30    pub gateway: String,
31}
32
33/// CLI arguments for Solana RPC connection.
34#[derive(Debug, Clone, Args)]
35pub struct RpcArgs {
36    /// Solana RPC URL.
37    #[arg(long, default_value = "https://api.mainnet-beta.solana.com")]
38    pub rpc_url: String,
39}
40
41/// Expand a leading `~` in a path to the user's home directory.
42///
43/// If the path does not start with `~/`, it is returned as-is.
44#[must_use]
45pub fn expand_home(path: &str) -> PathBuf {
46    if let Some(rest) = path.strip_prefix("~/") {
47        match dirs::home_dir() {
48            Some(home) => home.join(rest),
49            None => PathBuf::from(path),
50        }
51    } else {
52        PathBuf::from(path)
53    }
54}
55
56/// Load a wallet from an environment variable (priority) or file (fallback).
57///
58/// The env var is expected to contain a base58-encoded 64-byte keypair.
59/// The file is expected to be in Solana CLI JSON byte-array format (`[174, 47, ...]`).
60///
61/// # Errors
62///
63/// Returns a human-readable error string if neither source yields a valid wallet.
64pub fn load_wallet(args: &WalletArgs) -> Result<Wallet, String> {
65    // Try env var first
66    if let Ok(val) = std::env::var(&args.wallet_env) {
67        if !val.is_empty() {
68            return Wallet::from_keypair_b58(&val)
69                .map_err(|e| format!("invalid keypair in {}: {e}", args.wallet_env));
70        }
71    }
72
73    // Expand ~ to home directory
74    let expanded = expand_home(&args.wallet_file);
75
76    // Try wallet file
77    if expanded.exists() {
78        // Warn if wallet file has insecure permissions (private key exposure risk)
79        #[cfg(unix)]
80        {
81            use std::os::unix::fs::MetadataExt;
82            if let Ok(meta) = expanded.metadata() {
83                if meta.mode() & 0o077 != 0 {
84                    tracing::warn!(
85                        path = %expanded.display(),
86                        "wallet file has insecure permissions (should be 0600)"
87                    );
88                }
89            }
90        }
91
92        let contents = std::fs::read_to_string(&expanded)
93            .map_err(|e| format!("failed to read {}: {e}", expanded.display()))?;
94
95        // Parse Solana CLI format: JSON array of u8 values [174, 47, ...]
96        let bytes: Vec<u8> = serde_json::from_str(&contents)
97            .map_err(|e| format!("invalid wallet file format in {}: {e}", expanded.display()))?;
98
99        return Wallet::from_keypair_bytes(&bytes)
100            .map_err(|e| format!("invalid keypair in {}: {e}", expanded.display()));
101    }
102
103    Err(format!(
104        "no wallet found: set {} env var or create {}",
105        args.wallet_env,
106        expanded.display()
107    ))
108}
109
110/// Save raw keypair bytes to a file in Solana CLI JSON byte-array format.
111///
112/// The file is written with `0o600` permissions (owner read/write only).
113/// Refuses to overwrite an existing file unless `force` is `true`.
114///
115/// # Errors
116///
117/// Returns a human-readable error string if the file cannot be written or
118/// already exists without `force`.
119pub fn save_wallet(path: &str, keypair_bytes: &[u8], force: bool) -> Result<PathBuf, String> {
120    let expanded = expand_home(path);
121
122    if expanded.exists() && !force {
123        return Err(format!(
124            "wallet file already exists at {} (use --force to overwrite)",
125            expanded.display()
126        ));
127    }
128
129    // Fail closed on platforms where we cannot enforce owner-only ACLs at
130    // file-create time. The previous behavior (write + tracing::warn!) left
131    // the keypair on disk with whatever default ACL the platform applied —
132    // potentially world-readable on shared hosts. See issue #322 problem 2.
133    #[cfg(not(unix))]
134    {
135        let _ = keypair_bytes;
136        return Err(format!(
137            "refusing to write wallet file at {}: owner-only ACL enforcement \
138             is not implemented on this platform. Set the SOLVELA_WALLET_KEY \
139             env var with a base58-encoded keypair instead, or run on a Unix host.",
140            expanded.display()
141        ));
142    }
143
144    // Ensure parent directory exists
145    #[cfg(unix)]
146    if let Some(parent) = expanded.parent() {
147        std::fs::create_dir_all(parent)
148            .map_err(|e| format!("failed to create directory {}: {e}", parent.display()))?;
149    }
150
151    // Serialize as JSON byte array (Solana CLI format) and write with
152    // owner-only permissions. Reached only on Unix — the non-Unix branch
153    // above returned Err.
154    #[cfg(unix)]
155    {
156        use std::io::Write;
157        use std::os::unix::fs::OpenOptionsExt;
158        let json = serde_json::to_string(&keypair_bytes)
159            .map_err(|e| format!("failed to serialize keypair: {e}"))?;
160        // Restrict permissions at create time so there's no window in which
161        // the file is world-readable before chmod.
162        let mut file = std::fs::OpenOptions::new()
163            .write(true)
164            .create(true)
165            .truncate(true)
166            .mode(0o600)
167            .open(&expanded)
168            .map_err(|e| format!("failed to create {}: {e}", expanded.display()))?;
169        file.write_all(json.as_bytes())
170            .map_err(|e| format!("failed to write {}: {e}", expanded.display()))?;
171        Ok(expanded)
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use solana_sdk::signer::Signer;
178
179    use super::*;
180
181    #[test]
182    fn test_expand_home_with_tilde() {
183        let result = expand_home("~/some/path");
184        // Should NOT start with ~ (it should be expanded)
185        assert!(
186            !result.to_string_lossy().starts_with('~'),
187            "path was not expanded: {result:?}"
188        );
189        assert!(
190            result.to_string_lossy().ends_with("some/path"),
191            "path suffix missing: {result:?}"
192        );
193    }
194
195    #[test]
196    fn test_expand_home_without_tilde() {
197        let result = expand_home("/absolute/path");
198        assert_eq!(result, PathBuf::from("/absolute/path"));
199
200        let relative = expand_home("relative/path");
201        assert_eq!(relative, PathBuf::from("relative/path"));
202    }
203
204    #[test]
205    fn test_load_wallet_from_env() {
206        // Generate a fresh keypair and encode as base58
207        let kp = solana_sdk::signer::keypair::Keypair::new();
208        let b58 = bs58::encode(kp.to_bytes()).into_string();
209        let expected_addr = kp.pubkey().to_string();
210
211        // Use a unique env var name to avoid conflicts with parallel tests
212        let env_var = "SOLVELA_TEST_WALLET_LOAD_ENV_7291";
213        std::env::set_var(env_var, &b58);
214
215        let args = WalletArgs {
216            wallet_env: env_var.to_string(),
217            wallet_file: "/nonexistent/path.json".to_string(),
218        };
219
220        let wallet = load_wallet(&args).expect("should load from env");
221        assert_eq!(wallet.address(), expected_addr);
222
223        // Clean up
224        std::env::remove_var(env_var);
225    }
226
227    #[test]
228    fn test_load_wallet_no_source() {
229        // Ensure env var is not set
230        let env_var = "SOLVELA_TEST_WALLET_NOSOURCE_4821";
231        std::env::remove_var(env_var);
232
233        let args = WalletArgs {
234            wallet_env: env_var.to_string(),
235            wallet_file: "/nonexistent/wallet_file_that_does_not_exist.json".to_string(),
236        };
237
238        let result = load_wallet(&args);
239        assert!(result.is_err());
240        let err = result.unwrap_err();
241        assert!(
242            err.contains("no wallet found"),
243            "unexpected error message: {err}"
244        );
245    }
246
247    #[test]
248    fn test_save_wallet_creates_file() {
249        let dir = std::env::temp_dir().join("solvela_test_save_wallet");
250        let _ = std::fs::remove_dir_all(&dir);
251        std::fs::create_dir_all(&dir).unwrap();
252
253        let kp = solana_sdk::signer::keypair::Keypair::new();
254        let bytes = kp.to_bytes();
255        let file_path = dir.join("test_wallet.json");
256        let path_str = file_path.to_string_lossy().to_string();
257
258        let result = save_wallet(&path_str, &bytes, false);
259        assert!(result.is_ok(), "save_wallet failed: {result:?}");
260
261        let saved_path = result.unwrap();
262        assert!(saved_path.exists());
263
264        // Verify the saved content is valid Solana CLI format
265        let contents = std::fs::read_to_string(&saved_path).unwrap();
266        let parsed: Vec<u8> = serde_json::from_str(&contents).unwrap();
267        assert_eq!(parsed.len(), 64);
268        assert_eq!(&parsed[..], &bytes[..]);
269
270        // Verify permissions on Unix
271        #[cfg(unix)]
272        {
273            use std::os::unix::fs::MetadataExt;
274            let meta = saved_path.metadata().unwrap();
275            assert_eq!(meta.mode() & 0o777, 0o600, "permissions should be 0600");
276        }
277
278        // Clean up
279        let _ = std::fs::remove_dir_all(&dir);
280    }
281
282    #[test]
283    fn test_save_wallet_refuses_overwrite() {
284        let dir = std::env::temp_dir().join("solvela_test_save_overwrite");
285        let _ = std::fs::remove_dir_all(&dir);
286        std::fs::create_dir_all(&dir).unwrap();
287
288        let kp = solana_sdk::signer::keypair::Keypair::new();
289        let bytes = kp.to_bytes();
290        let file_path = dir.join("existing_wallet.json");
291        let path_str = file_path.to_string_lossy().to_string();
292
293        // Create the file first
294        save_wallet(&path_str, &bytes, false).unwrap();
295
296        // Attempt to overwrite without force — should fail
297        let result = save_wallet(&path_str, &bytes, false);
298        assert!(result.is_err());
299        let err = result.unwrap_err();
300        assert!(err.contains("already exists"), "unexpected error: {err}");
301
302        // With force — should succeed
303        let result = save_wallet(&path_str, &bytes, true);
304        assert!(result.is_ok(), "force overwrite failed: {result:?}");
305
306        // Clean up
307        let _ = std::fs::remove_dir_all(&dir);
308    }
309}