smartcar/
webhooks.rs

1//! Helpers for integrating webhooks with your application
2
3use hex;
4use hmac::{Hmac, Mac};
5use sha2::Sha256;
6
7type HmacSha256 = Hmac<Sha256>;
8
9use crate::error::Error;
10
11/// Generate hash challenege for webhooks.
12pub fn hash_challenge(amt: &str, challenge: &str) -> Result<String, Error> {
13    let mut mac = HmacSha256::new_from_slice(challenge.as_bytes())?;
14    mac.update(amt.as_bytes());
15    let mac_bytes = mac.finalize().into_bytes();
16
17    Ok(hex::encode(mac_bytes))
18}
19
20/// Verify webhook payload with AMT and signature.
21pub fn verify_payload(amt: &str, signature: &str, body: &str) -> Result<bool, Error> {
22    Ok(hash_challenge(amt, body)? == *signature)
23}
24
25#[test]
26fn test_hash_challenge() {
27    let amt = "abc123abc123";
28    let body = "9c9c9c9c";
29    let hex_encoding = hash_challenge(amt, body).unwrap();
30    let verified_payload = verify_payload(amt, &hex_encoding, body).unwrap();
31
32    assert!(verified_payload);
33}