Files
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

193 lines
6.5 KiB
Python

import asyncio
import hashlib
import hmac
import json
from typing import Any
import httpx2
import pytest
from handler.notification_channels import webhook
from handler.notification_channels.config import WebhookConfig
from handler.notification_channels.messages import OutboundMessage
from handler.notification_channels.webhook import (
WebhookError,
build_request,
check_url,
send,
)
from utils.ssrf import SSRFProtectedAsyncBackend
from .fixtures import make_actor, make_notification
def _message(**overrides) -> OutboundMessage:
return OutboundMessage(
notification=make_notification(**overrides),
title="Maintenance tonight",
body="RomM restarts at 23:00",
url="https://romm.example.com/platforms",
)
class TestBuildRequest:
def test_carries_the_notification_and_its_text(self):
request = build_request(
WebhookConfig(url="https://hooks.example.com/romm"),
_message(actor=make_actor()),
)
payload = json.loads(request.content)
assert request.url == "https://hooks.example.com/romm"
assert payload["event"] == "notification"
assert payload["title"] == "Maintenance tonight"
assert payload["url"] == "https://romm.example.com/platforms"
assert payload["actor"] == {"id": 1, "username": "admin"}
assert webhook.SIGNATURE_HEADER not in request.headers
def test_is_signed_with_the_secret(self):
request = build_request(
WebhookConfig(url="https://hooks.example.com", secret="k"),
_message(),
)
expected = hmac.new(b"k", request.content, hashlib.sha256).hexdigest()
assert request.headers[webhook.SIGNATURE_HEADER] == f"sha256={expected}"
class TestCheckUrl:
@pytest.mark.parametrize("url", ["ftp://example.com/x", "not a url", "https://"])
def test_refuses_anything_but_http(self, url):
with pytest.raises(ValueError):
check_url(url, allow_private=True)
def test_keeps_a_user_off_the_local_network(self):
with pytest.raises(ValueError):
check_url("http://192.168.1.10/hook", allow_private=False)
def test_lets_an_admin_reach_the_local_network(self):
check_url("http://192.168.1.10/hook", allow_private=True)
def test_a_user_gets_no_admin_configured_internal_origin(self, mocker):
validate = mocker.spy(webhook, "validate_url_for_http_request")
with pytest.raises(ValueError):
check_url("http://127.0.0.1:9099/hook", allow_private=False)
assert validate.call_args.kwargs["allowlist"] == frozenset()
async def test_a_users_client_gets_no_admin_configured_internal_origin(self):
async with webhook._client(allow_private=False) as client:
transport: Any = client._transport
backend = transport._pool._network_backend
assert isinstance(backend, SSRFProtectedAsyncBackend)
assert backend._allowlist == frozenset()
@pytest.mark.parametrize(
"url",
[
"https://example.com:abc/x",
"https://example.com:99999/x",
"https://example.com:0/x",
],
)
def test_refuses_a_port_that_isnt_one(self, url):
with pytest.raises(ValueError, match="port"):
check_url(url, allow_private=True)
def _serve(mocker, handler) -> None:
mocker.patch.object(
webhook,
"_client",
return_value=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)),
)
_CONFIG = WebhookConfig(url="https://hooks.example.com/romm")
class TestSend:
@pytest.fixture
def respond(self, mocker):
def install(status_code: int, text: str = ""):
calls: list[httpx2.Request] = []
async def body():
yield text.encode()
# Streamed, as a response off the network is.
def handler(request: httpx2.Request) -> httpx2.Response:
calls.append(request)
return httpx2.Response(status_code, content=body())
_serve(mocker, handler)
return calls
return install
async def test_posts_the_built_request(self, respond):
calls = respond(204)
await send(_CONFIG, _message(), allow_private=False)
[request] = calls
assert str(request.url) == "https://hooks.example.com/romm"
assert json.loads(request.content)["title"] == "Maintenance tonight"
async def test_a_refusal_says_who_refused_and_why(self, respond):
respond(404, '{"message": "Unknown Webhook"}')
with pytest.raises(
WebhookError, match="hooks.example.com answered 404: .*Unknown"
):
await send(_CONFIG, _message(), allow_private=False)
async def test_a_redirect_is_a_delivery_that_did_not_land(self, mocker):
_serve(
mocker,
lambda request: httpx2.Response(
301, headers={"Location": "https://hooks.example.com/new"}
),
)
with pytest.raises(
WebhookError,
match="answered 301: redirected to https://hooks.example.com/new",
):
await send(_CONFIG, _message(), allow_private=False)
async def test_reads_only_the_start_of_an_endless_refusal(self, mocker):
async def endless():
while True:
yield b"x" * 4096
_serve(mocker, lambda request: httpx2.Response(500, content=endless()))
with pytest.raises(WebhookError) as caught:
await send(_CONFIG, _message(), allow_private=False)
assert str(caught.value) == (
"hooks.example.com answered 500: " + "x" * webhook.ERROR_DETAIL_CHARS
)
async def test_gives_up_on_a_host_that_never_answers(self, mocker):
async def handler(request: httpx2.Request) -> httpx2.Response:
await asyncio.sleep(10)
return httpx2.Response(204)
mocker.patch.object(webhook, "TIMEOUT_SECONDS", 0.05)
_serve(mocker, handler)
with pytest.raises(WebhookError, match="hooks.example.com did not answer"):
await send(_CONFIG, _message(), allow_private=False)
async def test_an_unreachable_host_is_a_webhook_error(self, mocker):
def handler(request: httpx2.Request) -> httpx2.Response:
raise httpx2.ConnectError("Connection refused")
_serve(mocker, handler)
with pytest.raises(WebhookError, match="Could not reach hooks.example.com"):
await send(_CONFIG, _message(), allow_private=False)