taskfast-cli 0.22.0

`taskfast` CLI: worker + poster hot-loop operations, JSON-envelope output.
Documentation
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// SPDX-License-Identifier: MIT
//! Shared keystore + password resolution for `post` / `settle` / `escrow`.
//!
//! All three subcommands accept the same triad (`--keystore`,
//! `--wallet-password-file`, `--wallet-address`) and resolve the keystore via
//! the same two-step process:
//!
//!   1. Password: `TASKFAST_WALLET_PASSWORD` env wins (preserves CI); else
//!      read from `--wallet-password-file`, trim trailing newline, reject
//!      empty.
//!   2. Keystore: strip the optional `file:` scheme prefix (`taskfast init`
//!      writes that form to `TEMPO_KEY_SOURCE`), then
//!      `keystore::load(File { path }, password)`.
//!
//! Exposed as free functions (not a flattened clap struct) so each caller
//! keeps its existing `Args` struct — renaming those would churn wiremock
//! tests that import them by name.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

use alloy_primitives::Address;
use alloy_signer_local::PrivateKeySigner;
use zeroize::Zeroizing;

use taskfast_agent::keystore::{self, KeySource};

use super::CmdError;

/// One-shot guard so the env-var deprecation warning fires at most once
/// per process. Streaming subcommands could otherwise spam stderr.
static PWD_WARNING_EMITTED: AtomicBool = AtomicBool::new(false);

/// Resolve the clean PathBuf for the keystore, stripping any `file:` prefix.
pub fn resolve_keystore_path(
    cli_keystore: Option<&str>,
    ctx_keystore: Option<&Path>,
) -> Option<PathBuf> {
    let raw = cli_keystore
        .map(str::to_string)
        .or_else(|| ctx_keystore.and_then(|p| p.to_str().map(str::to_string)))?;
    let path_str = raw.strip_prefix("file:").unwrap_or(&raw);
    Some(PathBuf::from(path_str))
}

/// Validate that the decrypted signer address matches an expected address string, if given.
pub fn validate_signer_address(
    signer_address: Address,
    expected_address: Option<&str>,
) -> Result<(), CmdError> {
    if let Some(expected) = expected_address {
        let expected_addr: Address = expected.parse().map_err(|e| {
            CmdError::Usage(format!("--wallet-address is not a valid EVM address: {e}"))
        })?;
        if signer_address != expected_addr {
            return Err(CmdError::Usage(format!(
                "keystore address {:#x} does not match --wallet-address {}",
                signer_address, expected
            )));
        }
    }
    Ok(())
}

/// Decrypt the keystore at `keystore_path` and validate against the expected address.
pub fn load_signer_and_validate(
    keystore_path: Option<&Path>,
    password_file: Option<&Path>,
    expected_address: Option<&str>,
    purpose: &str,
) -> Result<PrivateKeySigner, CmdError> {
    let signer = load_signer(keystore_path, password_file, purpose)?;
    validate_signer_address(signer.address(), expected_address)?;
    Ok(signer)
}

/// Decrypt the keystore at `keystore_path` using the resolved password.
///
/// `purpose` is interpolated into the "missing --keystore" usage error so the
/// operator sees *which* flow demanded a signer (e.g. "submission fee",
/// "settlement approval", "escrow approval").
pub fn load_signer(
    keystore_path: Option<&Path>,
    password_file: Option<&Path>,
    purpose: &str,
) -> Result<PrivateKeySigner, CmdError> {
    let path = keystore_path.ok_or_else(|| {
        CmdError::Usage(format!(
            "--keystore (or TEMPO_KEY_SOURCE) is required to sign the {purpose}"
        ))
    })?;
    let password = resolve_password(password_file)?;
    // `&*password` narrows `Zeroizing<String>` → `&str` only at the
    // keystore boundary; the buffer zeroizes on drop at end of scope.
    keystore::load(
        &KeySource::File {
            path: path.to_path_buf(),
        },
        &password,
    )
    .map_err(CmdError::from)
}

/// Resolve the keystore password with an optional interactive/prompted inline password.
///
/// Precedence:
/// 1. `inline_password` (interactive prompt, avoids being second-guessed by stale env vars)
/// 2. `TASKFAST_WALLET_PASSWORD` environment variable (warns if used)
/// 3. `password_file` contents (single line required, trimmed of trailing CR/LF)
pub fn resolve_password_with_inline(
    inline_password: Option<&str>,
    password_file: Option<&Path>,
) -> Result<Zeroizing<String>, CmdError> {
    resolve_password_with_inline_and_missing_hint(
        inline_password,
        password_file,
        "TASKFAST_WALLET_PASSWORD or --wallet-password-file required to unlock keystore",
    )
}

