From 6298e7bf8cdb59bf7fb6853a3b515ee995f4834d Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 24 Sep 2026 02:30:47 +0200 Subject: [PATCH] fix(audit): apply the pr-ready code review - Hide events on roms of a hidden platform from non-admins. - Pin later pages to the highest matching id the API returns, not the first row's: rows are ordered by when they happened, so a play synced late has a higher id than newer events and was dropped. - Cap recorded failed sign-ins per address, dedupe reset requests and record them in the background with the email, and hash claim keys. - Keep another user's private collection by id only in bulk downloads. - Check a Range start without int(), which raises past 4300 digits. - Clear the list when a reload fails, load more only once it's shown, report a cover change only when the user made one, label only rom and platform unhides, accept an actor kind the API doesn't know. - One client IP helper, date-fns for today and yesterday, one time formatter for the list, no em-dashes. Co-Authored-By: Claude Opus 5.5 --- backend/endpoints/audit_events.py | 7 ++- backend/endpoints/auth.py | 47 ++++++++++++++----- backend/endpoints/collections.py | 4 +- backend/endpoints/permissions.py | 28 +++++++---- backend/endpoints/responses/audit_event.py | 4 +- backend/endpoints/roms/__init__.py | 27 +++++++++-- backend/endpoints/user.py | 6 +-- backend/handler/audit_handler.py | 32 +++++++++++-- .../handler/database/audit_events_handler.py | 33 ++++++++++--- .../endpoints/roms/test_download_audit.py | 40 +++++++++++++++- backend/tests/endpoints/test_audit_events.py | 15 +++--- backend/tests/endpoints/test_library_audit.py | 4 +- backend/tests/endpoints/test_play_sessions.py | 2 +- .../tests/endpoints/test_security_audit.py | 26 +++++++++- .../database/test_audit_events_handler.py | 14 +++++- backend/tests/handler/test_audit_handler.py | 5 +- .../__generated__/models/AuditEventSchema.ts | 2 +- .../models/AuditPage_AuditEventSchema_.ts | 1 + .../src/v2/components/Settings/EventLog.vue | 33 +++++++------ .../v2/components/Settings/EventLogRow.vue | 11 ++--- .../src/v2/components/Settings/LogViewer.vue | 2 +- .../v2/composables/useAuditLog/index.test.ts | 22 +++++++-- .../src/v2/composables/useAuditLog/index.ts | 9 +++- frontend/src/v2/utils/auditEvents.ts | 2 +- 24 files changed, 287 insertions(+), 89 deletions(-) diff --git a/backend/endpoints/audit_events.py b/backend/endpoints/audit_events.py index c7622e136..17acca38d 100644 --- a/backend/endpoints/audit_events.py +++ b/backend/endpoints/audit_events.py @@ -27,6 +27,10 @@ class AuditLimitOffsetParams(LimitOffsetParams): class AuditPage[T: BaseModel](TypedLimitOffsetPage[T]): __params_type__ = AuditLimitOffsetParams + # Rows are ordered by when they happened, not by id, so later pages pin to + # the highest id rather than to the first row's. + max_id: int | None = None + @protected_route(router.get, "", [Scope.ME_READ]) def get_audit_events( @@ -68,7 +72,7 @@ def get_audit_events( in_categories: set[str] = {a for c in category for a in actions_in(c)} actions = in_categories if actions is None else actions & in_categories - rows, total = db_audit_event_handler.get_events( + rows, total, highest_id = db_audit_event_handler.get_events( AuditEventFilters( actor_ids=(actor_id or None) if sees_everyone else [request.user.id], actions=actions, @@ -90,4 +94,5 @@ def get_audit_events( [AuditEventSchema.from_row(event, device_name) for event, device_name in rows], params, total=total, + max_id=highest_id, ) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index 8716815d2..9722c1fa3 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -23,7 +23,14 @@ from exceptions.auth_exceptions import ( OIDCNotConfiguredException, UserDisabledException, ) -from handler.audit_handler import AuditActor, AuditTarget, claim_once, record +from handler.audit_handler import ( + AuditActor, + AuditTarget, + claim_once, + client_ip, + record, + within_budget, +) from handler.auth import auth_handler, oauth_handler, oidc_handler from handler.database import db_user_handler from logger.formatter import CYAN @@ -41,20 +48,22 @@ router = APIRouter( # Failed sign-ins from one address for one username within this window are one attempt. LOGIN_FAILURE_WINDOW_SECONDS: Final = 60 +# At most this many failed sign-ins are recorded per address each window, so a +# client cycling usernames can't flood the log. +LOGIN_FAILURES_PER_ADDRESS: Final = 20 +LOGIN_FAILURE_ADDRESS_WINDOW_SECONDS: Final = 10 * 60 +# Repeated reset requests for one user from one address are one request. +PASSWORD_RESET_REQUEST_WINDOW_SECONDS: Final = 10 * 60 LoginMethod = Literal["password", "token", "oidc"] -def _client_ip(request: Request) -> str | None: - return request.client.host if request.client else None - - def _record_login( request: Request, user: User, method: LoginMethod, device_id: str | None = None ) -> None: record( AuditAction.AUTH_LOGIN, - AuditActor.for_user(user, ip_address=_client_ip(request), device_id=device_id), + AuditActor.for_user(user, ip_address=client_ip(request), device_id=device_id), data={"method": method}, ) @@ -65,9 +74,13 @@ def _record_login_failure( method: LoginMethod, reason: Literal["credentials", "disabled"], ) -> None: - ip_address = _client_ip(request) + ip_address = client_ip(request) if not claim_once( f"login_failed:{ip_address}:{username}", LOGIN_FAILURE_WINDOW_SECONDS + ) or not within_budget( + f"login_failed:{ip_address}", + LOGIN_FAILURES_PER_ADDRESS, + LOGIN_FAILURE_ADDRESS_WINDOW_SECONDS, ): return user = db_user_handler.get_user_by_username(username) if username else None @@ -87,6 +100,18 @@ def _record_login_failure( ) +def _record_password_reset_request(ip_address: str | None, user: User) -> None: + if claim_once( + f"password_reset:{ip_address}:{user.id}", + PASSWORD_RESET_REQUEST_WINDOW_SECONDS, + ): + record( + AuditAction.AUTH_PASSWORD_RESET_REQUEST, + AuditActor(AuditActorKind.ANONYMOUS, ip_address=ip_address), + AuditTarget.of_user(user), + ) + + # Session authentication endpoints @router.post("/login") def login( @@ -396,10 +421,8 @@ def request_password_reset( if user: # After the response, so its timing can't tell whether the user exists. background_tasks.add_task(auth_handler.send_password_reset_link, user) - record( - AuditAction.AUTH_PASSWORD_RESET_REQUEST, - AuditActor(AuditActorKind.ANONYMOUS, ip_address=_client_ip(request)), - AuditTarget.of_user(user), + background_tasks.add_task( + _record_password_reset_request, client_ip(request), user ) else: log.warning( @@ -427,7 +450,7 @@ async def reset_password( await auth_handler.set_user_new_password(user, new_password) record( AuditAction.AUTH_PASSWORD_RESET, - AuditActor.for_user(user, ip_address=_client_ip(request)), + AuditActor.for_user(user, ip_address=client_ip(request)), AuditTarget.of_user(user), ) diff --git a/backend/endpoints/collections.py b/backend/endpoints/collections.py index cedc41e01..8e63ddffa 100644 --- a/backend/endpoints/collections.py +++ b/backend/endpoints/collections.py @@ -552,7 +552,9 @@ async def update_collection( for field in ("name", "description", "is_public") if cleaned_data[field] != getattr(collection, field) ] - if remove_cover or "path_cover_l" in cleaned_data: + new_artwork = artwork is not None and artwork.filename is not None + new_cover_url = url_cover is not None and url_cover != collection.url_cover + if remove_cover or new_artwork or new_cover_url: changed.append("cover") before_ids, after_ids = set(collection.rom_ids), set(parsed_rom_ids) if changed or before_ids != after_ids: diff --git a/backend/endpoints/permissions.py b/backend/endpoints/permissions.py index 07b511263..1165c5a10 100644 --- a/backend/endpoints/permissions.py +++ b/backend/endpoints/permissions.py @@ -99,17 +99,19 @@ def _group_target(group: PermissionGroup) -> AuditTarget: return AuditTarget(AuditTargetType.PERMISSION_GROUP, group.id, group.name) -def _hidden_target(entity: PermEntity, entity_id: int) -> AuditTarget: +def _hidden_target(entity: PermEntity, entity_id: int) -> AuditTarget | None: if entity == PermEntity.ROMS: rom = db_rom_handler.get_rom_visibility_label(entity_id) name = (rom.name or rom.fs_name) if rom else None return AuditTarget(AuditTargetType.ROM, entity_id, name) - platform = db_platform_handler.get_platform(entity_id) - return AuditTarget( - AuditTargetType.PLATFORM, - entity_id, - (platform.custom_name or platform.name) if platform else None, - ) + if entity == PermEntity.PLATFORMS: + platform = db_platform_handler.get_platform(entity_id) + return AuditTarget( + AuditTargetType.PLATFORM, + entity_id, + (platform.custom_name or platform.name) if platform else None, + ) + return None def _principal(user_id: int | None, group_id: int | None) -> dict[str, Any]: @@ -355,7 +357,11 @@ async def add_hidden_entity( AuditAction.VISIBILITY_HIDE, AuditActor.from_request(request), _hidden_target(body.entity, body.entity_id), - {"from": _principal(body.user_id, body.group_id)}, + { + "from": _principal(body.user_id, body.group_id), + "entity": body.entity, + "entity_id": body.entity_id, + }, ) await _emit_for_principal(body.user_id, body.group_id) return HiddenEntitySchema(entity=body.entity, entity_id=body.entity_id) @@ -388,7 +394,11 @@ async def remove_hidden_entity( AuditAction.VISIBILITY_UNHIDE, AuditActor.from_request(request), _hidden_target(entity, entity_id), - {"from": _principal(user_id, group_id)}, + { + "from": _principal(user_id, group_id), + "entity": entity, + "entity_id": entity_id, + }, ) await _emit_for_principal(user_id, group_id) diff --git a/backend/endpoints/responses/audit_event.py b/backend/endpoints/responses/audit_event.py index 53509e4f8..bf0ec4f89 100644 --- a/backend/endpoints/responses/audit_event.py +++ b/backend/endpoints/responses/audit_event.py @@ -18,7 +18,7 @@ class AuditEventSchema(BaseModel): action: AuditAction | str category: AuditCategory | None occurred_at: UTCDatetime - actor_kind: AuditActorKind + actor_kind: AuditActorKind | str # The account as it is now; null once it's deleted, when `actor_name` remains. actor: NotificationActorSchema | None actor_name: str | None @@ -37,7 +37,7 @@ class AuditEventSchema(BaseModel): action=event.action, category=category_of(event.action), occurred_at=event.occurred_at, - actor_kind=AuditActorKind(event.actor_kind), + actor_kind=event.actor_kind, actor=( NotificationActorSchema.model_validate(event.actor) if event.actor diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 8dba44866..12ca7d3e2 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -870,21 +870,36 @@ def get_random_rom( def _bulk_download_target( + user_id: int, platform_id: int | None, collection_id: int | None, smart_collection_id: int | None, virtual_collection_id: str | None, ) -> AuditTarget | None: - """What a bulk download took whole, or None for a hand-picked list of roms.""" + """What a bulk download took whole, or None for a hand-picked list of roms. + + Another user's private collection is kept by id only, so its name doesn't + reach the caller's own history. + """ if platform_id: platform = db_platform_handler.get_platform(platform_id) return AuditTarget.of_platform(platform) if platform else None if collection_id: collection = db_collection_handler.get_collection(collection_id) - return AuditTarget.of_collection(collection) if collection else None + visible = collection and (collection.is_public or collection.user_id == user_id) + return AuditTarget( + AuditTargetType.COLLECTION, + collection_id, + collection.name if collection and visible else None, + ) if smart_collection_id: smart = db_collection_handler.get_smart_collection(smart_collection_id) - return AuditTarget.of_smart_collection(smart) if smart else None + visible = smart and (smart.is_public or smart.user_id == user_id) + return AuditTarget( + AuditTargetType.SMART_COLLECTION, + smart_collection_id, + smart.name if smart and visible else None, + ) if virtual_collection_id: virtual = db_collection_handler.get_virtual_collection(virtual_collection_id) return AuditTarget( @@ -1002,7 +1017,11 @@ async def download_roms( record_download( request, _bulk_download_target( - platform_id, collection_id, smart_collection_id, virtual_collection_id + request.user.id, + platform_id, + collection_id, + smart_collection_id, + virtual_collection_id, ), f"bulk:{binascii.crc32(','.join(map(str, sorted(found_ids))).encode())}", {"count": len(rom_objects), "rom_ids": sorted(found_ids)}, diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index 1509061eb..02b9a5bad 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -10,7 +10,7 @@ from decorators.auth import protected_route from endpoints.forms.identity import UserForm from endpoints.permissions import emit_permissions_changed from endpoints.responses.identity import InviteLinkSchema, UserSchema -from handler.audit_handler import AuditActor, AuditTarget, record +from handler.audit_handler import AuditActor, AuditTarget, client_ip, record from handler.auth import auth_handler from handler.auth.constants import Scope from handler.database import db_user_handler @@ -289,9 +289,7 @@ def create_user_from_invite( created_user = db_user_handler.add_user(user) record( AuditAction.USER_REGISTER, - AuditActor.for_user( - created_user, ip_address=request.client.host if request.client else None - ), + AuditActor.for_user(created_user, ip_address=client_ip(request)), AuditTarget.of_user(created_user), {"role": created_user.role, "via": "invite"}, ) diff --git a/backend/handler/audit_handler.py b/backend/handler/audit_handler.py index 3105d7041..6db5e62c2 100644 --- a/backend/handler/audit_handler.py +++ b/backend/handler/audit_handler.py @@ -5,6 +5,7 @@ Best effort: a failure to record is logged and never reaches the action. from __future__ import annotations +import hashlib import json import re from collections.abc import Sequence @@ -49,6 +50,10 @@ def _clip_name(name: str | None) -> str | None: return name.replace("\x00", "")[:AUDIT_NAME_MAX_LENGTH] +def client_ip(conn: HTTPConnection) -> str | None: + return conn.client.host if conn.client else None + + @dataclass(frozen=True, slots=True) class AuditActor: kind: AuditActorKind @@ -61,7 +66,7 @@ class AuditActor: def from_request(cls, conn: HTTPConnection) -> AuditActor: """Whoever made the request, anonymous when no account is behind it.""" user = conn.scope.get("user") - ip_address = conn.client.host if conn.client else None + ip_address = client_ip(conn) device_id = getattr(conn.state, "device_id", None) or ( conn.scope.get("session") or {} ).get("device_id") @@ -232,17 +237,34 @@ def record( record_many([AuditDraft(action, actor, target, data, occurred_at)]) +def _claim_key(key: str) -> str: + # Keys carry caller-supplied text (usernames, file ids), so they're hashed to + # a fixed size. + return f"{_CLAIM_KEY_PREFIX}:{hashlib.sha256(key.encode()).hexdigest()}" + + def claim_once(key: str, window_seconds: int) -> bool: """Whether this is the first claim on `key` within the window; True if Redis fails.""" try: - return bool( - sync_cache.set(f"{_CLAIM_KEY_PREFIX}:{key}", 1, nx=True, ex=window_seconds) - ) + return bool(sync_cache.set(_claim_key(key), 1, nx=True, ex=window_seconds)) except Exception: # noqa: BLE001 - better a duplicate than a gap log.exception(f"Failed to claim audit key {key}") return True +def within_budget(key: str, limit: int, window_seconds: int) -> bool: + """Whether `key` has been counted at most `limit` times this window; True if Redis fails.""" + try: + pipe = sync_cache.pipeline() + pipe.incr(_claim_key(key)) + pipe.expire(_claim_key(key), window_seconds, nx=True) + count, _ = pipe.execute() + except Exception: # noqa: BLE001 - better a duplicate than a gap + log.exception(f"Failed to count audit key {key}") + return True + return int(count) <= limit + + def _starts_a_transfer(range_header: str | None) -> bool: """Whether a request fetches a file from its first byte, rather than resuming it.""" if range_header is None: @@ -253,7 +275,7 @@ def _starts_a_transfer(range_header: str | None) -> bool: return True # `bytes=-500` asks for the last 500 bytes, which is no start either. start = match.group(1) - return start != "" and int(start) == 0 + return start != "" and start.strip("0") == "" def record_download( diff --git a/backend/handler/database/audit_events_handler.py b/backend/handler/database/audit_events_handler.py index 62de581d3..3fee958f9 100644 --- a/backend/handler/database/audit_events_handler.py +++ b/backend/handler/database/audit_events_handler.py @@ -2,12 +2,13 @@ from collections.abc import Collection, Sequence from dataclasses import dataclass, field from datetime import datetime -from sqlalchemy import ColumnElement, delete, func, or_, select +from sqlalchemy import ColumnElement, String, cast, delete, func, or_, select from sqlalchemy.orm import Session, joinedload from decorators.database import begin_session from models.audit_event import AuditEvent from models.device import Device +from models.rom import Rom from models.user import User from utils.database import LIKE_ESCAPE_CHAR, escape_like @@ -61,8 +62,9 @@ class DBAuditEventsHandler(DBBaseHandler): limit: int, offset: int, session: Session = None, # type: ignore - ) -> tuple[list[tuple[AuditEvent, str | None]], int]: - """A page of events, newest first, each with its device's name, and the total.""" + ) -> tuple[list[tuple[AuditEvent, str | None]], int, int | None]: + """A page of events, newest first, each with its device's name, the total, + and the highest id among the matches for later pages to be pinned to.""" clauses: list[ColumnElement[bool]] = [] if filters.actor_ids is not None: clauses.append(AuditEvent.actor_id.in_(filters.actor_ids)) @@ -96,10 +98,23 @@ class DBAuditEventsHandler(DBBaseHandler): clauses.append(_not_targeting("rom", filters.hidden_rom_ids)) if filters.hidden_platform_ids: clauses.append(_not_targeting("platform", filters.hidden_platform_ids)) + # A platform's hide covers its roms too. + clauses.append( + or_( + AuditEvent.target_type.is_(None), + AuditEvent.target_type != "rom", + AuditEvent.target_id.is_(None), + AuditEvent.target_id.not_in( + select(cast(Rom.id, String)).where( + Rom.platform_id.in_(filters.hidden_platform_ids) + ) + ), + ) + ) - total = session.scalar( - select(func.count()).select_from(AuditEvent).where(*clauses) - ) + total, highest_id = session.execute( + select(func.count(), func.max(AuditEvent.id)).where(*clauses) + ).one() rows = session.execute( select(AuditEvent, Device.name) .options(_with_actor()) @@ -109,7 +124,11 @@ class DBAuditEventsHandler(DBBaseHandler): .limit(limit) .offset(offset) ).all() - return [(event, device_name) for event, device_name in rows], total or 0 + return ( + [(event, device_name) for event, device_name in rows], + total or 0, + highest_id, + ) @begin_session def delete_batch_before( diff --git a/backend/tests/endpoints/roms/test_download_audit.py b/backend/tests/endpoints/roms/test_download_audit.py index d9d0e20ac..6aa33c17a 100644 --- a/backend/tests/endpoints/roms/test_download_audit.py +++ b/backend/tests/endpoints/roms/test_download_audit.py @@ -1,11 +1,17 @@ from fastapi import status from fastapi.testclient import TestClient -from handler.database import db_audit_event_handler, db_rom_handler +from handler.database import ( + db_audit_event_handler, + db_collection_handler, + db_rom_handler, +) from handler.database.audit_events_handler import AuditEventFilters from models.audit_event import AuditEvent +from models.collection import Collection from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory +from models.user import User def _auth(token: str) -> dict[str, str]: @@ -13,7 +19,9 @@ def _auth(token: str) -> dict[str, str]: def _events() -> list[AuditEvent]: - rows, _ = db_audit_event_handler.get_events(AuditEventFilters(), limit=50, offset=0) + rows, _, _ = db_audit_event_handler.get_events( + AuditEventFilters(), limit=50, offset=0 + ) return [event for event, _ in rows] @@ -144,3 +152,31 @@ def test_a_bulk_download_is_one_event_on_its_platform( assert event.action == "rom.bulk_download" assert (event.target_type, event.target_id) == ("platform", str(platform.id)) assert event.data["count"] == 1 + + +def test_someone_elses_private_collection_is_kept_by_id_only( + client: TestClient, + access_token: str, + editor_user: User, + rom: Rom, + rom_file: RomFile, +): + private = db_collection_handler.add_collection( + Collection( + name="Secret shelf", + description="", + is_public=False, + is_favorite=False, + user_id=editor_user.id, + ) + ) + db_collection_handler.add_roms_to_collection(private.id, [rom.id]) + + client.get( + "/api/roms/download", + params={"collection_id": private.id}, + headers=_auth(access_token), + ) + + [event] = _events() + assert (event.target_id, event.target_name) == (str(private.id), None) diff --git a/backend/tests/endpoints/test_audit_events.py b/backend/tests/endpoints/test_audit_events.py index 9971c8ff2..886ef6ccc 100644 --- a/backend/tests/endpoints/test_audit_events.py +++ b/backend/tests/endpoints/test_audit_events.py @@ -189,23 +189,26 @@ class TestFilters: assert _ids(address) == [from_lan.id] def test_pages_stay_pinned_to_max_id(self, client, access_token, admin_user): - events = [_add(admin_user, minutes_ago=10 - i) for i in range(3)] + newest = _add(admin_user, minutes_ago=1) + # Recorded after `newest` but happened before it, like a synced play. + synced = _add(admin_user, AuditAction.ROM_PLAY, minutes_ago=30) first = client.get( "/api/audit-events", - params={"limit": 2}, + params={"limit": 1}, headers=_auth(access_token), ) _add(admin_user) second = client.get( "/api/audit-events", - params={"limit": 2, "offset": 2, "max_id": _ids(first)[0]}, + params={"limit": 1, "offset": 1, "max_id": first.json()["max_id"]}, headers=_auth(access_token), ) - assert first.json()["total"] == 3 - assert _ids(first) == [events[2].id, events[1].id] - assert _ids(second) == [events[0].id] + assert _ids(first) == [newest.id] + assert first.json()["max_id"] == synced.id + assert _ids(second) == [synced.id] + assert second.json()["total"] == 2 def test_an_event_outlives_its_actor(client, access_token, viewer_user): diff --git a/backend/tests/endpoints/test_library_audit.py b/backend/tests/endpoints/test_library_audit.py index bd4ff3426..82fe60d9a 100644 --- a/backend/tests/endpoints/test_library_audit.py +++ b/backend/tests/endpoints/test_library_audit.py @@ -23,7 +23,9 @@ def _auth(token: str) -> dict[str, str]: def _events() -> list[AuditEvent]: - rows, _ = db_audit_event_handler.get_events(AuditEventFilters(), limit=50, offset=0) + rows, _, _ = db_audit_event_handler.get_events( + AuditEventFilters(), limit=50, offset=0 + ) return [event for event, _ in rows] diff --git a/backend/tests/endpoints/test_play_sessions.py b/backend/tests/endpoints/test_play_sessions.py index 5fc7b9f40..5eb46a31f 100644 --- a/backend/tests/endpoints/test_play_sessions.py +++ b/backend/tests/endpoints/test_play_sessions.py @@ -236,7 +236,7 @@ class TestPlaySessionAudit: headers={"Authorization": f"Bearer {access_token}"}, ) - rows, total = db_audit_event_handler.get_events( + rows, total, _ = db_audit_event_handler.get_events( AuditEventFilters(), limit=10, offset=0 ) assert total == 1 diff --git a/backend/tests/endpoints/test_security_audit.py b/backend/tests/endpoints/test_security_audit.py index 3866a1e76..7f8e89d1d 100644 --- a/backend/tests/endpoints/test_security_audit.py +++ b/backend/tests/endpoints/test_security_audit.py @@ -6,6 +6,8 @@ import pytest from fastapi import status from fastapi.testclient import TestClient +from endpoints import auth as auth_endpoints +from handler.auth import auth_handler from handler.database import db_audit_event_handler from handler.database.audit_events_handler import AuditEventFilters from models.audit_event import AuditEvent @@ -23,7 +25,9 @@ def _basic(username: str, password: str) -> dict[str, str]: def _events() -> list[AuditEvent]: - rows, _ = db_audit_event_handler.get_events(AuditEventFilters(), limit=50, offset=0) + rows, _, _ = db_audit_event_handler.get_events( + AuditEventFilters(), limit=50, offset=0 + ) return [event for event, _ in rows] @@ -61,6 +65,26 @@ class TestLogin: assert event.actor_kind == "anonymous" assert event.data["username"] == "nobody" + def test_one_address_cycling_usernames_is_capped(self, client: TestClient, mocker): + mocker.patch.object(auth_endpoints, "LOGIN_FAILURES_PER_ADDRESS", 3) + + for i in range(6): + client.post("/api/login", headers=_basic(f"guess{i}", "wrong")) + + assert len(_events()) == 3 + + def test_repeated_reset_requests_are_one( + self, client: TestClient, admin_user: User, mocker + ): + mocker.patch.object(auth_handler, "send_password_reset_link") + + for _ in range(2): + client.post("/api/forgot-password", json={"username": "test_admin"}) + + [event] = _events() + assert event.action == "auth.password_reset_request" + assert (event.actor_kind, event.target_name) == ("anonymous", "test_admin") + def test_a_token_grant_is_a_login(self, client: TestClient, admin_user: User): response = client.post( "/api/token", diff --git a/backend/tests/handler/database/test_audit_events_handler.py b/backend/tests/handler/database/test_audit_events_handler.py index e74e195d0..d436ce6dc 100644 --- a/backend/tests/handler/database/test_audit_events_handler.py +++ b/backend/tests/handler/database/test_audit_events_handler.py @@ -4,6 +4,7 @@ from handler.database import db_audit_event_handler, db_device_handler from handler.database.audit_events_handler import AuditEventFilters from models.audit_event import AuditAction, AuditActorKind, AuditEvent from models.device import Device +from models.rom import Rom from models.user import User @@ -20,11 +21,20 @@ def _add(minutes_ago: int = 0, **overrides) -> AuditEvent: def _ids(filters: AuditEventFilters) -> list[int]: - rows, _ = db_audit_event_handler.get_events(filters, limit=50, offset=0) + rows, _, _ = db_audit_event_handler.get_events(filters, limit=50, offset=0) return [event.id for event, _ in rows] class TestHiddenTargets: + def test_drops_events_on_roms_of_a_hidden_platform(self, rom: Rom): + on_hidden = _add(target_type="rom", target_id=str(rom.id)) + elsewhere = _add(target_type="rom", target_id="999999") + + ids = _ids(AuditEventFilters(hidden_platform_ids={rom.platform_id})) + + assert on_hidden.id not in ids + assert elsewhere.id in ids + def test_drops_events_on_hidden_roms_and_platforms_only(self): hidden_rom = _add(target_type="rom", target_id="7") visible_rom = _add(target_type="rom", target_id="8") @@ -45,7 +55,7 @@ def test_joins_the_device_name(admin_user: User): _add(device_id="dev-1") _add(device_id="gone") - rows, total = db_audit_event_handler.get_events( + rows, total, _ = db_audit_event_handler.get_events( AuditEventFilters(), limit=50, offset=0 ) diff --git a/backend/tests/handler/test_audit_handler.py b/backend/tests/handler/test_audit_handler.py index 46b2d6c24..655d8413c 100644 --- a/backend/tests/handler/test_audit_handler.py +++ b/backend/tests/handler/test_audit_handler.py @@ -57,7 +57,9 @@ def _request( def _events() -> list[AuditEvent]: - rows, _ = db_audit_event_handler.get_events(AuditEventFilters(), limit=50, offset=0) + rows, _, _ = db_audit_event_handler.get_events( + AuditEventFilters(), limit=50, offset=0 + ) return [event for event, _ in rows] @@ -179,6 +181,7 @@ class TestRecordDownload: ("bytes=100-", False), ("bytes=-500", False), ("not a range", True), + ("bytes=" + "9" * 5000 + "-", False), ], ) def test_only_a_transfer_from_the_first_byte_counts( diff --git a/frontend/src/__generated__/models/AuditEventSchema.ts b/frontend/src/__generated__/models/AuditEventSchema.ts index 36eb6f4cb..f7f8ec7a1 100644 --- a/frontend/src/__generated__/models/AuditEventSchema.ts +++ b/frontend/src/__generated__/models/AuditEventSchema.ts @@ -11,7 +11,7 @@ export type AuditEventSchema = { action: (AuditAction | string); category: (AuditCategory | null); occurred_at: string; - actor_kind: AuditActorKind; + actor_kind: (AuditActorKind | string); actor: (NotificationActorSchema | null); actor_name: (string | null); target_type: (string | null); diff --git a/frontend/src/__generated__/models/AuditPage_AuditEventSchema_.ts b/frontend/src/__generated__/models/AuditPage_AuditEventSchema_.ts index 70f0cddb5..1b9cbcdaf 100644 --- a/frontend/src/__generated__/models/AuditPage_AuditEventSchema_.ts +++ b/frontend/src/__generated__/models/AuditPage_AuditEventSchema_.ts @@ -8,5 +8,6 @@ export type AuditPage_AuditEventSchema_ = { total: number; limit: number; offset: number; + max_id?: (number | null); }; diff --git a/frontend/src/v2/components/Settings/EventLog.vue b/frontend/src/v2/components/Settings/EventLog.vue index 58a6ada09..90dd60323 100644 --- a/frontend/src/v2/components/Settings/EventLog.vue +++ b/frontend/src/v2/components/Settings/EventLog.vue @@ -1,7 +1,6 @@