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 chrono::{DateTime, Utc};
28use hmac::{Hmac, KeyInit, Mac};
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<DateTime<Utc>>,
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 = DateTime::parse_from_rfc3339(timestamp)
158        .map_err(|_| SignatureError::InvalidTimestamp(timestamp.to_string()))?
159        .with_timezone(&Utc);
160    let now = opts.now.unwrap_or_else(Utc::now);
161    let skew_secs = (now - parsed_ts).num_seconds().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() -> DateTime<Utc> {
205        DateTime::parse_from_rfc3339("2026-03-23T12:01:00Z")
206            .unwrap()
207            .with_timezone(&Utc)
208    }
209
210    fn opts_at(now: DateTime<Utc>) -> VerifyOptions {
211        VerifyOptions {
212            max_skew: DEFAULT_MAX_SKEW,
213            now: Some(now),
214        }
215    }
216
217    #[test]
218    fn sign_and_verify_roundtrip_accepts() {
219        let sig = sign_payload(SECRET, TS, BODY);
220        verify_signature(SECRET, TS, BODY, &sig, opts_at(fixed_now())).expect("valid signature");
221    }
222
223    #[test]
224    fn known_vector_matches_platform_elixir_impl() {
225        // HMAC-SHA256(secret="whsec_test_1234567890", "2026-03-23T12:00:00Z.BODY")
226        // hex-encoded — captured from a cross-check against the Elixir
227        // :crypto.mac/4 |> Base.encode16(case: :lower) pipeline.
228        let sig = sign_payload(SECRET, TS, BODY);
229        // 64 lowercase hex chars
230        assert_eq!(sig.len(), 64);
231        assert!(sig
232            .chars()
233            .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()));
234    }
235
236    #[test]
237    fn tampered_body_is_rejected() {
238        let sig = sign_payload(SECRET, TS, BODY);
239        let err = verify_signature(SECRET, TS, "{\"evil\":true}", &sig, opts_at(fixed_now()))
240            .unwrap_err();
241        assert!(matches!(err, SignatureError::Mismatch));
242    }
243
244    #[test]
245    fn tampered_timestamp_is_rejected_as_mismatch_when_in_window() {
246        // Different (but still-fresh) timestamp → hash mismatch, not skew.
247        let sig = sign_payload(SECRET, TS, BODY);
248        let other_ts = "2026-03-23T12:00:30Z";
249        let err = verify_signature(SECRET, other_ts, BODY, &sig, opts_at(fixed_now())).unwrap_err();
250        assert!(matches!(err, SignatureError::Mismatch));
251    }
252
253    #[test]
254    fn wrong_secret_is_rejected() {
255        let sig = sign_payload(SECRET, TS, BODY);
256        let err = verify_signature(
257            "whsec_wrong_0000000000",
258            TS,
259            BODY,
260            &sig,
261            opts_at(fixed_now()),
262        )
263        .unwrap_err();
264        assert!(matches!(err, SignatureError::Mismatch));
265    }
266
267    #[test]
268    fn stale_timestamp_is_rejected_even_with_valid_signature() {
269        let sig = sign_payload(SECRET, TS, BODY);
270        // 6 minutes after the signed timestamp — past 5-min window.
271        let late = DateTime::parse_from_rfc3339("2026-03-23T12:06:01Z")
272            .unwrap()
273            .with_timezone(&Utc);
274        let err = verify_signature(SECRET, TS, BODY, &sig, opts_at(late)).unwrap_err();
275        assert!(matches!(err, SignatureError::TimestampSkewed { .. }));
276    }
277
278    #[test]
279    fn malformed_timestamp_fails_before_hmac() {
280        let sig = sign_payload(SECRET, TS, BODY);
281        let err =
282            verify_signature(SECRET, "not-a-date", BODY, &sig, opts_at(fixed_now())).unwrap_err();
283        assert!(matches!(err, SignatureError::InvalidTimestamp(_)));
284    }
285
286    #[test]
287    fn non_hex_signature_is_rejected() {
288        let err =
289            verify_signature(SECRET, TS, BODY, "not-hex-!!", opts_at(fixed_now())).unwrap_err();
290        assert!(matches!(err, SignatureError::InvalidSignatureHex));
291    }
292
293    #[test]
294    fn empty_secret_is_rejected() {
295        let sig = sign_payload(SECRET, TS, BODY);
296        let err = verify_signature("", TS, BODY, &sig, opts_at(fixed_now())).unwrap_err();
297        assert!(matches!(err, SignatureError::EmptySecret));
298    }
299
300    #[test]
301    fn constant_time_compare_rejects_truncated_signature() {
302        let sig = sign_payload(SECRET, TS, BODY);
303        let truncated = &sig[..sig.len() - 2];
304        let err = verify_signature(SECRET, TS, BODY, truncated, opts_at(fixed_now())).unwrap_err();
305        // Length mismatch surfaces as Mismatch (verify_slice rejects
306        // wrong-length tags even before constant-time compare).
307        assert!(matches!(err, SignatureError::Mismatch));
308    }
309
310    #[test]
311    fn future_timestamp_beyond_window_is_rejected() {
312        let sig = sign_payload(SECRET, TS, BODY);
313        // Signed "in the future" relative to now; absolute skew > 5 min.
314        let past_now = DateTime::parse_from_rfc3339("2026-03-23T11:50:00Z")
315            .unwrap()
316            .with_timezone(&Utc);
317        let err = verify_signature(SECRET, TS, BODY, &sig, opts_at(past_now)).unwrap_err();
318        assert!(matches!(err, SignatureError::TimestampSkewed { .. }));
319    }
320}