Files
romm/backend/handler/notification_handler.py
zurdi 57311dc99a fix: apply the security-audit and code-review passes
Security:
- The netplay socket server shared the main server's Redis channel while
  letting unauthenticated clients name their own rooms, so a netplay socket
  in room `user:N` or `admin` received that user's pushes and the admin log
  stream. Netplay now has a channel of its own.
- Notifying other users also requires users.write on the token, so an admin
  token scoped to me.write can only notify its owner.
- The create payload rejects NUL characters, NaN/Infinity in data and an
  empty recipients list instead of failing in the database; mark-read takes
  at most as many ids as an inbox holds.

Correctness and cleanup:
- The inbox is cleared whenever the signed-in user changes, so a failed
  fetch can't leave the previous user's notifications on screen.
- Enter no longer sends the admin form, where an unfinished title would go
  out to everyone.
- A notification without its own icon shows its level's, in the list and in
  a pushed toast alike, from one LEVEL_ICONS map.
- One write-only Redis manager per event loop instead of one per push.
- Tests for the inbox socket wiring; em-dashes and long docstrings trimmed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:47:11 +02:00

125 lines
4.1 KiB
Python

"""Persistent per-user notifications, stored first and then pushed to open tabs."""
import asyncio
from collections.abc import Sequence
from typing import Any, Literal
import socketio
from config import REDIS_URL
from endpoints.responses.notification import NotificationSchema
from handler.database import db_notification_handler, db_user_handler
from logger.logger import log
from models.notification import Notification, NotificationKind, NotificationLevel
NOTIFICATIONS_NEW_EVENT = "notifications:new"
NOTIFICATIONS_READ_EVENT = "notifications:read"
NOTIFICATIONS_DISMISSED_EVENT = "notifications:dismissed"
# A Redis client is bound to the loop that made it, and a worker runs each job in
# a new loop, so the manager is kept only while its loop is the running one.
_manager: socketio.AsyncRedisManager | None = None
_manager_loop: asyncio.AbstractEventLoop | None = None
def _write_manager() -> socketio.AsyncRedisManager:
global _manager, _manager_loop
loop = asyncio.get_running_loop()
if _manager is None or _manager_loop is not loop:
_manager = socketio.AsyncRedisManager(REDIS_URL, write_only=True)
_manager_loop = loop
return _manager
async def emit_to_user(user_id: int, event: str, payload: dict[str, Any]) -> None:
"""Push an event to every open tab of one user, from the web process or a worker."""
try:
await _write_manager().emit(event, payload, room=f"user:{user_id}")
except Exception: # noqa: BLE001
log.warning(f"Failed to push {event} to user {user_id}", exc_info=True)
async def deliver(notification: Notification) -> NotificationSchema:
"""Store a notification and push it to its user's open tabs; raises if it can't be stored."""
stored = NotificationSchema.model_validate(
db_notification_handler.add_notification(notification)
)
await emit_to_user(
notification.user_id, NOTIFICATIONS_NEW_EVENT, stored.model_dump(mode="json")
)
return stored
def recipient_ids(recipients: Sequence[int] | Literal["admins", "all"]) -> list[int]:
"""The enabled users among the given ids, or among every admin or user."""
if recipients == "admins":
users = list(db_user_handler.get_admin_users())
elif recipients == "all":
users = list(db_user_handler.get_users())
else:
users = [
user
for user_id in dict.fromkeys(recipients)
if (user := db_user_handler.get_user(user_id))
]
return [user.id for user in users if user.enabled]
async def notify(
user_id: int,
kind: NotificationKind | str,
level: NotificationLevel,
data: dict[str, Any] | None = None,
actor_id: int | None = None,
*,
title: str | None = None,
body: str | None = None,
link: str | None = None,
icon: str | None = None,
) -> None:
"""Notify one user, logging rather than raising a failure to store it.
Args:
kind: A `NotificationKind` is translated from `data`; any other shows
`title`, `body`, `link` (an in-app path) and `icon`.
"""
try:
await deliver(
Notification(
user_id=user_id,
actor_id=actor_id,
kind=kind,
level=level,
title=title,
body=body,
link=link,
icon=icon,
data=data or {},
)
)
except Exception: # noqa: BLE001
log.exception(f"Failed to store {kind} notification for user {user_id}")
async def notify_admins(
kind: NotificationKind | str,
level: NotificationLevel,
data: dict[str, Any] | None = None,
*,
title: str | None = None,
body: str | None = None,
link: str | None = None,
icon: str | None = None,
) -> None:
"""Notify every enabled admin of what the system did on nobody's behalf."""
try:
admin_ids = recipient_ids("admins")
except Exception: # noqa: BLE001
log.exception(f"Failed to look up the admins to notify of {kind}")
return
for admin_id in admin_ids:
await notify(
admin_id, kind, level, data, title=title, body=body, link=link, icon=icon
)