mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 18:42:34 +01:00
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)},
|
||||
|
||||
@@ -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"},
|
||||
)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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]
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -8,5 +8,6 @@ export type AuditPage_AuditEventSchema_ = {
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
max_id?: (number | null);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
// EventLog: what every user, and RomM itself, did, newest first, grouped by
|
||||
// day. Filters live in the URL so a view of the log can be shared. The list is
|
||||
// windowed and pulls the next page in as its end scrolls into view.
|
||||
// EventLog: what users and RomM did, grouped by day, filters in the URL. The
|
||||
// list is windowed and pulls the next page in as its end scrolls into view.
|
||||
import {
|
||||
RBtn,
|
||||
RDateField,
|
||||
@@ -12,6 +11,7 @@ import {
|
||||
RTextField,
|
||||
RVirtualScroller,
|
||||
} from "@v2/lib";
|
||||
import { isToday, isYesterday } from "date-fns";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
@@ -190,19 +190,17 @@ const phase = useLoadingPhase(
|
||||
() => rows.value.length === 0,
|
||||
);
|
||||
|
||||
function sameDay(a: Date, b: Date): boolean {
|
||||
return (
|
||||
a.getFullYear() === b.getFullYear() &&
|
||||
a.getMonth() === b.getMonth() &&
|
||||
a.getDate() === b.getDate()
|
||||
);
|
||||
}
|
||||
const timeFormat = computed(
|
||||
() =>
|
||||
new Intl.DateTimeFormat(toBrowserLocale(locale.value), {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}),
|
||||
);
|
||||
|
||||
function dayLabel(date: Date, today: Date): string {
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(today.getDate() - 1);
|
||||
if (sameDay(date, today)) return t("common.today");
|
||||
if (sameDay(date, yesterday)) return t("audit.yesterday");
|
||||
if (isToday(date)) return t("common.today");
|
||||
if (isYesterday(date)) return t("audit.yesterday");
|
||||
return new Intl.DateTimeFormat(toBrowserLocale(locale.value), {
|
||||
weekday: "long",
|
||||
day: "numeric",
|
||||
@@ -272,6 +270,8 @@ function itemKey(item: unknown): string | number {
|
||||
}
|
||||
|
||||
function onViewportRange({ last }: { first: number; last: number }) {
|
||||
// The scroller holds no items until the list is shown.
|
||||
if (phase.value !== "content") return;
|
||||
if (hasMore.value && !moreFailed.value && last >= items.value.length - 20) {
|
||||
void showMore();
|
||||
}
|
||||
@@ -404,6 +404,11 @@ useGridNav(listRoot, {
|
||||
:view="(item as EventItem).row.view"
|
||||
:first="(item as EventItem).first"
|
||||
:last="(item as EventItem).last"
|
||||
:time="
|
||||
timeFormat.format(
|
||||
new Date((item as EventItem).row.event.occurred_at),
|
||||
)
|
||||
"
|
||||
/>
|
||||
</template>
|
||||
</RVirtualScroller>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { RouterLink } from "vue-router";
|
||||
import type { AuditEventSchema } from "@/__generated__";
|
||||
import { formatTimestamp, toBrowserLocale } from "@/utils";
|
||||
import { formatTimestamp } from "@/utils";
|
||||
import type { AuditEventView } from "@/v2/utils/auditEvents";
|
||||
import { userAvatarUrl } from "@/v2/utils/userAvatar";
|
||||
|
||||
@@ -16,17 +16,12 @@ const props = defineProps<{
|
||||
/** The day's first and last events close its panel and its rail. */
|
||||
first: boolean;
|
||||
last: boolean;
|
||||
/** The time of day it happened, formatted by the list for all its rows. */
|
||||
time: string;
|
||||
}>();
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
|
||||
const time = computed(() =>
|
||||
new Intl.DateTimeFormat(toBrowserLocale(locale.value), {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}).format(new Date(props.event.occurred_at)),
|
||||
);
|
||||
|
||||
const actorName = computed(() => {
|
||||
const { actor_kind, actor, actor_name } = props.event;
|
||||
if (actor_kind === "system") return t("audit.system");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
// LogViewer — real-time backend log viewer, the Logs page's second tab.
|
||||
// LogViewer: real-time backend log viewer, the Logs page's second tab.
|
||||
//
|
||||
// On open it backfills the last N buffered lines from `GET /logs`, then
|
||||
// streams new lines live over Socket.IO (`logs:entry`, emitted to the
|
||||
|
||||
@@ -9,13 +9,14 @@ vi.mock("@/services/api/audit", () => ({
|
||||
|
||||
const getAuditEvents = vi.mocked(auditApi.getAuditEvents);
|
||||
|
||||
function page(ids: number[], total: number) {
|
||||
function page(ids: number[], total: number, maxId: number | null = null) {
|
||||
return {
|
||||
data: {
|
||||
items: ids.map((id) => ({ id }) as AuditEventSchema),
|
||||
total,
|
||||
limit: 2,
|
||||
offset: 0,
|
||||
max_id: maxId,
|
||||
},
|
||||
} as Awaited<ReturnType<typeof auditApi.getAuditEvents>>;
|
||||
}
|
||||
@@ -25,9 +26,9 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("useAuditLog", () => {
|
||||
it("pins later pages to the newest event of the first", async () => {
|
||||
it("pins later pages to the highest id the first one saw", async () => {
|
||||
getAuditEvents
|
||||
.mockResolvedValueOnce(page([9, 8], 3))
|
||||
.mockResolvedValueOnce(page([9, 8], 3, 12))
|
||||
.mockResolvedValueOnce(page([7], 3));
|
||||
const log = useAuditLog(2);
|
||||
|
||||
@@ -36,7 +37,7 @@ describe("useAuditLog", () => {
|
||||
|
||||
expect(getAuditEvents).toHaveBeenLastCalledWith({
|
||||
categories: ["consumption"],
|
||||
maxId: 9,
|
||||
maxId: 12,
|
||||
limit: 2,
|
||||
offset: 2,
|
||||
});
|
||||
@@ -44,6 +45,19 @@ describe("useAuditLog", () => {
|
||||
expect(log.hasMore.value).toBe(false);
|
||||
});
|
||||
|
||||
it("clears what the old filters matched when a reload fails", async () => {
|
||||
getAuditEvents
|
||||
.mockResolvedValueOnce(page([9, 8], 2))
|
||||
.mockRejectedValueOnce(new Error("down"));
|
||||
const log = useAuditLog(2);
|
||||
|
||||
await log.reset({});
|
||||
await expect(log.reset({ search: "new" })).rejects.toThrow("down");
|
||||
|
||||
expect(log.events.value).toEqual([]);
|
||||
expect(log.hasMore.value).toBe(false);
|
||||
});
|
||||
|
||||
it("drops a page that a newer reset overtook", async () => {
|
||||
let resolveFirst: (value: ReturnType<typeof page>) => void = () => {};
|
||||
getAuditEvents
|
||||
|
||||
@@ -36,7 +36,14 @@ export function useAuditLog(pageSize = 50) {
|
||||
if (current !== generation) return;
|
||||
events.value = data.items;
|
||||
total.value = data.total;
|
||||
maxId = data.items[0]?.id;
|
||||
maxId = data.max_id ?? undefined;
|
||||
} catch (error) {
|
||||
// What's on screen was matched by the old filters, so it can't stay.
|
||||
if (current === generation) {
|
||||
events.value = [];
|
||||
total.value = 0;
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (current === generation) loading.value = false;
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ function fields(value: unknown): string | null {
|
||||
function change(value: unknown): { from: string; to: string } | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const { from, to } = value as Record<string, unknown>;
|
||||
return { from: String(from ?? "—"), to: String(to ?? "—") };
|
||||
return { from: String(from ?? ""), to: String(to ?? "") };
|
||||
}
|
||||
|
||||
function providers(data: AuditData): string | null {
|
||||
|
||||
Reference in New Issue
Block a user