Skip to main content

taskfast_cli/cmd/
post.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast post` — two-phase task creation (prepare → sign+broadcast → submit).
3//!
4//! Supersedes the `scripts/post-task` shell flow whose defect chain is tracked
5//! under am-q1m. Server contract (`lib/task_fast/payments/tempo_provider.ex`
6//! `charge_submission_fee/4`) accepts **two voucher forms** on
7//! `POST /api/task_drafts/{id}/submit`:
8//!
9//!   - `0x<64hex>` → already-broadcast tx hash; server polls for confirmation.
10//!   - any other hex → raw RLP-encoded signed tx; server broadcasts via
11//!     `eth_sendRawTransaction`.
12//!
13//! We take the **tx-hash voucher path**: the client signs + broadcasts the
14//! ERC-20 transfer locally, then hands the server just the hash. Rationale:
15//! failures on the broadcast side surface to the agent as a concrete RPC
16//! error before we pollute the server's draft state with a would-be-bad
17//! voucher.
18//!
19//! `payload_to_sign` (despite its historical name) is **not** an ECDSA signing
20//! payload — it's the encoded ERC-20 `transfer` calldata. We wrap it in a
21//! replay-safe legacy tx and sign the transaction hash via
22//! [`taskfast_agent::tempo_rpc::sign_and_broadcast_erc20_transfer`].
23
24use std::path::PathBuf;
25
26use alloy_primitives::{Address, Bytes};
27use clap::Parser;
28use serde_json::json;
29use uuid::Uuid;
30
31use super::{is_proxy_rpc_url, validate_override_rpc_url, CmdError, CmdResult, Ctx};
32use crate::envelope::Envelope;
33
34use taskfast_agent::tempo_rpc::{sign_and_broadcast_erc20_transfer, TempoRpcClient};
35use taskfast_chains::tempo::{is_allowed_fee_token, is_known_network};
36use taskfast_client::api::types::{
37    CompletionCriterionInput, TaskDraftPrepareRequest, TaskDraftPrepareRequestAssignmentType,
38    TaskDraftPrepareRequestPickupDeadlineHours, TaskDraftSubmitRequest,
39    TaskDraftSubmitRequestSignature,
40};
41use taskfast_client::{map_api_error, TaskFastClient};
42
43#[derive(Debug, Parser)]
44pub struct Args {
45    /// Task title (required).
46    #[arg(long)]
47    pub title: String,
48
49    /// Task description (required, non-empty). Validated client-side so a
50    /// typoed script fails fast instead of paying for a server 422 round-trip.
51    #[arg(long)]
52    pub description: String,
53
54    /// Max budget the poster will pay, as a decimal string ("2.50"). Passed
55    /// through as `budget_max` on the draft.
56    #[arg(long)]
57    pub budget: Option<String>,
58
59    /// Capability tags required from the assignee. Comma-separated.
60    #[arg(long, value_delimiter = ',')]
61    pub capabilities: Vec<String>,
62
63    /// Completion-criterion payout gate as a JSON object. Repeat `--criterion`
64    /// for multiple gates. Shape matches `CompletionCriterionInput`:
65    /// `{"description":"…","check_type":"json_schema|regex|count|http_status|file_exists",`
66    /// `"check_expression":"…","expected_value":"…","target_artifact_pattern":null}`.
67    /// Missing ⇒ no objective gate; server policy decides payout.
68    #[arg(long = "criterion")]
69    pub criteria: Vec<String>,
70
71    /// Path to a JSON file containing an array of `CompletionCriterionInput`
72    /// objects. Merged before any `--criterion` flags (file entries first).
73    /// Use this when you have many gates or want to keep them in version
74    /// control alongside the task.
75    #[arg(long)]
76    pub criteria_file: Option<PathBuf>,
77
78    /// Pickup window in hours: how long the task stays open for bidding
79    /// before closing. Required. The server owns the set of allowed windows
80    /// (`422 pickup_deadline_required` on an invalid choice).
81    #[arg(long)]
82    pub pickup_deadline_hours: i64,
83
84    /// Execution deadline (RFC3339 timestamp).
85    #[arg(long)]
86    pub execution_deadline: Option<String>,
87
88    /// Settlement venue `chain_key` (e.g. `tempo-zone-moderato`) electing the
89    /// settlement rail/chain for this task (ADR 0011 §5). Omit to settle on the
90    /// deployment's default venue (L1). The server validates the key (must
91    /// reference an active venue) and binds it once at creation, immutably.
92    #[arg(long)]
93    pub venue: Option<String>,
94
95    /// Assignment model: `open` (auction to any qualified bidder) or
96    /// `direct` (assign to a specific agent; requires `--direct-agent-id`).
97    #[arg(long, default_value = "open")]
98    pub assignment_type: AssignmentType,
99
100    /// Direct assignment target. Required when `--assignment-type=direct`.
101    #[arg(long)]
102    pub direct_agent_id: Option<String>,
103
104    /// Poster's on-chain wallet address (0x-prefixed). Matches `TEMPO_WALLET_ADDRESS`
105    /// written by `taskfast init`.
106    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
107    pub wallet_address: Option<String>,
108
109    /// Keystore reference. Accepts a bare path (`/.../abc.json`) or the
110    /// `file:/path` form `taskfast init` writes to `TEMPO_KEY_SOURCE`.
111    /// Keychain backends will slot in later under the same flag.
112    #[arg(long, env = "TEMPO_KEY_SOURCE")]
113    pub keystore: Option<String>,
114
115    /// Path to a file holding the keystore password (mode-0400 recommended).
116    /// Preferred over `TASKFAST_WALLET_PASSWORD` — files don't leak via
117    /// process args or `/proc/self/environ`.
118    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
119    pub wallet_password_file: Option<PathBuf>,
120
121    /// Tempo RPC endpoint. Defaults to the canonical proxy URL the
122    /// deployment advertises for the env's network.
123    #[arg(long, env = "TEMPO_RPC_URL")]
124    pub rpc_url: Option<String>,
125
126    /// Acknowledge oversized budgets. Required when the budget exceeds
127    /// `confirm_above_budget` in the config. No-op when the gate is unset
128    /// or when the budget is below it. Fail-closed by design (no TTY
129    /// prompt) so a CI script accident doesn't broadcast a huge approve.
130    #[arg(long)]
131    pub yes: bool,
132}
133
134#[derive(Debug, Clone, Copy, clap::ValueEnum)]
135pub enum AssignmentType {
136    Open,
137    Direct,
138}
139
140impl AssignmentType {
141    fn as_str(self) -> &'static str {
142        match self {
143            Self::Open => "open",
144            Self::Direct => "direct",
145        }
146    }
147}
148
149impl From<AssignmentType> for TaskDraftPrepareRequestAssignmentType {
150    fn from(a: AssignmentType) -> Self {
151        match a {
152            AssignmentType::Open => Self::Open,
153            AssignmentType::Direct => Self::Direct,
154        }
155    }
156}
157
158/// Convert `--pickup-deadline-hours` to the wire type generated from the
159/// vendored spec. The generated newtype is the only encoding of the allowed
160/// set — the CLI never restates it, so a server policy change flows in via a
161/// spec re-vendor with no code edit here.
162fn pickup_hours_to_wire(
163    hours: i64,
164) -> Result<TaskDraftPrepareRequestPickupDeadlineHours, CmdError> {
165    TaskDraftPrepareRequestPickupDeadlineHours::try_from(hours).map_err(|_| CmdError::Validation {
166        code: "pickup_deadline_invalid".into(),
167        message: format!(
168            "pickup window of {hours}h is not an allowed bidding window per the \
169             API contract; the server owns the valid set (422 pickup_deadline_required)"
170        ),
171    })
172}
173
174pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
175    // gh#144: validate every local input in ONE pass before any HTTP,
176    // keystore prompt, or signing — the old sequential early-returns cost an
177    // agent one full retry cycle per missing flag / guard conflict.
178    let pre = preflight(ctx, &args)?;
179
180    let prep_body = TaskDraftPrepareRequest {
181        assignment_type: args.assignment_type.into(),
182        budget_max: args.budget.clone(),
183        completion_criteria: pre.completion_criteria,
184        description: args.description.clone(),
185        direct_agent_id: pre.direct_agent_id,
186        execution_deadline: pre.execution_deadline,
187        pickup_deadline_hours: pre.pickup_hours,
188        poster_wallet_address: pre
189            .wallet_address
190            .parse()
191            .map_err(|e| CmdError::Usage(format!("--wallet-address rejected by schema: {e}")))?,
192        required_capabilities: args.capabilities.clone(),
193        settlement_venue: args.venue.clone(),
194        title: args.title.clone(),
195    };
196
197    // Dry-run must perform zero HTTP. Predict the proxy URL locally so the
198    // envelope still reports what the real path would have used.
199    if ctx.dry_run {
200        let rpc_url = match pre.rpc_url_override {
201            Some(override_url) => override_url,
202            None => format!(
203                "{}/rpc/{}",
204                ctx.base_url().trim_end_matches('/'),
205                ctx.environment.network().as_str()
206            ),
207        };
208        return Ok(Envelope::success(
209            ctx.environment,
210            ctx.dry_run,
211            json!({
212                "action": "would_post",
213                "draft_id": serde_json::Value::Null,
214                "title": args.title,
215                "assignment_type": args.assignment_type.as_str(),
216                "budget_max": args.budget,
217                "settlement_venue": args.venue,
218                "required_capabilities": args.capabilities,
219                "completion_criteria_count": prep_body.completion_criteria.len(),
220                "rpc_url": rpc_url,
221                "wallet_address": pre.wallet_address,
222            }),
223        ));
224    }
225
226    let client = ctx.client()?;
227
228    // Resolve the RPC URL. Default path: pull it from the deployment's
229    // `GET /config/network` (public). Override path: user supplied
230    // `--rpc-url` / `TEMPO_RPC_URL` and must also pass
231    // `--allow-custom-endpoints` (already checked in preflight).
232    let rpc_url = match pre.rpc_url_override {
233        Some(override_url) => override_url,
234        None => resolve_proxy_rpc_url(&client, ctx).await?,
235    };
236
237    // Phase 1 — prepare. Server returns ERC-20 transfer calldata + draft_id.
238    let prep = match client.inner().prepare_task_draft(&prep_body).await {
239        Ok(r) => r.into_inner(),
240        Err(e) => return Err(map_api_error(e).await.into()),
241    };
242
243    let token_address: Address = prep.token_address.parse().map_err(|e| {
244        CmdError::Server(format!(
245            "server returned invalid token_address `{}`: {e}",
246            prep.token_address
247        ))
248    })?;
249    let calldata = decode_0x_bytes(&prep.payload_to_sign)
250        .map_err(|e| CmdError::Server(format!("server returned invalid payload_to_sign: {e}")))?;
251
252    // Load signer only after prepare succeeds — avoids prompting the user for
253    // a keystore password on a request that never leaves local validation.
254    let keystore_ref = args.keystore.as_deref().map(str::to_string).or_else(|| {
255        ctx.keystore_path
256            .as_deref()
257            .and_then(|p| p.to_str().map(str::to_string))
258    });
259    let signer = super::wallet_args::load_signer(
260        keystore_ref.as_deref(),
261        args.wallet_password_file.as_deref(),
262        "submission fee",
263    )?;
264    // Sanity: the wallet address in the draft must match what we're signing
265    // with. A mismatch means the server recorded a charge on a wallet we
266    // don't control, which would poll forever.
267    let parsed_wallet_address = pre
268        .wallet_address
269        .parse::<Address>()
270        .map_err(|_| CmdError::Usage(format!("invalid wallet address: {}", pre.wallet_address)))?;
271    if signer.address() != parsed_wallet_address {
272        return Err(CmdError::Usage(format!(
273            "keystore address {:#x} does not match --wallet-address {}",
274            signer.address(),
275            pre.wallet_address
276        )));
277    }
278
279    // Pick the http client by URL, not by resolution branch: any URL
280    // landing on `{api_base}/rpc/` is the authenticated proxy and
281    // needs `X-API-Key` (set as a default header on `client.http_client()`).
282    // A `--rpc-url`/`TEMPO_RPC_URL` override that points at the proxy
283    // hit this same path; the prior `via_proxy` flag missed that case
284    // and dropped the header, returning 401 "missing API key".
285    let http = ctx.rpc_http_client(&client, &rpc_url);
286    let rpc = TempoRpcClient::new(http, rpc_url.clone());
287
288    // F1: consult the chain's own `eth_chainId` (not anything the server
289    // claims) and refuse to sign a `transfer` against a token that isn't
290    // on the PathUSD allowlist for that chain. A compromised TaskFast API
291    // returning an attacker `token_address` is the fund-drain vector here.
292    let chain_id = rpc
293        .chain_id()
294        .await
295        .map_err(|e| CmdError::Server(format!("tempo rpc eth_chainId: {e}")))?;
296    if !ctx.allow_custom_endpoints && !is_known_network(chain_id) {
297        return Err(CmdError::Validation {
298            code: "unknown_chain".into(),
299            message: format!(
300                "RPC reports chain_id={chain_id} which is not a known Tempo or \
301                 local-dev network; refusing to sign. Pass --allow-custom-endpoints \
302                 to override."
303            ),
304        });
305    }
306    if !is_allowed_fee_token(chain_id, &prep.token_address) {
307        return Err(CmdError::Validation {
308            code: "fee_token_not_allowed".into(),
309            message: format!(
310                "server returned token_address {} which is not on the PathUSD \
311                 allowlist for chain_id={chain_id}. Refusing to sign — this would \
312                 redirect your fee transfer to an arbitrary ERC-20 contract.",
313                prep.token_address
314            ),
315        });
316    }
317
318    // Audit line — always emitted to stderr so a CI log captures the exact
319    // recipient+token+chain we committed funds to. Not a prompt: CLI stays
320    // non-interactive.
321    eprintln!(
322        "taskfast: signing submission-fee transfer — token={} chain_id={} rpc={}",
323        prep.token_address, chain_id, rpc_url
324    );
325
326    // F9: serialize nonce-consuming sign+broadcast per wallet. `_guard`
327    // holds the exclusive file lock from here until function return,
328    // which scope-covers both eth_getTransactionCount (inside
329    // sign_and_broadcast_erc20_transfer) and eth_sendRawTransaction.
330    // Locked on the keystore path (stripping the optional `file:` prefix
331    // that `taskfast init` writes) so two processes sharing a keystore
332    // can't race, while distinct wallets proceed in parallel.
333    let _guard = if let Some(ref raw) = keystore_ref {
334        let path_str = raw.strip_prefix("file:").unwrap_or(raw);
335        Some(crate::wallet_lock::acquire(std::path::Path::new(path_str))?)
336    } else {
337        None
338    };
339
340    let tx_hash =
341        sign_and_broadcast_erc20_transfer(&rpc, &signer, token_address, Bytes::from(calldata))
342            .await
343            .map_err(|e| CmdError::Server(format!("tempo rpc: {e}")))?;
344    let tx_hash_hex = format!("{tx_hash:#x}");
345
346    // Phase 2 — submit voucher. The field is named `signature` for historical
347    // reasons; semantically it's a voucher (tx hash, in our path).
348    let signature: TaskDraftSubmitRequestSignature = tx_hash_hex
349        .parse()
350        .map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?;
351    let submit_body = TaskDraftSubmitRequest { signature };
352    let submitted = match client
353        .inner()
354        .submit_task_draft(&prep.draft_id, &submit_body)
355        .await
356    {
357        Ok(r) => r.into_inner(),
358        Err(e) => return Err(map_api_error(e).await.into()),
359    };
360
361    // gh#156: a task created at `blocked_on_submission_fee_debt` looks like a
362    // stalled post unless the envelope says otherwise. The draft-submit
363    // response carries no server `message` (the server's message exists only
364    // on the direct `POST /tasks` create view), so when the task lands
365    // blocked we mirror the server's canonical create message — the envelope
366    // then distinguishes "waiting for the fee tx to confirm" from "post
367    // failed". `submission_fee_status` above carries the machine state.
368    let blocked = submitted.status == "blocked_on_submission_fee_debt";
369    if blocked {
370        // stderr audit line, same contract as the signing line above — a CI
371        // log must show WHY the task is not `open` yet and how to watch it.
372        eprintln!(
373            "taskfast: task {} parked at blocked_on_submission_fee_debt — \
374             submission-fee transfer confirming on-chain; it opens automatically \
375             once confirmed. Poll `taskfast task get {}`.",
376            submitted.id, submitted.id
377        );
378    }
379    let message = blocked.then(|| {
380        "Task created. Submission fee transaction is pending on-chain \
381         confirmation before the task becomes actionable."
382            .to_string()
383    });
384
385    Ok(Envelope::success(
386        ctx.environment,
387        ctx.dry_run,
388        json!({
389            "task_id": submitted.id,
390            "draft_id": prep.draft_id,
391            "submission_fee_tx_hash": tx_hash_hex,
392            "status": submitted.status,
393            "submission_fee_status": submitted.submission_fee_status,
394            "message": message,
395        }),
396    ))
397}
398
399/// Everything [`run`] needs from local validation, parsed once by
400/// [`preflight`] so the runtime path never re-validates (gh#144).
401struct Preflight {
402    wallet_address: String,
403    direct_agent_id: Option<Uuid>,
404    execution_deadline: Option<chrono::DateTime<chrono::Utc>>,
405    completion_criteria: Vec<CompletionCriterionInput>,
406    pickup_hours: TaskDraftPrepareRequestPickupDeadlineHours,
407    /// User-supplied `--rpc-url` / `TEMPO_RPC_URL`, already through the
408    /// custom-endpoint guard. `None` = resolve the deployment's proxy URL.
409    rpc_url_override: Option<String>,
410}
411
412/// Bare problem text for the preflight list — `Display` on these variants
413/// carries an `usage:` / `validation [code]:` prefix that reads as noise
414/// inside an enumerated list (the envelope's `error.code` already classifies).
415fn problem_text(e: &CmdError) -> String {
416    match e {
417        CmdError::Usage(m) => m.clone(),
418        CmdError::Validation { message, .. } => message.clone(),
419        other => other.to_string(),
420    }
421}
422
423/// gh#144 one-pass input validation. Every locally-checkable problem with
424/// the invocation — missing/blank required values, malformed addresses and
425/// UUIDs, bad timestamps, unparseable criteria, out-of-contract pickup
426/// windows, endpoint-guard conflicts, the budget gate — is collected and
427/// reported in a single enumerated `Usage` error, so fixing one problem
428/// never reveals exactly one more. Runs before any HTTP, keystore prompt,
429/// or signing, and short-circuits `--dry-run` the same way.
430///
431/// Error message texts are unchanged from the former sequential checks —
432/// orchestrators scraping them see the same strings, just together.
433fn preflight(ctx: &Ctx, args: &Args) -> Result<Preflight, CmdError> {
434    let mut problems: Vec<String> = Vec::new();
435    // Each check stores one validated field as `Option`; `None` marks
436    // "check failed, problem already recorded" so every later check still
437    // runs and reports too.
438
439    if args.description.trim().is_empty() {
440        problems.push(
441            "--description must not be empty (server requires a non-blank description)".into(),
442        );
443    }
444
445    if let Err(e) = ctx.enforce_budget_gate(args.budget.as_deref(), args.yes, "post a task") {
446        problems.push(problem_text(&e));
447    }
448
449    let wallet_address = match args
450        .wallet_address
451        .as_deref()
452        .or(ctx.wallet_address.as_deref())
453    {
454        Some(w) => match w.parse::<Address>() {
455            Ok(_) => Some(w.to_string()),
456            Err(e) => {
457                problems.push(format!("--wallet-address is not a valid EVM address: {e}"));
458                None
459            }
460        },
461        None => {
462            problems.push(
463                "--wallet-address (or TEMPO_WALLET_ADDRESS, or wallet_address in config) required to post a task".into(),
464            );
465            None
466        }
467    };
468
469    let direct_agent_id = match (args.assignment_type, args.direct_agent_id.as_deref()) {
470        (AssignmentType::Direct, Some(s)) => match Uuid::parse_str(s) {
471            Ok(u) => Some(Some(u)),
472            Err(e) => {
473                problems.push(format!("--direct-agent-id not a UUID: {e}"));
474                None
475            }
476        },
477        (AssignmentType::Direct, None) => {
478            problems.push("--assignment-type=direct requires --direct-agent-id".into());
479            None
480        }
481        (AssignmentType::Open, _) => Some(None),
482    };
483
484    let execution_deadline =
485        match parse_iso_opt(args.execution_deadline.as_deref(), "--execution-deadline") {
486            Ok(v) => Some(v),
487            Err(e) => {
488                problems.push(problem_text(&e));
489                None
490            }
491        };
492
493    let completion_criteria = match resolve_criteria(args.criteria_file.as_deref(), &args.criteria)
494    {
495        Ok(v) => Some(v),
496        Err(e) => {
497            problems.push(problem_text(&e));
498            None
499        }
500    };
501
502    let pickup_hours = match pickup_hours_to_wire(args.pickup_deadline_hours) {
503        Ok(w) => Some(w),
504        Err(e) => {
505            problems.push(problem_text(&e));
506            None
507        }
508    };
509
510    let rpc_url_override = match args.rpc_url.as_deref() {
511        Some(u) => match validate_override_rpc_url(
512            u,
513            ctx.environment.network(),
514            ctx.allow_custom_endpoints,
515        ) {
516            Ok(u) => Some(Some(u.to_string())),
517            Err(e) => {
518                problems.push(problem_text(&e));
519                None
520            }
521        },
522        None => Some(None),
523    };
524
525    if !problems.is_empty() {
526        let n = problems.len();
527        let list = problems
528            .iter()
529            .enumerate()
530            .map(|(i, p)| format!("  {}. {p}", i + 1))
531            .collect::<Vec<_>>()
532            .join("\n");
533        return Err(CmdError::Usage(format!(
534            "post preflight found {n} problem{}:\n{list}",
535            if n == 1 { "" } else { "s" }
536        )));
537    }
538
539    Ok(Preflight {
540        wallet_address: wallet_address.expect("no problems ⇒ wallet present"),
541        direct_agent_id: direct_agent_id.expect("no problems ⇒ direct id resolved"),
542        execution_deadline: execution_deadline.expect("no problems ⇒ deadline resolved"),
543        completion_criteria: completion_criteria.expect("no problems ⇒ criteria resolved"),
544        pickup_hours: pickup_hours.expect("no problems ⇒ pickup hours valid"),
545        rpc_url_override: rpc_url_override.expect("no problems ⇒ rpc override resolved"),
546    })
547}
548
549/// Resolve the deployment's proxied RPC endpoint for a post invocation that
550/// did not supply `--rpc-url` (the override path is handled in [`preflight`]).
551///
552/// The deployment's `/config/network` entry for the selected network points
553/// the CLI at `{api_base}/rpc/{network}`, which the server proxies to its
554/// own Tempo upstream (Alchemy by default). The caller should carry the
555/// authenticated reqwest::Client through to `TempoRpcClient`.
556async fn resolve_proxy_rpc_url(client: &TaskFastClient, ctx: &Ctx) -> Result<String, CmdError> {
557    let cfg = client.fetch_network_config().await.map_err(|e| match e {
558        taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
559            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
560        }
561        other => CmdError::from(other),
562    })?;
563    // Runtime invariant — issue #62 (server-side): the env's deployment must
564    // advertise exactly its one network, and nothing else.
565    //
566    // Today's deployments still advertise multiple networks per response;
567    // until #62 lands, a `len != 1` mismatch logs a warn and continues.
568    // Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed.
569    // `--allow-custom-endpoints` and `Environment::Local` bypass entirely
570    // (matches `enforce_endpoint_guard`).
571    let name = ctx.environment.network().as_str();
572    if !ctx.allow_custom_endpoints
573        && ctx.environment != crate::Environment::Local
574        && cfg.networks.len() != 1
575    {
576        let advertised: Vec<&str> = cfg.networks.keys().map(String::as_str).collect();
577        let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
578            .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
579        if strict {
580            return Err(CmdError::Server(format!(
581                "deployment at {} advertises networks {advertised:?}; env {} requires \
582                 exactly [{name}]. Server-side fix tracked in issue #62. Unset \
583                 TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
584                ctx.base_url(),
585                ctx.environment.as_str(),
586            )));
587        }
588        tracing::warn!(
589            api_base = %ctx.base_url(),
590            env = ctx.environment.as_str(),
591            expected = name,
592            advertised = ?advertised,
593            "deployment advertises additional networks; server-side fix tracked in #62. \
594             Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed."
595        );
596    }
597    let entry = cfg.entry(name).map_err(|e| {
598        CmdError::Server(format!(
599            "deployment at {} does not advertise network `{name}`: {e}",
600            ctx.base_url()
601        ))
602    })?;
603    // F2-equivalent guard, minus the static allowlist: the old
604    // WELL_KNOWN_TEMPO_RPCS check trusted exactly two hardcoded URLs. The
605    // replacement says "the proxy must live on the same host as the api_base
606    // the endpoint-guard already approved" — the path it's mounted at
607    // (`/rpc/…` or `/api/rpc/…`) is the server's choice. Catches (a) a
608    // misconfigured deployment returning an upstream URL instead of its own
609    // proxy, and (b) a compromised backend trying to steer RPC traffic
610    // off-host — minus a full MITM on api_base itself (which has its own
611    // F5/F6 defenses).
612    if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
613        return Err(CmdError::Server(format!(
614            "deployment at {} returned rpc_url {:?} for network `{name}`, \
615             which is not on the same host. Refusing to route RPC traffic \
616             off-host.",
617            ctx.base_url(),
618            entry.rpc_url,
619        )));
620    }
621    Ok(entry.rpc_url.clone())
622}
623
624/// Merge file-sourced and inline `--criterion` payloads into one validated
625/// list of `CompletionCriterionInput`. File entries are prepended so a
626/// shared base file can be augmented with one-off overrides on the command
627/// line. Any shape/parse failure is a `Usage` error — the CLI catches it
628/// before the request ever reaches the server, so the exit-code contract
629/// (Auth=re-credential, Validation=server-rejected payload) stays clean.
630fn resolve_criteria(
631    file: Option<&std::path::Path>,
632    inline: &[String],
633) -> Result<Vec<CompletionCriterionInput>, CmdError> {
634    let mut out = Vec::with_capacity(inline.len());
635    if let Some(path) = file {
636        let raw = std::fs::read_to_string(path).map_err(|e| {
637            CmdError::Usage(format!("read --criteria-file {}: {e}", path.display()))
638        })?;
639        let parsed: Vec<CompletionCriterionInput> = serde_json::from_str(&raw).map_err(|e| {
640            CmdError::Usage(format!(
641                "--criteria-file {} is not a JSON array of CompletionCriterionInput: {e}",
642                path.display()
643            ))
644        })?;
645        out.extend(parsed);
646    }
647    for (i, raw) in inline.iter().enumerate() {
648        let one: CompletionCriterionInput = serde_json::from_str(raw)
649            .map_err(|e| CmdError::Usage(format!("--criterion[{i}] not valid JSON: {e}")))?;
650        out.push(one);
651    }
652    Ok(out)
653}
654
655fn parse_iso_opt(
656    s: Option<&str>,
657    flag: &str,
658) -> Result<Option<chrono::DateTime<chrono::Utc>>, CmdError> {
659    match s {
660        None => Ok(None),
661        Some(raw) => chrono::DateTime::parse_from_rfc3339(raw)
662            .map(|d| Some(d.with_timezone(&chrono::Utc)))
663            .map_err(|e| CmdError::Usage(format!("{flag} not a valid RFC3339 timestamp: {e}"))),
664    }
665}
666
667fn decode_0x_bytes(s: &str) -> Result<Vec<u8>, String> {
668    let stripped = s.strip_prefix("0x").unwrap_or(s);
669    hex::decode(stripped).map_err(|e| e.to_string())
670}
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675    use crate::Network;
676
677    #[test]
678    fn validate_override_rejects_without_opt_in() {
679        let err = validate_override_rpc_url("https://mallory.example", Network::Mainnet, false)
680            .expect_err("override without opt-in must be refused");
681        match err {
682            CmdError::Usage(msg) => {
683                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
684            }
685            other => panic!("expected Usage, got {other:?}"),
686        }
687    }
688
689    #[test]
690    fn validate_override_accepts_with_opt_in() {
691        validate_override_rpc_url("https://my-node.example", Network::Testnet, true)
692            .expect("opt-in bypasses the guard");
693    }
694
695    #[test]
696    fn validate_override_rejects_plain_http_on_mainnet() {
697        let err = validate_override_rpc_url("http://my-node.example", Network::Mainnet, true)
698            .expect_err("plain-http on mainnet is always refused (except loopback)");
699        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("plain-HTTP")));
700    }
701
702    #[test]
703    fn validate_override_allows_plain_http_loopback_on_mainnet() {
704        validate_override_rpc_url("http://127.0.0.1:8545", Network::Mainnet, true)
705            .expect("loopback bypasses mainnet-HTTPS check");
706        validate_override_rpc_url("http://localhost:8545", Network::Mainnet, true)
707            .expect("loopback bypasses mainnet-HTTPS check");
708    }
709
710    #[test]
711    fn validate_override_allows_plain_http_on_testnet() {
712        validate_override_rpc_url("http://my-testnet.example", Network::Testnet, true)
713            .expect("testnet does not enforce HTTPS");
714    }
715
716    #[test]
717    fn pickup_hours_conversion_follows_api_contract() {
718        // The allowed set lives only in the vendored spec (via the generated
719        // newtype) — an out-of-set value maps to a validation error without
720        // the CLI restating the list anywhere.
721        let err = pickup_hours_to_wire(3).expect_err("3 is outside the contract set");
722        assert!(matches!(err, CmdError::Validation { .. }));
723        // A contract-valid choice converts to the exact wire integer.
724        let wire = pickup_hours_to_wire(24).expect("24 is contract-valid");
725        assert_eq!(i64::from(wire), 24);
726    }
727
728    #[test]
729    fn network_name_matches_config_map_keys() {
730        // The lookup key into `GET /config/network`'s `networks` map.
731        // Must stay in sync with what the deployment advertises.
732        assert_eq!(Network::Mainnet.as_str(), "mainnet");
733        assert_eq!(Network::Testnet.as_str(), "testnet");
734    }
735}