Files
LangBot/plugins/misc/StickerHub/tests/test_upload_chunks.py
TyperBodyandmultica-agent a91210c43b fix(plugins/misc/StickerHub): copy the URL the page actually holds, inside the real sandbox
Copy was broken twice over. `langbot.api()` already resolves the unwrapped
payload (PageResponse.ok -> HTTP data -> resp.data.data -> the SDK's
resolve(data.data)), so `item.data.url` was always `undefined` and the page
copied an empty string. `writeText('')` resolves without throwing, so it also
never reached the fallback: the UI said "copied" while the clipboard stayed
empty.

The iframe is worse than assumed. It is a `blob:` document under
`sandbox="allow-scripts allow-forms"`, so its origin is opaque: `location.origin`
is "null", relative asset URLs do not load, and `navigator.clipboard` rejects
with NotAllowedError. `/list` returns relative URLs while `public_base_url` is
empty, so even a correct value would have pasted as an unusable path. URLs are
now made absolute against `location.ancestorOrigins[0]` before either the
clipboard or an `<img src>`, and copy reads `item.url` from the list cache
instead of making a redundant `/item` round trip.

Every other call had the same layer mistake: `res.error` is never set on a
resolved value, because failures reject the promise, so no failure ever
surfaced. All call sites now catch, and an empty URL toasts an error rather
than claiming success.

Verified in a real blob: iframe with the real sandbox: relative url -> absolute
-> clipboard read back byte for byte, and the same URL loads as the preview
(0 `/image` calls). Also passes with `navigator.clipboard` removed, proving the
execCommand tier is what carries it.

The host is untouched now, so this is plugin-only; the `allow-modals` flip is
dropped and the clear confirmation stays in-page.

Co-authored-by: multica-agent <github@multica.ai>
2026-11-07 15:09:17 +08:00

121 lines
4.3 KiB
Python

"""Chunked upload keeps the HTTP body constant regardless of image size."""
from __future__ import annotations
import asyncio
import base64
import json
import time
import pytest
from stickerlib import UPLOAD_CHUNK_BYTES
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 16
def run(coro):
return asyncio.run(coro)
def big_png(total: int) -> bytes:
return b"\x89PNG\r\n\x1a\n" + b"\x00" * (total - 8)
def test_upload_round_trips_through_chunks(make_plugin):
async def scenario():
plugin, _ = make_plugin()
payload = big_png(UPLOAD_CHUNK_BYTES * 2 + 10)
session = (await plugin.begin_upload())["session"]
received = 0
for index in range(0, (len(payload) + UPLOAD_CHUNK_BYTES - 1) // UPLOAD_CHUNK_BYTES):
piece = payload[index * UPLOAD_CHUNK_BYTES:(index + 1) * UPLOAD_CHUNK_BYTES]
result = await plugin.put_upload_chunk(
session, index, base64.b64encode(piece).decode("ascii")
)
received = result["received"]
assert received == len(payload)
item = await plugin.finish_upload("chunked", session)
assert item["slug"] == "chunked"
stored = await plugin.get_sticker_bytes("chunked")
assert stored is not None and stored[0] == payload
run(scenario())
def test_chunk_bytes_contract_is_constant(make_plugin):
async def scenario():
plugin, _ = make_plugin()
begin = await plugin.begin_upload()
assert begin["chunk_bytes"] == UPLOAD_CHUNK_BYTES == 256 * 1024
# The page splits on that number, so one request never exceeds it.
assert begin["chunk_bytes"] <= 256 * 1024
run(scenario())
def test_upload_rejects_a_gap(make_plugin):
async def scenario():
plugin, _ = make_plugin()
session = (await plugin.begin_upload())["session"]
await plugin.put_upload_chunk(session, 0, base64.b64encode(PNG).decode())
await plugin.put_upload_chunk(session, 2, base64.b64encode(PNG).decode())
with pytest.raises(ValueError, match="gap"):
await plugin.finish_upload("gappy", session)
run(scenario())
def test_upload_enforces_the_size_limit(make_plugin):
async def scenario():
plugin, _ = make_plugin({"max_sticker_mb": 1})
session = (await plugin.begin_upload())["session"]
payload = big_png(1024 * 1024 + 32)
with pytest.raises(ValueError, match="exceeds"):
await plugin.put_upload_chunk(
session, 0, base64.b64encode(payload).decode()
)
run(scenario())
def test_upload_rejects_a_bad_session(make_plugin):
async def scenario():
plugin, _ = make_plugin()
with pytest.raises(ValueError, match="invalid upload session"):
await plugin.put_upload_chunk("bad.session", 0, base64.b64encode(PNG).decode())
with pytest.raises(ValueError, match="invalid upload session"):
await plugin.finish_upload("cat", "../escape")
run(scenario())
def test_finish_drops_the_session(make_plugin):
async def scenario():
plugin, host = make_plugin()
session = (await plugin.begin_upload())["session"]
await plugin.put_upload_chunk(session, 0, base64.b64encode(PNG).decode())
await plugin.finish_upload("cat", session)
assert not [key for key in host.data if ":upload:" in key]
run(scenario())
def test_abandoned_sessions_are_reaped(make_plugin):
async def scenario():
plugin, host = make_plugin()
stale = (await plugin.begin_upload())["session"]
await plugin.put_upload_chunk(stale, 0, base64.b64encode(PNG).decode())
# Age the marker past the TTL, then open a fresh session.
key = next(k for k in host.data if ":upload:" in k and k.endswith(":000000"))
host.data[key] = json.dumps({"created_at": time.time() - 20 * 60}).encode()
await plugin.begin_upload()
assert not [k for k in host.data if f":upload:{stale}:" in k]
run(scenario())
def test_abort_drops_the_session(make_plugin):
async def scenario():
plugin, host = make_plugin()
session = (await plugin.begin_upload())["session"]
await plugin.put_upload_chunk(session, 0, base64.b64encode(PNG).decode())
await plugin.abort_upload(session)
assert not [k for k in host.data if ":upload:" in k]
run(scenario())