some
This commit is contained in:
@@ -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"]
|
||||
Reference in New Issue
Block a user