Skip to main content

taskfast_cli/cmd/
backer.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast backer` — manage an operator's external-backer allowlist
3//! (gh#54 Stream B, server #483 `OperatorBackerController`).
4//!
5//! These are owning-user operations: they authenticate with a user PAT
6//! (`tf_user_*`), NOT an agent key. Supply it via `--human-api-key` or
7//! `TASKFAST_HUMAN_API_KEY`; if neither is set it falls back to the standard
8//! `--api-key`/`TASKFAST_API_KEY` unconditionally. The token shape isn't
9//! screened locally — an agent key supplied that way is still sent and
10//! rejected server-side (401/403), surfaced here as an `Auth` error.
11//!
12//! `operator_id` is the operator's PK UUID. The platform has no "get my
13//! operator" endpoint yet, so it must be passed explicitly with `--operator` —
14//! you receive it in the `POST /operators` activation response.
15
16use clap::{Args, Subcommand};
17use serde_json::json;
18use uuid::Uuid;
19
20use super::{CmdError, CmdResult, Ctx};
21use crate::envelope::Envelope;
22
23use taskfast_client::api::types::OperatorBackerCreateRequest;
24use taskfast_client::{map_api_error, TaskFastClient};
25
26#[derive(Debug, Subcommand)]
27pub enum Command {
28    /// List the operator's approved backers.
29    List(ListArgs),
30    /// Approve a backer (account + wallet) for the operator.
31    Add(AddArgs),
32    /// Revoke an approved backer (blocks new stakes; posted bonds stand).
33    Revoke(RevokeArgs),
34}
35
36#[derive(Debug, Args)]
37pub struct ListArgs {
38    /// Operator PK UUID (from the `POST /operators` activation response).
39    #[arg(long)]
40    pub operator: String,
41    /// User PAT (`tf_user_*`). Falls back to the standard API key.
42    #[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
43    pub human_api_key: Option<String>,
44}
45
46#[derive(Debug, Args)]
47pub struct AddArgs {
48    /// Operator PK UUID.
49    #[arg(long)]
50    pub operator: String,
51    /// Backer account UUID (must be a human account).
52    #[arg(long)]
53    pub account: String,
54    /// Wallet the backer posts stakes from (`0x`-prefixed).
55    #[arg(long)]
56    pub wallet: String,
57    /// User PAT (`tf_user_*`). Falls back to the standard API key.
58    #[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
59    pub human_api_key: Option<String>,
60}
61
62#[derive(Debug, Args)]
63pub struct RevokeArgs {
64    /// Operator PK UUID.
65    #[arg(long)]
66    pub operator: String,
67    /// Backer allowlist entry UUID (the `id` from `backer list`).
68    #[arg(long)]
69    pub id: String,
70    /// User PAT (`tf_user_*`). Falls back to the standard API key.
71    #[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
72    pub human_api_key: Option<String>,
73}
74
75pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
76    match cmd {
77        Command::List(a) => list(ctx, a).await,
78        Command::Add(a) => add(ctx, a).await,
79        Command::Revoke(a) => revoke(ctx, a).await,
80    }
81}
82
83/// Build a client from the user PAT. Prefers `--human-api-key`
84/// (`TASKFAST_HUMAN_API_KEY`), then the standard API key, so a caller whose
85/// `TASKFAST_API_KEY` is already a user PAT needn't pass the flag twice.
86fn pat_client(ctx: &Ctx, human_api_key: Option<&str>) -> Result<TaskFastClient, CmdError> {
87    let key = human_api_key
88        .filter(|k| !k.trim().is_empty())
89        .or(ctx.api_key.as_deref())
90        .ok_or(CmdError::MissingApiKey)?;
91    TaskFastClient::from_api_key(ctx.base_url(), key).map_err(CmdError::from)
92}
93
94fn parse_operator(s: &str) -> Result<Uuid, CmdError> {
95    Uuid::parse_str(s).map_err(|e| CmdError::Usage(format!("--operator must be a UUID: {e}")))
96}
97
98async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
99    // A read — `--dry-run` only short-circuits mutations, so this always runs.
100    let operator_id = parse_operator(&args.operator)?;
101    let client = pat_client(ctx, args.human_api_key.as_deref())?;
102    let resp = match client.inner().list_operator_backers(&operator_id).await {
103        Ok(v) => v.into_inner(),
104        Err(e) => return Err(map_api_error(e).await.into()),
105    };
106    Ok(Envelope::success(
107        ctx.environment,
108        ctx.dry_run,
109        json!({ "backers": resp.backers }),
110    ))
111}
112
113async fn add(ctx: &Ctx, args: AddArgs) -> CmdResult {
114    let operator_id = parse_operator(&args.operator)?;
115    let backer_account_id = Uuid::parse_str(&args.account)
116        .map_err(|e| CmdError::Usage(format!("--account must be a UUID: {e}")))?;
117    let wallet_address = super::parse_wallet_address(&args.wallet)?;
118
119    if ctx.dry_run {
120        return Ok(Envelope::success(
121            ctx.environment,
122            ctx.dry_run,
123            json!({
124                "action": "would_add_backer",
125                "operator_id": operator_id.to_string(),
126                "backer_account_id": backer_account_id.to_string(),
127                "wallet_address": wallet_address,
128            }),
129        ));
130    }
131
132    let client = pat_client(ctx, args.human_api_key.as_deref())?;
133    // The request schema is an `anyOf` over the wallet key; send the canonical
134    // `backer_wallet_address` variant (the `wallet_address` alias is the same
135    // shape server-side).
136    let body = OperatorBackerCreateRequest::Variant0 {
137        backer_account_id,
138        backer_wallet_address: wallet_address,
139    };
140    let resp = match client
141        .inner()
142        .approve_operator_backer(&operator_id, &body)
143        .await
144    {
145        Ok(v) => v.into_inner(),
146        Err(e) => return Err(map_api_error(e).await.into()),
147    };
148    Ok(Envelope::success(
149        ctx.environment,
150        ctx.dry_run,
151        json!({ "backer": resp }),
152    ))
153}
154
155async fn revoke(ctx: &Ctx, args: RevokeArgs) -> CmdResult {
156    let operator_id = parse_operator(&args.operator)?;
157    let backer_id = Uuid::parse_str(&args.id)
158        .map_err(|e| CmdError::Usage(format!("--id must be a UUID: {e}")))?;
159
160    if ctx.dry_run {
161        return Ok(Envelope::success(
162            ctx.environment,
163            ctx.dry_run,
164            json!({
165                "action": "would_revoke_backer",
166                "operator_id": operator_id.to_string(),
167                "id": backer_id.to_string(),
168            }),
169        ));
170    }
171
172    let client = pat_client(ctx, args.human_api_key.as_deref())?;
173    let resp = match client
174        .inner()
175        .revoke_operator_backer(&operator_id, &backer_id)
176        .await
177    {
178        Ok(v) => v.into_inner(),
179        Err(e) => return Err(map_api_error(e).await.into()),
180    };
181    Ok(Envelope::success(
182        ctx.environment,
183        ctx.dry_run,
184        json!({ "backer": resp }),
185    ))
186}