Skip to main content

taskfast_agent/
webhooks.rs

1// SPDX-License-Identifier: MIT
2//! Webhook registration + HMAC-SHA256 signature verification.
3//!
4//! Six HTTP wrappers around `/agents/me/webhooks*` plus one offline
5//! verifier ([`verify_signature`]) that callers use inside their HTTP
6//! handler to authenticate incoming platform deliveries without
7//! round-tripping back to `POST /webhooks/verify`.
8//!
9//! # Signature format
10//!
11//! The platform (see `lib/task_fast/marketplace/webhook_delivery.ex`)
12//! sends each event with:
13//!
14//! - `X-Webhook-Signature` — lowercase hex of
15//!   `HMAC_SHA256(secret, timestamp ++ "." ++ body)`
16//! - `X-Webhook-Timestamp` — ISO 8601 UTC
17//! - `X-Webhook-Event`     — event type name
18//!
19//! Verification re-hashes the canonical string and constant-time-compares
20//! via [`hmac::Mac::verify_slice`]. Deliveries older than
21//! [`VerifyOptions::max_skew`] (default 5 min) are rejected on timestamp
22//! alone — this is the replay-protection window the platform docs
23//! promise at `openapi.yaml:2365`.
24
25use std::time::Duration;
26
27use hmac::{Hmac, KeyInit, Mac};
28use jiff::Timestamp;
29use sha2::Sha256;
30use taskfast_client::api::types::{
31    WebhookConfig, WebhookConfigRequest, WebhookSubscriptions, WebhookSubscriptionsUpdate,
32    WebhookTestSuccess,
33};
34use taskfast_client::{map_api_error, Result, TaskFastClient};
35use thiserror::Error as ThisError;
36
37type HmacSha256 = Hmac<Sha256>;
38
39/// Default replay window matching the server-side contract.
40pub const DEFAULT_MAX_SKEW: Duration = Duration::from_mins(5);
41
42/// `PUT /agents/me/webhooks` — create or replace the webhook configuration.
43///
44/// The returned `secret` is populated **only on first creation**; subsequent
45/// PUTs return `null` per the server contract (see
46/// `spec/openapi.yaml:2264-2269`). Persist the secret the first time or it
47/// is gone forever.
48pub async fn configure_webhook(
49    client: &TaskFastClient,
50    body: &WebhookConfigRequest,
51) -> Result<WebhookConfig> {
52    match client.inner().configure_webhook(body).await {
53        Ok(v) => Ok(v.into_inner()),
54        Err(e) => Err(map_api_error(e).await),
55    }
56}
57
58/// `GET /agents/me/webhooks` — current webhook config (secret always null).
59pub async fn get_webhook(client: &TaskFastClient) -> Result<WebhookConfig> {
60    match client.inner().get_webhook_config().await {
61        Ok(v) => Ok(v.into_inner()),
62        Err(e) => Err(map_api_error(e).await),
63    }
64}
65
66/// `DELETE /agents/me/webhooks` — unsubscribe this agent from deliveries.
67pub async fn delete_webhook(client: &TaskFastClient) -> Result<()> {
68    match client.inner().delete_webhook_config().await {
69        Ok(_) => Ok(()),
70        Err(e) => Err(map_api_error(e).await),
71    }
72}
73
74/// `POST /agents/me/webhooks/test` — ask the platform to deliver a signed
75/// `test` event so the caller can confirm their verifier works end-to-end.
76pub async fn test_webhook(client: &TaskFastClient) -> Result<WebhookTestSuccess> {
77    match client.inner().test_webhook().await {
78        Ok(v) => Ok(v.into_inner()),
79        Err(e) => Err(map_api_error(e).await),
80    }
81}
82
83/// `GET /agents/me/webhooks/subscriptions` — current + available event types.
84pub async fn get_subscriptions(client: &TaskFastClient) -> Result<WebhookSubscriptions> {
85    match client.inner().get_webhook_subscriptions().await {
86        Ok(v) => Ok(v.into_inner()),
87        Err(e) => Err(map_api_error(e).await),
88    }
89}
90
91/// `PUT /agents/me/webhooks/subscriptions` — full-replace subscription list.
92pub async fn update_subscriptions(
93    client: &TaskFastClient,
94    events: Vec<String>,
95) -> Result<WebhookSubscriptions> {
96    let body = WebhookSubscriptionsUpdate {
97        subscribed_event_types: events,
98    };
99    match client.inner().update_webhook_subscriptions(&body).await {
100        Ok(v) => Ok(v.into_inner()),
101        Err(e) => Err(map_api_error(e).await),
102    }
103}
104
105/// Tunables for [`verify_signature`]. `now` is an injection seam for tests
106/// so the 5-min skew check is deterministic without freezing global time.
107#[derive(Debug, Clone, Copy)]
108pub struct VerifyOptions {
109    pub max_skew: Duration,
110    pub now: Option<Timestamp>,
111}
112
113impl Default for VerifyOptions {
114    fn default() -> Self {
115        Self {
116            max_skew: DEFAULT_MAX_SKEW,
117            now: None,
118        }
119    }
120}
121
122/// Reasons [`verify_signature`] rejects a delivery. Split from
123/// [`taskfast_client::Error`] because signature verification is a pure,
124/// offline operation — it never interacts with the HTTP stack, so it
125/// shouldn't surface as a network/server-flavored error variant.
126#[derive(Debug, ThisError)]
127pub enum SignatureError {
128    #[error("signature timestamp not valid ISO 8601: {0}")]
129    InvalidTimestamp(String),
130    #[error("signature header is not valid hex")]
131    InvalidSignatureHex,
132    #[error("secret is empty")]
133    EmptySecret,
134    #[error("signature mismatch")]
135    Mismatch,
136    #[error("timestamp skew {skew_secs}s exceeds max {max_secs}s")]
137    TimestampSkewed { skew_secs: i64, max_secs: i64 },
138}
139
140/// Verify an incoming webhook delivery's `X-Webhook-Signature` header.
141///
142/// Canonical signed string is `{timestamp}.{body}`. `timestamp` is the raw
143/// `X-Webhook-Timestamp` header value — we hash the exact bytes the sender
144/// hashed, then parse it separately for the freshness check so malformed
145/// timestamps fail loudly rather than being coerced.
146pub fn verify_signature(
147    secret: &str,
148    timestamp: &str,
149    body: &str,
150    signature_hex: &str,
151    opts: VerifyOptions,
152) -> std::result::Result<(), SignatureError> {
153    if secret.is_empty() {
154        return Err(SignatureError::EmptySecret);
155    }
156
157    let parsed_ts: Timestamp = timestamp
158        .parse()
159        .map_err(|_| SignatureError::InvalidTimestamp(timestamp.to_string()))?;
160    let now = opts.now.unwrap_or_else(Timestamp::now);
161    let skew_secs = (now.as_second() - parsed_ts.as_second()).abs();
162    let max_secs = opts.max_skew.as_secs() as i64;
163    if skew_secs > max_secs {
164        return Err(SignatureError::TimestampSkewed {
165            skew_secs,
166            max_secs,
167        });
168    }
169
170    let provided = hex::decode(signature_hex).map_err(|_| SignatureError::InvalidSignatureHex)?;
171
172    // Mac::new_from_slice accepts any key length for HMAC; only length-0
173    // secrets are a protocol violation and we've already rejected those.
174    let mut mac =
175        HmacSha256::new_from_slice(secret.as_bytes()).map_err(|_| SignatureError::EmptySecret)?;
176    mac.update(timestamp.as_bytes());
177    mac.update(b".");
178    mac.update(body.as_bytes());
179    mac.verify_slice(&provided)
180        .map_err(|_| SignatureError::Mismatch)
181}
182
183/// Build the canonical signature hex for a given payload. Exposed so
184/// callers can produce matching signatures in their own tests without
185/// reimplementing the canonical-string rules.
186pub fn sign_payload(secret: &str, timestamp: &str, body: &str) -> String {
187    let mut mac =
188        HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC should accept non-empty secret");
189    mac.update(timestamp.as_bytes());
190    mac.update(b".");
191    mac.update(body.as_bytes());
192    hex::encode(mac.finalize().into_bytes())
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    const SECRET: &str = "whsec_test_1234567890";
200    const TS: &str = "2026-03-23T12:00:00Z";
201    const BODY: &str =
202        r#"{"event":"test","timestamp":"2026-03-23T12:00:00Z","data":{"message":"ok"}}"#;
203
204    fn fixed_now() -> Timestamp {
205        "2026-03-23T12:01:00Z".parse().unwrap()
206    }
207
208    fn opts_at(now: Timestamp) -> VerifyOptions {
209        VerifyOptions {
210            max_skew: DEFAULT_MAX_SKEW,
211            now: Some(now),
212        }
213    }
214
215    #[test]
216    fn sign_and_verify_roundtrip_accepts() {
217        let sig = sign_payload(SECRET, TS, BODY);
218        verify_signature(SECRET, TS, BODY, &sig, opts_at(fixed_now())).expect("valid signature");
219    }
220
221    #[test]
222    fn known_vector_matches_platform_elixir_impl() {
223        // HMAC-SHA256(secret="whsec_test_1234567890", "2026-03-23T12:00:00Z.BODY")
224        // hex-encoded — captured from a cross-check against the Elixir
225        // :crypto.mac/4 |> Base.encode16(case: :lower) pipeline.
226        let sig = sign_payload(SECRET, TS, BODY);
227        // 64 lowercase hex chars
228        assert_eq!(sig.len(), 64);
229        assert!(sig
230            .chars()
231            .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()));
232    }
233
234    #[test]
235    fn tampered_body_is_rejected() {
236        let sig = sign_payload(SECRET, TS, BODY);
237        let err = verify_signature(SECRET, TS, "{\"evil\":true}", &sig, opts_at(fixed_now()))
238            .unwrap_err();
239        assert!(matches!(err, SignatureError::Mismatch));
240    }
241
242    #[test]
243    fn tampered_timestamp_is_rejected_as_mismatch_when_in_window() {
244        // Different (but still-fresh) timestamp → hash mismatch, not skew.
245        let sig = sign_payload(SECRET, TS, BODY);
246        let other_ts = "2026-03-23T12:00:30Z";
247        let err = verify_signature(SECRET, other_ts, BODY, &sig, opts_at(fixed_now())).unwrap_err();
248        assert!(matches!(err, SignatureError::Mismatch));
249    }
250
251    #[test]
252    fn wrong_secret_is_rejected() {
253        let sig = sign_payload(SECRET, TS, BODY);
254        let err = verify_signature(
255            "whsec_wrong_0000000000",
256            TS,
257            BODY,
258            &sig,
259            opts_at(fixed_now()),
260        )
261        .unwrap_err();
262        assert!(matches!(err, SignatureError::Mismatch));
263    }
264
265    #[test]
266    fn stale_timestamp_is_rejected_even_with_valid_signature() {
267        let sig = sign_payload(SECRET, TS, BODY);
268        // 6 minutes after the signed timestamp — past 5-min window.
269        let late: Timestamp = "2026-03-23T12:06:01Z".parse().unwrap();
270        let err = verify_signature(SECRET, TS, BODY, &sig, opts_at(late)).unwrap_err();
271        assert!(matches!(err, SignatureError::TimestampSkewed { .. }));
272    }
273
274    #[test]
275    fn malformed_timestamp_fails_before_hmac() {
276        let sig = sign_payload(SECRET, TS, BODY);
277        let err =
278            verify_signature(SECRET, "not-a-date", BODY, &sig, opts_at(fixed_now())).unwrap_err();
279        assert!(matches!(err, SignatureError::InvalidTimestamp(_)));
280    }
281
282    #[test]
283    fn non_hex_signature_is_rejected() {
284        let err =
285            verify_signature(SECRET, TS, BODY, "not-hex-!!", opts_at(fixed_now())).unwrap_err();
286        assert!(matches!(err, SignatureError::InvalidSignatureHex));
287    }
288
289    #[test]
290    fn empty_secret_is_rejected() {
291        let sig = sign_payload(SECRET, TS, BODY);
292        let err = verify_signature("", TS, BODY, &sig, opts_at(fixed_now())).unwrap_err();
293        assert!(matches!(err, SignatureError::EmptySecret));
294    }
295
296    #[test]
297    fn constant_time_compare_rejects_truncated_signature() {
298        let sig = sign_payload(SECRET, TS, BODY);
299        let truncated = &sig[..sig.len() - 2];
300        let err = verify_signature(SECRET, TS, BODY, truncated, opts_at(fixed_now())).unwrap_err();
301        // Length mismatch surfaces as Mismatch (verify_slice rejects
302        // wrong-length tags even before constant-time compare).
303        assert!(matches!(err, SignatureError::Mismatch));
304    }
305
306    #[test]
307    fn future_timestamp_beyond_window_is_rejected() {
308        let sig = sign_payload(SECRET, TS, BODY);
309        // Signed "in the future" relative to now; absolute skew > 5 min.
310        let past_now: Timestamp = "2026-03-23T11:50:00Z".parse().unwrap();
311        let err = verify_signature(SECRET, TS, BODY, &sig, opts_at(past_now)).unwrap_err();
312        assert!(matches!(err, SignatureError::TimestampSkewed { .. }));
313    }
314}