#!/usr/bin/env python3 import binascii import hmac import secrets import sys import time from hashlib import sha512 CALLBACK_SECRET = secrets.token_urlsafe(32) CALLBACK_SECRET = "insecure_unsafe_qHScgrg_kP-R31jHUwp3GkVkGJolvBchz65b74Lzue0" request = { "body": '{"type":"https://schema.fitko.de/fit-connect/submission-api/callbacks/new-submissions","submissionIds":["f39ab143-d91a-474a-b69f-b00f1a1873c2"]}', "headers": { "callback-authentication": "798cd0edb70c08e5b32aa8a18cbbc8ff6b3078c51af6d011ff4e32e470c746234fc4314821fe5185264b029e962bd37de33f3b9fc5f1a93c40ce6672845e90df", "callback-timestamp": 1672527599, }, } # 1. Check timestamp current_time_epoch = int(time.time()) seconds_five_minutes = 60 * 5 if current_time_epoch - request["headers"]["callback-timestamp"] > seconds_five_minutes: print("Error: timestamp too old") sys.exit(1) else: print("timestamp ok") # 2. generate hmac payload = str(request["headers"]["callback-timestamp"]) + "." + request["body"] expected_hmac = hmac.digest( CALLBACK_SECRET.encode("utf-8"), payload.encode("utf-8"), digest=sha512 ) expected_hmac_hex = binascii.hexlify(expected_hmac).decode("utf-8") print("hmac", expected_hmac_hex) # 3. Compare generated hmac and `callback-authentication` header if not hmac.compare_digest( request["headers"]["callback-authentication"], expected_hmac_hex ): print("Error: invalid hmac") sys.exit(2) else: print("hmac ok")