Skip to main content

taskfast_agent/
keystore.rs

1// SPDX-License-Identifier: MIT
2//! Encrypted wallet persistence.
3//!
4//! Default: Web3 Secret Storage v3 JSON (Foundry/Geth/MetaMask-interoperable),
5//! resolved under `$XDG_DATA_HOME/taskfast/wallets/` so a wallet generated here
6//! can be imported by `cast wallet import` without conversion.
7//!
8//! This module owns two concerns and nothing else:
9//!
10//! 1. Path resolution — XDG-compliant directory layout with `0700` perms on
11//!    the containing dir and `0600` perms on the keyfile.
12//! 2. Encrypt/decrypt — thin wrappers around
13//!    `PrivateKeySigner::encrypt_keystore` / `decrypt_keystore`, which
14//!    delegate to `eth-keystore` for the scrypt+AES-128-CTR pipeline.
15//!
16//! # Future: OS keychain
17//!
18//! `KeySource::Keychain` is reserved but not yet implemented. When it lands,
19//! it'll go behind a `keyring` cargo feature so the default build has no
20//! dbus/secret-service transitive deps. CLI sandboxes that need portable
21//! persistence should use the file backend; keychain support is targeted at
22//! interactive dev boxes.
23
24use std::fs;
25use std::path::{Path, PathBuf};
26
27use alloy_primitives::Address;
28use alloy_signer_local::PrivateKeySigner;
29use thiserror::Error as ThisError;
30
31/// Where a wallet private key is (or will be) stored.
32///
33/// Kept as an enum rather than a boolean flag so the CLI's `--keystore` /
34/// `--keychain` flags can desugar into a discriminated choice that the
35/// lower layers (and tests) can match on. Adding a `Keychain` variant
36/// later is additive: existing `File` users keep working.
37#[derive(Debug, Clone)]
38pub enum KeySource {
39    /// Encrypted JSON v3 at an explicit path (or resolved via
40    /// [`default_keyfile_path`]).
41    File { path: PathBuf },
42    // Keychain { service: String, account: String } — deferred behind a
43    // future `keyring` cargo feature; see module docs.
44}
45
46#[derive(Debug, ThisError)]
47pub enum KeystoreError {
48    #[error("home directory not found; set $HOME or $XDG_DATA_HOME")]
49    HomeNotFound,
50    #[error("failed to create keystore dir {path}: {source}")]
51    CreateDir {
52        path: PathBuf,
53        #[source]
54        source: std::io::Error,
55    },
56    #[error("keystore file not found: {0}")]
57    NotFound(PathBuf),
58    #[error("signer/keystore error: {0}")]
59    Signer(String),
60    #[error("I/O error: {0}")]
61    Io(#[from] std::io::Error),
62}
63
64/// Returns `$XDG_DATA_HOME/taskfast/wallets`, falling back to
65/// `$HOME/.local/share/taskfast/wallets` when XDG is unset.
66///
67/// Creates the directory if it doesn't exist and tightens perms to `0700`
68/// on unix. Keystore files are written `0600` after the fact by
69/// [`save_signer`].
70pub fn default_keystore_dir() -> Result<PathBuf, KeystoreError> {
71    let base = match std::env::var("XDG_DATA_HOME") {
72        Ok(xdg) if !xdg.is_empty() => PathBuf::from(xdg),
73        _ => home_fallback()?,
74    };
75    let dir = base.join("taskfast").join("wallets");
76    ensure_dir(&dir)?;
77    Ok(dir)
78}
79
80fn home_fallback() -> Result<PathBuf, KeystoreError> {
81    // XDG spec §4: when $XDG_DATA_HOME is unset/empty, default to
82    // $HOME/.local/share.
83    std::env::var_os("HOME")
84        .filter(|s| !s.is_empty())
85        .map(|home| PathBuf::from(home).join(".local").join("share"))
86        .ok_or(KeystoreError::HomeNotFound)
87}
88
89fn ensure_dir(dir: &Path) -> Result<(), KeystoreError> {
90    fs::create_dir_all(dir).map_err(|source| KeystoreError::CreateDir {
91        path: dir.to_path_buf(),
92        source,
93    })?;
94    // `0700` — private to the owner. No-op on non-unix; Windows ACLs are
95    // the OS-native equivalent and out of scope here.
96    #[cfg(unix)]
97    {
98        use std::os::unix::fs::PermissionsExt;
99        let mut perms = fs::metadata(dir)?.permissions();
100        perms.set_mode(0o700);
101        fs::set_permissions(dir, perms)?;
102    }
103    Ok(())
104}
105
106/// Canonical filename for a wallet keyed by its address: lowercase hex,
107/// no `0x` prefix, `.json` suffix. Matches the shape `cast wallet import`
108/// produces when given `--keystore-dir` without an explicit name.
109pub fn default_keyfile_name(address: Address) -> String {
110    let hex = hex::encode(address.as_slice());
111    format!("{hex}.json")
112}
113
114/// Resolves the default keyfile path for a given address under the default
115/// keystore dir.
116pub fn default_keyfile_path(address: Address) -> Result<PathBuf, KeystoreError> {
117    Ok(default_keystore_dir()?.join(default_keyfile_name(address)))
118}
119
120/// Encrypts `signer` with `password` and writes it to `path`, creating parent
121/// directories as needed. Overwrites any existing file at the same path —
122/// callers wanting idempotency should check [`Path::exists`] first.
123///
124/// On unix the final file is chmod'd to `0600`. Returns the absolute path
125/// actually written.
126pub fn save_signer(
127    signer: &PrivateKeySigner,
128    path: &Path,
129    password: &str,
130) -> Result<PathBuf, KeystoreError> {
131    let parent = path
132        .parent()
133        .ok_or_else(|| KeystoreError::NotFound(path.to_path_buf()))?;
134    ensure_dir(parent)?;
135
136    let file_name = path
137        .file_name()
138        .and_then(|s| s.to_str())
139        .ok_or_else(|| KeystoreError::NotFound(path.to_path_buf()))?;
140
141    let written = parent.join(file_name);
142
143    // Pre-create the target at `0600` *before* eth-keystore writes the
144    // ciphertext. eth-keystore (0.5.0) writes via `File::create(dir/name)`,
145    // whose `0o666` mode is honored only when the inode is *created* — so it
146    // reopens this existing `0600` inode and rewrites without widening the
147    // mode. Relying on the post-write chmod alone leaves a window where the
148    // encrypted key is `0o666 & ~umask` (e.g. `0664` under `umask 002`) and
149    // world-readable. See gh#78.
150    //
151    // Note: no `.truncate(true)` here on purpose. Truncating would wipe an
152    // existing keystore before `encrypt_keystore` writes the new ciphertext,
153    // so a crash in between would leave an empty file and destroy recoverable
154    // key material. `encrypt_keystore` performs its own truncate-on-write.
155    #[cfg(unix)]
156    {
157        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
158        let f = fs::OpenOptions::new()
159            .write(true)
160            .create(true)
161            .truncate(false) // deliberate: don't wipe an existing keystore (see above)
162            .mode(0o600)
163            .open(&written)?;
164        // `.mode()` is a no-op when the file already existed (e.g. a stale
165        // `0664` keystore from an older build); tighten it explicitly so the
166        // overwrite path repairs broad perms too.
167        let mut perms = f.metadata()?.permissions();
168        perms.set_mode(0o600);
169        f.set_permissions(perms)?;
170    }
171
172    let mut rng = rand::thread_rng();
173    // `encrypt_keystore` writes `{parent}/{name}` via eth-keystore's
174    // scrypt + AES-128-CTR pipeline. We pass the already-generated key's
175    // bytes so the saved file corresponds to an existing signer.
176    let pk_bytes = signer.to_bytes();
177    PrivateKeySigner::encrypt_keystore(parent, &mut rng, pk_bytes, password, Some(file_name))
178        .map_err(|e| KeystoreError::Signer(e.to_string()))?;
179
180    // Backstop: re-assert `0600` after the write in case a future
181    // eth-keystore changes its write strategy (e.g. temp-file + rename,
182    // which would bypass the pre-created inode above).
183    #[cfg(unix)]
184    {
185        use std::os::unix::fs::PermissionsExt;
186        let mut perms = fs::metadata(&written)?.permissions();
187        perms.set_mode(0o600);
188        fs::set_permissions(&written, perms)?;
189    }
190    Ok(written)
191}
192
193/// Generates a fresh random signer, encrypts it, writes it to the default
194/// path for its address, and returns `(signer, path)`. The most common init
195/// flow: `taskfast init --generate-wallet`.
196pub fn generate_and_save(password: &str) -> Result<(PrivateKeySigner, PathBuf), KeystoreError> {
197    let signer = PrivateKeySigner::random();
198    let path = default_keyfile_path(signer.address())?;
199    save_signer(&signer, &path, password)?;
200    Ok((signer, path))
201}
202
203/// True when `mode`'s group/other bits are set — i.e. the file is readable
204/// (or writable) by anyone but the owner. `0o600` and `0o400` are tight;
205/// `0o640`/`0o664`/`0o644` are not.
206#[cfg(unix)]
207fn mode_is_too_open(mode: u32) -> bool {
208    mode & 0o077 != 0
209}
210
211/// Decrypts the keystore at `path` with `password` and returns the signer.
212///
213/// On unix, warns (does not repair — a read shouldn't silently mutate file
214/// modes) when the keystore is group/world-accessible, so a leak written by
215/// an older build or another tool is surfaced rather than ignored (gh#78).
216pub fn load_signer(path: &Path, password: &str) -> Result<PrivateKeySigner, KeystoreError> {
217    if !path.exists() {
218        return Err(KeystoreError::NotFound(path.to_path_buf()));
219    }
220    #[cfg(unix)]
221    {
222        use std::os::unix::fs::PermissionsExt;
223        let mode = fs::metadata(path)?.permissions().mode() & 0o777;
224        if mode_is_too_open(mode) {
225            tracing::warn!(
226                keystore = %path.display(),
227                mode = format!("{mode:o}"),
228                "keystore is group/world-accessible (expected 0600) — \
229                 run `chmod 600` on it; it holds your encrypted private key"
230            );
231        }
232    }
233    PrivateKeySigner::decrypt_keystore(path, password)
234        .map_err(|e| KeystoreError::Signer(e.to_string()))
235}
236
237/// Load a signer by [`KeySource`] — dispatches to the file backend today.
238/// Keychain support will slot in here under a cargo feature.
239pub fn load(source: &KeySource, password: &str) -> Result<PrivateKeySigner, KeystoreError> {
240    match source {
241        KeySource::File { path } => load_signer(path, password),
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248    use tempfile::TempDir;
249
250    #[test]
251    fn default_keyfile_name_is_lowercase_hex_without_prefix() {
252        // Deterministic check: bytes 0x01..0x14 → "0102..14.json".
253        let mut bytes = [0u8; 20];
254        for (i, b) in bytes.iter_mut().enumerate() {
255            *b = (i + 1) as u8;
256        }
257        let addr = Address::from(bytes);
258        let name = default_keyfile_name(addr);
259        assert_eq!(name, "0102030405060708090a0b0c0d0e0f1011121314.json");
260    }
261
262    #[test]
263    fn save_then_load_roundtrips_signer() {
264        let tmp = TempDir::new().unwrap();
265        let signer = PrivateKeySigner::random();
266        let expected = signer.address();
267
268        let path = tmp.path().join("wallet.json");
269        save_signer(&signer, &path, "s3kret").expect("save");
270        assert!(path.exists(), "keystore file must exist after save");
271
272        let loaded = load_signer(&path, "s3kret").expect("load");
273        assert_eq!(loaded.address(), expected);
274    }
275
276    #[test]
277    fn load_with_wrong_password_errors() {
278        let tmp = TempDir::new().unwrap();
279        let signer = PrivateKeySigner::random();
280        let path = tmp.path().join("wallet.json");
281        save_signer(&signer, &path, "correct").expect("save");
282
283        let err = load_signer(&path, "wrong").unwrap_err();
284        assert!(matches!(err, KeystoreError::Signer(_)));
285    }
286
287    #[test]
288    fn load_missing_file_reports_not_found() {
289        let tmp = TempDir::new().unwrap();
290        let missing = tmp.path().join("nope.json");
291        let err = load_signer(&missing, "pw").unwrap_err();
292        assert!(matches!(err, KeystoreError::NotFound(_)));
293    }
294
295    #[test]
296    fn save_creates_parent_dirs() {
297        let tmp = TempDir::new().unwrap();
298        let nested = tmp.path().join("a").join("b").join("wallet.json");
299        let signer = PrivateKeySigner::random();
300        save_signer(&signer, &nested, "pw").expect("save");
301        assert!(nested.exists());
302    }
303
304    #[cfg(unix)]
305    #[test]
306    fn saved_keyfile_has_0600_perms() {
307        use std::os::unix::fs::PermissionsExt;
308        let tmp = TempDir::new().unwrap();
309        let path = tmp.path().join("wallet.json");
310        let signer = PrivateKeySigner::random();
311        save_signer(&signer, &path, "pw").expect("save");
312        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
313        assert_eq!(mode, 0o600, "keyfile must be owner-only readable/writable");
314    }
315
316    #[cfg(unix)]
317    #[test]
318    fn overwriting_a_world_readable_keystore_tightens_to_0600() {
319        // A stale 0664 keystore (older build / foreign umask) must be
320        // repaired to 0600 when re-saved, not left wide. gh#78.
321        use std::os::unix::fs::PermissionsExt;
322        let tmp = TempDir::new().unwrap();
323        let path = tmp.path().join("wallet.json");
324        fs::write(&path, b"stale").unwrap();
325        fs::set_permissions(&path, fs::Permissions::from_mode(0o664)).unwrap();
326
327        let signer = PrivateKeySigner::random();
328        save_signer(&signer, &path, "pw").expect("save over existing file");
329
330        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
331        assert_eq!(mode, 0o600, "overwrite must tighten 0664 -> 0600");
332    }
333
334    #[cfg(unix)]
335    #[test]
336    fn mode_is_too_open_flags_group_and_other_bits() {
337        assert!(!mode_is_too_open(0o600));
338        assert!(!mode_is_too_open(0o400));
339        assert!(mode_is_too_open(0o640), "group-readable is too open");
340        assert!(mode_is_too_open(0o604), "other-readable is too open");
341        assert!(mode_is_too_open(0o664), "the observed leak mode");
342    }
343
344    #[test]
345    fn key_source_file_dispatches_to_file_backend() {
346        let tmp = TempDir::new().unwrap();
347        let signer = PrivateKeySigner::random();
348        let expected = signer.address();
349        let path = tmp.path().join("wallet.json");
350        save_signer(&signer, &path, "pw").expect("save");
351
352        let loaded = load(&KeySource::File { path: path.clone() }, "pw").expect("load");
353        assert_eq!(loaded.address(), expected);
354    }
355}