Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 # Should be sorted as first param
}
)

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

self.assertEqual(url, expected_url)
53 changes: 53 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,52 @@ 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,
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
- expires_in (Optional[int]): Expiration time of signature in milliseconds. Defaults to 1 hour.

:Returns:
str: The signed Smart CDN URL
"""
workspace_slug = quote_plus(workspace)
template_slug = quote_plus(template)
input_field = quote_plus(input)

# Convert url_params values to strings
params = {}
if url_params:
params.update({k: str(v) for k, v in url_params.items()})

params["auth_key"] = self.auth_key
params["exp"] = str(int(time.time() * 1000) + expires_in)

# Sort params alphabetically
sorted_params = dict(sorted(params.items()))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sort algos can work differently across languages, is that a problem?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I could research, this behaves the same way our server-side implementations do.

query_string = urlencode(sorted_params)

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

signature = 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={algorithm}:{signature}"
Loading