render-lab-media-contract 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Render Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.5
2
+ Name: render-lab-media-contract
3
+ Version: 0.1.0
4
+ Summary: Registration-free bounded media handoff contracts
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.12
8
+ Requires-Dist: render-lab-tasks-core<0.2,>=0.1.1
9
+ Description-Content-Type: text/markdown
10
+
11
+ # render-lab-media-contract
12
+
13
+ JSON media sources, destinations, results, and validators shared by the media packs.
14
+ Registration-free: importing this package registers no tasks and reads no credentials.
15
+
16
+ ```python
17
+ from render_lab_media_contract import assert_media_source
18
+
19
+ assert_media_source({"kind": "url", "url": "https://example.com/audio.mp3"})
20
+ ```
21
+
22
+ Use HTTPS URLs or signed PUT destinations for large media. Inline data URIs and
23
+ base64 results have a decoded 1 MiB limit; data URIs declare their content type
24
+ and byte count. The default bounded transfer limit is 100 MiB. Source headers
25
+ and signed destination URLs are credentials; do not log them.
26
+
27
+ Python rejects malformed base64 rather than silently discarding invalid bytes.
28
+ Validators have hermetic tests; this supporting package makes no network calls.
29
+
30
+ ## Installation
31
+
32
+ ```sh
33
+ pip install render-lab-media-contract==0.1.0
34
+ ```
@@ -0,0 +1,24 @@
1
+ # render-lab-media-contract
2
+
3
+ JSON media sources, destinations, results, and validators shared by the media packs.
4
+ Registration-free: importing this package registers no tasks and reads no credentials.
5
+
6
+ ```python
7
+ from render_lab_media_contract import assert_media_source
8
+
9
+ assert_media_source({"kind": "url", "url": "https://example.com/audio.mp3"})
10
+ ```
11
+
12
+ Use HTTPS URLs or signed PUT destinations for large media. Inline data URIs and
13
+ base64 results have a decoded 1 MiB limit; data URIs declare their content type
14
+ and byte count. The default bounded transfer limit is 100 MiB. Source headers
15
+ and signed destination URLs are credentials; do not log them.
16
+
17
+ Python rejects malformed base64 rather than silently discarding invalid bytes.
18
+ Validators have hermetic tests; this supporting package makes no network calls.
19
+
20
+ ## Installation
21
+
22
+ ```sh
23
+ pip install render-lab-media-contract==0.1.0
24
+ ```
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "render-lab-media-contract"
7
+ version = "0.1.0"
8
+ description = "Registration-free bounded media handoff contracts"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.12"
13
+ dependencies = ["render-lab-tasks-core>=0.1.1,<0.2"]
14
+
15
+ [tool.uv.sources]
16
+ render-lab-tasks-core = { workspace = true }
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["src/render_lab_media_contract"]
@@ -0,0 +1,138 @@
1
+ """Registration-free, JSON-safe media handoff contracts."""
2
+
3
+ import base64
4
+ import binascii
5
+ import math
6
+ from typing import Literal, NotRequired, TypedDict
7
+ from urllib.parse import urlsplit
8
+
9
+ from render_lab_tasks_core.bounded import (
10
+ MAX_INLINE_MEDIA_BYTES as MAX_INLINE_MEDIA_BYTES,
11
+ )
12
+ from render_lab_tasks_core.bounded import (
13
+ assert_byte_limit,
14
+ validate_byte_limit,
15
+ )
16
+
17
+ DEFAULT_TRANSFER_MAX_BYTES = 104_857_600
18
+
19
+
20
+ class UrlMediaSource(TypedDict):
21
+ kind: Literal["url"]
22
+ url: str
23
+ headers: NotRequired[dict[str, str]]
24
+
25
+
26
+ class DataUriMediaSource(TypedDict):
27
+ kind: Literal["dataUri"]
28
+ dataUri: str
29
+ contentType: str
30
+ byteCount: float
31
+
32
+
33
+ MediaSource = UrlMediaSource | DataUriMediaSource
34
+
35
+
36
+ class MediaDestination(TypedDict):
37
+ kind: Literal["signedPut"]
38
+ reference: str
39
+ url: str
40
+ headers: NotRequired[dict[str, str]]
41
+ maxBytes: float
42
+ expiresAt: NotRequired[str]
43
+
44
+
45
+ class MediaMetadata(TypedDict):
46
+ contentType: str
47
+ byteCount: float | None
48
+ truncated: bool
49
+
50
+
51
+ class UrlMediaResult(TypedDict):
52
+ kind: Literal["url"]
53
+ url: str
54
+ expiresAt: NotRequired[str]
55
+ metadata: MediaMetadata
56
+
57
+
58
+ class Base64MediaResult(TypedDict):
59
+ kind: Literal["base64"]
60
+ base64: str
61
+ metadata: MediaMetadata
62
+
63
+
64
+ class UploadedMediaResult(TypedDict):
65
+ kind: Literal["uploaded"]
66
+ reference: str
67
+ metadata: MediaMetadata
68
+
69
+
70
+ MediaResult = UrlMediaResult | Base64MediaResult | UploadedMediaResult
71
+
72
+
73
+ def assert_inline_byte_count(byte_count: float) -> None:
74
+ if byte_count > MAX_INLINE_MEDIA_BYTES:
75
+ raise ValueError(
76
+ f"Inline media is {byte_count} bytes, above the {MAX_INLINE_MEDIA_BYTES}-byte "
77
+ "inline limit. Return a URL result or provide a signed PUT destination for large media."
78
+ )
79
+ validate_byte_limit(byte_count, MAX_INLINE_MEDIA_BYTES)
80
+
81
+
82
+ def assert_media_source(source: MediaSource) -> None:
83
+ if source["kind"] == "url":
84
+ try:
85
+ parsed = urlsplit(source["url"])
86
+ if not parsed.scheme or (parsed.scheme == "https" and not parsed.hostname):
87
+ raise ValueError("missing scheme or host")
88
+ _ = parsed.port
89
+ except ValueError:
90
+ # Source URLs can also contain signed credentials.
91
+ raise ValueError("Media source url is not a valid URL.") from None
92
+ if parsed.scheme != "https":
93
+ raise ValueError(
94
+ f"Media source url must use HTTPS, received {parsed.scheme}:. "
95
+ "Use an HTTPS URL or a bounded data URI."
96
+ )
97
+ elif source["kind"] == "dataUri":
98
+ prefix = f"data:{source['contentType']};base64,"
99
+ if not source["dataUri"].startswith(prefix):
100
+ raise ValueError(f'Data URI media must start with "{prefix}".')
101
+ payload = source["dataUri"][len(prefix) :]
102
+ # Reject oversized input before allocating its decoded representation.
103
+ if len(payload) > 4 * ((MAX_INLINE_MEDIA_BYTES + 2) // 3):
104
+ raise ValueError("Inline media exceeds the 1048576-byte limit; use a URL source.")
105
+ try:
106
+ decoded = base64.b64decode(payload, validate=True)
107
+ except (ValueError, binascii.Error):
108
+ raise ValueError("Data URI media must contain valid base64.") from None
109
+ assert_byte_limit("Inline media", decoded, MAX_INLINE_MEDIA_BYTES)
110
+ if len(decoded) != source["byteCount"]:
111
+ raise ValueError(
112
+ f"Data URI media byteCount {source['byteCount']} does not match "
113
+ f"the decoded length {len(decoded)}."
114
+ )
115
+ assert_inline_byte_count(source["byteCount"])
116
+ else:
117
+ raise ValueError("Unhandled media source kind.")
118
+
119
+
120
+ def assert_media_destination(destination: MediaDestination) -> None:
121
+ if destination["kind"] != "signedPut":
122
+ raise ValueError("Unhandled media destination kind.")
123
+ if not destination["reference"].strip():
124
+ raise ValueError("Media destination reference must be a nonempty, nonsecret identifier.")
125
+ limit = destination["maxBytes"]
126
+ if isinstance(limit, bool) or not math.isfinite(limit) or limit <= 0 or int(limit) != limit:
127
+ raise ValueError(
128
+ f"Media destination maxBytes must be a positive integer, received {limit}."
129
+ )
130
+ try:
131
+ parsed = urlsplit(destination["url"])
132
+ if not parsed.scheme or (parsed.scheme == "https" and not parsed.hostname):
133
+ raise ValueError("missing scheme or host")
134
+ _ = parsed.port
135
+ except ValueError:
136
+ raise ValueError("Media destination url is not a valid URL.") from None
137
+ if parsed.scheme != "https":
138
+ raise ValueError("Media destination url must use HTTPS.")
@@ -0,0 +1,86 @@
1
+ import base64
2
+ import json
3
+ import subprocess
4
+ import sys
5
+
6
+ import pytest
7
+ from render_lab_media_contract import (
8
+ MAX_INLINE_MEDIA_BYTES,
9
+ assert_inline_byte_count,
10
+ assert_media_destination,
11
+ assert_media_source,
12
+ )
13
+
14
+
15
+ def source(data):
16
+ return {
17
+ "kind": "dataUri",
18
+ "contentType": "audio/wav",
19
+ "dataUri": "data:audio/wav;base64," + base64.b64encode(data).decode(),
20
+ "byteCount": len(data),
21
+ }
22
+
23
+
24
+ @pytest.mark.parametrize("data", [b"a", b"\0\xff", b"x" * MAX_INLINE_MEDIA_BYTES])
25
+ def test_valid_data_uri(data):
26
+ assert_media_source(source(data))
27
+
28
+
29
+ @pytest.mark.parametrize(
30
+ "count", [0, -1, 0.5, True, float("nan"), float("inf"), MAX_INLINE_MEDIA_BYTES + 1]
31
+ )
32
+ def test_inline_count_rejected(count):
33
+ with pytest.raises(ValueError):
34
+ assert_inline_byte_count(count)
35
+
36
+
37
+ def test_dishonest_count_and_oversized_data():
38
+ small = source(b"abc")
39
+ small["byteCount"] = 1
40
+ with pytest.raises(ValueError, match="decoded length 3"):
41
+ assert_media_source(small)
42
+ large = source(b"x" * (MAX_INLINE_MEDIA_BYTES + 10))
43
+ large["byteCount"] = 1
44
+ with pytest.raises(ValueError, match="limit"):
45
+ assert_media_source(large)
46
+
47
+
48
+ @pytest.mark.parametrize("payload", ["!!!", "YQ", "YQ===", "Y Q=="])
49
+ def test_malformed_base64(payload):
50
+ item = source(b"a")
51
+ item["dataUri"] = "data:audio/wav;base64," + payload
52
+ with pytest.raises(ValueError, match="base64"):
53
+ assert_media_source(item)
54
+
55
+
56
+ def test_https_sources_and_destination_secrecy():
57
+ assert_media_source({"kind": "url", "url": "https://example.com/a"})
58
+ for url in ["http://example.com/a", "https://", "https://[bad?secret=abc", "file:///secret"]:
59
+ with pytest.raises(ValueError) as error:
60
+ assert_media_destination(
61
+ {"kind": "signedPut", "reference": "asset", "url": url, "maxBytes": 5}
62
+ )
63
+ assert url not in str(error.value)
64
+ assert_media_destination(
65
+ {
66
+ "kind": "signedPut",
67
+ "reference": "asset",
68
+ "url": "https://example.com/?token=secret",
69
+ "maxBytes": 104857600,
70
+ }
71
+ )
72
+
73
+
74
+ def test_import_does_not_load_render_or_read_secrets():
75
+ result = subprocess.run(
76
+ [
77
+ sys.executable,
78
+ "-c",
79
+ "import render_lab_media_contract, sys, json; "
80
+ "print(json.dumps('render' in sys.modules))",
81
+ ],
82
+ capture_output=True,
83
+ text=True,
84
+ check=True,
85
+ )
86
+ assert json.loads(result.stdout) is False