/// Resolve password with inline precedence, using a custom missing-password message on failure.
pub fn resolve_password_with_inline_and_missing_hint(
    inline_password: Option<&str>,
    password_file: Option<&Path>,
    missing_msg: &str,
) -> Result<Zeroizing<String>, CmdError> {
    if let Some(pw) = inline_password {
        let trimmed = pw.trim_end_matches(['\n', '\r']);
        if !trimmed.is_empty() {
            if trimmed.contains('\n') || trimmed.contains('\r') {
                return Err(CmdError::Usage(
                    "inline wallet password must contain a single line (found an interior newline)"
                        .into(),
                ));
            }
            return Ok(Zeroizing::new(trimmed.to_string()));
        }
    }
    if let Ok(pw) = std::env::var("TASKFAST_WALLET_PASSWORD") {
        if !pw.is_empty() {
            warn_pwd_env_once();
            return Ok(Zeroizing::new(pw));
        }
    }
    let path = password_file.ok_or_else(|| CmdError::Usage(missing_msg.into()))?;
    let raw = Zeroizing::new(std::fs::read_to_string(path).map_err(|e| {
        CmdError::Usage(format!(
            "cannot read wallet password file {}: {e}",
            path.display()
        ))
    })?);
    let trimmed = raw.trim_end_matches(['\n', '\r']);
    if trimmed.is_empty() {
        return Err(CmdError::Usage(format!(
            "wallet password file {} is empty",
            path.display()
        )));
    }
    // F13: a trailing newline is fine (editors add one), but a newline
    // *inside* the trimmed body almost always means the operator pasted
    // extra content (two passwords, a commented-out line, a stray label).
    // Refuse rather than silently taking the first line as the password.
    if trimmed.contains('\n') || trimmed.contains('\r') {
        return Err(CmdError::Usage(format!(
            "wallet password file {} must contain a single line (found an interior newline)",
            path.display()
        )));
    }
    Ok(Zeroizing::new(trimmed.to_string()))
}

/// Resolve the keystore password: env var wins over file. Trims trailing
/// `\r`/`\n` but rejects a file that is otherwise empty.
pub fn resolve_password(password_file: Option<&Path>) -> Result<Zeroizing<String>, CmdError> {
    resolve_password_with_inline(None, password_file)
}

/// Print the `TASKFAST_WALLET_PASSWORD` deprecation nudge to stderr once
/// per process. Suppressed by `TASKFAST_SUPPRESS_PWD_WARNING=1` so CI
/// pipelines that intentionally use the env var can quiet the noise.
fn warn_pwd_env_once() {
    if std::env::var("TASKFAST_SUPPRESS_PWD_WARNING").is_ok_and(|v| v == "1") {
        return;
    }
    if PWD_WARNING_EMITTED.swap(true, Ordering::Relaxed) {
        return;
    }
    eprintln!(
        "warning: TASKFAST_WALLET_PASSWORD is readable via /proc/<pid>/environ; \
         prefer --wallet-password-file (TASKFAST_WALLET_PASSWORD_FILE) or set \
         TASKFAST_SUPPRESS_PWD_WARNING=1 to silence."
    );
}

/// Decode a `0x`-prefixed or bare hex string into raw bytes.
pub fn decode_0x_bytes(s: &str) -> Result<Vec<u8>, String> {
    let stripped = s.strip_prefix("0x").unwrap_or(s);
    hex::decode(stripped).map_err(|e| e.to_string())
}

