Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method for generating signed Smart CDN URLs #33

Merged
merged 10 commits into from
Nov 28, 2024
22 changes: 22 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import unittest
from unittest import mock

import requests_mock
from six.moves import urllib
Expand Down Expand Up @@ -94,3 +95,24 @@ def test_get_bill(self, mock):

response = self.transloadit.get_bill(month, year)
self.assertEqual(response.data["ok"], "BILL_FOUND")

def test_get_signed_smart_cdn_url(self):
client = Transloadit("foo_key", "foo_secret")

# Freeze time to 2024-05-01T00:00:00.000Z for consistent signatures
with mock.patch('time.time', return_value=1714521600):
url = client.get_signed_smart_cdn_url(
workspace="foo_workspace",
template="foo_template",
input="foo/input",
url_params={
"foo": "bar",
"aaa": [42, 21] # Should be sorted before `foo`
}
)

expected_url = (
"https://foo_workspace.tlcdn.com/foo_template/foo%2Finput?aaa=42&aaa=21&auth_key=foo_key&exp=1714525200000&foo=bar&sig=sha256%3A9a8df3bb28eea621b46ec808a250b7903b2546be7e66c048956d4f30b8da7519"
)

self.assertEqual(url, expected_url)
61 changes: 61 additions & 0 deletions transloadit/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import typing
import hmac
import hashlib
import time
from urllib.parse import urlencode, quote_plus

from typing import Optional

Expand Down Expand Up @@ -168,3 +172,60 @@ def get_bill(self, month: int, year: int):
Return an instance of <transloadit.response.Response>
"""
return self.request.get(f"/bill/{year}-{month:02d}")

def get_signed_smart_cdn_url(
self,
workspace: str,
template: str,
input: str,
url_params: Optional[dict] = None,
Acconut marked this conversation as resolved.
Show resolved Hide resolved
expires_in: Optional[int] = 60 * 60 * 1000 # 1 hour
) -> str:
"""
Construct a signed Smart CDN URL.
See https://transloadit.com/docs/topics/signature-authentication/#smart-cdn

:Args:
- workspace (str): Workspace slug
- template (str): Template slug or template ID
- input (str): Input value that is provided as ${fields.input} in the template
- url_params (Optional[dict]): Additional parameters for the URL query string. Values can be strings, numbers, booleans or arrays thereof.
- expires_in (Optional[int]): Expiration time of signature in milliseconds. Defaults to 1 hour.

:Returns:
str: The signed Smart CDN URL

:Raises:
ValueError: If url_params contains values that are not strings, numbers, booleans or arrays
"""
workspace_slug = quote_plus(workspace)
template_slug = quote_plus(template)
input_field = quote_plus(input)

params = []
if url_params:
for k, v in url_params.items():
if isinstance(v, (str, int, float, bool)):
params.append((k, str(v)))
elif isinstance(v, (list, tuple)):
params.append((k, [str(vv) for vv in v]))
else:
raise ValueError(f"URL parameter values must be strings, numbers, booleans or arrays. Got {type(v)} for {k}")

params.append(("auth_key", self.auth_key))
params.append(("exp", str(int(time.time() * 1000) + expires_in)))

# Sort params alphabetically by key
sorted_params = sorted(params, key=lambda x: x[0])
query_string = urlencode(sorted_params, doseq=True)

string_to_sign = f"{workspace_slug}/{template_slug}/{input_field}?{query_string}"
algorithm = "sha256"

signature = algorithm + ":" + hmac.new(
self.auth_secret.encode("utf-8"),
string_to_sign.encode("utf-8"),
hashlib.sha256
).hexdigest()

return f"https://{workspace_slug}.tlcdn.com/{template_slug}/{input_field}?{query_string}&sig={quote_plus(signature)}"
Loading