import hmac import hashlib import os from fastapi import Header, HTTPException from typing import Optional def verify_signature(body: bytes, signature: str, secret: str) -> bool: """ Verify HMAC-SHA256 signature. Args: body: Raw request body bytes signature: Signature from X-Signature header secret: Shared secret key Returns: True if signature is valid, False otherwise """ expected_signature = hmac.new( secret.encode('utf-8'), body, hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected_signature) async def verify_external_signature( x_signature: Optional[str] = Header(None, alias="X-Signature") ): """ FastAPI dependency to verify external API signature. Raises: HTTPException: If signature is missing or invalid """ if not x_signature: raise HTTPException( status_code=401, detail="Missing X-Signature header" ) # Note: We'll need to access the raw request body in the endpoint # This dependency just validates the header exists # Actual signature verification happens in the endpoint return x_signature