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