Skip to main content

taskfast_cli/cmd/
webhook.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast webhook` — configure, test, subscribe, inspect, delete.
3//!
4//! Replaces `scripts/webhook-setup.sh`. All HTTP work lives in
5//! `taskfast_agent::webhooks`; this module is the thin clap + envelope
6//! layer.
7//!
8//! # Secret-file contract
9//!
10//! The platform returns the signing secret exactly once (see
11//! `spec/openapi.yaml:2264-2269`). `register` persists it to
12//! `--secret-file` with mode `0600` on unix. If the server returns a
13//! null secret (idempotent PUT on existing config), we leave any
14//! existing secret file untouched — never silently truncate a
15//! persisted secret the caller may still rely on.
16
17use std::path::PathBuf;
18
19use clap::{Parser, Subcommand};
20use serde_json::json;
21
22use super::{CmdError, CmdResult, Ctx};
23use crate::envelope::Envelope;
24
25use taskfast_agent::webhooks;
26use taskfast_client::api::types::WebhookConfigRequest;
27
28/// Default subscription set for a fresh worker. Matches the list
29/// `scripts/webhook-setup.sh` hard-coded. Kept here only as a
30/// convenience default for `subscribe --default-events`; the
31/// authoritative list lives on the server and is surfaced by
32/// `webhook subscribe --list` (via `GET /webhooks/subscriptions`).
33pub const DEFAULT_WORKER_EVENTS: &[&str] = &[
34    "task_assigned",
35    "bid_accepted",
36    "bid_rejected",
37    "pickup_deadline_warning",
38    "payment_held",
39    "payment_disbursed",
40    "dispute_resolved",
41    "review_received",
42    "message_received",
43];
44
45#[derive(Debug, Subcommand)]
46pub enum Command {
47    /// PUT /agents/me/webhooks — create or update the endpoint. On first
48    /// creation the server returns the HMAC signing secret; pass
49    /// `--secret-file` to persist it (chmod 600).
50    Register(RegisterArgs),
51    /// POST /agents/me/webhooks/test — ask the platform to deliver a
52    /// signed test event and report the receipt.
53    Test,
54    /// PUT /agents/me/webhooks/subscriptions — replace the subscribed
55    /// event list.
56    Subscribe(SubscribeArgs),
57    /// GET /agents/me/webhooks — current config (secret always null).
58    Get,
59    /// DELETE /agents/me/webhooks — unsubscribe this agent.
60    Delete,
61}
62
63#[derive(Debug, Parser)]
64pub struct RegisterArgs {
65    /// HTTPS URL the platform will POST events to.
66    #[arg(long)]
67    pub url: String,
68
69    /// Path to persist the signing secret when the server returns one.
70    /// On unix the file is chmod'd to 0600. Existing files are
71    /// overwritten only when a fresh secret is present; a null secret
72    /// (idempotent re-register) leaves the file untouched.
73    #[arg(long)]
74    pub secret_file: Option<PathBuf>,
75
76    /// Subscribe to an event type. Repeat to pass multiple. Optional —
77    /// `taskfast webhook subscribe` can be run separately. Bypasses
78    /// the subscription step when omitted.
79    #[arg(long = "event", value_name = "EVENT")]
80    pub events: Vec<String>,
81}
82
83#[derive(Debug, Parser)]
84pub struct SubscribeArgs {
85    /// Event type to subscribe to. Repeat to pass multiple. Mutually
86    /// exclusive with `--default-events` and `--list`.
87    #[arg(long = "event", value_name = "EVENT", conflicts_with_all = ["default_events", "list"])]
88    pub events: Vec<String>,
89
90    /// Subscribe to the built-in worker default set (see
91    /// `DEFAULT_WORKER_EVENTS`). Convenience shortcut so orchestrators
92    /// don't have to hard-code the list.
93    #[arg(long, conflicts_with_all = ["events", "list"])]
94    pub default_events: bool,
95
96    /// Just list currently-subscribed + available event types; no
97    /// mutation.
98    #[arg(long, conflicts_with_all = ["events", "default_events"])]
99    pub list: bool,
100}
101
102pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
103    match cmd {
104        Command::Register(args) => register(ctx, args).await,
105        Command::Test => test(ctx).await,
106        Command::Subscribe(args) => subscribe(ctx, args).await,
107        Command::Get => get(ctx).await,
108        Command::Delete => delete(ctx).await,
109    }
110}
111
112/// Result of multi-step webhook provisioning (PUT /webhooks, secret persistence, PUT /subscriptions).
113#[derive(Debug, Clone)]
114pub struct WebhookProvisionOutcome {
115    pub url: String,
116    pub secret_returned: bool,
117    pub secret_persisted: bool,
118    pub secret_file: Option<PathBuf>,
119    pub subscribed: Option<Vec<String>>,
120}
121
122/// Orchestrate the multi-step webhook provisioning flow:
123/// 1. Configure the webhook endpoint via `PUT /agents/me/webhooks`.
124/// 2. Persist the returned secret (if any and if path provided) via `persist_secret` with mode 0600.
125/// 3. Replace subscriptions via `PUT /agents/me/webhooks/subscriptions` if non-empty events provided.
126pub async fn provision_webhook(
127    client: &taskfast_client::TaskFastClient,
128    url: &str,
129    secret_file: Option<&std::path::Path>,
130    events: &[String],
131) -> Result<WebhookProvisionOutcome, CmdError> {
132    let body = WebhookConfigRequest {
133        url: url.to_string(),
134        secret: None,
135        // Per spec, `events` here is informational — the server tracks
136        // subscriptions independently via the /subscriptions endpoint.
137        // Left empty on PUT so re-registering the URL doesn't clobber
138        // a carefully-curated subscription list.
139        events: None,
140    };
141    let cfg = webhooks::configure_webhook(client, &body)
142        .await
143        .map_err(CmdError::from)?;
144
145    let secret_persisted = match (cfg.secret.as_deref(), secret_file) {
146        (Some(secret), Some(path)) => {
147            persist_secret(path, secret)?;
148            true
149        }
150        _ => false,
151    };
152
153    let subscribed = if events.is_empty() {
154        None
155    } else {
156        let subs = webhooks::update_subscriptions(client, events.to_vec())
157            .await
158            .map_err(CmdError::from)?;
159        Some(subs.subscribed_event_types)
160    };
161
162    Ok(WebhookProvisionOutcome {
163        url: cfg.url,
164        secret_returned: cfg.secret.is_some(),
165        secret_persisted,
166        secret_file: secret_file.map(std::path::Path::to_path_buf),
167        subscribed,
168    })
169}
170
171async fn register(ctx: &Ctx, args: RegisterArgs) -> CmdResult {
172    if args.url.trim().is_empty() {
173        return Err(CmdError::Usage("--url must not be empty".into()));
174    }
175
176    if ctx.dry_run {
177        return Ok(Envelope::success(
178            ctx.environment,
179            ctx.dry_run,
180            json!({
181                "action": "would_register",
182                "url": args.url,
183                "events": args.events,
184                "secret_file": args.secret_file.as_ref().map(|p| p.display().to_string()),
185            }),
186        ));
187    }
188
189    let client = ctx.client()?;
190    let outcome = provision_webhook(
191        &client,
192        &args.url,
193        args.secret_file.as_deref(),
194        &args.events,
195    )
196    .await?;
197
198    let mut data = json!({
199        "action": "registered",
200        "url": outcome.url,
201        "secret_returned": outcome.secret_returned,
202        "secret_persisted": outcome.secret_persisted,
203    });
204    if let Some(path) = outcome.secret_file.as_ref() {
205        data["secret_file"] = json!(path.display().to_string());
206    }
207    if let Some(subscribed) = outcome.subscribed {
208        data["subscription"] = json!({
209            "subscribed": subscribed,
210        });
211    }
212    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
213}
214
215async fn test(ctx: &Ctx) -> CmdResult {
216    if ctx.dry_run {
217        return Ok(Envelope::success(
218            ctx.environment,
219            ctx.dry_run,
220            json!({ "action": "would_test" }),
221        ));
222    }
223    let client = ctx.client()?;
224    let receipt = webhooks::test_webhook(&client)
225        .await
226        .map_err(CmdError::from)?;
227    Ok(Envelope::success(
228        ctx.environment,
229        ctx.dry_run,
230        json!({
231            "success": receipt.success,
232            "status_code": receipt.status_code,
233            "message": receipt.message,
234        }),
235    ))
236}
237
238async fn subscribe(ctx: &Ctx, args: SubscribeArgs) -> CmdResult {
239    let client = ctx.client()?;
240
241    if args.list {
242        let subs = webhooks::get_subscriptions(&client)
243            .await
244            .map_err(CmdError::from)?;
245        return Ok(Envelope::success(
246            ctx.environment,
247            ctx.dry_run,
248            json!({
249                "subscribed": subs.subscribed_event_types,
250                "available": subs.available_event_types,
251            }),
252        ));
253    }
254
255    let events: Vec<String> = if args.default_events {
256        DEFAULT_WORKER_EVENTS
257            .iter()
258            .map(|e| (*e).to_string())
259            .collect()
260    } else if !args.events.is_empty() {
261        args.events.clone()
262    } else {
263        return Err(CmdError::Usage(
264            "pass --event <NAME> (repeatable), --default-events, or --list".into(),
265        ));
266    };
267
268    if ctx.dry_run {
269        return Ok(Envelope::success(
270            ctx.environment,
271            ctx.dry_run,
272            json!({
273                "action": "would_subscribe",
274                "events": events,
275            }),
276        ));
277    }
278
279    let subs = webhooks::update_subscriptions(&client, events)
280        .await
281        .map_err(CmdError::from)?;
282    Ok(Envelope::success(
283        ctx.environment,
284        ctx.dry_run,
285        json!({
286            "subscribed": subs.subscribed_event_types,
287            "available": subs.available_event_types,
288        }),
289    ))
290}
291
292async fn get(ctx: &Ctx) -> CmdResult {
293    let client = ctx.client()?;
294    let cfg = webhooks::get_webhook(&client)
295        .await
296        .map_err(CmdError::from)?;
297    Ok(Envelope::success(
298        ctx.environment,
299        ctx.dry_run,
300        json!({
301            "url": cfg.url,
302            "events": cfg.events,
303            "created_at": cfg.created_at,
304            "updated_at": cfg.updated_at,
305        }),
306    ))
307}
308
309async fn delete(ctx: &Ctx) -> CmdResult {
310    if ctx.dry_run {
311        return Ok(Envelope::success(
312            ctx.environment,
313            ctx.dry_run,
314            json!({ "action": "would_delete" }),
315        ));
316    }
317    let client = ctx.client()?;
318    webhooks::delete_webhook(&client)
319        .await
320        .map_err(CmdError::from)?;
321    Ok(Envelope::success(
322        ctx.environment,
323        ctx.dry_run,
324        json!({ "action": "deleted" }),
325    ))
326}
327
328/// Persist the webhook signing secret atomically with 0600 perms on unix from file creation.
329///
330/// Delegates to [`crate::state_store::StateStore::atomic_write_file`], eliminating any umask
331/// window before permissions tightening.
332pub(crate) fn persist_secret(path: &std::path::Path, secret: &str) -> Result<(), CmdError> {
333    crate::state_store::StateStore::atomic_write_file(path, secret.as_bytes())
334        .map_err(|e| CmdError::Usage(format!("write secret {}: {e}", path.display())))
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    use tempfile::TempDir;
341
342    #[test]
343    fn persist_secret_writes_file_with_tight_perms() {
344        let tmp = TempDir::new().unwrap();
345        let path = tmp.path().join("hook.secret");
346        persist_secret(&path, "whsec_abc").unwrap();
347        let body = std::fs::read_to_string(&path).unwrap();
348        assert_eq!(body, "whsec_abc");
349        #[cfg(unix)]
350        {
351            use std::os::unix::fs::PermissionsExt;
352            let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
353            assert_eq!(mode, 0o600, "secret file must be 0600");
354        }
355    }
356
357    #[test]
358    fn default_worker_events_match_shell_script_list() {
359        // Pin the list: this is the one documented in SKILL.md /
360        // BOOT.md and callers may rely on the exact set.
361        assert_eq!(
362            DEFAULT_WORKER_EVENTS,
363            &[
364                "task_assigned",
365                "bid_accepted",
366                "bid_rejected",
367                "pickup_deadline_warning",
368                "payment_held",
369                "payment_disbursed",
370                "dispute_resolved",
371                "review_received",
372                "message_received",
373            ]
374        );
375    }
376}