🎥 Make videos programmatically with React
feat(lambda-python): add validate_webhook_signature()
DeryFerd6dd7693ba62f
diff --git a/packages/docs/docs/lambda/python.mdx b/packages/docs/docs/lambda/python.mdxindex e4e856d201..74b5796a14 100644--- a/packages/docs/docs/lambda/python.mdx+++ b/packages/docs/docs/lambda/python.mdx@@ -220,6 +220,34 @@ render_params = RenderMediaParams(response = client.render_media_on_lambda(render_params)```+## Verifying webhooks<AvailableFrom v="4.0.536" />++If you [set up a webhook](/docs/lambda/webhooks) with a secret, Remotion signs every request so you can confirm it was sent by Remotion and that the body was not modified. The Python client ships `validate_webhook_signature()`, the equivalent of [`validateWebhookSignature()`](/docs/lambda/validatewebhooksignature) in the JavaScript client.++Pass the webhook secret, the raw request body exactly as it was received, and the `X-Remotion-Signature` header. It raises an exception if the request cannot be verified and returns `None` if it is authentic.++```python title="webhook.py"+import os+from flask import Flask, request+from remotion_lambda import validate_webhook_signature++app = Flask(__name__)+[email protected]("/webhook", methods=["POST"])+def webhook():+ validate_webhook_signature(+ secret=os.environ["REMOTION_WEBHOOK_SECRET"],+ body=request.get_data(),+ signature_header=request.headers.get("X-Remotion-Signature"),+ )++ # The request is authentic. Parse the body only now.+ payload = request.get_json()+ return "", 200+```++Read the body first and verify before decoding it. The signature covers the exact bytes that were sent, so parsing the JSON and re-serializing it can reorder keys and change whitespace, which would make a genuine request fail the check. Pass the body as it arrived (`request.get_data()` in Flask, `request.body` in Django) rather than a parsed dictionary.+## Rendering an imageBelow is a snippet showing how to initiate a still image render. Note that it does not require monitoring the render progress.diff --git a/packages/lambda-python/remotion_lambda/__init__.py b/packages/lambda-python/remotion_lambda/__init__.pyindex dfdc3d21f7..51012356a0 100644--- a/packages/lambda-python/remotion_lambda/__init__.py+++ b/packages/lambda-python/remotion_lambda/__init__.py@@ -25,3 +25,4 @@ from .models import (from .remotionclient import RemotionClientfrom .asyncremotionclient import AsyncRemotionClientfrom .version import VERSION+from .webhook import validate_webhook_signaturediff --git a/packages/lambda-python/remotion_lambda/webhook.py b/packages/lambda-python/remotion_lambda/webhook.pynew file mode 100644index 0000000000..9a6cd94202--- /dev/null+++ b/packages/lambda-python/remotion_lambda/webhook.py@@ -0,0 +1,62 @@+# pylint: disable=missing-module-docstring+import hashlib+import hmac+from typing import Union++from .exception import RemotionException, RemotionInvalidArgumentException+++def validate_webhook_signature(+ secret: str,+ body: Union[str, bytes],+ signature_header: str,+) -> None:+ """+ Validate that an incoming webhook request was sent by Remotion and that its+ body was not modified in transit.++ Pass the webhook secret that was configured when the render was started, the+ raw request body exactly as it was received, and the value of the+ ``X-Remotion-Signature`` header. The function raises an exception if the+ request cannot be verified and returns ``None`` if it is authentic.++ The signature covers the raw JSON bytes, so pass the body as it arrived+ (``request.get_data()`` in Flask, ``request.body`` in Django) and decode it+ only after this function returns. Decoding and re-encoding first can change+ key order and whitespace, which would break the comparison even for a+ genuine request.++ This mirrors ``validateWebhookSignature()`` from ``@remotion/lambda/client``+ and uses the same scheme: ``"sha512="`` followed by the hex digest of an+ HMAC-SHA512 over the request body, keyed with the webhook secret.+ """+ if not secret:+ raise RemotionInvalidArgumentException(+ "No 'secret' was provided to validate_webhook_signature()."+ )++ if body is None or body == '' or body == b'':+ raise RemotionInvalidArgumentException(+ "No 'body' was provided to validate_webhook_signature()."+ )++ if not signature_header or signature_header == 'NO_SECRET_PROVIDED':+ raise RemotionException('No webhook signature was provided')++ body_bytes = body.encode('utf-8') if isinstance(body, str) else body++ expected = (+ 'sha512='+ + hmac.new(+ secret.encode('utf-8'), body_bytes, hashlib.sha512+ ).hexdigest()+ )++ # Compare as bytes: `compare_digest()` rejects two `str` values when either+ # side contains non-ASCII characters, and the signature header is+ # attacker-controlled, so a non-ASCII value must fail the check with a+ # `RemotionException` instead of raising an uncaught `TypeError`.+ if not hmac.compare_digest(+ expected.encode('utf-8'), signature_header.encode('utf-8')+ ):+ raise RemotionException('Signatures do not match')