1use 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
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<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#[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: 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 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() -> 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 let sig = sign_payload(SECRET, TS, BODY);
227 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 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 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 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 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}