Skip to main content

taskfast_cli/cmd/
wallet_args.rs

1// SPDX-License-Identifier: MIT
2//! Shared keystore + password resolution for `post` / `settle` / `escrow`.
3//!
4//! All three subcommands accept the same triad (`--keystore`,
5//! `--wallet-password-file`, `--wallet-address`) and resolve the keystore via
6//! the same two-step process:
7//!
8//!   1. Password: `TASKFAST_WALLET_PASSWORD` env wins (preserves CI); else
9//!      read from `--wallet-password-file`, trim trailing newline, reject
10//!      empty.
11//!   2. Keystore: strip the optional `file:` scheme prefix (`taskfast init`
12//!      writes that form to `TEMPO_KEY_SOURCE`), then
13//!      `keystore::load(File { path }, password)`.
14//!
15//! Exposed as free functions (not a flattened clap struct) so each caller
16//! keeps its existing `Args` struct — renaming those would churn wiremock
17//! tests that import them by name.
18
19use std::path::{Path, PathBuf};
20use std::sync::atomic::{AtomicBool, Ordering};
21
22use alloy_primitives::Address;
23use alloy_signer_local::PrivateKeySigner;
24use zeroize::Zeroizing;
25
26use taskfast_agent::keystore::{self, KeySource};
27
28use super::CmdError;
29
30/// One-shot guard so the env-var deprecation warning fires at most once
31/// per process. Streaming subcommands could otherwise spam stderr.
32static PWD_WARNING_EMITTED: AtomicBool = AtomicBool::new(false);
33
34/// Resolve the clean PathBuf for the keystore, stripping any `file:` prefix.
35pub fn resolve_keystore_path(
36    cli_keystore: Option<&str>,
37    ctx_keystore: Option<&Path>,
38) -> Option<PathBuf> {
39    let raw = cli_keystore
40        .map(str::to_string)
41        .or_else(|| ctx_keystore.and_then(|p| p.to_str().map(str::to_string)))?;
42    let path_str = raw.strip_prefix("file:").unwrap_or(&raw);
43    Some(PathBuf::from(path_str))
44}
45
46/// Validate that the decrypted signer address matches an expected address string, if given.
47pub fn validate_signer_address(
48    signer_address: Address,
49    expected_address: Option<&str>,
50) -> Result<(), CmdError> {
51    if let Some(expected) = expected_address {
52        let expected_addr: Address = expected.parse().map_err(|e| {
53            CmdError::Usage(format!("--wallet-address is not a valid EVM address: {e}"))
54        })?;
55        if signer_address != expected_addr {
56            return Err(CmdError::Usage(format!(
57                "keystore address {:#x} does not match --wallet-address {}",
58                signer_address, expected
59            )));
60        }
61    }
62    Ok(())
63}
64
65/// Decrypt the keystore at `keystore_path` and validate against the expected address.
66pub fn load_signer_and_validate(
67    keystore_path: Option<&Path>,
68    password_file: Option<&Path>,
69    expected_address: Option<&str>,
70    purpose: &str,
71) -> Result<PrivateKeySigner, CmdError> {
72    let signer = load_signer(keystore_path, password_file, purpose)?;
73    validate_signer_address(signer.address(), expected_address)?;
74    Ok(signer)
75}
76
77/// Decrypt the keystore at `keystore_path` using the resolved password.
78///
79/// `purpose` is interpolated into the "missing --keystore" usage error so the
80/// operator sees *which* flow demanded a signer (e.g. "submission fee",
81/// "settlement approval", "escrow approval").
82pub fn load_signer(
83    keystore_path: Option<&Path>,
84    password_file: Option<&Path>,
85    purpose: &str,
86) -> Result<PrivateKeySigner, CmdError> {
87    let path = keystore_path.ok_or_else(|| {
88        CmdError::Usage(format!(
89            "--keystore (or TEMPO_KEY_SOURCE) is required to sign the {purpose}"
90        ))
91    })?;
92    let password = resolve_password(password_file)?;
93    // `&*password` narrows `Zeroizing<String>` → `&str` only at the
94    // keystore boundary; the buffer zeroizes on drop at end of scope.
95    keystore::load(
96        &KeySource::File {
97            path: path.to_path_buf(),
98        },
99        &password,
100    )
101    .map_err(CmdError::from)
102}
103
104/// Resolve the keystore password with an optional interactive/prompted inline password.
105///
106/// Precedence:
107/// 1. `inline_password` (interactive prompt, avoids being second-guessed by stale env vars)
108/// 2. `TASKFAST_WALLET_PASSWORD` environment variable (warns if used)
109/// 3. `password_file` contents (single line required, trimmed of trailing CR/LF)
110pub fn resolve_password_with_inline(
111    inline_password: Option<&str>,
112    password_file: Option<&Path>,
113) -> Result<Zeroizing<String>, CmdError> {
114    resolve_password_with_inline_and_missing_hint(
115        inline_password,
116        password_file,
117        "TASKFAST_WALLET_PASSWORD or --wallet-password-file required to unlock keystore",
118    )
119}
120
121/// Resolve password with inline precedence, using a custom missing-password message on failure.
122pub fn resolve_password_with_inline_and_missing_hint(
123    inline_password: Option<&str>,
124    password_file: Option<&Path>,
125    missing_msg: &str,
126) -> Result<Zeroizing<String>, CmdError> {
127    if let Some(pw) = inline_password {
128        let trimmed = pw.trim_end_matches(['\n', '\r']);
129        if !trimmed.is_empty() {
130            if trimmed.contains('\n') || trimmed.contains('\r') {
131                return Err(CmdError::Usage(
132                    "inline wallet password must contain a single line (found an interior newline)"
133                        .into(),
134                ));
135            }
136            return Ok(Zeroizing::new(trimmed.to_string()));
137        }
138    }
139    if let Ok(pw) = std::env::var("TASKFAST_WALLET_PASSWORD") {
140        if !pw.is_empty() {
141            warn_pwd_env_once();
142            return Ok(Zeroizing::new(pw));
143        }
144    }
145    let path = password_file.ok_or_else(|| CmdError::Usage(missing_msg.into()))?;
146    let raw = Zeroizing::new(std::fs::read_to_string(path).map_err(|e| {
147        CmdError::Usage(format!(
148            "cannot read wallet password file {}: {e}",
149            path.display()
150        ))
151    })?);
152    let trimmed = raw.trim_end_matches(['\n', '\r']);
153    if trimmed.is_empty() {
154        return Err(CmdError::Usage(format!(
155            "wallet password file {} is empty",
156            path.display()
157        )));
158    }
159    // F13: a trailing newline is fine (editors add one), but a newline
160    // *inside* the trimmed body almost always means the operator pasted
161    // extra content (two passwords, a commented-out line, a stray label).
162    // Refuse rather than silently taking the first line as the password.
163    if trimmed.contains('\n') || trimmed.contains('\r') {
164        return Err(CmdError::Usage(format!(
165            "wallet password file {} must contain a single line (found an interior newline)",
166            path.display()
167        )));
168    }
169    Ok(Zeroizing::new(trimmed.to_string()))
170}
171
172/// Resolve the keystore password: env var wins over file. Trims trailing
173/// `\r`/`\n` but rejects a file that is otherwise empty.
174pub fn resolve_password(password_file: Option<&Path>) -> Result<Zeroizing<String>, CmdError> {
175    resolve_password_with_inline(None, password_file)
176}
177
178/// Print the `TASKFAST_WALLET_PASSWORD` deprecation nudge to stderr once
179/// per process. Suppressed by `TASKFAST_SUPPRESS_PWD_WARNING=1` so CI
180/// pipelines that intentionally use the env var can quiet the noise.
181fn warn_pwd_env_once() {
182    if std::env::var("TASKFAST_SUPPRESS_PWD_WARNING").is_ok_and(|v| v == "1") {
183        return;
184    }
185    if PWD_WARNING_EMITTED.swap(true, Ordering::Relaxed) {
186        return;
187    }
188    eprintln!(
189        "warning: TASKFAST_WALLET_PASSWORD is readable via /proc/<pid>/environ; \
190         prefer --wallet-password-file (TASKFAST_WALLET_PASSWORD_FILE) or set \
191         TASKFAST_SUPPRESS_PWD_WARNING=1 to silence."
192    );
193}
194
195/// Decode a `0x`-prefixed or bare hex string into raw bytes.
196pub fn decode_0x_bytes(s: &str) -> Result<Vec<u8>, String> {
197    let stripped = s.strip_prefix("0x").unwrap_or(s);
198    hex::decode(stripped).map_err(|e| e.to_string())
199}
200
201/// Resolve the authenticated Tempo RPC URL for the deployment.
202///
203/// Discovers `tempo_rpc_url` from `GET /config/network`. For managed environments,
204/// this points to the authenticated proxy at `{api_base}/rpc/{network}`.
205pub async fn resolve_proxy_rpc_url(
206    client: &taskfast_client::TaskFastClient,
207    ctx: &super::Ctx,
208) -> Result<String, CmdError> {
209    let cfg = client.fetch_network_config().await.map_err(|e| match e {
210        taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
211            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
212        }
213        other => CmdError::from(other),
214    })?;
215    let name = ctx.environment.network().as_str();
216    if !ctx.allow_custom_endpoints
217        && ctx.environment != crate::Environment::Local
218        && cfg.networks.len() != 1
219    {
220        let advertised: Vec<&str> = cfg.networks.keys().map(String::as_str).collect();
221        let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
222            .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
223        if strict {
224            return Err(CmdError::Server(format!(
225                "deployment at {} advertises networks {advertised:?}; env {} requires \
226                 exactly [{name}]. Server-side fix tracked in issue #62. Unset \
227                 TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
228                ctx.base_url(),
229                ctx.environment.as_str(),
230            )));
231        }
232        tracing::warn!(
233            api_base = %ctx.base_url(),
234            env = ctx.environment.as_str(),
235            expected = name,
236            advertised = ?advertised,
237            "deployment advertises additional networks; server-side fix tracked in #62. \
238             Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed."
239        );
240    }
241    let entry = cfg.entry(name).map_err(|e| {
242        CmdError::Server(format!(
243            "deployment at {} does not advertise network `{name}`: {e}",
244            ctx.base_url()
245        ))
246    })?;
247    if !super::is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
248        return Err(CmdError::Server(format!(
249            "deployment at {} returned rpc_url {:?} for network `{name}`, \
250             which is not on the same host. Refusing to route RPC traffic \
251             off-host.",
252            ctx.base_url(),
253            entry.rpc_url,
254        )));
255    }
256    Ok(entry.rpc_url.clone())
257}
258
259/// Sign and broadcast an ERC-20 submission-fee transfer under the per-wallet lock.
260///
261/// Refuses to sign if the chain ID is not a known Tempo or local-dev network
262/// (unless `--allow-custom-endpoints` is active), or if the token is not on the
263/// PathUSD allowlist for that chain.
264pub async fn sign_and_send_submission_fee(
265    ctx: &super::Ctx,
266    client: &taskfast_client::TaskFastClient,
267    rpc_url: &str,
268    keystore_path: Option<PathBuf>,
269    signer: PrivateKeySigner,
270    token_address_str: &str,
271    calldata: alloy_primitives::Bytes,
272) -> Result<alloy_primitives::B256, CmdError> {
273    let token_address: Address = token_address_str.parse().map_err(|e| {
274        CmdError::Server(format!(
275            "server returned invalid token_address `{token_address_str}`: {e}"
276        ))
277    })?;
278
279    let http = ctx.rpc_http_client(client, rpc_url);
280    let rpc = taskfast_agent::tempo_rpc::TempoRpcClient::new(http, rpc_url.to_string());
281
282    let chain_id = rpc
283        .chain_id()
284        .await
285        .map_err(|e| CmdError::Server(format!("tempo rpc eth_chainId: {e}")))?;
286    if !ctx.allow_custom_endpoints && !taskfast_chains::tempo::is_known_network(chain_id) {
287        return Err(CmdError::Validation {
288            code: "unknown_chain".into(),
289            message: format!(
290                "RPC reports chain_id={chain_id} which is not a known Tempo or \
291                 local-dev network; refusing to sign. Pass --allow-custom-endpoints \
292                 to override."
293            ),
294        });
295    }
296
297    if !taskfast_chains::tempo::is_allowed_fee_token(chain_id, token_address_str) {
298        return Err(CmdError::Validation {
299            code: "fee_token_not_allowed".into(),
300            message: format!(
301                "server returned token_address {token_address_str} which is not on the PathUSD \
302                 allowlist for chain_id={chain_id}. Refusing to sign — this would \
303                 redirect your fee transfer to an arbitrary ERC-20 contract."
304            ),
305        });
306    }
307
308    eprintln!(
309        "taskfast: signing submission-fee transfer — token={} chain_id={} rpc={}",
310        token_address_str, chain_id, rpc_url
311    );
312
313    let session = crate::tempo_session::TempoSession::new(
314        signer,
315        keystore_path,
316        rpc,
317        std::time::Duration::from_mins(1),
318    );
319
320    let tx_hash = session.send_transaction(token_address, calldata).await?;
321    Ok(tx_hash)
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use std::io::Write;
328
329    fn write_temp(contents: &str) -> tempfile::NamedTempFile {
330        let mut f = tempfile::NamedTempFile::new().expect("tempfile");
331        f.write_all(contents.as_bytes()).unwrap();
332        f
333    }
334
335    // Serialize env-var-touching tests — parallel cargo test workers share
336    // process env and would clobber each other's assertions otherwise.
337    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
338
339    #[test]
340    fn password_env_wins_over_file() {
341        let _g = ENV_LOCK.lock().unwrap();
342        let f = write_temp("from-file\n");
343        std::env::set_var("TASKFAST_WALLET_PASSWORD", "from-env");
344        let pw = resolve_password(Some(f.path())).expect("ok");
345        assert_eq!(pw.as_str(), "from-env");
346        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
347    }
348
349    #[test]
350    fn password_file_trimmed_when_env_absent() {
351        let _g = ENV_LOCK.lock().unwrap();
352        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
353        let f = write_temp("secret\r\n");
354        let pw = resolve_password(Some(f.path())).expect("ok");
355        assert_eq!(pw.as_str(), "secret");
356    }
357
358    #[test]
359    fn password_rejects_interior_newline() {
360        let _g = ENV_LOCK.lock().unwrap();
361        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
362        let f = write_temp("first-line\nsecond-line\n");
363        let err = resolve_password(Some(f.path())).expect_err("multi-line must fail");
364        match err {
365            CmdError::Usage(m) => assert!(
366                m.contains("single line"),
367                "message must name the constraint: {m}"
368            ),
369            other => panic!("expected Usage, got {other:?}"),
370        }
371    }
372
373    #[test]
374    fn password_rejects_interior_carriage_return() {
375        let _g = ENV_LOCK.lock().unwrap();
376        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
377        // CRLF in the middle (Windows-edited file with a stray prefix line).
378        let f = write_temp("annotation\r\nsecret\n");
379        let err = resolve_password(Some(f.path())).expect_err("must fail");
380        assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
381    }
382
383    #[test]
384    fn password_is_zeroizing_wrapped() {
385        // Compile-time proof: return type is Zeroizing<String>, i.e. drop
386        // scrubs the backing allocation. Sanity-check via the type name.
387        let _g = ENV_LOCK.lock().unwrap();
388        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
389        let f = write_temp("scrubme\n");
390        let pw = resolve_password(Some(f.path())).expect("ok");
391        let name = std::any::type_name_of_val(&pw);
392        assert!(
393            name.contains("Zeroizing"),
394            "password must be Zeroizing: {name}"
395        );
396    }
397
398    #[test]
399    fn password_rejects_empty_file() {
400        let _g = ENV_LOCK.lock().unwrap();
401        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
402        let f = write_temp("\n\n");
403        let err = resolve_password(Some(f.path())).expect_err("empty must fail");
404        assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
405    }
406
407    #[test]
408    fn password_requires_file_when_env_absent() {
409        let _g = ENV_LOCK.lock().unwrap();
410        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
411        let err = resolve_password(None).expect_err("no source → Usage");
412        assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
413    }
414
415    #[test]
416    fn load_signer_missing_keystore_surfaces_purpose() {
417        let err = load_signer(None, None, "escrow approval").expect_err("no keystore → Usage");
418        match err {
419            CmdError::Usage(m) => {
420                assert!(m.contains("escrow approval"), "purpose must appear: {m}")
421            }
422            other => panic!("expected Usage, got {other:?}"),
423        }
424    }
425
426    #[test]
427    fn inline_password_wins_and_rejects_interior_newlines() {
428        let _g = ENV_LOCK.lock().unwrap();
429        std::env::set_var("TASKFAST_WALLET_PASSWORD", "from-env");
430        let pw = resolve_password_with_inline(Some("inline-secret\n"), None).expect("ok");
431        assert_eq!(pw.as_str(), "inline-secret");
432
433        let err = resolve_password_with_inline(Some("first\nsecond"), None)
434            .expect_err("interior newline must fail");
435        assert!(matches!(err, CmdError::Usage(m) if m.contains("single line")));
436        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
437    }
438
439    #[test]
440    fn resolve_keystore_helpers() {
441        assert_eq!(
442            resolve_keystore_path(Some("file:/tmp/key.json"), None),
443            Some(PathBuf::from("/tmp/key.json"))
444        );
445        assert_eq!(
446            resolve_keystore_path(Some("/tmp/key.json"), None),
447            Some(PathBuf::from("/tmp/key.json"))
448        );
449        assert_eq!(
450            resolve_keystore_path(None, Some(Path::new("/etc/key.json"))),
451            Some(PathBuf::from("/etc/key.json"))
452        );
453    }
454
455    #[test]
456    fn validate_signer_address_checks() {
457        let addr = Address::repeat_byte(0x11);
458        validate_signer_address(addr, None).expect("no expected address passes");
459        validate_signer_address(addr, Some(&format!("{addr:#x}")))
460            .expect("matching address passes");
461
462        let err = validate_signer_address(addr, Some("not-hex")).expect_err("invalid address");
463        assert!(matches!(err, CmdError::Usage(m) if m.contains("not a valid EVM address")));
464
465        let mismatch = Address::repeat_byte(0x22);
466        let err = validate_signer_address(addr, Some(&format!("{mismatch:#x}")))
467            .expect_err("mismatch must fail");
468        assert!(matches!(err, CmdError::Usage(m) if m.contains("does not match --wallet-address")));
469    }
470}