Files
romm/backend/tests/utils/test_images.py
Georges-Antoine Assi 37e4ca304d fix: permission, validation and resource-limit hardening (#5496)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: fix mypy errors in the new tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: apply review-polish pass on permission hardening

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(play-sessions): filter rom_id and device_id on PlaySession after the visibility join

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 11:39:30 -05:00

191 lines
6.4 KiB
Python

import struct
import zlib
from io import BytesIO
from typing import Any
import pytest
from PIL import Image
from utils.images import (
MAX_COVER_PIXELS,
frame_durations,
is_animated,
is_oversized_cover,
webp_loop,
)
FRAME_SIZE = (60, 90)
FRAME_COLORS = ("red", "green", "blue")
DURATIONS = [100, 250, 400]
def encode_animation(
frames: list[Image.Image], fmt: str, durations: list[int], **params: Any
) -> bytes:
"""Encode frames as an animated image of the given format."""
buf = BytesIO()
frames[0].save(
buf,
format=fmt,
save_all=True,
append_images=frames[1:],
duration=durations,
**params,
)
return buf.getvalue()
def animated_image_bytes(
fmt: str, durations: list[int] = DURATIONS, loop: int | None = 0
) -> bytes:
"""Encode one solid FRAME_SIZE frame per duration as an animated image."""
frames = [
Image.new("RGB", FRAME_SIZE, FRAME_COLORS[i % len(FRAME_COLORS)])
for i in range(len(durations))
]
return encode_animation(
frames, fmt, durations, **({} if loop is None else {"loop": loop})
)
def jxl_image_bytes(size: tuple[int, int] = FRAME_SIZE) -> bytes:
"""A still JPEG XL image, encoded through the plugin utils.images registers."""
buf = BytesIO()
Image.new("RGB", size, "red").save(buf, format="JXL")
return buf.getvalue()
def png_header_bytes(width: int, height: int) -> bytes:
"""A PNG that declares width x height but holds no pixel data."""
ihdr = b"IHDR" + struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return (
b"\x89PNG\r\n\x1a\n"
+ struct.pack(">I", len(ihdr) - 4)
+ ihdr
+ struct.pack(">I", zlib.crc32(ihdr))
+ b"\x00\x00\x00\x00IEND\xaeB`\x82"
)
def truncated_animation_bytes(fmt: str) -> bytes:
"""An animation with its last frame cut short."""
return animated_image_bytes(fmt)[:-40]
def growing_canvas_gif() -> bytes:
"""A 10x10 GIF whose second frame grows the canvas to 40x40."""
parts = []
for size in ((10, 10), (40, 40)):
buf = BytesIO()
Image.new("P", size).save(buf, format="GIF")
parts.append(buf.getvalue())
# Frames follow the header and global palette, sized alike in both files
frames_start = 13 + 3 * 2 ** ((parts[0][10] & 0x07) + 1)
return parts[0][:-1] + parts[1][frames_start:]
class TestIsOversizedCover:
def test_header_past_the_limit(self):
with Image.open(BytesIO(png_header_bytes(10000, 8000))) as img:
assert is_oversized_cover(img)
def test_header_at_the_limit(self):
with Image.open(BytesIO(png_header_bytes(MAX_COVER_PIXELS, 1))) as img:
assert not is_oversized_cover(img)
class TestIsAnimated:
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "WEBP", "AVIF"])
def test_multi_frame_image(self, fmt: str):
with Image.open(BytesIO(animated_image_bytes(fmt))) as img:
assert is_animated(img)
def test_single_frame_image(self):
buf = BytesIO()
Image.new("RGB", (4, 4)).save(buf, format="PNG")
with Image.open(buf) as img:
assert not is_animated(img)
def test_multi_page_tiff(self):
# Browsers show the first page of a TIFF, so its pages aren't frames
buf = BytesIO()
pages = [Image.new("RGB", (4, 4)), Image.new("RGB", (4, 4), "red")]
pages[0].save(buf, format="TIFF", save_all=True, append_images=pages[1:])
with Image.open(buf) as img:
assert getattr(img, "is_animated", False)
assert not is_animated(img)
def test_over_pixel_budget(self, monkeypatch: pytest.MonkeyPatch):
pixels = len(DURATIONS) * FRAME_SIZE[0] * FRAME_SIZE[1]
monkeypatch.setattr("utils.images.MAX_ANIMATION_PIXELS", pixels - 1)
with Image.open(BytesIO(animated_image_bytes("GIF"))) as img:
assert not is_animated(img)
class TestFrameDurations:
@pytest.mark.parametrize("fmt", ["GIF", "PNG", "WEBP", "AVIF"])
def test_reads_each_frame(self, fmt: str):
with Image.open(BytesIO(animated_image_bytes(fmt))) as img:
assert frame_durations(img) == DURATIONS
assert img.tell() == 0
def test_passes_each_decoded_frame(self):
seen: list[Image.Image] = []
with Image.open(BytesIO(animated_image_bytes("PNG"))) as img:
frame_durations(img, lambda frame: seen.append(frame.convert("RGB")))
assert [frame.getpixel((0, 0)) for frame in seen] == [
(255, 0, 0),
(0, 128, 0),
(0, 0, 255),
]
def test_still_image(self):
buf = BytesIO()
Image.new("RGB", (4, 4)).save(buf, format="PNG")
with Image.open(buf) as img:
assert frame_durations(img) is None
@pytest.mark.parametrize("fmt", ["GIF", "PNG"])
def test_damaged_frame(self, fmt: str):
with Image.open(BytesIO(truncated_animation_bytes(fmt))) as img:
assert frame_durations(img) is None
assert img.tell() == 0
def test_malformed_apng_frame(self):
data = bytearray(animated_image_bytes("PNG"))
second_fctl = data.find(b"fcTL", data.find(b"fcTL") + 4)
data[second_fctl + 4 : second_fctl + 8] = (99).to_bytes(4, "big")
with Image.open(BytesIO(bytes(data))) as img:
assert frame_durations(img) is None
def test_canvas_outgrows_pixel_budget(self, monkeypatch: pytest.MonkeyPatch):
# Declares 2 frames of 10x10 but decodes a 40x40 second frame
monkeypatch.setattr("utils.images.MAX_ANIMATION_PIXELS", 1000)
with Image.open(BytesIO(growing_canvas_gif())) as img:
assert is_animated(img)
assert frame_durations(img) is None
class TestWebpLoop:
@pytest.mark.parametrize(
"fmt, loop, expected",
[
("GIF", None, 1),
("GIF", 0, 0),
("GIF", 3, 4),
("GIF", 0xFFFF, 0xFFFF),
("PNG", 3, 3),
("WEBP", 0, 0),
],
)
def test_plays_as_often_as_source(self, fmt: str, loop: int | None, expected: int):
data = animated_image_bytes(fmt, [100, 100], loop=loop)
with Image.open(BytesIO(data)) as img:
assert webp_loop(img) == expected
def test_jpeg_xl_decodes_once_utils_images_is_imported():
with Image.open(BytesIO(jxl_image_bytes())) as img:
assert img.format == "JXL"
assert img.size == FRAME_SIZE