mirror of
https://github.com/rommapp/romm.git
synced 2026-12-02 18:18:47 +01:00
* test(backend): build test ROMs through one make_rom factory Tests created Rom rows by hand in dozens of places, each spelling out the same slug and filename fields and deriving the slug inline. Production never computes a slug from a name, so this was test-only filler duplicated across files. tests/factories.py adds make_rom(platform, name, *, fs_stem, fs_extension, **overrides), which fills the slug and filename columns and persists through db_rom_handler.add_rom. The shared conftest fixtures, scan_stubs.add_rom and the local helpers and inline constructors across 35 test files now use it. Each test keeps its filename shape (underscored stems in the FULLTEXT search tests, spaced "Name (USA)" stems in the sibling tests), and fixtures shared across files keep their exact slugs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend): keep extensionless filenames intact in scan_stubs.add_rom rpartition(".") on a name with no dot returned an empty stem and the whole name as the extension, so make_rom stored ".README" for "README". os.path.splitext leaves such names whole. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend): build test saves, states and screenshots through factories Tests built Save, State and Screenshot rows by hand across about 20 files, each spelling out file_name_no_tags, file_name_no_ext and file_extension although BaseAsset already derives them from file_name. tests/factories.py adds make_save, make_state and make_screenshot. Each sets the rom and user ids, the file name, and a default file_path under the rom's platform, applies overrides last, and persists through the matching db handler. The conftest asset fixtures and the persisted constructors and local helpers now use them. Rows a test observes keep their file_path, emulator, slot, size and hash, and a filename part stays an override wherever it differs from what the model derives. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend): ban direct add_* persistence in tests via ruff TID251 The factories only stay the one home for test rows if nothing routes around them. Ruff's banned-api rule now flags db_rom_handler.add_rom, db_save_handler.add_save, db_state_handler.add_state and db_screenshot_handler.add_screenshot anywhere under tests/ except tests/factories.py. Production code is unaffected. The remaining add_rom calls move onto make_rom: the unique-path, soundtrack and id-index tests in test_roms_handler.py, the scan tests in test_fastapi.py, physical and missing rows in the feed, download and model tests, and the name=None exporter rows. Scan tests keep a filename-derived placeholder as the name, which scan_rom treats the same as no name. Three calls keep a noqa: the tests of how add_rom merges a partial scanned row, and the rescan test that persists scan_rom's output as a scan does. The backend skill and the architecture doc now point at tests/factories.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend): move the firmware and client-token factories into tests/factories.py The add_firmware and add_device_token conftest fixtures returned a builder, unlike the importable make_* functions. They become make_firmware and make_device_token alongside them, with the same defaults, and their callers import them rather than requesting a fixture. make_device_token now draws the raw credential from auth_handler.generate_client_token, so it carries the real rmm_ prefix instead of restating it, and the hand-built client tokens in the auth tests use it too. The ruff TID251 ban now also covers db_firmware_handler.add_firmware and db_client_token_handler.add_token under tests/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: point at every test factory, not just the ROM and asset ones Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
284 lines
9.7 KiB
Python
284 lines
9.7 KiB
Python
"""Admin CRUD for groups, memberships, overrides and hidden entities, and the
|
|
end-to-end effect on a member's /permissions/me."""
|
|
|
|
from datetime import timedelta
|
|
from unittest.mock import AsyncMock
|
|
|
|
from tests.factories import make_device_token
|
|
|
|
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
|
|
from endpoints import permissions as permissions_endpoints
|
|
from handler.auth import oauth_handler
|
|
from handler.database import db_user_handler
|
|
from handler.database.base_handler import sync_session
|
|
from handler.database.permissions_handler import DBPermissionsHandler
|
|
from models.permission import PermissionGroup
|
|
|
|
|
|
def _bearer(token):
|
|
return {"Authorization": f"Bearer {token}"}
|
|
|
|
|
|
def _fresh_user_auth(user_id):
|
|
# Mint a token from the user's CURRENT (post-change) projected scopes.
|
|
user = db_user_handler.get_user(user_id)
|
|
assert user is not None
|
|
return _bearer(
|
|
oauth_handler.create_access_token(
|
|
data={
|
|
"sub": user.username,
|
|
"iss": "romm:oauth",
|
|
"scopes": " ".join(user.oauth_scopes),
|
|
},
|
|
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
|
|
)
|
|
)
|
|
|
|
|
|
def _me_actions(client, user_id):
|
|
body = client.get("/api/permissions/me", headers=_fresh_user_auth(user_id)).json()
|
|
return {g["action"] for g in body["grants"]}, body
|
|
|
|
|
|
def _cleanup():
|
|
with sync_session.begin() as s:
|
|
s.query(PermissionGroup).filter(PermissionGroup.system_key.is_(None)).delete(
|
|
synchronize_session="evaluate"
|
|
)
|
|
|
|
|
|
def test_non_admin_forbidden(client, viewer_access_token):
|
|
h = _bearer(viewer_access_token)
|
|
assert client.get("/api/permissions/groups", headers=h).status_code == 403
|
|
assert client.get("/api/permissions/catalog", headers=h).status_code == 403
|
|
assert (
|
|
client.post(
|
|
"/api/permissions/groups", headers=h, json={"name": "x"}
|
|
).status_code
|
|
== 403
|
|
)
|
|
|
|
|
|
def test_catalog_lists_vocabulary(client, access_token):
|
|
body = client.get("/api/permissions/catalog", headers=_bearer(access_token)).json()
|
|
assert "roms" in body["entities"] and "platforms" in body["entities"]
|
|
assert set(body["actions"]) == {"read", "write", "delete"}
|
|
|
|
|
|
def test_groups_expose_the_system_key(client, access_token):
|
|
groups = client.get("/api/permissions/groups", headers=_bearer(access_token)).json()
|
|
keys = {g["name"]: g["system_key"] for g in groups}
|
|
assert keys["Viewer"] == "viewer"
|
|
assert keys["Editor"] == "editor"
|
|
assert "is_system" not in groups[0]
|
|
|
|
|
|
def test_group_create_assign_and_effective_permissions(
|
|
client, access_token, viewer_user
|
|
):
|
|
try:
|
|
created = client.post(
|
|
"/api/permissions/groups",
|
|
headers=_bearer(access_token),
|
|
json={
|
|
"name": "Curators",
|
|
"description": "roms + platform read",
|
|
"grants": [
|
|
{"entity": "roms", "action": "read"},
|
|
{"entity": "roms", "action": "write"},
|
|
{"entity": "platforms", "action": "read"},
|
|
],
|
|
},
|
|
)
|
|
assert created.status_code == 201
|
|
group = created.json()
|
|
assert group["member_count"] == 0
|
|
assert {(g["entity"], g["action"]) for g in group["grants"]} == {
|
|
("roms", "read"),
|
|
("roms", "write"),
|
|
("platforms", "read"),
|
|
}
|
|
gid = group["id"]
|
|
|
|
assigned = client.put(
|
|
f"/api/permissions/users/{viewer_user.id}",
|
|
headers=_bearer(access_token),
|
|
json={"set_group": True, "permission_group_id": gid},
|
|
)
|
|
assert assigned.status_code == 200
|
|
assert assigned.json()["permission_group_id"] == gid
|
|
|
|
actions, _ = _me_actions(client, viewer_user.id)
|
|
# Group grants -> these actions; nothing from the default viewer matrix.
|
|
assert {"rom.view", "rom.upload", "platform.view"} <= actions
|
|
assert "collection.create" not in actions # group grants no collections
|
|
finally:
|
|
_cleanup()
|
|
|
|
|
|
def test_user_override_adds_capability(client, access_token, viewer_user):
|
|
try:
|
|
gid = client.post(
|
|
"/api/permissions/groups",
|
|
headers=_bearer(access_token),
|
|
json={"name": "RO", "grants": [{"entity": "roms", "action": "read"}]},
|
|
).json()["id"]
|
|
client.put(
|
|
f"/api/permissions/users/{viewer_user.id}",
|
|
headers=_bearer(access_token),
|
|
json={
|
|
"set_group": True,
|
|
"permission_group_id": gid,
|
|
"overrides": [{"entity": "roms", "action": "delete", "granted": True}],
|
|
},
|
|
)
|
|
actions, _ = _me_actions(client, viewer_user.id)
|
|
assert "rom.delete" in actions # granted by override on top of read-only group
|
|
finally:
|
|
_cleanup()
|
|
|
|
|
|
def test_a_permission_change_closes_the_users_device_sockets(
|
|
mocker, client, access_token, viewer_user
|
|
):
|
|
token, _ = make_device_token(viewer_user, None, scopes="devices.read")
|
|
close = mocker.patch.object(
|
|
permissions_endpoints, "close_client_token_sockets", AsyncMock()
|
|
)
|
|
|
|
response = client.put(
|
|
f"/api/permissions/users/{viewer_user.id}",
|
|
headers=_bearer(access_token),
|
|
json={"overrides": [{"entity": "roms", "action": "delete", "granted": True}]},
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
close.assert_awaited_once_with([token.id])
|
|
|
|
|
|
def test_a_group_edit_closes_every_members_device_sockets_at_once(
|
|
mocker, client, access_token, viewer_user, editor_user
|
|
):
|
|
try:
|
|
gid = client.post(
|
|
"/api/permissions/groups",
|
|
headers=_bearer(access_token),
|
|
json={"name": "Handhelds"},
|
|
).json()["id"]
|
|
for user in (viewer_user, editor_user):
|
|
client.put(
|
|
f"/api/permissions/users/{user.id}",
|
|
headers=_bearer(access_token),
|
|
json={"set_group": True, "permission_group_id": gid},
|
|
)
|
|
viewer_token, _ = make_device_token(viewer_user, None, scopes="devices.read")
|
|
editor_token, _ = make_device_token(editor_user, None, scopes="devices.read")
|
|
close = mocker.patch.object(
|
|
permissions_endpoints, "close_client_token_sockets", AsyncMock()
|
|
)
|
|
|
|
response = client.put(
|
|
f"/api/permissions/groups/{gid}",
|
|
headers=_bearer(access_token),
|
|
json={"grants": [{"entity": "roms", "action": "read"}]},
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
close.assert_awaited_once()
|
|
assert close.await_args is not None
|
|
assert sorted(close.await_args.args[0]) == sorted(
|
|
[viewer_token.id, editor_token.id]
|
|
)
|
|
finally:
|
|
_cleanup()
|
|
|
|
|
|
def test_hide_entity_for_user(client, access_token, viewer_user):
|
|
resp = client.post(
|
|
"/api/permissions/hidden",
|
|
headers=_bearer(access_token),
|
|
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
|
)
|
|
assert resp.status_code == 200
|
|
|
|
_, body = _me_actions(client, viewer_user.id)
|
|
assert body["hidden"]["platforms"] == [11]
|
|
|
|
# Idempotent + removable.
|
|
client.post(
|
|
"/api/permissions/hidden",
|
|
headers=_bearer(access_token),
|
|
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
|
)
|
|
removed = client.request(
|
|
"DELETE",
|
|
"/api/permissions/hidden",
|
|
headers=_bearer(access_token),
|
|
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
|
)
|
|
assert removed.status_code == 204
|
|
_, body = _me_actions(client, viewer_user.id)
|
|
assert body["hidden"]["platforms"] == []
|
|
|
|
|
|
def test_hidden_requires_exactly_one_principal(client, access_token):
|
|
resp = client.post(
|
|
"/api/permissions/hidden",
|
|
headers=_bearer(access_token),
|
|
json={"entity": "roms", "entity_id": 1, "user_id": 1, "group_id": 1},
|
|
)
|
|
assert resp.status_code == 400
|
|
|
|
|
|
def test_cannot_delete_default_group(client, access_token):
|
|
groups = client.get("/api/permissions/groups", headers=_bearer(access_token)).json()
|
|
default = next(g for g in groups if g["is_default"])
|
|
resp = client.delete(
|
|
f"/api/permissions/groups/{default['id']}", headers=_bearer(access_token)
|
|
)
|
|
assert resp.status_code == 400
|
|
|
|
|
|
def test_update_group_deleted_mid_update_returns_404(client, access_token, mocker):
|
|
try:
|
|
gid = client.post(
|
|
"/api/permissions/groups",
|
|
headers=_bearer(access_token),
|
|
json={"name": "Vanishing"},
|
|
).json()["id"]
|
|
mocker.patch.object(DBPermissionsHandler, "update_group", return_value=None)
|
|
|
|
resp = client.put(
|
|
f"/api/permissions/groups/{gid}",
|
|
headers=_bearer(access_token),
|
|
json={"description": "renamed"},
|
|
)
|
|
assert resp.status_code == 404
|
|
finally:
|
|
_cleanup()
|
|
|
|
|
|
def test_delete_group_falls_members_back(client, access_token, viewer_user):
|
|
gid = client.post(
|
|
"/api/permissions/groups",
|
|
headers=_bearer(access_token),
|
|
json={"name": "Temp", "grants": [{"entity": "roms", "action": "read"}]},
|
|
).json()["id"]
|
|
client.put(
|
|
f"/api/permissions/users/{viewer_user.id}",
|
|
headers=_bearer(access_token),
|
|
json={"set_group": True, "permission_group_id": gid},
|
|
)
|
|
|
|
resp = client.delete(
|
|
f"/api/permissions/groups/{gid}", headers=_bearer(access_token)
|
|
)
|
|
assert resp.status_code == 200
|
|
|
|
# FK SET NULL -> user falls back to the default (viewer) matrix.
|
|
user = db_user_handler.get_user(viewer_user.id)
|
|
assert user is not None
|
|
assert user.permission_group_id is None
|
|
actions, _ = _me_actions(client, viewer_user.id)
|
|
assert "collection.create" in actions # default viewer behaviour restored
|