some
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Importer boundary tests."""
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Wire fixture and independent conversion assets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import io
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Final, override
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
from pydantic import JsonValue
|
||||
|
||||
TOKEN: Final = "123456:FixtureCredential_Only_0123456789"
|
||||
ROOT: Final = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Reply:
|
||||
"""Immutable wire response for one fixture route."""
|
||||
|
||||
body: bytes
|
||||
status: int = 200
|
||||
location: str = ""
|
||||
|
||||
|
||||
def encoded(value: JsonValue) -> bytes:
|
||||
"""Serialize independent fixture JSON into a wire response."""
|
||||
return json.dumps(value).encode()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def api_server(
|
||||
routes: dict[str, Reply], received: list[str] | None = None
|
||||
) -> Iterator[str]:
|
||||
"""Serve fixture routes on loopback without logging request credentials."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None:
|
||||
if received is not None:
|
||||
received.append(self.path)
|
||||
parsed = urlsplit(self.path)
|
||||
key = parsed.path.rsplit("/", 1)[-1]
|
||||
if key == "getFile":
|
||||
key = parse_qs(parsed.query)["file_id"][0]
|
||||
reply = routes.get(key, Reply(b"", 404))
|
||||
self.send_response(reply.status)
|
||||
if reply.location:
|
||||
self.send_header("Location", reply.location)
|
||||
self.send_header("Content-Length", str(len(reply.body)))
|
||||
self.end_headers()
|
||||
try:
|
||||
_ = self.wfile.write(reply.body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
return # Expected when bounded client rejects oversized fixture.
|
||||
|
||||
@override
|
||||
def log_message(self, format: str, *args: str | int) -> None:
|
||||
return # Never log credential-bearing fixture paths.
|
||||
|
||||
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield f"http://127.0.0.1:{server.server_port}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def routes_for(assets: dict[str, bytes]) -> dict[str, Reply]:
|
||||
"""Describe source files using Bot API envelopes and download routes."""
|
||||
stickers: list[JsonValue] = []
|
||||
routes: dict[str, Reply] = {}
|
||||
for index, (filename, data) in enumerate(assets.items()):
|
||||
file_id = f"file{index}"
|
||||
stickers.append(
|
||||
{
|
||||
"file_id": file_id,
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"is_animated": filename.endswith(".tgs"),
|
||||
"is_video": filename.endswith(".webm"),
|
||||
"emoji": "😀",
|
||||
"file_size": len(data),
|
||||
}
|
||||
)
|
||||
routes[file_id] = Reply(
|
||||
encoded(
|
||||
{
|
||||
"ok": True,
|
||||
"result": {
|
||||
"file_path": "stickers/" + filename,
|
||||
"file_size": len(data),
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
routes[filename] = Reply(data)
|
||||
routes["getStickerSet"] = Reply(
|
||||
encoded(
|
||||
{
|
||||
"ok": True,
|
||||
"result": {
|
||||
"name": "FixturePack",
|
||||
"title": "Fixture pack",
|
||||
"stickers": stickers,
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
return routes
|
||||
|
||||
|
||||
def vector_data() -> JsonValue:
|
||||
"""Describe a moving solid layer independently of the converter."""
|
||||
return {
|
||||
"v": "5.5.2",
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 30,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"layers": [
|
||||
{
|
||||
"ty": 1,
|
||||
"ind": 1,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"st": 0,
|
||||
"sw": 128,
|
||||
"sh": 128,
|
||||
"sc": "#00ff00",
|
||||
"ks": {
|
||||
"o": {"a": 0, "k": 100},
|
||||
"r": {"a": 0, "k": 0},
|
||||
"p": {
|
||||
"a": 1,
|
||||
"k": [
|
||||
{
|
||||
"t": 0,
|
||||
"s": [64, 192],
|
||||
"e": [320, 192],
|
||||
"i": {"x": 1, "y": 1},
|
||||
"o": {"x": 0, "y": 0},
|
||||
},
|
||||
{"t": 30, "s": [320, 192]},
|
||||
],
|
||||
},
|
||||
"a": {"a": 0, "k": [0, 0]},
|
||||
"s": {"a": 0, "k": [100, 100]},
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def make_conversion_assets() -> dict[str, bytes]:
|
||||
"""Generate source media shared by CLI tests and the isolated game API fixture."""
|
||||
image = Image.new("RGBA", (256, 128))
|
||||
ImageDraw.Draw(image).rectangle((64, 32, 191, 95), fill=(255, 0, 0, 255))
|
||||
with io.BytesIO() as buffer:
|
||||
image.save(buffer, format="WEBP", lossless=True)
|
||||
webp = buffer.getvalue()
|
||||
frames: list[bytes] = []
|
||||
for index in range(80):
|
||||
image = Image.new("RGBA", (128, 128))
|
||||
ImageDraw.Draw(image).rectangle(
|
||||
(index % 64, 32, index % 64 + 31, 63), fill=(0, 0, 255, 255)
|
||||
)
|
||||
frames.append(image.tobytes())
|
||||
ffmpeg = shutil.which("ffmpeg")
|
||||
if ffmpeg is None:
|
||||
pytest.fail("ffmpeg is required to generate independent video fixtures")
|
||||
video = subprocess.run(
|
||||
[
|
||||
ffmpeg,
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
"-threads",
|
||||
"1",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-pixel_format",
|
||||
"rgba",
|
||||
"-video_size",
|
||||
"128x128",
|
||||
"-framerate",
|
||||
"20",
|
||||
"-i",
|
||||
"pipe:0",
|
||||
"-c:v",
|
||||
"libvpx-vp9",
|
||||
"-threads",
|
||||
"1",
|
||||
"-pix_fmt",
|
||||
"yuva420p",
|
||||
"-auto-alt-ref",
|
||||
"0",
|
||||
"-f",
|
||||
"webm",
|
||||
"pipe:1",
|
||||
],
|
||||
input=b"".join(frames),
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
).stdout
|
||||
return {
|
||||
"static.webp": webp,
|
||||
"vector.tgs": gzip.compress(encoded(vector_data())),
|
||||
"video.webm": video,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def conversion_assets() -> dict[str, bytes]:
|
||||
"""Provide the same independent source media to parametrized import checks."""
|
||||
return make_conversion_assets()
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Hostile wire responses and invalid committed catalogs for CLI scenarios."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, assert_never
|
||||
|
||||
from tests.conftest import TOKEN, Reply, encoded
|
||||
|
||||
WireFailure = Literal[
|
||||
"traversal",
|
||||
"absolute",
|
||||
"encoded_path",
|
||||
"redirect_api",
|
||||
"redirect_file",
|
||||
"oversize_download",
|
||||
"bad_json",
|
||||
"api_error",
|
||||
]
|
||||
CatalogFailure = Literal[
|
||||
"duplicate_packs", "bad_catalog", "catalog_bytes", "pack_limit", "overall_limit"
|
||||
]
|
||||
Failure = (
|
||||
WireFailure
|
||||
| CatalogFailure
|
||||
| Literal[
|
||||
"dimensions",
|
||||
"expansion",
|
||||
"external_tgs",
|
||||
"credential_metadata",
|
||||
"late_conversion",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def reject_wire(routes: dict[str, Reply], failure: WireFailure) -> None:
|
||||
"""Replace a fixture route with the requested hostile Bot API response."""
|
||||
match failure:
|
||||
case "traversal" | "absolute" | "encoded_path":
|
||||
path = {
|
||||
"traversal": "stickers/../secret.webp",
|
||||
"absolute": "https://evil.test/file.webp",
|
||||
"encoded_path": "stickers/%2e%2e/file.webp",
|
||||
}[failure]
|
||||
routes["file0"] = Reply(
|
||||
encoded({"ok": True, "result": {"file_path": path}})
|
||||
)
|
||||
case "redirect_api" | "redirect_file":
|
||||
key = "getStickerSet" if failure == "redirect_api" else "static.webp"
|
||||
routes[key] = Reply(b"", 302, "https://evil.test/" + TOKEN)
|
||||
case "oversize_download":
|
||||
routes["static.webp"] = Reply(b"x" * 4_194_305)
|
||||
case "bad_json":
|
||||
routes["getStickerSet"] = Reply(b"{broken " + TOKEN.encode())
|
||||
case "api_error":
|
||||
routes["getStickerSet"] = Reply(
|
||||
encoded({"ok": False, "description": TOKEN})
|
||||
)
|
||||
case _:
|
||||
assert_never(failure)
|
||||
|
||||
|
||||
def invalid_catalog(failure: CatalogFailure) -> bytes:
|
||||
"""Encode one independently constructed invalid on-disk catalog."""
|
||||
match failure:
|
||||
case "duplicate_packs":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{"id": "Old", "title": "One", "stickers": []},
|
||||
{"id": "Old", "title": "Two", "stickers": []},
|
||||
],
|
||||
}
|
||||
)
|
||||
case "bad_catalog":
|
||||
return b"{invalid"
|
||||
case "catalog_bytes":
|
||||
return b" " * 524_289
|
||||
case "pack_limit":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{"id": f"Old{i}", "title": "Old", "stickers": []}
|
||||
for i in range(64)
|
||||
],
|
||||
}
|
||||
)
|
||||
case "overall_limit":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": f"Old{i}",
|
||||
"title": "Old",
|
||||
"stickers": [
|
||||
{"id": f"{j:064x}", "emoji": "", "frames": 1}
|
||||
for j in range(128)
|
||||
],
|
||||
}
|
||||
for i in range(16)
|
||||
],
|
||||
}
|
||||
)
|
||||
case _:
|
||||
assert_never(failure)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Disk ownership and interrupted-job recovery through the real CLI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import selectors
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, Literal, assert_never
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from tests.conftest import ROOT, TOKEN, api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def png(color: str) -> bytes:
|
||||
"""Encode a deterministic opaque asset for cache ownership scenarios."""
|
||||
with io.BytesIO() as buffer:
|
||||
Image.new("RGBA", (128, 128), color).save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_recovery_and_replacement_reclaim_only_owned_unreferenced_assets(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
) -> None:
|
||||
"""Retain shared and unrelated files while reclaiming stale owned assets."""
|
||||
cache = tmp_path / "cache"
|
||||
assets = cache / "assets"
|
||||
assets.mkdir(parents=True)
|
||||
ids: list[str] = []
|
||||
for color in ("red", "green", "blue", "yellow"):
|
||||
data = png(color)
|
||||
asset_id = hashlib.sha256(data).hexdigest()
|
||||
_ = (assets / (asset_id + ".png")).write_bytes(data)
|
||||
ids.append(asset_id)
|
||||
_ = (assets / "unrelated.txt").write_text("keep")
|
||||
_ = (cache / "catalog.json").write_bytes(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": "FixturePack",
|
||||
"title": "Old",
|
||||
"stickers": [
|
||||
{"id": ids[0], "emoji": "", "frames": 1},
|
||||
{"id": ids[1], "emoji": "", "frames": 1},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "KeepMe",
|
||||
"title": "Protected",
|
||||
"stickers": [
|
||||
{"id": ids[0], "emoji": "", "frames": 1},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
root = cache / ".wowmine-stickers-importer-v1"
|
||||
job = root / "job-12345678"
|
||||
job.mkdir(parents=True)
|
||||
_ = (root / "owner").write_bytes(b"wowmine-stickers-importer-v1\n")
|
||||
_ = (job / "journal.json").write_bytes(
|
||||
encoded({"version": 1, "assets": [ids[0], ids[2]]})
|
||||
)
|
||||
_ = (job / "input.webp").write_bytes(b"stale input")
|
||||
_ = (root / "unrelated.txt").write_text("keep too")
|
||||
with api_server(
|
||||
routes_for({"static.webp": conversion_assets["static.webp"]})
|
||||
) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert (assets / (ids[0] + ".png")).read_bytes() == png("red")
|
||||
assert not (assets / (ids[1] + ".png")).exists()
|
||||
assert not (assets / (ids[2] + ".png")).exists()
|
||||
assert (assets / (ids[3] + ".png")).read_bytes() == png("yellow")
|
||||
assert (assets / "unrelated.txt").read_text() == "keep"
|
||||
assert (root / "unrelated.txt").read_text() == "keep too"
|
||||
assert sorted(p.name for p in root.iterdir()) == ["owner", "unrelated.txt"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interrupt", [signal.SIGKILL, signal.SIGALRM])
|
||||
def test_interrupted_job_retains_catalog_and_next_import_recovers_staging(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
interrupt: Literal[signal.Signals.SIGKILL, signal.Signals.SIGALRM],
|
||||
) -> None:
|
||||
"""Recover killed or timed-out jobs without changing the committed catalog."""
|
||||
token = tmp_path / "token"
|
||||
_ = token.write_text(TOKEN)
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
original = b'{"version":1,"packs":[]}'
|
||||
_ = (cache / "catalog.json").write_bytes(original)
|
||||
command = (
|
||||
[os.environ["IMPORTER_BINARY"]]
|
||||
if "IMPORTER_BINARY" in os.environ
|
||||
else [
|
||||
sys.executable,
|
||||
str(ROOT / "import_pack.py"),
|
||||
]
|
||||
)
|
||||
with api_server(routes_for(conversion_assets)) as origin:
|
||||
with subprocess.Popen(
|
||||
[
|
||||
*command,
|
||||
"--token-file",
|
||||
str(token),
|
||||
"--pack",
|
||||
"FixturePack",
|
||||
"--output",
|
||||
str(cache),
|
||||
"--api-base",
|
||||
origin,
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
bufsize=0,
|
||||
) as child:
|
||||
assert child.stdout is not None
|
||||
with selectors.DefaultSelector() as selector:
|
||||
_ = selector.register(child.stdout, selectors.EVENT_READ)
|
||||
assert selector.select(timeout=10)
|
||||
assert child.stdout.readline() == b'{"status":"fetching"}\n'
|
||||
assert selector.select(timeout=10)
|
||||
assert b'"status": "converting"' in child.stdout.readline()
|
||||
child.send_signal(interrupt)
|
||||
stdout, stderr = child.communicate(timeout=10)
|
||||
match interrupt:
|
||||
case signal.SIGKILL:
|
||||
assert child.returncode == -signal.SIGKILL
|
||||
case signal.SIGALRM:
|
||||
assert child.returncode == 1
|
||||
assert stderr == b'{"status":"error","code":"job_timeout"}\n'
|
||||
case _:
|
||||
assert_never(interrupt)
|
||||
assert TOKEN.encode() not in stdout + stderr
|
||||
assert (cache / "catalog.json").read_bytes() == original
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert sorted(
|
||||
p.name for p in (cache / ".wowmine-stickers-importer-v1").iterdir()
|
||||
) == ["owner"]
|
||||
@@ -0,0 +1,76 @@
|
||||
"""PNG identity includes timing, even when visible atlas pixels are identical."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from models import Catalog, ImportFailureError
|
||||
from tests.conftest import api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_transparent_animations_with_different_timing_keep_distinct_ids(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Distinguish frame counts even when transparent atlas pixels match."""
|
||||
assets = {
|
||||
f"empty{count}.tgs": gzip.compress(
|
||||
encoded(
|
||||
{
|
||||
"v": "5.5.2",
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 20,
|
||||
"ip": 0,
|
||||
"op": count,
|
||||
"layers": [],
|
||||
}
|
||||
)
|
||||
)
|
||||
for count in (9, 10)
|
||||
}
|
||||
with api_server(routes_for(assets)) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
catalog = Catalog.model_validate_json(
|
||||
(tmp_path / "cache" / "catalog.json").read_bytes()
|
||||
)
|
||||
stickers = catalog.packs[0].stickers
|
||||
assert [s.frames for s in stickers] == [9, 10]
|
||||
assert stickers[0].id != stickers[1].id
|
||||
pixels: list[bytes] = []
|
||||
for sticker in stickers:
|
||||
with Image.open(tmp_path / "cache" / "assets" / (sticker.id + ".png")) as image:
|
||||
assert image.size == (1024, 256)
|
||||
assert image.info["wowmine_frames"] == str(sticker.frames)
|
||||
pixels.append(image.tobytes())
|
||||
assert pixels[0] == pixels[1]
|
||||
|
||||
|
||||
def test_catalog_rejects_conflicting_frames_for_shared_asset_id() -> None:
|
||||
"""Reject an asset ID associated with incompatible animation timing."""
|
||||
with pytest.raises(ImportFailureError, match="conflicting frame counts"):
|
||||
_ = Catalog.model_validate_json(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": f"Pack{count}",
|
||||
"title": "Title",
|
||||
"stickers": [
|
||||
{"id": "a" * 64, "emoji": "", "frames": count},
|
||||
],
|
||||
}
|
||||
for count in (9, 10)
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,242 @@
|
||||
"""CLI conversion, catalog compatibility and hostile input rejection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, assert_never
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from pydantic import JsonValue, TypeAdapter
|
||||
|
||||
from models import Catalog
|
||||
from tests.conftest import ROOT, TOKEN, Reply, api_server, encoded, routes_for
|
||||
from tests.rejected_inputs import invalid_catalog, reject_wire
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from tests.rejected_inputs import Failure
|
||||
|
||||
|
||||
def run_cli(
|
||||
directory: Path, origin: str, pack: str = "https://t.me/addstickers/FixturePack"
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
"""Run the installed or source CLI against an isolated fixture origin."""
|
||||
token = directory / "token"
|
||||
_ = token.write_text(TOKEN)
|
||||
command = (
|
||||
[os.environ["IMPORTER_BINARY"]]
|
||||
if "IMPORTER_BINARY" in os.environ
|
||||
else [
|
||||
sys.executable,
|
||||
str(ROOT / "import_pack.py"),
|
||||
]
|
||||
)
|
||||
return subprocess.run(
|
||||
[
|
||||
*command,
|
||||
"--token-file",
|
||||
str(token),
|
||||
"--pack",
|
||||
pack,
|
||||
"--output",
|
||||
str(directory / "cache"),
|
||||
"--api-base",
|
||||
origin,
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=90,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def test_import_converts_all_formats_preserves_packs_and_deduplicates(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
) -> None:
|
||||
"""Preserve the wire catalog, alpha, animation and deduplication contracts."""
|
||||
assets = {**conversion_assets, "duplicate.webp": conversion_assets["static.webp"]}
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
retained: JsonValue = {"id": "KeepMe", "title": "Other pack", "stickers": []}
|
||||
replaced: JsonValue = {"id": "FixturePack", "title": "Old title", "stickers": []}
|
||||
_ = (cache / "catalog.json").write_bytes(
|
||||
encoded({"version": 1, "packs": [retained, replaced]})
|
||||
)
|
||||
with api_server(routes_for(assets)) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
statuses = [
|
||||
TypeAdapter[JsonValue](JsonValue).validate_json(line)
|
||||
for line in result.stdout.splitlines()
|
||||
]
|
||||
assert statuses == [
|
||||
{"status": "fetching"},
|
||||
*[{"status": "converting", "completed": i, "total": 4} for i in range(4)],
|
||||
{"status": "complete", "pack": "FixturePack", "stickers": 3},
|
||||
]
|
||||
raw = (cache / "catalog.json").read_bytes()
|
||||
assert TOKEN.encode() not in raw
|
||||
catalog = TypeAdapter[JsonValue](JsonValue).validate_json(raw)
|
||||
assert isinstance(catalog, dict)
|
||||
packs = catalog["packs"]
|
||||
assert isinstance(packs, list)
|
||||
assert packs[0] == retained
|
||||
pack = packs[1]
|
||||
assert isinstance(pack, dict)
|
||||
assert set(catalog) == {"version", "packs"}
|
||||
assert set(pack) == {"id", "title", "stickers"}
|
||||
assert pack["title"] == "Fixture pack"
|
||||
parsed = Catalog.model_validate_json(raw).packs[1]
|
||||
assert [sticker.frames for sticker in parsed.stickers] == [1, 20, 60]
|
||||
entries = pack["stickers"]
|
||||
assert isinstance(entries, list)
|
||||
for entry, sticker in zip(entries, parsed.stickers, strict=True):
|
||||
assert isinstance(entry, dict)
|
||||
assert set(entry) == {"id", "emoji", "frames"}
|
||||
asset = cache / "assets" / (sticker.id + ".png")
|
||||
assert hashlib.sha256(asset.read_bytes()).hexdigest() == sticker.id
|
||||
with Image.open(asset) as image:
|
||||
count = sticker.frames
|
||||
assert image.size == (
|
||||
min(8, count) * 128,
|
||||
((count + min(8, count) - 1) // min(8, count)) * 128,
|
||||
)
|
||||
assert image.mode == "RGBA"
|
||||
pixel = image.getpixel((0, 0))
|
||||
assert isinstance(pixel, tuple)
|
||||
assert pixel[3] == 0
|
||||
assert image.getchannel("A").getextrema() == (0, 255)
|
||||
if count == 1:
|
||||
assert image.getpixel((40, 60)) == (255, 0, 0, 255)
|
||||
if count > 1:
|
||||
last = ((count - 1) % 8 * 128, (count - 1) // 8 * 128)
|
||||
assert (
|
||||
image.crop((0, 0, 128, 128)).tobytes()
|
||||
!= image.crop(
|
||||
(*last, last[0] + 128, last[1] + 128),
|
||||
).tobytes()
|
||||
)
|
||||
assert TOKEN not in result.stdout + result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
[
|
||||
"traversal",
|
||||
"absolute",
|
||||
"encoded_path",
|
||||
"redirect_api",
|
||||
"redirect_file",
|
||||
"oversize_download",
|
||||
"bad_json",
|
||||
"api_error",
|
||||
"dimensions",
|
||||
"expansion",
|
||||
"external_tgs",
|
||||
"duplicate_packs",
|
||||
"bad_catalog",
|
||||
"credential_metadata",
|
||||
"late_conversion",
|
||||
"catalog_bytes",
|
||||
"pack_limit",
|
||||
"overall_limit",
|
||||
],
|
||||
)
|
||||
def test_rejected_import_retains_catalog_and_hides_credentials(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
failure: Failure,
|
||||
) -> None:
|
||||
"""Retain committed state and redact credentials on every rejection path."""
|
||||
assets = {"static.webp": conversion_assets["static.webp"]}
|
||||
routes = routes_for(assets)
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
original = encoded(
|
||||
{"version": 1, "packs": [{"id": "Old", "title": "Retained", "stickers": []}]}
|
||||
)
|
||||
match failure:
|
||||
case (
|
||||
"traversal"
|
||||
| "absolute"
|
||||
| "encoded_path"
|
||||
| "redirect_api"
|
||||
| "redirect_file"
|
||||
| "oversize_download"
|
||||
| "bad_json"
|
||||
| "api_error"
|
||||
):
|
||||
reject_wire(routes, failure)
|
||||
case "dimensions":
|
||||
with io.BytesIO() as buffer:
|
||||
Image.new("RGBA", (513, 1)).save(buffer, format="WEBP")
|
||||
routes = routes_for({"huge.webp": buffer.getvalue()})
|
||||
case "expansion":
|
||||
routes = routes_for({"bomb.tgs": gzip.compress(b" " * 2_097_153)})
|
||||
case "external_tgs":
|
||||
routes = routes_for(
|
||||
{
|
||||
"linked.tgs": gzip.compress(
|
||||
encoded(
|
||||
{
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 30,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"assets": [
|
||||
{
|
||||
"id": "external",
|
||||
"p": "file:///etc/passwd",
|
||||
"u": "",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
case (
|
||||
"duplicate_packs"
|
||||
| "bad_catalog"
|
||||
| "catalog_bytes"
|
||||
| "pack_limit"
|
||||
| "overall_limit"
|
||||
):
|
||||
original = invalid_catalog(failure)
|
||||
case "credential_metadata":
|
||||
value = TypeAdapter[JsonValue](JsonValue).validate_json(
|
||||
routes["getStickerSet"].body
|
||||
)
|
||||
assert isinstance(value, dict)
|
||||
remote = value["result"]
|
||||
assert isinstance(remote, dict)
|
||||
remote["title"] = TOKEN
|
||||
routes["getStickerSet"] = Reply(json.dumps(value).encode())
|
||||
case "late_conversion":
|
||||
routes = routes_for({**assets, "broken.tgs": b"not gzip"})
|
||||
case _:
|
||||
assert_never(failure)
|
||||
_ = (cache / "catalog.json").write_bytes(original)
|
||||
with api_server(routes) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 1
|
||||
assert (cache / "catalog.json").read_bytes() == original
|
||||
assert TOKEN not in result.stdout + result.stderr
|
||||
assert "Traceback" not in result.stderr
|
||||
assert TypeAdapter[JsonValue](JsonValue).validate_json(result.stderr) == {
|
||||
"status": "error",
|
||||
"code": "import_failed",
|
||||
}
|
||||
stage_root = cache / ".wowmine-stickers-importer-v1"
|
||||
if stage_root.exists():
|
||||
assert sorted(p.name for p in stage_root.iterdir()) == ["owner"]
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Client catalog compatibility and player-controlled input rejection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from pydantic import JsonValue, ValidationError
|
||||
|
||||
from models import Catalog, ImportFailureError
|
||||
from tests.conftest import TOKEN, Reply, api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pack",
|
||||
[
|
||||
"https://evil.test/addstickers/FixturePack",
|
||||
"https://t.me@evil.test/addstickers/FixturePack",
|
||||
"https://user@t.me/addstickers/FixturePack",
|
||||
"//t.me/addstickers/FixturePack",
|
||||
"https://t.me/addstickers/FixturePack?host=evil.test",
|
||||
"FixturePack/../secret",
|
||||
"FixturePack\n",
|
||||
],
|
||||
)
|
||||
def test_player_pack_input_cannot_select_fetch_origin(
|
||||
tmp_path: Path, pack: str
|
||||
) -> None:
|
||||
"""Reject player-controlled origins before making any fixture request."""
|
||||
received: list[str] = []
|
||||
with api_server({}, received) as origin:
|
||||
result = run_cli(tmp_path, origin, pack)
|
||||
assert result.returncode == 1
|
||||
assert received == []
|
||||
assert not (tmp_path / "cache" / "catalog.json").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["getStickerSet", "static.webp"])
|
||||
def test_redirect_never_sends_token_to_destination(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
route: str,
|
||||
) -> None:
|
||||
"""Never forward credential-bearing API or file redirects."""
|
||||
received: list[str] = []
|
||||
with api_server({}, received) as destination:
|
||||
routes = routes_for({"static.webp": conversion_assets["static.webp"]})
|
||||
routes[route] = Reply(b"", 302, destination + "/" + TOKEN)
|
||||
with api_server(routes) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 1
|
||||
assert received == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("frames", 0),
|
||||
("frames", 61),
|
||||
("id", "A" * 64),
|
||||
("emoji", "😀" * 33),
|
||||
],
|
||||
)
|
||||
def test_catalog_rejects_values_client_cannot_use(field: str, value: str | int) -> None:
|
||||
"""Reject sticker values outside the client's catalog contract."""
|
||||
sticker: JsonValue = {"id": "a" * 64, "emoji": "", "frames": 1, field: value}
|
||||
with pytest.raises((ValueError, UnicodeError, ImportFailureError)):
|
||||
_ = Catalog.model_validate_json(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [{"id": "Pack", "title": "Title", "stickers": [sticker]}],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [True, 0, 2, "1"])
|
||||
def test_catalog_version_requires_integer_one(*, version: bool | int | str) -> None:
|
||||
"""Reject booleans, other versions and string coercion for catalog version."""
|
||||
with pytest.raises(ValidationError):
|
||||
_ = Catalog.model_validate_json(encoded({"version": version, "packs": []}))
|
||||
Reference in New Issue
Block a user