/// Resolve the authenticated Tempo RPC URL for the deployment.
///
/// Discovers `tempo_rpc_url` from `GET /config/network`. For managed environments,
/// this points to the authenticated proxy at `{api_base}/rpc/{network}`.
pub async fn resolve_proxy_rpc_url(
    client: &taskfast_client::TaskFastClient,
    ctx: &super::Ctx,
) -> Result<String, CmdError> {
    let cfg = client.fetch_network_config().await.map_err(|e| match e {
        taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
        }
        other => CmdError::from(other),
    })?;
    let name = ctx.environment.network().as_str();
    if !ctx.allow_custom_endpoints
        && ctx.environment != crate::Environment::Local
        && cfg.networks.len() != 1
    {
        let advertised: Vec<&str> = cfg.networks.keys().map(String::as_str).collect();
        let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
            .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
        if strict {
            return Err(CmdError::Server(format!(
                "deployment at {} advertises networks {advertised:?}; env {} requires \
                 exactly [{name}]. Server-side fix tracked in issue #62. Unset \
                 TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
                ctx.base_url(),
                ctx.environment.as_str(),
            )));
        }
        tracing::warn!(
            api_base = %ctx.base_url(),
            env = ctx.environment.as_str(),
            expected = name,
            advertised = ?advertised,
            "deployment advertises additional networks; server-side fix tracked in #62. \
             Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed."
        );
    }
    let entry = cfg.entry(name).map_err(|e| {
        CmdError::Server(format!(
            "deployment at {} does not advertise network `{name}`: {e}",
            ctx.base_url()
        ))
    })?;
    if !super::is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
        return Err(CmdError::Server(format!(
            "deployment at {} returned rpc_url {:?} for network `{name}`, \
             which is not on the same host. Refusing to route RPC traffic \
             off-host.",
            ctx.base_url(),
            entry.rpc_url,
        )));
    }
    Ok(entry.rpc_url.clone())
}

