1use 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
39pub const DEFAULT_MAX_SKEW: Duration = Duration::from_mins(5);
41
42pub 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
58pub 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
66pub 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
74pub 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
83pub 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
91pub 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#[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#[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
140pub 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 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
183pub 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 let sig = sign_payload(SECRET, TS, BODY);
229 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 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 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 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 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}