fix: HMAC format — match server POST\npath\ntimestamp\nsha256(body) scheme

- hmac_sign now takes method+path instead of device_id; builds message as
  method\npath\ntimestamp\nhex(sha256(body)) per server verify_device_hmac
- reporter: header renamed X-HMAC-Signature → X-Signature; passes "POST"+path
- test vector regenerated against new message format; timestamp-diff test updated
- .size() → .length() throughout (Arduino String has no size())

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-14 10:47:13 -07:00
parent 6d41529570
commit 135eb3b46c
4 changed files with 31 additions and 21 deletions

View File

@@ -8,28 +8,31 @@ void tearDown(void) {}
// Expected value derived via:
// import hmac, hashlib
// secret = bytes.fromhex("0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20")
// method = "POST"
// path = "/api/v1/camera/events/batch"
// timestamp = 1712000000
// body = '{"location_id":"retailer-123","records":[]}'
// body_hash = hashlib.sha256(body.encode()).hexdigest()
// msg = f"dc-0042:1712000000:{body_hash}"
// hmac.new(secret, msg.encode(), hashlib.sha256).hexdigest()
// message = f"{method}\n{path}\n{timestamp}\n{body_hash}"
// hmac.new(secret, message.encode(), hashlib.sha256).hexdigest()
void test_hmac_known_vector() {
HString secret = "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
HString device = "dc-0042";
HString method = "POST";
HString path = "/api/v1/camera/events/batch";
HString body = "{\"location_id\":\"retailer-123\",\"records\":[]}";
uint32_t ts = 1712000000;
HString result = hmac_sign(secret, device, ts, body);
HString result = hmac_sign(secret, method, path, ts, body);
TEST_ASSERT_EQUAL_STRING("90f5fa5fdbf7f95e7475791bf5bb90cdef7f16534d9a7d263fc588305bad0525", result.c_str());
TEST_ASSERT_EQUAL_STRING("44a0e129d7635a76190f63bfb65b08ad20bdd237b6382503cbe675165619ed6d", result.c_str());
}
void test_hmac_different_timestamp_gives_different_sig() {
HString secret = "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
HString device = "dc-0042";
HString body = "{}";
HString sig1 = hmac_sign(secret, device, 1712000000, body);
HString sig2 = hmac_sign(secret, device, 1712000001, body);
HString sig1 = hmac_sign(secret, "POST", "/api/v1/heartbeat", 1712000000, body);
HString sig2 = hmac_sign(secret, "POST", "/api/v1/heartbeat", 1712000001, body);
TEST_ASSERT_NOT_EQUAL(0, sig1.compare(sig2));
}