/// Sign and broadcast an ERC-20 submission-fee transfer under the per-wallet lock.
///
/// Refuses to sign if the chain ID is not a known Tempo or local-dev network
/// (unless `--allow-custom-endpoints` is active), or if the token is not on the
/// PathUSD allowlist for that chain.
pub async fn sign_and_send_submission_fee(
    ctx: &super::Ctx,
    client: &taskfast_client::TaskFastClient,
    rpc_url: &str,
    keystore_path: Option<PathBuf>,
    signer: PrivateKeySigner,
    token_address_str: &str,
    calldata: alloy_primitives::Bytes,
) -> Result<alloy_primitives::B256, CmdError> {
    let token_address: Address = token_address_str.parse().map_err(|e| {
        CmdError::Server(format!(
            "server returned invalid token_address `{token_address_str}`: {e}"
        ))
    })?;

    let http = ctx.rpc_http_client(client, rpc_url);
    let rpc = taskfast_agent::tempo_rpc::TempoRpcClient::new(http, rpc_url.to_string());

    let chain_id = rpc
        .chain_id()
        .await
        .map_err(|e| CmdError::Server(format!("tempo rpc eth_chainId: {e}")))?;
    if !ctx.allow_custom_endpoints && !taskfast_chains::tempo::is_known_network(chain_id) {
        return Err(CmdError::Validation {
            code: "unknown_chain".into(),
            message: format!(
                "RPC reports chain_id={chain_id} which is not a known Tempo or \
                 local-dev network; refusing to sign. Pass --allow-custom-endpoints \
                 to override."
            ),
        });
    }

    if !taskfast_chains::tempo::is_allowed_fee_token(chain_id, token_address_str) {
        return Err(CmdError::Validation {
            code: "fee_token_not_allowed".into(),
            message: format!(
                "server returned token_address {token_address_str} which is not on the PathUSD \
                 allowlist for chain_id={chain_id}. Refusing to sign — this would \
                 redirect your fee transfer to an arbitrary ERC-20 contract."
            ),
        });
    }

    eprintln!(
        "taskfast: signing submission-fee transfer — token={} chain_id={} rpc={}",
        token_address_str, chain_id, rpc_url
    );

    let session = crate::tempo_session::TempoSession::new(
        signer,
        keystore_path,
        rpc,
        std::time::Duration::from_mins(1),
    );

    let tx_hash = session.send_transaction(token_address, calldata).await?;
    Ok(tx_hash)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    fn write_temp(contents: &str) -> tempfile::NamedTempFile {
        let mut f = tempfile::NamedTempFile::new().expect("tempfile");
        f.write_all(contents.as_bytes()).unwrap();
        f
    }

    // Serialize env-var-touching tests — parallel cargo test workers share
    // process env and would clobber each other's assertions otherwise.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn password_env_wins_over_file() {
        let _g = ENV_LOCK.lock().unwrap();
        let f = write_temp("from-file\n");
        std::env::set_var("TASKFAST_WALLET_PASSWORD", "from-env");
        let pw = resolve_password(Some(f.path())).expect("ok");
        assert_eq!(pw.as_str(), "from-env");
        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
    }

    #[test]
    fn password_file_trimmed_when_env_absent() {
        let _g = ENV_LOCK.lock().unwrap();
        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
        let f = write_temp("secret\r\n");
        let pw = resolve_password(Some(f.path())).expect("ok");
        assert_eq!(pw.as_str(), "secret");
    }

    #[test]
    fn password_rejects_interior_newline() {
        let _g = ENV_LOCK.lock().unwrap();
        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
        let f = write_temp("first-line\nsecond-line\n");
        let err = resolve_password(Some(f.path())).expect_err("multi-line must fail");
        match err {
            CmdError::Usage(m) => assert!(
                m.contains("single line"),
                "message must name the constraint: {m}"
            ),
            other => panic!("expected Usage, got {other:?}"),
        }
    }

    #[test]
    fn password_rejects_interior_carriage_return() {
        let _g = ENV_LOCK.lock().unwrap();
        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
        // CRLF in the middle (Windows-edited file with a stray prefix line).
        let f = write_temp("annotation\r\nsecret\n");
        let err = resolve_password(Some(f.path())).expect_err("must fail");
        assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
    }

    #[test]
    fn password_is_zeroizing_wrapped() {
        // Compile-time proof: return type is Zeroizing<String>, i.e. drop
        // scrubs the backing allocation. Sanity-check via the type name.
        let _g = ENV_LOCK.lock().unwrap();
        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
        let f = write_temp("scrubme\n");
        let pw = resolve_password(Some(f.path())).expect("ok");
        let name = std::any::type_name_of_val(&pw);
        assert!(
            name.contains("Zeroizing"),
            "password must be Zeroizing: {name}"
        );
    }

    #[test]
    fn password_rejects_empty_file() {
        let _g = ENV_LOCK.lock().unwrap();
        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
        let f = write_temp("\n\n");
        let err = resolve_password(Some(f.path())).expect_err("empty must fail");
        assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
    }

    #[test]
    fn password_requires_file_when_env_absent() {
        let _g = ENV_LOCK.lock().unwrap();
        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
        let err = resolve_password(None).expect_err("no source → Usage");
        assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
    }

    #[test]
    fn load_signer_missing_keystore_surfaces_purpose() {
        let err = load_signer(None, None, "escrow approval").expect_err("no keystore → Usage");
        match err {
            CmdError::Usage(m) => {
                assert!(m.contains("escrow approval"), "purpose must appear: {m}")
            }
            other => panic!("expected Usage, got {other:?}"),
        }
    }

    #[test]
    fn inline_password_wins_and_rejects_interior_newlines() {
        let _g = ENV_LOCK.lock().unwrap();
        std::env::set_var("TASKFAST_WALLET_PASSWORD", "from-env");
        let pw = resolve_password_with_inline(Some("inline-secret\n"), None).expect("ok");
        assert_eq!(pw.as_str(), "inline-secret");

        let err = resolve_password_with_inline(Some("first\nsecond"), None)
            .expect_err("interior newline must fail");
        assert!(matches!(err, CmdError::Usage(m) if m.contains("single line")));
        std::env::remove_var("TASKFAST_WALLET_PASSWORD");
    }

    #[test]
    fn resolve_keystore_helpers() {
        assert_eq!(
            resolve_keystore_path(Some("file:/tmp/key.json"), None),
            Some(PathBuf::from("/tmp/key.json"))
        );
        assert_eq!(
            resolve_keystore_path(Some("/tmp/key.json"), None),
            Some(PathBuf::from("/tmp/key.json"))
        );
        assert_eq!(
            resolve_keystore_path(None, Some(Path::new("/etc/key.json"))),
            Some(PathBuf::from("/etc/key.json"))
        );
    }

    #[test]
    fn validate_signer_address_checks() {
        let addr = Address::repeat_byte(0x11);
        validate_signer_address(addr, None).expect("no expected address passes");
        validate_signer_address(addr, Some(&format!("{addr:#x}")))
            .expect("matching address passes");

        let err = validate_signer_address(addr, Some("not-hex")).expect_err("invalid address");
        assert!(matches!(err, CmdError::Usage(m) if m.contains("not a valid EVM address")));

        let mismatch = Address::repeat_byte(0x22);
        let err = validate_signer_address(addr, Some(&format!("{mismatch:#x}")))
            .expect_err("mismatch must fail");
        assert!(matches!(err, CmdError::Usage(m) if m.contains("does not match --wallet-address")));
    }
}