From 4a868b599f3f147e779db37c9a2bf05cb4fda24f Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 10:46:23 +0100 Subject: [PATCH 01/45] feat(image): activity log receiver over UDP, squid.conf lines while it is on squid sends one lmnactivity line per request (epoch second, user, domain, status, size, filter category; no URL, no client address) to a receiver in the container that writes finished files into the instance's spool. UDP and not squid's daemon: module, because squid ends itself when its log daemon dies (measured with squid 6.14, also with on-error=drop). --- image/Dockerfile | 5 +- image/entrypoint.sh | 33 ++++- image/lmn-activity-logd | 182 ++++++++++++++++++++++++++++ image/templates/squid.conf.template | 4 + 4 files changed, 221 insertions(+), 3 deletions(-) create mode 100755 image/lmn-activity-logd diff --git a/image/Dockerfile b/image/Dockerfile index 24d797d..ef08a12 100644 --- a/image/Dockerfile +++ b/image/Dockerfile @@ -61,8 +61,11 @@ LABEL org.faircomp.linuxmuster-squid.filter="2" COPY lmn-filter-acl /usr/local/bin/lmn-filter-acl COPY lmn_filterdecision.py /usr/local/bin/lmn_filterdecision.py COPY errors/ERR_LMN_BLOCKED /usr/share/squid/errors/templates/ERR_LMN_BLOCKED +# Activity log (ADR-023): squid's logfile daemon writing finished files into the instance's spool. +LABEL org.faircomp.linuxmuster-squid.activity="1" +COPY lmn-activity-logd /usr/local/bin/lmn-activity-logd RUN chmod 0755 /usr/local/bin/entrypoint.sh /usr/local/bin/healthcheck.sh /usr/local/bin/sni-sent.sh \ - /usr/local/bin/lists-sync.sh /usr/local/bin/lmn-filter-acl \ + /usr/local/bin/lists-sync.sh /usr/local/bin/lmn-filter-acl /usr/local/bin/lmn-activity-logd \ && chmod 0644 /usr/local/bin/lmn_filterdecision.py \ && /usr/bin/python3 -I -c 'import sqlite3, zoneinfo; zoneinfo.ZoneInfo("Europe/Berlin")' diff --git a/image/entrypoint.sh b/image/entrypoint.sh index 56905f3..30be231 100644 --- a/image/entrypoint.sh +++ b/image/entrypoint.sh @@ -23,6 +23,7 @@ set -eu : "${ACCESS_LOG_ENABLED:=1}" # 1=access log on, 0=off (data privacy) : "${INTERNET_GROUP:=}" # optional 2nd gate: linuxmuster Internetsperre (empty=off) : "${KRB5_CLOCKSKEW_SECONDS:=300}" # Kerberos clock skew accepted (krb5.conf clockskew) +: "${ACTIVITY_LOG_ENABLED:=0}" # 1=activity log into the mounted spool (ADR-023) # Validated here because libkrb5 would not complain: a value it cannot parse silently becomes # its default 300. Plain decimal only (no sign, no leading zero), 300..7200 (ADR-017). @@ -44,6 +45,21 @@ else ACCESS_LOG_DIRECTIVE="access_log stdio:/var/log/squid/access.log squid" fi +# Activity log (ADR-023): one line per request with the epoch second, the user, the requested +# domain, the status codes, the reply size and the filter category; never the URL or the client +# address. squid sends each line as a UDP datagram to the receiver lmn-activity-logd (started +# below, as proxy), which writes finished files into the spool the control plane mounts at +# ACTIVITY_DIR while the log is on. UDP and not squid's daemon: module, because squid ends +# itself when its log daemon dies; a lost receiver must never stop the proxy. +ACTIVITY_DIR=/var/log/lmnsquid-activity +ACTIVITY_ADDR=127.0.0.1:3130 +if [ "${ACTIVITY_LOG_ENABLED}" = "1" ]; then + ACTIVITY_LOG_DIRECTIVE="logformat lmnactivity %ts %un %>rd %>Hs %Ss % FATAL). export INSTANCE HTTP_PORT CACHE_SIZE_MB KEYTAB REALM AD_GROUP VISIBLE_HOSTNAME SCHOOL_SUBNETS -export ACCESS_LOG_DIRECTIVE INTERNET_ACL_DEF INTERNET_ACL_REF +export ACCESS_LOG_DIRECTIVE INTERNET_ACL_DEF INTERNET_ACL_REF ACTIVITY_LOG_DIRECTIVE # krb5.conf: rdns/canonicalize=false so that the ldap/ SPN is built from the literal DC name # (via SRV) and NOT via reverse DNS (-> SASL "Local error"). @@ -128,7 +144,7 @@ TEMPLATE=/etc/squid/templates/squid.conf.template CONF="${RUN}/squid.conf" # Only substitute OUR variables so Squid's own %-tokens survive untouched. -envsubst '${INSTANCE} ${HTTP_PORT} ${CACHE_SIZE_MB} ${KEYTAB} ${REALM} ${AD_GROUP} ${VISIBLE_HOSTNAME} ${SCHOOL_SUBNETS} ${ACCESS_LOG_DIRECTIVE} ${INTERNET_ACL_DEF} ${INTERNET_ACL_REF}' \ +envsubst '${INSTANCE} ${HTTP_PORT} ${CACHE_SIZE_MB} ${KEYTAB} ${REALM} ${AD_GROUP} ${VISIBLE_HOSTNAME} ${SCHOOL_SUBNETS} ${ACCESS_LOG_DIRECTIVE} ${INTERNET_ACL_DEF} ${INTERNET_ACL_REF} ${ACTIVITY_LOG_DIRECTIVE}' \ < "${TEMPLATE}" > "${CONF}" # The lists squid reads (/run/lmnsquid/lists/) from the mounted ones: without the entries @@ -151,6 +167,19 @@ if [ "${ACCESS_LOG_ENABLED}" != "0" ]; then stdbuf -oL tail -F /var/log/squid/access.log 2>/dev/null & fi +# Activity log receiver (ADR-023) as proxy, restarted when it ends (it ends only when killed). +if [ "${ACTIVITY_LOG_ENABLED}" = "1" ]; then + if [ -d "${ACTIVITY_DIR}" ]; then + ( while true; do + setpriv --reuid=proxy --regid=proxy --init-groups \ + /usr/local/bin/lmn-activity-logd "${ACTIVITY_ADDR}" "${ACTIVITY_DIR}" || true + sleep 1 + done ) & + else + echo "linuxmuster-squid: activity log on, but ${ACTIVITY_DIR} is not mounted; nothing is logged" >&2 + fi +fi + # logrotate: cache.log ALWAYS (it grows regardless of the access-log toggle -> would fill # the volume in privacy mode otherwise), access.log only when enabled. State on the # PERSISTENT volume so "daily" is correct across restarts. copytruncate: no squid signal diff --git a/image/lmn-activity-logd b/image/lmn-activity-logd new file mode 100755 index 0000000..db8d765 --- /dev/null +++ b/image/lmn-activity-logd @@ -0,0 +1,182 @@ +#!/usr/bin/python3 -I +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Receiver of the activity log (ADR-023): squid's UDP log lines into finished spool files. + +squid.conf: ``access_log udp://127.0.0.1:3130 logformat=lmnactivity buffer-size=0KB``: squid +sends every line at once as its own datagram and ignores send errors, so a receiver that is not +running loses lines but never stops squid (squid's ``daemon:`` module ends squid when its daemon +dies, measured with squid 6.14; ``on-error=drop`` does not change that). The entrypoint starts +this receiver as ``proxy`` in a restart loop: ``lmn-activity-logd ``. + +The lines go to ``.part---`` in the directory (the host's spool of this +instance); at the latest every ``ROLL_SECONDS`` (and at ``ROLL_BYTES`` and on SIGTERM) a part with +content is renamed to ``act---.log``: a finished file, which the control +plane's collector reads, sums into its day files and deletes. A file is never written after its +rename, so the collector needs no offsets and never reads half a file twice. + +A write error (full disk, removed directory) drops the line and is reported on stderr at most +once a minute. Lines are also dropped while the finished files this receiver wrote and the +collector has not taken yet exceed ``PENDING_MAX`` bytes (a stopped collector must not fill the +disk). +""" + +from __future__ import annotations + +import errno +import os +import secrets +import select +import signal +import socket +import sys +import time + +ROLL_SECONDS = float(os.environ.get("LMN_ACTIVITY_ROLL_SECONDS", "30")) +ROLL_BYTES = 16 * 1024 * 1024 +PENDING_MAX = int(os.environ.get("LMN_ACTIVITY_PENDING_MAX", str(1024 * 1024 * 1024))) +WAKE_SECONDS = min(5.0, ROLL_SECONDS) +RECV_SIZE = 65535 +RECV_BUFFER = 4 * 1024 * 1024 # the kernel caps it at net.core.rmem_max + + +def log(message: str) -> None: + try: + sys.stderr.write(f"lmn-activity-logd: {message}\n") + sys.stderr.flush() + except OSError: + pass + + +class Spool: + def __init__(self, directory: str) -> None: + self.directory = directory + self.token = secrets.token_hex(4) + self.seq = 0 + self.fd = -1 + self.part = "" + self.started = 0.0 + self.size = 0 + self.pending: list[tuple[str, int]] = [] + self.dropped = 0 + self.reported = 0.0 + + def _open(self, now: float) -> bool: + self.seq += 1 + name = f".part-{int(now):010d}-{self.token}-{self.seq:06d}" + path = os.path.join(self.directory, name) + try: + # 0640: the directory's set-group-id bit gives the file the control plane's group. + self.fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_APPEND, 0o640) + except OSError as exc: + self._problem(f"cannot create a file in {self.directory}: {exc.strerror}") + return False + self.part = path + self.started = now + self.size = 0 + return True + + def _problem(self, text: str) -> None: + now = time.monotonic() + if now - self.reported >= 60: + self.reported = now + suffix = f" ({self.dropped} line(s) dropped so far)" if self.dropped else "" + log(text + suffix) + + def _pending_bytes(self) -> int: + alive: list[tuple[str, int]] = [] + for path, size in self.pending: + if os.path.exists(path): + alive.append((path, size)) + self.pending = alive + return sum(size for _path, size in alive) + + def write(self, data: bytes) -> None: + now = time.time() + if self.fd < 0: + if self._pending_bytes() > PENDING_MAX: + self.dropped += 1 + self._problem(f"{PENDING_MAX} bytes wait for the collector, lines are dropped") + return + if not self._open(now): + self.dropped += 1 + return + try: + os.write(self.fd, data) + except OSError as exc: + self.dropped += 1 + reason = "disk full" if exc.errno == errno.ENOSPC else exc.strerror + self._problem(f"cannot write {self.part}: {reason}") + return + self.size += len(data) + if self.size >= ROLL_BYTES: + self.roll() + + def roll(self) -> None: + """Finish the current part (renamed for the collector); an empty one is removed.""" + if self.fd < 0: + return + try: + os.close(self.fd) + except OSError: + pass + self.fd = -1 + if self.size == 0: + try: + os.unlink(self.part) + except OSError: + pass + return + name = os.path.basename(self.part)[len(".part-") :] + done = os.path.join(self.directory, f"act-{name}.log") + try: + os.rename(self.part, done) + except OSError as exc: + # The collector takes a part nobody wrote to for a few minutes as well. + self._problem(f"cannot finish {self.part}: {exc.strerror}") + return + self.pending.append((done, self.size)) + + def tick(self) -> None: + if self.fd >= 0 and self.size > 0 and time.time() - self.started >= ROLL_SECONDS: + self.roll() + + +class Stop(Exception): + pass + + +def _stop(_signum: int, _frame: object) -> None: + raise Stop + + +def main(argv: list[str]) -> int: + if len(argv) < 3 or ":" not in argv[1]: + log("usage: lmn-activity-logd ") + return 1 + host, _, port = argv[1].rpartition(":") + os.umask(0o027) + spool = Spool(argv[2]) + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, RECV_BUFFER) + sock.bind((host, int(port))) + signal.signal(signal.SIGTERM, _stop) + signal.signal(signal.SIGINT, _stop) + try: + while True: + ready, _w, _x = select.select([sock], [], [], WAKE_SECONDS) + if ready: + data = sock.recv(RECV_SIZE) + for line in data.split(b"\n"): + if line.strip(): + spool.write(line + b"\n") + spool.tick() + except Stop: + pass + finally: + spool.roll() + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/image/templates/squid.conf.template b/image/templates/squid.conf.template index 905fb2b..f51f976 100644 --- a/image/templates/squid.conf.template +++ b/image/templates/squid.conf.template @@ -137,6 +137,10 @@ cache_dir ufs /var/spool/squid ${CACHE_SIZE_MB} 16 256 # user, no address. Before the access log line: "access_log none" there would end the logging. logformat lmnfilter %{%Y-%m-%d}tl %{category}note access_log stdio:/var/log/squid/filter.log lmnfilter filter_categorised +# Activity log (ADR-023, per instance, off by default; rendered by the entrypoint, empty when +# off): user, domain and minute only, no URL, no client address, through lmn-activity-logd into +# the host's spool of this instance (/var/log/lmnsquid-activity), summed there per minute. +${ACTIVITY_LOG_DIRECTIVE} ${ACCESS_LOG_DIRECTIVE} cache_log /var/log/squid/cache.log From 7650efd42eff7d204e8eaa14b4dc273d844741b6 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 10:51:21 +0100 Subject: [PATCH 02/45] feat(controlplane): activity log collector, day files, retention, spool mount lmnsquid-activity collect reads the finished spool files of every instance with the log on, sums them per user, domain and minute into one SQLite file per local day (tables per minute, per hour, per day and domain) and deletes them. The file name is stored in the same transaction, so a run that stops anywhere neither loses nor double-counts. Whole day files expire with the retention (1-365 days, default 7). The container gets the spool and ACTIVITY_LOG_ENABLED only while the log is on: other instances keep their spec, an upgrade replaces nothing. Queries with hard limits and a time budget; an audit log module. --- controlplane/lmnsquid/activity.py | 636 ++++++++++++++++++++++++ controlplane/lmnsquid/activity_audit.py | 124 +++++ controlplane/lmnsquid/activity_query.py | 547 ++++++++++++++++++++ controlplane/lmnsquid/config.py | 13 + controlplane/lmnsquid/docker_service.py | 41 +- controlplane/lmnsquid/main.py | 1 + controlplane/lmnsquid/models.py | 38 +- controlplane/pyproject.toml | 1 + controlplane/tests/conftest.py | 3 + controlplane/tests/test_activity.py | 474 ++++++++++++++++++ 10 files changed, 1864 insertions(+), 14 deletions(-) create mode 100644 controlplane/lmnsquid/activity.py create mode 100644 controlplane/lmnsquid/activity_audit.py create mode 100644 controlplane/lmnsquid/activity_query.py create mode 100644 controlplane/tests/test_activity.py diff --git a/controlplane/lmnsquid/activity.py b/controlplane/lmnsquid/activity.py new file mode 100644 index 0000000..8cd359b --- /dev/null +++ b/controlplane/lmnsquid/activity.py @@ -0,0 +1,636 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Activity log (ADR-023): collect the spool of every instance into one SQLite file per day. + +The data-plane image writes finished files ``act-*.log`` into the host's spool of the instance +(``//``, mounted while the log is on). ``lmnsquid-activity collect`` +(a systemd timer, every 30 s, as ``lmnsquid``) reads each finished file, sums its lines per +user, domain and minute, and adds them to ``//.sqlite`` (local +day of ``filter_timezone``). The file's name goes into the same transaction (table +``ingested``), so a run that stops anywhere neither loses nor counts a file twice: a file +already recorded for a day is skipped for that day and deleted. Memory is bounded by one spool +file (the daemon finishes a file at the latest every 16 MiB). + +Retention: whole day files are deleted once they are ``retention_days`` days old (the day of +today counts as the first), never rows in a big table. +""" + +from __future__ import annotations + +import argparse +import datetime +import errno +import fcntl +import logging +import os +import shutil +import sqlite3 +import stat +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Iterable, Iterator +from urllib.parse import unquote +from zoneinfo import ZoneInfo + +from .models import Instance + +logger = logging.getLogger("lmnsquid.activity") + +FORMAT = "1" +SPOOL_CONTAINER_DIR = "/var/log/lmnsquid-activity" +ACTIVITY_LABEL = "org.faircomp.linuxmuster-squid.activity" +# A part file nobody wrote to for this long belongs to a daemon that ended without finishing it. +STALE_PART_SECONDS = 300 +# Lines with a time this far in the future are dropped (a wrong clock must not create files). +FUTURE_SLACK_SECONDS = 86400 +MAX_HOST = 253 +MAX_USER = 64 +SPOOL_MODE = 0o3733 # owner rwx; others may create (squid's proxy user), not list; sticky+setgid +DAY_SUFFIX = ".sqlite" + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS meta(k TEXT PRIMARY KEY, v TEXT) WITHOUT ROWID; +CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE); +CREATE TABLE IF NOT EXISTS hosts(id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE); +-- one row per user, minute (epoch minute) and domain: requests, bytes, blocked, category +CREATE TABLE IF NOT EXISTS act( + u INTEGER NOT NULL, m INTEGER NOT NULL, h INTEGER NOT NULL, + n INTEGER NOT NULL, b INTEGER NOT NULL, x INTEGER NOT NULL, c TEXT, + PRIMARY KEY(u, m, h)) WITHOUT ROWID; +-- per user and hour (epoch hour): the overview and the heat map +CREATE TABLE IF NOT EXISTS uh( + u INTEGER NOT NULL, hr INTEGER NOT NULL, + n INTEGER NOT NULL, b INTEGER NOT NULL, x INTEGER NOT NULL, last INTEGER NOT NULL, + PRIMARY KEY(u, hr)) WITHOUT ROWID; +-- per user and domain for the whole day: top domains and "who was on X" (index on h) +CREATE TABLE IF NOT EXISTS uhd( + u INTEGER NOT NULL, h INTEGER NOT NULL, + n INTEGER NOT NULL, b INTEGER NOT NULL, x INTEGER NOT NULL, c TEXT, + first INTEGER NOT NULL, last INTEGER NOT NULL, + PRIMARY KEY(u, h)) WITHOUT ROWID; +CREATE INDEX IF NOT EXISTS uhd_h ON uhd(h); +CREATE TABLE IF NOT EXISTS ingested(f TEXT PRIMARY KEY, at INTEGER NOT NULL) WITHOUT ROWID; +""" + + +class ActivityError(Exception): + """A request the activity log cannot serve (bad input, limit), with a readable reason.""" + + +# -- paths ------------------------------------------------------------------------------------ + + +def _safe(name: str) -> str: + if not name or "/" in name or "\\" in name or name.startswith(".") or ".." in name: + raise ValueError(f"unsafe instance name: {name!r}") + return name + + +def data_dir(root: str, name: str) -> Path: + return Path(root) / _safe(name) + + +def spool_dir(root: str, name: str) -> Path: + return Path(root) / _safe(name) + + +def ensure_spool(root: str, name: str) -> Path: + """The instance's spool (created before Docker mounts it, else Docker makes a root dir). + + Mode 3733: squid's ``proxy`` user in the container may create files there but cannot list + the directory; the set-group-id bit gives its files the control plane's group, which reads + them (0640); the sticky bit keeps one writer from removing another's files, the owner (the + control plane) removes them after collecting. + """ + base = Path(root) + base.mkdir(mode=0o750, parents=True, exist_ok=True) + path = spool_dir(root, name) + try: + path.mkdir(mode=0o700) + except FileExistsError: + pass + if stat.S_IMODE(path.stat().st_mode) != SPOOL_MODE: + os.chmod(path, SPOOL_MODE) + return path + + +def day_name(day: datetime.date) -> str: + return f"{day.isoformat()}{DAY_SUFFIX}" + + +def parse_day_name(name: str) -> datetime.date | None: + if not name.endswith(DAY_SUFFIX) or len(name) != 10 + len(DAY_SUFFIX): + return None + try: + return datetime.date.fromisoformat(name[:10]) + except ValueError: + return None + + +def day_files(directory: Path) -> list[tuple[datetime.date, Path]]: + """The day files of one instance, oldest first.""" + found: list[tuple[datetime.date, Path]] = [] + try: + entries = list(os.scandir(directory)) + except FileNotFoundError: + return [] + for entry in entries: + day = parse_day_name(entry.name) + if day is not None and entry.is_file(follow_symlinks=False): + found.append((day, Path(entry.path))) + found.sort() + return found + + +def oldest_kept(today: datetime.date, retention_days: int) -> datetime.date: + """The first day still kept: ``retention_days`` = 1 keeps today only.""" + return today - datetime.timedelta(days=retention_days - 1) + + +def today_in(zone: ZoneInfo, now: float | None = None) -> datetime.date: + return datetime.datetime.fromtimestamp(time.time() if now is None else now, zone).date() + + +def remove_day_file(path: Path) -> None: + for suffix in ("", "-wal", "-shm", "-journal"): + try: + os.unlink(f"{path}{suffix}") + except FileNotFoundError: + pass + + +def apply_retention( + root: str, name: str, retention_days: int, zone: ZoneInfo, now: float | None = None +) -> list[str]: + """Delete the day files of ``name`` older than its retention; their names.""" + keep_from = oldest_kept(today_in(zone, now), retention_days) + removed: list[str] = [] + for day, path in day_files(data_dir(root, name)): + if day < keep_from: + remove_day_file(path) + removed.append(path.name) + return removed + + +def purge_instance(data_root: str, spool_root: str, name: str) -> None: + """Delete everything the activity log holds of ``name``: day files and spool.""" + shutil.rmtree(data_dir(data_root, name), ignore_errors=True) + shutil.rmtree(spool_dir(spool_root, name), ignore_errors=True) + + +def delete_data(data_root: str, spool_root: str, name: str) -> int: + """Delete the day files and the spool's content of ``name`` (the spool directory stays, a + running container may still have it mounted); the number of day files removed.""" + files = day_files(data_dir(data_root, name)) + for _day, path in files: + remove_day_file(path) + spool = spool_dir(spool_root, name) + try: + for entry in os.scandir(spool): + if entry.is_file(follow_symlinks=False): + try: + os.unlink(entry.path) + except OSError: + pass + except FileNotFoundError: + pass + return len(files) + + +def usage(data_root: str, spool_root: str, name: str) -> dict[str, object]: + """Days, bytes, oldest and newest day held for ``name``; files waiting in its spool.""" + files = day_files(data_dir(data_root, name)) + total = 0 + for _day, path in files: + for suffix in ("", "-wal"): + try: + total += os.stat(f"{path}{suffix}").st_size + except FileNotFoundError: + pass + waiting = 0 + waiting_bytes = 0 + try: + for entry in os.scandir(spool_dir(spool_root, name)): + if entry.name.startswith(("act-", ".part-")): + waiting += 1 + waiting_bytes += entry.stat(follow_symlinks=False).st_size + except (FileNotFoundError, PermissionError): + pass + return { + "days": len(files), + "bytes": total, + "oldest": files[0][0].isoformat() if files else None, + "newest": files[-1][0].isoformat() if files else None, + "spool_files": waiting, + "spool_bytes": waiting_bytes, + } + + +# -- parsing ---------------------------------------------------------------------------------- + + +@dataclass +class Counters: + files: int = 0 + lines: int = 0 + used: int = 0 + anonymous: int = 0 + broken: int = 0 + dropped_old: int = 0 + rows: int = 0 + days: set[str] = field(default_factory=set) + + +def parse_line(line: bytes) -> tuple[int, str, str, int, int, str | None] | None: + """``(epoch second, user, host, bytes, blocked, category)`` of one log line. + + Format ``lmnactivity``: ``%ts %un %>rd %>Hs %Ss % MAX_USER or any(ch.isspace() for ch in user): + raise ValueError("bad user") + host = parts[2].decode("ascii", "strict").strip().lower().rstrip(".") + if host.startswith("[") and host.endswith("]"): + host = host[1:-1] + if not host or host == "-" or len(host) > MAX_HOST: + raise ValueError("bad host") + status = parts[3] + squid_status = parts[4] + size = int(parts[5]) if parts[5] != b"-" else 0 + category: str | None = None + if len(parts) == 7: + raw = parts[6].strip() + if raw and raw != b"-": + category = raw.decode("ascii", "replace").split(",", 1)[0][:64] + blocked = int( + category is not None or status == b"403" or squid_status.startswith(b"TCP_DENIED") + ) + return ts, user, host, max(size, 0), blocked, category + + +class DayMapper: + """Epoch minute -> local day (cached per minute; the zone's offsets are whole minutes).""" + + def __init__(self, zone: ZoneInfo) -> None: + self.zone = zone + self._cache: dict[int, datetime.date] = {} + + def day(self, minute: int) -> datetime.date: + found = self._cache.get(minute) + if found is None: + found = datetime.datetime.fromtimestamp(minute * 60, self.zone).date() + if len(self._cache) > 100_000: + self._cache.clear() + self._cache[minute] = found + return found + + +Key = tuple[str, int, str] # user, minute, host +Agg = dict[datetime.date, dict[Key, list]] + + +def aggregate( + lines: Iterable[bytes], + days: DayMapper, + counters: Counters, + keep_from: datetime.date | None, + now: float, +) -> Agg: + """Sum the lines of one spool file per local day, user, minute and domain.""" + out: Agg = {} + for line in lines: + counters.lines += 1 + try: + parsed = parse_line(line) + except (ValueError, UnicodeDecodeError): + counters.broken += 1 + continue + if parsed is None: + counters.anonymous += 1 + continue + ts, user, host, size, blocked, category = parsed + if ts > now + FUTURE_SLACK_SECONDS or ts <= 0: + counters.broken += 1 + continue + minute = ts // 60 + day = days.day(minute) + if keep_from is not None and day < keep_from: + counters.dropped_old += 1 + continue + counters.used += 1 + bucket = out.setdefault(day, {}) + key = (user, minute, host) + row = bucket.get(key) + if row is None: + bucket[key] = [1, size, blocked, category] + else: + row[0] += 1 + row[1] += size + row[2] += blocked + if category is not None: + row[3] = category + return out + + +def complete_lines(data: bytes, counters: Counters) -> list[bytes]: + """The lines of a spool file; a last line without newline is a write cut short (broken).""" + lines = data.split(b"\n") + tail = lines.pop() + if tail.strip(): + counters.broken += 1 + return [line for line in lines if line.strip()] + + +# -- the day file ----------------------------------------------------------------------------- + + +def connect_day(path: Path, create: bool) -> sqlite3.Connection: + if create: + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + db = sqlite3.connect(str(path), timeout=30, isolation_level=None) + os.chmod(path, 0o600) + db.execute("PRAGMA journal_mode=WAL") + db.execute("PRAGMA synchronous=NORMAL") + db.executescript(SCHEMA) + db.execute("INSERT OR IGNORE INTO meta(k, v) VALUES ('format', ?)", (FORMAT,)) + db.execute("INSERT OR IGNORE INTO meta(k, v) VALUES ('day', ?)", (path.name[:10],)) + return db + db = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=30, isolation_level=None) + db.execute("PRAGMA query_only=1") + return db + + +def _ids(db: sqlite3.Connection, table: str, names: Iterable[str]) -> dict[str, int]: + wanted = sorted(set(names)) + ids: dict[str, int] = {} + for i in range(0, len(wanted), 500): + chunk = wanted[i : i + 500] + db.executemany(f"INSERT OR IGNORE INTO {table}(name) VALUES (?)", [(n,) for n in chunk]) + marks = ",".join("?" * len(chunk)) + for row_id, name in db.execute( + f"SELECT id, name FROM {table} WHERE name IN ({marks})", chunk + ): + ids[str(name)] = int(row_id) + return ids + + +def store_day(db: sqlite3.Connection, source: str, rows: dict[Key, list]) -> bool: + """Add one spool file's rows of one day in one transaction; ``False`` if it was already in.""" + db.execute("BEGIN IMMEDIATE") + try: + if db.execute("SELECT 1 FROM ingested WHERE f = ?", (source,)).fetchone(): + db.execute("ROLLBACK") + return False + users = _ids(db, "users", (k[0] for k in rows)) + hosts = _ids(db, "hosts", (k[2] for k in rows)) + act = [] + hourly: dict[tuple[int, int], list[int]] = {} + daily: dict[tuple[int, int], list] = {} + for (user, minute, host), (n, b, x, c) in rows.items(): + u = users[user] + h = hosts[host] + act.append((u, minute, h, n, b, x, c)) + hk = (u, minute // 60) + hr = hourly.get(hk) + if hr is None: + hourly[hk] = [n, b, x, minute] + else: + hr[0] += n + hr[1] += b + hr[2] += x + hr[3] = max(hr[3], minute) + dk = (u, h) + dr = daily.get(dk) + if dr is None: + daily[dk] = [n, b, x, c, minute, minute] + else: + dr[0] += n + dr[1] += b + dr[2] += x + if c is not None: + dr[3] = c + dr[4] = min(dr[4], minute) + dr[5] = max(dr[5], minute) + act.sort() + db.executemany( + "INSERT INTO act(u, m, h, n, b, x, c) VALUES (?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT(u, m, h) DO UPDATE SET n = n + excluded.n, b = b + excluded.b, " + "x = x + excluded.x, c = coalesce(excluded.c, c)", + act, + ) + db.executemany( + "INSERT INTO uh(u, hr, n, b, x, last) VALUES (?, ?, ?, ?, ?, ?) " + "ON CONFLICT(u, hr) DO UPDATE SET n = n + excluded.n, b = b + excluded.b, " + "x = x + excluded.x, last = max(last, excluded.last)", + [(u, hr, *v) for (u, hr), v in sorted(hourly.items())], + ) + db.executemany( + "INSERT INTO uhd(u, h, n, b, x, c, first, last) VALUES (?, ?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT(u, h) DO UPDATE SET n = n + excluded.n, b = b + excluded.b, " + "x = x + excluded.x, c = coalesce(excluded.c, c), " + "first = min(first, excluded.first), last = max(last, excluded.last)", + [(u, h, *v) for (u, h), v in sorted(daily.items())], + ) + db.execute("INSERT INTO ingested(f, at) VALUES (?, ?)", (source, int(time.time()))) + db.execute("COMMIT") + except BaseException: + db.execute("ROLLBACK") + raise + return True + + +# -- collecting ------------------------------------------------------------------------------- + + +def spool_files(directory: Path, now: float) -> list[Path]: + """Finished files, oldest first, and parts a daemon left behind (no write for 5 minutes).""" + found: list[Path] = [] + try: + entries = list(os.scandir(directory)) + except FileNotFoundError: + return [] + for entry in entries: + if not entry.is_file(follow_symlinks=False): + continue + if entry.name.startswith("act-") and entry.name.endswith(".log"): + found.append(Path(entry.path)) + elif entry.name.startswith(".part-"): + st = entry.stat(follow_symlinks=False) + if now - st.st_mtime >= STALE_PART_SECONDS: + if st.st_size == 0: + _unlink(Path(entry.path)) + else: + found.append(Path(entry.path)) + # act---.log and .part--... sort by their epoch + found.sort(key=lambda p: p.name.split("-", 1)[1]) + return found + + +def _unlink(path: Path) -> None: + try: + path.unlink() + except FileNotFoundError: + pass + + +def _source_name(path: Path) -> str: + """The ledger name of a spool file: the same for a part and its finished file.""" + name = path.name + if name.startswith(".part-"): + name = "act-" + name[len(".part-") :] + ".log" + return name + + +def collect_instance( + inst: Instance, + data_root: str, + spool_root: str, + zone: ZoneInfo, + now: float | None = None, + counters: Counters | None = None, +) -> Counters: + """Collect the spool of ``inst`` into its day files and apply its retention.""" + counters = counters or Counters() + now = time.time() if now is None else now + days = DayMapper(zone) + keep_from = oldest_kept(today_in(zone, now), inst.activity_retention_days) + target = data_dir(data_root, inst.name) + for path in spool_files(spool_dir(spool_root, inst.name), now): + try: + data = path.read_bytes() + except FileNotFoundError: + continue + counters.files += 1 + grouped = aggregate(complete_lines(data, counters), days, counters, keep_from, now) + source = _source_name(path) + for day, rows in sorted(grouped.items()): + db = connect_day(target / day_name(day), create=True) + try: + if store_day(db, source, rows): + counters.rows += len(rows) + counters.days.add(day.isoformat()) + finally: + db.close() + _unlink(path) + apply_retention(data_root, inst.name, inst.activity_retention_days, zone, now) + return counters + + +@dataclass +class Paths: + data_root: str + spool_root: str + zone: ZoneInfo + + +def collect_all( + instances: list[Instance], paths: Paths, now: float | None = None +) -> dict[str, Counters]: + """One run over every instance that has the log on or still has spool files or data.""" + results: dict[str, Counters] = {} + for inst in instances: + has_spool = spool_dir(paths.spool_root, inst.name).is_dir() + has_data = data_dir(paths.data_root, inst.name).is_dir() + if not (inst.activity_log_enabled or has_spool or has_data): + continue + try: + results[inst.name] = collect_instance( + inst, paths.data_root, paths.spool_root, paths.zone, now + ) + except (OSError, sqlite3.Error) as exc: + logger.error("activity: collecting %s failed: %s", inst.name, exc) + return results + + +@dataclass +class Lock: + path: Path + fd: int = -1 + + def acquire(self) -> bool: + self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT, 0o600) + try: + fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as exc: + os.close(self.fd) + self.fd = -1 + if exc.errno in (errno.EAGAIN, errno.EACCES): + return False + raise + return True + + def release(self) -> None: + if self.fd >= 0: + os.close(self.fd) + self.fd = -1 + + +def iter_instances(instances_dir: str) -> Iterator[Instance]: + from .store import Store + + yield from Store(instances_dir).list() + + +def main(argv: list[str] | None = None) -> int: + """``lmnsquid-activity collect``: one collector run (the systemd timer calls it).""" + from .config import load_settings + + parser = argparse.ArgumentParser(prog="lmnsquid-activity") + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("collect", help="collect the spools into the day files, apply the retention") + args = parser.parse_args(argv) + logging.basicConfig(level=logging.INFO, format="%(message)s") + settings = load_settings() + if args.command == "collect": + paths = Paths( + settings.activity_dir, settings.activity_spool_dir, ZoneInfo(settings.filter_timezone) + ) + lock = Lock(Path(settings.activity_dir) / ".collect.lock") + if not lock.acquire(): + logger.info("activity: another collector run is still working") + return 0 + try: + started = time.monotonic() + results = collect_all(list(iter_instances(settings.instances_dir)), paths) + from . import activity_audit + + activity_audit.apply_retention( + activity_audit.audit_dir(settings.activity_dir), + settings.activity_audit_retention_days, + paths.zone, + ) + finally: + lock.release() + for name, c in results.items(): + if c.files or c.broken: + logger.info( + "activity: %s: %d file(s), %d line(s), %d used, %d without user, " + "%d broken, %d too old, %d row(s) into %s (%.2f s)", + name, + c.files, + c.lines, + c.used, + c.anonymous, + c.broken, + c.dropped_old, + c.rows, + ", ".join(sorted(c.days)) or "-", + time.monotonic() - started, + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/controlplane/lmnsquid/activity_audit.py b/controlplane/lmnsquid/activity_audit.py new file mode 100644 index 0000000..8b75729 --- /dev/null +++ b/controlplane/lmnsquid/activity_audit.py @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Audit log of the activity log (ADR-023): who read whose activity data, when. + +One JSON line per access in ``/_audit/.jsonl`` (local day, 0600), +appended with a single ``write`` on an ``O_APPEND`` file, so concurrent API workers never mix +lines. A query is answered only after its audit line is written: an audit log that cannot be +written refuses the query. Kept ``activity_audit_retention_days`` days (config.yml, default +365), deleted as whole day files like the data. +""" + +from __future__ import annotations + +import datetime +import json +import os +import time +from pathlib import Path +from typing import Any +from zoneinfo import ZoneInfo + +SUFFIX = ".jsonl" +MAX_READ_LINES = 200_000 + + +def audit_dir(activity_dir: str) -> Path: + # Instance names always contain a "-" and never start with "_": no clash. + return Path(activity_dir) / "_audit" + + +def record( + directory: Path, zone: ZoneInfo, entry: dict[str, Any], now: float | None = None +) -> None: + """Append ``entry`` (plus the time) to today's audit file; raises ``OSError`` on failure.""" + now = time.time() if now is None else now + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + day = datetime.datetime.fromtimestamp(now, zone).date() + line = json.dumps({"ts": int(now), **entry}, ensure_ascii=False, sort_keys=True) + "\n" + fd = os.open( + directory / f"{day.isoformat()}{SUFFIX}", os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600 + ) + try: + data = line.encode("utf-8") + if os.write(fd, data) != len(data): + raise OSError("short write to the audit log") + finally: + os.close(fd) + + +def _files(directory: Path) -> list[tuple[datetime.date, Path]]: + found: list[tuple[datetime.date, Path]] = [] + try: + entries = list(os.scandir(directory)) + except FileNotFoundError: + return [] + for entry in entries: + if not entry.name.endswith(SUFFIX): + continue + try: + day = datetime.date.fromisoformat(entry.name[: -len(SUFFIX)]) + except ValueError: + continue + found.append((day, Path(entry.path))) + found.sort() + return found + + +def apply_retention(directory: Path, days: int, zone: ZoneInfo, now: float | None = None) -> int: + today = datetime.datetime.fromtimestamp(time.time() if now is None else now, zone).date() + keep_from = today - datetime.timedelta(days=days - 1) + removed = 0 + for day, path in _files(directory): + if day < keep_from: + path.unlink(missing_ok=True) + removed += 1 + return removed + + +def read( + directory: Path, + zone: ZoneInfo, + since: int, + until: int, + actor: str | None = None, + limit: int = 100, + offset: int = 0, +) -> dict[str, Any]: + """Entries with ``since <= ts < until`` (optionally of one actor), newest first, paged.""" + first = datetime.datetime.fromtimestamp(since, zone).date() + last = datetime.datetime.fromtimestamp(max(since, until - 1), zone).date() + matched: list[dict[str, Any]] = [] + read_lines = 0 + truncated = False + for day, path in reversed(_files(directory)): + if day < first or day > last: + continue + try: + lines = path.read_text(encoding="utf-8").splitlines() + except OSError: + continue + for raw in reversed(lines): + read_lines += 1 + if read_lines > MAX_READ_LINES: + truncated = True + break + try: + entry = json.loads(raw) + except ValueError: + continue + if not isinstance(entry, dict): + continue + ts = int(entry.get("ts") or 0) + if not since <= ts < until: + continue + if actor and entry.get("actor") != actor: + continue + matched.append(entry) + if truncated: + break + return { + "total": len(matched), + "truncated": truncated, + "entries": matched[offset : offset + limit], + } diff --git a/controlplane/lmnsquid/activity_query.py b/controlplane/lmnsquid/activity_query.py new file mode 100644 index 0000000..88a8d7c --- /dev/null +++ b/controlplane/lmnsquid/activity_query.py @@ -0,0 +1,547 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Queries over the activity log's day files (ADR-023), with hard limits. + +Every query names a time range (``since`` <= t < ``until``, epoch seconds), optionally a list of +users it is restricted to (the WebUI passes the users the asking person may see: that list is +the scope, the proxy filters on it in SQL) and the instances to read. Only day files within an +instance's retention are read, also before the collector deleted older ones. + +Limits: ranges, page sizes, the user list and a time budget per query (an SQLite progress +handler); a query over the budget fails with a readable message instead of running on. +""" + +from __future__ import annotations + +import csv +import datetime +import io +import json +import sqlite3 +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Iterator +from zoneinfo import ZoneInfo + +from . import activity +from .activity import ActivityError + +DAY = 86400 +MAX_RANGE_DAYS = 366 +MAX_MINUTE_RANGE = 2 * DAY +MAX_EXPORT_DAYS = 31 +MAX_EXPORT_ROWS = 1_000_000 +MAX_USERS = 10_000 +MAX_LIMIT = 1000 +MAX_DOMAIN_LIMIT = 500 +MAX_TIMELINE_ROWS = 5000 +MAX_SEARCH_CANDIDATES = 5000 +TIME_BUDGET = 20.0 +ACTIVE_SECONDS = 300 + + +@dataclass +class Source: + """One instance to read: its name and retention.""" + + name: str + retention_days: int + + +class Budget: + def __init__(self, seconds: float = TIME_BUDGET) -> None: + self.deadline = time.monotonic() + seconds + + def expired(self) -> bool: + return time.monotonic() > self.deadline + + def handler(self) -> Callable[[], int]: + return lambda: 1 if self.expired() else 0 + + def check(self) -> None: + if self.expired(): + raise ActivityError("query too large: choose a shorter range or fewer users") + + +def check_range(since: int, until: int, max_seconds: int = MAX_RANGE_DAYS * DAY) -> None: + if since < 0 or until <= since: + raise ActivityError("until must be after since") + if until - since > max_seconds: + raise ActivityError(f"range too long (at most {max_seconds // DAY or 1} days)") + + +def check_users(users: list[str] | None) -> list[str] | None: + if users is None: + return None + if len(users) > MAX_USERS: + raise ActivityError(f"too many users (at most {MAX_USERS})") + cleaned = sorted({u.strip().lower() for u in users if isinstance(u, str) and u.strip()}) + return cleaned + + +def _like_escape(text: str) -> str: + return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + + +class Query: + def __init__( + self, + data_root: str, + zone: ZoneInfo, + sources: list[Source], + now: float | None = None, + budget: Budget | None = None, + ) -> None: + self.data_root = data_root + self.zone = zone + self.sources = sources + self.now = time.time() if now is None else now + self.budget = budget or Budget() + + # -- files -------------------------------------------------------------------------------- + + def _day_bounds(self, day: datetime.date) -> tuple[int, int]: + start = datetime.datetime.combine(day, datetime.time(), self.zone) + end = datetime.datetime.combine( + day + datetime.timedelta(days=1), datetime.time(), self.zone + ) + return int(start.timestamp()), int(end.timestamp()) + + def files(self, since: int, until: int) -> list[tuple[datetime.date, Path, bool]]: + """(day, path, whole day in range) of every day file the range touches, oldest first. + + A day counts as whole when the range covers it, or covers it from its start up to now + (there is no data after now). + """ + first = datetime.datetime.fromtimestamp(since, self.zone).date() + last = datetime.datetime.fromtimestamp(until - 1, self.zone).date() + today = activity.today_in(self.zone, self.now) + out: list[tuple[datetime.date, Path, bool]] = [] + for source in self.sources: + keep_from = activity.oldest_kept(today, source.retention_days) + for day, path in activity.day_files(activity.data_dir(self.data_root, source.name)): + if day < first or day > last or day < keep_from: + continue + start, end = self._day_bounds(day) + whole = since <= start and (until >= end or until >= self.now) + out.append((day, path, whole)) + out.sort(key=lambda item: item[0]) + return out + + def _open(self, path: Path) -> sqlite3.Connection: + db = activity.connect_day(path, create=False) + db.set_progress_handler(self.budget.handler(), 20_000) + return db + + def _run(self, path: Path, work: Callable[[sqlite3.Connection], None]) -> None: + self.budget.check() + try: + db = self._open(path) + except sqlite3.Error: + return # deleted by the retention meanwhile, or not readable: no data from it + try: + work(db) + except sqlite3.OperationalError as exc: + if "interrupted" in str(exc): + raise ActivityError( + "query too large: choose a shorter range or fewer users" + ) from None + raise + finally: + db.close() + + @staticmethod + def _user_filter(users: list[str] | None, column: str = "u") -> tuple[str, list[Any]]: + if users is None: + return "", [] + return ( + f" AND {column} IN (SELECT id FROM users WHERE name IN " + "(SELECT value FROM json_each(?)))", + [json.dumps(users)], + ) + + # -- queries ------------------------------------------------------------------------------ + + def users( + self, + since: int, + until: int, + users: list[str] | None, + limit: int = 100, + offset: int = 0, + sort: str = "requests", + with_domains: bool = True, + ) -> dict[str, Any]: + """Per user: requests, bytes, blocked, distinct domains, last seen, active now.""" + check_range(since, until) + users = check_users(users) + limit = max(1, min(limit, MAX_LIMIT)) + if users == []: + return {"total": 0, "users": []} + hs, he = since // 3600, (until - 1) // 3600 + ms, me = since // 60, (until - 1) // 60 + acc: dict[str, list[int]] = {} + domains: dict[str, set[str]] = {} + where, args = self._user_filter(users, "uh.u") + + for _day, path, whole in self.files(since, until): + + def work(db: sqlite3.Connection, whole: bool = whole) -> None: + for name, n, b, x, last in db.execute( + "SELECT us.name, sum(uh.n), sum(uh.b), sum(uh.x), max(uh.last) FROM uh " + "JOIN users us ON us.id = uh.u WHERE uh.hr BETWEEN ? AND ?" + + where + + " GROUP BY us.name", + [hs, he, *args], + ): + row = acc.setdefault(name, [0, 0, 0, 0]) + row[0] += n + row[1] += b + row[2] += x + row[3] = max(row[3], last) + if not with_domains: + return + if whole: + w2, a2 = self._user_filter(users, "uhd.u") + sql = ( + "SELECT us.name, ho.name FROM uhd JOIN users us ON us.id = uhd.u " + "JOIN hosts ho ON ho.id = uhd.h WHERE 1" + w2 + ) + params: list[Any] = a2 + else: + w2, a2 = self._user_filter(users, "act.u") + sql = ( + "SELECT DISTINCT us.name, ho.name FROM act JOIN users us ON us.id = act.u " + "JOIN hosts ho ON ho.id = act.h WHERE act.m BETWEEN ? AND ?" + w2 + ) + params = [ms, me, *a2] + for name, host in db.execute(sql, params): + domains.setdefault(name, set()).add(host) + + self._run(path, work) + + keys: dict[str, Callable[[tuple[str, list[int]]], Any]] = { + "requests": lambda kv: (-kv[1][0], kv[0]), + "blocked": lambda kv: (-kv[1][2], -kv[1][0], kv[0]), + "last": lambda kv: (-kv[1][3], kv[0]), + "name": lambda kv: kv[0], + "bytes": lambda kv: (-kv[1][1], kv[0]), + } + ordered = sorted(acc.items(), key=keys.get(sort, keys["requests"])) + page = ordered[offset : offset + limit] + return { + "total": len(ordered), + "users": [ + { + "user": name, + "requests": n, + "bytes": b, + "blocked": x, + "domains": len(domains.get(name, ())) if with_domains else None, + "last": last * 60, + "active_now": last * 60 >= self.now - ACTIVE_SECONDS, + } + for name, (n, b, x, last) in page + ], + } + + def timeline( + self, + user: str, + since: int, + until: int, + resolution: str = "hour", + limit: int = 1000, + offset: int = 0, + ) -> dict[str, Any]: + """One user's activity: per hour (heat map) or per minute and domain.""" + user = user.strip().lower() + if not user: + raise ActivityError("user missing") + if resolution == "minute": + check_range(since, until, MAX_MINUTE_RANGE) + limit = max(1, min(limit, MAX_TIMELINE_ROWS)) + ms, me = since // 60, (until - 1) // 60 + rows: dict[tuple[int, str], list[Any]] = {} + for _day, path, _whole in self.files(since, until): + + def work_m(db: sqlite3.Connection) -> None: + for m, host, n, b, x, c in db.execute( + "SELECT act.m, ho.name, act.n, act.b, act.x, act.c FROM act " + "JOIN hosts ho ON ho.id = act.h WHERE act.u = " + "(SELECT id FROM users WHERE name = ?) AND act.m BETWEEN ? AND ?", + [user, ms, me], + ): + row = rows.setdefault((m, host), [0, 0, 0, None]) + row[0] += n + row[1] += b + row[2] += x + row[3] = c or row[3] + + self._run(path, work_m) + ordered = sorted(rows.items()) + return { + "user": user, + "resolution": "minute", + "total": len(ordered), + "rows": [ + { + "t": m * 60, + "domain": host, + "requests": n, + "bytes": b, + "blocked": x, + "category": c, + } + for (m, host), (n, b, x, c) in ordered[offset : offset + limit] + ], + } + if resolution != "hour": + raise ActivityError("resolution must be hour or minute") + check_range(since, until) + hs, he = since // 3600, (until - 1) // 3600 + hours: dict[int, list[int]] = {} + for _day, path, _whole in self.files(since, until): + + def work_h(db: sqlite3.Connection) -> None: + for hr, n, b, x, last in db.execute( + "SELECT hr, n, b, x, last FROM uh WHERE u = " + "(SELECT id FROM users WHERE name = ?) AND hr BETWEEN ? AND ?", + [user, hs, he], + ): + row = hours.setdefault(hr, [0, 0, 0, 0]) + row[0] += n + row[1] += b + row[2] += x + row[3] = max(row[3], last) + + self._run(path, work_h) + return { + "user": user, + "resolution": "hour", + "total": len(hours), + "rows": [ + {"t": hr * 3600, "requests": n, "bytes": b, "blocked": x, "last": last * 60} + for hr, (n, b, x, last) in sorted(hours.items()) + ], + } + + def domains( + self, + since: int, + until: int, + users: list[str] | None, + limit: int = 50, + ) -> dict[str, Any]: + """Top domains of the users (or of everyone): requests, bytes, blocked, users, category.""" + check_range(since, until) + users = check_users(users) + limit = max(1, min(limit, MAX_DOMAIN_LIMIT)) + if users == []: + return {"total": 0, "domains": []} + ms, me = since // 60, (until - 1) // 60 + acc: dict[str, list[Any]] = {} + files = self.files(since, until) + for _day, path, whole in files: + + def work(db: sqlite3.Connection, whole: bool = whole) -> None: + if whole: + w, a = self._user_filter(users, "uhd.u") + sql = ( + "SELECT ho.name, sum(uhd.n), sum(uhd.b), sum(uhd.x), max(uhd.c) FROM uhd " + "JOIN hosts ho ON ho.id = uhd.h WHERE 1" + w + " GROUP BY uhd.h" + ) + params: list[Any] = a + else: + w, a = self._user_filter(users, "act.u") + sql = ( + "SELECT ho.name, sum(act.n), sum(act.b), sum(act.x), max(act.c) FROM act " + "JOIN hosts ho ON ho.id = act.h WHERE act.m BETWEEN ? AND ?" + + w + + " GROUP BY act.h" + ) + params = [ms, me, *a] + for host, n, b, x, c in db.execute(sql, params): + row = acc.setdefault(host, [0, 0, 0, None]) + row[0] += n + row[1] += b + row[2] += x + row[3] = c or row[3] + + self._run(path, work) + ordered = sorted(acc.items(), key=lambda kv: (-kv[1][0], kv[0]))[:limit] + top = [host for host, _row in ordered] + who: dict[str, set[str]] = {host: set() for host in top} + if top: + for _day, path, whole in files: + + def work_users(db: sqlite3.Connection, whole: bool = whole) -> None: + hosts_json = json.dumps(top) + if whole: + w, a = self._user_filter(users, "uhd.u") + sql = ( + "SELECT DISTINCT ho.name, us.name FROM uhd JOIN hosts ho ON " + "ho.id = uhd.h JOIN users us ON us.id = uhd.u WHERE ho.name IN " + "(SELECT value FROM json_each(?))" + w + ) + params: list[Any] = [hosts_json, *a] + else: + w, a = self._user_filter(users, "act.u") + sql = ( + "SELECT DISTINCT ho.name, us.name FROM act JOIN hosts ho ON " + "ho.id = act.h JOIN users us ON us.id = act.u WHERE ho.name IN " + "(SELECT value FROM json_each(?)) AND act.m BETWEEN ? AND ?" + w + ) + params = [hosts_json, ms, me, *a] + for host, name in db.execute(sql, params): + who[host].add(name) + + self._run(path, work_users) + return { + "total": len(acc), + "domains": [ + { + "domain": host, + "requests": n, + "bytes": b, + "blocked": x, + "category": c, + "users": len(who.get(host, ())), + } + for host, (n, b, x, c) in ordered + ], + } + + def search( + self, + domain: str, + since: int, + until: int, + users: list[str] | None, + limit: int = 200, + ) -> dict[str, Any]: + """Who was on ``domain`` (or a subdomain of it) in the range.""" + check_range(since, until) + users = check_users(users) + limit = max(1, min(limit, MAX_LIMIT)) + domain = domain.strip().lower().rstrip(".") + if not domain or len(domain) > activity.MAX_HOST or any(c.isspace() for c in domain): + raise ActivityError("invalid domain") + if users == []: + return {"total": 0, "users": []} + ms, me = since // 60, (until - 1) // 60 + found: dict[str, list[Any]] = {} + for _day, path, whole in self.files(since, until): + + def work(db: sqlite3.Connection, whole: bool = whole) -> None: + host_ids = { + int(i): str(n) + for i, n in db.execute( + "SELECT id, name FROM hosts WHERE name = ? OR name LIKE ? ESCAPE '\\'", + [domain, "%." + _like_escape(domain)], + ) + } + if not host_ids: + return + w, a = self._user_filter(users, "uhd.u") + cands = db.execute( + "SELECT uhd.u, us.name, uhd.h, uhd.n, uhd.x, uhd.first, uhd.last FROM uhd " + "JOIN users us ON us.id = uhd.u WHERE uhd.h IN (SELECT value FROM json_each(?))" + + w + + " LIMIT ?", + [json.dumps(sorted(host_ids)), *a, MAX_SEARCH_CANDIDATES + 1], + ).fetchall() + if len(cands) > MAX_SEARCH_CANDIDATES: + raise ActivityError("too many hits: choose a shorter range or a longer name") + for u, name, h, n, x, first, last in cands: + if not whole: + if last < ms or first > me: + continue + n, x, first, last = db.execute( + "SELECT sum(n), sum(x), min(m), max(m) FROM act " + "WHERE u = ? AND m BETWEEN ? AND ? AND h = ?", + [u, ms, me, h], + ).fetchone() + if not n: + continue + row = found.setdefault(name, [0, 0, first, last, set()]) + row[0] += n + row[1] += x + row[2] = min(row[2], first) + row[3] = max(row[3], last) + row[4].add(host_ids[h]) + + self._run(path, work) + ordered = sorted(found.items(), key=lambda kv: (-kv[1][0], kv[0])) + return { + "domain": domain, + "total": len(ordered), + "users": [ + { + "user": name, + "requests": n, + "blocked": x, + "first": first * 60, + "last": last * 60, + "domains": sorted(hosts)[:10], + } + for name, (n, x, first, last, hosts) in ordered[:limit] + ], + } + + def export(self, since: int, until: int, users: list[str] | None) -> Iterator[str]: + """CSV, one row per minute, user and domain (at most 31 days, 1 million rows).""" + check_range(since, until, MAX_EXPORT_DAYS * DAY) + users = check_users(users) + files = self.files(since, until) + ms, me = since // 60, (until - 1) // 60 + # The export is long-running by nature: its own, larger budget. + self.budget = Budget(120.0) + + def lines() -> Iterator[str]: + buf = io.StringIO() + out = csv.writer(buf) + out.writerow(["time", "user", "domain", "requests", "bytes", "blocked", "category"]) + yield buf.getvalue() + written = 0 + if users == []: + return + for _day, path, _whole in files: + try: + db = self._open(path) + except sqlite3.Error: + continue + try: + w, a = self._user_filter(users, "act.u") + cursor = db.execute( + "SELECT act.m, us.name, ho.name, act.n, act.b, act.x, act.c FROM act " + "JOIN users us ON us.id = act.u JOIN hosts ho ON ho.id = act.h " + "WHERE act.m BETWEEN ? AND ?" + w + " ORDER BY act.m", + [ms, me, *a], + ) + while True: + batch = cursor.fetchmany(5000) + if not batch: + break + buf.seek(0) + buf.truncate() + for m, name, host, n, b, x, c in batch: + if written >= MAX_EXPORT_ROWS: + break + stamp = datetime.datetime.fromtimestamp(m * 60, self.zone) + out.writerow( + [stamp.isoformat(timespec="minutes"), name, host, n, b, x, c or ""] + ) + written += 1 + yield buf.getvalue() + if written >= MAX_EXPORT_ROWS: + yield f"# truncated after {MAX_EXPORT_ROWS} rows\n" + return + except sqlite3.OperationalError as exc: + yield f"# stopped: {'too large' if 'interrupted' in str(exc) else 'error'}\n" + return + finally: + db.close() + + return lines() diff --git a/controlplane/lmnsquid/config.py b/controlplane/lmnsquid/config.py index 3062ddd..4ed2e95 100644 --- a/controlplane/lmnsquid/config.py +++ b/controlplane/lmnsquid/config.py @@ -14,6 +14,7 @@ from typing import Any import yaml +from pydantic import field_validator from pydantic_settings import BaseSettings, SettingsConfigDict _ENV_PREFIX = "LMNSQUID_" @@ -37,6 +38,11 @@ class Settings(BaseSettings): # Time zone of the filter's schedules: school time, not the proxy host's clock zone (a VM # from a cloud image runs in UTC). Also the zone the WebUI shows server times in. filter_timezone: str = "Europe/Berlin" + # Activity log (ADR-023): the day files per instance, the spool the containers write into + # (outside /var/lib, which the package's configure chowns), the audit log's retention. + activity_dir: str = "/var/lib/linuxmuster-squid/activity" + activity_spool_dir: str = "/var/spool/linuxmuster-squid/activity" + activity_audit_retention_days: int = 365 docker_host: str | None = None bind_host: str = "127.0.0.1" bind_port: int = 8080 @@ -56,6 +62,13 @@ class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix=_ENV_PREFIX) + @field_validator("activity_audit_retention_days") + @classmethod + def _v_audit_retention(cls, v: int) -> int: + if not 1 <= v <= 3650: + raise ValueError("activity_audit_retention_days must be between 1 and 3650") + return v + def load_settings(config_path: str | None = None) -> Settings: """Load :class:`Settings` from an optional YAML file plus environment. diff --git a/controlplane/lmnsquid/docker_service.py b/controlplane/lmnsquid/docker_service.py index 3ae72c6..dde6465 100644 --- a/controlplane/lmnsquid/docker_service.py +++ b/controlplane/lmnsquid/docker_service.py @@ -17,6 +17,7 @@ from docker.models.containers import Container from docker.types import LogConfig, Mount +from . import activity from .blocklist import CONTAINER_DIR, Blocklist, noauth_list from .filters import FilterStore from .models import KRB5_CLOCKSKEW_DEFAULT, Instance @@ -117,6 +118,7 @@ def __init__( poll_interval: float = 2.0, catalog_dir: str = "/var/lib/linuxmuster-squid/catalog", filter_timezone: Optional[str] = None, + activity_spool_dir: str = "/var/spool/linuxmuster-squid/activity", ) -> None: self.docker_host: Optional[str] = docker_host self.secrets_dir: str = secrets_dir @@ -127,6 +129,7 @@ def __init__( self.noauth = noauth_list(blocklists_dir) self.filters = FilterStore(blocklists_dir, filter_timezone) self.catalog_dir = catalog_dir + self.activity_spool_dir = activity_spool_dir self.health_timeout = health_timeout self.poll_interval = poll_interval self.client: docker.DockerClient = ( @@ -192,6 +195,9 @@ def env_for(self, inst: Instance) -> dict[str, str]: # the spec fingerprint, so instances at the default are not replaced on upgrade. if inst.krb5_clockskew_seconds != KRB5_CLOCKSKEW_DEFAULT: env["KRB5_CLOCKSKEW_SECONDS"] = str(inst.krb5_clockskew_seconds) + # Activity log (ADR-023): only while on, so the spec of every other instance is unchanged. + if inst.activity_log_enabled: + env["ACTIVITY_LOG_ENABLED"] = "1" return env def spec_for(self, inst: Instance) -> dict[str, Any]: @@ -208,6 +214,23 @@ def spec_for(self, inst: Instance) -> dict[str, Any]: keytab_host_path = os.path.realpath(os.path.join(secrets_root, inst.keytab_secret)) if os.path.commonpath([secrets_root, keytab_host_path]) != secrets_root: raise ValueError(f"keytab_secret escapes secrets_dir: {inst.keytab_secret!r}") + volumes: dict[str, dict[str, str]] = { + keytab_host_path: {"bind": env["KEYTAB"], "mode": "ro"}, + # Per-instance blocklist directory (see blocklist.py for why the directory). + os.path.realpath(self.blocklist.dir_for(inst.name)): { + "bind": CONTAINER_DIR, + "mode": "ro", + }, + # The category catalog (ADR-022); a directory, so the atomic switch of + # current.sqlite on the host reaches the container. + os.path.realpath(self.catalog_dir): {"bind": CATALOG_CONTAINER_DIR, "mode": "ro"}, + f"lmnsquid-cache-{inst.name}": {"bind": "/var/spool/squid", "mode": "rw"}, + f"lmnsquid-logs-{inst.name}": {"bind": "/var/log/squid", "mode": "rw"}, + } + if inst.activity_log_enabled: + # The activity log's spool (ADR-023): mounted only while the log is on. + spool = os.path.realpath(activity.spool_dir(self.activity_spool_dir, inst.name)) + volumes[spool] = {"bind": activity.SPOOL_CONTAINER_DIR, "mode": "rw"} return { "image": inst.image, "hostname": inst.visible_hostname, @@ -221,19 +244,7 @@ def spec_for(self, inst: Instance) -> dict[str, Any]: # Docker json-log is capped (only the live view); the durable, gzip-rotated # history lives in the persistent log volume (logrotate, LOG_RETENTION_DAYS). "log_config": {"max-size": self.log_max_size, "max-file": str(self.log_max_file)}, - "volumes": { - keytab_host_path: {"bind": env["KEYTAB"], "mode": "ro"}, - # Per-instance blocklist directory (see blocklist.py for why the directory). - os.path.realpath(self.blocklist.dir_for(inst.name)): { - "bind": CONTAINER_DIR, - "mode": "ro", - }, - # The category catalog (ADR-022); a directory, so the atomic switch of - # current.sqlite on the host reaches the container. - os.path.realpath(self.catalog_dir): {"bind": CATALOG_CONTAINER_DIR, "mode": "ro"}, - f"lmnsquid-cache-{inst.name}": {"bind": "/var/spool/squid", "mode": "rw"}, - f"lmnsquid-logs-{inst.name}": {"bind": "/var/log/squid", "mode": "rw"}, - }, + "volumes": volumes, "ports": {f"{inst.http_port}/tcp": [self.container_bind_ip, inst.http_port]}, } @@ -275,6 +286,8 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: # The catalog directory must exist before Docker mounts it (else Docker creates a # root-owned one); SafeSearch addresses are resolved again for a new container. os.makedirs(self.catalog_dir, mode=0o755, exist_ok=True) + if inst.activity_log_enabled: + activity.ensure_spool(self.activity_spool_dir, inst.name) self.filters.refresh_safesearch(inst.name) cname = inst.container_name @@ -545,6 +558,8 @@ def status(self, name: str) -> dict[str, Any]: "image": image, # the data-plane image has the category filter (label set by image/Dockerfile) "filter_capable": bool(labels.get(FILTER_LABEL)), + # ... and the activity log receiver (ADR-023) + "activity_capable": bool(labels.get(activity.ACTIVITY_LABEL)), } def logs( diff --git a/controlplane/lmnsquid/main.py b/controlplane/lmnsquid/main.py index 92df61d..98fa962 100644 --- a/controlplane/lmnsquid/main.py +++ b/controlplane/lmnsquid/main.py @@ -62,6 +62,7 @@ def main() -> None: settings.blocklists_dir, catalog_dir=settings.catalog_dir, filter_timezone=settings.filter_timezone, + activity_spool_dir=settings.activity_spool_dir, ) reconciler = Reconciler(store, docker) updater = Updater(store, docker, reconciler) diff --git a/controlplane/lmnsquid/models.py b/controlplane/lmnsquid/models.py index 34b19fc..daae716 100644 --- a/controlplane/lmnsquid/models.py +++ b/controlplane/lmnsquid/models.py @@ -13,7 +13,7 @@ import ipaddress import re -from pydantic import BaseModel, computed_field, field_validator +from pydantic import BaseModel, computed_field, field_validator, model_validator from .blocklist import normalize_domain, normalize_noauth_domain @@ -47,6 +47,11 @@ KRB5_CLOCKSKEW_DEFAULT = 300 KRB5_CLOCKSKEW_MAX = 7200 +# Activity log (ADR-023): off unless switched on with a confirmed privacy notice. +ACTIVITY_RETENTION_DEFAULT = 7 +ACTIVITY_RETENTION_MAX = 365 +_ACK_RE = re.compile(r"^[^\x00-\x1f\x7f]{1,128}$") + def _normalize_cidr_list(value: str) -> str: """Split on commas/whitespace, validate each part as a CIDR, and return the @@ -79,6 +84,12 @@ class Instance(BaseModel): log_retention_days: int = 30 access_log_enabled: bool = True krb5_clockskew_seconds: int = KRB5_CLOCKSKEW_DEFAULT + # Activity log (ADR-023). Changed only through PUT /v1/instances/{name}/activity (not in + # InstancePatch), which records who confirmed the privacy notice and when. + activity_log_enabled: bool = False + activity_retention_days: int = ACTIVITY_RETENTION_DEFAULT + activity_ack_by: str | None = None + activity_ack_at: str | None = None @field_validator("school", "role") @classmethod @@ -169,6 +180,31 @@ def _v_clockskew(cls, v: int) -> int: ) return v + @field_validator("activity_retention_days") + @classmethod + def _v_activity_retention(cls, v: int) -> int: + if not 1 <= v <= ACTIVITY_RETENTION_MAX: + raise ValueError( + f"activity_retention_days must be between 1 and {ACTIVITY_RETENTION_MAX}" + ) + return v + + @field_validator("activity_ack_by", "activity_ack_at") + @classmethod + def _v_ack(cls, v: str | None) -> str | None: + if v is not None and not _ACK_RE.match(v): + raise ValueError("must be 1-128 printable characters") + return v + + @model_validator(mode="after") + def _v_activity_ack(self) -> "Instance": + if self.activity_log_enabled and not (self.activity_ack_by and self.activity_ack_at): + raise ValueError( + "activity_log_enabled needs a confirmed privacy notice (activity_ack_by/_at): " + "switch it on with PUT /v1/instances/{name}/activity" + ) + return self + @computed_field # type: ignore[prop-decorator] @property def name(self) -> str: diff --git a/controlplane/pyproject.toml b/controlplane/pyproject.toml index ed5c55d..2a50817 100644 --- a/controlplane/pyproject.toml +++ b/controlplane/pyproject.toml @@ -44,6 +44,7 @@ dev = [ lmnsquid-api = "lmnsquid.main:main" lmnsquid = "lmnsquid.cli:main" lmnsquid-catalog = "lmnsquid.catalog:main" +lmnsquid-activity = "lmnsquid.activity:main" [tool.setuptools.packages.find] include = ["lmnsquid*"] diff --git a/controlplane/tests/conftest.py b/controlplane/tests/conftest.py index 8cfe4f2..a39dddf 100644 --- a/controlplane/tests/conftest.py +++ b/controlplane/tests/conftest.py @@ -158,6 +158,7 @@ def status(self, name: str) -> dict[str, Any]: "image": container["image"], # an image tagged "old" stands for one without the category filter (ADR-022) "filter_capable": "old" not in container["image"], + "activity_capable": "old" not in container["image"], } def logs( @@ -211,6 +212,8 @@ def settings(tmp_path: Any, token: str) -> Settings: catalog_custom=str(tmp_path / "catalog-custom.yml"), protected_file=str(tmp_path / "protected.domains"), filter_timezone="Europe/Berlin", + activity_dir=str(tmp_path / "activity"), + activity_spool_dir=str(tmp_path / "spool" / "activity"), ) diff --git a/controlplane/tests/test_activity.py b/controlplane/tests/test_activity.py new file mode 100644 index 0000000..c5e092f --- /dev/null +++ b/controlplane/tests/test_activity.py @@ -0,0 +1,474 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Activity log (ADR-023): the image's UDP receiver, the collector (parsing, aggregation, +restart without loss or double counting, broken lines, day split, retention) and the queries +(scope by user list, limits, whole and partial days).""" + +from __future__ import annotations + +import datetime +import os +import signal +import socket +import sqlite3 +import subprocess +import sys +import time +from pathlib import Path +from typing import Any +from zoneinfo import ZoneInfo + +import pytest + +from lmnsquid import activity +from lmnsquid.activity import ActivityError, parse_line +from lmnsquid.activity_query import MAX_USERS, Budget, Query, Source +from lmnsquid.models import Instance + +LOGD = Path(__file__).resolve().parents[2] / "image" / "lmn-activity-logd" +ZONE = ZoneInfo("Europe/Berlin") +# 2026-11-25 10:00:00 Europe/Berlin (UTC+1) +T0 = int(datetime.datetime(2026, 11, 25, 10, 0, tzinfo=ZONE).timestamp()) + + +def _inst(**over: Any) -> Instance: + data: dict[str, Any] = dict( + school="default-school", + role="students", + ad_group="students", + realm="EX.LAN", + visible_hostname="proxy.example.lan", + keytab_secret="proxy.keytab", + image="ghcr.io/x/y:1", + activity_log_enabled=True, + activity_ack_by="admin", + activity_ack_at="2026-11-25T09:00:00+00:00", + ) + data.update(over) + return Instance(**data) + + +def line( + ts: int, + user: str, + host: str, + status: int = 200, + sq: str = "TCP_TUNNEL", + size: int = 100, + cat: str = "-", +) -> str: + return f"{ts} {user} {host} {status} {sq} {size} {cat}\n" + + +class Env: + def __init__(self, tmp: Path) -> None: + self.data = str(tmp / "activity") + self.spool_root = str(tmp / "spool") + self.inst = _inst() + self.spool = activity.ensure_spool(self.spool_root, self.inst.name) + self.seq = 0 + + def put(self, text: str, name: str | None = None) -> Path: + self.seq += 1 + path = self.spool / (name or f"act-{T0:010d}-abcd{self.seq:04d}-{self.seq:06d}.log") + path.write_text(text) + return path + + def collect(self, now: float = T0 + 3600, **over: Any) -> activity.Counters: + inst = _inst(**over) if over else self.inst + return activity.collect_instance(inst, self.data, self.spool_root, ZONE, now=now) + + def db(self, day: str = "2026-11-25") -> sqlite3.Connection: + return sqlite3.connect(Path(self.data) / self.inst.name / f"{day}.sqlite") + + def total(self, day: str = "2026-11-25") -> int: + return self.db(day).execute("SELECT coalesce(sum(n), 0) FROM act").fetchone()[0] + + def query(self, now: float = T0 + 3600) -> Query: + return Query(self.data, ZONE, [Source(self.inst.name, 7)], now=now) + + +@pytest.fixture +def env(tmp_path: Path) -> Env: + return Env(tmp_path) + + +# -- parsing ---------------------------------------------------------------------------------- + + +def test_parse_line_user_without_realm_and_blocked_flags() -> None: + assert parse_line(b"1795599222 Anna.Schmidt@EX.LAN www.Example.com. 200 TCP_TUNNEL 512 -") == ( + 1795599222, + "anna.schmidt", + "www.example.com", + 512, + 0, + None, + ) + # squid may %-encode the @ of the principal + assert parse_line(b"1 s1%40EX.LAN a.b 200 TCP_MISS 1 -")[1] == "s1" # type: ignore[index] + assert parse_line(b"1 s1 a.b 403 TCP_DENIED 10 porn")[4:] == (1, "porn") # type: ignore[index] + assert parse_line(b"1 s1 a.b 403 TCP_DENIED 10 -")[4] == 1 # type: ignore[index] + assert parse_line(b"1 s1 a.b 200 NONE_NONE - ads")[3:] == (0, 1, "ads") # type: ignore[index] + # no ticket / a domain without authentication: no user, not counted + assert parse_line(b"1 - healthcheck.invalid 407 TCP_DENIED 3497 -") is None + + +@pytest.mark.parametrize( + "raw", + [ + b"", + b"garbage", + b"x s1 a.b 200 TCP_MISS 1 -", + b"1 s1 - 200 TCP_MISS 1 -", + b"1 " + b"u" * 80 + b" a.b 200 TCP_MISS 1 -", + b"1 s1 a.b 200 TCP_MISS notanumber -", + ], +) +def test_parse_line_refuses_broken_lines(raw: bytes) -> None: + with pytest.raises(ValueError): + parse_line(raw) + + +# -- collecting ------------------------------------------------------------------------------- + + +def test_collect_sums_per_minute_and_deletes_the_spool_file(env: Env) -> None: + f = env.put( + line(T0, "s1@EX.LAN", "a.example") + + line(T0 + 10, "s1@EX.LAN", "a.example", size=50) + + line(T0 + 70, "s1@EX.LAN", "a.example") + + line(T0 + 5, "s2@EX.LAN", "b.example", 403, "TCP_DENIED", cat="porn") + + line(T0 + 6, "-", "healthcheck.invalid", 407, "TCP_DENIED") + ) + c = env.collect() + assert (c.files, c.lines, c.used, c.anonymous, c.broken) == (1, 5, 4, 1, 0) + assert not f.exists() + db = env.db() + rows = db.execute( + "SELECT us.name, act.m, ho.name, n, b, x, c FROM act JOIN users us ON us.id = u " + "JOIN hosts ho ON ho.id = h ORDER BY 1, 2" + ).fetchall() + assert rows == [ + ("s1", T0 // 60, "a.example", 2, 150, 0, None), + ("s1", T0 // 60 + 1, "a.example", 1, 100, 0, None), + ("s2", T0 // 60, "b.example", 1, 100, 1, "porn"), + ] + assert db.execute("SELECT sum(n), sum(x) FROM uh").fetchone() == (4, 1) + assert db.execute( + "SELECT n, first, last FROM uhd WHERE u = (SELECT id FROM users WHERE name='s1')" + ).fetchone() == (3, T0 // 60, T0 // 60 + 1) + assert oct(os.stat(Path(env.data) / env.inst.name / "2026-11-25.sqlite").st_mode)[-3:] == "600" + + +def test_a_file_collected_twice_is_counted_once(env: Env) -> None: + text = line(T0, "s1", "a.example") * 3 + f = env.put(text) + env.collect() + # a run that stopped after the commit, before the unlink: the same file is there again + f.write_text(text) + c = env.collect() + assert c.rows == 0 and not f.exists() + assert env.total() == 3 + + +def test_restart_between_two_files_loses_nothing(env: Env) -> None: + env.put(line(T0, "s1", "a.example")) + env.collect() + env.put(line(T0 + 1, "s1", "a.example")) + env.put(line(T0 + 2, "s1", "b.example")) + env.collect() + assert env.total() == 3 + + +def test_broken_and_cut_lines_are_counted_not_stored(env: Env) -> None: + env.put(line(T0, "s1", "a.example") + "complete garbage\n" + "1795599222 s1 a.exa") + c = env.collect() + assert (c.used, c.broken) == (1, 2) + assert env.total() == 1 + + +def test_parts_are_taken_only_when_stale(env: Env) -> None: + part = env.put(line(T0, "s1", "a.example"), name=f".part-{T0:010d}-ffff0000-000001") + env.collect(now=time.time()) + assert part.exists(), "a part being written must stay" + old = time.time() - activity.STALE_PART_SECONDS - 5 + os.utime(part, (old, old)) + env.collect(now=time.time()) + assert not part.exists() + assert env.total() == 1 + # its finished twin (same ledger name) is not counted again + env.put(line(T0, "s1", "a.example"), name=f"act-{T0:010d}-ffff0000-000001.log") + env.collect(now=time.time()) + assert env.total() == 1 + + +def test_lines_split_at_local_midnight(env: Env) -> None: + midnight = int(datetime.datetime(2026, 11, 26, 0, 0, tzinfo=ZONE).timestamp()) + env.put(line(midnight - 30, "s1", "a.example") + line(midnight + 30, "s1", "a.example")) + env.collect(now=midnight + 60) + assert env.total("2026-11-25") == 1 + assert env.total("2026-11-26") == 1 + + +def test_retention_deletes_whole_days_and_drops_old_lines(env: Env) -> None: + for day in ("2026-11-17", "2026-11-18", "2026-11-19", "2026-11-25"): + (Path(env.data) / env.inst.name).mkdir(parents=True, exist_ok=True) + activity.connect_day(Path(env.data) / env.inst.name / f"{day}.sqlite", True).close() + old = int(datetime.datetime(2026, 11, 10, 12, 0, tzinfo=ZONE).timestamp()) + env.put(line(old, "s1", "a.example") + line(T0, "s1", "a.example")) + c = env.collect(activity_retention_days=7) + assert c.dropped_old == 1 + names = sorted(p.name for _d, p in activity.day_files(Path(env.data) / env.inst.name)) + # 7 days: 2026-11-19 .. 2026-11-25 are kept + assert names == ["2026-11-19.sqlite", "2026-11-25.sqlite"] + activity.apply_retention(env.data, env.inst.name, 1, ZONE, now=T0) + names = sorted(p.name for _d, p in activity.day_files(Path(env.data) / env.inst.name)) + assert names == ["2026-11-25.sqlite"] + + +def test_future_lines_are_dropped(env: Env) -> None: + env.put(line(T0 + 3 * 86400, "s1", "a.example")) + c = env.collect(now=T0) + assert c.broken == 1 and c.used == 0 + + +def test_spool_mode_and_purge(env: Env) -> None: + assert oct(env.spool.stat().st_mode & 0o7777) == oct(activity.SPOOL_MODE) + env.put(line(T0, "s1", "a.example")) + env.collect() + activity.purge_instance(env.data, env.spool_root, env.inst.name) + assert not (Path(env.data) / env.inst.name).exists() + assert not env.spool.exists() + + +def test_collect_all_skips_instances_without_the_log(tmp_path: Path) -> None: + paths = activity.Paths(str(tmp_path / "a"), str(tmp_path / "s"), ZONE) + off = _inst( + role="teachers", activity_log_enabled=False, activity_ack_by=None, activity_ack_at=None + ) + assert activity.collect_all([off], paths) == {} + assert not (tmp_path / "a").exists() + + +def test_lock_allows_one_run(tmp_path: Path) -> None: + a = activity.Lock(tmp_path / "x.lock") + b = activity.Lock(tmp_path / "x.lock") + assert a.acquire() + assert not b.acquire() + a.release() + assert b.acquire() + b.release() + + +# -- the receiver in the image ---------------------------------------------------------------- + + +def _free_port() -> int: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return int(port) + + +def _receiver(directory: Path, **env: str) -> tuple[subprocess.Popen[bytes], int]: + port = _free_port() + proc = subprocess.Popen( + [sys.executable, "-I", str(LOGD), f"127.0.0.1:{port}", str(directory)], + stderr=subprocess.PIPE, + env={"PATH": os.environ.get("PATH", ""), **env}, + ) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + probe.bind(("127.0.0.1", port)) + except OSError: + break # the receiver holds the port + finally: + probe.close() + time.sleep(0.05) + return proc, port + + +def _send(port: int, *lines: str) -> None: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + for text in lines: + s.sendto(text.encode(), ("127.0.0.1", port)) + s.close() + + +def _wait_files(directory: Path, prefix: str, count: int = 1, timeout: float = 10) -> list[Path]: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + found = sorted(p for p in directory.iterdir() if p.name.startswith(prefix)) + if len(found) >= count: + return found + time.sleep(0.05) + return sorted(p for p in directory.iterdir() if p.name.startswith(prefix)) + + +def test_receiver_finishes_files_on_time_and_on_sigterm(tmp_path: Path) -> None: + proc, port = _receiver(tmp_path, LMN_ACTIVITY_ROLL_SECONDS="0.3") + try: + _send(port, line(T0, "s1", "a.example"), line(T0, "s1", "b.example")) + done = _wait_files(tmp_path, "act-") + assert len(done) == 1 + assert done[0].read_text().count("\n") == 2 + assert oct(done[0].stat().st_mode)[-3:] == "640" + _send(port, line(T0 + 1, "s2", "c.example")) + _wait_files(tmp_path, ".part-") + finally: + proc.send_signal(signal.SIGTERM) + proc.wait(timeout=10) + assert proc.returncode == 0 + done = _wait_files(tmp_path, "act-", 2) + assert len(done) == 2 + assert not [p for p in tmp_path.iterdir() if p.name.startswith(".part-")] + + +def test_receiver_drops_lines_while_the_collector_is_behind(tmp_path: Path) -> None: + proc, port = _receiver(tmp_path, LMN_ACTIVITY_ROLL_SECONDS="0.2", LMN_ACTIVITY_PENDING_MAX="10") + try: + _send(port, line(T0, "s1", "a.example")) + assert len(_wait_files(tmp_path, "act-")) == 1 + _send(port, line(T0 + 1, "s1", "b.example")) + time.sleep(1.0) + assert len(_wait_files(tmp_path, "act-", timeout=0.1)) == 1 + assert not [p for p in tmp_path.iterdir() if p.name.startswith(".part-")] + finally: + proc.send_signal(signal.SIGTERM) + _out, err = proc.communicate(timeout=10) + assert b"wait for the collector" in err + + +def test_receiver_survives_an_unwritable_directory(tmp_path: Path) -> None: + gone = tmp_path / "gone" + proc, port = _receiver(gone, LMN_ACTIVITY_ROLL_SECONDS="0.2") + try: + _send(port, line(T0, "s1", "a.example")) + time.sleep(0.5) + assert proc.poll() is None + gone.mkdir() + _send(port, line(T0, "s1", "b.example")) + assert len(_wait_files(gone, "act-")) == 1 + finally: + proc.send_signal(signal.SIGTERM) + proc.wait(timeout=10) + + +# -- queries ---------------------------------------------------------------------------------- + + +def _fill(env: Env) -> None: + env.put( + line(T0, "s1", "a.example") + + line(T0 + 60, "s1", "a.example") + + line(T0 + 3600, "s1", "cdn.b.example") + + line(T0, "s2", "b.example", 403, "TCP_DENIED", cat="porn") + + line(T0 + 120, "t1", "secret.example") + ) + env.collect() + + +def test_users_overview_is_limited_to_the_given_users(env: Env) -> None: + _fill(env) + q = env.query() + all_users = q.users(T0 - 3600, T0 + 7200, None) + assert {u["user"] for u in all_users["users"]} == {"s1", "s2", "t1"} + scoped = q.users(T0 - 3600, T0 + 7200, ["s1", "S2", "nobody"]) + assert [u["user"] for u in scoped["users"]] == ["s1", "s2"] + s1 = scoped["users"][0] + assert (s1["requests"], s1["domains"], s1["blocked"]) == (3, 2, 0) + assert q.users(T0, T0 + 60, [])["users"] == [] + # partial day: only 10:00-10:59 + part = env.query(now=T0 + 86400).users(T0, T0 + 3600, ["s1"]) + assert part["users"][0]["requests"] == 2 and part["users"][0]["domains"] == 1 + + +def test_active_now(env: Env) -> None: + _fill(env) + users = env.query(now=T0 + 3600 + 60).users(T0, T0 + 7200, None)["users"] + active = {u["user"]: u["active_now"] for u in users} + assert active == {"s1": True, "s2": False, "t1": False} + + +def test_timeline_hour_and_minute(env: Env) -> None: + _fill(env) + q = env.query() + hours = q.timeline("s1", T0 - 86400, T0 + 86400, "hour")["rows"] + assert [(r["t"], r["requests"]) for r in hours] == [(T0, 2), (T0 + 3600, 1)] + minutes = q.timeline("s1", T0, T0 + 7200, "minute")["rows"] + assert [(r["t"], r["domain"]) for r in minutes] == [ + (T0, "a.example"), + (T0 + 60, "a.example"), + (T0 + 3600, "cdn.b.example"), + ] + with pytest.raises(ActivityError): + q.timeline("s1", T0, T0 + 3 * 86400, "minute") + + +def test_top_domains_with_users_and_category(env: Env) -> None: + _fill(env) + q = env.query() + top = q.domains(T0 - 3600, T0 + 7200, ["s1", "s2"])["domains"] + assert [(d["domain"], d["requests"], d["users"]) for d in top] == [ + ("a.example", 2, 1), + ("b.example", 1, 1), + ("cdn.b.example", 1, 1), + ] + assert top[1]["category"] == "porn" and top[1]["blocked"] == 1 + assert "secret.example" not in {d["domain"] for d in top} + # partial range from the minute table + assert [d["domain"] for d in q.domains(T0 + 3000, T0 + 4000, None)["domains"]] == [ + "cdn.b.example" + ] + + +def test_search_matches_subdomains_within_scope(env: Env) -> None: + _fill(env) + q = env.query() + hits = q.search("b.example", T0 - 3600, T0 + 7200, None)["users"] + assert {h["user"]: h["domains"] for h in hits} == {"s1": ["cdn.b.example"], "s2": ["b.example"]} + assert q.search("b.example", T0 - 3600, T0 + 7200, ["s2"])["total"] == 1 + # partial range excludes s1's visit at 11:00 + assert [h["user"] for h in q.search("b.example", T0, T0 + 600, None)["users"]] == ["s2"] + # LIKE wildcards are literal + assert q.search("%.example", T0 - 3600, T0 + 7200, None)["total"] == 0 + + +def test_export_csv(env: Env) -> None: + _fill(env) + text = "".join(env.query().export(T0 - 3600, T0 + 7200, ["s1"])) + rows = text.strip().splitlines() + assert rows[0] == "time,user,domain,requests,bytes,blocked,category" + assert len(rows) == 4 and all(",s1," in r for r in rows[1:]) + + +def test_limits(env: Env) -> None: + q = env.query() + with pytest.raises(ActivityError): + q.users(T0, T0 - 1, None) + with pytest.raises(ActivityError): + q.users(T0 - 400 * 86400, T0, None) + with pytest.raises(ActivityError): + q.users(T0, T0 + 60, ["u"] * (MAX_USERS + 1)) + with pytest.raises(ActivityError): + q.export(T0 - 40 * 86400, T0, None) + with pytest.raises(ActivityError): + q.search("bad domain", T0, T0 + 60, None) + + +def test_time_budget_stops_a_query(env: Env) -> None: + _fill(env) + q = Query(env.data, ZONE, [Source(env.inst.name, 7)], now=T0 + 3600, budget=Budget(-1)) + with pytest.raises(ActivityError, match="too large"): + q.users(T0 - 3600, T0 + 7200, None) + + +def test_queries_ignore_days_beyond_the_retention(env: Env) -> None: + _fill(env) + later = T0 + 10 * 86400 + q = Query(env.data, ZONE, [Source(env.inst.name, 7)], now=later) + assert q.users(T0 - 3600, later, None)["total"] == 0 From 4d97e6ed82c70ead94c59f67a55671fe1c04021e Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 10:53:55 +0100 Subject: [PATCH 03/45] feat(controlplane): activity log API with audit before every read GET/PUT /v1/instances/{name}/activity (switching on needs who confirmed the privacy notice; recorded in the definition), DELETE .../activity/data, and POST /v1/activity/{users,timeline,domains,search,export} restricted to the users list the caller sends. Every query is written to the activity audit log first (503 when it cannot be); GET /v1/activity/audit reads it. Deleting an instance deletes its activity data. --- controlplane/lmnsquid/activity_api.py | 395 ++++++++++++++++++++++++ controlplane/lmnsquid/api.py | 5 + controlplane/tests/test_activity_api.py | 305 ++++++++++++++++++ 3 files changed, 705 insertions(+) create mode 100644 controlplane/lmnsquid/activity_api.py create mode 100644 controlplane/tests/test_activity_api.py diff --git a/controlplane/lmnsquid/activity_api.py b/controlplane/lmnsquid/activity_api.py new file mode 100644 index 0000000..0dc58cd --- /dev/null +++ b/controlplane/lmnsquid/activity_api.py @@ -0,0 +1,395 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""REST endpoints of the activity log (ADR-023), registered by :func:`lmnsquid.api.create_app`. + +Settings per instance (``GET``/``PUT /v1/instances/{name}/activity``, ``DELETE …/activity/data``) +and the queries (``POST /v1/activity/{users,timeline,domains,search,export}``). Every query +carries ``audit`` (who asks, in which role, for what): it is written to the audit log before +anything is read, and a query whose audit line cannot be written is refused (503). The users a +query may see are the ``users`` list the caller sends (the WebUI computes it per person from +the AD); the proxy restricts every SQL statement to that list. Omitted = everyone, which only +the token holder (global administrator, CLI) can ask for. +""" + +from __future__ import annotations + +import datetime +import logging +import re +import time +from typing import Any, Callable, Literal +from zoneinfo import ZoneInfo + +from fastapi import FastAPI, HTTPException, status +from fastapi.responses import StreamingResponse +from pydantic import BaseModel, Field, field_validator + +from . import activity, activity_audit +from .activity import ActivityError +from .activity_query import MAX_USERS, Query, Source +from .config import Settings +from .models import ACTIVITY_RETENTION_MAX, Instance +from .store import Store + +audit = logging.getLogger("lmnsquid.audit") + +_TEXT_RE = re.compile(r"^[^\x00-\x1f\x7f]*$") +_USER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$") +_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{1,62}$") + + +def _printable(value: str | None, limit: int) -> str | None: + if value is None: + return None + if len(value) > limit or not _TEXT_RE.match(value): + raise ValueError(f"at most {limit} printable characters") + return value + + +class AuditInfo(BaseModel): + """Who asks: the WebUI sends the person, their role and what they selected (class …).""" + + actor: str = Field(min_length=1) + role: str | None = None + scope: str | None = None + + @field_validator("actor") + @classmethod + def _v_actor(cls, v: str) -> str: + return _printable(v, 128) or "" + + @field_validator("role") + @classmethod + def _v_role(cls, v: str | None) -> str | None: + return _printable(v, 64) + + @field_validator("scope") + @classmethod + def _v_scope(cls, v: str | None) -> str | None: + return _printable(v, 256) + + +class QueryBase(BaseModel): + since: int + until: int + instances: list[str] | None = None + users: list[str] | None = Field(default=None, max_length=MAX_USERS) + audit: AuditInfo + + @field_validator("instances") + @classmethod + def _v_instances(cls, v: list[str] | None) -> list[str] | None: + if v is not None: + for name in v: + if not _NAME_RE.match(name): + raise ValueError(f"invalid instance name {name!r}") + return v + + @field_validator("users") + @classmethod + def _v_users(cls, v: list[str] | None) -> list[str] | None: + if v is not None: + for name in v: + if not _USER_RE.match(name): + raise ValueError(f"invalid user name {name[:70]!r}") + return v + + +class UsersQuery(QueryBase): + limit: int = 100 + offset: int = Field(default=0, ge=0) + sort: Literal["requests", "blocked", "last", "name", "bytes"] = "requests" + with_domains: bool = True + + +class TimelineQuery(QueryBase): + user: str + resolution: Literal["hour", "minute"] = "hour" + limit: int = 1000 + offset: int = Field(default=0, ge=0) + + @field_validator("user") + @classmethod + def _v_user(cls, v: str) -> str: + if not _USER_RE.match(v): + raise ValueError("invalid user name") + return v + + +class DomainsQuery(QueryBase): + limit: int = 50 + + +class SearchQuery(QueryBase): + domain: str = Field(min_length=1, max_length=253) + limit: int = 200 + + +class ActivitySettings(BaseModel): + """Body of ``PUT /v1/instances/{name}/activity``.""" + + enabled: bool + retention_days: int | None = None + # Switching on needs the confirmed privacy notice: the person who confirmed it. + ack_by: str | None = None + # Switching off: delete the data at once (else it expires with the retention). + delete_data: bool = False + actor: str = "api" + + @field_validator("retention_days") + @classmethod + def _v_retention(cls, v: int | None) -> int | None: + if v is not None and not 1 <= v <= ACTIVITY_RETENTION_MAX: + raise ValueError(f"retention_days must be between 1 and {ACTIVITY_RETENTION_MAX}") + return v + + @field_validator("ack_by") + @classmethod + def _v_ack(cls, v: str | None) -> str | None: + return _printable(v, 128) + + @field_validator("actor") + @classmethod + def _v_actor(cls, v: str) -> str: + return _printable(v, 128) or "api" + + +def register( + app: FastAPI, + settings: Settings, + store: Store, + auth: list[Any], + require: Callable[[str], Instance], + apply: Callable[[Instance], dict[str, Any]], + container_status: Callable[[str], dict[str, Any]], +) -> None: + zone = ZoneInfo(settings.filter_timezone) + audit_path = activity_audit.audit_dir(settings.activity_dir) + + def _settings_view(inst: Instance) -> dict[str, Any]: + return { + "name": inst.name, + "school": inst.school, + "role": inst.role, + "enabled": inst.activity_log_enabled, + "retention_days": inst.activity_retention_days, + "ack_by": inst.activity_ack_by, + "ack_at": inst.activity_ack_at, + "usage": activity.usage(settings.activity_dir, settings.activity_spool_dir, inst.name), + } + + def _audit(entry: dict[str, Any]) -> None: + try: + activity_audit.record(audit_path, zone, entry) + except OSError as exc: + audit.error("activity audit log not writable: %s", exc) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="the activity audit log cannot be written; no data is read", + ) from exc + + def _sources(names: list[str] | None) -> list[Source]: + known = {inst.name: inst for inst in store.list()} + if names is None: + chosen = list(known.values()) + else: + missing = [n for n in names if n not in known] + if missing: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"instance(s) not found: {', '.join(missing)}", + ) + chosen = [known[n] for n in names] + return [Source(i.name, i.activity_retention_days) for i in chosen] + + def _query_audit(kind: str, body: QueryBase, sources: list[Source], **extra: Any) -> None: + users = body.users + _audit( + { + "action": kind, + "actor": body.audit.actor, + "role": body.audit.role, + "scope": body.audit.scope, + "since": body.since, + "until": body.until, + "instances": [s.name for s in sources], + "users_count": None if users is None else len(users), + # whose data: the list itself, up to 200 names (a class, a project) + "users": None if users is None else sorted(users)[:200], + **extra, + } + ) + + def _run(call: Callable[[], dict[str, Any]]) -> dict[str, Any]: + try: + return call() + except ActivityError as exc: + raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) + + # ------------------------------------------------------------- settings + @app.get("/v1/activity", dependencies=auth) + def activity_overview() -> dict[str, Any]: + return { + "timezone": settings.filter_timezone, + "audit_retention_days": settings.activity_audit_retention_days, + "instances": [_settings_view(inst) for inst in store.list()], + } + + @app.get("/v1/instances/{name}/activity", dependencies=auth) + def get_activity(name: str) -> dict[str, Any]: + inst = require(name) + view = _settings_view(inst) + try: + state = container_status(name) + view["image_capable"] = state.get("activity_capable") if state.get("exists") else None + except Exception: # noqa: BLE001 - the settings stay readable without Docker + view["image_capable"] = None + return view + + @app.put("/v1/instances/{name}/activity", dependencies=auth) + def put_activity(name: str, body: ActivitySettings) -> dict[str, Any]: + inst = require(name) + updates: dict[str, Any] = {} + switching_on = body.enabled and not inst.activity_log_enabled + if switching_on: + if not body.ack_by: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="switching the activity log on needs the confirmed privacy notice " + "(ack_by: who confirmed it)", + ) + updates["activity_ack_by"] = body.ack_by + updates["activity_ack_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat( + timespec="seconds" + ) + updates["activity_log_enabled"] = body.enabled + if body.retention_days is not None: + updates["activity_retention_days"] = body.retention_days + merged = Instance.model_validate( + {**inst.model_dump(exclude={"name", "container_name"}), **updates} + ) + _audit( + { + "action": "settings", + "actor": body.actor, + "instance": name, + "enabled": merged.activity_log_enabled, + "retention_days": merged.activity_retention_days, + "ack_by": body.ack_by if switching_on else None, + "delete_data": bool(body.delete_data and not body.enabled), + } + ) + if merged.activity_log_enabled != inst.activity_log_enabled: + # the container gets (or loses) the spool and the receiver: replaced, health-gated + result: dict[str, Any] | None = apply(merged) + else: + store.put(merged) + result = None + deleted = None + if body.delete_data and not merged.activity_log_enabled: + deleted = activity.delete_data(settings.activity_dir, settings.activity_spool_dir, name) + else: + activity.apply_retention( + settings.activity_dir, name, merged.activity_retention_days, zone + ) + audit.info( + "activity settings name=%s enabled=%s retention=%d deleted=%s by=%s", + name, + merged.activity_log_enabled, + merged.activity_retention_days, + deleted, + body.actor, + ) + view = _settings_view(merged) + view["status"] = result + view["deleted_days"] = deleted + return view + + @app.delete("/v1/instances/{name}/activity/data", dependencies=auth) + def delete_activity_data(name: str, actor: str = "api") -> dict[str, Any]: + require(name) + try: + actor = _printable(actor, 128) or "api" + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + _audit({"action": "delete_data", "actor": actor, "instance": name}) + deleted = activity.delete_data(settings.activity_dir, settings.activity_spool_dir, name) + audit.info("activity data deleted name=%s days=%d by=%s", name, deleted, actor) + return {"name": name, "deleted_days": deleted} + + # -------------------------------------------------------------- queries + def _query(sources: list[Source]) -> Query: + return Query(settings.activity_dir, zone, sources) + + @app.post("/v1/activity/users", dependencies=auth) + def query_users(body: UsersQuery) -> dict[str, Any]: + sources = _sources(body.instances) + _query_audit("users", body, sources) + return _run( + lambda: _query(sources).users( + body.since, + body.until, + body.users, + body.limit, + body.offset, + body.sort, + body.with_domains, + ) + ) + + @app.post("/v1/activity/timeline", dependencies=auth) + def query_timeline(body: TimelineQuery) -> dict[str, Any]: + sources = _sources(body.instances) + if body.users is not None and body.user.lower() not in {u.lower() for u in body.users}: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="user not in scope") + _query_audit("timeline", body, sources, user=body.user, resolution=body.resolution) + return _run( + lambda: _query(sources).timeline( + body.user, body.since, body.until, body.resolution, body.limit, body.offset + ) + ) + + @app.post("/v1/activity/domains", dependencies=auth) + def query_domains(body: DomainsQuery) -> dict[str, Any]: + sources = _sources(body.instances) + _query_audit("domains", body, sources) + return _run(lambda: _query(sources).domains(body.since, body.until, body.users, body.limit)) + + @app.post("/v1/activity/search", dependencies=auth) + def query_search(body: SearchQuery) -> dict[str, Any]: + sources = _sources(body.instances) + _query_audit("search", body, sources, domain=body.domain) + return _run( + lambda: _query(sources).search( + body.domain, body.since, body.until, body.users, body.limit + ) + ) + + @app.post("/v1/activity/export", dependencies=auth) + def query_export(body: QueryBase) -> StreamingResponse: + sources = _sources(body.instances) + try: + lines = _query(sources).export(body.since, body.until, body.users) + except ActivityError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + _query_audit("export", body, sources) + return StreamingResponse(lines, media_type="text/csv; charset=utf-8") + + @app.get("/v1/activity/audit", dependencies=auth) + def read_audit( + since: int | None = None, + until: int | None = None, + actor: str | None = None, + limit: int = 100, + offset: int = 0, + ) -> dict[str, Any]: + now = int(time.time()) + until = until if until is not None else now + 1 + since = since if since is not None else until - 7 * 86400 + if until <= since or until - since > 3660 * 86400: + raise HTTPException(status_code=422, detail="invalid range") + if not 1 <= limit <= 1000 or offset < 0: + raise HTTPException(status_code=422, detail="limit 1-1000, offset >= 0") + if actor is not None and (len(actor) > 128 or not _TEXT_RE.match(actor)): + raise HTTPException(status_code=422, detail="invalid actor") + return activity_audit.read(audit_path, zone, since, until, actor, limit, offset) diff --git a/controlplane/lmnsquid/api.py b/controlplane/lmnsquid/api.py index fe43d1b..ba3f4fe 100644 --- a/controlplane/lmnsquid/api.py +++ b/controlplane/lmnsquid/api.py @@ -18,6 +18,7 @@ from fastapi.responses import JSONResponse, Response from pydantic import ValidationError +from . import activity, activity_api from . import catalog as catalog_mod from .blocklist import Blocklist, noauth_list from .config import Settings @@ -505,6 +506,9 @@ def delete_instance(name: str, keep_logs: bool = False) -> None: """ _require(name) reconciler.remove(name, keep_logs=keep_logs) + # The activity log's day files and spool go with the instance, also with keep_logs + # (they are derived from the access log, which keep_logs is about; ADR-023). + activity.purge_instance(settings.activity_dir, settings.activity_spool_dir, name) audit.info("delete instance name=%s keep_logs=%s", name, keep_logs) # ---------------------------------------------------------------- blocklist @@ -836,4 +840,5 @@ def rollback_instance(name: str) -> dict[str, Any]: except FileNotFoundError as exc: raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc + activity_api.register(app, settings, store, auth, _require, _apply, lambda n: docker.status(n)) return app diff --git a/controlplane/tests/test_activity_api.py b/controlplane/tests/test_activity_api.py new file mode 100644 index 0000000..b346d83 --- /dev/null +++ b/controlplane/tests/test_activity_api.py @@ -0,0 +1,305 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Activity log API (ADR-023): switching on needs the confirmed notice, the container gets the +spool only while on, every query is audited before it reads, scope by user list, limits, +deletion with the instance, an upgrade changes nothing.""" + +from __future__ import annotations + +import json +import time +from pathlib import Path +from typing import Any + +import yaml +from starlette.testclient import TestClient + +from lmnsquid import activity +from lmnsquid.config import Settings +from lmnsquid.models import Instance +from lmnsquid.store import Store + +NAME = "default-school-teachers" + + +def _create(client: TestClient, auth: dict[str, str], data: dict[str, Any]) -> None: + r = client.post("/v1/instances", json=data, headers=auth) + assert r.status_code == 201, r.text + + +def _enable(client: TestClient, auth: dict[str, str], **extra: Any) -> Any: + body = {"enabled": True, "ack_by": "globaladmin", "actor": "globaladmin", **extra} + return client.put(f"/v1/instances/{NAME}/activity", json=body, headers=auth) + + +def _seed(settings: Settings, now: int) -> None: + spool = activity.ensure_spool(settings.activity_spool_dir, NAME) + (spool / f"act-{now:010d}-aaaa0000-000001.log").write_text( + f"{now} s1@EX.LAN a.example 200 TCP_TUNNEL 10 -\n" + f"{now} s2@EX.LAN b.example 403 TCP_DENIED 10 porn\n" + f"{now} t1@EX.LAN c.example 200 TCP_TUNNEL 10 -\n" + ) + inst = Store(settings.instances_dir).get(NAME) + assert inst is not None + from zoneinfo import ZoneInfo + + activity.collect_instance( + inst, settings.activity_dir, settings.activity_spool_dir, ZoneInfo("Europe/Berlin") + ) + + +def _audit_lines(settings: Settings) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + for path in sorted((Path(settings.activity_dir) / "_audit").glob("*.jsonl")): + out += [json.loads(x) for x in path.read_text().splitlines()] + return out + + +def _q(now: int, **extra: Any) -> dict[str, Any]: + return { + "since": now - 3600, + "until": now + 60, + "audit": {"actor": "lehrer1", "role": "teacher", "scope": "class 5a"}, + **extra, + } + + +def test_off_by_default_and_no_change_to_the_container( + client: TestClient, auth_headers: dict[str, str], instance_data: dict[str, Any], docker: Any +) -> None: + _create(client, auth_headers, instance_data) + r = client.get(f"/v1/instances/{NAME}/activity", headers=auth_headers) + assert r.status_code == 200 + assert r.json()["enabled"] is False and r.json()["retention_days"] == 7 + assert "ACTIVITY_LOG_ENABLED" not in docker.containers[NAME]["env"] + + +def test_upgrade_reads_old_definitions_unchanged(settings: Settings, instance_data: dict) -> None: + Path(settings.instances_dir).mkdir(parents=True) + (Path(settings.instances_dir) / f"{NAME}.yaml").write_text(yaml.safe_dump(instance_data)) + inst = Store(settings.instances_dir).get(NAME) + assert inst is not None and inst.activity_log_enabled is False + + +def test_switching_on_needs_the_confirmed_notice( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + docker: Any, + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + r = client.put(f"/v1/instances/{NAME}/activity", json={"enabled": True}, headers=auth_headers) + assert r.status_code == 422 + assert "privacy notice" in r.text + # a definition sent with the flag but without the notice is refused as well + bad = {**instance_data, "role": "students", "activity_log_enabled": True} + assert client.post("/v1/instances", json=bad, headers=auth_headers).status_code == 422 + r = _enable(client, auth_headers, retention_days=14) + assert r.status_code == 200, r.text + body = r.json() + assert body["enabled"] and body["ack_by"] == "globaladmin" and body["ack_at"] + assert body["retention_days"] == 14 + assert docker.containers[NAME]["env"]["ACTIVITY_LOG_ENABLED"] == "1" + assert [e["action"] for e in _audit_lines(settings)] == ["settings"] + + +def test_retention_change_does_not_replace_the_container( + client: TestClient, auth_headers: dict[str, str], instance_data: dict[str, Any], docker: Any +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + calls = len(docker.ensure_calls) + r = client.put( + f"/v1/instances/{NAME}/activity", + json={"enabled": True, "retention_days": 30}, + headers=auth_headers, + ) + assert r.status_code == 200 and r.json()["retention_days"] == 30 + assert len(docker.ensure_calls) == calls + assert r.json()["ack_by"] == "globaladmin", "the first confirmation is kept" + r = client.put( + f"/v1/instances/{NAME}/activity", + json={"enabled": True, "retention_days": 366}, + headers=auth_headers, + ) + assert r.status_code == 422 + + +def test_switching_off_can_delete_the_data( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + docker: Any, + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + now = int(time.time()) + _seed(settings, now) + assert activity.usage(settings.activity_dir, settings.activity_spool_dir, NAME)["days"] == 1 + r = client.put( + f"/v1/instances/{NAME}/activity", + json={"enabled": False, "delete_data": True}, + headers=auth_headers, + ) + assert r.status_code == 200 and r.json()["deleted_days"] == 1 + assert "ACTIVITY_LOG_ENABLED" not in docker.containers[NAME]["env"] + assert activity.usage(settings.activity_dir, settings.activity_spool_dir, NAME)["days"] == 0 + + +def test_queries_are_scoped_and_audited( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + now = int(time.time()) + _seed(settings, now) + r = client.post("/v1/activity/users", json=_q(now, users=["s1", "s2"]), headers=auth_headers) + assert r.status_code == 200, r.text + assert {u["user"] for u in r.json()["users"]} == {"s1", "s2"} + r = client.post("/v1/activity/domains", json=_q(now, users=["s1", "s2"]), headers=auth_headers) + assert "c.example" not in {d["domain"] for d in r.json()["domains"]} + r = client.post( + "/v1/activity/search", json=_q(now, users=["s1"], domain="example"), headers=auth_headers + ) + assert [u["user"] for u in r.json()["users"]] == ["s1"] + r = client.post( + "/v1/activity/timeline", json=_q(now, users=["s1"], user="t1"), headers=auth_headers + ) + assert r.status_code == 403 + r = client.post( + "/v1/activity/timeline", + json=_q(now, users=["s1"], user="s1", resolution="minute"), + headers=auth_headers, + ) + assert r.status_code == 200 and r.json()["rows"][0]["domain"] == "a.example" + r = client.post("/v1/activity/export", json=_q(now, users=["s2"]), headers=auth_headers) + assert r.status_code == 200 and "b.example" in r.text and "a.example" not in r.text + lines = [e for e in _audit_lines(settings) if e["action"] != "settings"] + assert [e["action"] for e in lines] == ["users", "domains", "search", "timeline", "export"] + assert all(e["actor"] == "lehrer1" and e["scope"] == "class 5a" for e in lines) + assert lines[0]["users"] == ["s1", "s2"] and lines[2]["domain"] == "example" + assert lines[3]["user"] == "s1" + audit = client.get("/v1/activity/audit", params={"actor": "lehrer1"}, headers=auth_headers) + assert audit.status_code == 200 and audit.json()["total"] == 5 + assert audit.json()["entries"][0]["action"] == "export", "newest first" + + +def test_unwritable_audit_log_refuses_the_query( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + Path(settings.activity_dir).mkdir(parents=True, exist_ok=True) + (Path(settings.activity_dir) / "_audit").write_text("not a directory") + r = client.post("/v1/activity/users", json=_q(int(time.time())), headers=auth_headers) + assert r.status_code == 503 + + +def test_query_input_is_checked( + client: TestClient, auth_headers: dict[str, str], instance_data: dict[str, Any] +) -> None: + _create(client, auth_headers, instance_data) + now = int(time.time()) + assert ( + client.post( + "/v1/activity/users", json={"since": now - 60, "until": now}, headers=auth_headers + ).status_code + == 422 + ) # no audit + assert ( + client.post( + "/v1/activity/users", json=_q(now, users=["../x"]), headers=auth_headers + ).status_code + == 422 + ) + assert ( + client.post( + "/v1/activity/users", json=_q(now, instances=["nope-x"]), headers=auth_headers + ).status_code + == 404 + ) + r = client.post( + "/v1/activity/users", json={**_q(now), "since": now - 400 * 86400}, headers=auth_headers + ) + assert r.status_code == 422 and "range too long" in r.text + bad_actor = _q(now) + bad_actor["audit"]["actor"] = "x\ny" + assert ( + client.post("/v1/activity/users", json=bad_actor, headers=auth_headers).status_code == 422 + ) + + +def test_without_token_nothing(client: TestClient) -> None: + assert client.post("/v1/activity/users", json={}).status_code == 401 + assert ( + client.get("/v1/activity/audit", headers={"Authorization": "Bearer x"}).status_code == 403 + ) + + +def test_deleting_the_instance_deletes_its_activity( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + _seed(settings, int(time.time())) + r = client.delete(f"/v1/instances/{NAME}", params={"keep_logs": True}, headers=auth_headers) + assert r.status_code == 204 + assert not (Path(settings.activity_dir) / NAME).exists() + assert not (Path(settings.activity_spool_dir) / NAME).exists() + + +def test_patch_cannot_switch_it_on( + client: TestClient, auth_headers: dict[str, str], instance_data: dict[str, Any], docker: Any +) -> None: + _create(client, auth_headers, instance_data) + r = client.patch( + f"/v1/instances/{NAME}", json={"activity_log_enabled": True}, headers=auth_headers + ) + assert r.status_code == 200 + assert "ACTIVITY_LOG_ENABLED" not in docker.containers[NAME]["env"] + + +def test_spec_gets_the_spool_only_while_on(tmp_path: Path) -> None: + from test_docker_service import _inst, _service + + ds = _service(tmp_path) + ds.activity_spool_dir = str(tmp_path / "spool") + off = ds.spec_for(_inst()) + assert len(off["volumes"]) == 5 and "ACTIVITY_LOG_ENABLED" not in off["environment"] + on = ds.spec_for(_inst(activity_log_enabled=True, activity_ack_by="a", activity_ack_at="b")) + assert on["environment"]["ACTIVITY_LOG_ENABLED"] == "1" + assert on["volumes"][str(tmp_path / "spool" / "s-teachers")] == { + "bind": "/var/log/lmnsquid-activity", + "mode": "rw", + } + # retention and the confirmation are not part of the container + assert ds.fingerprint(on) == ds.fingerprint( + ds.spec_for( + _inst( + activity_log_enabled=True, + activity_ack_by="x", + activity_ack_at="y", + activity_retention_days=30, + ) + ) + ) + assert ds.fingerprint(off) == ds.fingerprint( + ds.spec_for( + Instance( + **{ + **_inst().model_dump(exclude={"name", "container_name"}), + "activity_retention_days": 99, + } + ) + ) + ) From d7ef5559fbb17ef5d80bab42107a61094b0cc54c Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 10:53:56 +0100 Subject: [PATCH 04/45] feat(cli): lmnsquid activity status/enable/disable/retention/delete-data/users/timeline/domains/search/export/audit --- controlplane/lmnsquid/cli.py | 245 +++++++++++++++++++++++++++++++++ controlplane/tests/test_cli.py | 44 ++++++ 2 files changed, 289 insertions(+) diff --git a/controlplane/lmnsquid/cli.py b/controlplane/lmnsquid/cli.py index 1cf46ea..178091c 100644 --- a/controlplane/lmnsquid/cli.py +++ b/controlplane/lmnsquid/cli.py @@ -951,6 +951,251 @@ def tls_enable( typer.echo(f"TLS listener set in {path}: systemctl restart linuxmuster-squid") +# ------------------------------------------------------------------ activity log (ADR-023) +activity_app = typer.Typer( + help="Activity log: who visited which domain, per minute (off by default, per instance).", + no_args_is_help=True, +) +app.add_typer(activity_app, name="activity") + +_RANGES = {"hour": 3600, "today": None, "7d": 7 * 86400, "30d": 30 * 86400} + + +def _actor() -> str: + try: + import getpass + + return f"cli:{getpass.getuser()}" + except Exception: # noqa: BLE001 - no passwd entry in a container + return "cli" + + +def activity_range( + range_: str, since: Optional[int], until: Optional[int], zone: str +) -> tuple[int, int]: + """(since, until) from --since/--until (epoch seconds) or a named range in ``zone``.""" + now = int(time.time()) + if since is not None or until is not None: + end = until if until is not None else now + 1 + start = since if since is not None else end - 86400 + return start, end + if range_ == "today": + import datetime + from zoneinfo import ZoneInfo + + local = datetime.datetime.now(ZoneInfo(zone)) + return int(local.replace(hour=0, minute=0, second=0, microsecond=0).timestamp()), now + 1 + if range_ not in _RANGES: + raise typer.BadParameter(f"range must be one of {', '.join(_RANGES)}") + return now - int(_RANGES[range_] or 0), now + 1 + + +def _query_body( + range_: str, + since: Optional[int], + until: Optional[int], + users: list[str], + instance: list[str], + scope: Optional[str], +) -> dict[str, Any]: + zone = load_settings().filter_timezone + start, end = activity_range(range_, since, until, zone) + return { + "since": start, + "until": end, + "users": users or None, + "instances": instance or None, + "audit": {"actor": _actor(), "role": "cli", "scope": scope}, + } + + +_RANGE_OPT = typer.Option("today", "--range", help="hour | today | 7d | 30d") +_SINCE_OPT = typer.Option(None, help="start, epoch seconds (instead of --range)") +_UNTIL_OPT = typer.Option(None, help="end, epoch seconds (exclusive)") +_USER_OPT = typer.Option([], "--user", help="restrict to this user; repeat") +_INST_OPT = typer.Option([], "--instance", help="read only this instance; repeat") +_SCOPE_OPT = typer.Option(None, help="what the query is for (written to the audit log)") + + +@activity_app.command("status") +def activity_status() -> None: + """Activity log settings and stored days of every instance.""" + with _get_client() as c: + _emit(c.get("/v1/activity")) + + +@activity_app.command("enable") +def activity_enable( + name: str, + ack_by: str = typer.Option( + ..., + help="who confirmed the privacy notice (legal basis, informing the people concerned, " + "staff council for employees; docs/operations.md)", + ), + retention_days: Optional[int] = typer.Option(None, help="days to keep (1-365, default 7)"), +) -> None: + """Switch the activity log of an instance on (replaces its container, health-gated).""" + body: dict[str, Any] = {"enabled": True, "ack_by": ack_by, "actor": _actor()} + if retention_days is not None: + body["retention_days"] = retention_days + with _get_client() as c: + _emit(c.put(f"/v1/instances/{quote(name, safe='')}/activity", json=body)) + + +@activity_app.command("disable") +def activity_disable( + name: str, + delete_data: bool = typer.Option(False, help="delete the stored data at once"), +) -> None: + """Switch the activity log of an instance off (replaces its container).""" + body = {"enabled": False, "delete_data": delete_data, "actor": _actor()} + with _get_client() as c: + _emit(c.put(f"/v1/instances/{quote(name, safe='')}/activity", json=body)) + + +@activity_app.command("retention") +def activity_retention(name: str, days: int) -> None: + """Set the days the activity log of an instance is kept (1-365).""" + with _get_client() as c: + current = c.get(f"/v1/instances/{quote(name, safe='')}/activity") + if current.status_code >= 400: + _emit(current) + body = {"enabled": current.json()["enabled"], "retention_days": days, "actor": _actor()} + _emit(c.put(f"/v1/instances/{quote(name, safe='')}/activity", json=body)) + + +@activity_app.command("delete-data") +def activity_delete_data(name: str) -> None: + """Delete the stored activity data of an instance now.""" + with _get_client() as c: + _emit( + c.delete( + f"/v1/instances/{quote(name, safe='')}/activity/data", params={"actor": _actor()} + ) + ) + + +@activity_app.command("users") +def activity_users( + range_: str = _RANGE_OPT, + since: Optional[int] = _SINCE_OPT, + until: Optional[int] = _UNTIL_OPT, + user: list[str] = _USER_OPT, + instance: list[str] = _INST_OPT, + scope: Optional[str] = _SCOPE_OPT, + sort: str = typer.Option("requests", help="requests | blocked | last | name | bytes"), + limit: int = typer.Option(100), + offset: int = typer.Option(0), +) -> None: + """Users active in the range: requests, blocked, domains, last seen.""" + body = _query_body(range_, since, until, user, instance, scope) + body.update({"sort": sort, "limit": limit, "offset": offset}) + with _get_client() as c: + _emit(c.post("/v1/activity/users", json=body)) + + +@activity_app.command("timeline") +def activity_timeline( + name: str = typer.Argument(..., help="user (sAMAccountName)"), + range_: str = _RANGE_OPT, + since: Optional[int] = _SINCE_OPT, + until: Optional[int] = _UNTIL_OPT, + instance: list[str] = _INST_OPT, + scope: Optional[str] = _SCOPE_OPT, + minute: bool = typer.Option(False, help="per minute and domain (at most 2 days)"), + limit: int = typer.Option(1000), + offset: int = typer.Option(0), +) -> None: + """One user's activity per hour, or per minute and domain.""" + body = _query_body(range_, since, until, [], instance, scope) + body.update( + { + "user": name, + "resolution": "minute" if minute else "hour", + "limit": limit, + "offset": offset, + } + ) + with _get_client() as c: + _emit(c.post("/v1/activity/timeline", json=body)) + + +@activity_app.command("domains") +def activity_domains( + range_: str = _RANGE_OPT, + since: Optional[int] = _SINCE_OPT, + until: Optional[int] = _UNTIL_OPT, + user: list[str] = _USER_OPT, + instance: list[str] = _INST_OPT, + scope: Optional[str] = _SCOPE_OPT, + limit: int = typer.Option(50), +) -> None: + """Top domains (of the given users, or of everyone).""" + body = _query_body(range_, since, until, user, instance, scope) + body["limit"] = limit + with _get_client() as c: + _emit(c.post("/v1/activity/domains", json=body)) + + +@activity_app.command("search") +def activity_search( + domain: str, + range_: str = _RANGE_OPT, + since: Optional[int] = _SINCE_OPT, + until: Optional[int] = _UNTIL_OPT, + user: list[str] = _USER_OPT, + instance: list[str] = _INST_OPT, + scope: Optional[str] = _SCOPE_OPT, + limit: int = typer.Option(200), +) -> None: + """Who was on DOMAIN (or a subdomain of it).""" + body = _query_body(range_, since, until, user, instance, scope) + body.update({"domain": domain, "limit": limit}) + with _get_client() as c: + _emit(c.post("/v1/activity/search", json=body)) + + +@activity_app.command("export") +def activity_export( + range_: str = _RANGE_OPT, + since: Optional[int] = _SINCE_OPT, + until: Optional[int] = _UNTIL_OPT, + user: list[str] = _USER_OPT, + instance: list[str] = _INST_OPT, + scope: Optional[str] = _SCOPE_OPT, +) -> None: + """CSV per minute, user and domain to stdout (at most 31 days).""" + body = _query_body(range_, since, until, user, instance, scope) + with _get_client() as c: + with c.stream("POST", "/v1/activity/export", json=body) as resp: + if resp.status_code >= 400: + resp.read() + _emit(resp) + for chunk in resp.iter_text(): + typer.echo(chunk, nl=False) + + +@activity_app.command("audit") +def activity_audit( + days: int = typer.Option(7, help="the last N days"), + actor: Optional[str] = typer.Option(None, help="only this person"), + limit: int = typer.Option(100), + offset: int = typer.Option(0), +) -> None: + """Who read activity data (newest first).""" + now = int(time.time()) + params: dict[str, Any] = { + "since": now - days * 86400, + "until": now + 1, + "limit": limit, + "offset": offset, + } + if actor: + params["actor"] = actor + with _get_client() as c: + _emit(c.get("/v1/activity/audit", params=params)) + + def main() -> None: app() diff --git a/controlplane/tests/test_cli.py b/controlplane/tests/test_cli.py index ed1419b..ba60fde 100644 --- a/controlplane/tests/test_cli.py +++ b/controlplane/tests/test_cli.py @@ -329,3 +329,47 @@ def test_cli_prints_the_warnings( ) assert r.exit_code == 0, r.output assert "warning: Werbung und Tracking (Pro):" in r.output + + +def test_cli_activity( + patch_client: None, + monkeypatch: pytest.MonkeyPatch, + settings: Any, + instance_data: dict[str, Any], +) -> None: + """Enable with the confirmation, query (audited as the CLI user), disable with deletion.""" + monkeypatch.setattr(cli, "load_settings", lambda: settings) + name = f"{instance_data['school']}-{instance_data['role']}" + with cli._get_client() as c: + assert c.post("/v1/instances", json=instance_data).status_code == 201 + r = runner.invoke(cli.app, ["activity", "enable", name]) + assert r.exit_code != 0, "the confirmation is required" + r = runner.invoke( + cli.app, ["activity", "enable", name, "--ack-by", "admin", "--retention-days", "3"] + ) + assert r.exit_code == 0, r.output + assert '"retention_days": 3' in r.output + r = runner.invoke(cli.app, ["activity", "users", "--range", "7d", "--scope", "check"]) + assert r.exit_code == 0 and '"total": 0' in r.output, r.output + r = runner.invoke(cli.app, ["activity", "timeline", "s1", "--minute", "--range", "hour"]) + assert r.exit_code == 0, r.output + r = runner.invoke(cli.app, ["activity", "export", "--range", "hour"]) + assert r.exit_code == 0 and r.output.startswith("time,user,domain"), r.output + r = runner.invoke(cli.app, ["activity", "users", "--range", "year"]) + assert r.exit_code != 0 + r = runner.invoke(cli.app, ["activity", "audit"]) + assert r.exit_code == 0 and '"scope": "check"' in r.output and '"actor": "cli:' in r.output + r = runner.invoke(cli.app, ["activity", "retention", name, "10"]) + assert r.exit_code == 0 and '"retention_days": 10' in r.output + r = runner.invoke(cli.app, ["activity", "disable", name, "--delete-data"]) + assert r.exit_code == 0 and '"enabled": false' in r.output + + +def test_activity_range_today_starts_at_local_midnight() -> None: + import datetime + from zoneinfo import ZoneInfo + + start, end = cli.activity_range("today", None, None, "Europe/Berlin") + local = datetime.datetime.fromtimestamp(start, ZoneInfo("Europe/Berlin")) + assert (local.hour, local.minute) == (0, 0) and end > start + assert cli.activity_range("hour", 5, 10, "UTC") == (5, 10) From 877cdbd4f3494a73498a08c055aef486b1ce474a Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 10:54:37 +0100 Subject: [PATCH 05/45] build(debian): activity collector timer (every 30 s), spool and data directories, purge The spool lives in /var/spool/linuxmuster-squid (its files belong to the containers' proxy user, and the configure resets the ownership of /var/lib/linuxmuster-squid); the day files in /var/lib/linuxmuster-squid/ activity (0700). The timer is enabled like the catalog timer and does nothing while no instance has the log on. Purge removes both. --- debian/linuxmuster-squid.install | 2 ++ debian/linuxmuster-squid.postinst | 27 ++++++++++++--- debian/linuxmuster-squid.postrm | 6 ++-- debian/linuxmuster-squid.prerm | 2 ++ .../linuxmuster-squid-activity.service | 34 +++++++++++++++++++ .../systemd/linuxmuster-squid-activity.timer | 12 +++++++ packaging/systemd/linuxmuster-squid.service | 2 +- 7 files changed, 78 insertions(+), 7 deletions(-) create mode 100644 packaging/systemd/linuxmuster-squid-activity.service create mode 100644 packaging/systemd/linuxmuster-squid-activity.timer diff --git a/debian/linuxmuster-squid.install b/debian/linuxmuster-squid.install index 7514219..f4f7d1e 100644 --- a/debian/linuxmuster-squid.install +++ b/debian/linuxmuster-squid.install @@ -7,6 +7,8 @@ packaging/systemd/linuxmuster-squid.service lib/systemd/system/ packaging/systemd/linuxmuster-squid-catalog.service lib/systemd/system/ packaging/systemd/linuxmuster-squid-catalog.timer lib/systemd/system/ +packaging/systemd/linuxmuster-squid-activity.service lib/systemd/system/ +packaging/systemd/linuxmuster-squid-activity.timer lib/systemd/system/ # Admin scripts the docs refer to (run on the DC / from cron), so an admin with only the # .deb has them: docs/install.md, docs/keytab-and-dns.md, docs/operations.md. scripts/provision-keytab.sh usr/share/linuxmuster-squid/scripts/ diff --git a/debian/linuxmuster-squid.postinst b/debian/linuxmuster-squid.postinst index 14ccb64..f051da0 100644 --- a/debian/linuxmuster-squid.postinst +++ b/debian/linuxmuster-squid.postinst @@ -19,6 +19,13 @@ mkdir -p /etc/linuxmuster-squid/secrets /etc/linuxmuster-squid/blocklists \ # it as user proxy (ADR-022). chmod 755 /var/lib/linuxmuster-squid /var/lib/linuxmuster-squid/catalog +# Activity log (ADR-023): the day files (private) and the spool the containers write into. The +# spool is outside /var/lib/linuxmuster-squid, whose ownership is reset below on every +# configure: the files in it belong to squid's proxy user of the containers. +mkdir -p /var/lib/linuxmuster-squid/activity /var/spool/linuxmuster-squid/activity +chown lmnsquid:lmnsquid /var/spool/linuxmuster-squid /var/spool/linuxmuster-squid/activity +chmod 750 /var/spool/linuxmuster-squid /var/spool/linuxmuster-squid/activity + # Config with a random API token (only if it does not exist yet) CFG=/etc/linuxmuster-squid/config.yml if [ ! -f "$CFG" ]; then @@ -83,7 +90,7 @@ INST_DIR=/var/lib/linuxmuster-squid/instances # caught by the 7.3.3 release gate). Running first, the chown also repairs root-owned # files those versions left in the repository, before git touches it as lmnsquid below. chown -R lmnsquid:lmnsquid /etc/linuxmuster-squid /var/lib/linuxmuster-squid -chmod 700 /etc/linuxmuster-squid/secrets "$TLS_DIR" +chmod 700 /etc/linuxmuster-squid/secrets "$TLS_DIR" /var/lib/linuxmuster-squid/activity # Git change log of the instance definitions (docs/operations.md). Every git command runs # AS lmnsquid, the owner of the repository and the user the service commits as, so git @@ -178,11 +185,23 @@ else deb-systemd-helper update-state "$TIMER" >/dev/null || true fi +# The activity log's collector (ADR-023), by the same rules. It reads nothing while no instance +# has the log on (the log itself is off by default). +ACTIVITY_TIMER=linuxmuster-squid-activity.timer +deb-systemd-helper unmask "$ACTIVITY_TIMER" >/dev/null || true +if deb-systemd-helper --quiet was-enabled "$ACTIVITY_TIMER"; then + deb-systemd-helper enable "$ACTIVITY_TIMER" >/dev/null || true +else + deb-systemd-helper update-state "$ACTIVITY_TIMER" >/dev/null || true +fi + if [ -d /run/systemd/system ]; then systemctl daemon-reload || true - if [ "$(systemctl is-enabled "$TIMER" 2>/dev/null)" = enabled ]; then - deb-systemd-invoke start "$TIMER" || true - fi + for timer in "$TIMER" "$ACTIVITY_TIMER"; do + if [ "$(systemctl is-enabled "$timer" 2>/dev/null)" = enabled ]; then + deb-systemd-invoke start "$timer" || true + fi + done # Enabled: restart on an upgrade (loads the new code, starts a stopped service), start on # a new installation. Disabled or masked: only try-restart, so a service that still runs # gets the new code and a stopped one stays stopped (restart would do the same for a diff --git a/debian/linuxmuster-squid.postrm b/debian/linuxmuster-squid.postrm index 3141e8e..3e03129 100644 --- a/debian/linuxmuster-squid.postrm +++ b/debian/linuxmuster-squid.postrm @@ -13,10 +13,12 @@ if [ "$1" = "purge" ]; then # init-system-helpers, which is Essential. deb-systemd-helper purge linuxmuster-squid.service >/dev/null || true deb-systemd-helper purge linuxmuster-squid-catalog.timer >/dev/null || true + deb-systemd-helper purge linuxmuster-squid-activity.timer >/dev/null || true rm -rf /opt/linuxmuster-squid # /var/lib/linuxmuster-squid holds the instances' git log, the category catalog and its - # downloads (ADR-022). - rm -rf /etc/linuxmuster-squid /var/lib/linuxmuster-squid + # downloads (ADR-022), the activity log's day files and audit log (ADR-023); its spool is + # /var/spool/linuxmuster-squid. + rm -rf /etc/linuxmuster-squid /var/lib/linuxmuster-squid /var/spool/linuxmuster-squid # The safe.directory entry the postinst added for the instances repo. if command -v git >/dev/null 2>&1; then git config --system --unset-all safe.directory \ diff --git a/debian/linuxmuster-squid.prerm b/debian/linuxmuster-squid.prerm index 07ffc6a..13372a4 100644 --- a/debian/linuxmuster-squid.prerm +++ b/debian/linuxmuster-squid.prerm @@ -11,6 +11,8 @@ if [ "$1" = remove ] && [ -d /run/systemd/system ]; then deb-systemd-invoke stop linuxmuster-squid.service >/dev/null || true deb-systemd-invoke stop linuxmuster-squid-catalog.timer \ linuxmuster-squid-catalog.service >/dev/null || true + deb-systemd-invoke stop linuxmuster-squid-activity.timer \ + linuxmuster-squid-activity.service >/dev/null || true fi #DEBHELPER# exit 0 diff --git a/packaging/systemd/linuxmuster-squid-activity.service b/packaging/systemd/linuxmuster-squid-activity.service new file mode 100644 index 0000000..a2d4e97 --- /dev/null +++ b/packaging/systemd/linuxmuster-squid-activity.service @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +[Unit] +Description=linuxmuster-squid: collect the activity log of the instances into day files +Documentation=https://github.com/faircomp/linuxmuster-squid + +[Service] +Type=oneshot +User=lmnsquid +# Does nothing while no instance has the activity log on (ADR-023); applies the retention. +ExecStart=/opt/linuxmuster-squid/venv/bin/lmnsquid-activity collect +Environment=LMNSQUID_CONFIG=/etc/linuxmuster-squid/config.yml +# One spool file at a time (at most 16 MiB of lines): measured RSS in docs/operations.md. +MemoryMax=256M +Nice=5 +TimeoutStartSec=15min + +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +PrivateNetwork=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictAddressFamilies=AF_UNIX +RestrictNamespaces=yes +LockPersonality=yes +RestrictSUIDSGID=yes +ProtectClock=yes +ProtectHostname=yes +SystemCallArchitectures=native +ReadWritePaths=/var/lib/linuxmuster-squid -/var/spool/linuxmuster-squid diff --git a/packaging/systemd/linuxmuster-squid-activity.timer b/packaging/systemd/linuxmuster-squid-activity.timer new file mode 100644 index 0000000..7193c0e --- /dev/null +++ b/packaging/systemd/linuxmuster-squid-activity.timer @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +[Unit] +Description=linuxmuster-squid: collect the activity log every 30 seconds + +[Timer] +OnBootSec=1min +OnUnitActiveSec=30s +AccuracySec=5s + +[Install] +WantedBy=timers.target diff --git a/packaging/systemd/linuxmuster-squid.service b/packaging/systemd/linuxmuster-squid.service index 3490898..458884c 100644 --- a/packaging/systemd/linuxmuster-squid.service +++ b/packaging/systemd/linuxmuster-squid.service @@ -31,7 +31,7 @@ RemoveIPC=yes ProtectClock=yes ProtectHostname=yes SystemCallArchitectures=native -ReadWritePaths=/etc/linuxmuster-squid /var/lib/linuxmuster-squid +ReadWritePaths=/etc/linuxmuster-squid /var/lib/linuxmuster-squid -/var/spool/linuxmuster-squid [Install] WantedBy=multi-user.target From 098433b0b20222843c2adc74328b7e848de21bc6 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 11:03:54 +0100 Subject: [PATCH 06/45] fix(controlplane): activity CSV export with plain newlines csv's default \r\n made the WebUI keep each proxy's header when it merges exports from several proxies. --- controlplane/lmnsquid/activity_query.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controlplane/lmnsquid/activity_query.py b/controlplane/lmnsquid/activity_query.py index 88a8d7c..b8bfbfe 100644 --- a/controlplane/lmnsquid/activity_query.py +++ b/controlplane/lmnsquid/activity_query.py @@ -501,7 +501,7 @@ def export(self, since: int, until: int, users: list[str] | None) -> Iterator[st def lines() -> Iterator[str]: buf = io.StringIO() - out = csv.writer(buf) + out = csv.writer(buf, lineterminator="\n") out.writerow(["time", "user", "domain", "requests", "bytes", "blocked", "category"]) yield buf.getvalue() written = 0 From 8cff5ad4109d831694ac5c9a41c2b36091934aae Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 11:04:15 +0100 Subject: [PATCH 07/45] feat(webui): Internetprotokoll view for teachers, school and global administrators A second view with its own permission lm:squid:activity (permissions.yml: globaladministrator, schooladministrator, teacher; the management stays global-admin only). The scope is computed on the server from the AD the way the official plugins read it (linuxmusterTools /users, /rawusers, /projects): teachers see only students of their own school in classes and projects they are a member or admin of (also through a project's member groups), never teachers; school administrators their school; other roles 403 also with the permission granted by hand. Only that users list goes to the proxies, which filter and audit with the person. Overview per class with active-now and blocked attempts, top domains, domain search, a heat map of the last 7 days per student with the minutes of an hour, live reload, CSV export for administrators, settings with the privacy notice and the audit log for global administrators. Proxies are asked in parallel; one that does not answer is named and does not block. --- scripts/tests/webui_deb_smoke.sh | 17 +- webui/build_plugin.py | 2 + webui/lmn_squid/__init__.py | 3 +- webui/lmn_squid/activity_scope.py | 293 ++++++++++ webui/lmn_squid/activity_views.py | 529 ++++++++++++++++++ webui/lmn_squid/client.py | 4 + webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 222 ++++++++ webui/lmn_squid/main.py | 19 +- webui/lmn_squid/permissions.yml | 19 +- webui/lmn_squid/plugin.yml | 2 + .../js/controllers/activity.controller.es | 474 ++++++++++++++++ webui/lmn_squid/resources/js/routing.es | 4 + .../lmn_squid/resources/partial/activity.html | 309 ++++++++++ webui/pyproject.toml | 2 +- webui/tests/conftest.py | 12 +- webui/tests/js/activity_check.js | 115 ++++ webui/tests/test_activity_views.py | 390 +++++++++++++ webui/tests/test_build.py | 26 +- webui/tests/test_permissions.py | 20 +- 19 files changed, 2439 insertions(+), 23 deletions(-) create mode 100644 webui/lmn_squid/activity_scope.py create mode 100644 webui/lmn_squid/activity_views.py create mode 100644 webui/lmn_squid/resources/js/controllers/activity.controller.es create mode 100644 webui/lmn_squid/resources/partial/activity.html create mode 100644 webui/tests/js/activity_check.js create mode 100644 webui/tests/test_activity_views.py diff --git a/scripts/tests/webui_deb_smoke.sh b/scripts/tests/webui_deb_smoke.sh index dbcd8d0..f496ad8 100755 --- a/scripts/tests/webui_deb_smoke.sh +++ b/scripts/tests/webui_deb_smoke.sh @@ -6,7 +6,8 @@ # the package is installed with --force-depends next to stand-ins of the two WebUI commands its # maintainer scripts call (merge-permissions.py, sophomorix-ui), which only record that they # ran and what they saw. Checks: the shipped file tree and modes, permissions.yml grants the -# global administrator only, configure/remove/purge run the WebUI steps in the right state, +# management to the global administrator only and the activity view (ADR-023) to global and school +# administrators and teachers, configure/remove/purge run the WebUI steps in the right state, # the token directory is 0700, prerm removes the WebUI's __pycache__, purge removes the # configuration, and a configure without any WebUI piece present still succeeds. # What it cannot show (needs the lab): the WebUI loading the plugin, sophomorix-ui writing @@ -48,7 +49,7 @@ if grep -v ' \./usr/share/doc/' <<< "$listing" | grep -v " $SHARE/provision-keyt fi ok "file tree: plugin files 0644 root:root, provision-keytab.sh 0755, bundled .deb with sha256" -# --- permissions.yml: global administrators only ------------------------------------------ +# --- permissions.yml: management global administrators only, activity view ADR-023 ------------ tmp="$(mktemp -d)" trap 'rm -rf "$tmp"' EXIT dpkg-deb -x "$DEB" "$tmp/x" @@ -57,19 +58,25 @@ awk ' /^- / { value = ($0 ~ /: true.$/) ? "true" : (($0 ~ /: false.$/) ? "false" : "bad") if (value == "bad") { print "bad line: " $0; bad = 1 } - if ((role == "globaladministrator") != (value == "true")) { print role ": " $0; bad = 1 } + # the activity view (lm:squid:activity, its sidebar entry) is for global and school + # administrators and teachers; everything else (management) for global administrators + if ($0 ~ /squid-activity|squid:activity/) + allowed = (role == "globaladministrator" || role == "schooladministrator" || role == "teacher") + else + allowed = (role == "globaladministrator") + if (allowed != (value == "true")) { print role ": " $0; bad = 1 } n[role]++ } END { split("globaladministrator schooladministrator teacher student parent staff", want, " ") - for (i in want) if (n[want[i]] != 3) { print "role " want[i] ": " n[want[i]] " entries"; bad = 1 } + for (i in want) if (n[want[i]] != 5) { print "role " want[i] ": " n[want[i]] " entries"; bad = 1 } exit bad }' "$tmp/x$PLUGIN/permissions.yml" || fail "permissions.yml" ( cd "$tmp/x/${SHARE#./}" && sha256sum -c --status ./*.deb.sha256 ) || fail "bundled .deb does not match its sha256" [ "$(dpkg-deb -f "$tmp/x/${bundled#./}" Package Version)" = "$(printf 'Package: linuxmuster-squid\nVersion: %s' "$(dpkg-deb -f "$DEB" Version)")" ] \ || fail "bundled .deb is not linuxmuster-squid of the same version" ok "bundled control plane: same version, sha256 matches" -ok "permissions.yml: lm:squid:list, lm:squid:change and the sidebar only for globaladministrator" +ok "permissions.yml: management only for globaladministrator, activity view for global/school administrators and teachers" # --- configure without any WebUI piece ---------------------------------------------------- rm -f "$MERGE" "$SOPHO" diff --git a/webui/build_plugin.py b/webui/build_plugin.py index cfea397..41208ed 100644 --- a/webui/build_plugin.py +++ b/webui/build_plugin.py @@ -40,6 +40,8 @@ "runtime.py", "sshsetup.py", "setup_runner.py", + "activity_scope.py", + "activity_views.py", ) META_FILES = ("plugin.yml", "permissions.yml") SKIP_LOCALES = ("en",) # English is the source language (msgid), as upstream diff --git a/webui/lmn_squid/__init__.py b/webui/lmn_squid/__init__.py index a5ee074..d549448 100644 --- a/webui/lmn_squid/__init__.py +++ b/webui/lmn_squid/__init__.py @@ -3,6 +3,7 @@ """linuxmuster-squid plugin for the linuxmuster.net WebUI (lmn73): manage the proxy servers.""" from .main import ItemProvider, Permissions +from .activity_views import ActivityHandler from .views import Handler -__all__ = ["Handler", "ItemProvider", "Permissions"] +__all__ = ["ActivityHandler", "Handler", "ItemProvider", "Permissions"] diff --git a/webui/lmn_squid/activity_scope.py b/webui/lmn_squid/activity_scope.py new file mode 100644 index 0000000..421d593 --- /dev/null +++ b/webui/lmn_squid/activity_scope.py @@ -0,0 +1,293 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Who may see whose activity data (ADR-023), computed on the school server from the AD. + +- ``globaladministrator`` (and the WebUI's ``root``): everyone; optionally one school. +- ``schooladministrator``: every user of their own school (``sophomorixSchoolname``). +- ``teacher``: only **students** (``sophomorixRole`` student) of their own school who are in a + class or project the teacher is a member or admin of (sophomorix writes members and admins + of a class or project into the group's ``member``, so both are in the teacher's + ``memberOf``; groups that are members of a project count with their students). Never other + teachers, also when they are in the same class. +- every other role: nothing (403). + +The role, school and groups are read from the AD on every request (cached for a few seconds), +not from the session, so a role or a class membership changed in the AD applies at once. The +data are read the way the official plugins read them (``linuxmusterTools`` ``LMNLdapReader``: +``/users/`` for the person, ``/rawusers`` for the users of a school, ``/projects/`` +for a project's member groups); tests use a fake directory with the same shape. +""" + +from __future__ import annotations + +import re +import threading +import time +from dataclasses import dataclass, field +from typing import Any, Callable, Protocol + +ROLES = ("globaladministrator", "schooladministrator", "teacher") +ADMIN_ROLES = ("globaladministrator", "schooladministrator") +# sAMAccountName as linuxmusterTools' /users/ route accepts it ([\w\-]*) +USER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") +GROUP_RE = re.compile(r"^[A-Za-z0-9][\w\-]{0,63}$") +SCHOOL_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,30}$") +# sophomorix's role groups (all students/teachers/parents of a school) are never a "class" for +# the scope, even if a reader lists one among a user's classes. +ROLE_GROUP_RE = re.compile(r"^(?:[a-z0-9-]+-)?(?:students|teachers|parents)$") +CACHE_SECONDS = 60.0 +PERSON_CACHE_SECONDS = 10.0 + + +class ScopeDenied(Exception): + """The person may not see activity data (or not this user/group).""" + + +class Directory(Protocol): + """The AD as the plugin reads it (linuxmusterTools; a fake in the tests).""" + + def person(self, name: str) -> dict[str, Any] | None: + """LMNUserModel fields of one user: sAMAccountName, sophomorixRole, + sophomorixSchoolname, schoolclasses, projects; ``None`` if unknown.""" + + def school_users(self, school: str) -> list[dict[str, Any]]: + """Every user of one school (sAMAccountName, sophomorixRole, sophomorixSchoolname, + schoolclasses, projects, displayName).""" + + def project_groups(self, school: str, project: str) -> list[str]: + """The groups that are members or admin groups of a project (cn).""" + + +@dataclass +class Group: + kind: str # "class" | "project" + name: str + members: list[dict[str, str]] = field(default_factory=list) # visible members only + + def brief(self) -> dict[str, Any]: + return {"kind": self.kind, "name": self.name, "count": len(self.members)} + + +@dataclass +class Scope: + user: str + role: str + school: str | None # None: all schools (global administrator without a choice) + users: set[str] | None # None: everyone + groups: list[Group] + names: dict[str, str] # user -> display name of the visible users + + @property + def can_export(self) -> bool: + return self.role in ADMIN_ROLES + + @property + def is_global(self) -> bool: + return self.role == "globaladministrator" + + def group(self, kind: str, name: str) -> Group: + for g in self.groups: + if g.kind == kind and g.name == name: + return g + raise ScopeDenied(f"{kind} {name!r} is not in your scope") + + def check_user(self, user: str) -> None: + if self.users is not None and user.lower() not in self.users: + raise ScopeDenied("user not in your scope") + + def restrict(self, users: list[str]) -> list[str]: + found = {u.lower() for u in users} + return sorted(found if self.users is None else found & self.users) + + +def _str(value: Any) -> str: + if isinstance(value, list): + value = value[0] if value else "" + return str(value or "") + + +def _names(value: Any) -> list[str]: + if isinstance(value, str): + return [value] if value else [] + return [str(v) for v in value or [] if v] + + +def _display(entry: dict[str, Any]) -> str: + shown = _str(entry.get("displayName")) + if not shown: + shown = " ".join(x for x in (_str(entry.get("givenName")), _str(entry.get("sn"))) if x) + return shown or _str(entry.get("sAMAccountName")) + + +class _Cache: + def __init__(self) -> None: + self.lock = threading.Lock() + self.data: dict[Any, tuple[float, Any]] = {} + + def get(self, key: Any, ttl: float, load: Callable[[], Any]) -> Any: + now = time.monotonic() + with self.lock: + hit = self.data.get(key) + if hit is not None and now - hit[0] < ttl: + return hit[1] + value = load() + with self.lock: + self.data[key] = (now, value) + return value + + def clear(self) -> None: + with self.lock: + self.data.clear() + + +CACHE = _Cache() + + +def _role_of(entry: dict[str, Any]) -> str: + return _str(entry.get("sophomorixRole")) + + +def _groups_of(entry: dict[str, Any]) -> set[str]: + return set(_names(entry.get("schoolclasses"))) | set(_names(entry.get("projects"))) + + +def _school_users(directory: Directory, school: str) -> list[dict[str, Any]]: + users = CACHE.get(("school", school), CACHE_SECONDS, lambda: directory.school_users(school)) + # defense in depth: the reader filters by the school's OU already + return [ + u + for u in users + if _str(u.get("sophomorixSchoolname")) == school + and USER_RE.match(_str(u.get("sAMAccountName"))) + ] + + +def _members( + directory: Directory, + school: str, + kind: str, + name: str, + users: list[dict[str, Any]], + keep: Callable[[dict[str, Any]], bool], +) -> list[dict[str, str]]: + wanted = {name} + if kind == "project": + wanted |= set( + CACHE.get( + ("project", school, name), + CACHE_SECONDS, + lambda: directory.project_groups(school, name), + ) + ) + found = [ + {"user": _str(u["sAMAccountName"]).lower(), "display": _display(u), "role": _role_of(u)} + for u in users + if keep(u) and _groups_of(u) & wanted + ] + return sorted(found, key=lambda m: (m["display"].lower(), m["user"])) + + +def scope_for(identity: str | None, directory: Directory, school: str | None = None) -> Scope: + """The scope of ``identity``; ``school`` chooses one school for a global administrator.""" + if not identity: + raise ScopeDenied("not logged in") + if school is not None and not SCHOOL_RE.match(school): + raise ScopeDenied("invalid school") + person: dict[str, Any] = {} + own_school: str | None = None + if identity == "root": + role = "globaladministrator" + else: + if not USER_RE.match(identity): + raise ScopeDenied("invalid user") + person = ( + CACHE.get( + ("person", identity), PERSON_CACHE_SECONDS, lambda: directory.person(identity) + ) + or {} + ) + role = _role_of(person) + own_school = _str(person.get("sophomorixSchoolname")) or None + if role not in ROLES: + raise ScopeDenied("your role has no access to the activity log") + + if role == "globaladministrator": + if school is None: + return Scope(identity, role, None, None, [], {}) + target = school + keep: Callable[[dict[str, Any]], bool] = lambda _u: True # noqa: E731 + elif role == "schooladministrator": + if not own_school or (school is not None and school != own_school): + raise ScopeDenied("only your own school") + target = own_school + keep = lambda _u: True # noqa: E731 + else: + if not own_school or (school is not None and school != own_school): + raise ScopeDenied("only your own school") + target = own_school + keep = lambda u: _role_of(u) == "student" # noqa: E731 + + users = _school_users(directory, target) + if role == "teacher": + mine = [("class", c) for c in _names(person.get("schoolclasses"))] + [ + ("project", p) for p in _names(person.get("projects")) + ] + else: + classes = sorted({c for u in users for c in _names(u.get("schoolclasses"))}) + projects = sorted({p for u in users for p in _names(u.get("projects"))}) + mine = [("class", c) for c in classes] + [("project", p) for p in projects] + groups = [ + Group(kind, name, _members(directory, target, kind, name, users, keep)) + for kind, name in mine + if GROUP_RE.match(name) and not ROLE_GROUP_RE.match(name.lower()) + ] + if role == "teacher": + visible = {m["user"] for g in groups for m in g.members} + else: + visible = {_str(u["sAMAccountName"]).lower() for u in users} + names = { + _str(u["sAMAccountName"]).lower(): _display(u) + for u in users + if _str(u["sAMAccountName"]).lower() in visible + } + return Scope(identity, role, target, visible, groups, names) + + +class LdapDirectory: + """:class:`Directory` over linuxmusterTools, the way the official WebUI plugins read it.""" + + ATTRS = [ + "sAMAccountName", + "sophomorixRole", + "sophomorixSchoolname", + "schoolclasses", + "projects", + "displayName", + "givenName", + "sn", + ] + + def __init__(self) -> None: + from linuxmusterTools.ldapconnector import LMNLdapReader + + self.lr = LMNLdapReader + + def person(self, name: str) -> dict[str, Any] | None: + found = self.lr.get(f"/users/{name}", attributes=self.ATTRS) + return found if isinstance(found, dict) and found.get("sAMAccountName") else None + + def school_users(self, school: str) -> list[dict[str, Any]]: + found = self.lr.get("/rawusers", school=school, attributes=self.ATTRS) + return [u for u in found or [] if isinstance(u, dict)] + + def project_groups(self, school: str, project: str) -> list[str]: + found = self.lr.get( + f"/projects/{project}", + school=school, + attributes=["sophomorixMemberGroups", "sophomorixAdminGroups"], + ) + if not isinstance(found, dict): + return [] + return _names(found.get("sophomorixMemberGroups")) + _names( + found.get("sophomorixAdminGroups") + ) diff --git a/webui/lmn_squid/activity_views.py b/webui/lmn_squid/activity_views.py new file mode 100644 index 0000000..e3dcd08 --- /dev/null +++ b/webui/lmn_squid/activity_views.py @@ -0,0 +1,529 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""HTTP endpoints of the activity log view ("Internetprotokoll", ADR-023) under +``/api/lmn/squid-activity/``. + +Every endpoint carries ``@authorize('lm:squid:activity')`` (true for globaladministrator, +schooladministrator and teacher in permissions.yml) and computes the person's scope from the AD +on the server (:mod:`activity_scope`): a teacher's requests carry exactly the students of their +classes and projects as the ``users`` list to the proxies, which filter on it; a user or group +outside the scope is 403 before any proxy is asked. Students and other roles get 403 even if a +permission was granted by hand. Export is for school and global administrators, the settings +and the audit log for global administrators. State-changing requests (all POST/PUT) pass the +same-origin check of the management view. Every proxy whose instances belong to the school is +asked in parallel; one that does not answer is named and does not block the others. +""" + +from __future__ import annotations + +import logging +import time +from concurrent import futures +from functools import wraps +from typing import Any, Callable + +from aj.api.endpoint import EndpointReturn, endpoint +from aj.api.http import HttpPlugin, get, post, put +from aj.auth import authorize +from jadi import component + +from .activity_scope import ( + SCHOOL_RE, + USER_RE, + LdapDirectory, + Scope, + ScopeDenied, + scope_for, +) +from .client import LONG, SHORT, ControlPlaneClient, ControlPlaneError, instance_path +from .connections import CONFIG_PATH, Connection, ConnectionFileError, ConnectionStore +from .views import STATE_CHANGING, _body, check_same_origin + +audit = logging.getLogger("lmn_squid.audit") + +PERM_ACTIVITY = "lm:squid:activity" +PREFIX = r"/api/lmn/squid-activity" +MAX_RANGE = 366 * 86400 +WORKERS = 8 +# what the browser may choose (the proxy enforces its own limits as well) +RESOLUTIONS = ("hour", "minute") +SORTS = ("requests", "blocked", "last", "name", "bytes") + + +def activity_endpoint(fx: Callable[..., Any]) -> Callable[..., Any]: + """Same-origin check of state-changing requests, scope errors as 403, plugin errors as + readable answers (never a traceback).""" + + @wraps(fx) + def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: + if str(getattr(http_context, "method", "")).upper() in STATE_CHANGING: + check_same_origin(http_context) + try: + return fx(self, http_context, **kwargs) + except ScopeDenied as exc: + raise EndpointReturn(403, {"error": "scope", "message": str(exc)}) from None + except ControlPlaneError as exc: + raise EndpointReturn(exc.http_status(), exc.as_dict()) from None + except ConnectionFileError as exc: + raise EndpointReturn(409, {"error": "config", "message": exc.message}) from None + + return wrapper + + +def _int(body: dict[str, Any], key: str, default: int | None = None) -> int: + value = body.get(key, default) + if isinstance(value, bool) or value is None: + raise EndpointReturn(422, {"error": "invalid", "field": key, "message": f"{key} missing"}) + try: + return int(value) + except (TypeError, ValueError): + raise EndpointReturn( + 422, {"error": "invalid", "field": key, "message": f"{key} must be a number"} + ) from None + + +def _range(body: dict[str, Any]) -> tuple[int, int]: + since, until = _int(body, "since"), _int(body, "until") + if since < 0 or until <= since or until - since > MAX_RANGE: + raise EndpointReturn( + 422, {"error": "invalid", "field": "until", "message": "invalid time range"} + ) + return since, until + + +def _school(value: Any) -> str | None: + if value in (None, ""): + return None + if not isinstance(value, str) or not SCHOOL_RE.match(value): + raise EndpointReturn(422, {"error": "invalid", "field": "school", "message": "school"}) + return value + + +@component(HttpPlugin) +class ActivityHandler(HttpPlugin): + # Replaceable in tests (a fake AD with the same shape). + directory_factory: Callable[[], Any] = LdapDirectory + + def __init__(self, context: Any) -> None: + self.context = context + self.store = ConnectionStore(CONFIG_PATH) + + # ------------------------------------------------------------------ helpers + def _scope(self, school: str | None = None) -> Scope: + return scope_for(getattr(self.context, "identity", None), self.directory_factory(), school) + + def _require_global(self, scope: Scope) -> None: + if not scope.is_global: + raise ScopeDenied("global administrators only") + + def _audit_info(self, scope: Scope, label: str) -> dict[str, Any]: + return {"actor": scope.user, "role": scope.role, "scope": label[:256]} + + def _log(self, scope: Scope, what: str, label: str) -> None: + audit.info("user=%s role=%s activity %s scope=%s", scope.user, scope.role, what, label) + + def _fan_out( + self, call: Callable[[Connection, ControlPlaneClient], Any] + ) -> tuple[list[tuple[Connection, Any]], list[dict[str, str]]]: + """``call`` on every connection in parallel: (results, connections that failed).""" + conns = list(self.store.load().values()) + results: list[tuple[Connection, Any]] = [] + failed: list[dict[str, str]] = [] + if not conns: + return results, failed + with futures.ThreadPoolExecutor(max_workers=min(WORKERS, len(conns))) as pool: + jobs = {pool.submit(call, c, ControlPlaneClient(c)): c for c in conns} + for job in futures.as_completed(jobs): + conn = jobs[job] + try: + results.append((conn, job.result())) + except ControlPlaneError as exc: + failed.append( + {"connection": conn.display_name or conn.name, "message": exc.message} + ) + except Exception as exc: # noqa: BLE001 - one proxy never blocks the view + failed.append( + {"connection": conn.display_name or conn.name, "message": str(exc)[:300]} + ) + results.sort(key=lambda item: item[0].name) + return results, failed + + @staticmethod + def _instances(overview: Any, scope: Scope) -> list[str]: + """The instances of one proxy that hold activity data of the scope's school.""" + found = [] + for inst in (overview or {}).get("instances") or []: + if not isinstance(inst, dict): + continue + usage = inst.get("usage") or {} + if not (inst.get("enabled") or usage.get("days")): + continue + if scope.school is not None and inst.get("school") != scope.school: + continue + found.append(str(inst.get("name"))) + return found + + def _query( + self, + scope: Scope, + path: str, + body: dict[str, Any], + timeouts: tuple[float, float] = SHORT, + text: bool = False, + ) -> tuple[list[Any], list[dict[str, str]]]: + """POST ``body`` to ``path`` of every proxy with matching instances.""" + + def call(_conn: Connection, client: ControlPlaneClient) -> Any: + names = self._instances(client.request("GET", "/v1/activity"), scope) + if not names: + return None + return client.request( + "POST", path, {**body, "instances": names}, timeouts=timeouts, text=text + ) + + results, failed = self._fan_out(call) + return [r for _c, r in results if r is not None], failed + + def _users_for(self, scope: Scope, body: dict[str, Any]) -> tuple[list[str] | None, str]: + """The users list sent to the proxies and a label for the audit log.""" + group = body.get("group") + if isinstance(group, dict) and group.get("name"): + g = scope.group(str(group.get("kind") or ""), str(group.get("name"))) + members = [m["user"] for m in g.members] + return scope.restrict(members), f"{g.kind} {g.name}" + if scope.users is None: + return None, f"school {scope.school}" if scope.school else "all schools" + return sorted(scope.users), f"all visible users ({scope.school})" + + # ------------------------------------------------------------------ scope + @get(PREFIX + r"/scope") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_scope(self, http_context: Any) -> Any: + """What the person may look at: role, school, classes and projects with members.""" + school = _school((http_context.query or {}).get("school")) + scope = self._scope(school) + schools: list[str] = [] + if scope.is_global: + results, _failed = self._fan_out( + lambda _c, client: client.request("GET", "/v1/activity") + ) + schools = sorted( + { + str(i.get("school")) + for _c, r in results + for i in (r or {}).get("instances") or [] + if isinstance(i, dict) and i.get("school") + } + ) + return { + "user": scope.user, + "role": scope.role, + "school": scope.school, + "schools": schools, + "can_export": scope.can_export, + "is_global": scope.is_global, + "groups": [{**g.brief(), "members": g.members} for g in scope.groups], + } + + # ---------------------------------------------------------------- queries + @post(PREFIX + r"/query/users") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_users(self, http_context: Any) -> Any: + """Per user: requests, blocked, domains, last seen, active now (merged over proxies).""" + body = _body(http_context) + scope = self._scope(_school(body.get("school"))) + since, until = _range(body) + users, label = self._users_for(scope, body) + sort = body.get("sort") if body.get("sort") in SORTS else "requests" + self._log(scope, "users", label) + if users == []: + return {"users": [], "unreachable": []} + results, failed = self._query( + scope, + "/v1/activity/users", + { + "since": since, + "until": until, + "users": users, + "limit": 1000, + "sort": sort, + "audit": self._audit_info(scope, label), + }, + ) + merged: dict[str, dict[str, Any]] = {} + for result in results: + for row in result.get("users") or []: + cur = merged.get(row["user"]) + if cur is None: + merged[row["user"]] = dict(row) + continue + for key in ("requests", "bytes", "blocked"): + cur[key] = int(cur.get(key) or 0) + int(row.get(key) or 0) + if row.get("domains") is not None: + cur["domains"] = int(cur.get("domains") or 0) + int(row["domains"]) + cur["last"] = max(int(cur.get("last") or 0), int(row.get("last") or 0)) + cur["active_now"] = bool(cur.get("active_now") or row.get("active_now")) + for name, row in merged.items(): + row["display"] = scope.names.get(name, name) + return {"users": list(merged.values()), "unreachable": failed} + + @post(PREFIX + r"/query/timeline") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_timeline(self, http_context: Any) -> Any: + """One user's activity per hour (heat map) or per minute and domain.""" + body = _body(http_context) + scope = self._scope(_school(body.get("school"))) + since, until = _range(body) + user = str(body.get("user") or "").lower() + if not USER_RE.match(user): + raise EndpointReturn(422, {"error": "invalid", "field": "user", "message": "user"}) + scope.check_user(user) + resolution = body.get("resolution") if body.get("resolution") in RESOLUTIONS else "hour" + self._log(scope, f"timeline {resolution}", f"user {user}") + results, failed = self._query( + scope, + "/v1/activity/timeline", + { + "since": since, + "until": until, + "user": user, + "users": None if scope.users is None else [user], + "resolution": resolution, + "limit": 5000 if resolution == "minute" else 1000, + "audit": self._audit_info(scope, f"user {user}"), + }, + ) + rows: dict[tuple[Any, ...], dict[str, Any]] = {} + for result in results: + for row in result.get("rows") or []: + key = (row.get("t"), row.get("domain")) + cur = rows.get(key) + if cur is None: + rows[key] = dict(row) + continue + for k in ("requests", "bytes", "blocked"): + cur[k] = int(cur.get(k) or 0) + int(row.get(k) or 0) + ordered = [rows[k] for k in sorted(rows, key=lambda k: (k[0] or 0, k[1] or ""))] + return { + "user": user, + "display": scope.names.get(user, user), + "resolution": resolution, + "rows": ordered, + "unreachable": failed, + } + + @post(PREFIX + r"/query/domains") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_domains(self, http_context: Any) -> Any: + """Top domains of a group, a user or the whole scope.""" + body = _body(http_context) + scope = self._scope(_school(body.get("school"))) + since, until = _range(body) + user = str(body.get("user") or "").lower() + if user: + if not USER_RE.match(user): + raise EndpointReturn(422, {"error": "invalid", "field": "user", "message": "user"}) + scope.check_user(user) + users: list[str] | None = [user] + label = f"user {user}" + else: + users, label = self._users_for(scope, body) + self._log(scope, "domains", label) + if users == []: + return {"domains": [], "unreachable": []} + results, failed = self._query( + scope, + "/v1/activity/domains", + { + "since": since, + "until": until, + "users": users, + "limit": 100, + "audit": self._audit_info(scope, label), + }, + ) + merged: dict[str, dict[str, Any]] = {} + for result in results: + for row in result.get("domains") or []: + cur = merged.get(row["domain"]) + if cur is None: + merged[row["domain"]] = dict(row) + continue + for k in ("requests", "bytes", "blocked", "users"): + cur[k] = int(cur.get(k) or 0) + int(row.get(k) or 0) + cur["category"] = cur.get("category") or row.get("category") + ordered = sorted(merged.values(), key=lambda r: (-int(r["requests"]), r["domain"])) + return {"domains": ordered[:100], "unreachable": failed} + + @post(PREFIX + r"/query/search") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_search(self, http_context: Any) -> Any: + """Who of the scope was on a domain (or a subdomain of it).""" + body = _body(http_context) + scope = self._scope(_school(body.get("school"))) + since, until = _range(body) + domain = str(body.get("domain") or "").strip().lower() + if not domain or len(domain) > 253 or any(c.isspace() for c in domain): + raise EndpointReturn(422, {"error": "invalid", "field": "domain", "message": "domain"}) + users, label = self._users_for(scope, body) + self._log(scope, "search", f"{label} domain {domain}") + if users == []: + return {"users": [], "unreachable": []} + results, failed = self._query( + scope, + "/v1/activity/search", + { + "since": since, + "until": until, + "users": users, + "domain": domain, + "limit": 1000, + "audit": self._audit_info(scope, label), + }, + ) + merged: dict[str, dict[str, Any]] = {} + for result in results: + for row in result.get("users") or []: + cur = merged.get(row["user"]) + if cur is None: + merged[row["user"]] = dict(row) + continue + cur["requests"] = int(cur["requests"]) + int(row["requests"]) + cur["blocked"] = int(cur["blocked"]) + int(row["blocked"]) + cur["first"] = min(int(cur["first"]), int(row["first"])) + cur["last"] = max(int(cur["last"]), int(row["last"])) + cur["domains"] = sorted(set(cur["domains"]) | set(row["domains"]))[:10] + for name, row in merged.items(): + row["display"] = scope.names.get(name, name) + ordered = sorted(merged.values(), key=lambda r: (-int(r["requests"]), r["user"])) + return {"domain": domain, "users": ordered, "unreachable": failed} + + @post(PREFIX + r"/export") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_export(self, http_context: Any) -> Any: + """CSV per minute, user and domain: school and global administrators only.""" + body = _body(http_context) + scope = self._scope(_school(body.get("school"))) + if not scope.can_export: + raise ScopeDenied("export is for school and global administrators") + since, until = _range(body) + users, label = self._users_for(scope, body) + self._log(scope, "export", label) + if users == []: + return {"csv": "time,user,domain,requests,bytes,blocked,category\n", "unreachable": []} + results, failed = self._query( + scope, + "/v1/activity/export", + { + "since": since, + "until": until, + "users": users, + "audit": self._audit_info(scope, label), + }, + timeouts=LONG, + text=True, + ) + header = "time,user,domain,requests,bytes,blocked,category\n" + parts = [header] + for text in results: + body_text = str(text or "") + parts.append(body_text[len(header) :] if body_text.startswith(header) else body_text) + return {"csv": "".join(parts), "unreachable": failed} + + # ------------------------------------------------- global administrators + @get(PREFIX + r"/audit") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_audit(self, http_context: Any) -> Any: + """Who read activity data, from every proxy (newest first).""" + scope = self._scope() + self._require_global(scope) + query = http_context.query or {} + try: + days = max(1, min(int(query.get("days") or 7), 3650)) + except ValueError: + days = 7 + actor = str(query.get("actor") or "") or None + now = int(time.time()) + params = {"since": now - days * 86400, "until": now + 1, "limit": 1000, "actor": actor} + results, failed = self._fan_out( + lambda _c, client: client.request("GET", "/v1/activity/audit", query=params) + ) + entries = [] + for conn, result in results: + for entry in (result or {}).get("entries") or []: + entries.append({**entry, "connection": conn.display_name or conn.name}) + entries.sort(key=lambda e: -int(e.get("ts") or 0)) + return {"entries": entries[:1000], "unreachable": failed} + + @get(PREFIX + r"/settings") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_settings(self, http_context: Any) -> Any: + """The activity log settings of every instance on every proxy.""" + scope = self._scope() + self._require_global(scope) + results, failed = self._fan_out(lambda _c, client: client.request("GET", "/v1/activity")) + servers = [ + { + "connection": conn.name, + "display_name": conn.display_name or conn.name, + "timezone": (r or {}).get("timezone"), + "instances": (r or {}).get("instances") or [], + } + for conn, r in results + ] + return {"servers": servers, "unreachable": failed} + + @put(PREFIX + r"/settings/(?P[^/]+)/(?P[^/]+)") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_put_settings(self, http_context: Any, conn: str = "", name: str = "") -> Any: + """Switch the log of one instance on/off, set its retention; switching on needs the + confirmed privacy notice (stored on the proxy with who and when).""" + scope = self._scope() + self._require_global(scope) + found = self.store.get(conn) + if found is None: + raise EndpointReturn(404, {"error": "unknown_connection", "message": conn}) + body = _body(http_context) + enabled = body.get("enabled") + if not isinstance(enabled, bool): + raise EndpointReturn(422, {"error": "invalid", "field": "enabled", "message": "bool"}) + payload: dict[str, Any] = {"enabled": enabled, "actor": scope.user} + if body.get("retention_days") not in (None, ""): + payload["retention_days"] = _int(body, "retention_days") + if enabled: + if body.get("privacy_confirmed") is True: + payload["ack_by"] = scope.user + else: + payload["delete_data"] = body.get("delete_data") is True + audit.info( + "user=%s activity settings connection=%s instance=%s enabled=%s retention=%s " + "delete_data=%s", + scope.user, + conn, + name, + enabled, + payload.get("retention_days"), + payload.get("delete_data"), + ) + # switching on or off replaces the container (health-gated): the long timeout + return ControlPlaneClient(found).request( + "PUT", instance_path(name, "activity"), payload, timeouts=LONG + ) diff --git a/webui/lmn_squid/client.py b/webui/lmn_squid/client.py index 56abf48..22ff1b4 100644 --- a/webui/lmn_squid/client.py +++ b/webui/lmn_squid/client.py @@ -179,10 +179,12 @@ def request( timeouts: tuple[float, float] = SHORT, auth: bool = True, raw: bytes | None = None, + text: bool = False, ) -> Any: """Send one request; return the decoded JSON body (``None`` for an empty one). ``raw`` is sent as ``application/octet-stream`` (a keytab for ``PUT /v1/secrets``). + ``text``: a successful answer is returned as text (the activity log's CSV export). """ if query: path = f"{path}?{urlencode({k: v for k, v in query.items() if v is not None})}" @@ -212,6 +214,8 @@ def request( if len(raw) > MAX_BODY: raise ControlPlaneError("http", f"{self.conn.url}: answer too large", resp.status) data: Any = None + if text and resp.status < 400: + return raw.decode("utf-8", "replace") if raw: try: data = json.loads(raw) diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index 6aa7a4f..3e9c86f 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -1164,3 +1164,225 @@ msgstr "SafeSearch ist an, aber die SafeSearch-Adresse einer Suchmaschine ist un msgid "Filter configured, but the image of this instance cannot filter: nothing is blocked by categories. Update the image (Container actions → Update image)." msgstr "Filter konfiguriert, aber das Image der Instanz kann nicht filtern: nach Kategorien wird nichts gesperrt. Image aktualisieren (Container-Aktionen → Image aktualisieren)." + +msgid "(red border: blocked attempts; click an hour for its domains)" +msgstr "(roter Rand: gesperrte Versuche; eine Stunde anklicken zeigt ihre Domains)" + +msgid "7 days" +msgstr "7 Tage" + +msgid "Activity log" +msgstr "Internetprotokoll" + +msgid "Activity log settings" +msgstr "Einstellungen" + +msgid "Activity log switched off" +msgstr "Internetprotokoll ausgeschaltet" + +msgid "Activity log switched on" +msgstr "Internetprotokoll eingeschaltet" + +msgid "Audit log" +msgstr "Zugriffsprotokoll" + +msgid "Before switching it on: clarify the legal basis (school law, terms of use, consent or a service agreement), inform the people concerned (students, parents, staff), and for employees involve the staff council. Keep the retention as short as the purpose allows. Every access to the data is recorded in the audit log." +msgstr "Vor dem Einschalten: Rechtsgrundlage klären (Schulgesetz, Nutzungsordnung, Einwilligung oder Dienstvereinbarung), die Betroffenen informieren (Schülerinnen und Schüler, Eltern, Beschäftigte) und bei Beschäftigten den Personalrat beteiligen. Die Aufbewahrung so kurz wählen, wie der Zweck es erlaubt. Jeder Abruf der Daten wird im Zugriffsprotokoll festgehalten." + +msgid "Blocked attempts" +msgstr "Gesperrt" + +msgid "Class or project" +msgstr "Klasse oder Projekt" + +msgid "Click an hour in the heat map." +msgstr "Eine Stunde in der Übersicht anklicken." + +msgid "Confirmed by" +msgstr "Bestätigt von" + +msgid "Delete the stored data now" +msgstr "Gespeicherte Daten jetzt löschen" + +msgid "Distinct domains" +msgstr "Domains" + +msgid "Distinct users" +msgstr "Benutzer" + +msgid "Domain name" +msgstr "Domain" + +msgid "Domain search" +msgstr "Domain-Suche" + +msgid "Export CSV" +msgstr "CSV exportieren" + +msgid "Filter by name" +msgstr "Nach Namen filtern" + +msgid "First visit" +msgstr "Erster Aufruf" + +msgid "I confirm that the points above are settled for this instance." +msgstr "Ich bestätige, dass die genannten Punkte für diese Instanz geklärt sind." + +msgid "Internet activity log" +msgstr "Internetprotokoll" + +msgid "Last 7 days, requests per hour" +msgstr "Letzte 7 Tage, Anfragen je Stunde" + +msgid "Last days" +msgstr "Letzte Tage" + +msgid "Last seen" +msgstr "Zuletzt aktiv" + +msgid "Last visit" +msgstr "Letzter Aufruf" + +msgid "Live update" +msgstr "Live" + +msgid "Login name" +msgstr "Anmeldename" + +msgid "Minutes of the chosen hour" +msgstr "Minuten der gewählten Stunde" + +msgid "No activity in this time range." +msgstr "Keine Aktivität in diesem Zeitraum." + +msgid "No new data is recorded. The stored data expire with the retention, or are deleted now." +msgstr "Es werden keine neuen Daten erfasst. Die gespeicherten Daten laufen mit der Aufbewahrungsfrist ab oder werden jetzt gelöscht." + +msgid "Nobody in your scope was on this domain in this time range." +msgstr "Niemand aus Ihrem Bereich war in diesem Zeitraum auf dieser Domain." + +msgid "Number of requests" +msgstr "Anfragen" + +msgid "Only students of your classes and projects are shown." +msgstr "Angezeigt werden nur Schülerinnen und Schüler Ihrer Klassen und Projekte." + +msgid "Proxy server not reachable, its data are missing:" +msgstr "Proxy-Server nicht erreichbar, seine Daten fehlen:" + +msgid "Queried time range" +msgstr "Abgefragter Zeitraum" + +msgid "Query type" +msgstr "Abfrage" + +msgid "Read by" +msgstr "Abgerufen von" + +msgid "Reload every 30 seconds" +msgstr "Alle 30 Sekunden neu laden" + +msgid "Request failed" +msgstr "Anfrage fehlgeschlagen" + +msgid "Retention (days)" +msgstr "Aufbewahrung (Tage)" + +msgid "Retention saved" +msgstr "Aufbewahrung gespeichert" + +msgid "Save retention" +msgstr "Aufbewahrung speichern" + +msgid "School hours" +msgstr "Unterrichtszeit" + +msgid "Search domain" +msgstr "Suchen" + +msgid "Show entries" +msgstr "Anzeigen" + +msgid "Some proxy servers were not reachable; their data are missing." +msgstr "Einige Proxy-Server waren nicht erreichbar; ihre Daten fehlen." + +msgid "Stored data" +msgstr "Gespeichert" + +msgid "Switch off" +msgstr "Ausschalten" + +msgid "Switch on" +msgstr "Einschalten" + +msgid "Switch the activity log off" +msgstr "Internetprotokoll ausschalten" + +msgid "Switch the activity log on" +msgstr "Internetprotokoll einschalten" + +msgid "The activity log is off for every instance until it is switched on here. Switching it on or off restarts the instance (a few seconds). The retention applies at once." +msgstr "Das Internetprotokoll ist für jede Instanz aus, bis es hier eingeschaltet wird. Ein- und Ausschalten startet die Instanz neu (einige Sekunden). Die Aufbewahrung gilt sofort." + +msgid "The activity log stores per user, domain and minute which web sites were visited (no full addresses). These are personal data." +msgstr "Das Internetprotokoll speichert je Benutzer, Domain und Minute, welche Webseiten aufgerufen wurden (keine vollständigen Adressen). Das sind personenbezogene Daten." + +msgid "This hour" +msgstr "Diese Stunde" + +msgid "This notice is no legal advice." +msgstr "Dieser Hinweis ist keine Rechtsberatung." + +msgid "Time of access" +msgstr "Zeitpunkt" + +msgid "Today so far" +msgstr "Heute" + +msgid "Top domains" +msgstr "Top-Domains" + +msgid "Top domains in the chosen time range" +msgstr "Top-Domains im gewählten Zeitraum" + +msgid "Users overview" +msgstr "Übersicht" + +msgid "Who was on this domain?" +msgstr "Wer war auf dieser Domain?" + +msgid "Whose data" +msgstr "Wessen Daten" + +msgid "You are not a member of any class or project with students, so there is nothing to show." +msgstr "Sie sind in keiner Klasse und keinem Projekt mit Schülerinnen und Schülern, daher gibt es nichts anzuzeigen." + +msgid "active in the last 5 minutes" +msgstr "in den letzten 5 Minuten aktiv" + +msgid "all my students" +msgstr "alle meine Schülerinnen und Schüler" + +msgid "all users" +msgstr "alle Benutzer" + +msgid "days of data" +msgstr "Tage" + +msgid "e.g. example.org (subdomains included)" +msgstr "z. B. example.org (mit Subdomains)" + +msgid "of them blocked" +msgstr "davon gesperrt" + +msgid "only this person" +msgstr "nur diese Person" + +msgid "only with activity" +msgstr "nur mit Aktivität" + +msgid "only with blocked attempts" +msgstr "nur mit gesperrten Versuchen" + +msgid "requests in this hour" +msgstr "Anfragen in dieser Stunde" diff --git a/webui/lmn_squid/main.py b/webui/lmn_squid/main.py index c32b9ed..9980806 100644 --- a/webui/lmn_squid/main.py +++ b/webui/lmn_squid/main.py @@ -1,6 +1,7 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later -"""Sidebar entry and permissions of the plugin (global administrators only, permissions.yml).""" +"""Sidebar entries and permissions of the plugin (permissions.yml): the management for global +administrators, the activity log view "Internetprotokoll" for teachers and administrators.""" from __future__ import annotations @@ -11,6 +12,7 @@ from jadi import component URL = "/view/lmn/squid" +ACTIVITY_URL = "/view/lmn/squid-activity" @component(SidebarItemProvider) @@ -26,7 +28,14 @@ def provide(self) -> list[dict[str, Any]]: "icon": "fas fa-shield-alt", "url": URL, "children": [], - } + }, + { + "attach": "category:software", + "name": "Internetprotokoll", + "icon": "fas fa-history", + "url": ACTIVITY_URL, + "children": [], + }, ] @@ -44,4 +53,10 @@ def provide(self) -> list[dict[str, Any]]: "name": "linuxmuster-squid: change connections, instances and lists", "default": False, }, + { + "id": "lm:squid:activity", + "name": "linuxmuster-squid: activity log (what each role sees is decided by the " + "server: teachers their classes' students, school administrators their school)", + "default": False, + }, ] diff --git a/webui/lmn_squid/permissions.yml b/webui/lmn_squid/permissions.yml index d289260..b4dfed6 100644 --- a/webui/lmn_squid/permissions.yml +++ b/webui/lmn_squid/permissions.yml @@ -2,29 +2,44 @@ # SPDX-License-Identifier: GPL-3.0-or-later # # Merged into default-ui-permissions.ini by the WebUI's merge-permissions.py (postinst), -# then written to every user's LDAP entry by sophomorix-ui. Global administrators only; -# every other role is denied explicitly. views.py checks the role again on every request. +# then written to every user's LDAP entry by sophomorix-ui. The management (lm:squid:list, +# lm:squid:change): global administrators only; every other role is denied explicitly, views.py +# checks the role again on every request. The activity log view "Internetprotokoll" +# (lm:squid:activity, ADR-023): global and school administrators and teachers; what each of +# them sees is decided on the server from the AD (activity_scope.py), students get nothing. globaladministrator: - 'lm:squid:change: true' - 'lm:squid:list: true' - 'sidebar:view:/view/lmn/squid: true' +- 'lm:squid:activity: true' +- 'sidebar:view:/view/lmn/squid-activity: true' schooladministrator: - 'lm:squid:change: false' - 'lm:squid:list: false' - 'sidebar:view:/view/lmn/squid: false' +- 'lm:squid:activity: true' +- 'sidebar:view:/view/lmn/squid-activity: true' teacher: - 'lm:squid:change: false' - 'lm:squid:list: false' - 'sidebar:view:/view/lmn/squid: false' +- 'lm:squid:activity: true' +- 'sidebar:view:/view/lmn/squid-activity: true' student: - 'lm:squid:change: false' - 'lm:squid:list: false' - 'sidebar:view:/view/lmn/squid: false' +- 'lm:squid:activity: false' +- 'sidebar:view:/view/lmn/squid-activity: false' parent: - 'lm:squid:change: false' - 'lm:squid:list: false' - 'sidebar:view:/view/lmn/squid: false' +- 'lm:squid:activity: false' +- 'sidebar:view:/view/lmn/squid-activity: false' staff: - 'lm:squid:change: false' - 'lm:squid:list: false' - 'sidebar:view:/view/lmn/squid: false' +- 'lm:squid:activity: false' +- 'sidebar:view:/view/lmn/squid-activity: false' diff --git a/webui/lmn_squid/plugin.yml b/webui/lmn_squid/plugin.yml index 0d5050b..5a30ba3 100644 --- a/webui/lmn_squid/plugin.yml +++ b/webui/lmn_squid/plugin.yml @@ -17,4 +17,6 @@ resources: - 'resources/js/controllers/index.controller.es' - 'resources/partial/index.html' - 'resources/css/dialogs.css' + - 'resources/js/controllers/activity.controller.es' + - 'resources/partial/activity.html' - 'ng:lmn.squid' diff --git a/webui/lmn_squid/resources/js/controllers/activity.controller.es b/webui/lmn_squid/resources/js/controllers/activity.controller.es new file mode 100644 index 0000000..463861a --- /dev/null +++ b/webui/lmn_squid/resources/js/controllers/activity.controller.es @@ -0,0 +1,474 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// Activity log view "Internetprotokoll" (ADR-023). ES5 on purpose (webui/build_plugin.py). +// The server decides what the person may see; this page only asks and shows. +angular.module('lmn.squid').controller('LMNSquidActivityController', function ($scope, $http, $interval, $window, pageTitle, gettext, notify) { + 'use strict'; + pageTitle.set(gettext('Internet activity log')); + + var API = '/api/lmn/squid-activity'; + var LIVE_SECONDS = 30; + // "Unterrichtszeit": today from 7:45 to 16:00 (local time of the browser) + var LESSON_START = [7, 45]; + var LESSON_END = [16, 0]; + var HEAT_DAYS = 7; + + $scope.loaded = false; + $scope.loadError = ''; + $scope.busy = false; + $scope.info = {groups: [], schools: []}; + $scope.sel = {school: '', group: '', range: 'today', live: false}; + $scope.tab = {index: 0, name: 'overview'}; + $scope.rows = []; + $scope.loadedRows = false; + $scope.domains = []; + $scope.loadedDomains = false; + $scope.search = {domain: '', users: [], done: false}; + $scope.unreachable = []; + $scope.sort = {key: 'requests', reverse: true}; + $scope.tableFilter = {text: '', activeOnly: false, blockedOnly: false}; + $scope.detail = null; + $scope.settings = {servers: []}; + $scope.audit = []; + $scope.auditForm = {days: 7, actor: ''}; + $scope.enableDialog = null; + $scope.disableDialog = null; + $scope.hours = []; + var h; + for (h = 0; h < 24; h++) { + $scope.hours.push(h); + } + $scope.ranges = [ + {id: 'hour', label: gettext('This hour')}, + {id: 'today', label: gettext('Today so far')}, + {id: 'lesson', label: gettext('School hours')}, + {id: 'week', label: gettext('7 days')} + ]; + + function errorText(resp) { + var data = resp && resp.data; + if (data && data.message) { + return data.message; + } + if (data && data.detail) { + return typeof data.detail === 'string' ? data.detail : angular.toJson(data.detail); + } + return gettext('Request failed') + ' (' + (resp && resp.status) + ')'; + } + + // since/until in epoch seconds for a named range, in the browser's local time + function rangeOf(id, now) { + var d = new Date(now); + var end = Math.floor(now / 1000) + 60; + if (id === 'hour') { + d.setMinutes(0, 0, 0); + return [Math.floor(d.getTime() / 1000), end]; + } + if (id === 'lesson') { + var s = new Date(now); + s.setHours(LESSON_START[0], LESSON_START[1], 0, 0); + var e = new Date(now); + e.setHours(LESSON_END[0], LESSON_END[1], 0, 0); + return [Math.floor(s.getTime() / 1000), Math.min(Math.floor(e.getTime() / 1000), end)]; + } + d.setHours(0, 0, 0, 0); + if (id === 'week') { + d.setDate(d.getDate() - 6); + } + return [Math.floor(d.getTime() / 1000), end]; + } + $scope.rangeOf = rangeOf; + + function rangeLabel() { + var r = rangeOf($scope.sel.range, Date.now()); + var from = new Date(r[0] * 1000); + var to = new Date(Math.min(r[1] * 1000, Date.now())); + function two(n) { return (n < 10 ? '0' : '') + n; } + function fmt(x) { return two(x.getDate()) + '.' + two(x.getMonth() + 1) + '. ' + two(x.getHours()) + ':' + two(x.getMinutes()); } + $scope.rangeText = fmt(from) + ' – ' + fmt(to); + } + + function selectedGroup() { + if (!$scope.sel.group) { + return null; + } + var i = $scope.sel.group.indexOf(':'); + return {kind: $scope.sel.group.substring(0, i), name: $scope.sel.group.substring(i + 1)}; + } + + function groupMembers() { + var g = selectedGroup(); + var i; + if (!g) { + return []; + } + for (i = 0; i < $scope.info.groups.length; i++) { + if ($scope.info.groups[i].kind === g.kind && $scope.info.groups[i].name === g.name) { + return $scope.info.groups[i].members || []; + } + } + return []; + } + + function baseBody() { + var r = rangeOf($scope.sel.range, Date.now()); + return {since: r[0], until: r[1], school: $scope.sel.school || null, group: selectedGroup()}; + } + + // The proxies' rows plus every member of the chosen group without activity (zeros), so a + // class shows all its students. + function mergeRows(found, members) { + var byUser = {}; + var out = []; + angular.forEach(found, function (r) { + byUser[r.user] = r; + out.push(r); + }); + angular.forEach(members, function (m) { + if (!byUser[m.user]) { + out.push({user: m.user, display: m.display, requests: 0, domains: 0, blocked: 0, last: 0, active_now: false}); + } + }); + return out; + } + $scope.mergeRows = mergeRows; + + $scope.rowVisible = function (r) { + var text = ($scope.tableFilter.text || '').toLowerCase(); + if (text && (r.display || '').toLowerCase().indexOf(text) < 0 && r.user.indexOf(text) < 0) { + return false; + } + if ($scope.tableFilter.activeOnly && !r.requests) { + return false; + } + if ($scope.tableFilter.blockedOnly && !r.blocked) { + return false; + } + return true; + }; + + $scope.sortBy = function (key) { + if ($scope.sort.key === key) { + $scope.sort.reverse = !$scope.sort.reverse; + } else { + $scope.sort.key = key; + $scope.sort.reverse = key !== 'display' && key !== 'user'; + } + }; + + function loadUsers() { + $scope.busy = true; + return $http.post(API + '/query/users', baseBody()).then(function (resp) { + $scope.rows = mergeRows(resp.data.users || [], groupMembers()); + $scope.unreachable = resp.data.unreachable || []; + $scope.loadedRows = true; + }, function (resp) { + notify.error(errorText(resp)); + }).finally(function () { + $scope.busy = false; + }); + } + + function loadDomains() { + $scope.busy = true; + return $http.post(API + '/query/domains', baseBody()).then(function (resp) { + $scope.domains = resp.data.domains || []; + $scope.unreachable = resp.data.unreachable || []; + $scope.loadedDomains = true; + }, function (resp) { + notify.error(errorText(resp)); + }).finally(function () { + $scope.busy = false; + }); + } + + $scope.runSearch = function () { + var domain = ($scope.search.domain || '').trim(); + if (!domain) { + return; + } + var body = baseBody(); + body.domain = domain; + $scope.busy = true; + $http.post(API + '/query/search', body).then(function (resp) { + $scope.search.users = resp.data.users || []; + $scope.search.done = true; + $scope.unreachable = resp.data.unreachable || []; + }, function (resp) { + notify.error(errorText(resp)); + }).finally(function () { + $scope.busy = false; + }); + }; + + $scope.searchFor = function (domain) { + $scope.search.domain = domain; + $scope.tab.index = 2; + $scope.tab.name = 'search'; + $scope.runSearch(); + }; + + $scope.reload = function () { + rangeLabel(); + if ($scope.tab.name === 'overview') { + return loadUsers(); + } + if ($scope.tab.name === 'domains') { + return loadDomains(); + } + if ($scope.tab.name === 'search' && $scope.search.done) { + return $scope.runSearch(); + } + if ($scope.tab.name === 'settings') { + return $scope.loadSettings(); + } + if ($scope.tab.name === 'audit') { + return $scope.loadAudit(); + } + }; + + $scope.selectTab = function (name) { + $scope.tab.name = name; + $scope.reload(); + }; + + $scope.setRange = function (id) { + $scope.sel.range = id; + $scope.reload(); + }; + + $scope.changeGroup = function () { + $scope.rows = []; + $scope.reload(); + }; + + function loadScope() { + var params = $scope.sel.school ? {school: $scope.sel.school} : {}; + return $http.get(API + '/scope', {params: params}).then(function (resp) { + $scope.info = resp.data; + $scope.loaded = true; + $scope.loadError = ''; + }, function (resp) { + $scope.loaded = true; + $scope.loadError = errorText(resp); + }); + } + + $scope.changeSchool = function () { + $scope.sel.group = ''; + loadScope().then(function () { + $scope.reload(); + }); + }; + + var live = null; + $scope.toggleLive = function () { + if (live) { + $interval.cancel(live); + live = null; + } + if ($scope.sel.live) { + live = $interval(function () { + if (!$scope.busy && ($scope.tab.name === 'overview' || $scope.tab.name === 'domains')) { + $scope.reload(); + } + }, LIVE_SECONDS * 1000); + } + }; + $scope.$on('$destroy', function () { + if (live) { + $interval.cancel(live); + } + }); + + // ------------------------------------------------------------- one user + function heatColor(n, max) { + if (!n) { + return '#f2f2f2'; + } + var level = Math.min(1, Math.log(1 + n) / Math.log(1 + Math.max(max, 1))); + var light = Math.round(90 - level * 55); + return 'hsl(207, 70%, ' + light + '%)'; + } + + // days x hours from the hourly rows: the last HEAT_DAYS local days + function buildHeat(rows, now) { + var byHour = {}; + var max = 0; + angular.forEach(rows, function (r) { + byHour[r.t] = r; + max = Math.max(max, r.requests); + }); + var days = []; + var start = new Date(now); + start.setHours(0, 0, 0, 0); + start.setDate(start.getDate() - (HEAT_DAYS - 1)); + var names = [gettext('Sun'), gettext('Mon'), gettext('Tue'), gettext('Wed'), gettext('Thu'), gettext('Fri'), gettext('Sat')]; + var d; + for (d = 0; d < HEAT_DAYS; d++) { + var day = new Date(start.getTime()); + day.setDate(start.getDate() + d); + var cells = []; + var hh; + for (hh = 0; hh < 24; hh++) { + var at = new Date(day.getTime()); + at.setHours(hh, 0, 0, 0); + var t = Math.floor(at.getTime() / 1000); + var row = byHour[t] || {requests: 0, blocked: 0}; + cells.push({ + t: t, + requests: row.requests, + blocked: row.blocked, + color: heatColor(row.requests, max), + title: hh + ':00 – ' + row.requests + ' ' + gettext('requests in this hour') + (row.blocked ? ', ' + row.blocked + ' ' + gettext('of them blocked') : '') + }); + } + days.push({label: names[day.getDay()] + ' ' + day.getDate() + '.' + (day.getMonth() + 1) + '.', cells: cells}); + } + return days; + } + $scope.buildHeat = buildHeat; + + $scope.openUser = function (r) { + var now = Date.now(); + var week = rangeOf('week', now); + var school = $scope.sel.school || null; + $scope.detail = {user: r.user, display: r.display || r.user, heat: buildHeat([], now), domains: [], minutes: [], hourT: null, unreachable: []}; + var detail = $scope.detail; + $http.post(API + '/query/timeline', {user: r.user, since: week[0], until: week[1], resolution: 'hour', school: school}).then(function (resp) { + detail.heat = buildHeat(resp.data.rows || [], now); + detail.unreachable = resp.data.unreachable || []; + }, function (resp) { + notify.error(errorText(resp)); + }); + var body = baseBody(); + body.user = r.user; + body.group = null; + $http.post(API + '/query/domains', body).then(function (resp) { + detail.domains = resp.data.domains || []; + detail.domainsLoaded = true; + }, function (resp) { + notify.error(errorText(resp)); + }); + }; + + $scope.openHour = function (cell) { + if (!$scope.detail || !cell.requests) { + return; + } + var detail = $scope.detail; + detail.hourT = cell.t; + detail.minutes = []; + $http.post(API + '/query/timeline', {user: detail.user, since: cell.t, until: cell.t + 3600, resolution: 'minute', school: $scope.sel.school || null}).then(function (resp) { + detail.minutes = resp.data.rows || []; + }, function (resp) { + notify.error(errorText(resp)); + }); + }; + + $scope.closeDetail = function () { $scope.detail = null; }; + + // ------------------------------------------------------------- export + $scope.exportCsv = function () { + $scope.busy = true; + $http.post(API + '/export', baseBody()).then(function (resp) { + var blob = new $window.Blob([resp.data.csv], {type: 'text/csv;charset=utf-8'}); + var link = $window.document.createElement('a'); + link.href = $window.URL.createObjectURL(blob); + link.download = 'internetprotokoll.csv'; + $window.document.body.appendChild(link); + link.click(); + $window.document.body.removeChild(link); + if ((resp.data.unreachable || []).length) { + notify.warning(gettext('Some proxy servers were not reachable; their data are missing.')); + } + }, function (resp) { + notify.error(errorText(resp)); + }).finally(function () { + $scope.busy = false; + }); + }; + + // ------------------------------------------------- global administrators + $scope.loadSettings = function () { + return $http.get(API + '/settings').then(function (resp) { + angular.forEach(resp.data.servers, function (srv) { + angular.forEach(srv.instances, function (inst) { + inst.newRetention = inst.retention_days; + }); + }); + $scope.settings = resp.data; + $scope.unreachable = resp.data.unreachable || []; + }, function (resp) { + notify.error(errorText(resp)); + }); + }; + + function putSettings(srv, inst, body) { + return $http.put(API + '/settings/' + encodeURIComponent(srv.connection) + '/' + encodeURIComponent(inst.name), body); + } + + $scope.saveRetention = function (srv, inst) { + putSettings(srv, inst, {enabled: inst.enabled, retention_days: inst.newRetention}).then(function () { + notify.success(gettext('Retention saved')); + $scope.loadSettings(); + }, function (resp) { + notify.error(errorText(resp)); + }); + }; + + $scope.askEnable = function (srv, inst) { + $scope.enableDialog = {srv: srv, inst: inst, retention: inst.newRetention || inst.retention_days, confirmed: false, busy: false, error: ''}; + }; + $scope.closeEnable = function () { $scope.enableDialog = null; }; + $scope.confirmEnable = function () { + var dlg = $scope.enableDialog; + dlg.busy = true; + dlg.error = ''; + putSettings(dlg.srv, dlg.inst, {enabled: true, retention_days: dlg.retention, privacy_confirmed: dlg.confirmed === true}).then(function () { + $scope.enableDialog = null; + notify.success(gettext('Activity log switched on')); + $scope.loadSettings(); + }, function (resp) { + dlg.busy = false; + dlg.error = errorText(resp); + }); + }; + + $scope.askDisable = function (srv, inst) { + $scope.disableDialog = {srv: srv, inst: inst, deleteData: false, busy: false, error: ''}; + }; + $scope.closeDisable = function () { $scope.disableDialog = null; }; + $scope.confirmDisable = function () { + var dlg = $scope.disableDialog; + dlg.busy = true; + dlg.error = ''; + putSettings(dlg.srv, dlg.inst, {enabled: false, delete_data: dlg.deleteData === true}).then(function () { + $scope.disableDialog = null; + notify.success(gettext('Activity log switched off')); + $scope.loadSettings(); + }, function (resp) { + dlg.busy = false; + dlg.error = errorText(resp); + }); + }; + + $scope.loadAudit = function () { + var params = {days: $scope.auditForm.days || 7}; + if ($scope.auditForm.actor) { + params.actor = $scope.auditForm.actor; + } + return $http.get(API + '/audit', {params: params}).then(function (resp) { + $scope.audit = resp.data.entries || []; + $scope.unreachable = resp.data.unreachable || []; + }, function (resp) { + notify.error(errorText(resp)); + }); + }; + + loadScope().then(function () { + if (!$scope.loadError) { + $scope.reload(); + } + }); +}); diff --git a/webui/lmn_squid/resources/js/routing.es b/webui/lmn_squid/resources/js/routing.es index a084b7e..fa40eba 100644 --- a/webui/lmn_squid/resources/js/routing.es +++ b/webui/lmn_squid/resources/js/routing.es @@ -5,4 +5,8 @@ angular.module('lmn.squid').config(function ($routeProvider) { templateUrl: '/lmn_squid:resources/partial/index.html', controller: 'LMNSquidIndexController' }); + $routeProvider.when('/view/lmn/squid-activity', { + templateUrl: '/lmn_squid:resources/partial/activity.html', + controller: 'LMNSquidActivityController' + }); }); diff --git a/webui/lmn_squid/resources/partial/activity.html b/webui/lmn_squid/resources/partial/activity.html new file mode 100644 index 0000000..2b3df12 --- /dev/null +++ b/webui/lmn_squid/resources/partial/activity.html @@ -0,0 +1,309 @@ + +
+ +
{{loadError}}
+ +
+
+
+ + +
+
+ + +
+
+ +
+
+ + + +
+
+

{{rangeText}} · Only students of your classes and projects are shown.

+ +
+ Proxy server not reachable, its data are missing: {{u.connection}} – {{u.message}} +
+
You are not a member of any class or project with students, so there is nothing to show.
+ + + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + +
NameLogin nameNumber of requestsDistinct domainsBlocked attemptsLast seen
{{r.display}}{{r.user}}{{r.requests | number}}{{r.domains == null ? '–' : (r.domains | number)}}{{r.blocked | number}}0{{r.last ? (r.last * 1000 | date:'dd.MM. HH:mm') : '–'}}
+

No activity in this time range.

+
+ + +
+ + + + + + + + + + + + + + + + + + + +
Domain nameCategoryNumber of requestsDistinct usersBlocked attempts
{{d.domain}}{{d.category}}{{d.requests | number}}{{d.users | number}}{{d.blocked | number}}
+

No activity in this time range.

+
+ + +
+
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + +
NameLogin nameNumber of requestsBlocked attemptsFirst visitLast visitDistinct domains
{{u.display}}{{u.user}}{{u.requests | number}}{{u.blocked | number}}{{u.first * 1000 | date:'dd.MM. HH:mm'}}{{u.last * 1000 | date:'dd.MM. HH:mm'}}{{u.domains.join(', ')}}
+

Nobody in your scope was on this domain in this time range.

+
+ + +
+

The activity log is off for every instance until it is switched on here. Switching it on or off restarts the instance (a few seconds). The retention applies at once.

+
+

{{srv.display_name}} {{srv.timezone}}

+ + + + + + + + + + + + + + + + + + + + + +
InstanceActivity logRetention (days)Stored dataConfirmed by
{{inst.name}}{{inst.enabled ? ('on' | translate) : ('off' | translate)}}{{inst.usage.days}} days of data, {{inst.usage.bytes / 1048576 | number:1}} MB{{inst.ack_by}} {{inst.ack_at}} + + + +
+
+
+ + +
+
+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + +
Time of accessRead byRoleQuery typeWhose dataQueried time rangeProxy server
{{e.ts * 1000 | date:'dd.MM.yyyy HH:mm:ss'}}{{e.actor}}{{e.role}}{{e.action}} {{e.domain || e.user || e.instance}}{{e.scope}} ({{e.users_count}}){{e.since * 1000 | date:'dd.MM. HH:mm'}} – {{e.until * 1000 | date:'dd.MM. HH:mm'}}{{e.connection}}
+
+
+
+ + + + + + + + + + + + + + + + + + + + + diff --git a/webui/pyproject.toml b/webui/pyproject.toml index acb2481..8c57cc0 100644 --- a/webui/pyproject.toml +++ b/webui/pyproject.toml @@ -19,7 +19,7 @@ warn_redundant_casts = true [[tool.mypy.overrides]] # Provided by linuxmuster-webui7 (and its venv: paramiko) at run time; tests stub them. -module = ["aj", "aj.*", "jadi", "paramiko"] +module = ["aj", "aj.*", "jadi", "paramiko", "linuxmusterTools", "linuxmusterTools.*"] ignore_missing_imports = true [tool.pytest.ini_options] diff --git a/webui/tests/conftest.py b/webui/tests/conftest.py index f5db4a1..ebaa135 100644 --- a/webui/tests/conftest.py +++ b/webui/tests/conftest.py @@ -148,7 +148,7 @@ def inner(f: Any) -> Any: AJ = _install_stubs() sys.path.insert(0, str(WEBUI)) -from lmn_squid import views # noqa: E402 +from lmn_squid import activity_views, views # noqa: E402 from lmn_squid.connections import ConnectionStore # noqa: E402 @@ -199,6 +199,9 @@ def __init__(self, store_path: Path) -> None: self.context = types.SimpleNamespace(identity=None, profile={}) self.handler = views.Handler(self.context) self.handler.store = ConnectionStore(str(store_path)) + # the activity log view (ADR-023): its own HttpPlugin, same connections + self.activity = activity_views.ActivityHandler(self.context) + self.activity.store = self.handler.store self.as_role("globaladministrator") def as_role(self, role: str, granted: set[str] | None = None, user: str = "admin1") -> None: @@ -227,8 +230,9 @@ def call( env: dict | None = None, ) -> tuple[int, Any]: ctx = HttpContext(method, path, body, query, env) + handler = self.activity if path.startswith(activity_views.PREFIX + "/") else self.handler try: - out = self.handler.handle(ctx) + out = handler.handle(ctx) except AJ.SecurityError: # aj.routing: respond_forbidden return 403, "Forbidden" if out is None: @@ -321,6 +325,8 @@ def control_plane(tmp_path: Path, token: str) -> Iterator[dict[str, Any]]: catalog_custom=str(tmp_path / "catalog-custom.yml"), protected_file=str(tmp_path / "protected.domains"), filter_timezone="Europe/Berlin", + activity_dir=str(tmp_path / "activity"), + activity_spool_dir=str(tmp_path / "spool"), ) store = Store(settings.instances_dir) docker = cp.FakeDockerService( @@ -356,6 +362,8 @@ def capture_signals(self) -> Iterator[None]: "fingerprint": fingerprint(crt), "recorder": app, "docker": docker, + "settings": settings, + "store": store, } finally: server.should_exit = True diff --git a/webui/tests/js/activity_check.js b/webui/tests/js/activity_check.js new file mode 100644 index 0000000..aa7b842 --- /dev/null +++ b/webui/tests/js/activity_check.js @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Runs the built bundle's activity controller (ADR-023) in node against stand-ins of angular, +// $http and notify: time ranges, a class with members without activity, the heat map, the +// requests the page sends. usage: node activity_check.js +'use strict'; +const fs = require('fs'); +const assert = require('assert'); + +process.env.TZ = 'Europe/Berlin'; +const controllers = {}; +const mod = { + config() { return mod; }, + controller(name, fn) { controllers[name] = fn; return mod; }, +}; +global.angular = { + module: () => mod, + isArray: Array.isArray, + copy: (x) => JSON.parse(JSON.stringify(x)), + toJson: JSON.stringify, + forEach: (obj, fn) => { (obj || []).forEach ? obj.forEach(fn) : Object.keys(obj).forEach((k) => fn(obj[k], k)); }, +}; +new Function(fs.readFileSync(process.argv[2], 'utf8'))(); +const Ctrl = controllers.LMNSquidActivityController; +assert(Ctrl, 'activity controller registered'); + +function settled(ok, value) { + return { + then(onOk, onErr) { + const cb = ok ? onOk : onErr; + if (!cb) { return settled(ok, value); } + const out = cb(value); + return out && out.then ? out : settled(true, out); + }, + finally(cb) { cb(); return settled(ok, value); }, + }; +} + +const posts = []; +const scopeAnswer = { + role: 'teacher', school: 'default-school', schools: [], can_export: false, is_global: false, + groups: [{kind: 'class', name: '5a', count: 2, members: [ + {user: 's5a1', display: 'Anna'}, {user: 's5a2', display: 'Ben'}]}], +}; +const $http = { + get(url) { + assert.strictEqual(url, '/api/lmn/squid-activity/scope'); + return settled(true, {data: scopeAnswer}); + }, + post(url, body) { + posts.push([url, body]); + if (url.endsWith('/query/users')) { + return settled(true, {data: {users: [{user: 's5a1', display: 'Anna', requests: 5, blocked: 1, domains: 2, last: 1, active_now: true}], unreachable: []}}); + } + if (url.endsWith('/query/timeline')) { + return settled(true, {data: {rows: [], unreachable: []}}); + } + return settled(true, {data: {domains: [], unreachable: []}}); + }, + put() { return settled(true, {data: {}}); }, +}; +const $scope = {$on() {}}; +const notify = {error(m) { throw new Error('notify.error ' + m); }, success() {}, warning() {}}; +const $interval = () => 1; +$interval.cancel = () => {}; +Ctrl($scope, $http, $interval, {}, {set() {}}, (s) => s, notify); + +// first load: scope, then the overview of all my students for today +assert.strictEqual($scope.info.role, 'teacher'); +assert.strictEqual(posts[0][0], '/api/lmn/squid-activity/query/users'); +assert.strictEqual(posts[0][1].group, null); + +// a class: its members without activity are shown with zeros +$scope.sel.group = 'class:5a'; +$scope.changeGroup(); +const last = posts[posts.length - 1][1]; +assert.deepStrictEqual(last.group, {kind: 'class', name: '5a'}); +assert.deepStrictEqual($scope.rows.map((r) => [r.user, r.requests]), [['s5a1', 5], ['s5a2', 0]]); +assert.strictEqual($scope.rowVisible({user: 's5a2', display: 'Ben', requests: 0, blocked: 0}), true); +$scope.tableFilter.activeOnly = true; +assert.strictEqual($scope.rowVisible({user: 's5a2', display: 'Ben', requests: 0, blocked: 0}), false); + +// ranges in local time +const noon = new Date(2026, 10, 25, 12, 34, 56).getTime(); +const day = $scope.rangeOf('today', noon); +assert.strictEqual(new Date(day[0] * 1000).getHours(), 0); +const hour = $scope.rangeOf('hour', noon); +assert.strictEqual(new Date(hour[0] * 1000).getMinutes(), 0); +assert.strictEqual(new Date(hour[0] * 1000).getHours(), 12); +const week = $scope.rangeOf('week', noon); +assert.strictEqual(new Date(week[0] * 1000).getDate(), 19); +const lesson = $scope.rangeOf('lesson', noon); +assert.strictEqual(new Date(lesson[0] * 1000).getHours(), 7); +assert(lesson[1] > lesson[0]); + +// heat map: 7 days x 24 hours, the hour with data coloured +const t = Math.floor(new Date(2026, 10, 25, 9, 0, 0).getTime() / 1000); +const heat = $scope.buildHeat([{t: t, requests: 10, blocked: 2}], noon); +assert.strictEqual(heat.length, 7); +assert.strictEqual(heat[6].cells.length, 24); +assert.strictEqual(heat[6].cells[9].requests, 10); +assert.strictEqual(heat[6].cells[9].blocked, 2); +assert.notStrictEqual(heat[6].cells[9].color, heat[6].cells[8].color); + +// one user: heat map and domains are asked for that user only +$scope.openUser({user: 's5a1', display: 'Anna'}); +const asked = posts.slice(-2); +assert.strictEqual(asked[0][1].user, 's5a1'); +assert.strictEqual(asked[0][1].resolution, 'hour'); +assert.strictEqual(asked[1][1].user, 's5a1'); +assert.strictEqual(asked[1][1].group, null); +$scope.closeDetail(); +assert.strictEqual($scope.detail, null); +console.log('activity controller ok'); diff --git a/webui/tests/test_activity_views.py b/webui/tests/test_activity_views.py new file mode 100644 index 0000000..d1e39bb --- /dev/null +++ b/webui/tests/test_activity_views.py @@ -0,0 +1,390 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The activity log view (ADR-023) against a real control plane and a fake AD shaped like +linuxmusterTools' LMNLdapReader answers (/users/, /rawusers, /projects/). + +Scope: a teacher sees only students of their own classes and projects (also through a project's +member group), never teachers of the same class, never another school; a school administrator +their school; students and other roles nothing, also with the permission granted by hand; the +role is read from the AD, not from the session. The proxy gets exactly the allowed users list +and audits the query with the person. +""" + +from __future__ import annotations + +import time +from pathlib import Path +from typing import Any, Iterator +from zoneinfo import ZoneInfo + +import pytest +from conftest import SAME_ORIGIN, WebUI, control_plane, free_port, needs_openssl + +from lmn_squid import activity_scope, activity_views + +pytestmark = needs_openssl + +TOKEN = "cp-token-0123456789abcdef0123456789" +PREFIX = "/api/lmn/squid-activity" + + +def _user( + name: str, + role: str, + school: str = "default-school", + classes: list[str] | None = None, + projects: list[str] | None = None, + display: str = "", +) -> dict[str, Any]: + return { + "sAMAccountName": name, + "sophomorixRole": role, + "sophomorixSchoolname": school, + "schoolclasses": classes or [], + "projects": projects or [], + "displayName": display or name.upper(), + } + + +USERS = [ + _user("global-admin", "globaladministrator", "global"), + _user("pgmadmin", "schooladministrator"), + _user("dslehr01", "teacher", classes=["5a"], projects=["p_robotik"]), + _user("dslehr02", "teacher", classes=["6b"]), + _user("dslehr03", "teacher", classes=["5a"]), # a teacher in the same class: never shown + _user("dslehr04", "teacher", classes=["students"]), # a role group as "class": ignored + _user("s5a1", "student", classes=["5a"]), + _user("s5a2", "student", classes=["5a"]), + _user("s6b1", "student", classes=["6b"]), + _user("s7c1", "student", classes=["7c"]), # in p_robotik through its member group 7c + _user("sp1", "student", classes=["8d"], projects=["p_robotik"]), + _user("dsstaff01", "staff"), + _user("o5a1", "student", "one", classes=["5a"]), # another school, same class name + _user("onelehr", "teacher", "one", classes=["5a"]), +] + + +class FakeDirectory: + def __init__(self) -> None: + self.users = {u["sAMAccountName"]: dict(u) for u in USERS} + self.calls: list[str] = [] + + def person(self, name: str) -> dict[str, Any] | None: + self.calls.append(f"person {name}") + return self.users.get(name) + + def school_users(self, school: str) -> list[dict[str, Any]]: + self.calls.append(f"school {school}") + # the reader returns only entries below OU= + return [u for u in self.users.values() if u["sophomorixSchoolname"] == school] + + def project_groups(self, school: str, project: str) -> list[str]: + return ["7c"] if project == "p_robotik" else [] + + +@pytest.fixture +def ad(webui: WebUI) -> Iterator[FakeDirectory]: + fake = FakeDirectory() + activity_scope.CACHE.clear() + webui.activity.directory_factory = lambda: fake # type: ignore[method-assign] + yield fake + activity_scope.CACHE.clear() + + +@pytest.fixture +def cp(tmp_path: Path) -> Iterator[dict[str, Any]]: + with control_plane(tmp_path / "cp", TOKEN) as info: + yield info + + +def login(webui: WebUI, user: str, role: str, granted: set[str] | None = None) -> None: + webui.as_role(role, granted=granted, user=user) + activity_scope.CACHE.clear() + + +def setup_proxy(webui: WebUI, cp: dict[str, Any], seed: bool = True) -> int: + """One proxy with default-school-students (log on) and data of every user; returns now.""" + login(webui, "global-admin", "globaladministrator") + body = {"name": "proxy1", "url": cp["url"], "token": TOKEN, "fingerprint": cp["fingerprint"]} + assert webui.call("POST", "/api/lmn/squid/connections", body)[0] == 200 + inst = { + "school": "default-school", + "role": "students", + "ad_group": "students", + "realm": "DEV.LMSCHULE.DE", + "visible_hostname": "proxy.dev.lmschule.de", + "keytab_secret": "proxy.keytab", + "image": "ghcr.io/faircomp/linuxmuster-squid:test", + } + assert webui.call("POST", "/api/lmn/squid/proxy1/instances", inst)[0] == 200 + status, data = webui.call( + "PUT", + f"{PREFIX}/settings/proxy1/default-school-students", + {"enabled": True, "privacy_confirmed": True, "retention_days": 7}, + ) + assert status == 200, data + assert data["enabled"] and data["ack_by"] == "global-admin" + now = int(time.time()) + if seed: + from lmnsquid import activity + + settings = cp["settings"] + spool = activity.ensure_spool(settings.activity_spool_dir, "default-school-students") + lines = "".join( + f"{now - 60} {u['sAMAccountName']}@DEV.LMSCHULE.DE site-{u['sAMAccountName']}.example " + "200 TCP_TUNNEL 100 -\n" + for u in USERS + ) + lines += f"{now - 30} s5a1@DEV.LMSCHULE.DE bad.example 403 TCP_DENIED 10 porn\n" + (spool / f"act-{now:010d}-aaaa0000-000001.log").write_text(lines) + stored = cp["store"].get("default-school-students") + activity.collect_instance( + stored, settings.activity_dir, settings.activity_spool_dir, ZoneInfo("Europe/Berlin") + ) + return now + + +def users_of(webui: WebUI, now: int, **extra: Any) -> tuple[int, Any]: + return webui.call( + "POST", f"{PREFIX}/query/users", {"since": now - 3600, "until": now + 60, **extra} + ) + + +def proxy_bodies(cp: dict[str, Any], path: str) -> list[str]: + return [p for (_m, p, _a) in cp["recorder"].seen if p == path] + + +# ------------------------------------------------------------------------- scope + + +def test_teacher_sees_only_students_of_own_classes_and_projects( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp) + login(webui, "dslehr01", "teacher") + status, info = webui.call("GET", f"{PREFIX}/scope") + assert status == 200 and info["role"] == "teacher" and info["school"] == "default-school" + groups = {(g["kind"], g["name"]): [m["user"] for m in g["members"]] for g in info["groups"]} + assert groups == {("class", "5a"): ["s5a1", "s5a2"], ("project", "p_robotik"): ["s7c1", "sp1"]} + assert info["can_export"] is False and info["is_global"] is False + + status, data = users_of(webui, now) + assert status == 200, data + assert sorted(u["user"] for u in data["users"]) == ["s5a1", "s5a2", "s7c1", "sp1"] + status, data = users_of(webui, now, group={"kind": "class", "name": "5a"}) + assert sorted(u["user"] for u in data["users"]) == ["s5a1", "s5a2"] + s5a1 = next(u for u in data["users"] if u["user"] == "s5a1") + assert (s5a1["blocked"], s5a1["display"]) == (1, "S5A1") + + # the proxy audited it with the person and the class + login(webui, "global-admin", "globaladministrator") + status, audit = webui.call("GET", f"{PREFIX}/audit", query={"days": "1"}) + assert status == 200 + mine = [e for e in audit["entries"] if e["actor"] == "dslehr01"] + assert mine[0]["scope"] == "class 5a" and mine[0]["users"] == ["s5a1", "s5a2"] + assert mine[0]["role"] == "teacher" + + +def test_teacher_is_refused_outside_the_scope( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp) + login(webui, "dslehr01", "teacher") + asked = len(cp["recorder"].seen) + for body in ( + {"group": {"kind": "class", "name": "6b"}}, + {"group": {"kind": "class", "name": "students"}}, + {"school": "one"}, + ): + assert users_of(webui, now, **body)[0] == 403, body + for user in ("s6b1", "dslehr03", "o5a1", "pgmadmin"): + status, _ = webui.call( + "POST", + f"{PREFIX}/query/timeline", + {"user": user, "since": now - 3600, "until": now + 60}, + ) + assert status == 403, user + status, _ = webui.call( + "POST", + f"{PREFIX}/query/domains", + {"user": user, "since": now - 3600, "until": now + 60}, + ) + assert status == 403, user + assert webui.call("POST", f"{PREFIX}/export", {"since": now - 60, "until": now})[0] == 403 + assert webui.call("GET", f"{PREFIX}/audit")[0] == 403 + assert webui.call("GET", f"{PREFIX}/settings")[0] == 403 + status, _ = webui.call( + "PUT", f"{PREFIX}/settings/proxy1/default-school-students", {"enabled": False} + ) + assert status == 403 + assert len(cp["recorder"].seen) == asked, "nothing reached a proxy" + + +def test_teacher_search_and_domains_stay_in_scope( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp) + login(webui, "dslehr01", "teacher") + status, data = webui.call( + "POST", + f"{PREFIX}/query/search", + {"domain": "example", "since": now - 3600, "until": now + 60}, + ) + assert status == 200 + assert sorted(u["user"] for u in data["users"]) == ["s5a1", "s5a2", "s7c1", "sp1"] + status, data = webui.call( + "POST", f"{PREFIX}/query/domains", {"since": now - 3600, "until": now + 60} + ) + domains = {d["domain"] for d in data["domains"]} + assert "site-dslehr03.example" not in domains and "site-s6b1.example" not in domains + assert "bad.example" in domains + status, data = webui.call( + "POST", + f"{PREFIX}/query/timeline", + {"user": "s7c1", "since": now - 3600, "until": now + 60, "resolution": "minute"}, + ) + assert status == 200 and data["rows"][0]["domain"] == "site-s7c1.example" + + +def test_school_admin_sees_the_school_and_nothing_else( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp) + login(webui, "pgmadmin", "schooladministrator") + status, data = users_of(webui, now) + assert status == 200 + found = {u["user"] for u in data["users"]} + assert "dslehr03" in found and "s6b1" in found and "pgmadmin" in found + assert not found & {"o5a1", "onelehr", "global-admin"} + assert users_of(webui, now, school="one")[0] == 403 + status, data = webui.call( + "POST", + f"{PREFIX}/export", + {"since": now - 3600, "until": now + 60, "group": {"kind": "class", "name": "6b"}}, + ) + assert status == 200 + rows = data["csv"].strip().splitlines() + # a school administrator sees every member of the class, teachers included + assert rows[0].startswith("time,user,domain") and len(rows) == 3 + assert {r.split(",")[1] for r in rows[1:]} == {"s6b1", "dslehr02"} + assert webui.call("GET", f"{PREFIX}/audit")[0] == 403 + + +def test_students_and_other_roles_get_nothing( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp, seed=False) + asked = len(cp["recorder"].seen) + for user, role in (("s5a1", "student"), ("dsstaff01", "staff")): + # also with the permission granted by hand + login(webui, user, role, granted={activity_views.PERM_ACTIVITY}) + assert webui.call("GET", f"{PREFIX}/scope")[0] == 403 + assert users_of(webui, now)[0] == 403 + assert ( + webui.call( + "POST", f"{PREFIX}/query/timeline", {"user": user, "since": now - 60, "until": now} + )[0] + == 403 + ) + # and without it, aj's authorize refuses first + login(webui, user, role) + assert webui.call("GET", f"{PREFIX}/scope")[0] == 403 + assert len(cp["recorder"].seen) == asked + + +def test_the_role_comes_from_the_ad_not_from_the_session( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp, seed=False) + # a session that claims globaladministrator for a user the AD knows as a student + login(webui, "s5a1", "globaladministrator") + assert users_of(webui, now)[0] == 403 + # a teacher removed from a class loses it at once (cache cleared like after its ttl) + login(webui, "dslehr01", "teacher") + ad.users["dslehr01"]["schoolclasses"] = [] + ad.users["dslehr01"]["projects"] = [] + activity_scope.CACHE.clear() + assert users_of(webui, now, group={"kind": "class", "name": "5a"})[0] == 403 + + +def test_global_admin_all_schools_and_settings( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp) + login(webui, "global-admin", "globaladministrator") + status, info = webui.call("GET", f"{PREFIX}/scope") + assert info["is_global"] and info["schools"] == ["default-school"] and info["groups"] == [] + status, data = users_of(webui, now) + assert len(data["users"]) == len(USERS) + status, info = webui.call("GET", f"{PREFIX}/scope", query={"school": "default-school"}) + assert ("class", "5a") in {(g["kind"], g["name"]) for g in info["groups"]} + status, settings = webui.call("GET", f"{PREFIX}/settings") + inst = settings["servers"][0]["instances"][0] + assert inst["enabled"] and inst["usage"]["days"] == 1 + # switching on again without the confirmation: the proxy refuses (422 passed on) + path = f"{PREFIX}/settings/proxy1/default-school-students" + assert webui.call("PUT", path, {"enabled": False, "delete_data": True})[0] == 200 + status, data = webui.call("PUT", path, {"enabled": True}) + assert status == 422 and "privacy notice" in str(data) + webui.as_root() + activity_scope.CACHE.clear() + root_status, _ = webui.call("GET", f"{PREFIX}/settings") + assert root_status == 200 + + +def test_a_proxy_that_does_not_answer_does_not_block( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp) + body = { + "name": "down", + "url": f"https://127.0.0.1:{free_port()}", + "token": TOKEN, + "fingerprint": cp["fingerprint"], + } + assert webui.call("POST", "/api/lmn/squid/connections", body)[0] == 200 + login(webui, "dslehr01", "teacher") + started = time.monotonic() + status, data = users_of(webui, now) + assert time.monotonic() - started < 8 + assert status == 200 and len(data["users"]) == 4 + assert [u["connection"] for u in data["unreachable"]] == ["down"] + + +def test_state_changing_requests_need_json_from_the_same_site( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp, seed=False) + login(webui, "dslehr01", "teacher") + body = {"since": now - 60, "until": now} + form = {**SAME_ORIGIN, "CONTENT_TYPE": "text/plain"} + assert webui.call("POST", f"{PREFIX}/query/users", body, env=form)[0] == 415 + evil = {**SAME_ORIGIN, "HTTP_ORIGIN": "https://evil.example"} + assert webui.call("POST", f"{PREFIX}/query/users", body, env=evil)[0] == 403 + login(webui, "global-admin", "globaladministrator") + path = f"{PREFIX}/settings/proxy1/default-school-students" + assert webui.call("PUT", path, {"enabled": False}, env=evil)[0] == 403 + + +def test_bad_input_is_a_readable_422(webui: WebUI, ad: FakeDirectory, cp: dict[str, Any]) -> None: + setup_proxy(webui, cp, seed=False) + login(webui, "dslehr01", "teacher") + assert webui.call("POST", f"{PREFIX}/query/users", {"since": 10, "until": 5})[0] == 422 + assert webui.call("POST", f"{PREFIX}/query/users", {"since": "x", "until": 5})[0] == 422 + assert ( + webui.call("POST", f"{PREFIX}/query/timeline", {"user": "../x", "since": 1, "until": 5})[0] + == 422 + ) + assert ( + webui.call("POST", f"{PREFIX}/query/search", {"domain": "a b", "since": 1, "until": 5})[0] + == 422 + ) + assert webui.call("GET", f"{PREFIX}/scope", query={"school": "../x"})[0] == 422 + + +def test_every_activity_endpoint_needs_the_permission() -> None: + routes = [f for f in vars(activity_views.ActivityHandler).values() if hasattr(f, "url_pattern")] + assert len(routes) == 9 + for fn in routes: + assert fn.url_pattern.pattern.startswith("^/api/lmn/squid-activity/") + assert fn.permission_id == activity_views.PERM_ACTIVITY diff --git a/webui/tests/test_build.py b/webui/tests/test_build.py index d062fb0..e3f2423 100644 --- a/webui/tests/test_build.py +++ b/webui/tests/test_build.py @@ -26,6 +26,8 @@ def test_build_produces_what_the_webui_serves(tmp_path: Path) -> None: files = sorted(str(p.relative_to(dest)) for p in dest.rglob("*") if p.is_file()) assert files == [ "__init__.py", + "activity_scope.py", + "activity_views.py", "client.py", "connections.py", "jobs.py", @@ -41,9 +43,11 @@ def test_build_produces_what_the_webui_serves(tmp_path: Path) -> None: "resources/build/all.vendor.css", "resources/build/all.vendor.js", "resources/css/dialogs.css", + "resources/js/controllers/activity.controller.es", "resources/js/controllers/index.controller.es", "resources/js/module.es", "resources/js/routing.es", + "resources/partial/activity.html", "resources/partial/index.html", "runtime.py", "setup_runner.py", @@ -83,7 +87,7 @@ def test_po_parser() -> None: def msgids() -> set[str]: - html = (PLUGIN / "resources/partial/index.html").read_text() + html = "".join(p.read_text() for p in sorted((PLUGIN / "resources/partial").glob("*.html"))) ids = { " ".join(m.group(2).split()) for m in re.finditer(r"<(\w+)[^>]*\stranslate(?:\s[^>]*)?>(.*?)", html, re.S) @@ -125,7 +129,7 @@ def test_controller_logic_in_node(tmp_path: Path) -> None: def test_no_assignment_in_template_event_handlers() -> None: """`ng:click="detail = null"` inside a sets a property of the dialog's own scope, and the dialog never closed (webui7 7.3.44). Handlers call controller functions instead.""" - html = (PLUGIN / "resources/partial/index.html").read_text() + html = "".join(p.read_text() for p in sorted((PLUGIN / "resources/partial").glob("*.html"))) handlers = re.findall(r'ng[:-](?:click|submit|change|dblclick)="([^"]*)"', html) assert handlers bad = [h for h in handlers if re.search(r"(?])=(?!=)", h)] @@ -163,8 +167,8 @@ def handle_endtag(self, tag: str) -> None: def test_every_dialog_scrolls_inside_the_window(tmp_path: Path) -> None: """A dialog longer than the window could not be scrolled (Ajenti's renders a Bootstrap .modal with overflow hidden). Every dialog uses the plugin's scrollable layout: - class lmn-squid-dialog and exactly header, body, footer as children.""" - html = (PLUGIN / "resources/partial/index.html").read_text() + class lmn-squid-dialog and exactly header, body, footer as children (every page).""" + html = "".join(p.read_text() for p in sorted((PLUGIN / "resources/partial").glob("*.html"))) dialogs = _dialogs(html) assert len(dialogs) == html.count("= 8 for attrs, children in dialogs: @@ -229,3 +233,17 @@ def test_long_lists_in_dialogs_scroll_on_their_own() -> None: assert 'ng:repeat="g in detail.filter.catalog.grouped"' in html[first : first + 400] second = html.index(scroll, first + 1) assert 'ng:repeat="r in bulk.rows"' in html[second : second + 600] + + +@pytest.mark.skipif(shutil.which("node") is None, reason="node missing (controller checks)") +def test_activity_controller_logic_in_node(tmp_path: Path) -> None: + """The activity view (ADR-023): ranges, class members, heat map: tests/js/activity_check.js.""" + dest = tmp_path / "lmn_squid" + build_plugin.build(PLUGIN, dest) + check = WEBUI / "tests" / "js" / "activity_check.js" + out = subprocess.run( + ["node", str(check), str(dest / "resources/build/all.js")], + capture_output=True, + text=True, + ) + assert out.returncode == 0, out.stderr + out.stdout diff --git a/webui/tests/test_permissions.py b/webui/tests/test_permissions.py index cfc4ff9..eea69c0 100644 --- a/webui/tests/test_permissions.py +++ b/webui/tests/test_permissions.py @@ -1,30 +1,38 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later -"""Global administrators only: permissions.yml, the sidebar, and the server-side check.""" +"""The management for global administrators only: permissions.yml, the sidebar, and the +server-side check. The activity log view (lm:squid:activity) for teachers and administrators: +test_activity_views.py.""" from __future__ import annotations import yaml from conftest import WEBUI, WebUI -from lmn_squid import main, views +from lmn_squid import activity_views, main, views -PERMS = {p["id"] for p in main.Permissions().provide()} +ALL_PERMS = {p["id"] for p in main.Permissions().provide()} +PERMS = {views.PERM_LIST, views.PERM_CHANGE} +ACTIVITY = {activity_views.PERM_ACTIVITY, "sidebar:view:" + main.ACTIVITY_URL} +ACTIVITY_ROLES = ("globaladministrator", "schooladministrator", "teacher") def test_permissions_yml_grants_only_the_global_administrator() -> None: data = yaml.safe_load((WEBUI / "lmn_squid" / "permissions.yml").read_text()) assert set(data) == set(WebUI.ROLES) - expected_ids = PERMS | {"sidebar:view:" + main.URL} + expected_ids = ALL_PERMS | {"sidebar:view:" + main.URL, "sidebar:view:" + main.ACTIVITY_URL} for role, entries in data.items(): parsed = dict(e.split(": ") for e in entries) # merge-permissions.py format assert set(parsed) == expected_ids, role + management = {k: v for k, v in parsed.items() if k not in ACTIVITY} want = "true" if role == "globaladministrator" else "false" - assert set(parsed.values()) == {want}, role + assert set(management.values()) == {want}, role + activity = {parsed[k] for k in ACTIVITY} + assert activity == {"true" if role in ACTIVITY_ROLES else "false"}, role def test_permission_provider_defaults_deny() -> None: - assert PERMS == {views.PERM_LIST, views.PERM_CHANGE} + assert ALL_PERMS == PERMS | {activity_views.PERM_ACTIVITY} assert all(p["default"] is False for p in main.Permissions().provide()) From 50f0553ae6c6d7ef06bcd48f756dcd954b1590e6 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 11:05:41 +0100 Subject: [PATCH 08/45] test(perf): synthetic activity load (users x school day): collector time and RSS, day file size, query times --- scripts/tests/activity_load.py | 257 +++++++++++++++++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100755 scripts/tests/activity_load.py diff --git a/scripts/tests/activity_load.py b/scripts/tests/activity_load.py new file mode 100755 index 0000000..245cc6a --- /dev/null +++ b/scripts/tests/activity_load.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Synthetic load for the activity log (ADR-023): collector time and memory, day file size, +query times. Not part of run.sh (minutes of CPU); the numbers go into docs/operations.md. + + .venv/bin/python scripts/tests/activity_load.py [--users 1000] [--days 7] [--rate 8] [--work DIR] + +Model per school day: every user is online from 8:00 to 16:00, active in 70 % of the minutes +with on average ``--rate`` requests per active minute over 1-6 domains from a personal pool of +120 domains (Zipf over 30 000 domains); 2 % of the requests are blocked. The lines go into +30-second spool files as the receiver writes them; every day is collected as a backlog in a +child process (its peak RSS is the collector's memory), the last day also as single 30-second +runs (what the timer does). +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import os +import random +import resource +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from zoneinfo import ZoneInfo + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "controlplane")) + +from lmnsquid import activity +from lmnsquid.activity_query import Query, Source +from lmnsquid.models import Instance + +ZONE = ZoneInfo("Europe/Berlin") +NAME = "default-school-students" +HOSTS = 30_000 + + +def instance(retention: int) -> Instance: + return Instance( + school="default-school", + role="students", + ad_group="students", + realm="EX.LAN", + visible_hostname="proxy.example.lan", + keytab_secret="proxy.keytab", + image="ghcr.io/x/y:1", + activity_log_enabled=True, + activity_ack_by="load", + activity_ack_at="now", + activity_retention_days=retention, + ) + + +def zipf_hosts(rng: random.Random) -> list[str]: + weights = [1.0 / (i + 1) for i in range(HOSTS)] + names = [f"h{i}.example{i % 97}.org" for i in range(HOSTS)] + return rng.choices(names, weights=weights, k=120) + + +def generate_day( + spool: Path, day: datetime.date, users: int, rate: float, seed: int +) -> int: + rng = random.Random(seed) + pools = [zipf_hosts(rng) for _ in range(users)] + start = int(datetime.datetime.combine(day, datetime.time(8, 0), ZONE).timestamp()) + lines = 0 + for window in range(8 * 120): # 30-second files + t0 = start + window * 30 + out: list[str] = [] + for u in range(users): + if rng.random() > 0.7: + continue + n = max(1, int(rng.expovariate(1 / (rate / 2)))) + hosts = rng.sample(pools[u], k=min(len(pools[u]), rng.randint(1, 3))) + for _ in range(n): + host = rng.choice(hosts) + blocked = rng.random() < 0.02 + status, sq, cat = ( + ("403", "TCP_DENIED", "ads") + if blocked + else ("200", "TCP_TUNNEL", "-") + ) + out.append( + f"{t0 + rng.randrange(30)} schueler{u:04d}@EX.LAN {host} {status} {sq} " + f"{rng.randrange(200, 90000)} {cat}\n" + ) + lines += len(out) + (spool / f"act-{t0:010d}-load{seed:04d}-{window:06d}.log").write_text( + "".join(out) + ) + return lines + + +def collect_child( + data: str, spool_root: str, retention: int, now: float +) -> dict[str, float]: + code = ( + "import sys, time, json, resource\n" + f"sys.path.insert(0, {str(ROOT / 'controlplane')!r})\n" + "from zoneinfo import ZoneInfo\n" + "from lmnsquid import activity\n" + "sys.path.insert(0, " + repr(str(Path(__file__).parent)) + ")\n" + "import activity_load as L\n" + "t = time.monotonic()\n" + f"c = activity.collect_instance(L.instance({retention}), {data!r}, {spool_root!r}, " + f"ZoneInfo('Europe/Berlin'), now={now})\n" + "print(json.dumps({'seconds': time.monotonic() - t, 'lines': c.lines, 'rows': c.rows, " + "'files': c.files, 'maxrss_mib': resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024}))\n" + ) + out = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=True + ) + return json.loads(out.stdout.strip().splitlines()[-1]) + + +def timed(fn, repeat: int = 3) -> tuple[float, object]: # type: ignore[no-untyped-def] + best = float("inf") + result = None + for _ in range(repeat): + t = time.perf_counter() + result = fn() + best = min(best, time.perf_counter() - t) + return best, result + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--users", type=int, default=1000) + parser.add_argument("--days", type=int, default=7) + parser.add_argument("--rate", type=float, default=8.0) + parser.add_argument("--work", default="") + args = parser.parse_args() + work = Path(args.work or tempfile.mkdtemp(prefix="activity-load-")) + data, spool_root = str(work / "data"), str(work / "spool") + spool = activity.ensure_spool(spool_root, NAME) + os.chmod(spool, 0o700) # the load script writes as the owner + today = datetime.date(2026, 11, 27) + now = datetime.datetime.combine(today, datetime.time(16, 5), ZONE).timestamp() + report: dict[str, object] = { + "users": args.users, + "days": args.days, + "rate": args.rate, + } + per_day = [] + for i in range(args.days): + day = today - datetime.timedelta(days=args.days - 1 - i) + t = time.monotonic() + lines = generate_day(spool, day, args.users, args.rate, seed=i) + gen = time.monotonic() - t + if i < args.days - 1: + res = collect_child(data, spool_root, 365, now) + else: + # the last day also as the timer sees it: single 30-second files around noon + hold = work / "hold" + hold.mkdir() + for f in sorted(spool.iterdir()): + f.rename(hold / f.name) + single = [] + for f in sorted(hold.iterdir())[480:485]: + f.rename(spool / f.name) + single.append(collect_child(data, spool_root, 365, now)) + for f in hold.iterdir(): + f.rename(spool / f.name) + hold.rmdir() + res = collect_child(data, spool_root, 365, now) + report["single_run"] = single + path = Path(data) / NAME / activity.day_name(day) + size = path.stat().st_size + ( + Path(f"{path}-wal").stat().st_size if Path(f"{path}-wal").exists() else 0 + ) + per_day.append( + { + "day": day.isoformat(), + "lines": lines, + "generate_s": round(gen, 1), + **{ + k: round(v, 2) if isinstance(v, float) else v + for k, v in res.items() + }, + "file_mib": round(size / 1048576, 1), + } + ) + print(json.dumps(per_day[-1]), flush=True) + report["per_day"] = per_day + + q = Query(data, ZONE, [Source(NAME, 365)], now=now) + day_start = int( + datetime.datetime.combine(today, datetime.time(0, 0), ZONE).timestamp() + ) + week_start = int( + datetime.datetime.combine( + today - datetime.timedelta(days=6), datetime.time(0, 0), ZONE + ).timestamp() + ) + lesson = ( + int(datetime.datetime.combine(today, datetime.time(9, 0), ZONE).timestamp()), + int(datetime.datetime.combine(today, datetime.time(10, 30), ZONE).timestamp()), + ) + klass = [f"schueler{u:04d}" for u in range(30)] + end = int(now) + 60 + queries = { + "class_overview_today (30 users)": lambda: q.users(day_start, end, klass), + "class_overview_lesson_90min (30 users)": lambda: q.users(*lesson, klass), + "class_overview_7d (30 users)": lambda: q.users(week_start, end, klass), + "timeline_student_7d_hour": lambda: q.timeline( + "schueler0007", week_start, end, "hour" + ), + "timeline_student_1h_minute": lambda: q.timeline( + "schueler0007", lesson[0], lesson[0] + 3600, "minute" + ), + "timeline_student_day_minute": lambda: q.timeline( + "schueler0007", day_start, end, "minute", limit=5000 + ), + "top_domains_class_today": lambda: q.domains(day_start, end, klass), + "top_domains_class_lesson": lambda: q.domains(*lesson, klass), + "search_domain_class_7d": lambda: q.search( + "example3.org", week_start, end, klass + ), + "overview_all_users_today (school admin)": lambda: q.users( + day_start, end, None + ), + "overview_all_users_7d (school admin)": lambda: q.users(week_start, end, None), + "top_domains_all_today": lambda: q.domains(day_start, end, None), + "search_domain_all_today": lambda: q.search( + "h5.example5.org", day_start, end, None + ), + "export_class_day_rows": lambda: sum( + 1 for _ in q.export(day_start, end, klass) + ), + } + times = {} + for label, fn in queries.items(): + seconds, result = timed(fn) + size = result if isinstance(result, int) else (result or {}).get("total") # type: ignore[union-attr] + times[label] = {"seconds": round(seconds, 3), "total": size} + print(label, times[label], flush=True) + report["queries"] = times + total = sum(f.stat().st_size for f in (Path(data) / NAME).iterdir()) + report["data_mib"] = round(total / 1048576, 1) + report["maxrss_self_mib"] = round( + resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1 + ) + print(json.dumps(report, indent=1)) + if not args.work: + shutil.rmtree(work) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From f380c76be1bf1366e9277c9975941540144deb0a Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 11:20:35 +0100 Subject: [PATCH 09/45] docs: ADR-023 activity log, operations (use, retention, audit, load numbers, data protection), threat model T24-T26, test strategy, architecture, changelog --- README.md | 4 ++ debian/changelog | 22 +++++++++++ docs/architecture.md | 9 +++++ docs/decisions.md | 72 +++++++++++++++++++++++++++++++++ docs/operations.md | 92 +++++++++++++++++++++++++++++++++++++++++++ docs/test-strategy.md | 27 +++++++++++++ docs/threat-model.md | 3 ++ 7 files changed, 229 insertions(+) diff --git a/README.md b/README.md index 7b655ae..44593b5 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,10 @@ the same AD/Kerberos infrastructure the school already operates. - **WebUI plugin (optional):** `linuxmuster-squid-webui` adds the page *Squid proxy* to the linuxmuster.net 7.3 WebUI for global administrators; it manages one or more proxy hosts over their opt-in TLS listener with a pinned certificate. + A second page *Internetprotokoll* shows the optional activity log (ADR-023, off by default per + instance, domain and minute, no URLs): teachers see the students of their own classes and + projects, school administrators their school, global administrators everything; every access + is audited. | Package | Install on | What | |---|---|---| diff --git a/debian/changelog b/debian/changelog index f91d1ee..30ad00d 100644 --- a/debian/changelog +++ b/debian/changelog @@ -158,6 +158,28 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium "apply to other instances" and the container log scroll on their own, sized to the window so they fit into the dialog (no scroll area inside a scrolling one at 125 % zoom). + * Activity log per instance (off by default; docs/operations.md, + "Activity log"): who visited which domain, per minute (requests, + bytes, blocked, filter category; no URLs, no client addresses), kept + 1-365 days (default 7) as one file per day. Switching it on needs who + confirmed the privacy notice; switching it off can delete the data at + once; deleting an instance deletes its activity data, purge deletes + all of it. The collector runs every 30 s (linuxmuster-squid-activity + .timer) and does nothing while no instance has the log on. Queries + through the API and "lmnsquid activity ..." are limited and written + to an audit log first (kept 365 days, activity_audit_retention_days). + Takes effect with a data-plane image built from this release; an + instance is restarted once when the log is switched on or off. + * WebUI plugin: new page "Internetprotokoll" (permission + lm:squid:activity) for teachers, school and global administrators: + per class or project the students with activity now/today, requests, + domains and blocked attempts, top domains, "who was on X", a heat map + of the last 7 days per student with the minutes of an hour, live + reload, CSV export for administrators; settings with the privacy + notice and the audit log for global administrators. Teachers see only + students of their own classes and projects, school administrators + their school; the server decides this from the AD on every request. + Log out and in again after the upgrade (new permission). -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium diff --git a/docs/architecture.md b/docs/architecture.md index 1f10a21..cf9a1b4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -109,6 +109,10 @@ Status document. Keep it up to date with every substantive change (see exceptions → protected list → categories with their chosen variant and schedules; fail-closed for youth protection. HTTP block page `ERR_LMN_BLOCKED`; SafeSearch via `hosts_file` (`/etc/hosts` + `safesearch.hosts`); anonymous statistics in `filter.log` (day + category). +- **Activity log (ADR-023, off by default):** with `ACTIVITY_LOG_ENABLED=1` squid sends one + `lmnactivity` line per request (second, user, domain, status, size, category) over UDP to + `lmn-activity-logd` in the same container, which writes finished files into the host spool + mounted at `/var/log/lmnsquid-activity` while the log is on. ## 4. Control Plane @@ -131,6 +135,11 @@ Status document. Keep it up to date with every substantive change (see streaming (sort on disk), checked and switched atomically; `GET|PUT …/filter`, `…/catalog/custom…`, `…/allowlist`, `…/filter/lookup`, `…/filter/stats` write the instance's files and reconfigure the running squid. `filterdecision.py` is shared byte for byte with the image's helper. +- **Activity log (ADR-023):** `lmnsquid-activity collect` (timer every 30 s) sums the spool + files into one SQLite file per instance and local day (per minute, per hour, per day and + domain), retention by whole files; `GET|PUT …/activity`, `POST /v1/activity/{users,timeline, + domains,search,export}` restricted to the caller's users list and audited before reading, + `GET /v1/activity/audit`. - **Reconciler:** declarative, git-versioned state (`instances/*.yaml`) → renders config, reconciles actual against desired state (docker-py). - **Updater:** pull-by-**digest** (`image@sha256:`), health-gated, **auto-rollback** diff --git a/docs/decisions.md b/docs/decisions.md index a5566b0..3972ec9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -626,6 +626,78 @@ the image. HTTPS still shows no block page (ADR-002 unchanged). as for ADR-016. A catalog of the first test build (format 1) is reported as unusable until the next `lmnsquid catalog update`. +### ADR-023 — Activity log: UDP receiver in the container, spool files, one SQLite file per day, scope by user list +**Status:** Proposed (2026-11-25, Kevin: task `work/tasks/squid-aktivitaetsprotokoll.md`). +**Decision:** per instance, off by default, an activity log of who visited which domain, per +minute: one row per user, domain and minute with requests, bytes, blocked requests and the filter +category of a blocked one. No URLs (also not for HTTP), no client address. Switching it on +(`PUT /v1/instances/{name}/activity`, CLI `lmnsquid activity enable --ack-by`, WebUI settings) +needs who confirmed the privacy notice; who and when are stored in the instance definition (and +so in its git change log). Retention per instance, 1–365 days, default 7. +**Capture:** squid writes the `lmnactivity` format (`%ts %un %>rd %>Hs %Ss %/` on the host, mounted only while the log is on) +and renames a part to `act-*.log` at the latest after 30 s or 16 MiB. A finished file is never +written again. The collector `lmnsquid-activity collect` (systemd timer every 30 s, as +`lmnsquid`, `MemoryMax=256M`) reads the finished files one at a time, sums them per user, domain +and minute, adds them to `/var/lib/linuxmuster-squid/activity//.sqlite` (local +day of `filter_timezone`) and deletes them. The file's name is inserted into the day file's table +`ingested` in the same transaction as its rows: a run that stops anywhere (before the commit, +between the commit and the delete) neither loses a file nor counts it twice; a part left by a +receiver that died is taken once nobody wrote to it for 5 minutes, under the ledger name of the +finished file it would have become. Lines without a user (no ticket, noauth domains, the health +check) are not stored; a line cut short or broken is counted and skipped. +**Day file:** tables `act(u, m, h)` (per minute, primary key user+minute+domain, WITHOUT ROWID), +`uh(u, hr)` (per user and hour: overview, heat map), `uhd(u, h)` (per user and domain for the +day, with an index on the domain: top domains and "who was on X"), `users`/`hosts` dictionaries; +WAL. Retention deletes whole day files (`retention_days` = 1 keeps today only), also before a +query reads them; no DELETE over big tables. +**Queries:** `POST /v1/activity/{users,timeline,domains,search,export}`, each with a time range, +the instances and optionally `users`: the list of users the caller may see. Every SQL statement is +restricted to that list (`json_each`), so the proxy never returns another user. Limits: range up +to 366 days (minute timeline 2 days, export 31 days and 1 million rows), at most 10 000 users per +request, page sizes, 20 s per query (SQLite progress handler, then 422 "query too large"). +**Audit:** every query (and every settings change) is written to +`/var/lib/linuxmuster-squid/activity/_audit/.jsonl` before anything is read (who, role, what +for, time range, instances, the users list up to 200 names, the user of a timeline, the domain of a +search); a query whose audit line cannot be written is refused (503). Own retention +(`activity_audit_retention_days`, default 365). `GET /v1/activity/audit`; in the WebUI only for +global administrators. +**WebUI:** a second page "Internetprotokoll" with its own permission `lm:squid:activity` (true for +globaladministrator, schooladministrator and teacher); the management keeps its global-admin-only +permissions. The scope is computed on the school server from the AD on every request (cached +10 s for the person, 60 s for the school's users), the way the official plugins read it +(linuxmusterTools: `/users/`, `/rawusers` of the school, `/projects/`): a global +administrator sees everything (or one school), a school administrator every user of their school, +a teacher only users with `sophomorixRole` student of their school who are in a class or project +the teacher is in (sophomorix syncs members and admins of a group into its `member`, so the +teacher's `memberOf` holds both; a project's member and admin groups count with their students; +role groups such as `students` never count as a class). Other roles 403, also with the permission +granted by hand, and the role comes from the AD, not from the session. Only that list goes to the +proxies; a user or group outside it is 403 before any proxy is asked. Export (CSV) for school and +global administrators only. Every proxy whose instances belong to the school is asked in +parallel; one that does not answer is named and does not block the page. +**Deviations from the task, and why:** (1) Capture by UDP to a receiver that writes finished files +instead of reading the access log by offset and inode: squid's `daemon:` module ends squid when its +log daemon dies (measured with squid 6.14, also with `on-error=drop`), the access log can be off +(`access_log_enabled: false`) and holds full URLs and client addresses, and reading the Docker +volume needs root or `docker exec`. With finished files the collector needs no offsets: rotation +and restarts cannot double-count or skip, which is what offset + inode is for. Price: lines squid +sends while the receiver restarts (1 s) are lost, and a burst larger than the socket buffer +(`net.core.rmem_max`, 208 KiB by default ≈ 2500 lines) would be dropped; measured load is far +below. (2) No separate index "domain + time" on the minute table: the day table `uhd` has the +domain index and the first/last minute; a partial-day search refines the candidates through the +primary key (user + minute). The minute table stays as small as possible. (3) The settings +(switch, retention, confirmation) live in the new page's tab for global administrators, not in the +management page, so the two pages stay independent. +**Why per day files:** retention is a file deletion, a day file is written by one collector run at +a time and read by any number of queries (WAL), a broken file costs one day, and the size per day +is known. **Price:** a few minutes of the day can sit in the spool when the collector is stopped +(the receiver stops accepting at 1 GiB waiting per instance); a multi-day query opens one file per +day and instance. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/operations.md b/docs/operations.md index 1b30808..2a8ce00 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -666,6 +666,88 @@ logs; all request/cache logs live in the Docker volumes above. - **For centralized long-term analysis** instead hook the Docker `syslog` log driver into your existing syslog/SIEM — the control plane is **not** a log database. +## Activity log (per instance, off by default) + +Who visited which domain, per minute (ADR-023): per user, domain and minute the number of +requests, the bytes, the blocked requests and the filter category of a blocked one. No URLs (also +not for HTTP), no client addresses. Users come from the Kerberos ticket (realm removed); requests +without a user (no ticket, domains without authentication) are not recorded. + +**Switch on** (restarts the instance once, health-gated): + +```bash +lmnsquid activity enable default-school-students --ack-by "Name of who confirmed" --retention-days 7 +lmnsquid activity status # settings, stored days and size, files waiting +lmnsquid activity retention default-school-students 14 +lmnsquid activity disable default-school-students [--delete-data] +lmnsquid activity delete-data default-school-students +``` + +or in the WebUI, page *Internetprotokoll*, tab *Einstellungen* (global administrators). Switching +on needs the confirmation of the privacy notice (below); who confirmed it and when is stored in +the instance definition (`activity_ack_by`, `activity_ack_at`, in its git change log). Needs a +data-plane image built from 7.3.11 or later (`image_capable` in `GET /v1/instances//activity`). + +**Where the data are:** squid sends each line over UDP to a receiver in the container, which +writes finished files into `/var/spool/linuxmuster-squid/activity//` (at the latest every +30 s); `linuxmuster-squid-activity.timer` runs `lmnsquid-activity collect` every 30 s as +`lmnsquid`, which sums them into `/var/lib/linuxmuster-squid/activity//.sqlite` +(local day of `filter_timezone`) and deletes them. Data appear in queries about 30–70 s after +the request. `journalctl -u linuxmuster-squid-activity` shows one line per run with work +(files, lines, used, without user, broken, too old). If the collector stops, the receiver keeps +at most 1 GiB per instance waiting and then drops new lines (logged in the container log). + +**Retention:** 1–365 days per instance (default 7; 1 = today only). Whole day files are deleted +by the collector; a query never reads a file older than the retention, even before it is +deleted. Switching off keeps the data until they expire, unless deleted at once. `lmnsquid rm` +deletes the instance's activity data (also with `--keep-logs`); `apt-get purge` deletes all. + +**Queries** (API, CLI, WebUI), always with a time range: users active in the range +(`lmnsquid activity users --range today|hour|7d|30d [--user …]`), one user's timeline per hour or +per minute (`timeline [--minute]`), top domains (`domains`), who was on a domain or a +subdomain of it (`search `), CSV per minute (`export`, at most 31 days). Limits: 366 days +per query (minute timeline 2 days), 10 000 users per request, 1 million export rows, 20 s per +query ("query too large": choose a shorter range or fewer users). + +**Audit log:** every query and every settings change is written to +`/var/lib/linuxmuster-squid/activity/_audit/.jsonl` before anything is read: time, person +(the WebUI user, or `cli:`), role, what for (class, project, user), time range, instances, +the users (up to 200 names), the domain of a search. A query whose audit line cannot be written is +refused. Kept `activity_audit_retention_days` days (config.yml, default 365, 1–3650). +`lmnsquid activity audit [--days 30] [--actor …]`; in the WebUI tab *Zugriffsprotokoll* (global +administrators only). + +**Who sees what in the WebUI** (decided on the school server from the AD on every request, never +in the browser): global administrators everything (optionally one school); school administrators +every user of their school; teachers only users with the role student of their own school who are +in a class or project the teacher is a member or admin of (also through a project's member +groups), never other teachers; students and every other role nothing. Export only for school and +global administrators. Only the proxies whose instances belong to the school are asked; one that +does not answer is named on the page. With several proxy servers the domain counts per user are +added up per server. + +**Load (measured locally, `scripts/tests/activity_load.py`):** 1000 students, 8 school hours a day, about +2.5 million requests per day (5 days a week in practice; measured with 7 days in a row), +Xeon E5-2609 v3 1.9 GHz, one core, SSD, 2026-11-25: + +| What | Measured | +|---|---| +| collector, one 30-second file (≈ 2 600 lines, what the timer sees at peak) | 0.05 s (+ ≈ 0.3 s Python start) | +| collector, a whole day as a backlog (960 files, 2.5 million lines) | 66 s, RSS 44 MiB | +| day file | 28.7 MiB (957 000 minute rows, 91 500 user-domain rows, 17 600 domains) | +| overview of a class (30 students), today / 90 minutes / 7 days | 0.007 / 0.013 / 0.055 s | +| one student: 7 days per hour (heat map) / one hour per minute / one day per minute | 0.006 / 0.001 / 0.005 s | +| top domains of a class, today / 90 minutes | 0.016 / 0.024 s | +| who of a class was on a domain, 7 days | 0.067 s | +| all 1000 users today / 7 days (with distinct domains; 7 days without them 0.06 s) | 0.21 / 1.49 s | +| top domains of everyone today / who of everyone was on a domain today | 0.35 / 0.012 s | +| CSV of a class for a day (28 500 rows) | 0.28 s | + +**Disk:** about 29 MiB per school day per 1000 active students at this rate, i.e. with 190 +school days a year about 5.5 GiB per 1000 students at 365 days' retention (10.5 GiB if every +day of the year were a school day), 0.2 GiB at the default 7 days. Scale linearly with users and +requests; plan the space of `/var/lib/linuxmuster-squid` accordingly. + ### ⚠️ Data protection (GDPR) Access logs show **who visited/was blocked from which site** = personal data @@ -679,6 +761,16 @@ Access logs show **who visited/was blocked from which site** = personal data written when the access log is off (nothing in it identifies a person). - **`lmnsquid rm` deletes the log volume** with the instance (the deletion path); pass `--keep-logs` only when a retention obligation requires it. +- **Activity log (ADR-023)** is off by default. Before switching it on for an instance, clarify + (this is no legal advice, but these points are required in practice): the **legal basis** + (school law of the state, the school's terms of use for the network, consent where required, + for employees a service agreement); **inform the people concerned** (students, parents, + staff) about purpose, content, retention and who can see it; for **employees involve the staff + council** (Personalrat), monitoring of staff is subject to co-determination; record it in the + **record of processing activities** and check whether a **data protection impact assessment** + is needed. Keep the retention as short as the purpose allows. Who confirmed this and when is + stored when switching on. Teachers see only their own students; every access is in the audit + log, which only global administrators can read. ## Backup diff --git a/docs/test-strategy.md b/docs/test-strategy.md index d0c36d5..22e1a60 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -236,6 +236,33 @@ acceptance list in `deployment-gpo.md`. systemctl): an upgrade starts the catalog unit without blocking, not with the timer disabled, not on a new installation, and a failed start does not fail the configure. Lab plan: `work/tasks/squid-filterkategorien.md`. +- **Activity log (ADR-023):** `controlplane/tests/test_activity.py` (line parser: realm stripped, + `%40`, blocked by 403/TCP_DENIED/category, no user; broken and cut lines counted; collector: + per-minute sums, a file collected twice counted once, restart between files, stale parts taken + once under the finished file's name, split at local midnight, future lines, retention by whole + day files and dropped old lines, spool mode 3733, purge, lock; the image's UDP receiver as a + process: finished files on time and on SIGTERM, mode 0640, lines dropped while 1 GiB waits, + survives a missing directory; queries: scope by user list, partial and whole days, active now, + hour and minute timeline, top domains with users and category, subdomain search with literal + LIKE characters, CSV, limits, time budget, retention also before deletion), + `test_activity_api.py` (off by default and no container change, old definitions load, switching + on needs the confirmation, retention without replacement, switching off deletes on request, + every query audited with person/scope/users before reading, unwritable audit log → 503, input + checks, 401/403, the instance's deletion removes its activity data, PATCH cannot switch it on, + spool mounted only while on and the fingerprint independent of retention), `test_cli.py` + (`lmnsquid activity …`), webui `test_activity_views.py` (real control plane, fake AD shaped like + linuxmusterTools: teacher sees only students of own classes and projects incl. a project's + member group, never a teacher of the same class, never another school, role groups ignored; + out-of-scope group/user/school 403 before any proxy is asked; school administrator the whole + school, export allowed, audit not; students/staff 403 also with the permission granted by hand; + role from the AD not the session; global settings with the confirmation; a proxy that does not + answer is named; CSRF), `test_permissions.py` (`lm:squid:activity` for the three roles only, + management unchanged), node `webui/tests/js/activity_check.js` (ranges, class members without + activity, heat map). **E2E** (`squid-filter` with `ACTIVITY_LOG_ENABLED=1`): the spool holds + the Kerberos user, the domain, 403 and the category of a blocked request, no URL and no client + address; the production collector turns it into a day file and empties the spool. Measured + locally with squid 6.14: a killed receiver does not stop squid (the `daemon:` module did). + Load: `scripts/tests/activity_load.py` (numbers in operations.md). - **Lists squid 6 refuses** (`FATAL: Bungled`: a name covered by a listed parent before it, or the bare apex next to it), both lists: unit (`uncovered`, `add` keeps the parent and drops what it covers, a hand-edited file is cleaned on the next write), blocklist smoke diff --git a/docs/threat-model.md b/docs/threat-model.md index 1a6412c..dc458f8 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -44,6 +44,9 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T21 | **Category catalog source manipulated or broken** (ADR-022): a list server, a mirror (`catalog_url`), an admin's own source (`catalog-custom.yml`, any https URL a token holder adds) or a man in the middle delivers a list that blocks everything (denial of service), unblocks a category (an empty or truncated list), or a file that crashes the helper | HTTPS only, redirects away from https refused, size cap per download (own sources at most 200 MB, own ids/URLs validated, the merged configuration must load before it is written); each source is checked on its own and a refused one falls back to its last good download (or is left out), so a broken or hostile list cannot freeze the other lists; youth protection without any list fails closed; entries normalised (lower case, IDNA, no IP addresses, no single labels such as `com`); a source below `min_entries` or a category shrinking by more than half stops the build and the active catalog stays; `quick_check` and a test open before the atomic switch; the previous version kept for a manual rollback; the packaged **protected list** keeps Windows Update, Microsoft 365, Google Workspace, OCSP etc. out of every category, so a poisoned list cannot cut them. Not covered: a plausible-sized list with *wrong* entries (no signatures exist for UT1 or HaGeZi): "Warum ist X gesperrt?" names category, entry and source, exceptions repair it per instance | controlplane/tests/test_catalog.py (formats, IP/single-label drop, min_entries, shrink, publish, fetch fallbacks, http redirect refused) | | T22 | **Helper denial of service / crash** (ADR-022): many distinct host names (cache misses), a hand-broken `filter.json`, a damaged catalog, a crashing helper making the deny line be skipped (squid treats a helper error like "no match") | the helper never answers `BH`: any internal error gives the fail-closed answer when a youth protection category is active, else no block, and is logged in `cache.log`; squid caches answers 60 s and runs up to 4 + 2 helper processes per instance (measured 13 000–14 000 lookups/s per process); squid restarts helpers that exit; a broken `filter.json` (only written atomically by the control plane) fails closed; the catalog is opened read-only (`immutable`) so a container cannot write it (read-only mount) | controlplane/tests/test_filter_helper.py (protocol, broken files, fail-closed, rate); measured in the image (work/tasks/squid-filterkategorien.md) | | T23 | **Fail-open vs. fail-closed of the filter** (ADR-022): during a missing catalog youth protection would silently stop | SafeSearch switched on for an engine without any known address blocks that engine (`safesearch_unresolved`) instead of leaving it unfiltered; an image without the filter is reported (`image_without_filter`), not shown as filtering; fail-closed for the categories marked `fail_closed` (youth protection): every request but exceptions and the protected list refused while the catalog is unusable, shown in `status`/WebUI; other categories fail open (ads, telemetry, distraction: availability first). The noauth path is filtered too (T16 amended). Bypass of the proxy (direct 443/853/QUIC) defeats every filter and SafeSearch: firewall's job (operations.md) | test_filterdecision.py, test_filter_helper.py, E2E (fail-closed without catalog) | +| T24 | **Activity log = profile of browsing per person** (ADR-023): data of students and staff, a teacher looking at students of other classes or at colleagues, an exported CSV passed on | off by default per instance; switching on needs who confirmed the privacy notice (stored with the time in the instance's git log); minute and domain only, no URL, no client address; retention 1–365 days as whole day files (deleted before a query could read them); scope computed on the school server from the AD on every request, only the allowed users list goes to the proxy, which filters every SQL statement on it; teachers only students of their own classes/projects and school, never teachers; export only for administrators; every read and every settings change audited (person, scope, users, range) before data is read, 503 if the audit log cannot be written; the audit log only for global administrators, own retention | `test_activity.py`, `test_activity_api.py`, webui `test_activity_views.py`, E2E spool check | +| T25 | **The users list comes from the WebUI** (ADR-023): the proxy cannot check who asks; a stolen token reads everything | the token is the global administrator's credential already (T5, T18); the list is computed on the server, never taken from the browser; the audit names the person the WebUI reports and, for the CLI, `cli:` | `test_activity_views.py` (out-of-scope requests never reach a proxy) | +| T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 3733 (squid's proxy user can create, not list), files 0640 to the control plane's group; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured) | `test_activity.py` (receiver), local squid 6.14 test | ## Non-goals (deliberate) From dcfbbd20c4a7fdcc6fac6b08f657edeaa4a2b6ec Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 11:21:30 +0100 Subject: [PATCH 10/45] fix(webui): an unreadable AD is a readable 503 on the activity page, not a 500 --- webui/lmn_squid/activity_scope.py | 22 +++++++++++++++++----- webui/lmn_squid/activity_views.py | 3 +++ webui/tests/test_activity_views.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/webui/lmn_squid/activity_scope.py b/webui/lmn_squid/activity_scope.py index 421d593..db16a0b 100644 --- a/webui/lmn_squid/activity_scope.py +++ b/webui/lmn_squid/activity_scope.py @@ -43,6 +43,10 @@ class ScopeDenied(Exception): """The person may not see activity data (or not this user/group).""" +class DirectoryError(Exception): + """The AD could not be read (the page says so instead of showing anyone's data).""" + + class Directory(Protocol): """The AD as the plugin reads it (linuxmusterTools; a fake in the tests).""" @@ -268,20 +272,28 @@ class LdapDirectory: ] def __init__(self) -> None: - from linuxmusterTools.ldapconnector import LMNLdapReader - + try: + from linuxmusterTools.ldapconnector import LMNLdapReader + except ImportError as exc: + raise DirectoryError(f"linuxmusterTools missing ({exc})") from None self.lr = LMNLdapReader + def _get(self, url: str, **kwargs: Any) -> Any: + try: + return self.lr.get(url, **kwargs) + except Exception as exc: # noqa: BLE001 - ldap errors, an unknown route: one message + raise DirectoryError(f"the AD could not be read ({type(exc).__name__})") from None + def person(self, name: str) -> dict[str, Any] | None: - found = self.lr.get(f"/users/{name}", attributes=self.ATTRS) + found = self._get(f"/users/{name}", attributes=self.ATTRS) return found if isinstance(found, dict) and found.get("sAMAccountName") else None def school_users(self, school: str) -> list[dict[str, Any]]: - found = self.lr.get("/rawusers", school=school, attributes=self.ATTRS) + found = self._get("/rawusers", school=school, attributes=self.ATTRS) return [u for u in found or [] if isinstance(u, dict)] def project_groups(self, school: str, project: str) -> list[str]: - found = self.lr.get( + found = self._get( f"/projects/{project}", school=school, attributes=["sophomorixMemberGroups", "sophomorixAdminGroups"], diff --git a/webui/lmn_squid/activity_views.py b/webui/lmn_squid/activity_views.py index e3dcd08..5fab8b3 100644 --- a/webui/lmn_squid/activity_views.py +++ b/webui/lmn_squid/activity_views.py @@ -29,6 +29,7 @@ from .activity_scope import ( SCHOOL_RE, + DirectoryError, USER_RE, LdapDirectory, Scope, @@ -62,6 +63,8 @@ def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: return fx(self, http_context, **kwargs) except ScopeDenied as exc: raise EndpointReturn(403, {"error": "scope", "message": str(exc)}) from None + except DirectoryError as exc: + raise EndpointReturn(503, {"error": "directory", "message": str(exc)}) from None except ControlPlaneError as exc: raise EndpointReturn(exc.http_status(), exc.as_dict()) from None except ConnectionFileError as exc: diff --git a/webui/tests/test_activity_views.py b/webui/tests/test_activity_views.py index d1e39bb..0697ce9 100644 --- a/webui/tests/test_activity_views.py +++ b/webui/tests/test_activity_views.py @@ -388,3 +388,31 @@ def test_every_activity_endpoint_needs_the_permission() -> None: for fn in routes: assert fn.url_pattern.pattern.startswith("^/api/lmn/squid-activity/") assert fn.permission_id == activity_views.PERM_ACTIVITY + + +def test_an_unreadable_ad_is_a_readable_503(webui: WebUI, ad: FakeDirectory) -> None: + def broken(_school: str) -> list[dict[str, Any]]: + raise activity_scope.DirectoryError("the AD could not be read (SERVER_DOWN)") + + ad.school_users = broken # type: ignore[method-assign] + login(webui, "dslehr01", "teacher") + status, data = webui.call("GET", f"{PREFIX}/scope") + assert status == 503 and "AD could not be read" in data["message"] + + +def test_ldap_directory_wraps_reader_errors(monkeypatch: pytest.MonkeyPatch) -> None: + import sys + import types + + reader = types.SimpleNamespace(get=lambda url, **kw: (_ for _ in ()).throw(ValueError("x"))) + pkg = types.ModuleType("linuxmusterTools.ldapconnector") + pkg.LMNLdapReader = reader # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "linuxmusterTools", types.ModuleType("linuxmusterTools")) + monkeypatch.setitem(sys.modules, "linuxmusterTools.ldapconnector", pkg) + directory = activity_scope.LdapDirectory() + with pytest.raises(activity_scope.DirectoryError): + directory.person("dslehr01") + reader.get = lambda url, **kw: {"sAMAccountName": "dslehr01", "sophomorixRole": "teacher"} + assert directory.person("dslehr01")["sophomorixRole"] == "teacher" # type: ignore[index] + reader.get = lambda url, **kw: {"sophomorixMemberGroups": ["7c"], "sophomorixAdminGroups": []} + assert directory.project_groups("default-school", "p_x") == ["7c"] From 9e2a77c42a69e624202b11b3e2b9129ac5b9e919 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 11:21:52 +0100 Subject: [PATCH 11/45] fix(image): the activity receiver drops lines without a user; the collector logs only runs that stored something The health check every 30 s made a spool file and a journal line every 30 s on an idle instance; lines without a user were never stored anyway. --- controlplane/lmnsquid/activity.py | 2 +- controlplane/tests/test_activity.py | 3 ++- image/lmn-activity-logd | 5 ++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/controlplane/lmnsquid/activity.py b/controlplane/lmnsquid/activity.py index 8cd359b..7f8d4e3 100644 --- a/controlplane/lmnsquid/activity.py +++ b/controlplane/lmnsquid/activity.py @@ -614,7 +614,7 @@ def main(argv: list[str] | None = None) -> int: finally: lock.release() for name, c in results.items(): - if c.files or c.broken: + if c.used or c.broken: logger.info( "activity: %s: %d file(s), %d line(s), %d used, %d without user, " "%d broken, %d too old, %d row(s) into %s (%.2f s)", diff --git a/controlplane/tests/test_activity.py b/controlplane/tests/test_activity.py index c5e092f..a3facc7 100644 --- a/controlplane/tests/test_activity.py +++ b/controlplane/tests/test_activity.py @@ -312,10 +312,11 @@ def _wait_files(directory: Path, prefix: str, count: int = 1, timeout: float = 1 def test_receiver_finishes_files_on_time_and_on_sigterm(tmp_path: Path) -> None: proc, port = _receiver(tmp_path, LMN_ACTIVITY_ROLL_SECONDS="0.3") try: + _send(port, line(T0, "-", "healthcheck.invalid", 407, "TCP_DENIED")) _send(port, line(T0, "s1", "a.example"), line(T0, "s1", "b.example")) done = _wait_files(tmp_path, "act-") assert len(done) == 1 - assert done[0].read_text().count("\n") == 2 + assert done[0].read_text().count("\n") == 2, "the line without a user is not written" assert oct(done[0].stat().st_mode)[-3:] == "640" _send(port, line(T0 + 1, "s2", "c.example")) _wait_files(tmp_path, ".part-") diff --git a/image/lmn-activity-logd b/image/lmn-activity-logd index db8d765..d6ff155 100755 --- a/image/lmn-activity-logd +++ b/image/lmn-activity-logd @@ -168,7 +168,10 @@ def main(argv: list[str]) -> int: if ready: data = sock.recv(RECV_SIZE) for line in data.split(b"\n"): - if line.strip(): + # no user (no ticket, the health check, domains without authentication): + # never stored, so not written either + fields = line.split(None, 2) + if len(fields) > 1 and fields[1] != b"-": spool.write(line + b"\n") spool.tick() except Stop: From cd1d5d775e0cab9dfb42ef5136cf8e2ac3b74a37 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 11:24:58 +0100 Subject: [PATCH 12/45] test(e2e): activity log of squid-filter with real Kerberos: user, domain, 403 and category in the spool, no URL or address, collected into a day file --- deploy/e2e/docker-compose.yml | 3 ++ scripts/tests/e2e_kerberos.sh | 52 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/deploy/e2e/docker-compose.yml b/deploy/e2e/docker-compose.yml index f87f8d7..53b128a 100644 --- a/deploy/e2e/docker-compose.yml +++ b/deploy/e2e/docker-compose.yml @@ -137,6 +137,8 @@ services: SCHOOL_SUBNETS: "10.228.0.30/32" KEYTAB: "/shared/squid.keytab" CACHE_SIZE_MB: "200" + # activity log (ADR-023) into a spool made like the control plane makes it (mode 3733) + ACTIVITY_LOG_ENABLED: "1" dns: ["10.228.0.2"] networks: e2e: @@ -145,6 +147,7 @@ services: - shared:/shared:ro - ${LMNSQUID_E2E_FILTER_DIR:-./filter-not-prepared}/lists:/etc/squid/lists:ro - ${LMNSQUID_E2E_FILTER_DIR:-./filter-not-prepared}/catalog:/etc/squid/catalog:ro + - ${LMNSQUID_E2E_FILTER_DIR:-./filter-not-prepared}/activity:/var/log/lmnsquid-activity read_only: true tmpfs: ["/run", "/tmp", "/var/log/squid", "/var/spool/squid"] cap_drop: ["ALL"] diff --git a/scripts/tests/e2e_kerberos.sh b/scripts/tests/e2e_kerberos.sh index 20e5dbe..608421c 100755 --- a/scripts/tests/e2e_kerberos.sh +++ b/scripts/tests/e2e_kerberos.sh @@ -41,6 +41,9 @@ printf '.secure2.example.internal\n.a.secure.example.internal\n' > "$FILTER_DIR/ : > "$FILTER_DIR/lists/blocked.domains" chmod 644 "$FILTER_DIR/lists/"*.domains filter_json '"categories": ["porn", "ai", "ads", "own_e2e"], "fail_closed": ["porn"]' +# Activity log spool of squid-filter (ADR-023), made as the control plane makes it. +mkdir -p "$FILTER_DIR/activity" +chmod 3733 "$FILTER_DIR/activity" # squid-old: the data-plane image 7.3.7 pins, the last one without ADR-016 (lists-sync.sh, # noauth). A constant on purpose, not DEFAULT_IMAGE: it stands for what installed instances run @@ -314,6 +317,55 @@ else echo " [FAIL] filter.log: $(printf '%s' "$stats" | head -5)"; rc=$((rc + 1)) fi +log "activity log: spool of squid-filter, collected like the control plane does" +# the receiver finishes a file at the latest 30 s after its first line +for _ in $(seq 1 45); do + ls "$FILTER_DIR/activity"/act-*.log >/dev/null 2>&1 && break + sleep 1 +done +spooled=$(cat "$FILTER_DIR/activity"/act-*.log 2>/dev/null) +if printf '%s\n' "$spooled" | grep -Eq '^[0-9]+ teacher1@EXAMPLE.INTERNAL origin.example.internal 403 TCP_DENIED [0-9]+ porn$'; then + echo " [PASS] spool: teacher1, domain, 403, category porn" +else + echo " [FAIL] spool without the blocked request: $(printf '%s' "$spooled" | head -5)"; rc=$((rc + 1)) +fi +if printf '%s' "$spooled" | grep -Eq 'http://|10\.228\.'; then + echo " [FAIL] spool holds a URL or a client address"; rc=$((rc + 1)) +else + echo " [PASS] spool: no URL, no client address" +fi +if "$PY" -I - "$FILTER_DIR" <<'PYEOF' +import sys, sqlite3, time +from pathlib import Path +from zoneinfo import ZoneInfo +from lmnsquid import activity +from lmnsquid.models import Instance +base = Path(sys.argv[1]) +# the spool as / +root = base / "spoolroot" +root.mkdir(exist_ok=True) +(root / "e2e-filter").symlink_to(base / "activity") +inst = Instance(school="e2e", role="filter", ad_group="teachers", realm="EXAMPLE.INTERNAL", + visible_hostname="squid7.example.internal", keytab_secret="k", + image="linuxmuster-squid:dev", activity_log_enabled=True, + activity_ack_by="e2e", activity_ack_at="now") +c = activity.collect_instance(inst, str(base / "data"), str(root), ZoneInfo("Europe/Berlin")) +assert c.files and c.used, c +day = next((base / "data" / "e2e-filter").glob("*.sqlite")) +db = sqlite3.connect(day) +rows = db.execute("SELECT us.name, ho.name, sum(n), sum(x), max(c) FROM act JOIN users us ON us.id = u " + "JOIN hosts ho ON ho.id = h GROUP BY 1, 2").fetchall() +print(" collected:", rows) +assert ("teacher1", "origin.example.internal") in {(r[0], r[1]) for r in rows}, rows +assert any(r[4] == "porn" and r[3] > 0 for r in rows), rows +assert not list((base / "activity").glob("act-*")), "spool not emptied" +PYEOF +then + echo " [PASS] collector: day file with teacher1, blocked porn, spool emptied" +else + echo " [FAIL] collector on the e2e spool"; rc=$((rc + 1)) +fi + log "squid-noauth access.log (excerpt)" $DC exec -T squid-noauth sh -c 'tail -25 /var/log/squid/access.log' 2>/dev/null || true From 1b328f5cf1517c78329fa7c798eedf0109cddb99 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 14:06:55 +0100 Subject: [PATCH 13/45] fix(controlplane): switching the activity log on under the unit's restrictions; feat: day, blocked and drill-down queries Fixes from the lab test of 2026-11-25: - The spool is 1733 without a set-group-id bit (RestrictSUIDSGID=yes of the service refused 3733 with a 500); the receiver writes 0644 behind the 0750 parent. Checked under systemd-run with the unit's own restrictions. - Switching on or off writes the definition only after the container matches it; a failure leaves the instance unchanged and says why (code apply_failed). Switching on again applies a definition the running container lacks. Switching off removes the empty spool. - One HTTPS visit is one request: squid's NONE_NONE side lines (the SNI peek, the error page of a refused CONNECT) go with their CONNECT line and only mark it blocked when the SNI is in a category. - The collector unit has LogLevelMax=notice: idle runs leave no journal lines (systemd's own included); runs with work are notice. For the student-centred view: - POST /v1/activity/day: a user's active minutes and the domains with the minutes they were used in, from the primary key only, with a part of the day and a live delta (since_minute); POST /v1/activity/blocked; timeline per minute for one domain (drill-down). - GET /v1/activity?usage=false: the light overview with the oldest day, lesson hours (activity_lesson_hours) and the catalog's category labels. - Categories of allowed domains too (catalog and own lists) and a background flag (ads, telemetry) with hide_background for top domains. - ETag on day and timeline answers, 304 after the audit line. - Limit errors carry a code; queries over 1 s are logged without names. - The domain search over a partial day is one statement. - CLI: lmnsquid activity day, blocked, timeline --domain. --- controlplane/lmnsquid/activity.py | 131 +++++-- controlplane/lmnsquid/activity_api.py | 288 ++++++++++++--- controlplane/lmnsquid/activity_query.py | 341 ++++++++++++++++-- controlplane/lmnsquid/api.py | 14 +- controlplane/lmnsquid/cli.py | 43 +++ controlplane/lmnsquid/config.py | 12 + controlplane/lmnsquid/docker_service.py | 10 + controlplane/tests/conftest.py | 4 + controlplane/tests/test_activity.py | 218 ++++++++++- controlplane/tests/test_activity_api.py | 153 ++++++++ controlplane/tests/test_cli.py | 8 + deploy/e2e/docker-compose.yml | 2 +- image/lmn-activity-logd | 8 +- .../linuxmuster-squid-activity.service | 3 + scripts/tests/e2e_kerberos.sh | 2 +- 15 files changed, 1137 insertions(+), 100 deletions(-) diff --git a/controlplane/lmnsquid/activity.py b/controlplane/lmnsquid/activity.py index 7f8d4e3..c726cce 100644 --- a/controlplane/lmnsquid/activity.py +++ b/controlplane/lmnsquid/activity.py @@ -47,7 +47,7 @@ FUTURE_SLACK_SECONDS = 86400 MAX_HOST = 253 MAX_USER = 64 -SPOOL_MODE = 0o3733 # owner rwx; others may create (squid's proxy user), not list; sticky+setgid +SPOOL_MODE = 0o1733 # owner rwx; others may create (squid's proxy user), not list; sticky DAY_SUFFIX = ".sqlite" SCHEMA = """ @@ -76,7 +76,13 @@ class ActivityError(Exception): - """A request the activity log cannot serve (bad input, limit), with a readable reason.""" + """A request the activity log cannot serve (bad input, limit), with a readable reason and a + code the WebUI translates (``invalid``, ``range_too_long``, ``too_many_users``, + ``too_many_hits``, ``query_too_large``).""" + + def __init__(self, message: str, code: str = "invalid") -> None: + super().__init__(message) + self.code = code # -- paths ------------------------------------------------------------------------------------ @@ -99,10 +105,12 @@ def spool_dir(root: str, name: str) -> Path: def ensure_spool(root: str, name: str) -> Path: """The instance's spool (created before Docker mounts it, else Docker makes a root dir). - Mode 3733: squid's ``proxy`` user in the container may create files there but cannot list - the directory; the set-group-id bit gives its files the control plane's group, which reads - them (0640); the sticky bit keeps one writer from removing another's files, the owner (the - control plane) removes them after collecting. + Mode 1733: squid's ``proxy`` user in the container may create files there but cannot list + the directory; the sticky bit keeps one writer from removing another's files, the owner (the + control plane) reads and removes them after collecting. The receiver writes its files 0644: + nobody else on the host reaches them, ``activity_spool_dir`` itself is 0750 lmnsquid. No + set-group-id bit: the service runs with ``RestrictSUIDSGID=yes``, which refuses it (lab + 2026-11-25, the first design used 3733). """ base = Path(root) base.mkdir(mode=0o750, parents=True, exist_ok=True) @@ -174,6 +182,17 @@ def apply_retention( return removed +def remove_spool_if_empty(root: str, name: str) -> bool: + """Remove the spool of an instance whose log is off once nothing waits in it.""" + try: + spool_dir(root, name).rmdir() + except FileNotFoundError: + return True + except OSError: + return False + return True + + def purge_instance(data_root: str, spool_root: str, name: str) -> None: """Delete everything the activity log holds of ``name``: day files and spool.""" shutil.rmtree(data_dir(data_root, name), ignore_errors=True) @@ -237,18 +256,24 @@ class Counters: lines: int = 0 used: int = 0 anonymous: int = 0 + side: int = 0 broken: int = 0 dropped_old: int = 0 rows: int = 0 days: set[str] = field(default_factory=set) -def parse_line(line: bytes) -> tuple[int, str, str, int, int, str | None] | None: - """``(epoch second, user, host, bytes, blocked, category)`` of one log line. +Parsed = tuple[int, str, str, int, int, str | None, bool] + + +def parse_line(line: bytes) -> Parsed | None: + """``(epoch second, user, host, bytes, blocked, category, side)`` of one log line. Format ``lmnactivity``: ``%ts %un %>rd %>Hs %Ss % tuple[int, str, str, int, int, str | None] | None blocked = int( category is not None or status == b"403" or squid_status.startswith(b"TCP_DENIED") ) - return ts, user, host, max(size, 0), blocked, category + side = squid_status.startswith(b"NONE") + return ts, user, host, max(size, 0), blocked, category, side class DayMapper: @@ -300,6 +326,10 @@ def day(self, minute: int) -> datetime.date: Agg = dict[datetime.date, dict[Key, list]] +# A side line belongs to the CONNECT line of the same user and domain within this many seconds. +SIDE_WINDOW = 2 + + def aggregate( lines: Iterable[bytes], days: DayMapper, @@ -307,8 +337,17 @@ def aggregate( keep_from: datetime.date | None, now: float, ) -> Agg: - """Sum the lines of one spool file per local day, user, minute and domain.""" + """Sum the lines of one spool file per local day, user, minute and domain. + + One HTTPS visit is one request: squid logs a CONNECT (``TCP_TUNNEL`` or ``TCP_DENIED``) plus + a ``NONE_NONE`` side line (the SNI peek, or the error page of a refused CONNECT). A side + line next to its CONNECT line adds nothing but, if it says "blocked" (an SNI in a filter + category behind an allowed CONNECT), marks that request blocked with its category. A side + line without such a partner counts only when it is a blocked attempt (a peek of an allowed + CONNECT alone is the tunnel's, which is in the same or a neighbouring file). + """ out: Agg = {} + parsed_lines: list[Parsed] = [] for line in lines: counters.lines += 1 try: @@ -319,27 +358,55 @@ def aggregate( if parsed is None: counters.anonymous += 1 continue - ts, user, host, size, blocked, category = parsed + ts = parsed[0] if ts > now + FUTURE_SLACK_SECONDS or ts <= 0: counters.broken += 1 continue - minute = ts // 60 - day = days.day(minute) - if keep_from is not None and day < keep_from: + if keep_from is not None and days.day(ts // 60) < keep_from: counters.dropped_old += 1 continue - counters.used += 1 - bucket = out.setdefault(day, {}) + parsed_lines.append(parsed) + + def add(ts: int, user: str, host: str, size: int, blocked: int, category: str | None) -> list: + minute = ts // 60 + bucket = out.setdefault(days.day(minute), {}) key = (user, minute, host) row = bucket.get(key) if row is None: - bucket[key] = [1, size, blocked, category] - else: - row[0] += 1 - row[1] += size - row[2] += blocked - if category is not None: - row[3] = category + row = bucket[key] = [0, 0, 0, None] + row[0] += 1 + row[1] += size + row[2] += blocked + if category is not None: + row[3] = category + counters.used += 1 + return row + + # CONNECT and plain lines first; remember them for their side lines + partners: dict[tuple[str, str], list[list]] = {} + for ts, user, host, size, blocked, category, side in parsed_lines: + if side: + continue + row = add(ts, user, host, size, blocked, category) + partners.setdefault((user, host), []).append([ts, blocked, row]) + for ts, user, host, size, blocked, category, side in parsed_lines: + if not side: + continue + partner = next( + (p for p in partners.get((user, host), ()) if abs(p[0] - ts) <= SIDE_WINDOW), None + ) + if partner is not None: + counters.side += 1 + if blocked and not partner[1]: + partner[1] = 1 + partner[2][2] += 1 + if category is not None: + partner[2][3] = category + continue + if not blocked: + counters.side += 1 + continue + add(ts, user, host, size, blocked, category) return out @@ -548,6 +615,8 @@ def collect_all( results[inst.name] = collect_instance( inst, paths.data_root, paths.spool_root, paths.zone, now ) + if not inst.activity_log_enabled and has_spool: + remove_spool_if_empty(paths.spool_root, inst.name) except (OSError, sqlite3.Error) as exc: logger.error("activity: collecting %s failed: %s", inst.name, exc) return results @@ -583,6 +652,13 @@ def iter_instances(instances_dir: str) -> Iterator[Instance]: yield from Store(instances_dir).list() +class _JournalFormatter(logging.Formatter): + LEVELS = {logging.ERROR: 3, logging.WARNING: 4, logging.INFO: 5} + + def format(self, record: logging.LogRecord) -> str: + return f"<{self.LEVELS.get(record.levelno, 6)}>{super().format(record)}" + + def main(argv: list[str] | None = None) -> int: """``lmnsquid-activity collect``: one collector run (the systemd timer calls it).""" from .config import load_settings @@ -591,7 +667,12 @@ def main(argv: list[str] | None = None) -> int: sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("collect", help="collect the spools into the day files, apply the retention") args = parser.parse_args(argv) - logging.basicConfig(level=logging.INFO, format="%(message)s") + # The unit runs with LogLevelMax=notice, so its idle runs leave nothing in the journal (also + # not systemd's "Starting/Finished", which are info): work lines go out as notice, errors as + # err, through the journal's level prefix. + handler = logging.StreamHandler() + handler.setFormatter(_JournalFormatter("%(message)s")) + logging.basicConfig(level=logging.INFO, handlers=[handler]) settings = load_settings() if args.command == "collect": paths = Paths( diff --git a/controlplane/lmnsquid/activity_api.py b/controlplane/lmnsquid/activity_api.py index 0dc58cd..e712a5e 100644 --- a/controlplane/lmnsquid/activity_api.py +++ b/controlplane/lmnsquid/activity_api.py @@ -14,19 +14,22 @@ from __future__ import annotations import datetime +import hashlib import logging +import os import re import time +from pathlib import Path from typing import Any, Callable, Literal from zoneinfo import ZoneInfo -from fastapi import FastAPI, HTTPException, status -from fastapi.responses import StreamingResponse +from fastapi import FastAPI, HTTPException, Request, status +from fastapi.responses import JSONResponse, Response, StreamingResponse from pydantic import BaseModel, Field, field_validator from . import activity, activity_audit from .activity import ActivityError -from .activity_query import MAX_USERS, Query, Source +from .activity_query import MAX_USERS, SLOW_SECONDS, Categorizer, Query, Source from .config import Settings from .models import ACTIVITY_RETENTION_MAX, Instance from .store import Store @@ -69,9 +72,9 @@ def _v_scope(cls, v: str | None) -> str | None: return _printable(v, 256) -class QueryBase(BaseModel): - since: int - until: int +class Scoped(BaseModel): + """What every query names: the instances, the users it may see, who asks.""" + instances: list[str] | None = None users: list[str] | None = Field(default=None, max_length=MAX_USERS) audit: AuditInfo @@ -95,6 +98,11 @@ def _v_users(cls, v: list[str] | None) -> list[str] | None: return v +class QueryBase(Scoped): + since: int + until: int + + class UsersQuery(QueryBase): limit: int = 100 offset: int = Field(default=0, ge=0) @@ -107,6 +115,8 @@ class TimelineQuery(QueryBase): resolution: Literal["hour", "minute"] = "hour" limit: int = 1000 offset: int = Field(default=0, ge=0) + # minute resolution: only this domain (the drill-down of the student page) + domain: str | None = Field(default=None, max_length=253) @field_validator("user") @classmethod @@ -118,6 +128,29 @@ def _v_user(cls, v: str) -> str: class DomainsQuery(QueryBase): limit: int = 50 + hide_background: bool = False + + +class BlockedQuery(QueryBase): + limit: int = 100 + + +class DayQuery(Scoped): + """Body of ``POST /v1/activity/day``: one user's day (the student page).""" + + user: str + day: datetime.date + start: int | None = None + end: int | None = None + since_minute: int | None = Field(default=None, ge=0) + domain_limit: int = 100 + + @field_validator("user") + @classmethod + def _v_user(cls, v: str) -> str: + if not _USER_RE.match(v): + raise ValueError("invalid user name") + return v class SearchQuery(QueryBase): @@ -160,12 +193,19 @@ def register( store: Store, auth: list[Any], require: Callable[[str], Instance], - apply: Callable[[Instance], dict[str, Any]], + ensure: Callable[[Instance], dict[str, Any]], container_status: Callable[[str], dict[str, Any]], + is_current: Callable[[Instance], bool], + categorizer: Categorizer | None = None, ) -> None: + """``ensure`` makes the container match a definition (health-gated, the previous container + stays when it fails); ``is_current`` says whether the running container already does.""" zone = ZoneInfo(settings.filter_timezone) audit_path = activity_audit.audit_dir(settings.activity_dir) + def _fail(code: str, message: str, http: int = status.HTTP_422_UNPROCESSABLE_ENTITY) -> None: + raise HTTPException(status_code=http, detail={"code": code, "message": message}) + def _settings_view(inst: Instance) -> dict[str, Any]: return { "name": inst.name, @@ -220,19 +260,82 @@ def _query_audit(kind: str, body: QueryBase, sources: list[Source], **extra: Any } ) - def _run(call: Callable[[], dict[str, Any]]) -> dict[str, Any]: + def _run( + call: Callable[[], dict[str, Any]], kind: str = "", users: list[str] | None = None + ) -> dict[str, Any]: + started = time.monotonic() try: return call() except ActivityError as exc: - raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail={"code": exc.code, "message": str(exc)}, + ) from None + finally: + took = time.monotonic() - started + if took > SLOW_SECONDS: + # the kind and the size, never names + audit.info( + "activity slow query kind=%s users=%s seconds=%.2f", + kind, + "all" if users is None else len(users), + took, + ) + + def _etag(paths: list[Path], body: BaseModel) -> str: + """Changes when a file the answer comes from or the question changes.""" + parts = [body.model_dump_json(exclude={"audit"})] + for path in sorted(paths): + for suffix in ("", "-wal"): + try: + st = os.stat(f"{path}{suffix}") + except FileNotFoundError: + continue + if suffix and st.st_size == 0: + continue # an empty WAL appears with the first reader: no change + parts.append(f"{path}{suffix}:{st.st_mtime_ns}:{st.st_size}") + return '"' + hashlib.sha1("|".join(parts).encode()).hexdigest() + '"' + + def _maybe_304(request: Request, etag: str) -> Response | None: + """After the audit line: an unchanged answer is 304 (the WebUI keeps the last one).""" + if request.headers.get("if-none-match") == etag: + return Response(status_code=status.HTTP_304_NOT_MODIFIED, headers={"ETag": etag}) + return None + + def _lesson_hours() -> list[str]: + return settings.activity_lesson_hours.split("-", 1) # ------------------------------------------------------------- settings @app.get("/v1/activity", dependencies=auth) - def activity_overview() -> dict[str, Any]: + def activity_overview(usage: bool = True) -> dict[str, Any]: + """Settings of every instance; ``usage=false`` is the light form the WebUI asks before + each view (no stat of every day file): the oldest day per instance, the lesson hours and + the category labels.""" + if usage: + instances = [_settings_view(inst) for inst in store.list()] + else: + instances = [] + for inst in store.list(): + files = activity.day_files(activity.data_dir(settings.activity_dir, inst.name)) + instances.append( + { + "name": inst.name, + "school": inst.school, + "role": inst.role, + "enabled": inst.activity_log_enabled, + "retention_days": inst.activity_retention_days, + "oldest": files[0][0].isoformat() if files else None, + "days": len(files), + } + ) + labels, background, _order = categorizer.meta() if categorizer else ({}, [], []) return { "timezone": settings.filter_timezone, "audit_retention_days": settings.activity_audit_retention_days, - "instances": [_settings_view(inst) for inst in store.list()], + "lesson_hours": _lesson_hours(), + "category_labels": labels, + "background_categories": background, + "instances": instances, } @app.get("/v1/instances/{name}/activity", dependencies=auth) @@ -246,6 +349,22 @@ def get_activity(name: str) -> dict[str, Any]: view["image_capable"] = None return view + def _audit_settings( + body: ActivitySettings, name: str, merged: Instance, switching_on: bool, result: str + ) -> None: + _audit( + { + "action": "settings", + "actor": body.actor, + "instance": name, + "enabled": merged.activity_log_enabled, + "retention_days": merged.activity_retention_days, + "ack_by": body.ack_by if switching_on else None, + "delete_data": bool(body.delete_data and not body.enabled), + "result": result[:300], + } + ) + @app.put("/v1/instances/{name}/activity", dependencies=auth) def put_activity(name: str, body: ActivitySettings) -> dict[str, Any]: inst = require(name) @@ -253,9 +372,9 @@ def put_activity(name: str, body: ActivitySettings) -> dict[str, Any]: switching_on = body.enabled and not inst.activity_log_enabled if switching_on: if not body.ack_by: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="switching the activity log on needs the confirmed privacy notice " + _fail( + "ack_missing", + "switching the activity log on needs the confirmed privacy notice " "(ack_by: who confirmed it)", ) updates["activity_ack_by"] = body.ack_by @@ -268,23 +387,29 @@ def put_activity(name: str, body: ActivitySettings) -> dict[str, Any]: merged = Instance.model_validate( {**inst.model_dump(exclude={"name", "container_name"}), **updates} ) - _audit( - { - "action": "settings", - "actor": body.actor, - "instance": name, - "enabled": merged.activity_log_enabled, - "retention_days": merged.activity_retention_days, - "ack_by": body.ack_by if switching_on else None, - "delete_data": bool(body.delete_data and not body.enabled), - } - ) - if merged.activity_log_enabled != inst.activity_log_enabled: - # the container gets (or loses) the spool and the receiver: replaced, health-gated - result: dict[str, Any] | None = apply(merged) - else: + toggled = merged.activity_log_enabled != inst.activity_log_enabled + result: dict[str, Any] | None = None + try: + # The definition is written only after the container matches it: a failure leaves + # the instance as it was (lab 2026-11-25: the definition said "on", the container + # had no spool, and switching on again did nothing). Switching on again while the + # container lacks the log (an earlier failure, a manual change) applies it. + if toggled or (merged.activity_log_enabled and not is_current(merged)): + if merged.activity_log_enabled: + activity.ensure_spool(settings.activity_spool_dir, name) + result = ensure(merged) store.put(merged) - result = None + except HTTPException as exc: + _audit_settings(body, name, merged, switching_on, f"failed: {exc.detail}") + _fail("apply_failed", f"activity log not changed: {exc.detail}", exc.status_code) + except Exception as exc: # noqa: BLE001 - reported legibly, nothing half done + _audit_settings(body, name, merged, switching_on, f"failed: {exc}") + _fail( + "apply_failed", + f"activity log not changed: {type(exc).__name__}: {exc}", + status.HTTP_500_INTERNAL_SERVER_ERROR, + ) + _audit_settings(body, name, merged, switching_on, "ok") deleted = None if body.delete_data and not merged.activity_log_enabled: deleted = activity.delete_data(settings.activity_dir, settings.activity_spool_dir, name) @@ -292,6 +417,9 @@ def put_activity(name: str, body: ActivitySettings) -> dict[str, Any]: activity.apply_retention( settings.activity_dir, name, merged.activity_retention_days, zone ) + if not merged.activity_log_enabled: + # nothing waits in it any more (or the collector removes it once it is empty) + activity.remove_spool_if_empty(settings.activity_spool_dir, name) audit.info( "activity settings name=%s enabled=%s retention=%d deleted=%s by=%s", name, @@ -319,7 +447,11 @@ def delete_activity_data(name: str, actor: str = "api") -> dict[str, Any]: # -------------------------------------------------------------- queries def _query(sources: list[Source]) -> Query: - return Query(settings.activity_dir, zone, sources) + return Query(settings.activity_dir, zone, sources, categorizer=categorizer) + + def _check_in_scope(user: str, users: list[str] | None) -> None: + if users is not None and user.lower() not in {u.lower() for u in users}: + _fail("not_in_scope", "user not in scope", status.HTTP_403_FORBIDDEN) @app.post("/v1/activity/users", dependencies=auth) def query_users(body: UsersQuery) -> dict[str, Any]: @@ -334,26 +466,92 @@ def query_users(body: UsersQuery) -> dict[str, Any]: body.offset, body.sort, body.with_domains, - ) + ), + "users", + body.users, ) @app.post("/v1/activity/timeline", dependencies=auth) - def query_timeline(body: TimelineQuery) -> dict[str, Any]: + def query_timeline(body: TimelineQuery, request: Request) -> Any: sources = _sources(body.instances) - if body.users is not None and body.user.lower() not in {u.lower() for u in body.users}: - raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="user not in scope") - _query_audit("timeline", body, sources, user=body.user, resolution=body.resolution) - return _run( - lambda: _query(sources).timeline( - body.user, body.since, body.until, body.resolution, body.limit, body.offset - ) + _check_in_scope(body.user, body.users) + extra: dict[str, Any] = {"user": body.user, "resolution": body.resolution} + if body.domain: + extra["domain"] = body.domain + _query_audit("timeline", body, sources, **extra) + query = _query(sources) + etag = _etag([p for _d, p, _w in query.files(body.since, body.until)], body) + not_modified = _maybe_304(request, etag) + if not_modified is not None: + return not_modified + data = _run( + lambda: query.timeline( + body.user, + body.since, + body.until, + body.resolution, + body.limit, + body.offset, + body.domain, + ), + "timeline", + body.users, ) + return JSONResponse(data, headers={"ETag": etag}) + + @app.post("/v1/activity/day", dependencies=auth) + def query_day(body: DayQuery, request: Request) -> Any: + sources = _sources(body.instances) + _check_in_scope(body.user, body.users) + query = _query(sources) + day_start, day_end = query._day_bounds(body.day) + _audit( + { + "action": "day", + "actor": body.audit.actor, + "role": body.audit.role, + "scope": body.audit.scope, + "since": max(day_start, body.start or day_start), + "until": min(day_end, body.end or day_end), + "instances": [s.name for s in sources], + "user": body.user, + "live": body.since_minute is not None, + } + ) + etag = _etag(query.day_files(body.day), body) + not_modified = _maybe_304(request, etag) + if not_modified is not None: + return not_modified + data = _run( + lambda: query.day( + body.user, body.day, body.start, body.end, body.since_minute, body.domain_limit + ), + "day", + [body.user], + ) + return JSONResponse(data, headers={"ETag": etag}) @app.post("/v1/activity/domains", dependencies=auth) def query_domains(body: DomainsQuery) -> dict[str, Any]: sources = _sources(body.instances) _query_audit("domains", body, sources) - return _run(lambda: _query(sources).domains(body.since, body.until, body.users, body.limit)) + return _run( + lambda: _query(sources).domains( + body.since, body.until, body.users, body.limit, body.hide_background + ), + "domains", + body.users, + ) + + @app.post("/v1/activity/blocked", dependencies=auth) + def query_blocked(body: BlockedQuery) -> dict[str, Any]: + sources = _sources(body.instances) + _query_audit("blocked", body, sources) + return _run( + lambda: _query(sources).blocked(body.since, body.until, body.users, body.limit), + "blocked", + body.users, + ) @app.post("/v1/activity/search", dependencies=auth) def query_search(body: SearchQuery) -> dict[str, Any]: @@ -362,7 +560,9 @@ def query_search(body: SearchQuery) -> dict[str, Any]: return _run( lambda: _query(sources).search( body.domain, body.since, body.until, body.users, body.limit - ) + ), + "search", + body.users, ) @app.post("/v1/activity/export", dependencies=auth) @@ -371,7 +571,9 @@ def query_export(body: QueryBase) -> StreamingResponse: try: lines = _query(sources).export(body.since, body.until, body.users) except ActivityError as exc: - raise HTTPException(status_code=422, detail=str(exc)) from exc + raise HTTPException( + status_code=422, detail={"code": exc.code, "message": str(exc)} + ) from exc _query_audit("export", body, sources) return StreamingResponse(lines, media_type="text/csv; charset=utf-8") diff --git a/controlplane/lmnsquid/activity_query.py b/controlplane/lmnsquid/activity_query.py index b8bfbfe..c273077 100644 --- a/controlplane/lmnsquid/activity_query.py +++ b/controlplane/lmnsquid/activity_query.py @@ -17,7 +17,10 @@ import datetime import io import json +import logging +import os import sqlite3 +import threading import time from dataclasses import dataclass from pathlib import Path @@ -25,8 +28,11 @@ from zoneinfo import ZoneInfo from . import activity +from . import filterdecision as fd from .activity import ActivityError +logger = logging.getLogger("lmnsquid.activity") + DAY = 86400 MAX_RANGE_DAYS = 366 MAX_MINUTE_RANGE = 2 * DAY @@ -39,6 +45,106 @@ MAX_SEARCH_CANDIDATES = 5000 TIME_BUDGET = 20.0 ACTIVE_SECONDS = 300 +MAX_DAY_DOMAINS = 200 +SLOW_SECONDS = 1.0 +# catalog groups whose domains are background services (ads, trackers, telemetry), not pages a +# student opened: hidden in the views on request +BACKGROUND_GROUPS = ("ads", "telemetry") + + +class Categorizer: + """Category ids of domains (also of allowed ones) from the host's catalog and own lists, + their German labels, and which of them are background services. + + The catalog file is opened once and again only when ``current.sqlite`` changes; the labels + come from the catalog description (``sources.yml``) and the admin's own categories, read again + after 60 s. Nothing of it is activity data. + """ + + def __init__(self, catalog_dir: str, config: Callable[[], Any] | None = None) -> None: + self.catalog_dir = catalog_dir + self.config = config + self.lock = threading.Lock() + self._catalog: fd.Catalog | None = None + self._stamp: tuple[int, int] | None = None + self._custom: tuple[float, dict[str, frozenset[str]], dict[str, str]] | None = None + self._meta: tuple[float, dict[str, str], list[str], list[str]] | None = None + + def _current(self) -> fd.Catalog | None: + path = os.path.join(self.catalog_dir, "current.sqlite") + try: + st = os.stat(path) + except OSError: + return None + stamp = (st.st_ino, st.st_mtime_ns) + if stamp != self._stamp: + if self._catalog is not None: + self._catalog.close() + try: + self._catalog = fd.Catalog(path) + except Exception: # noqa: BLE001 - an unusable catalog: no categories, no error + self._catalog = None + self._stamp = stamp + return self._catalog + + def _own(self) -> tuple[dict[str, frozenset[str]], dict[str, str]]: + now = time.monotonic() + if self._custom is None or now - self._custom[0] > 60: + lists, labels = fd.read_custom(os.path.join(self.catalog_dir, "custom")) + self._custom = (now, lists, labels) + return self._custom[1], self._custom[2] + + def meta(self) -> tuple[dict[str, str], list[str], list[str]]: + """(labels {id: label}, background ids, the order of the categories).""" + now = time.monotonic() + with self.lock: + if self._meta is None or now - self._meta[0] > 60: + labels: dict[str, str] = {} + background: list[str] = [] + order: list[str] = [] + try: + config = self.config() if self.config else None + except Exception: # noqa: BLE001 - labels are a convenience + config = None + for cat in getattr(config, "categories", None) or []: + labels[str(cat["id"])] = str(cat.get("label") or cat["id"]) + order.append(str(cat["id"])) + if cat.get("group") in BACKGROUND_GROUPS: + background.append(str(cat["id"])) + _lists, own_labels = self._own() + labels.update(own_labels) + order += sorted(own_labels) + self._meta = (now, labels, background, order) + return self._meta[1], self._meta[2], self._meta[3] + + def lookup(self, hosts: list[str]) -> dict[str, list[str]]: + """Category ids of each host (catalog and own lists), in the order of the categories.""" + _labels, background, order = self.meta() + rank = {cid: i for i, cid in enumerate(order)} + out: dict[str, list[str]] = {} + with self.lock: + catalog = self._current() + own, _own_labels = self._own() + for host in hosts: + found: set[str] = set() + parts = fd.suffixes(host) + if catalog is not None: + try: + fmask, _hits = catalog.lookup(host, parts) + except sqlite3.Error: + fmask = 0 + for bit, (_src, cid) in catalog.feeds.items(): + if fmask & (1 << bit): + found.add(cid) + for cid, names in own.items(): + if fd.listed(host, names, parts): + found.add(cid) + if found: + # pages first, background services last + out[host] = sorted( + found, key=lambda c: (c in background, rank.get(c, len(rank)), c) + ) + return out @dataclass @@ -61,21 +167,25 @@ def handler(self) -> Callable[[], int]: def check(self) -> None: if self.expired(): - raise ActivityError("query too large: choose a shorter range or fewer users") + raise ActivityError( + "query too large: choose a shorter range or fewer users", "query_too_large" + ) def check_range(since: int, until: int, max_seconds: int = MAX_RANGE_DAYS * DAY) -> None: if since < 0 or until <= since: raise ActivityError("until must be after since") if until - since > max_seconds: - raise ActivityError(f"range too long (at most {max_seconds // DAY or 1} days)") + raise ActivityError( + f"range too long (at most {max_seconds // DAY or 1} days)", "range_too_long" + ) def check_users(users: list[str] | None) -> list[str] | None: if users is None: return None if len(users) > MAX_USERS: - raise ActivityError(f"too many users (at most {MAX_USERS})") + raise ActivityError(f"too many users (at most {MAX_USERS})", "too_many_users") cleaned = sorted({u.strip().lower() for u in users if isinstance(u, str) and u.strip()}) return cleaned @@ -92,9 +202,11 @@ def __init__( sources: list[Source], now: float | None = None, budget: Budget | None = None, + categorizer: Categorizer | None = None, ) -> None: self.data_root = data_root self.zone = zone + self.categorizer = categorizer self.sources = sources self.now = time.time() if now is None else now self.budget = budget or Budget() @@ -129,6 +241,24 @@ def files(self, since: int, until: int) -> list[tuple[datetime.date, Path, bool] out.sort(key=lambda item: item[0]) return out + def _categories(self, hosts: list[str]) -> tuple[dict[str, list[str]], set[str]]: + if self.categorizer is None or not hosts: + return {}, set() + _labels, background, _order = self.categorizer.meta() + return self.categorizer.lookup(hosts), set(background) + + def day_files(self, day: datetime.date) -> list[Path]: + """The files of one local day (one per instance), within each instance's retention.""" + today = activity.today_in(self.zone, self.now) + out = [] + for source in self.sources: + if day < activity.oldest_kept(today, source.retention_days) or day > today: + continue + path = activity.data_dir(self.data_root, source.name) / activity.day_name(day) + if path.is_file(): + out.append(path) + return out + def _open(self, path: Path) -> sqlite3.Connection: db = activity.connect_day(path, create=False) db.set_progress_handler(self.budget.handler(), 20_000) @@ -145,7 +275,7 @@ def _run(self, path: Path, work: Callable[[sqlite3.Connection], None]) -> None: except sqlite3.OperationalError as exc: if "interrupted" in str(exc): raise ActivityError( - "query too large: choose a shorter range or fewer users" + "query too large: choose a shorter range or fewer users", "query_too_large" ) from None raise finally: @@ -254,8 +384,10 @@ def timeline( resolution: str = "hour", limit: int = 1000, offset: int = 0, + domain: str | None = None, ) -> dict[str, Any]: - """One user's activity: per hour (heat map) or per minute and domain.""" + """One user's activity: per hour (heat map) or per minute and domain; ``domain`` (minute + resolution only) keeps the minutes of that one domain (the drill-down).""" user = user.strip().lower() if not user: raise ActivityError("user missing") @@ -267,11 +399,15 @@ def timeline( for _day, path, _whole in self.files(since, until): def work_m(db: sqlite3.Connection) -> None: + extra, args = "", [] + if domain: + extra = " AND act.h = (SELECT id FROM hosts WHERE name = ?)" + args = [domain.strip().lower()] for m, host, n, b, x, c in db.execute( "SELECT act.m, ho.name, act.n, act.b, act.x, act.c FROM act " "JOIN hosts ho ON ho.id = act.h WHERE act.u = " - "(SELECT id FROM users WHERE name = ?) AND act.m BETWEEN ? AND ?", - [user, ms, me], + "(SELECT id FROM users WHERE name = ?) AND act.m BETWEEN ? AND ?" + extra, + [user, ms, me, *args], ): row = rows.setdefault((m, host), [0, 0, 0, None]) row[0] += n @@ -333,8 +469,11 @@ def domains( until: int, users: list[str] | None, limit: int = 50, + hide_background: bool = False, ) -> dict[str, Any]: - """Top domains of the users (or of everyone): requests, bytes, blocked, users, category.""" + """Top domains of the users (or of everyone): requests, bytes, blocked, users, category + (of a blocked request), the catalog's categories of the domain and whether it is a + background service (ads, trackers, telemetry); ``hide_background`` leaves those out.""" check_range(since, until) users = check_users(users) limit = max(1, min(limit, MAX_DOMAIN_LIMIT)) @@ -370,7 +509,15 @@ def work(db: sqlite3.Connection, whole: bool = whole) -> None: row[3] = c or row[3] self._run(path, work) - ordered = sorted(acc.items(), key=lambda kv: (-kv[1][0], kv[0]))[:limit] + ordered = sorted(acc.items(), key=lambda kv: (-kv[1][0], kv[0])) + cats, background = self._categories([h for h, _r in ordered[: limit * 4]]) + if hide_background: + ordered = [ + kv + for kv in ordered[: limit * 4] + if not (cats.get(kv[0]) and set(cats[kv[0]]) <= background) + ] + ordered = ordered[:limit] top = [host for host, _row in ordered] who: dict[str, set[str]] = {host: set() for host in top} if top: @@ -407,12 +554,156 @@ def work_users(db: sqlite3.Connection, whole: bool = whole) -> None: "bytes": b, "blocked": x, "category": c, + "categories": cats.get(host, []), + "background": bool(cats.get(host)) and set(cats[host]) <= background, "users": len(who.get(host, ())), } for host, (n, b, x, c) in ordered ], } + def blocked( + self, since: int, until: int, users: list[str] | None, limit: int = 100 + ) -> dict[str, Any]: + """Blocked attempts of the users per domain: how often, by how many, the category.""" + check_range(since, until) + users = check_users(users) + limit = max(1, min(limit, MAX_DOMAIN_LIMIT)) + if users == []: + return {"total": 0, "domains": []} + ms, me = since // 60, (until - 1) // 60 + acc: dict[str, list[Any]] = {} + for _day, path, whole in self.files(since, until): + + def work(db: sqlite3.Connection, whole: bool = whole) -> None: + if whole: + w, a = self._user_filter(users, "uhd.u") + sql = ( + "SELECT ho.name, us.name, sum(uhd.x), max(uhd.c) FROM uhd " + "JOIN hosts ho ON ho.id = uhd.h JOIN users us ON us.id = uhd.u " + "WHERE uhd.x > 0" + w + " GROUP BY uhd.h, uhd.u" + ) + params: list[Any] = a + else: + w, a = self._user_filter(users, "act.u") + sql = ( + "SELECT ho.name, us.name, sum(act.x), max(act.c) FROM act " + "JOIN hosts ho ON ho.id = act.h JOIN users us ON us.id = act.u " + "WHERE act.x > 0 AND act.m BETWEEN ? AND ?" + w + " GROUP BY act.h, act.u" + ) + params = [ms, me, *a] + for host, name, x, c in db.execute(sql, params): + row = acc.setdefault(host, [0, set(), None]) + row[0] += x + row[1].add(name) + row[2] = c or row[2] + + self._run(path, work) + ordered = sorted(acc.items(), key=lambda kv: (-len(kv[1][1]), -kv[1][0], kv[0])) + return { + "total": len(ordered), + "domains": [ + {"domain": host, "blocked": x, "users": len(who), "category": c} + for host, (x, who, c) in ordered[:limit] + ], + } + + def day( + self, + user: str, + day: datetime.date, + start: int | None = None, + end: int | None = None, + since_minute: int | None = None, + domain_limit: int = 100, + ) -> dict[str, Any]: + """One user's day: active minutes (requests, blocked, domains per minute) and the domains + with the minutes they were used in, from the primary key (user, minute) only. + + ``start``/``end`` (epoch seconds, within the day) narrow it to a part of the day; + ``since_minute`` returns only the minutes from that one on (the live delta), the domains + and totals stay those of the whole range. + """ + user = user.strip().lower() + if not user: + raise ActivityError("user missing") + day_start, day_end = self._day_bounds(day) + start = day_start if start is None else max(day_start, start) + end = day_end if end is None else min(day_end, end) + if end <= start: + raise ActivityError("until must be after since") + domain_limit = max(1, min(domain_limit, MAX_DAY_DOMAINS)) + ms, me = start // 60, (end - 1) // 60 + first_minute = ms if since_minute is None else max(ms, since_minute - 1) + minutes: dict[int, list[int]] = {} + domains: dict[str, list[Any]] = {} + for path in self.day_files(day): + + def work(db: sqlite3.Connection) -> None: + uid = db.execute("SELECT id FROM users WHERE name = ?", [user]).fetchone() + if uid is None: + return + for m, n, x, d in db.execute( + "SELECT m, sum(n), sum(x), count(*) FROM act WHERE u = ? AND m BETWEEN ? AND ? " + "GROUP BY m", + [uid[0], ms, me], + ): + row = minutes.setdefault(m, [0, 0, 0]) + row[0] += n + row[1] += x + row[2] = max(row[2], d) + for host, mins, n, x, c, first, last in db.execute( + "SELECT ho.name, count(*), sum(act.n), sum(act.x), max(act.c), min(act.m), " + "max(act.m) FROM act JOIN hosts ho ON ho.id = act.h " + "WHERE act.u = ? AND act.m BETWEEN ? AND ? GROUP BY act.h", + [uid[0], ms, me], + ): + row = domains.setdefault(host, [0, 0, 0, None, first, last]) + row[0] += mins + row[1] += n + row[2] += x + row[3] = c or row[3] + row[4] = min(row[4], first) + row[5] = max(row[5], last) + + self._run(path, work) + ordered = sorted(domains.items(), key=lambda kv: (-kv[1][0], -kv[1][1], kv[0])) + top, rest = ordered[:domain_limit], ordered[domain_limit:] + cats, background = self._categories([h for h, _r in top]) + return { + "user": user, + "day": day.isoformat(), + "start": start, + "end": end, + "minutes": [ + [m * 60, n, x, d] for m, (n, x, d) in sorted(minutes.items()) if m >= first_minute + ], + "domains": [ + { + "domain": host, + "minutes": mins, + "requests": n, + "blocked": x, + "category": c, + "categories": cats.get(host, []), + "background": bool(cats.get(host)) and set(cats[host]) <= background, + "first": first * 60, + "last": last * 60, + } + for host, (mins, n, x, c, first, last) in top + ], + "other": {"count": len(rest), "requests": sum(r[1] for _h, r in rest)}, + "totals": { + "active_minutes": len(minutes), + "requests": sum(r[0] for r in minutes.values()), + "blocked": sum(r[1] for r in minutes.values()), + "domains": len(domains), + "first": min(minutes) * 60 if minutes else None, + "last": max(minutes) * 60 if minutes else None, + }, + "cursor": max(minutes) if minutes else None, + } + def search( self, domain: str, @@ -445,26 +736,32 @@ def work(db: sqlite3.Connection, whole: bool = whole) -> None: if not host_ids: return w, a = self._user_filter(users, "uhd.u") + hosts_json = json.dumps(sorted(host_ids)) cands = db.execute( "SELECT uhd.u, us.name, uhd.h, uhd.n, uhd.x, uhd.first, uhd.last FROM uhd " "JOIN users us ON us.id = uhd.u WHERE uhd.h IN (SELECT value FROM json_each(?))" + w + " LIMIT ?", - [json.dumps(sorted(host_ids)), *a, MAX_SEARCH_CANDIDATES + 1], + [hosts_json, *a, MAX_SEARCH_CANDIDATES + 1], ).fetchall() if len(cands) > MAX_SEARCH_CANDIDATES: - raise ActivityError("too many hits: choose a shorter range or a longer name") - for u, name, h, n, x, first, last in cands: - if not whole: - if last < ms or first > me: - continue - n, x, first, last = db.execute( - "SELECT sum(n), sum(x), min(m), max(m) FROM act " - "WHERE u = ? AND m BETWEEN ? AND ? AND h = ?", - [u, ms, me, h], - ).fetchone() - if not n: - continue + raise ActivityError( + "too many hits: choose a shorter range or a longer name", "too_many_hits" + ) + if not whole: + # a partial day: the candidates' minutes in one statement (primary key + # prefix user + minute per candidate), not one query per candidate + names = {c[0]: c[1] for c in cands if not (c[6] < ms or c[5] > me)} + cands = [ + (u, names[u], h, n, x, first, last) + for u, h, n, x, first, last in db.execute( + "SELECT u, h, sum(n), sum(x), min(m), max(m) FROM act " + "WHERE u IN (SELECT value FROM json_each(?)) AND m BETWEEN ? AND ? " + "AND h IN (SELECT value FROM json_each(?)) GROUP BY u, h", + [json.dumps(sorted(names)), ms, me, hosts_json], + ) + ] + for _u, name, h, n, x, first, last in cands: row = found.setdefault(name, [0, 0, first, last, set()]) row[0] += n row[1] += x diff --git a/controlplane/lmnsquid/api.py b/controlplane/lmnsquid/api.py index ba3f4fe..9f79b1c 100644 --- a/controlplane/lmnsquid/api.py +++ b/controlplane/lmnsquid/api.py @@ -18,7 +18,7 @@ from fastapi.responses import JSONResponse, Response from pydantic import ValidationError -from . import activity, activity_api +from . import activity, activity_api, activity_query from . import catalog as catalog_mod from .blocklist import Blocklist, noauth_list from .config import Settings @@ -840,5 +840,15 @@ def rollback_instance(name: str) -> dict[str, Any]: except FileNotFoundError as exc: raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc - activity_api.register(app, settings, store, auth, _require, _apply, lambda n: docker.status(n)) + activity_api.register( + app, + settings, + store, + auth, + _require, + lambda inst: _ensure(inst), + lambda n: docker.status(n), + lambda inst: docker.is_current(inst), + activity_query.Categorizer(settings.catalog_dir, lambda: catalog_paths.config()), + ) return app diff --git a/controlplane/lmnsquid/cli.py b/controlplane/lmnsquid/cli.py index 178091c..8c44c91 100644 --- a/controlplane/lmnsquid/cli.py +++ b/controlplane/lmnsquid/cli.py @@ -1103,6 +1103,7 @@ def activity_timeline( instance: list[str] = _INST_OPT, scope: Optional[str] = _SCOPE_OPT, minute: bool = typer.Option(False, help="per minute and domain (at most 2 days)"), + domain: Optional[str] = typer.Option(None, help="with --minute: only this domain"), limit: int = typer.Option(1000), offset: int = typer.Option(0), ) -> None: @@ -1114,12 +1115,54 @@ def activity_timeline( "resolution": "minute" if minute else "hour", "limit": limit, "offset": offset, + "domain": domain, } ) with _get_client() as c: _emit(c.post("/v1/activity/timeline", json=body)) +@activity_app.command("day") +def activity_day( + name: str = typer.Argument(..., help="user (sAMAccountName)"), + date: Optional[str] = typer.Option(None, help="YYYY-MM-DD (default: today)"), + instance: list[str] = _INST_OPT, + scope: Optional[str] = _SCOPE_OPT, +) -> None: + """One user's day: active minutes and the domains with the minutes they were used in.""" + import datetime + from zoneinfo import ZoneInfo + + day = ( + date or datetime.datetime.now(ZoneInfo(load_settings().filter_timezone)).date().isoformat() + ) + body = { + "user": name, + "day": day, + "instances": instance or None, + "audit": {"actor": _actor(), "role": "cli", "scope": scope}, + } + with _get_client() as c: + _emit(c.post("/v1/activity/day", json=body)) + + +@activity_app.command("blocked") +def activity_blocked( + range_: str = _RANGE_OPT, + since: Optional[int] = _SINCE_OPT, + until: Optional[int] = _UNTIL_OPT, + user: list[str] = _USER_OPT, + instance: list[str] = _INST_OPT, + scope: Optional[str] = _SCOPE_OPT, + limit: int = typer.Option(100), +) -> None: + """Blocked attempts per domain: how often, by how many users, the category.""" + body = _query_body(range_, since, until, user, instance, scope) + body["limit"] = limit + with _get_client() as c: + _emit(c.post("/v1/activity/blocked", json=body)) + + @activity_app.command("domains") def activity_domains( range_: str = _RANGE_OPT, diff --git a/controlplane/lmnsquid/config.py b/controlplane/lmnsquid/config.py index 4ed2e95..a4f91a1 100644 --- a/controlplane/lmnsquid/config.py +++ b/controlplane/lmnsquid/config.py @@ -43,6 +43,8 @@ class Settings(BaseSettings): activity_dir: str = "/var/lib/linuxmuster-squid/activity" activity_spool_dir: str = "/var/spool/linuxmuster-squid/activity" activity_audit_retention_days: int = 365 + # "Unterricht" of the activity view (local time of filter_timezone), HH:MM-HH:MM + activity_lesson_hours: str = "07:45-16:00" docker_host: str | None = None bind_host: str = "127.0.0.1" bind_port: int = 8080 @@ -62,6 +64,16 @@ class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix=_ENV_PREFIX) + @field_validator("activity_lesson_hours") + @classmethod + def _v_lesson_hours(cls, v: str) -> str: + import re + + m = re.fullmatch(r"([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)", v.strip()) + if m is None or (m[1], m[2]) >= (m[3], m[4]): + raise ValueError("activity_lesson_hours must be HH:MM-HH:MM, start before end") + return v.strip() + @field_validator("activity_audit_retention_days") @classmethod def _v_audit_retention(cls, v: int) -> int: diff --git a/controlplane/lmnsquid/docker_service.py b/controlplane/lmnsquid/docker_service.py index dde6465..0ed7f67 100644 --- a/controlplane/lmnsquid/docker_service.py +++ b/controlplane/lmnsquid/docker_service.py @@ -367,6 +367,16 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: f"container for {inst.name!r} did not become healthy: {reason}{restored}" ) + def is_current(self, inst: Instance) -> bool: + """Whether a running container already carries the spec of ``inst`` (no pull).""" + existing = self._get(inst.name) + if existing is None or existing.labels.get(SPEC_LABEL) != self.fingerprint( + self.spec_for(inst) + ): + return False + existing.reload() + return bool((existing.attrs.get("State") or {}).get("Running", False)) + def _wait_healthy(self, container: Container) -> Optional[str]: """Return ``None`` once ``container`` is healthy, else why it is not. diff --git a/controlplane/tests/conftest.py b/controlplane/tests/conftest.py index a39dddf..948dfcb 100644 --- a/controlplane/tests/conftest.py +++ b/controlplane/tests/conftest.py @@ -88,6 +88,10 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: } return self.status(inst.name) + def is_current(self, inst: Instance) -> bool: + container = self.containers.get(inst.name) + return bool(container and container["running"] and container["env"] == self.env_for(inst)) + def start(self, name: str) -> dict[str, Any]: container = self.containers.get(name) if container is not None: diff --git a/controlplane/tests/test_activity.py b/controlplane/tests/test_activity.py index a3facc7..7fded10 100644 --- a/controlplane/tests/test_activity.py +++ b/controlplane/tests/test_activity.py @@ -104,12 +104,14 @@ def test_parse_line_user_without_realm_and_blocked_flags() -> None: 512, 0, None, + False, ) + assert parse_line(b"1 s1 a.b 200 NONE_NONE 0 -")[6] is True # type: ignore[index] # squid may %-encode the @ of the principal assert parse_line(b"1 s1%40EX.LAN a.b 200 TCP_MISS 1 -")[1] == "s1" # type: ignore[index] - assert parse_line(b"1 s1 a.b 403 TCP_DENIED 10 porn")[4:] == (1, "porn") # type: ignore[index] + assert parse_line(b"1 s1 a.b 403 TCP_DENIED 10 porn")[4:6] == (1, "porn") # type: ignore[index] assert parse_line(b"1 s1 a.b 403 TCP_DENIED 10 -")[4] == 1 # type: ignore[index] - assert parse_line(b"1 s1 a.b 200 NONE_NONE - ads")[3:] == (0, 1, "ads") # type: ignore[index] + assert parse_line(b"1 s1 a.b 200 NONE_NONE - ads")[3:6] == (0, 1, "ads") # type: ignore[index] # no ticket / a domain without authentication: no user, not counted assert parse_line(b"1 - healthcheck.invalid 407 TCP_DENIED 3497 -") is None @@ -161,6 +163,125 @@ def test_collect_sums_per_minute_and_deletes_the_spool_file(env: Env) -> None: assert oct(os.stat(Path(env.data) / env.inst.name / "2026-11-25.sqlite").st_mode)[-3:] == "600" +def _rows(env: Env) -> list[tuple[Any, ...]]: + return ( + env.db() + .execute( + "SELECT us.name, ho.name, sum(n), sum(x), max(c) FROM act JOIN users us ON us.id = u " + "JOIN hosts ho ON ho.id = h GROUP BY 1, 2 ORDER BY 1, 2" + ) + .fetchall() + ) + + +def test_one_https_visit_is_one_request(env: Env) -> None: + """squid's lines as logged by squid 6.14 in the e2e: the peek of an allowed CONNECT, the error + page inside TLS of a refused one, an SNI in a category behind an allowed CONNECT.""" + env.put( + # allowed: NONE_NONE/200 peek + TCP_TUNNEL/200 + line(T0, "t1", "ok.example", 200, "NONE_NONE", 0) + + line(T0, "t1", "ok.example", 200, "TCP_TUNNEL", 2197) + # refused CONNECT (own blocklist): TCP_DENIED/200 + NONE_NONE/403 error page + + line(T0 + 1, "t1", "bad.example", 200, "TCP_DENIED", 0) + + line(T0 + 1, "t1", "bad.example", 403, "NONE_NONE", 3435) + # CONNECT allowed, SNI in a category: the peek line carries the category + + line(T0 + 2, "t1", "sni.example", 200, "NONE_NONE", 0, cat="porn") + + line(T0 + 2, "t1", "sni.example", 200, "TCP_TUNNEL", 0) + # a blocked side line alone (its CONNECT in another file) still counts + + line(T0 + 3, "t1", "alone.example", 403, "NONE_NONE", 10, cat="gambling") + # an allowed peek alone does not + + line(T0 + 4, "t1", "peek.example", 200, "NONE_NONE", 0) + ) + c = env.collect() + assert c.side == 4 + assert _rows(env) == [ + ("t1", "alone.example", 1, 1, "gambling"), + ("t1", "bad.example", 1, 1, None), + ("t1", "ok.example", 1, 0, None), + ("t1", "sni.example", 1, 1, "porn"), + ] + + +def test_spool_never_needs_a_set_id_bit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """RestrictSUIDSGID=yes refuses S_ISUID/S_ISGID (lab 2026-11-25: 500 on switching on).""" + real_chmod, real_mkdir = os.chmod, os.mkdir + + def chmod(path: Any, mode: int, *a: Any, **k: Any) -> None: + if mode & 0o6000: + raise PermissionError(1, "Operation not permitted (RestrictSUIDSGID)") + real_chmod(path, mode, *a, **k) + + def mkdir(path: Any, mode: int = 0o777, *a: Any, **k: Any) -> None: + if mode & 0o6000: + raise PermissionError(1, "Operation not permitted (RestrictSUIDSGID)") + real_mkdir(path, mode, *a, **k) + + monkeypatch.setattr(os, "chmod", chmod) + monkeypatch.setattr(os, "mkdir", mkdir) + path = activity.ensure_spool(str(tmp_path / "spool"), "x-students") + assert path.stat().st_mode & 0o7777 == 0o1733 + + +def _unit_hardening() -> list[str]: + """The properties of linuxmuster-squid.service a user manager can apply as well.""" + unit = Path(__file__).resolve().parents[2] / "packaging/systemd/linuxmuster-squid.service" + wanted = ("RestrictSUIDSGID=", "NoNewPrivileges=", "LockPersonality=", "RestrictNamespaces=") + return [ln.strip() for ln in unit.read_text().splitlines() if ln.strip().startswith(wanted)] + + +def _user_systemd() -> bool: + import shutil + + if shutil.which("systemd-run") is None: + return False + probe = subprocess.run( + ["systemd-run", "--user", "--quiet", "--wait", "--pipe", "true"], + capture_output=True, + timeout=30, + ) + return probe.returncode == 0 + + +@pytest.mark.skipif(not _user_systemd(), reason="no systemd user manager (systemd-run --user)") +def test_switching_on_works_under_the_units_restrictions(tmp_path: Path) -> None: + """ensure_spool run by systemd with the service's own restrictions (not only a mock).""" + props = _unit_hardening() + assert "RestrictSUIDSGID=yes" in props + root = Path(__file__).resolve().parents[1] + args = ["systemd-run", "--user", "--quiet", "--wait", "--pipe"] + for prop in props: + args += ["-p", prop] + code = ( + f"import sys; sys.path.insert(0, {str(root)!r}); from lmnsquid import activity; " + f"print(oct(activity.ensure_spool({str(tmp_path / 'spool')!r}, 'x-students').stat().st_mode))" + ) + out = subprocess.run(args + [sys.executable, "-c", code], capture_output=True, text=True) + assert out.returncode == 0, out.stderr + assert out.stdout.strip().endswith("1733") + # the old mode is what the restriction refuses (proves the test bites) + bad = subprocess.run( + args + + [ + sys.executable, + "-c", + f"import os; os.mkdir({str(tmp_path / 'b')!r}); " + f"os.chmod({str(tmp_path / 'b')!r}, 0o3733)", + ], + capture_output=True, + text=True, + ) + assert bad.returncode != 0 and "Operation not permitted" in bad.stderr + + +def test_spool_of_a_disabled_instance_goes_once_empty(env: Env) -> None: + env.put(line(T0, "s1", "a.example")) + paths = activity.Paths(env.data, env.spool_root, ZONE) + off = _inst(activity_log_enabled=False, activity_ack_by=None, activity_ack_at=None) + activity.collect_all([off], paths, now=T0 + 3600) + assert env.total() == 1, "what was spooled while on is still collected" + assert not env.spool.exists() + + def test_a_file_collected_twice_is_counted_once(env: Env) -> None: text = line(T0, "s1", "a.example") * 3 f = env.put(text) @@ -317,7 +438,7 @@ def test_receiver_finishes_files_on_time_and_on_sigterm(tmp_path: Path) -> None: done = _wait_files(tmp_path, "act-") assert len(done) == 1 assert done[0].read_text().count("\n") == 2, "the line without a user is not written" - assert oct(done[0].stat().st_mode)[-3:] == "640" + assert oct(done[0].stat().st_mode)[-3:] == "644" _send(port, line(T0 + 1, "s2", "c.example")) _wait_files(tmp_path, ".part-") finally: @@ -473,3 +594,94 @@ def test_queries_ignore_days_beyond_the_retention(env: Env) -> None: later = T0 + 10 * 86400 q = Query(env.data, ZONE, [Source(env.inst.name, 7)], now=later) assert q.users(T0 - 3600, later, None)["total"] == 0 + + +def test_day_of_one_student(env: Env) -> None: + _fill(env) + env.put(line(T0 + 61, "s1", "a.example", 403, "TCP_DENIED", cat="gambling")) + env.collect() + q = env.query() + d = q.day("s1", datetime.date(2026, 11, 25)) + assert [m[0] for m in d["minutes"]] == [T0, T0 + 60, T0 + 3600] + assert d["minutes"][1] == [T0 + 60, 2, 1, 1] + assert d["totals"] == { + "active_minutes": 3, + "requests": 4, + "blocked": 1, + "domains": 2, + "first": T0, + "last": T0 + 3600, + } + a = d["domains"][0] + assert (a["domain"], a["minutes"], a["requests"], a["blocked"], a["category"]) == ( + "a.example", + 2, + 3, + 1, + "gambling", + ) + assert d["cursor"] == (T0 + 3600) // 60 + # part of the day, and the live delta from a minute on + part = q.day("s1", datetime.date(2026, 11, 25), start=T0, end=T0 + 120) + assert part["totals"]["active_minutes"] == 2 and len(part["domains"]) == 1 + live = q.day("s1", datetime.date(2026, 11, 25), since_minute=(T0 + 3600) // 60) + assert [m[0] for m in live["minutes"]] == [T0 + 3600] + assert live["totals"]["active_minutes"] == 3, "totals stay those of the day" + # nobody / another day / beyond the retention + assert q.day("nobody", datetime.date(2026, 11, 25))["minutes"] == [] + assert q.day("s1", datetime.date(2026, 11, 24))["minutes"] == [] + later = Query(env.data, ZONE, [Source(env.inst.name, 1)], now=T0 + 86400) + assert later.day("s1", datetime.date(2026, 11, 25))["minutes"] == [] + + +def test_day_adds_up_instances(tmp_path: Path) -> None: + a, b = Env(tmp_path / "a"), Env(tmp_path / "b") + b.data = a.data + b.inst = _inst(role="teachers") + b.spool = activity.ensure_spool(b.spool_root, b.inst.name) + a.put(line(T0, "s1", "x.example")) + b.put(line(T0, "s1", "x.example") + line(T0, "s1", "y.example")) + a.collect() + b.collect() + q = Query(a.data, ZONE, [Source(a.inst.name, 7), Source(b.inst.name, 7)], now=T0 + 600) + d = q.day("s1", datetime.date(2026, 11, 25)) + assert d["minutes"] == [[T0, 3, 0, 2]] + assert {x["domain"]: x["requests"] for x in d["domains"]} == {"x.example": 2, "y.example": 1} + + +def test_drill_down_of_one_domain(env: Env) -> None: + _fill(env) + rows = env.query().timeline("s1", T0, T0 + 7200, "minute", domain="a.example")["rows"] + assert [(r["t"], r["domain"]) for r in rows] == [(T0, "a.example"), (T0 + 60, "a.example")] + + +def test_blocked_attempts_of_a_group(env: Env) -> None: + _fill(env) + env.put(line(T0 + 5, "s1", "b.example", 403, "TCP_DENIED", cat="porn")) + env.collect() + q = env.query() + got = q.blocked(T0 - 3600, T0 + 7200, ["s1", "s2"])["domains"] + assert got == [{"domain": "b.example", "blocked": 2, "users": 2, "category": "porn"}] + assert q.blocked(T0 - 3600, T0 + 7200, ["t1"])["domains"] == [] + assert q.blocked(T0 + 120, T0 + 180, ["s1", "s2"])["total"] == 0, "partial range" + + +def test_categories_of_allowed_domains_and_background(env: Env, tmp_path: Path) -> None: + from conftest import make_catalog + + from lmnsquid import catalog as catalog_mod + from lmnsquid.activity_query import Categorizer + + make_catalog(tmp_path / "catalog", {"ads": ["a.example"], "porn": ["b.example"]}) + cat = Categorizer(str(tmp_path / "catalog"), catalog_mod.load_config) + labels, background, _order = cat.meta() + assert labels["porn"] and "ads" in background and "porn" not in background + _fill(env) + q = Query(env.data, ZONE, [Source(env.inst.name, 7)], now=T0 + 3600, categorizer=cat) + top = {d["domain"]: d for d in q.domains(T0 - 3600, T0 + 7200, None)["domains"]} + assert top["a.example"]["categories"] == ["ads"] and top["a.example"]["background"] + assert top["b.example"]["categories"] == ["porn"] and not top["b.example"]["background"] + shown = q.domains(T0 - 3600, T0 + 7200, None, hide_background=True)["domains"] + assert "a.example" not in {d["domain"] for d in shown} + day = q.day("s1", datetime.date(2026, 11, 25)) + assert next(d for d in day["domains"] if d["domain"] == "a.example")["background"] is True diff --git a/controlplane/tests/test_activity_api.py b/controlplane/tests/test_activity_api.py index b346d83..91119ff 100644 --- a/controlplane/tests/test_activity_api.py +++ b/controlplane/tests/test_activity_api.py @@ -303,3 +303,156 @@ def test_spec_gets_the_spool_only_while_on(tmp_path: Path) -> None: ) ) ) + + +def test_a_failed_switch_on_changes_nothing_and_says_why( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + docker: Any, + store: Store, +) -> None: + """Lab 2026-11-25 (A1): the definition said "on" after a 500 and switching on again did + nothing. Now the definition is written only after the container step succeeded.""" + _create(client, auth_headers, instance_data) + real = docker.ensure_running + + def failing(inst: Instance) -> Any: + if inst.activity_log_enabled: + raise RuntimeError("container did not become healthy") + return real(inst) + + docker.ensure_running = failing + r = _enable(client, auth_headers) + assert r.status_code == 500 + detail = r.json()["detail"] + assert detail["code"] == "apply_failed" and "not changed" in detail["message"] + stored = store.get(NAME) + assert stored is not None and not stored.activity_log_enabled and stored.activity_ack_by is None + docker.ensure_running = real + assert _enable(client, auth_headers).status_code == 200 + assert docker.containers[NAME]["env"]["ACTIVITY_LOG_ENABLED"] == "1" + + +def test_switching_on_again_applies_a_definition_the_container_lacks( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + docker: Any, + store: Store, +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + # a container that lost the log (an older failure, a manual docker run) + docker.containers[NAME]["env"].pop("ACTIVITY_LOG_ENABLED") + calls = len(docker.ensure_calls) + assert _enable(client, auth_headers).status_code == 200 + assert len(docker.ensure_calls) == calls + 1 + assert docker.containers[NAME]["env"]["ACTIVITY_LOG_ENABLED"] == "1" + # already as defined: nothing replaced + assert _enable(client, auth_headers).status_code == 200 + assert len(docker.ensure_calls) == calls + 1 + + +def test_switching_off_removes_the_empty_spool( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + spool = Path(settings.activity_spool_dir) / NAME + assert spool.is_dir() and oct(spool.stat().st_mode & 0o7777) == "0o1733" + r = client.put(f"/v1/instances/{NAME}/activity", json={"enabled": False}, headers=auth_headers) + assert r.status_code == 200 + assert not spool.exists() + + +def test_light_overview_for_the_views( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + _seed(settings, int(time.time())) + r = client.get("/v1/activity", params={"usage": "false"}, headers=auth_headers) + assert r.status_code == 200 + body = r.json() + assert body["lesson_hours"] == ["07:45", "16:00"] + inst = body["instances"][0] + assert inst["days"] == 1 and inst["oldest"] and "usage" not in inst + assert "category_labels" in body and "background_categories" in body + + +def test_day_query_is_audited_and_revalidated( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + now = int(time.time()) + _seed(settings, now) + import datetime as dt + from zoneinfo import ZoneInfo + + day = dt.datetime.fromtimestamp(now, ZoneInfo("Europe/Berlin")).date().isoformat() + body = { + "user": "s2", + "day": day, + "users": ["s1", "s2"], + "audit": {"actor": "lehrer1", "role": "teacher", "scope": "user s2"}, + } + r = client.post("/v1/activity/day", json=body, headers=auth_headers) + assert r.status_code == 200, r.text + data = r.json() + assert data["totals"]["blocked"] == 1 and data["domains"][0]["domain"] == "b.example" + etag = r.headers["etag"] + again = client.post( + "/v1/activity/day", json=body, headers={**auth_headers, "If-None-Match": etag} + ) + assert again.status_code == 304 + lines = [e for e in _audit_lines(settings) if e["action"] == "day"] + assert len(lines) == 2, "the 304 is audited as well" + assert lines[0]["user"] == "s2" and lines[0]["actor"] == "lehrer1" + out = client.post("/v1/activity/day", json={**body, "user": "t1"}, headers=auth_headers) + assert out.status_code == 403 and out.json()["detail"]["code"] == "not_in_scope" + + +def test_blocked_and_drill_down_endpoints( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, +) -> None: + _create(client, auth_headers, instance_data) + _enable(client, auth_headers) + now = int(time.time()) + _seed(settings, now) + r = client.post("/v1/activity/blocked", json=_q(now, users=["s1", "s2"]), headers=auth_headers) + assert r.status_code == 200 + assert r.json()["domains"] == [ + {"domain": "b.example", "blocked": 1, "users": 1, "category": "porn"} + ] + r = client.post( + "/v1/activity/timeline", + json=_q(now, users=["s1"], user="s1", resolution="minute", domain="a.example"), + headers=auth_headers, + ) + assert r.status_code == 200 and [x["domain"] for x in r.json()["rows"]] == ["a.example"] + assert [e for e in _audit_lines(settings) if e.get("domain") == "a.example"] + + +def test_limit_errors_carry_a_code( + client: TestClient, auth_headers: dict[str, str], instance_data: dict[str, Any] +) -> None: + _create(client, auth_headers, instance_data) + now = int(time.time()) + r = client.post( + "/v1/activity/users", json={**_q(now), "since": now - 400 * 86400}, headers=auth_headers + ) + assert r.status_code == 422 and r.json()["detail"]["code"] == "range_too_long" diff --git a/controlplane/tests/test_cli.py b/controlplane/tests/test_cli.py index ba60fde..2c5b2b4 100644 --- a/controlplane/tests/test_cli.py +++ b/controlplane/tests/test_cli.py @@ -353,6 +353,14 @@ def test_cli_activity( assert r.exit_code == 0 and '"total": 0' in r.output, r.output r = runner.invoke(cli.app, ["activity", "timeline", "s1", "--minute", "--range", "hour"]) assert r.exit_code == 0, r.output + r = runner.invoke(cli.app, ["activity", "day", "s1"]) + assert r.exit_code == 0 and '"totals"' in r.output, r.output + r = runner.invoke(cli.app, ["activity", "blocked", "--range", "7d"]) + assert r.exit_code == 0 and '"domains"' in r.output, r.output + r = runner.invoke( + cli.app, ["activity", "timeline", "s1", "--minute", "--range", "hour", "--domain", "a.b"] + ) + assert r.exit_code == 0, r.output r = runner.invoke(cli.app, ["activity", "export", "--range", "hour"]) assert r.exit_code == 0 and r.output.startswith("time,user,domain"), r.output r = runner.invoke(cli.app, ["activity", "users", "--range", "year"]) diff --git a/deploy/e2e/docker-compose.yml b/deploy/e2e/docker-compose.yml index 53b128a..98a60e6 100644 --- a/deploy/e2e/docker-compose.yml +++ b/deploy/e2e/docker-compose.yml @@ -137,7 +137,7 @@ services: SCHOOL_SUBNETS: "10.228.0.30/32" KEYTAB: "/shared/squid.keytab" CACHE_SIZE_MB: "200" - # activity log (ADR-023) into a spool made like the control plane makes it (mode 3733) + # activity log (ADR-023) into a spool made like the control plane makes it (mode 1733) ACTIVITY_LOG_ENABLED: "1" dns: ["10.228.0.2"] networks: diff --git a/image/lmn-activity-logd b/image/lmn-activity-logd index d6ff155..8d0b0d7 100755 --- a/image/lmn-activity-logd +++ b/image/lmn-activity-logd @@ -66,8 +66,10 @@ class Spool: name = f".part-{int(now):010d}-{self.token}-{self.seq:06d}" path = os.path.join(self.directory, name) try: - # 0640: the directory's set-group-id bit gives the file the control plane's group. - self.fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_APPEND, 0o640) + # 0644: the control plane (another user) reads it; nobody else on the host reaches + # the spool (its parent is 0750). No set-group-id directory: refused under the + # control plane's RestrictSUIDSGID=yes. + self.fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_APPEND, 0o644) except OSError as exc: self._problem(f"cannot create a file in {self.directory}: {exc.strerror}") return False @@ -155,7 +157,7 @@ def main(argv: list[str]) -> int: log("usage: lmn-activity-logd ") return 1 host, _, port = argv[1].rpartition(":") - os.umask(0o027) + os.umask(0o022) spool = Spool(argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, RECV_BUFFER) diff --git a/packaging/systemd/linuxmuster-squid-activity.service b/packaging/systemd/linuxmuster-squid-activity.service index a2d4e97..59ee6d6 100644 --- a/packaging/systemd/linuxmuster-squid-activity.service +++ b/packaging/systemd/linuxmuster-squid-activity.service @@ -14,6 +14,9 @@ Environment=LMNSQUID_CONFIG=/etc/linuxmuster-squid/config.yml MemoryMax=256M Nice=5 TimeoutStartSec=15min +# Every 30 s: no journal lines for idle runs, also not systemd's own "Starting/Finished" (info); +# the collector writes the runs with work as notice and errors as err. +LogLevelMax=notice NoNewPrivileges=yes ProtectSystem=strict diff --git a/scripts/tests/e2e_kerberos.sh b/scripts/tests/e2e_kerberos.sh index 608421c..6ee8ff9 100755 --- a/scripts/tests/e2e_kerberos.sh +++ b/scripts/tests/e2e_kerberos.sh @@ -43,7 +43,7 @@ chmod 644 "$FILTER_DIR/lists/"*.domains filter_json '"categories": ["porn", "ai", "ads", "own_e2e"], "fail_closed": ["porn"]' # Activity log spool of squid-filter (ADR-023), made as the control plane makes it. mkdir -p "$FILTER_DIR/activity" -chmod 3733 "$FILTER_DIR/activity" +chmod 1733 "$FILTER_DIR/activity" # squid-old: the data-plane image 7.3.7 pins, the last one without ADR-016 (lists-sync.sh, # noauth). A constant on purpose, not DEFAULT_IMAGE: it stands for what installed instances run From 78cae3067a11eb4e6bb2d94b6d3a0a8375a006f2 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 14:12:34 +0100 Subject: [PATCH 14/45] feat(webui): activity view backend for the student-centred page; settings and audit in the management - Menu: "Internetnutzung" (msgid "Internet use") under upstream's category Klassenzimmer (category:class, weight 30); the management stays under Software. Category and name are kept in one place (main.py). - /scope lists classes and projects with counts only; members per group on request (GET /group///members), teachers of a class only for administrators and only on request (E3); a teacher never sees teachers. - GET /people?q=: up to 10 people of the scope by login or name, from the AD only (no proxy, no activity data). - POST /query/day (one student's day merged over the proxies, ETags passed through: unchanged answers are not sent again, the proxies audit every one), /query/blocked, /query/timeline with a domain (drill-down), /query/domains with hide_background, /query/users without the domain count by default. - Performance: the computed scope is cached 10 s, a project's member groups 300 s, every proxy's light overview 60 s (dropped on a settings change); never activity data. All proxies are asked in parallel from one pool with an overall deadline of 5 s (2 s connect, 5 s read); answers carry timing per proxy. - Failures are typed (unreachable, timeout, too_old, auth, tls, limit with the proxy's code and words, error) instead of "not reachable"; an export is refused as a whole when a proxy cannot deliver its part or truncated it (lab A2). - Every request of the view is written to the system log (tag lmn-squid-activity, authpriv), also refused ones and those that needed no proxy (lab A4). - E1: the activity settings and the proxies' audit log are endpoints of the management (global administrators): GET //activity, PUT //instances//activity, GET //activity/audit (paged). --- webui/lmn_squid/activity_scope.py | 21 +- webui/lmn_squid/activity_views.py | 686 +++++++++++++------ webui/lmn_squid/client.py | 18 +- webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 3 + webui/lmn_squid/main.py | 29 +- webui/lmn_squid/views.py | 83 +++ webui/tests/test_activity_views.py | 293 +++++++- 7 files changed, 880 insertions(+), 253 deletions(-) diff --git a/webui/lmn_squid/activity_scope.py b/webui/lmn_squid/activity_scope.py index db16a0b..ad22ab6 100644 --- a/webui/lmn_squid/activity_scope.py +++ b/webui/lmn_squid/activity_scope.py @@ -37,6 +37,8 @@ class or project the teacher is a member or admin of (sophomorix writes members ROLE_GROUP_RE = re.compile(r"^(?:[a-z0-9-]+-)?(?:students|teachers|parents)$") CACHE_SECONDS = 60.0 PERSON_CACHE_SECONDS = 10.0 +SCOPE_CACHE_SECONDS = 10.0 +PROJECT_CACHE_SECONDS = 300.0 class ScopeDenied(Exception): @@ -80,6 +82,7 @@ class Scope: users: set[str] | None # None: everyone groups: list[Group] names: dict[str, str] # user -> display name of the visible users + classes_of: dict[str, list[str]] = field(default_factory=dict) # user -> groups in scope @property def can_export(self) -> bool: @@ -179,7 +182,7 @@ def _members( wanted |= set( CACHE.get( ("project", school, name), - CACHE_SECONDS, + PROJECT_CACHE_SECONDS, lambda: directory.project_groups(school, name), ) ) @@ -254,7 +257,21 @@ def scope_for(identity: str | None, directory: Directory, school: str | None = N for u in users if _str(u["sAMAccountName"]).lower() in visible } - return Scope(identity, role, target, visible, groups, names) + classes_of: dict[str, list[str]] = {} + for g in groups: + for m in g.members: + classes_of.setdefault(m["user"], []).append(g.name) + return Scope(identity, role, target, visible, groups, names, classes_of) + + +def cached_scope(identity: str | None, directory: Directory, school: str | None = None) -> Scope: + """:func:`scope_for`, computed at most every 10 s per person and school (no activity data; + a refusal is never cached).""" + return CACHE.get( + ("scope", identity, school), + SCOPE_CACHE_SECONDS, + lambda: scope_for(identity, directory, school), + ) class LdapDirectory: diff --git a/webui/lmn_squid/activity_views.py b/webui/lmn_squid/activity_views.py index 5fab8b3..df29d72 100644 --- a/webui/lmn_squid/activity_views.py +++ b/webui/lmn_squid/activity_views.py @@ -1,59 +1,93 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later -"""HTTP endpoints of the activity log view ("Internetprotokoll", ADR-023) under -``/api/lmn/squid-activity/``. - -Every endpoint carries ``@authorize('lm:squid:activity')`` (true for globaladministrator, -schooladministrator and teacher in permissions.yml) and computes the person's scope from the AD -on the server (:mod:`activity_scope`): a teacher's requests carry exactly the students of their -classes and projects as the ``users`` list to the proxies, which filter on it; a user or group -outside the scope is 403 before any proxy is asked. Students and other roles get 403 even if a -permission was granted by hand. Export is for school and global administrators, the settings -and the audit log for global administrators. State-changing requests (all POST/PUT) pass the -same-origin check of the management view. Every proxy whose instances belong to the school is -asked in parallel; one that does not answer is named and does not block the others. +"""HTTP endpoints of the activity view ("Internetnutzung", ADR-023) under +``/api/lmn/squid-activity/``: a pure view for teachers, school and global administrators. + +Every endpoint carries ``@authorize('lm:squid:activity')`` and computes the person's scope from +the AD on the server (:mod:`activity_scope`): a teacher's requests carry exactly the students of +their classes and projects as the ``users`` list to the proxies, which filter on it and audit the +query before reading; a user or group outside the scope is 403 before any proxy is asked. +Students and other roles get 403 also with the permission granted by hand. Export is for school +and global administrators. The settings and the proxies' audit log are in the management page +(global administrators, ``views.py``, ADR-023 addendum E1). + +The plugin writes its own audit line for every request of this view, also for refused ones and +for those that needed no proxy (an empty scope), to the system log with the tag +``lmn-squid-activity`` (facility authpriv: ``journalctl -t lmn-squid-activity``). + +Performance (spec ``ux-ueberarbeitung.md`` §4): the scope and the proxies' instance lists are +cached briefly (never activity data, which must be audited on the proxy at every read); all +proxies are asked in parallel with an overall deadline of 5 s; a proxy that does not answer in +time, refuses or reports a limit is named with the kind of failure, the others' data are shown. """ from __future__ import annotations import logging +import syslog +import threading import time from concurrent import futures from functools import wraps from typing import Any, Callable from aj.api.endpoint import EndpointReturn, endpoint -from aj.api.http import HttpPlugin, get, post, put +from aj.api.http import HttpPlugin, get, post from aj.auth import authorize from jadi import component from .activity_scope import ( SCHOOL_RE, - DirectoryError, USER_RE, + DirectoryError, LdapDirectory, Scope, ScopeDenied, - scope_for, + cached_scope, ) -from .client import LONG, SHORT, ControlPlaneClient, ControlPlaneError, instance_path +from .client import LONG, NOT_MODIFIED, ControlPlaneClient, ControlPlaneError from .connections import CONFIG_PATH, Connection, ConnectionFileError, ConnectionStore from .views import STATE_CHANGING, _body, check_same_origin -audit = logging.getLogger("lmn_squid.audit") +logger = logging.getLogger("lmn_squid.activity") PERM_ACTIVITY = "lm:squid:activity" PREFIX = r"/api/lmn/squid-activity" MAX_RANGE = 366 * 86400 WORKERS = 8 -# what the browser may choose (the proxy enforces its own limits as well) -RESOLUTIONS = ("hour", "minute") +DEADLINE = 5.0 # all proxies of one view request, seconds +VIEW_TIMEOUTS = (2.0, 5.0) # connect, read per proxy request +INSTANCES_TTL = 60.0 +PEOPLE_MAX = 10 SORTS = ("requests", "blocked", "last", "name", "bytes") +_POOL = futures.ThreadPoolExecutor(max_workers=WORKERS, thread_name_prefix="lmn-squid-activity") +# connection name -> (fetched at, light overview of GET /v1/activity?usage=false) +_INSTANCES: dict[str, tuple[float, Any]] = {} +_INSTANCES_LOCK = threading.Lock() + + +def forget_instances(conn: str | None = None) -> None: + """Drop the cached instance list (after a settings change in the management page).""" + with _INSTANCES_LOCK: + if conn is None: + _INSTANCES.clear() + else: + _INSTANCES.pop(conn, None) + + +def audit_line(text: str) -> None: + """One line in the system log (authpriv, tag lmn-squid-activity); replaceable in tests.""" + syslog.openlog("lmn-squid-activity", syslog.LOG_PID, syslog.LOG_AUTHPRIV) + syslog.syslog(syslog.LOG_INFO, text) + + +def _identity(handler: Any) -> str: + return str(getattr(handler.context, "identity", None) or "-") def activity_endpoint(fx: Callable[..., Any]) -> Callable[..., Any]: - """Same-origin check of state-changing requests, scope errors as 403, plugin errors as - readable answers (never a traceback).""" + """Same-origin check of state-changing requests, scope errors as 403 (audited), AD and + plugin errors as readable answers (never a traceback).""" @wraps(fx) def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: @@ -62,6 +96,7 @@ def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: try: return fx(self, http_context, **kwargs) except ScopeDenied as exc: + self.audit(f"user={_identity(self)} refused path={http_context.path} reason={exc}") raise EndpointReturn(403, {"error": "scope", "message": str(exc)}) from None except DirectoryError as exc: raise EndpointReturn(503, {"error": "directory", "message": str(exc)}) from None @@ -102,6 +137,32 @@ def _school(value: Any) -> str | None: return value +def _user(value: Any) -> str: + user = str(value or "").lower() + if not USER_RE.match(user): + raise EndpointReturn(422, {"error": "invalid", "field": "user", "message": "user"}) + return user + + +def _failure(conn: Connection, exc: Exception) -> dict[str, Any]: + """A failed proxy as the page shows it: the kind of failure and the proxy's own words.""" + name = conn.display_name or conn.name + if isinstance(exc, ControlPlaneError): + detail = exc.detail if isinstance(exc.detail, dict) else {} + if exc.kind == "http" and exc.status == 422 and detail.get("code"): + return { + "connection": name, + "kind": "limit", + "code": detail.get("code"), + "message": str(detail.get("message") or exc.message), + } + if exc.kind == "http" and isinstance(detail, dict) and detail.get("message"): + return {"connection": name, "kind": "error", "message": str(detail["message"])} + kind = exc.kind if exc.kind != "http" else "error" + return {"connection": name, "kind": kind, "message": exc.message} + return {"connection": name, "kind": "error", "message": str(exc)[:300]} + + @component(HttpPlugin) class ActivityHandler(HttpPlugin): # Replaceable in tests (a fake AD with the same shape). @@ -112,45 +173,78 @@ def __init__(self, context: Any) -> None: self.store = ConnectionStore(CONFIG_PATH) # ------------------------------------------------------------------ helpers - def _scope(self, school: str | None = None) -> Scope: - return scope_for(getattr(self.context, "identity", None), self.directory_factory(), school) + def audit(self, text: str) -> None: + try: + audit_line(text) + except OSError as exc: # no /dev/log (tests, containers): the WebUI's own log + logger.warning("activity audit line not written (%s): %s", exc, text) - def _require_global(self, scope: Scope) -> None: - if not scope.is_global: - raise ScopeDenied("global administrators only") + def _scope(self, school: str | None = None) -> Scope: + return cached_scope( + getattr(self.context, "identity", None), self.directory_factory(), school + ) def _audit_info(self, scope: Scope, label: str) -> dict[str, Any]: return {"actor": scope.user, "role": scope.role, "scope": label[:256]} - def _log(self, scope: Scope, what: str, label: str) -> None: - audit.info("user=%s role=%s activity %s scope=%s", scope.user, scope.role, what, label) + def _log(self, scope: Scope, what: str, label: str, result: str = "asked") -> None: + self.audit( + f"user={scope.user} role={scope.role} school={scope.school or '-'} {what} " + f"scope={label} result={result}" + ) def _fan_out( - self, call: Callable[[Connection, ControlPlaneClient], Any] - ) -> tuple[list[tuple[Connection, Any]], list[dict[str, str]]]: - """``call`` on every connection in parallel: (results, connections that failed).""" + self, call: Callable[[Connection, ControlPlaneClient], Any], deadline: float = DEADLINE + ) -> tuple[list[tuple[Connection, Any, float]], list[dict[str, Any]]]: + """``call`` on every connection in parallel within ``deadline``: (results with their + time in ms, failures with their kind).""" conns = list(self.store.load().values()) - results: list[tuple[Connection, Any]] = [] - failed: list[dict[str, str]] = [] + results: list[tuple[Connection, Any, float]] = [] + failed: list[dict[str, Any]] = [] if not conns: return results, failed - with futures.ThreadPoolExecutor(max_workers=min(WORKERS, len(conns))) as pool: - jobs = {pool.submit(call, c, ControlPlaneClient(c)): c for c in conns} - for job in futures.as_completed(jobs): - conn = jobs[job] - try: - results.append((conn, job.result())) - except ControlPlaneError as exc: - failed.append( - {"connection": conn.display_name or conn.name, "message": exc.message} - ) - except Exception as exc: # noqa: BLE001 - one proxy never blocks the view - failed.append( - {"connection": conn.display_name or conn.name, "message": str(exc)[:300]} - ) + + def timed(conn: Connection) -> tuple[Any, float]: + started = time.monotonic() + value = call(conn, ControlPlaneClient(conn)) + return value, (time.monotonic() - started) * 1000 + + jobs = {_POOL.submit(timed, c): c for c in conns} + done, pending = futures.wait(jobs, timeout=deadline) + for job in done: + conn = jobs[job] + try: + value, ms = job.result() + results.append((conn, value, ms)) + except Exception as exc: # noqa: BLE001 - one proxy never blocks the view + failed.append(_failure(conn, exc)) + for job in pending: + conn = jobs[job] + failed.append( + { + "connection": conn.display_name or conn.name, + "kind": "timeout", + "message": f"no answer within {deadline:.0f} s", + } + ) results.sort(key=lambda item: item[0].name) + failed.sort(key=lambda f: f["connection"]) return results, failed + @staticmethod + def _overview(conn: Connection, client: ControlPlaneClient) -> Any: + now = time.monotonic() + with _INSTANCES_LOCK: + hit = _INSTANCES.get(conn.name) + if hit is not None and now - hit[0] < INSTANCES_TTL: + return hit[1] + data = client.request( + "GET", "/v1/activity", query={"usage": "false"}, timeouts=VIEW_TIMEOUTS + ) + with _INSTANCES_LOCK: + _INSTANCES[conn.name] = (now, data) + return data + @staticmethod def _instances(overview: Any, scope: Scope) -> list[str]: """The instances of one proxy that hold activity data of the scope's school.""" @@ -158,8 +252,7 @@ def _instances(overview: Any, scope: Scope) -> list[str]: for inst in (overview or {}).get("instances") or []: if not isinstance(inst, dict): continue - usage = inst.get("usage") or {} - if not (inst.get("enabled") or usage.get("days")): + if not (inst.get("enabled") or inst.get("days")): continue if scope.school is not None and inst.get("school") != scope.school: continue @@ -171,32 +264,74 @@ def _query( scope: Scope, path: str, body: dict[str, Any], - timeouts: tuple[float, float] = SHORT, + timeouts: tuple[float, float] = VIEW_TIMEOUTS, text: bool = False, - ) -> tuple[list[Any], list[dict[str, str]]]: - """POST ``body`` to ``path`` of every proxy with matching instances.""" - - def call(_conn: Connection, client: ControlPlaneClient) -> Any: - names = self._instances(client.request("GET", "/v1/activity"), scope) + etags: dict[str, str] | None = None, + deadline: float = DEADLINE, + ) -> tuple[list[tuple[Connection, Any]], list[dict[str, Any]], dict[str, Any]]: + """POST ``body`` to ``path`` of every proxy with matching instances: (answers, failures, + timing). With ``etags`` (connection -> ETag) a proxy may answer NOT_MODIFIED.""" + started = time.monotonic() + + def call(conn: Connection, client: ControlPlaneClient) -> Any: + names = self._instances(self._overview(conn, client), scope) if not names: return None return client.request( - "POST", path, {**body, "instances": names}, timeouts=timeouts, text=text + "POST", + path, + {**body, "instances": names}, + timeouts=timeouts, + text=text, + etag=(etags or {}).get(conn.name), ) - results, failed = self._fan_out(call) - return [r for _c, r in results if r is not None], failed + results, failed = self._fan_out(call, deadline) + timing = { + "total_ms": round((time.monotonic() - started) * 1000), + "proxies": {c.name: round(ms) for c, _r, ms in results}, + } + return [(c, r) for c, r, _ms in results if r is not None], failed, timing + + def _users_for(self, scope: Scope, body: dict[str, Any]) -> tuple[list[str] | None, str, Any]: + """The users list sent to the proxies, a label for the audit, the group (or None). - def _users_for(self, scope: Scope, body: dict[str, Any]) -> tuple[list[str] | None, str]: - """The users list sent to the proxies and a label for the audit log.""" + A class or project of a school or global administrator lists its teachers only on + request (``teachers``: true, decision E3); a teacher's scope never holds teachers. + """ group = body.get("group") if isinstance(group, dict) and group.get("name"): g = scope.group(str(group.get("kind") or ""), str(group.get("name"))) - members = [m["user"] for m in g.members] - return scope.restrict(members), f"{g.kind} {g.name}" + with_teachers = body.get("teachers") is True and scope.role != "teacher" + members = [m["user"] for m in g.members if with_teachers or m.get("role") != "teacher"] + return scope.restrict(members), f"{g.kind} {g.name}", g if scope.users is None: - return None, f"school {scope.school}" if scope.school else "all schools" - return sorted(scope.users), f"all visible users ({scope.school})" + return None, f"school {scope.school}" if scope.school else "all schools", None + return sorted(scope.users), f"all visible users ({scope.school})", None + + def _empty(self, scope: Scope, what: str, label: str, **extra: Any) -> dict[str, Any]: + self._log(scope, what, label, "empty scope, no proxy asked") + return {"unreachable": [], "timing": {"total_ms": 0, "proxies": {}}, **extra} + + def _labels(self) -> dict[str, Any]: + """Category labels, background categories and lesson hours from the cached overviews.""" + labels: dict[str, str] = {} + background: set[str] = set() + lesson: list[str] | None = None + timezone: str | None = None + with _INSTANCES_LOCK: + cached = [v for _t, v in _INSTANCES.values()] + for overview in cached: + labels.update((overview or {}).get("category_labels") or {}) + background |= set((overview or {}).get("background_categories") or []) + lesson = lesson or (overview or {}).get("lesson_hours") + timezone = timezone or (overview or {}).get("timezone") + return { + "category_labels": labels, + "background_categories": sorted(background), + "lesson_hours": lesson or ["07:45", "16:00"], + "timezone": timezone, + } # ------------------------------------------------------------------ scope @get(PREFIX + r"/scope") @@ -204,61 +339,113 @@ def _users_for(self, scope: Scope, body: dict[str, Any]) -> tuple[list[str] | No @endpoint(api=True) @activity_endpoint def handle_scope(self, http_context: Any) -> Any: - """What the person may look at: role, school, classes and projects with members.""" + """What the person may look at: role, school and the classes and projects (counts only; + members per group on request). Asks the proxies only for their (cached) overview.""" + started = time.monotonic() school = _school((http_context.query or {}).get("school")) scope = self._scope(school) - schools: list[str] = [] - if scope.is_global: - results, _failed = self._fan_out( - lambda _c, client: client.request("GET", "/v1/activity") - ) - schools = sorted( - { - str(i.get("school")) - for _c, r in results - for i in (r or {}).get("instances") or [] - if isinstance(i, dict) and i.get("school") - } - ) + results, failed = self._fan_out(self._overview) + schools = sorted( + { + str(i.get("school")) + for _c, r, _ms in results + for i in (r or {}).get("instances") or [] + if isinstance(i, dict) and i.get("school") + } + ) return { "user": scope.user, "role": scope.role, "school": scope.school, - "schools": schools, + "schools": schools if scope.is_global else [], "can_export": scope.can_export, "is_global": scope.is_global, - "groups": [{**g.brief(), "members": g.members} for g in scope.groups], + "groups": [ + { + **g.brief(), + "students": sum(1 for m in g.members if m.get("role") != "teacher"), + } + for g in scope.groups + ], + **self._labels(), + "unreachable": failed, + "timing": {"total_ms": round((time.monotonic() - started) * 1000)}, } + @get(PREFIX + r"/group/(?Pclass|project)/(?P[^/]+)/members") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_members(self, http_context: Any, kind: str = "", name: str = "") -> Any: + """The visible members of one class or project (teachers only for administrators and + only with ``teachers=1``). From the AD only: no proxy, no activity data.""" + query = http_context.query or {} + scope = self._scope(_school(query.get("school"))) + g = scope.group(kind, name) + with_teachers = str(query.get("teachers") or "") == "1" and scope.role != "teacher" + members = [m for m in g.members if with_teachers or m.get("role") != "teacher"] + return { + "kind": g.kind, + "name": g.name, + "members": members, + "teachers_hidden": sum(1 for m in g.members if m.get("role") == "teacher") + if not with_teachers + else 0, + } + + @get(PREFIX + r"/people") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_people(self, http_context: Any) -> Any: + """Up to 10 people of the scope whose login or name contains ``q`` (at least 2 + characters). From the AD only: no proxy, no activity data, no audit needed.""" + query = http_context.query or {} + q = str(query.get("q") or "").strip().lower() + if len(q) < 2 or len(q) > 64: + return {"people": []} + scope = self._scope(_school(query.get("school"))) + found = [] + for user, display in sorted(scope.names.items(), key=lambda kv: kv[1].lower()): + if q in user or q in display.lower(): + found.append( + {"user": user, "display": display, "classes": scope.classes_of.get(user, [])} + ) + if len(found) >= PEOPLE_MAX: + break + return {"people": found} + # ---------------------------------------------------------------- queries @post(PREFIX + r"/query/users") @authorize(PERM_ACTIVITY) @endpoint(api=True) @activity_endpoint def handle_users(self, http_context: Any) -> Any: - """Per user: requests, blocked, domains, last seen, active now (merged over proxies).""" + """Per user of a class (or the scope): requests, blocked, last seen, active now; the + distinct domains only with ``with_domains`` (expensive, off by default).""" body = _body(http_context) scope = self._scope(_school(body.get("school"))) since, until = _range(body) - users, label = self._users_for(scope, body) + users, label, _g = self._users_for(scope, body) sort = body.get("sort") if body.get("sort") in SORTS else "requests" - self._log(scope, "users", label) if users == []: - return {"users": [], "unreachable": []} - results, failed = self._query( + return self._empty(scope, "users", label, users=[]) + self._log(scope, "users", label) + results, failed, timing = self._query( scope, "/v1/activity/users", { "since": since, "until": until, "users": users, - "limit": 1000, + "limit": max(1, min(len(users) if users else 1000, 1000)), "sort": sort, + "with_domains": body.get("with_domains") is True, "audit": self._audit_info(scope, label), }, ) merged: dict[str, dict[str, Any]] = {} - for result in results: + for _conn, result in results: for row in result.get("users") or []: cur = merged.get(row["user"]) if cur is None: @@ -272,38 +459,88 @@ def handle_users(self, http_context: Any) -> Any: cur["active_now"] = bool(cur.get("active_now") or row.get("active_now")) for name, row in merged.items(): row["display"] = scope.names.get(name, name) - return {"users": list(merged.values()), "unreachable": failed} + return {"users": list(merged.values()), "unreachable": failed, "timing": timing} + + @post(PREFIX + r"/query/day") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_day(self, http_context: Any) -> Any: + """One student's day (the student page): minutes and domains, merged over the proxies. + + ``etags`` (connection -> ETag of the browser's last answer): when no proxy has anything + new the answer is ``{"not_modified": true}``; the proxies audit every one of these. + """ + body = _body(http_context) + scope = self._scope(_school(body.get("school"))) + user = _user(body.get("user")) + scope.check_user(user) + day = str(body.get("day") or "") + if len(day) != 10: + raise EndpointReturn(422, {"error": "invalid", "field": "day", "message": "day"}) + payload: dict[str, Any] = { + "user": user, + "day": day, + "users": None if scope.users is None else [user], + "audit": self._audit_info(scope, f"user {user}"), + } + for key in ("start", "end", "since_minute"): + if body.get(key) not in (None, ""): + payload[key] = _int(body, key) + etags = body.get("etags") if isinstance(body.get("etags"), dict) else None + self._log(scope, "day", f"user {user} {day}") + results, failed, timing = self._query(scope, "/v1/activity/day", payload, etags=etags) + if etags and results and all(r is NOT_MODIFIED for _c, r in results): + return {"not_modified": True, "unreachable": failed, "timing": timing} + if any(r is NOT_MODIFIED for _c, r in results): + # some proxies have news: everything again, without ETags + results, failed, timing = self._query(scope, "/v1/activity/day", payload) + return { + **merge_days([r for _c, r in results]), + "user": user, + "display": scope.names.get(user, user), + "classes": scope.classes_of.get(user, []), + "day": day, + "etags": {c.name: r.get("_etag") for c, r in results if isinstance(r, dict)}, + "unreachable": failed, + "timing": timing, + } @post(PREFIX + r"/query/timeline") @authorize(PERM_ACTIVITY) @endpoint(api=True) @activity_endpoint def handle_timeline(self, http_context: Any) -> Any: - """One user's activity per hour (heat map) or per minute and domain.""" + """One user's activity per hour (heat map) or per minute, optionally of one domain.""" body = _body(http_context) scope = self._scope(_school(body.get("school"))) since, until = _range(body) - user = str(body.get("user") or "").lower() - if not USER_RE.match(user): - raise EndpointReturn(422, {"error": "invalid", "field": "user", "message": "user"}) + user = _user(body.get("user")) scope.check_user(user) - resolution = body.get("resolution") if body.get("resolution") in RESOLUTIONS else "hour" - self._log(scope, f"timeline {resolution}", f"user {user}") - results, failed = self._query( - scope, - "/v1/activity/timeline", - { - "since": since, - "until": until, - "user": user, - "users": None if scope.users is None else [user], - "resolution": resolution, - "limit": 5000 if resolution == "minute" else 1000, - "audit": self._audit_info(scope, f"user {user}"), - }, - ) + resolution = "minute" if body.get("resolution") == "minute" else "hour" + domain = str(body.get("domain") or "").strip().lower() or None + if domain is not None and (len(domain) > 253 or any(c.isspace() for c in domain)): + raise EndpointReturn(422, {"error": "invalid", "field": "domain", "message": "domain"}) + label = f"user {user}" + (f" domain {domain}" if domain else "") + self._log(scope, f"timeline {resolution}", label) + payload = { + "since": since, + "until": until, + "user": user, + "users": None if scope.users is None else [user], + "resolution": resolution, + "limit": 5000 if resolution == "minute" else 1000, + "domain": domain, + "audit": self._audit_info(scope, label), + } + etags = body.get("etags") if isinstance(body.get("etags"), dict) else None + results, failed, timing = self._query(scope, "/v1/activity/timeline", payload, etags=etags) + if etags and results and all(r is NOT_MODIFIED for _c, r in results): + return {"not_modified": True, "unreachable": failed, "timing": timing} + if any(r is NOT_MODIFIED for _c, r in results): + results, failed, timing = self._query(scope, "/v1/activity/timeline", payload) rows: dict[tuple[Any, ...], dict[str, Any]] = {} - for result in results: + for _conn, result in results: for row in result.get("rows") or []: key = (row.get("t"), row.get("domain")) cur = rows.get(key) @@ -318,7 +555,9 @@ def handle_timeline(self, http_context: Any) -> Any: "display": scope.names.get(user, user), "resolution": resolution, "rows": ordered, + "etags": {c.name: r.get("_etag") for c, r in results if isinstance(r, dict)}, "unreachable": failed, + "timing": timing, } @post(PREFIX + r"/query/domains") @@ -326,35 +565,34 @@ def handle_timeline(self, http_context: Any) -> Any: @endpoint(api=True) @activity_endpoint def handle_domains(self, http_context: Any) -> Any: - """Top domains of a group, a user or the whole scope.""" + """Top domains of a group or of one user (background services hidden on request).""" body = _body(http_context) scope = self._scope(_school(body.get("school"))) since, until = _range(body) - user = str(body.get("user") or "").lower() - if user: - if not USER_RE.match(user): - raise EndpointReturn(422, {"error": "invalid", "field": "user", "message": "user"}) + if body.get("user"): + user = _user(body.get("user")) scope.check_user(user) users: list[str] | None = [user] label = f"user {user}" else: - users, label = self._users_for(scope, body) - self._log(scope, "domains", label) + users, label, _g = self._users_for(scope, body) if users == []: - return {"domains": [], "unreachable": []} - results, failed = self._query( + return self._empty(scope, "domains", label, domains=[]) + self._log(scope, "domains", label) + results, failed, timing = self._query( scope, "/v1/activity/domains", { "since": since, "until": until, "users": users, - "limit": 100, + "limit": 50, + "hide_background": body.get("hide_background") is True, "audit": self._audit_info(scope, label), }, ) merged: dict[str, dict[str, Any]] = {} - for result in results: + for _conn, result in results: for row in result.get("domains") or []: cur = merged.get(row["domain"]) if cur is None: @@ -364,25 +602,64 @@ def handle_domains(self, http_context: Any) -> Any: cur[k] = int(cur.get(k) or 0) + int(row.get(k) or 0) cur["category"] = cur.get("category") or row.get("category") ordered = sorted(merged.values(), key=lambda r: (-int(r["requests"]), r["domain"])) - return {"domains": ordered[:100], "unreachable": failed} + return {"domains": ordered[:50], "unreachable": failed, "timing": timing} + + @post(PREFIX + r"/query/blocked") + @authorize(PERM_ACTIVITY) + @endpoint(api=True) + @activity_endpoint + def handle_blocked(self, http_context: Any) -> Any: + """Blocked attempts of a group per domain: how often, by how many, the category.""" + body = _body(http_context) + scope = self._scope(_school(body.get("school"))) + since, until = _range(body) + users, label, _g = self._users_for(scope, body) + if users == []: + return self._empty(scope, "blocked", label, domains=[]) + self._log(scope, "blocked", label) + results, failed, timing = self._query( + scope, + "/v1/activity/blocked", + { + "since": since, + "until": until, + "users": users, + "limit": 100, + "audit": self._audit_info(scope, label), + }, + ) + merged: dict[str, dict[str, Any]] = {} + for _conn, result in results: + for row in result.get("domains") or []: + cur = merged.get(row["domain"]) + if cur is None: + merged[row["domain"]] = dict(row) + continue + cur["blocked"] = int(cur["blocked"]) + int(row["blocked"]) + cur["users"] = int(cur["users"]) + int(row["users"]) + cur["category"] = cur.get("category") or row.get("category") + ordered = sorted( + merged.values(), key=lambda r: (-int(r["users"]), -int(r["blocked"]), r["domain"]) + ) + return {"domains": ordered, "unreachable": failed, "timing": timing} @post(PREFIX + r"/query/search") @authorize(PERM_ACTIVITY) @endpoint(api=True) @activity_endpoint def handle_search(self, http_context: Any) -> Any: - """Who of the scope was on a domain (or a subdomain of it).""" + """Who of the group (or the scope) was on a domain (or a subdomain of it).""" body = _body(http_context) scope = self._scope(_school(body.get("school"))) since, until = _range(body) domain = str(body.get("domain") or "").strip().lower() if not domain or len(domain) > 253 or any(c.isspace() for c in domain): raise EndpointReturn(422, {"error": "invalid", "field": "domain", "message": "domain"}) - users, label = self._users_for(scope, body) - self._log(scope, "search", f"{label} domain {domain}") + users, label, _g = self._users_for(scope, body) if users == []: - return {"users": [], "unreachable": []} - results, failed = self._query( + return self._empty(scope, "search", f"{label} domain {domain}", users=[]) + self._log(scope, "search", f"{label} domain {domain}") + results, failed, timing = self._query( scope, "/v1/activity/search", { @@ -395,7 +672,7 @@ def handle_search(self, http_context: Any) -> Any: }, ) merged: dict[str, dict[str, Any]] = {} - for result in results: + for _conn, result in results: for row in result.get("users") or []: cur = merged.get(row["user"]) if cur is None: @@ -409,24 +686,26 @@ def handle_search(self, http_context: Any) -> Any: for name, row in merged.items(): row["display"] = scope.names.get(name, name) ordered = sorted(merged.values(), key=lambda r: (-int(r["requests"]), r["user"])) - return {"domain": domain, "users": ordered, "unreachable": failed} + return {"domain": domain, "users": ordered, "unreachable": failed, "timing": timing} @post(PREFIX + r"/export") @authorize(PERM_ACTIVITY) @endpoint(api=True) @activity_endpoint def handle_export(self, http_context: Any) -> Any: - """CSV per minute, user and domain: school and global administrators only.""" + """CSV per minute, user and domain: school and global administrators only. Refused as a + whole when a proxy cannot deliver its part (never a CSV with rows missing).""" body = _body(http_context) scope = self._scope(_school(body.get("school"))) if not scope.can_export: raise ScopeDenied("export is for school and global administrators") since, until = _range(body) - users, label = self._users_for(scope, body) - self._log(scope, "export", label) + users, label, _g = self._users_for(scope, body) + header = "time,user,domain,requests,bytes,blocked,category\n" if users == []: - return {"csv": "time,user,domain,requests,bytes,blocked,category\n", "unreachable": []} - results, failed = self._query( + return {**self._empty(scope, "export", label), "csv": header} + self._log(scope, "export", label) + results, failed, timing = self._query( scope, "/v1/activity/export", { @@ -437,96 +716,61 @@ def handle_export(self, http_context: Any) -> Any: }, timeouts=LONG, text=True, + deadline=LONG[1], ) - header = "time,user,domain,requests,bytes,blocked,category\n" + if failed: + self._log(scope, "export", label, "refused: a proxy failed") + raise EndpointReturn( + 409, {"error": "export_incomplete", "message": "", "unreachable": failed} + ) parts = [header] - for text in results: + truncated = False + for _conn, text in results: body_text = str(text or "") + truncated = truncated or "# truncated" in body_text or "# stopped" in body_text parts.append(body_text[len(header) :] if body_text.startswith(header) else body_text) - return {"csv": "".join(parts), "unreachable": failed} - - # ------------------------------------------------- global administrators - @get(PREFIX + r"/audit") - @authorize(PERM_ACTIVITY) - @endpoint(api=True) - @activity_endpoint - def handle_audit(self, http_context: Any) -> Any: - """Who read activity data, from every proxy (newest first).""" - scope = self._scope() - self._require_global(scope) - query = http_context.query or {} - try: - days = max(1, min(int(query.get("days") or 7), 3650)) - except ValueError: - days = 7 - actor = str(query.get("actor") or "") or None - now = int(time.time()) - params = {"since": now - days * 86400, "until": now + 1, "limit": 1000, "actor": actor} - results, failed = self._fan_out( - lambda _c, client: client.request("GET", "/v1/activity/audit", query=params) - ) - entries = [] - for conn, result in results: - for entry in (result or {}).get("entries") or []: - entries.append({**entry, "connection": conn.display_name or conn.name}) - entries.sort(key=lambda e: -int(e.get("ts") or 0)) - return {"entries": entries[:1000], "unreachable": failed} - - @get(PREFIX + r"/settings") - @authorize(PERM_ACTIVITY) - @endpoint(api=True) - @activity_endpoint - def handle_settings(self, http_context: Any) -> Any: - """The activity log settings of every instance on every proxy.""" - scope = self._scope() - self._require_global(scope) - results, failed = self._fan_out(lambda _c, client: client.request("GET", "/v1/activity")) - servers = [ - { - "connection": conn.name, - "display_name": conn.display_name or conn.name, - "timezone": (r or {}).get("timezone"), - "instances": (r or {}).get("instances") or [], - } - for conn, r in results - ] - return {"servers": servers, "unreachable": failed} - - @put(PREFIX + r"/settings/(?P[^/]+)/(?P[^/]+)") - @authorize(PERM_ACTIVITY) - @endpoint(api=True) - @activity_endpoint - def handle_put_settings(self, http_context: Any, conn: str = "", name: str = "") -> Any: - """Switch the log of one instance on/off, set its retention; switching on needs the - confirmed privacy notice (stored on the proxy with who and when).""" - scope = self._scope() - self._require_global(scope) - found = self.store.get(conn) - if found is None: - raise EndpointReturn(404, {"error": "unknown_connection", "message": conn}) - body = _body(http_context) - enabled = body.get("enabled") - if not isinstance(enabled, bool): - raise EndpointReturn(422, {"error": "invalid", "field": "enabled", "message": "bool"}) - payload: dict[str, Any] = {"enabled": enabled, "actor": scope.user} - if body.get("retention_days") not in (None, ""): - payload["retention_days"] = _int(body, "retention_days") - if enabled: - if body.get("privacy_confirmed") is True: - payload["ack_by"] = scope.user - else: - payload["delete_data"] = body.get("delete_data") is True - audit.info( - "user=%s activity settings connection=%s instance=%s enabled=%s retention=%s " - "delete_data=%s", - scope.user, - conn, - name, - enabled, - payload.get("retention_days"), - payload.get("delete_data"), - ) - # switching on or off replaces the container (health-gated): the long timeout - return ControlPlaneClient(found).request( - "PUT", instance_path(name, "activity"), payload, timeouts=LONG - ) + if truncated: + raise EndpointReturn( + 409, {"error": "export_too_large", "message": "", "unreachable": []} + ) + return {"csv": "".join(parts), "unreachable": [], "timing": timing} + + +def merge_days(answers: list[dict[str, Any]]) -> dict[str, Any]: + """The day answers of several proxies as one: minutes and domains added up, totals again.""" + minutes: dict[int, list[int]] = {} + domains: dict[str, dict[str, Any]] = {} + other = {"count": 0, "requests": 0} + for answer in answers: + for t, n, x, d in answer.get("minutes") or []: + row = minutes.setdefault(int(t), [0, 0, 0]) + row[0] += int(n) + row[1] += int(x) + row[2] = max(row[2], int(d)) + for dom in answer.get("domains") or []: + cur = domains.get(dom["domain"]) + if cur is None: + domains[dom["domain"]] = dict(dom) + continue + for k in ("minutes", "requests", "blocked"): + cur[k] = int(cur.get(k) or 0) + int(dom.get(k) or 0) + cur["category"] = cur.get("category") or dom.get("category") + cur["first"] = min(int(cur["first"]), int(dom["first"])) + cur["last"] = max(int(cur["last"]), int(dom["last"])) + for k in ("count", "requests"): + other[k] += int((answer.get("other") or {}).get(k) or 0) + ordered = sorted(domains.values(), key=lambda d: (-int(d["minutes"]), -int(d["requests"]))) + return { + "minutes": [[t, n, x, d] for t, (n, x, d) in sorted(minutes.items())], + "domains": ordered, + "other": other, + "totals": { + "active_minutes": len(minutes), + "requests": sum(r[0] for r in minutes.values()), + "blocked": sum(r[1] for r in minutes.values()), + "domains": len(domains) + other["count"], + "first": min(minutes) if minutes else None, + "last": max(minutes) if minutes else None, + }, + "cursor": max(minutes) // 60 if minutes else None, + } diff --git a/webui/lmn_squid/client.py b/webui/lmn_squid/client.py index 22ff1b4..e32cb94 100644 --- a/webui/lmn_squid/client.py +++ b/webui/lmn_squid/client.py @@ -44,14 +44,17 @@ LONG = (5.0, 900.0) # create/patch/update/rollback/reconcile: health-gated, may take minutes +NOT_MODIFIED = object() # 304: the caller's copy is current + + class ControlPlaneError(Exception): """A request that did not succeed, in words an admin can act on. ``kind``: ``too_old`` (the control plane lacks the endpoint, 404 without a sentence), ``unreachable``, ``timeout``, ``fingerprint``, ``tls``, ``auth`` (the control plane refused the token), ``allowlist`` (its TLS listener refused this client's address, - ``tls_allowed_clients``), ``http`` (any other error status) or ``invalid`` (bad input - caught before sending). + ``tls_allowed_clients``), ``too_large`` (an answer over 16 MiB), ``http`` (any other error + status) or ``invalid`` (bad input caught before sending). """ def __init__( @@ -180,15 +183,20 @@ def request( auth: bool = True, raw: bytes | None = None, text: bool = False, + etag: str | None = None, ) -> Any: """Send one request; return the decoded JSON body (``None`` for an empty one). ``raw`` is sent as ``application/octet-stream`` (a keytab for ``PUT /v1/secrets``). ``text``: a successful answer is returned as text (the activity log's CSV export). + ``etag``: sent as ``If-None-Match``; an unchanged answer (304) returns + :data:`NOT_MODIFIED`, a JSON object answer carries the server's ETag as ``_etag``. """ if query: path = f"{path}?{urlencode({k: v for k, v in query.items() if v is not None})}" headers = {"Accept": "application/json"} + if etag: + headers["If-None-Match"] = etag if auth: headers["Authorization"] = f"Bearer {self.conn.token}" payload = None @@ -212,8 +220,10 @@ def request( finally: conn.close() if len(raw) > MAX_BODY: - raise ControlPlaneError("http", f"{self.conn.url}: answer too large", resp.status) + raise ControlPlaneError("too_large", f"{self.conn.url}: answer too large", resp.status) data: Any = None + if resp.status == 304: + return NOT_MODIFIED if text and resp.status < 400: return raw.decode("utf-8", "replace") if raw: @@ -244,4 +254,6 @@ def request( raise ControlPlaneError( "http", f"{self.conn.url}: {resp.status} {resp.reason}", resp.status, detail ) + if isinstance(data, dict) and resp.getheader("ETag"): + data["_etag"] = resp.getheader("ETag") return data diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index 3e9c86f..7dd4928 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -1386,3 +1386,6 @@ msgstr "nur mit gesperrten Versuchen" msgid "requests in this hour" msgstr "Anfragen in dieser Stunde" + +msgid "Internet use" +msgstr "Internetnutzung" diff --git a/webui/lmn_squid/main.py b/webui/lmn_squid/main.py index 9980806..0296314 100644 --- a/webui/lmn_squid/main.py +++ b/webui/lmn_squid/main.py @@ -1,11 +1,13 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later """Sidebar entries and permissions of the plugin (permissions.yml): the management for global -administrators, the activity log view "Internetprotokoll" for teachers and administrators.""" +administrators under Software, the activity view "Internetnutzung" for teachers and +administrators under Klassenzimmer.""" from __future__ import annotations -from typing import Any +import builtins +from typing import Any, Callable from aj.auth import PermissionProvider from aj.plugins.core.api.sidebar import SidebarItemProvider @@ -14,6 +16,20 @@ URL = "/view/lmn/squid" ACTIVITY_URL = "/view/lmn/squid-activity" +# the WebUI installs gettext's _ as a builtin; tests and tools have none +_: Callable[[str], str] = getattr(builtins, "_", lambda text: text) + + +# The activity view sits with what teachers do with their classes: upstream's category +# "Klassenzimmer" (category:class of lmn_common; Kevin E2, 2026-11-25). Its name cannot be +# changed here; to move the entry, change only these two lines. weight 30: after "Einschreiben" +# (25), before "Passwörter drucken" (40). The names are msgids translated by the WebUI +# (locale/de/LC_MESSAGES/app.po). +ACTIVITY_CATEGORY = "category:class" +ACTIVITY_NAME = _("Internet use") +ACTIVITY_WEIGHT = 30 +MANAGEMENT_NAME = _("Squid proxy") + @component(SidebarItemProvider) class ItemProvider(SidebarItemProvider): @@ -24,16 +40,17 @@ def provide(self) -> list[dict[str, Any]]: return [ { "attach": "category:software", - "name": "Squid proxy", + "name": MANAGEMENT_NAME, "icon": "fas fa-shield-alt", "url": URL, "children": [], }, { - "attach": "category:software", - "name": "Internetprotokoll", - "icon": "fas fa-history", + "attach": ACTIVITY_CATEGORY, + "name": ACTIVITY_NAME, + "icon": "fas fa-globe", "url": ACTIVITY_URL, + "weight": ACTIVITY_WEIGHT, "children": [], }, ] diff --git a/webui/lmn_squid/views.py b/webui/lmn_squid/views.py index 7f41d6b..e88e715 100644 --- a/webui/lmn_squid/views.py +++ b/webui/lmn_squid/views.py @@ -877,6 +877,89 @@ def handle_filter_stats(self, http_context: Any, conn: str = "", name: str = "") timeouts=(SHORT[0], 60.0), ) + # ------------------------------------------- activity log settings and audit (E1, ADR-023) + @get(PREFIX + "/" + CONN + r"/activity") + @authorize(PERM_LIST) + @endpoint(api=True) + @global_admin_only + def handle_activity(self, http_context: Any, conn: str = "") -> Any: + """Activity log settings of every instance of one server, with what is stored.""" + return self._client(conn).request("GET", "/v1/activity") + + @put(PREFIX + "/" + CONN + "/instances/" + NAME + r"/activity") + @authorize(PERM_CHANGE) + @endpoint(api=True) + @global_admin_only + def handle_activity_settings(self, http_context: Any, conn: str = "", name: str = "") -> Any: + """Switch the log of one instance on/off, set its retention. Switching on needs the + confirmed privacy notice; who confirmed it is the logged-in global administrator.""" + from . import activity_views + + body = _body(http_context) + enabled = body.get("enabled") + if not isinstance(enabled, bool): + raise EndpointReturn(422, {"error": "invalid", "field": "enabled", "message": "bool"}) + identity = str(getattr(self.context, "identity", None) or "") + payload: dict[str, Any] = {"enabled": enabled, "actor": identity} + retention = _int_param_body(body, "retention_days") + if retention is not None: + payload["retention_days"] = retention + if enabled and body.get("privacy_confirmed") is True: + payload["ack_by"] = identity + if not enabled: + payload["delete_data"] = body.get("delete_data") is True + self._audit( + "activity settings", + connection=conn, + instance=name, + enabled=enabled, + retention=payload.get("retention_days"), + delete_data=payload.get("delete_data"), + ) + try: + # switching on or off replaces the container (health-gated): the long timeout + return self._client(conn).request( + "PUT", instance_path(name, "activity"), payload, timeouts=LONG + ) + finally: + activity_views.forget_instances(conn) + + @get(PREFIX + "/" + CONN + r"/activity/audit") + @authorize(PERM_LIST) + @endpoint(api=True) + @global_admin_only + def handle_activity_audit(self, http_context: Any, conn: str = "") -> Any: + """Who read activity data on this server (newest first, 100 per page).""" + days = max(1, min(_int_param(http_context, "days", 7) or 7, 3650)) + offset = max(0, _int_param(http_context, "offset", 0) or 0) + actor = str((http_context.query or {}).get("actor") or "").strip() or None + now = int(time.time()) + return self._client(conn).request( + "GET", + "/v1/activity/audit", + query={ + "since": now - days * 86400, + "until": now + 1, + "actor": actor, + "limit": 100, + "offset": offset, + }, + ) + + +def _int_param_body(body: dict[str, Any], key: str) -> int | None: + value = body.get(key) + if value in (None, ""): + return None + if isinstance(value, bool): + raise EndpointReturn(422, {"error": "invalid", "field": key, "message": f"{key}"}) + try: + return int(value) + except (TypeError, ValueError): + raise EndpointReturn( + 422, {"error": "invalid", "field": key, "message": f"{key} must be a number"} + ) from None + def _filter_body(data: Any) -> dict[str, Any]: """Only the keys of the API's FilterSettings go through; the API validates the values.""" diff --git a/webui/tests/test_activity_views.py b/webui/tests/test_activity_views.py index 0697ce9..0802b1c 100644 --- a/webui/tests/test_activity_views.py +++ b/webui/tests/test_activity_views.py @@ -86,6 +86,7 @@ def project_groups(self, school: str, project: str) -> list[str]: def ad(webui: WebUI) -> Iterator[FakeDirectory]: fake = FakeDirectory() activity_scope.CACHE.clear() + activity_views.forget_instances() webui.activity.directory_factory = lambda: fake # type: ignore[method-assign] yield fake activity_scope.CACHE.clear() @@ -102,6 +103,12 @@ def login(webui: WebUI, user: str, role: str, granted: set[str] | None = None) - activity_scope.CACHE.clear() +def members(webui: WebUI, kind: str, name: str, **query: str) -> list[str]: + status, data = webui.call("GET", f"{PREFIX}/group/{kind}/{name}/members", query=query) + assert status == 200, data + return [m["user"] for m in data["members"]] + + def setup_proxy(webui: WebUI, cp: dict[str, Any], seed: bool = True) -> int: """One proxy with default-school-students (log on) and data of every user; returns now.""" login(webui, "global-admin", "globaladministrator") @@ -119,7 +126,7 @@ def setup_proxy(webui: WebUI, cp: dict[str, Any], seed: bool = True) -> int: assert webui.call("POST", "/api/lmn/squid/proxy1/instances", inst)[0] == 200 status, data = webui.call( "PUT", - f"{PREFIX}/settings/proxy1/default-school-students", + "/api/lmn/squid/proxy1/instances/default-school-students/activity", {"enabled": True, "privacy_confirmed": True, "retention_days": 7}, ) assert status == 200, data @@ -164,8 +171,12 @@ def test_teacher_sees_only_students_of_own_classes_and_projects( login(webui, "dslehr01", "teacher") status, info = webui.call("GET", f"{PREFIX}/scope") assert status == 200 and info["role"] == "teacher" and info["school"] == "default-school" - groups = {(g["kind"], g["name"]): [m["user"] for m in g["members"]] for g in info["groups"]} - assert groups == {("class", "5a"): ["s5a1", "s5a2"], ("project", "p_robotik"): ["s7c1", "sp1"]} + groups = {(g["kind"], g["name"]): g["count"] for g in info["groups"]} + assert groups == {("class", "5a"): 2, ("project", "p_robotik"): 2} + assert "members" not in info["groups"][0], "the start page loads no member lists" + assert members(webui, "class", "5a") == ["s5a1", "s5a2"] + assert members(webui, "project", "p_robotik") == ["s7c1", "sp1"] + assert members(webui, "class", "5a", teachers="1") == ["s5a1", "s5a2"], "never teachers" assert info["can_export"] is False and info["is_global"] is False status, data = users_of(webui, now) @@ -178,7 +189,7 @@ def test_teacher_sees_only_students_of_own_classes_and_projects( # the proxy audited it with the person and the class login(webui, "global-admin", "globaladministrator") - status, audit = webui.call("GET", f"{PREFIX}/audit", query={"days": "1"}) + status, audit = webui.call("GET", "/api/lmn/squid/proxy1/activity/audit", query={"days": "1"}) assert status == 200 mine = [e for e in audit["entries"] if e["actor"] == "dslehr01"] assert mine[0]["scope"] == "class 5a" and mine[0]["users"] == ["s5a1", "s5a2"] @@ -211,12 +222,15 @@ def test_teacher_is_refused_outside_the_scope( ) assert status == 403, user assert webui.call("POST", f"{PREFIX}/export", {"since": now - 60, "until": now})[0] == 403 - assert webui.call("GET", f"{PREFIX}/audit")[0] == 403 - assert webui.call("GET", f"{PREFIX}/settings")[0] == 403 + assert webui.call("GET", "/api/lmn/squid/proxy1/activity/audit")[0] == 403 + assert webui.call("GET", "/api/lmn/squid/proxy1/activity")[0] == 403 status, _ = webui.call( - "PUT", f"{PREFIX}/settings/proxy1/default-school-students", {"enabled": False} + "PUT", + "/api/lmn/squid/proxy1/instances/default-school-students/activity", + {"enabled": False}, ) assert status == 403 + assert webui.call("GET", f"{PREFIX}/group/class/6b/members")[0] == 403 assert len(cp["recorder"].seen) == asked, "nothing reached a proxy" @@ -264,10 +278,11 @@ def test_school_admin_sees_the_school_and_nothing_else( ) assert status == 200 rows = data["csv"].strip().splitlines() - # a school administrator sees every member of the class, teachers included - assert rows[0].startswith("time,user,domain") and len(rows) == 3 - assert {r.split(",")[1] for r in rows[1:]} == {"s6b1", "dslehr02"} - assert webui.call("GET", f"{PREFIX}/audit")[0] == 403 + # teachers of the class only on request (E3) + assert rows[0].startswith("time,user,domain") and [r.split(",")[1] for r in rows[1:]] == [ + "s6b1" + ] + assert webui.call("GET", "/api/lmn/squid/proxy1/activity/audit")[0] == 403 def test_students_and_other_roles_get_nothing( @@ -318,17 +333,25 @@ def test_global_admin_all_schools_and_settings( assert len(data["users"]) == len(USERS) status, info = webui.call("GET", f"{PREFIX}/scope", query={"school": "default-school"}) assert ("class", "5a") in {(g["kind"], g["name"]) for g in info["groups"]} - status, settings = webui.call("GET", f"{PREFIX}/settings") - inst = settings["servers"][0]["instances"][0] + status, settings = webui.call("GET", "/api/lmn/squid/proxy1/activity") + inst = settings["instances"][0] assert inst["enabled"] and inst["usage"]["days"] == 1 # switching on again without the confirmation: the proxy refuses (422 passed on) - path = f"{PREFIX}/settings/proxy1/default-school-students" - assert webui.call("PUT", path, {"enabled": False, "delete_data": True})[0] == 200 - status, data = webui.call("PUT", path, {"enabled": True}) + assert ( + webui.call( + "PUT", + "/api/lmn/squid/proxy1/instances/default-school-students/activity", + {"enabled": False, "delete_data": True}, + )[0] + == 200 + ) + status, data = webui.call( + "PUT", "/api/lmn/squid/proxy1/instances/default-school-students/activity", {"enabled": True} + ) assert status == 422 and "privacy notice" in str(data) webui.as_root() activity_scope.CACHE.clear() - root_status, _ = webui.call("GET", f"{PREFIX}/settings") + root_status, _ = webui.call("GET", "/api/lmn/squid/proxy1/activity") assert root_status == 200 @@ -348,7 +371,7 @@ def test_a_proxy_that_does_not_answer_does_not_block( status, data = users_of(webui, now) assert time.monotonic() - started < 8 assert status == 200 and len(data["users"]) == 4 - assert [u["connection"] for u in data["unreachable"]] == ["down"] + assert [(u["connection"], u["kind"]) for u in data["unreachable"]] == [("down", "unreachable")] def test_state_changing_requests_need_json_from_the_same_site( @@ -362,8 +385,15 @@ def test_state_changing_requests_need_json_from_the_same_site( evil = {**SAME_ORIGIN, "HTTP_ORIGIN": "https://evil.example"} assert webui.call("POST", f"{PREFIX}/query/users", body, env=evil)[0] == 403 login(webui, "global-admin", "globaladministrator") - path = f"{PREFIX}/settings/proxy1/default-school-students" - assert webui.call("PUT", path, {"enabled": False}, env=evil)[0] == 403 + assert ( + webui.call( + "PUT", + "/api/lmn/squid/proxy1/instances/default-school-students/activity", + {"enabled": False}, + env=evil, + )[0] + == 403 + ) def test_bad_input_is_a_readable_422(webui: WebUI, ad: FakeDirectory, cp: dict[str, Any]) -> None: @@ -384,7 +414,7 @@ def test_bad_input_is_a_readable_422(webui: WebUI, ad: FakeDirectory, cp: dict[s def test_every_activity_endpoint_needs_the_permission() -> None: routes = [f for f in vars(activity_views.ActivityHandler).values() if hasattr(f, "url_pattern")] - assert len(routes) == 9 + assert len(routes) == 10 for fn in routes: assert fn.url_pattern.pattern.startswith("^/api/lmn/squid-activity/") assert fn.permission_id == activity_views.PERM_ACTIVITY @@ -416,3 +446,224 @@ def test_ldap_directory_wraps_reader_errors(monkeypatch: pytest.MonkeyPatch) -> assert directory.person("dslehr01")["sophomorixRole"] == "teacher" # type: ignore[index] reader.get = lambda url, **kw: {"sophomorixMemberGroups": ["7c"], "sophomorixAdminGroups": []} assert directory.project_groups("default-school", "p_x") == ["7c"] + + +# ------------------------------------------------------------- round 2 (spec + lab findings) + + +def test_people_search_stays_in_the_scope_and_asks_no_proxy( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + setup_proxy(webui, cp, seed=False) + login(webui, "dslehr01", "teacher") + webui.call("GET", f"{PREFIX}/scope") # warms the instance cache + asked = len(cp["recorder"].seen) + status, data = webui.call("GET", f"{PREFIX}/people", query={"q": "s"}) + assert (status, data) == (200, {"people": []}), "at least two characters" + status, data = webui.call("GET", f"{PREFIX}/people", query={"q": "S5"}) + assert [p["user"] for p in data["people"]] == ["s5a1", "s5a2"] + assert data["people"][0]["classes"] == ["5a"] + for q in ("lehr", "s6b", "o5a"): + assert webui.call("GET", f"{PREFIX}/people", query={"q": q})[1]["people"] == [], q + assert len(cp["recorder"].seen) == asked, "no proxy request" + + +def test_teachers_in_a_class_only_on_request_for_admins( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp) + login(webui, "pgmadmin", "schooladministrator") + assert members(webui, "class", "5a") == ["s5a1", "s5a2"] + assert members(webui, "class", "5a", teachers="1") == ["dslehr01", "dslehr03", "s5a1", "s5a2"] + group = {"kind": "class", "name": "5a"} + found = {u["user"] for u in users_of(webui, now, group=group)[1]["users"]} + assert found == {"s5a1", "s5a2"} + found = {u["user"] for u in users_of(webui, now, group=group, teachers=True)[1]["users"]} + assert found == {"s5a1", "s5a2", "dslehr01", "dslehr03"} + # a teacher asking for teachers gets students only + login(webui, "dslehr01", "teacher") + found = {u["user"] for u in users_of(webui, now, group=group, teachers=True)[1]["users"]} + assert found == {"s5a1", "s5a2"} + + +def test_student_day_merged_and_revalidated( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + import datetime + + now = setup_proxy(webui, cp) + login(webui, "dslehr01", "teacher") + day = datetime.datetime.fromtimestamp(now, ZoneInfo("Europe/Berlin")).date().isoformat() + status, data = webui.call("POST", f"{PREFIX}/query/day", {"user": "s5a1", "day": day}) + assert status == 200, data + assert data["display"] == "S5A1" and data["classes"] == ["5a"] + assert data["totals"]["blocked"] == 1 and data["totals"]["domains"] == 2 + assert {d["domain"] for d in data["domains"]} == {"site-s5a1.example", "bad.example"} + etags = data["etags"] + assert etags["proxy1"] + status, again = webui.call( + "POST", f"{PREFIX}/query/day", {"user": "s5a1", "day": day, "etags": etags} + ) + assert status == 200 and again["not_modified"] is True + # the drill-down of one domain, and the heat map + status, rows = webui.call( + "POST", + f"{PREFIX}/query/timeline", + { + "user": "s5a1", + "since": now - 3600, + "until": now + 60, + "resolution": "minute", + "domain": "bad.example", + }, + ) + assert [r["domain"] for r in rows["rows"]] == ["bad.example"] + # out of scope + for user in ("s6b1", "dslehr03"): + assert webui.call("POST", f"{PREFIX}/query/day", {"user": user, "day": day})[0] == 403 + + +def test_blocked_attempts_of_a_class(webui: WebUI, ad: FakeDirectory, cp: dict[str, Any]) -> None: + now = setup_proxy(webui, cp) + login(webui, "dslehr01", "teacher") + body = {"since": now - 3600, "until": now + 60, "group": {"kind": "class", "name": "5a"}} + status, data = webui.call("POST", f"{PREFIX}/query/blocked", body) + assert status == 200 + assert data["domains"] == [ + {"domain": "bad.example", "blocked": 1, "users": 1, "category": "porn"} + ] + + +def test_limits_are_named_not_unreachable( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + """Lab A2: a limit of the proxy was shown as "not reachable" and 422.""" + now = setup_proxy(webui, cp) + login(webui, "global-admin", "globaladministrator") + import lmnsquid.activity_query as aq + + old = aq.MAX_SEARCH_CANDIDATES + aq.MAX_SEARCH_CANDIDATES = 1 + try: + status, data = webui.call( + "POST", + f"{PREFIX}/query/search", + {"since": now - 3600, "until": now + 60, "domain": "example"}, + ) + finally: + aq.MAX_SEARCH_CANDIDATES = old + assert status == 200 + (fail,) = data["unreachable"] + assert (fail["kind"], fail["code"]) == ("limit", "too_many_hits") + assert "too many hits" in fail["message"] + + +def test_export_is_refused_when_a_proxy_cannot_deliver( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any] +) -> None: + now = setup_proxy(webui, cp) + body = { + "name": "down", + "url": f"https://127.0.0.1:{free_port()}", + "token": TOKEN, + "fingerprint": cp["fingerprint"], + } + assert webui.call("POST", "/api/lmn/squid/connections", body)[0] == 200 + login(webui, "pgmadmin", "schooladministrator") + status, data = webui.call("POST", f"{PREFIX}/export", {"since": now - 3600, "until": now + 60}) + assert status == 409 and data["error"] == "export_incomplete" + assert data["unreachable"][0]["connection"] == "down" + + +def test_refusals_and_empty_scopes_are_audited( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """Lab A4: refused requests and those without a proxy request were in no log.""" + lines: list[str] = [] + monkeypatch.setattr(activity_views, "audit_line", lines.append) + now = setup_proxy(webui, cp, seed=False) + login(webui, "dslehr02", "teacher") + ad.users["dslehr02"]["schoolclasses"] = [] + activity_scope.CACHE.clear() + assert users_of(webui, now)[1]["users"] == [] + assert ( + webui.call("POST", f"{PREFIX}/query/day", {"user": "s5a1", "day": "2026-11-25"})[0] == 403 + ) + assert any("dslehr02" in ln and "empty scope" in ln for ln in lines), lines + assert any("dslehr02" in ln and "refused" in ln and "/query/day" in ln for ln in lines), lines + login(webui, "dslehr01", "teacher") + users_of(webui, now, group={"kind": "class", "name": "5a"}) + assert any("dslehr01" in ln and "class 5a" in ln for ln in lines) + + +def test_a_hanging_proxy_costs_at_most_the_deadline( + webui: WebUI, ad: FakeDirectory, cp: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + import socket + import threading + + now = setup_proxy(webui, cp) + hang = socket.socket() + hang.bind(("127.0.0.1", 0)) + hang.listen(5) + port = hang.getsockname()[1] + stop = threading.Event() + + def accept() -> None: + held = [] + while not stop.is_set(): + try: + hang.settimeout(0.2) + held.append(hang.accept()[0]) # accept, never answer the TLS handshake + except OSError: + pass + + threading.Thread(target=accept, daemon=True).start() + try: + body = { + "name": "hang", + "url": f"https://127.0.0.1:{port}", + "token": TOKEN, + "fingerprint": cp["fingerprint"], + } + assert webui.call("POST", "/api/lmn/squid/connections", body)[0] == 200 + monkeypatch.setattr(activity_views, "DEADLINE", 1.0) + login(webui, "dslehr01", "teacher") + started = time.monotonic() + status, data = users_of(webui, now) + took = time.monotonic() - started + finally: + stop.set() + hang.close() + assert status == 200 and len(data["users"]) == 4 + assert took < 2.5, took + assert data["unreachable"][0]["connection"] == "hang" + assert data["unreachable"][0]["kind"] in ("timeout", "unreachable") + assert set(data["timing"]["proxies"]) == {"proxy1"} + + +def test_scope_of_a_large_school_is_fast_and_small(webui: WebUI) -> None: + """Fake AD: 1000 users, 40 classes, 20 projects; /scope without LDAP < 50 ms, < 20 KB.""" + import json as jsonlib + + fake = FakeDirectory() + fake.users = {"pgmadmin": _user("pgmadmin", "schooladministrator")} + for i in range(1000): + fake.users[f"s{i:04d}"] = _user( + f"s{i:04d}", "student", classes=[f"k{i % 40:02d}"], projects=[f"p{i % 20:02d}"] + ) + activity_scope.CACHE.clear() + webui.activity.directory_factory = lambda: fake # type: ignore[method-assign] + login(webui, "pgmadmin", "schooladministrator") + status, info = webui.call("GET", f"{PREFIX}/scope") # cold: builds the scope + assert status == 200 and len(info["groups"]) == 60 + started = time.monotonic() + for _ in range(10): + webui.call("GET", f"{PREFIX}/scope") + warm_ms = (time.monotonic() - started) * 100 + assert warm_ms < 50, warm_ms + assert len(jsonlib.dumps(info)) < 20_000 + started = time.monotonic() + status, data = webui.call("GET", f"{PREFIX}/people", query={"q": "s09"}) + assert status == 200 and len(data["people"]) == 10 + assert (time.monotonic() - started) * 1000 < 50 From 2e6003fa54165715935b8e6dfd66f6970f466274 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 14:18:01 +0100 Subject: [PATCH 15/45] feat(webui): Internetnutzung centred on one student: start page, class list, student page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One route, the page in the query string (links open in a new tab, Back works): - Start: student search (typeahead from the AD, no proxy request) and tiles of the person's classes and projects; a teacher without classes is told where to join them; a global administrator chooses a school first. No "all users" query any more. - Class: members with last seen, requests and blocked attempts from one cheap list query (no domain count), teachers only on request for administrators (E3), live every 60 s while visible; blocked attempts, top domains (background services hidden) and "who was on …" in this class, each loaded when opened. - Student page instead of the dialog: date navigation down to the oldest stored day, whole day / school hours / this hour, key figures, the day as sessions (gaps up to 4 minutes) with blocked minutes in red, domains with active minutes and category names, a domain's minutes on click, the domains of one session, a 7-day heat map that fits 1366 px (an hour opens that day); live every 30 s as a delta of minutes, paused while the tab is hidden, ended after 15 minutes. - German numbers and times in the proxies' time zone (filters lmnNum and lmnTime), range buttons translated, one line for proxies that delivered nothing with the reason per proxy (lab A2, A3). - The settings and the audit log left this page (E1). --- webui/lmn_squid/activity_views.py | 9 + webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 177 ++++ webui/lmn_squid/plugin.yml | 1 + .../js/controllers/activity.controller.es | 922 ++++++++++++------ webui/lmn_squid/resources/js/filters.es | 111 +++ webui/lmn_squid/resources/js/routing.es | 4 +- .../lmn_squid/resources/partial/activity.html | 520 +++++----- webui/tests/js/activity_check.js | 207 ++-- webui/tests/js/controller_check.js | 2 + webui/tests/test_build.py | 1 + 10 files changed, 1295 insertions(+), 659 deletions(-) create mode 100644 webui/lmn_squid/resources/js/filters.es diff --git a/webui/lmn_squid/activity_views.py b/webui/lmn_squid/activity_views.py index df29d72..8e435c6 100644 --- a/webui/lmn_squid/activity_views.py +++ b/webui/lmn_squid/activity_views.py @@ -353,10 +353,19 @@ def handle_scope(self, http_context: Any) -> Any: if isinstance(i, dict) and i.get("school") } ) + oldest = sorted( + str(i.get("oldest")) + for _c, r, _ms in results + for i in (r or {}).get("instances") or [] + if isinstance(i, dict) + and i.get("oldest") + and (scope.school is None or i.get("school") == scope.school) + ) return { "user": scope.user, "role": scope.role, "school": scope.school, + "oldest": oldest[0] if oldest else None, "schools": schools if scope.is_global else [], "can_export": scope.can_export, "is_global": scope.is_global, diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index 7dd4928..3553c71 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -1389,3 +1389,180 @@ msgstr "Anfragen in dieser Stunde" msgid "Internet use" msgstr "Internetnutzung" + +msgid "(click a session for its domains)" +msgstr "(eine Sitzung anklicken zeigt ihre Domains)" + +msgid "-- choose a school --" +msgstr "-- Schule wählen --" + +msgid "Active" +msgstr "Aktiv" + +msgid "Active minutes" +msgstr "Aktive Minuten" + +msgid "Blocked attempts of the class" +msgstr "Gesperrte Versuche der Klasse" + +msgid "Choose a school to see its classes and students." +msgstr "Bitte eine Schule wählen, um ihre Klassen und Schülerinnen und Schüler zu sehen." + +msgid "Class" +msgstr "Klasse" + +msgid "Classes and projects" +msgstr "Klassen und Projekte" + +msgid "Click a domain: when exactly it was used." +msgstr "Eine Domain anklicken: wann genau sie genutzt wurde." + +msgid "Details" +msgstr "Details" + +msgid "Domains of the session" +msgstr "Domains der Sitzung" + +msgid "Every 30 seconds while the page is visible, for 15 minutes" +msgstr "Alle 30 Sekunden, solange die Seite sichtbar ist, für 15 Minuten" + +msgid "Every view of the data is recorded." +msgstr "Jeder Abruf wird protokolliert." + +msgid "Export refused: a proxy server cannot deliver its part." +msgstr "Export abgelehnt: ein Proxy-Server kann seinen Teil nicht liefern." + +msgid "Export too large: choose a shorter range or one class." +msgstr "Export zu groß: einen kürzeren Zeitraum oder eine Klasse wählen." + +msgid "Filter classes" +msgstr "Klassen filtern" + +msgid "Find a student (name or login)" +msgstr "Schülerin oder Schüler suchen (Name oder Anmeldename)" + +msgid "Further domains:" +msgstr "Weitere Domains:" + +msgid "Join classes under \"Einschreiben\"." +msgstr "Klassen treten Sie unter „Einschreiben“ bei." + +msgid "Last 7 days" +msgstr "Letzte 7 Tage" + +msgid "Live update ended after 15 minutes." +msgstr "Live-Aktualisierung nach 15 Minuten beendet." + +msgid "Most used domains" +msgstr "Häufigste Domains" + +msgid "Most visited domains of the class" +msgstr "Häufigste Domains der Klasse" + +msgid "My classes and projects" +msgstr "Meine Klassen und Projekte" + +msgid "No blocked attempts in this time range." +msgstr "Keine gesperrten Versuche in diesem Zeitraum." + +msgid "No internet use in this class in this time range yet." +msgstr "In diesem Zeitraum noch keine Internetnutzung in dieser Klasse." + +msgid "No internet use on this day." +msgstr "An diesem Tag keine Internetnutzung." + +msgid "Not in your classes and projects." +msgstr "Nicht in Ihren Klassen und Projekten." + +msgid "Older data are deleted (retention)." +msgstr "Ältere Daten sind gelöscht (Aufbewahrung)." + +msgid "Overview" +msgstr "Übersicht" + +msgid "Project" +msgstr "Projekt" + +msgid "Reload every 60 seconds while the page is visible" +msgstr "Alle 60 Sekunden neu laden, solange die Seite sichtbar ist" + +msgid "Sessions" +msgstr "Sitzungen" + +msgid "Show background services (ads, tracking, telemetry)" +msgstr "Hintergrunddienste zeigen (Werbung, Tracking, Telemetrie)" + +msgid "Show teachers" +msgstr "Lehrkräfte anzeigen" + +msgid "Students" +msgstr "Schüler" + +msgid "Teacher" +msgstr "Lehrkraft" + +msgid "This person does not belong to your classes." +msgstr "Diese Person gehört nicht zu Ihren Klassen." + +msgid "Who else of the class was on this domain?" +msgstr "Wer aus der Klasse war noch auf dieser Domain?" + +msgid "Who was on …?" +msgstr "Wer war auf …?" + +msgid "Whole day" +msgstr "Ganzer Tag" + +msgid "Yesterday" +msgstr "Gestern" + +msgid "You are not in any class or project with students." +msgstr "Sie sind in keiner Klasse und keinem Projekt mit Schülerinnen und Schülern." + +msgid "active minutes" +msgstr "aktive Minuten" + +msgid "answer too large: choose a shorter range or one class" +msgstr "Antwort zu groß: einen kürzeren Zeitraum oder eine Klasse wählen" + +msgid "blocked" +msgstr "gesperrt" + +msgid "certificate does not match the stored fingerprint" +msgstr "Zertifikat passt nicht zum gespeicherten Fingerabdruck" + +msgid "does not answer in time (5 s)" +msgstr "antwortet nicht rechtzeitig (5 s)" + +msgid "error" +msgstr "Fehler" + +msgid "proxy server(s) delivered no data for this view." +msgstr "Proxy-Server lieferte(n) keine Daten für diese Ansicht." + +msgid "query too large: choose a shorter range or fewer people" +msgstr "Abfrage zu groß: einen kürzeren Zeitraum oder weniger Personen wählen" + +msgid "refuses this server (tls_allowed_clients)" +msgstr "lehnt diesen Server ab (tls_allowed_clients)" + +msgid "requests per hour, red border: blocked attempts; click an hour to open it" +msgstr "Anfragen je Stunde, roter Rand: gesperrte Versuche; eine Stunde anklicken öffnet sie" + +msgid "show the whole range" +msgstr "ganzen Zeitraum zeigen" + +msgid "time range too long" +msgstr "Zeitraum zu lang" + +msgid "token refused" +msgstr "Token abgelehnt" + +msgid "too many hits: choose a shorter range or a longer domain name" +msgstr "zu viele Treffer: einen kürzeren Zeitraum oder einen längeren Domainnamen wählen" + +msgid "too many people at once" +msgstr "zu viele Personen auf einmal" + +msgid "version too old for this function (update linuxmuster-squid)" +msgstr "Version zu alt für diese Funktion (linuxmuster-squid aktualisieren)" diff --git a/webui/lmn_squid/plugin.yml b/webui/lmn_squid/plugin.yml index 5a30ba3..b17fecf 100644 --- a/webui/lmn_squid/plugin.yml +++ b/webui/lmn_squid/plugin.yml @@ -14,6 +14,7 @@ dependencies: resources: - 'resources/js/module.es' - 'resources/js/routing.es' + - 'resources/js/filters.es' - 'resources/js/controllers/index.controller.es' - 'resources/partial/index.html' - 'resources/css/dialogs.css' diff --git a/webui/lmn_squid/resources/js/controllers/activity.controller.es b/webui/lmn_squid/resources/js/controllers/activity.controller.es index 463861a..c660970 100644 --- a/webui/lmn_squid/resources/js/controllers/activity.controller.es +++ b/webui/lmn_squid/resources/js/controllers/activity.controller.es @@ -1,133 +1,326 @@ // SPDX-FileCopyrightText: Kevin Stenzel // SPDX-License-Identifier: GPL-3.0-or-later -// Activity log view "Internetprotokoll" (ADR-023). ES5 on purpose (webui/build_plugin.py). -// The server decides what the person may see; this page only asks and shows. -angular.module('lmn.squid').controller('LMNSquidActivityController', function ($scope, $http, $interval, $window, pageTitle, gettext, notify) { +// Internetnutzung (ADR-023): start page, class list and the student page, all on one route; the +// page comes from the query string. ES5 on purpose (webui/build_plugin.py). The server decides +// what the person may see; every request for activity data is audited on the proxy, so this page +// asks only for what it shows: nothing on the start page, one cheap list for a class, one day and +// one heat map for a student, details only when opened. +angular.module('lmn.squid').controller('LMNSquidActivityController', function ($scope, $http, $interval, $location, $window, $document, pageTitle, gettext, notify, lmnSquidTime) { 'use strict'; - pageTitle.set(gettext('Internet activity log')); + pageTitle.set(gettext('Internet use')); var API = '/api/lmn/squid-activity'; - var LIVE_SECONDS = 30; - // "Unterrichtszeit": today from 7:45 to 16:00 (local time of the browser) - var LESSON_START = [7, 45]; - var LESSON_END = [16, 0]; + var VIEW_URL = '/view/lmn/squid-activity'; + var SESSION_GAP = 4 * 60; // minutes without activity that still belong to one session + var GROUP_LIVE = 60; // seconds + var USER_LIVE = 30; // the collector runs every 30 s; faster brings nothing + var LIVE_MAX = 15 * 60; // live updates end after 15 minutes var HEAT_DAYS = 7; + var T = lmnSquidTime; $scope.loaded = false; $scope.loadError = ''; $scope.busy = false; $scope.info = {groups: [], schools: []}; - $scope.sel = {school: '', group: '', range: 'today', live: false}; - $scope.tab = {index: 0, name: 'overview'}; + $scope.tz = 'Europe/Berlin'; + $scope.page = 'start'; + $scope.sel = {school: '', range: 'today', part: 'day', live: false, teachers: false, background: false, day: ''}; + $scope.failures = []; + $scope.showFailures = false; + $scope.people = {selected: null}; + $scope.tiles = {filter: ''}; + $scope.group = null; + $scope.groupKey = ''; + $scope.members = []; + $scope.teachersHidden = 0; $scope.rows = []; $scope.loadedRows = false; - $scope.domains = []; - $scope.loadedDomains = false; - $scope.search = {domain: '', users: [], done: false}; - $scope.unreachable = []; - $scope.sort = {key: 'requests', reverse: true}; + $scope.anyActivity = false; $scope.tableFilter = {text: '', activeOnly: false, blockedOnly: false}; - $scope.detail = null; - $scope.settings = {servers: []}; - $scope.audit = []; - $scope.auditForm = {days: 7, actor: ''}; - $scope.enableDialog = null; - $scope.disableDialog = null; + $scope.sort = {key: 'active', reverse: false}; + $scope.sortKeys = ['-active_now', 'display']; + $scope.agg = { + blocked: {open: false, rows: []}, + domains: {open: false, rows: [], background: false}, + search: {open: false, rows: [], domain: ''} + }; + $scope.person = {}; + $scope.dayData = null; + $scope.sessions = []; + $scope.chosenSession = null; + $scope.blockedTicks = []; + $scope.axis = {ticks: []}; + $scope.domainsShown = {rows: [], other: {count: 0}}; + $scope.domainDetail = {}; + $scope.heat = []; + $scope.dateInput = {value: null}; $scope.hours = []; var h; for (h = 0; h < 24; h++) { $scope.hours.push(h); } - $scope.ranges = [ - {id: 'hour', label: gettext('This hour')}, + $scope.groupRanges = [ {id: 'today', label: gettext('Today so far')}, + {id: 'hour', label: gettext('This hour')}, + {id: 'lesson', label: gettext('School hours')} + ]; + $scope.dayParts = [ + {id: 'day', label: gettext('Whole day')}, {id: 'lesson', label: gettext('School hours')}, - {id: 'week', label: gettext('7 days')} + {id: 'hour', label: gettext('This hour')} ]; + // ------------------------------------------------------------------ helpers + function now() { + return Math.floor(Date.now() / 1000); + } + + var FAILURE_TEXT = { + unreachable: gettext('not reachable'), + timeout: gettext('does not answer in time (5 s)'), + too_old: gettext('version too old for this function (update linuxmuster-squid)'), + auth: gettext('token refused'), + allowlist: gettext('refuses this server (tls_allowed_clients)'), + tls: gettext('certificate does not match the stored fingerprint'), + fingerprint: gettext('certificate does not match the stored fingerprint'), + too_large: gettext('answer too large: choose a shorter range or one class') + }; + var LIMIT_TEXT = { + range_too_long: gettext('time range too long'), + too_many_users: gettext('too many people at once'), + too_many_hits: gettext('too many hits: choose a shorter range or a longer domain name'), + query_too_large: gettext('query too large: choose a shorter range or fewer people') + }; + $scope.failureText = function (f) { + if (f.kind === 'limit') { + return LIMIT_TEXT[f.code] || f.message; + } + return (FAILURE_TEXT[f.kind] || gettext('error')) + (f.kind === 'error' && f.message ? ': ' + f.message : ''); + }; + $scope.toggleFailures = function () { $scope.showFailures = !$scope.showFailures; }; + + function noteFailures(list) { + $scope.failures = list || []; + } + function errorText(resp) { var data = resp && resp.data; + if (data && data.error === 'export_incomplete') { + return gettext('Export refused: a proxy server cannot deliver its part.') + ' ' + + (data.unreachable || []).map(function (f) { return f.connection + ': ' + $scope.failureText(f); }).join('; '); + } + if (data && data.error === 'export_too_large') { + return gettext('Export too large: choose a shorter range or one class.'); + } + if (data && data.error === 'scope') { + return gettext('Not in your classes and projects.'); + } if (data && data.message) { return data.message; } - if (data && data.detail) { - return typeof data.detail === 'string' ? data.detail : angular.toJson(data.detail); - } return gettext('Request failed') + ' (' + (resp && resp.status) + ')'; } - // since/until in epoch seconds for a named range, in the browser's local time - function rangeOf(id, now) { - var d = new Date(now); - var end = Math.floor(now / 1000) + 60; - if (id === 'hour') { - d.setMinutes(0, 0, 0); - return [Math.floor(d.getTime() / 1000), end]; + $scope.href = function (params) { + var parts = []; + var all = angular.copy(params || {}); + if ($scope.sel.school && !all.school) { + all.school = $scope.sel.school; } - if (id === 'lesson') { - var s = new Date(now); - s.setHours(LESSON_START[0], LESSON_START[1], 0, 0); - var e = new Date(now); - e.setHours(LESSON_END[0], LESSON_END[1], 0, 0); - return [Math.floor(s.getTime() / 1000), Math.min(Math.floor(e.getTime() / 1000), end)]; + angular.forEach(['school', 'group', 'user', 'day'], function (k) { + if (all[k]) { + parts.push(k + '=' + encodeURIComponent(all[k])); + } + }); + return VIEW_URL + (parts.length ? '?' + parts.join('&') : ''); + }; + + function go(params) { + var all = angular.copy(params || {}); + if ($scope.sel.school && !all.school) { + all.school = $scope.sel.school; } - d.setHours(0, 0, 0, 0); - if (id === 'week') { - d.setDate(d.getDate() - 6); + $location.search(all); + } + + $scope.categoryLabel = function (id) { + return ($scope.info.category_labels || {})[id] || id; + }; + + $scope.durationText = function (minutes) { + if (!minutes) { + return '0 min'; } - return [Math.floor(d.getTime() / 1000), end]; + var hh = Math.floor(minutes / 60); + var mm = minutes % 60; + return (hh ? hh + ' h ' : '') + mm + ' min'; + }; + + function lesson(day) { + var lh = $scope.info.lesson_hours || ['07:45', '16:00']; + return [T.at(day, lh[0], $scope.tz), T.at(day, lh[1], $scope.tz)]; } - $scope.rangeOf = rangeOf; - - function rangeLabel() { - var r = rangeOf($scope.sel.range, Date.now()); - var from = new Date(r[0] * 1000); - var to = new Date(Math.min(r[1] * 1000, Date.now())); - function two(n) { return (n < 10 ? '0' : '') + n; } - function fmt(x) { return two(x.getDate()) + '.' + two(x.getMonth() + 1) + '. ' + two(x.getHours()) + ':' + two(x.getMinutes()); } - $scope.rangeText = fmt(from) + ' – ' + fmt(to); + + function currentHour(day) { + var p = T.parts(now(), $scope.tz); + var two = (p.h < 10 ? '0' : '') + p.h; + var start = T.at(day, two + ':00', $scope.tz); + return [start, start + 3600]; } - function selectedGroup() { - if (!$scope.sel.group) { - return null; + // since/until of the class list's range (today in the proxies' zone) + function groupRange(id, t) { + var day = T.dayOf(t, $scope.tz); + if (id === 'hour') { + return [currentHour(day)[0], t + 60]; } - var i = $scope.sel.group.indexOf(':'); - return {kind: $scope.sel.group.substring(0, i), name: $scope.sel.group.substring(i + 1)}; + if (id === 'lesson') { + var l = lesson(day); + return [l[0], Math.min(l[1], t + 60)]; + } + return [T.dayStart(day, $scope.tz), t + 60]; } + $scope.groupRange = groupRange; - function groupMembers() { - var g = selectedGroup(); - var i; - if (!g) { - return []; + // ------------------------------------------------------------------ sessions + // minutes [[t, n, x, d], ...] (t = start of the minute, seconds) -> sessions + function buildSessions(minutes) { + var out = []; + var cur = null; + angular.forEach(minutes, function (m) { + if (cur && m[0] - (cur.end - 60) <= SESSION_GAP + 60) { + cur.end = m[0] + 60; + cur.minutes += 1; + cur.requests += m[1]; + cur.blocked += m[2]; + } else { + cur = {start: m[0], end: m[0] + 60, minutes: 1, requests: m[1], blocked: m[2]}; + out.push(cur); + } + }); + return out; + } + $scope.buildSessions = buildSessions; + + function layoutDay(data) { + var sessions = buildSessions(data.minutes || []); + var start = T.dayStart($scope.sel.day, $scope.tz); + var first = sessions.length ? sessions[0].start : start + 7 * 3600; + var last = sessions.length ? sessions[sessions.length - 1].end : start + 17 * 3600; + var from = Math.min(start + 7 * 3600, first - (first - start) % 3600); + var to = Math.max(start + 17 * 3600, last + (3600 - (last - start) % 3600) % 3600); + var span = Math.max(to - from, 3600); + function pct(t) { return Math.max(0, Math.min(100, (t - from) * 100 / span)); } + angular.forEach(sessions, function (s) { + s.left = pct(s.start); + s.width = Math.max(0.3, pct(s.end) - pct(s.start)); + s.title = T.format(s.start, $scope.tz, 'time') + '–' + T.format(s.end, $scope.tz, 'time') + + ' · ' + s.minutes + ' min' + (s.blocked ? ' · ' + s.blocked + ' ' + gettext('of them blocked') : ''); + }); + var ticks = []; + var t; + for (t = from; t <= to; t += 3600) { + ticks.push({left: pct(t), label: T.format(t, $scope.tz, 'time').substring(0, 2)}); } - for (i = 0; i < $scope.info.groups.length; i++) { - if ($scope.info.groups[i].kind === g.kind && $scope.info.groups[i].name === g.name) { - return $scope.info.groups[i].members || []; + var blocked = []; + angular.forEach(data.minutes || [], function (m) { + if (m[2]) { + blocked.push({left: pct(m[0]), title: T.format(m[0], $scope.tz, 'time') + ' · ' + m[2] + ' ' + gettext('blocked')}); } + }); + $scope.sessions = sessions; + $scope.axis = {ticks: ticks}; + $scope.blockedTicks = blocked; + } + + $scope.refreshDomains = function () { + var src = $scope.chosenSession && $scope.chosenSession.data ? $scope.chosenSession.data : $scope.dayData; + var rows = []; + angular.forEach((src && src.domains) || [], function (d) { + if ($scope.sel.background || !d.background) { + rows.push(d); + } + }); + $scope.domainsShown = {rows: rows, other: (src && src.other) || {count: 0}}; + }; + + // ------------------------------------------------------------------ heat map + function heatColor(n, max) { + if (!n) { + return '#f2f2f2'; } - return []; + var level = Math.min(1, Math.log(1 + n) / Math.log(1 + Math.max(max, 1))); + return 'hsl(207, 70%, ' + Math.round(90 - level * 55) + '%)'; } - function baseBody() { - var r = rangeOf($scope.sel.range, Date.now()); - return {since: r[0], until: r[1], school: $scope.sel.school || null, group: selectedGroup()}; + function buildHeat(rows, today) { + var byHour = {}; + var max = 0; + angular.forEach(rows, function (r) { + byHour[r.t] = r; + max = Math.max(max, r.requests); + }); + var out = []; + var d; + for (d = HEAT_DAYS - 1; d >= 0; d--) { + var day = T.addDays(today, -d); + var start = T.dayStart(day, $scope.tz); + var cells = []; + var hh; + for (hh = 0; hh < 24; hh++) { + var t = start + hh * 3600; + var r = byHour[t] || {requests: 0, blocked: 0}; + cells.push({ + t: t, hour: hh, requests: r.requests, blocked: r.blocked, + color: heatColor(r.requests, max), + title: hh + ':00 – ' + r.requests + ' ' + gettext('requests in this hour') + (r.blocked ? ', ' + r.blocked + ' ' + gettext('of them blocked') : '') + }); + } + out.push({day: day, label: T.format(start + 43200, $scope.tz, 'weekday').substring(0, 10), cells: cells}); + } + return out; } + $scope.buildHeat = buildHeat; - // The proxies' rows plus every member of the chosen group without activity (zeros), so a - // class shows all its students. + // ------------------------------------------------------------------ start page + $scope.tileVisible = function (g) { + var f = ($scope.tiles.filter || '').toLowerCase(); + return !f || g.name.toLowerCase().indexOf(f) >= 0; + }; + + $scope.findPeople = function (q) { + var params = {q: q}; + if ($scope.sel.school) { + params.school = $scope.sel.school; + } + return $http.get(API + '/people', {params: params}).then(function (resp) { + return resp.data.people || []; + }, function () { + return []; + }); + }; + + $scope.openPerson = function (p) { + go({user: p.user}); + }; + + $scope.changeSchool = function () { + go({school: $scope.sel.school}); + loadScope(); + }; + + // ------------------------------------------------------------------ class page function mergeRows(found, members) { var byUser = {}; var out = []; angular.forEach(found, function (r) { byUser[r.user] = r; - out.push(r); }); angular.forEach(members, function (m) { - if (!byUser[m.user]) { - out.push({user: m.user, display: m.display, requests: 0, domains: 0, blocked: 0, last: 0, active_now: false}); - } + var r = byUser[m.user] || {user: m.user, requests: 0, blocked: 0, last: 0, active_now: false}; + r.display = m.display; + r.role = m.role; + out.push(r); }); return out; } @@ -154,27 +347,41 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ $scope.sort.key = key; $scope.sort.reverse = key !== 'display' && key !== 'user'; } + $scope.sortKeys = [key]; }; - function loadUsers() { - $scope.busy = true; - return $http.post(API + '/query/users', baseBody()).then(function (resp) { - $scope.rows = mergeRows(resp.data.users || [], groupMembers()); - $scope.unreachable = resp.data.unreachable || []; - $scope.loadedRows = true; - }, function (resp) { - notify.error(errorText(resp)); - }).finally(function () { - $scope.busy = false; + function groupBody() { + var r = groupRange($scope.sel.range, now()); + return {since: r[0], until: r[1], school: $scope.sel.school || null, group: $scope.group, teachers: $scope.sel.teachers}; + } + + function rangeLabel(r) { + $scope.rangeText = T.format(r[0], $scope.tz, 'short') + ' – ' + T.format(Math.min(r[1], now()), $scope.tz, 'time'); + } + + function loadMembers() { + var params = {}; + if ($scope.sel.school) { + params.school = $scope.sel.school; + } + if ($scope.sel.teachers) { + params.teachers = '1'; + } + return $http.get(API + '/group/' + encodeURIComponent($scope.group.kind) + '/' + encodeURIComponent($scope.group.name) + '/members', {params: params}).then(function (resp) { + $scope.members = resp.data.members || []; + $scope.teachersHidden = resp.data.teachers_hidden || 0; }); } - function loadDomains() { + function loadGroupRows() { + var body = groupBody(); + rangeLabel([body.since, body.until]); $scope.busy = true; - return $http.post(API + '/query/domains', baseBody()).then(function (resp) { - $scope.domains = resp.data.domains || []; - $scope.unreachable = resp.data.unreachable || []; - $scope.loadedDomains = true; + return $http.post(API + '/query/users', body).then(function (resp) { + $scope.rows = mergeRows(resp.data.users || [], $scope.members); + $scope.anyActivity = (resp.data.users || []).length > 0; + $scope.loadedRows = true; + noteFailures(resp.data.unreachable); }, function (resp) { notify.error(errorText(resp)); }).finally(function () { @@ -182,206 +389,244 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ }); } - $scope.runSearch = function () { - var domain = ($scope.search.domain || '').trim(); - if (!domain) { - return; + $scope.loadAgg = function (kind) { + var a = $scope.agg[kind]; + var body = groupBody(); + var url = API + '/query/' + (kind === 'search' ? 'search' : kind); + if (kind === 'domains') { + body.hide_background = !a.background; } - var body = baseBody(); - body.domain = domain; - $scope.busy = true; - $http.post(API + '/query/search', body).then(function (resp) { - $scope.search.users = resp.data.users || []; - $scope.search.done = true; - $scope.unreachable = resp.data.unreachable || []; + if (kind === 'search') { + body.domain = (a.domain || '').trim(); + if (!body.domain) { + return; + } + } + a.loading = true; + $http.post(url, body).then(function (resp) { + a.rows = (kind === 'search' ? resp.data.users : resp.data.domains) || []; + a.loaded = true; + noteFailures(resp.data.unreachable); }, function (resp) { notify.error(errorText(resp)); }).finally(function () { - $scope.busy = false; + a.loading = false; }); }; - $scope.searchFor = function (domain) { - $scope.search.domain = domain; - $scope.tab.index = 2; - $scope.tab.name = 'search'; - $scope.runSearch(); + $scope.toggleAgg = function (kind) { + var a = $scope.agg[kind]; + a.open = !a.open; + if (a.open && !a.loaded && kind !== 'search') { + $scope.loadAgg(kind); + } }; - $scope.reload = function () { - rangeLabel(); - if ($scope.tab.name === 'overview') { - return loadUsers(); - } - if ($scope.tab.name === 'domains') { - return loadDomains(); - } - if ($scope.tab.name === 'search' && $scope.search.done) { - return $scope.runSearch(); - } - if ($scope.tab.name === 'settings') { - return $scope.loadSettings(); - } - if ($scope.tab.name === 'audit') { - return $scope.loadAudit(); - } + $scope.runSearch = function () { + $scope.loadAgg('search'); }; - $scope.selectTab = function (name) { - $scope.tab.name = name; - $scope.reload(); + $scope.searchFor = function (domain) { + if (!$scope.groupKey) { + return; + } + if ($scope.page !== 'group') { + go({group: $scope.groupKey}); + } + $scope.agg.search.open = true; + $scope.agg.search.domain = domain; + $scope.loadAgg('search'); }; $scope.setRange = function (id) { $scope.sel.range = id; + $scope.agg.blocked.loaded = false; + $scope.agg.domains.loaded = false; $scope.reload(); }; - $scope.changeGroup = function () { - $scope.rows = []; - $scope.reload(); + $scope.toggleTeachers = function () { + loadMembers().then(loadGroupRows); }; - function loadScope() { - var params = $scope.sel.school ? {school: $scope.sel.school} : {}; - return $http.get(API + '/scope', {params: params}).then(function (resp) { - $scope.info = resp.data; - $scope.loaded = true; - $scope.loadError = ''; - }, function (resp) { - $scope.loaded = true; - $scope.loadError = errorText(resp); - }); + // ------------------------------------------------------------------ student page + function dayBody(extra) { + var body = {user: $scope.person.user, day: $scope.sel.day, school: $scope.sel.school || null}; + if ($scope.sel.part === 'lesson') { + var l = lesson($scope.sel.day); + body.start = l[0]; + body.end = l[1]; + } else if ($scope.sel.part === 'hour') { + var hr = $scope.hourStart || currentHour($scope.sel.day)[0]; + body.start = hr; + body.end = hr + 3600; + } + return angular.extend(body, extra || {}); } - $scope.changeSchool = function () { - $scope.sel.group = ''; - loadScope().then(function () { - $scope.reload(); - }); - }; + function showDay(data) { + $scope.dayData = data; + $scope.person.display = data.display; + $scope.person.classes = data.classes || []; + $scope.chosenSession = null; + layoutDay(data); + $scope.refreshDomains(); + } - var live = null; - $scope.toggleLive = function () { - if (live) { - $interval.cancel(live); - live = null; - } - if ($scope.sel.live) { - live = $interval(function () { - if (!$scope.busy && ($scope.tab.name === 'overview' || $scope.tab.name === 'domains')) { - $scope.reload(); - } - }, LIVE_SECONDS * 1000); - } - }; - $scope.$on('$destroy', function () { - if (live) { - $interval.cancel(live); - } - }); + function loadDay() { + $scope.dayLoading = true; + return $http.post(API + '/query/day', dayBody()).then(function (resp) { + $scope.dayEtags = resp.data.etags; + showDay(resp.data); + noteFailures(resp.data.unreachable); + }, function (resp) { + if (resp.status === 403) { + $scope.person.denied = true; + } else { + notify.error(errorText(resp)); + } + }).finally(function () { + $scope.dayLoading = false; + }); + } - // ------------------------------------------------------------- one user - function heatColor(n, max) { - if (!n) { - return '#f2f2f2'; + function loadHeat() { + var start = T.dayStart(T.addDays($scope.today, -(HEAT_DAYS - 1)), $scope.tz); + var body = {user: $scope.person.user, since: start, until: now() + 60, resolution: 'hour', school: $scope.sel.school || null}; + if ($scope.heatEtags && $scope.heatUser === $scope.person.user) { + body.etags = $scope.heatEtags; } - var level = Math.min(1, Math.log(1 + n) / Math.log(1 + Math.max(max, 1))); - var light = Math.round(90 - level * 55); - return 'hsl(207, 70%, ' + light + '%)'; + return $http.post(API + '/query/timeline', body).then(function (resp) { + if (resp.data.not_modified) { + return; + } + $scope.heatEtags = resp.data.etags; + $scope.heatUser = $scope.person.user; + $scope.heat = buildHeat(resp.data.rows || [], $scope.today); + }, function (resp) { + if (resp.status !== 403) { + notify.error(errorText(resp)); + } + }); } - // days x hours from the hourly rows: the last HEAT_DAYS local days - function buildHeat(rows, now) { - var byHour = {}; - var max = 0; - angular.forEach(rows, function (r) { - byHour[r.t] = r; - max = Math.max(max, r.requests); - }); - var days = []; - var start = new Date(now); - start.setHours(0, 0, 0, 0); - start.setDate(start.getDate() - (HEAT_DAYS - 1)); - var names = [gettext('Sun'), gettext('Mon'), gettext('Tue'), gettext('Wed'), gettext('Thu'), gettext('Fri'), gettext('Sat')]; - var d; - for (d = 0; d < HEAT_DAYS; d++) { - var day = new Date(start.getTime()); - day.setDate(start.getDate() + d); - var cells = []; - var hh; - for (hh = 0; hh < 24; hh++) { - var at = new Date(day.getTime()); - at.setHours(hh, 0, 0, 0); - var t = Math.floor(at.getTime() / 1000); - var row = byHour[t] || {requests: 0, blocked: 0}; - cells.push({ - t: t, - requests: row.requests, - blocked: row.blocked, - color: heatColor(row.requests, max), - title: hh + ':00 – ' + row.requests + ' ' + gettext('requests in this hour') + (row.blocked ? ', ' + row.blocked + ' ' + gettext('of them blocked') : '') - }); + // live: only the minutes from the last one on (the domains and totals come whole) + function mergeLive(data) { + var since = data.minutes.length ? data.minutes[0][0] : null; + var kept = []; + angular.forEach($scope.dayData.minutes, function (m) { + if (since === null || m[0] < since) { + kept.push(m); } - days.push({label: names[day.getDay()] + ' ' + day.getDate() + '.' + (day.getMonth() + 1) + '.', cells: cells}); - } - return days; + }); + data.minutes = kept.concat(data.minutes); + showDay(data); } - $scope.buildHeat = buildHeat; + $scope.mergeLive = mergeLive; - $scope.openUser = function (r) { - var now = Date.now(); - var week = rangeOf('week', now); - var school = $scope.sel.school || null; - $scope.detail = {user: r.user, display: r.display || r.user, heat: buildHeat([], now), domains: [], minutes: [], hourT: null, unreachable: []}; - var detail = $scope.detail; - $http.post(API + '/query/timeline', {user: r.user, since: week[0], until: week[1], resolution: 'hour', school: school}).then(function (resp) { - detail.heat = buildHeat(resp.data.rows || [], now); - detail.unreachable = resp.data.unreachable || []; - }, function (resp) { - notify.error(errorText(resp)); + function liveTick() { + if ($scope.page !== 'user' || !$scope.dayData || $scope.dayLoading) { + return; + } + var cursor = $scope.dayData.cursor; + var extra = cursor ? {since_minute: cursor} : {}; + $http.post(API + '/query/day', dayBody(extra)).then(function (resp) { + if (cursor && !resp.data.not_modified) { + mergeLive(resp.data); + } else if (!resp.data.not_modified) { + showDay(resp.data); + } }); - var body = baseBody(); - body.user = r.user; - body.group = null; - $http.post(API + '/query/domains', body).then(function (resp) { - detail.domains = resp.data.domains || []; - detail.domainsLoaded = true; + } + + $scope.openSession = function (s) { + if (!s) { + $scope.chosenSession = null; + $scope.refreshDomains(); + return; + } + $scope.chosenSession = s; + if (s.data) { + $scope.refreshDomains(); + return; + } + $http.post(API + '/query/day', dayBody({start: s.start, end: s.end})).then(function (resp) { + s.data = resp.data; + if ($scope.chosenSession === s) { + $scope.refreshDomains(); + } }, function (resp) { notify.error(errorText(resp)); }); }; - $scope.openHour = function (cell) { - if (!$scope.detail || !cell.requests) { - return; - } - var detail = $scope.detail; - detail.hourT = cell.t; - detail.minutes = []; - $http.post(API + '/query/timeline', {user: detail.user, since: cell.t, until: cell.t + 3600, resolution: 'minute', school: $scope.sel.school || null}).then(function (resp) { - detail.minutes = resp.data.rows || []; + $scope.openDomain = function (d) { + var start = T.dayStart($scope.sel.day, $scope.tz); + var detail = {domain: d.domain, first: d.first, last: d.last, label: (d.category || (d.categories || [])[0]) ? $scope.categoryLabel(d.category || d.categories[0]) : '', rows: [], loading: true}; + $scope.domainDetail = detail; + $http.post(API + '/query/timeline', {user: $scope.person.user, since: start, until: T.dayStart(T.addDays($scope.sel.day, 1), $scope.tz), resolution: 'minute', domain: d.domain, school: $scope.sel.school || null}).then(function (resp) { + detail.rows = resp.data.rows || []; }, function (resp) { notify.error(errorText(resp)); + }).finally(function () { + detail.loading = false; }); }; - $scope.closeDetail = function () { $scope.detail = null; }; + $scope.goDay = function (day) { + go({user: $scope.person.user, group: $scope.groupKey || null, day: day}); + }; + $scope.shiftDay = function (n) { + $scope.goDay(T.addDays($scope.sel.day, n)); + }; + $scope.pickDate = function () { + var v = $scope.dateInput.value; + if (v instanceof Date && !isNaN(v.getTime())) { + var two = function (x) { return (x < 10 ? '0' : '') + x; }; + $scope.goDay(v.getFullYear() + '-' + two(v.getMonth() + 1) + '-' + two(v.getDate())); + } + }; + $scope.canGoBack = function () { + return !$scope.oldest || $scope.sel.day > $scope.oldest; + }; + $scope.backTitle = function () { + return $scope.canGoBack() ? '' : gettext('Older data are deleted (retention).'); + }; + $scope.setPart = function (id) { + $scope.sel.part = id; + $scope.hourStart = null; + $scope.domainDetail = {}; + loadDay(); + }; + $scope.openHour = function (row, cell) { + $scope.hourStart = cell.t; + $scope.sel.part = 'hour'; + if (row.day !== $scope.sel.day) { + $scope.pendingHour = cell.t; + $scope.goDay(row.day); + } else { + loadDay(); + } + }; - // ------------------------------------------------------------- export + // ------------------------------------------------------------------ export $scope.exportCsv = function () { + var body; + if ($scope.page === 'user') { + var r = dayBody(); + body = {since: r.start || T.dayStart($scope.sel.day, $scope.tz), until: r.end || T.dayStart(T.addDays($scope.sel.day, 1), $scope.tz), school: $scope.sel.school || null, group: $scope.group}; + } else { + body = groupBody(); + } $scope.busy = true; - $http.post(API + '/export', baseBody()).then(function (resp) { + $http.post(API + '/export', body).then(function (resp) { var blob = new $window.Blob([resp.data.csv], {type: 'text/csv;charset=utf-8'}); var link = $window.document.createElement('a'); link.href = $window.URL.createObjectURL(blob); - link.download = 'internetprotokoll.csv'; + link.download = 'internetnutzung.csv'; $window.document.body.appendChild(link); link.click(); $window.document.body.removeChild(link); - if ((resp.data.unreachable || []).length) { - notify.warning(gettext('Some proxy servers were not reachable; their data are missing.')); - } }, function (resp) { notify.error(errorText(resp)); }).finally(function () { @@ -389,86 +634,147 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ }); }; - // ------------------------------------------------- global administrators - $scope.loadSettings = function () { - return $http.get(API + '/settings').then(function (resp) { - angular.forEach(resp.data.servers, function (srv) { - angular.forEach(srv.instances, function (inst) { - inst.newRetention = inst.retention_days; - }); - }); - $scope.settings = resp.data; - $scope.unreachable = resp.data.unreachable || []; - }, function (resp) { - notify.error(errorText(resp)); - }); + // ------------------------------------------------------------------ live updates + var live = null; + var liveSince = 0; + function stopLive() { + if (live) { + $interval.cancel(live); + live = null; + } + } + function hidden() { + var doc = $document[0]; + return !!(doc && doc.hidden); + } + $scope.toggleLive = function () { + stopLive(); + $scope.liveEnded = false; + if (!$scope.sel.live) { + return; + } + liveSince = now(); + var seconds = $scope.page === 'user' ? USER_LIVE : GROUP_LIVE; + live = $interval(function () { + if (now() - liveSince > LIVE_MAX) { + stopLive(); + $scope.sel.live = false; + $scope.liveEnded = true; + return; + } + if (hidden() || $scope.busy) { + return; // paused while the tab is not visible + } + if ($scope.page === 'user') { + liveTick(); + } else if ($scope.page === 'group') { + loadGroupRows(); + } + }, seconds * 1000); }; + $scope.$on('$destroy', stopLive); - function putSettings(srv, inst, body) { - return $http.put(API + '/settings/' + encodeURIComponent(srv.connection) + '/' + encodeURIComponent(inst.name), body); + // ------------------------------------------------------------------ routing + $scope.reload = function () { + if ($scope.page === 'group') { + return loadGroupRows(); + } + if ($scope.page === 'user') { + return loadDay(); + } + }; + + function findGroup(key) { + var i = key.indexOf(':'); + if (i < 0) { + return null; + } + return {kind: key.substring(0, i), name: key.substring(i + 1)}; } - $scope.saveRetention = function (srv, inst) { - putSettings(srv, inst, {enabled: inst.enabled, retention_days: inst.newRetention}).then(function () { - notify.success(gettext('Retention saved')); - $scope.loadSettings(); - }, function (resp) { - notify.error(errorText(resp)); - }); - }; + function applyRoute() { + var s = $location.search(); + var previousPage = $scope.page; + var previousUser = $scope.person.user; + stopLive(); + $scope.sel.live = false; + $scope.groupKey = s.group || ''; + $scope.group = s.group ? findGroup(s.group) : null; + $scope.today = T.dayOf(now(), $scope.tz); + $scope.yesterday = T.addDays($scope.today, -1); + if (s.user) { + $scope.page = 'user'; + $scope.person = {user: String(s.user).toLowerCase(), display: s.user, classes: []}; + $scope.sel.day = /^\d{4}-\d{2}-\d{2}$/.test(s.day || '') ? s.day : $scope.today; + $scope.dayStartT = T.dayStart($scope.sel.day, $scope.tz); + $scope.dateInput.value = null; + $scope.domainDetail = {}; + if ($scope.pendingHour) { + $scope.hourStart = $scope.pendingHour; + $scope.pendingHour = null; + $scope.sel.part = 'hour'; + } else if (previousPage !== 'user' || previousUser !== $scope.person.user) { + $scope.sel.part = 'day'; + $scope.hourStart = null; + } + loadDay(); + if (previousUser !== $scope.person.user || !$scope.heat.length) { + $scope.heat = buildHeat([], $scope.today); + loadHeat(); + } + } else if ($scope.group) { + $scope.page = 'group'; + $scope.rows = []; + $scope.loadedRows = false; + $scope.agg.blocked = {open: false, rows: []}; + $scope.agg.domains = {open: false, rows: [], background: false}; + $scope.agg.search = {open: $scope.agg.search.open, rows: [], domain: $scope.agg.search.domain}; + loadMembers().then(loadGroupRows, function (resp) { + notify.error(errorText(resp)); + }); + } else { + $scope.page = 'start'; + noteFailures([]); + } + } - $scope.askEnable = function (srv, inst) { - $scope.enableDialog = {srv: srv, inst: inst, retention: inst.newRetention || inst.retention_days, confirmed: false, busy: false, error: ''}; - }; - $scope.closeEnable = function () { $scope.enableDialog = null; }; - $scope.confirmEnable = function () { - var dlg = $scope.enableDialog; - dlg.busy = true; - dlg.error = ''; - putSettings(dlg.srv, dlg.inst, {enabled: true, retention_days: dlg.retention, privacy_confirmed: dlg.confirmed === true}).then(function () { - $scope.enableDialog = null; - notify.success(gettext('Activity log switched on')); - $scope.loadSettings(); - }, function (resp) { - dlg.busy = false; - dlg.error = errorText(resp); - }); - }; + function oldestDay() { + // the oldest stored day of the school's instances (the ◀ limit) + $scope.oldest = $scope.info.oldest || null; + } - $scope.askDisable = function (srv, inst) { - $scope.disableDialog = {srv: srv, inst: inst, deleteData: false, busy: false, error: ''}; - }; - $scope.closeDisable = function () { $scope.disableDialog = null; }; - $scope.confirmDisable = function () { - var dlg = $scope.disableDialog; - dlg.busy = true; - dlg.error = ''; - putSettings(dlg.srv, dlg.inst, {enabled: false, delete_data: dlg.deleteData === true}).then(function () { - $scope.disableDialog = null; - notify.success(gettext('Activity log switched off')); - $scope.loadSettings(); + function loadScope() { + var params = $scope.sel.school ? {school: $scope.sel.school} : {}; + return $http.get(API + '/scope', {params: params}).then(function (resp) { + $scope.info = resp.data; + $scope.tz = resp.data.timezone || 'Europe/Berlin'; + if (!$scope.sel.school && resp.data.school && !resp.data.is_global) { + $scope.sel.school = ''; + } + oldestDay(); + $scope.loaded = true; + $scope.loadError = ''; + noteFailures(resp.data.unreachable); }, function (resp) { - dlg.busy = false; - dlg.error = errorText(resp); + $scope.loaded = true; + $scope.loadError = errorText(resp); }); - }; + } - $scope.loadAudit = function () { - var params = {days: $scope.auditForm.days || 7}; - if ($scope.auditForm.actor) { - params.actor = $scope.auditForm.actor; + $scope.$on('$routeUpdate', function () { + var school = $location.search().school || ''; + if (school !== $scope.sel.school) { + $scope.sel.school = school; + loadScope().then(applyRoute); + } else { + applyRoute(); } - return $http.get(API + '/audit', {params: params}).then(function (resp) { - $scope.audit = resp.data.entries || []; - $scope.unreachable = resp.data.unreachable || []; - }, function (resp) { - notify.error(errorText(resp)); - }); - }; + }); + $scope.sel.school = $location.search().school || ''; loadScope().then(function () { if (!$scope.loadError) { - $scope.reload(); + applyRoute(); } }); }); diff --git a/webui/lmn_squid/resources/js/filters.es b/webui/lmn_squid/resources/js/filters.es new file mode 100644 index 0000000..e3a46c7 --- /dev/null +++ b/webui/lmn_squid/resources/js/filters.es @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// ES5 on purpose (webui/build_plugin.py). German numbers and times for both pages, in the time +// zone of the proxy servers (filter_timezone; the browser may sit in another one): angular's +// number and date filters follow the WebUI's English locale ("4,642,016", "11/25/26"). +angular.module('lmn.squid').factory('lmnSquidTime', function () { + 'use strict'; + var cache = {}; + function fmt(tz, opts) { + var key = tz + '|' + angular.toJson(opts); + if (!cache[key]) { + var o = angular.copy(opts); + try { + o.timeZone = tz || undefined; + cache[key] = new Intl.DateTimeFormat('de-DE', o); + } catch (e) { + delete o.timeZone; // unknown zone: the browser's + cache[key] = new Intl.DateTimeFormat('de-DE', o); + } + } + return cache[key]; + } + var NUMERIC = {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false, weekday: 'short'}; + + // {y, mo, d, h, mi, wd} of epoch seconds t in zone tz + function parts(t, tz) { + var out = {}; + var list = fmt(tz, NUMERIC).formatToParts(new Date(t * 1000)); + var i; + for (i = 0; i < list.length; i++) { + out[list[i].type] = list[i].value; + } + return { + y: parseInt(out.year, 10), mo: parseInt(out.month, 10), d: parseInt(out.day, 10), + h: parseInt(out.hour, 10) % 24, mi: parseInt(out.minute, 10), wd: out.weekday + }; + } + + // epoch seconds of a wall-clock time in zone tz (two passes settle a DST change) + function epoch(y, mo, d, h, mi, tz) { + var wall = Date.UTC(y, mo - 1, d, h || 0, mi || 0) / 1000; + var guess = wall; + var i; + for (i = 0; i < 3; i++) { + var p = parts(guess, tz); + var seen = Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi) / 1000; + guess += wall - seen; + } + return guess; + } + + function two(n) { return (n < 10 ? '0' : '') + n; } + + function dayOf(t, tz) { + var p = parts(t, tz); + return p.y + '-' + two(p.mo) + '-' + two(p.d); + } + + function addDays(day, n) { + var d = new Date(Date.UTC(+day.substring(0, 4), +day.substring(5, 7) - 1, +day.substring(8, 10)) + n * 86400000); + return d.getUTCFullYear() + '-' + two(d.getUTCMonth() + 1) + '-' + two(d.getUTCDate()); + } + + function dayStart(day, tz) { + return epoch(+day.substring(0, 4), +day.substring(5, 7), +day.substring(8, 10), 0, 0, tz); + } + + function at(day, hhmm, tz) { + return epoch(+day.substring(0, 4), +day.substring(5, 7), +day.substring(8, 10), +hhmm.substring(0, 2), +hhmm.substring(3, 5), tz); + } + + function format(t, tz, kind) { + if (t === null || t === undefined || t === '' || isNaN(t)) { + return '–'; + } + var p = parts(+t, tz); + if (kind === 'time') { + return two(p.h) + ':' + two(p.mi); + } + if (kind === 'date') { + return two(p.d) + '.' + two(p.mo) + '.' + p.y; + } + if (kind === 'short') { + return two(p.d) + '.' + two(p.mo) + '. ' + two(p.h) + ':' + two(p.mi); + } + if (kind === 'weekday') { + return p.wd + ', ' + two(p.d) + '.' + two(p.mo) + '.' + p.y; + } + return two(p.d) + '.' + two(p.mo) + '.' + p.y + ', ' + two(p.h) + ':' + two(p.mi); + } + + return {parts: parts, epoch: epoch, dayOf: dayOf, addDays: addDays, dayStart: dayStart, at: at, format: format}; +}).filter('lmnNum', function () { + 'use strict'; + var nf = new Intl.NumberFormat('de-DE', {maximumFractionDigits: 1}); + return function (n) { + if (n === null || n === undefined || n === '' || isNaN(n)) { + return '–'; + } + return nf.format(+n); + }; +}).filter('lmnTime', function (lmnSquidTime) { + 'use strict'; + // {{t | lmnTime:tz:'datetime'|'short'|'time'|'date'|'weekday'}}; t in epoch seconds or ISO text + return function (t, tz, kind) { + if (typeof t === 'string' && t && isNaN(t)) { + t = Date.parse(t) / 1000; + } + return lmnSquidTime.format(t, tz, kind || 'datetime'); + }; +}); diff --git a/webui/lmn_squid/resources/js/routing.es b/webui/lmn_squid/resources/js/routing.es index fa40eba..f6bc3f3 100644 --- a/webui/lmn_squid/resources/js/routing.es +++ b/webui/lmn_squid/resources/js/routing.es @@ -7,6 +7,8 @@ angular.module('lmn.squid').config(function ($routeProvider) { }); $routeProvider.when('/view/lmn/squid-activity', { templateUrl: '/lmn_squid:resources/partial/activity.html', - controller: 'LMNSquidActivityController' + controller: 'LMNSquidActivityController', + // the page lives in the query string (?group=…, ?user=…&day=…): no reload on a change + reloadOnSearch: false }); }); diff --git a/webui/lmn_squid/resources/partial/activity.html b/webui/lmn_squid/resources/partial/activity.html index 2b3df12..5542b77 100644 --- a/webui/lmn_squid/resources/partial/activity.html +++ b/webui/lmn_squid/resources/partial/activity.html @@ -2,308 +2,282 @@ SPDX-FileCopyrightText: Kevin Stenzel SPDX-License-Identifier: GPL-3.0-or-later -Activity log view "Internetprotokoll" (ADR-023). Markup as in index.html (lmn73 plugins); the -page scrolls with the WebUI, only long lists scroll in their own box. Dialogs: class -lmn-squid-dialog with modal-header, modal-body and modal-footer as direct children. What a -person sees is decided by the server (activity_views.py); the page only shows it. +Internetnutzung (ADR-023): a pure view, centred on one student. One route, the page is chosen by +the query string (?group=class:5a, ?user=x&day=YYYY-MM-DD, ?search=domain&group=...), so links +open in a new tab and the browser's Back works. What a person may see is decided by the server +(activity_views.py). The page scrolls with the WebUI; no dialogs. Times in the proxies' zone. -->
{{loadError}}
-
-
+ +
+ + {{failures.length}} proxy server(s) delivered no data for this view. + Details +
    +
  • {{f.connection}}: {{failureText(f)}}
  • +
+
+ + +
+ - + -
-
- - -
-
- -
-
- - - -
- -

{{rangeText}} · Only students of your classes and projects are shown.

+ +
Choose a school to see its classes and students.
-
- Proxy server not reachable, its data are missing: {{u.connection}} – {{u.message}} +
+
+
+ + +
+
+ +
+ You are not in any class or project with students. + Join classes under "Einschreiben". +
+ +
+
+

My classes and projects

+

Classes and projects

+ +
+ +
+

+ Only students of your classes and projects are shown. + Every view of the data is recorded. +

+
-
You are not a member of any class or project with students, so there is nothing to show.
- - -
-
- - - + +
+
+ Overview + {{group.kind == 'project' ? ('Project' | translate) : ('Class' | translate)}} {{group.name}} + ({{members.length}}) +
+
+ +
+ + +
- - - - - - - - - - - - - - - - - - - - - - - -
NameLogin nameNumber of requestsDistinct domainsBlocked attemptsLast seen
{{r.display}}{{r.user}}{{r.requests | number}}{{r.domains == null ? '–' : (r.domains | number)}}{{r.blocked | number}}0{{r.last ? (r.last * 1000 | date:'dd.MM. HH:mm') : '–'}}
-

No activity in this time range.

- +
+

{{rangeText}}

+
+ + + + +
+ + + + + + + + + + + + + + + + + + + + + +
NameLogin nameLast seenNumber of requestsBlocked attempts
{{r.display}} Teacher{{r.user}}{{r.last ? (r.last | lmnTime:tz:'time') : '–'}}{{r.requests | lmnNum}}{{r.blocked | lmnNum}}0
+

No internet use in this class in this time range yet.

- -
- - - - - - - - - - - - + +
+ +
+ +

No blocked attempts in this time range.

+
Domain nameCategoryNumber of requestsDistinct usersBlocked attempts
+ + - - - - + + + - -
Domain nameCategoryStudentsBlocked attempts
{{d.domain}}{{d.category}}{{d.requests | number}}{{d.users | number}}{{d.blocked | number}}{{categoryLabel(d.category)}}{{d.users | lmnNum}}{{d.blocked | lmnNum}}
-

No activity in this time range.

-
- - -
-
- - -
- - - - - - - - - - +
NameLogin nameNumber of requestsBlocked attemptsFirst visitLast visitDistinct domains
+
+
+
+ +
+ + + + + + + + + + - - - - - - - - - +
Domain nameCategoryStudentsNumber of requestsBlocked attempts
{{d.domain}}{{categoryLabel(d.category || d.categories[0])}}{{d.users | lmnNum}}{{d.requests | lmnNum}}{{d.blocked | lmnNum}}
{{u.display}}{{u.user}}{{u.requests | number}}{{u.blocked | number}}{{u.first * 1000 | date:'dd.MM. HH:mm'}}{{u.last * 1000 | date:'dd.MM. HH:mm'}}
+
+
+
+ +
+
+ + +
+ +

Nobody in your scope was on this domain in this time range.

+ + + + + + + + - -
NameNumber of requestsBlocked attemptsFirst visitLast visitDistinct domains
{{u.display}}{{u.requests | lmnNum}}{{u.blocked | lmnNum}}{{u.first | lmnTime:tz:'short'}}{{u.last | lmnTime:tz:'short'}} {{u.domains.join(', ')}}
-

Nobody in your scope was on this domain in this time range.

- - - -
-

The activity log is off for every instance until it is switched on here. Switching it on or off restarts the instance (a few seconds). The retention applies at once.

-
-

{{srv.display_name}} {{srv.timezone}}

- - - - - - - - - - - - - - - - - - - - -
InstanceActivity logRetention (days)Stored dataConfirmed by
{{inst.name}}{{inst.enabled ? ('on' | translate) : ('off' | translate)}}{{inst.usage.days}} days of data, {{inst.usage.bytes / 1048576 | number:1}} MB{{inst.ack_by}} {{inst.ack_at}} - - - -
-
+
+
+ + +
+
This person does not belong to your classes.
+
+
+ {{group.name}}Overview + {{person.display}} + {{person.user}} · {{person.classes.join(', ')}} + +
+
+
+ + + +
+ + + +
+ +
+ + Live update ended after 15 minutes. +
- -
-
- - - - -
- - - - - - - - - - - - - - - - - - - - - - - -
Time of accessRead byRoleQuery typeWhose dataQueried time rangeProxy server
{{e.ts * 1000 | date:'dd.MM.yyyy HH:mm:ss'}}{{e.actor}}{{e.role}}{{e.action}} {{e.domain || e.user || e.instance}}{{e.scope}} ({{e.users_count}}){{e.since * 1000 | date:'dd.MM. HH:mm'}} – {{e.until * 1000 | date:'dd.MM. HH:mm'}}{{e.connection}}
-
- -
+ +
+
Active
{{durationText(dayData.totals.active_minutes)}}
+
Sessions
{{sessions.length}}
+
Distinct domains
{{dayData.totals.domains | lmnNum}}
+
Blocked attempts
{{dayData.totals.blocked | lmnNum}}
+
Last seen
{{dayData.totals.last | lmnTime:tz:'time'}}
+
+

No internet use on this day.

- - - - - - - - - - - - - - - - - +
diff --git a/webui/tests/js/activity_check.js b/webui/tests/js/activity_check.js index aa7b842..ee18cee 100644 --- a/webui/tests/js/activity_check.js +++ b/webui/tests/js/activity_check.js @@ -2,28 +2,52 @@ // SPDX-License-Identifier: GPL-3.0-or-later // // Runs the built bundle's activity controller (ADR-023) in node against stand-ins of angular, -// $http and notify: time ranges, a class with members without activity, the heat map, the -// requests the page sends. usage: node activity_check.js +// $http, $location and notify: the page from the query string, which requests each page makes +// (the start page asks no proxy for activity data), time ranges in the proxies' zone, sessions, +// the heat map, live deltas, German numbers and times. +// usage: node activity_check.js 'use strict'; const fs = require('fs'); const assert = require('assert'); -process.env.TZ = 'Europe/Berlin'; +process.env.TZ = 'America/New_York'; // the browser in another zone than the proxies const controllers = {}; +const factories = {}; +const filters = {}; const mod = { config() { return mod; }, controller(name, fn) { controllers[name] = fn; return mod; }, + factory(name, fn) { factories[name] = fn; return mod; }, + filter(name, fn) { filters[name] = fn; return mod; }, }; global.angular = { module: () => mod, isArray: Array.isArray, - copy: (x) => JSON.parse(JSON.stringify(x)), + copy: (x) => (x === undefined ? x : JSON.parse(JSON.stringify(x))), toJson: JSON.stringify, - forEach: (obj, fn) => { (obj || []).forEach ? obj.forEach(fn) : Object.keys(obj).forEach((k) => fn(obj[k], k)); }, + extend: Object.assign, + forEach: (obj, fn) => { if (!obj) { return; } if (Array.isArray(obj)) { obj.forEach(fn); } else { Object.keys(obj).forEach((k) => fn(obj[k], k)); } }, }; new Function(fs.readFileSync(process.argv[2], 'utf8'))(); const Ctrl = controllers.LMNSquidActivityController; assert(Ctrl, 'activity controller registered'); +const T = factories.lmnSquidTime(); +const lmnNum = filters.lmnNum(); +const lmnTime = filters.lmnTime(T); + +// ---- German numbers and times in the proxies' zone +assert.strictEqual(lmnNum(4642016), '4.642.016'); +assert.strictEqual(lmnNum(0.5), '0,5'); +const t0 = Date.UTC(2026, 10, 25, 9, 7) / 1000; // 10:07 in Berlin +assert.strictEqual(lmnTime(t0, 'Europe/Berlin', 'time'), '10:07'); +assert.strictEqual(lmnTime(t0, 'Europe/Berlin', 'datetime'), '25.11.2026, 10:07'); +assert.strictEqual(lmnTime('2026-11-25T11:00:53+00:00', 'Europe/Berlin', 'datetime'), '25.11.2026, 12:00'); +assert.strictEqual(T.dayOf(t0, 'Europe/Berlin'), '2026-11-25'); +assert.strictEqual(T.dayStart('2026-11-25', 'Europe/Berlin'), Date.UTC(2026, 10, 24, 23, 0) / 1000); +// across the change to summer time +assert.strictEqual(T.dayStart('2027-03-29', 'Europe/Berlin'), Date.UTC(2027, 2, 28, 22, 0) / 1000); +assert.strictEqual(T.at('2026-11-25', '07:45', 'Europe/Berlin'), Date.UTC(2026, 10, 25, 6, 45) / 1000); +assert.strictEqual(T.addDays('2026-03-01', -1), '2026-02-28'); function settled(ok, value) { return { @@ -37,79 +61,108 @@ function settled(ok, value) { }; } -const posts = []; -const scopeAnswer = { - role: 'teacher', school: 'default-school', schools: [], can_export: false, is_global: false, - groups: [{kind: 'class', name: '5a', count: 2, members: [ - {user: 's5a1', display: 'Anna'}, {user: 's5a2', display: 'Ben'}]}], -}; -const $http = { - get(url) { - assert.strictEqual(url, '/api/lmn/squid-activity/scope'); - return settled(true, {data: scopeAnswer}); - }, - post(url, body) { - posts.push([url, body]); - if (url.endsWith('/query/users')) { - return settled(true, {data: {users: [{user: 's5a1', display: 'Anna', requests: 5, blocked: 1, domains: 2, last: 1, active_now: true}], unreachable: []}}); - } - if (url.endsWith('/query/timeline')) { - return settled(true, {data: {rows: [], unreachable: []}}); - } - return settled(true, {data: {domains: [], unreachable: []}}); - }, - put() { return settled(true, {data: {}}); }, -}; -const $scope = {$on() {}}; -const notify = {error(m) { throw new Error('notify.error ' + m); }, success() {}, warning() {}}; -const $interval = () => 1; -$interval.cancel = () => {}; -Ctrl($scope, $http, $interval, {}, {set() {}}, (s) => s, notify); - -// first load: scope, then the overview of all my students for today -assert.strictEqual($scope.info.role, 'teacher'); -assert.strictEqual(posts[0][0], '/api/lmn/squid-activity/query/users'); -assert.strictEqual(posts[0][1].group, null); - -// a class: its members without activity are shown with zeros -$scope.sel.group = 'class:5a'; -$scope.changeGroup(); -const last = posts[posts.length - 1][1]; -assert.deepStrictEqual(last.group, {kind: 'class', name: '5a'}); -assert.deepStrictEqual($scope.rows.map((r) => [r.user, r.requests]), [['s5a1', 5], ['s5a2', 0]]); -assert.strictEqual($scope.rowVisible({user: 's5a2', display: 'Ben', requests: 0, blocked: 0}), true); -$scope.tableFilter.activeOnly = true; -assert.strictEqual($scope.rowVisible({user: 's5a2', display: 'Ben', requests: 0, blocked: 0}), false); +function harness(search) { + const requests = []; + let routeUpdate = null; + const answers = { + '/scope': {role: 'teacher', school: 'default-school', schools: [], is_global: false, can_export: false, + timezone: 'Europe/Berlin', lesson_hours: ['07:45', '16:00'], oldest: '2026-11-20', + category_labels: {gambling: 'Glücksspiel'}, unreachable: [], + groups: [{kind: 'class', name: '5a', count: 2, students: 2}]}, + '/group/class/5a/members': {members: [{user: 's5a1', display: 'Anna', role: 'student'}, {user: 's5a2', display: 'Ben', role: 'student'}], teachers_hidden: 0}, + '/query/users': {users: [{user: 's5a1', requests: 5, blocked: 1, last: t0, active_now: true}], unreachable: [{connection: 'old', kind: 'too_old', message: 'x'}]}, + '/query/day': {display: 'Anna', classes: ['5a'], etags: {p: '"e"'}, unreachable: [], + minutes: [[t0, 3, 0, 2], [t0 + 60, 2, 1, 1], [t0 + 600, 1, 0, 1]], + domains: [{domain: 'a.example', minutes: 2, requests: 5, blocked: 1, category: 'gambling', categories: [], background: false, first: t0, last: t0 + 60}, + {domain: 'ads.example', minutes: 1, requests: 1, blocked: 0, category: null, categories: ['ads'], background: true, first: t0, last: t0}], + other: {count: 0, requests: 0}, totals: {active_minutes: 3, requests: 6, blocked: 1, domains: 2, first: t0, last: t0 + 600}, cursor: (t0 + 600) / 60}, + '/query/timeline': {rows: [], etags: {}, unreachable: []}, + '/query/blocked': {domains: [{domain: 'a.example', blocked: 1, users: 1, category: 'gambling'}], unreachable: []}, + }; + const $http = { + get(url, cfg) { requests.push(['GET', url, cfg && cfg.params]); return settled(true, {data: answers[url.replace('/api/lmn/squid-activity', '')]}); }, + post(url, body) { requests.push(['POST', url, body]); return settled(true, {data: answers[url.replace('/api/lmn/squid-activity', '')]}); }, + }; + let current = Object.assign({}, search); + const $location = { + search(set) { + if (set === undefined) { return current; } + current = {}; + Object.keys(set).forEach((k) => { if (set[k] !== null && set[k] !== undefined && set[k] !== '') { current[k] = set[k]; } }); + if (routeUpdate) { routeUpdate(); } + return $location; + }, + }; + const $scope = {$on(name, fn) { if (name === '$routeUpdate') { routeUpdate = fn; } }}; + const $interval = () => 1; + $interval.cancel = () => {}; + const notify = {error(m) { throw new Error('notify.error ' + m); }, success() {}, warning() {}}; + Ctrl($scope, $http, $interval, $location, {}, [{hidden: false}], {set() {}}, (s) => s, notify, T); + return {$scope, requests, $location}; +} -// ranges in local time -const noon = new Date(2026, 10, 25, 12, 34, 56).getTime(); -const day = $scope.rangeOf('today', noon); -assert.strictEqual(new Date(day[0] * 1000).getHours(), 0); -const hour = $scope.rangeOf('hour', noon); -assert.strictEqual(new Date(hour[0] * 1000).getMinutes(), 0); -assert.strictEqual(new Date(hour[0] * 1000).getHours(), 12); -const week = $scope.rangeOf('week', noon); -assert.strictEqual(new Date(week[0] * 1000).getDate(), 19); -const lesson = $scope.rangeOf('lesson', noon); -assert.strictEqual(new Date(lesson[0] * 1000).getHours(), 7); -assert(lesson[1] > lesson[0]); +// ---- the start page asks for the scope only: no activity data +let h = harness({}); +assert.strictEqual(h.$scope.page, 'start'); +assert.deepStrictEqual(h.requests.map((r) => r[1]), ['/api/lmn/squid-activity/scope']); +assert.strictEqual(h.$scope.href({group: 'class:5a'}), '/view/lmn/squid-activity?group=class%3A5a'); -// heat map: 7 days x 24 hours, the hour with data coloured -const t = Math.floor(new Date(2026, 10, 25, 9, 0, 0).getTime() / 1000); -const heat = $scope.buildHeat([{t: t, requests: 10, blocked: 2}], noon); -assert.strictEqual(heat.length, 7); -assert.strictEqual(heat[6].cells.length, 24); -assert.strictEqual(heat[6].cells[9].requests, 10); -assert.strictEqual(heat[6].cells[9].blocked, 2); -assert.notStrictEqual(heat[6].cells[9].color, heat[6].cells[8].color); +// ---- a class: its members and one list query, members without activity shown with zeros +h.$location.search({group: 'class:5a'}); +assert.strictEqual(h.$scope.page, 'group'); +let urls = h.requests.slice(1).map((r) => r[1]); +assert.deepStrictEqual(urls, ['/api/lmn/squid-activity/group/class/5a/members', '/api/lmn/squid-activity/query/users']); +const usersBody = h.requests[2][2]; +assert.deepStrictEqual(usersBody.group, {kind: 'class', name: '5a'}); +assert.strictEqual(usersBody.with_domains, undefined, 'no domain count for the list'); +assert.deepStrictEqual(h.$scope.rows.map((r) => [r.user, r.requests]), [['s5a1', 5], ['s5a2', 0]]); +assert.strictEqual(h.$scope.failures[0].kind, 'too_old'); +assert.ok(/version too old/.test(h.$scope.failureText(h.$scope.failures[0]))); +// "today" starts at midnight in Berlin, whatever the browser's zone +const day = new Date(usersBody.since * 1000); +assert.strictEqual(T.format(usersBody.since, 'Europe/Berlin', 'time'), '00:00', day.toISOString()); +// aggregates only when opened +const before = h.requests.length; +h.$scope.toggleAgg('blocked'); +assert.strictEqual(h.requests.length, before + 1); +assert.strictEqual(h.requests[before][1], '/api/lmn/squid-activity/query/blocked'); -// one user: heat map and domains are asked for that user only -$scope.openUser({user: 's5a1', display: 'Anna'}); -const asked = posts.slice(-2); -assert.strictEqual(asked[0][1].user, 's5a1'); -assert.strictEqual(asked[0][1].resolution, 'hour'); -assert.strictEqual(asked[1][1].user, 's5a1'); -assert.strictEqual(asked[1][1].group, null); -$scope.closeDetail(); -assert.strictEqual($scope.detail, null); +// ---- a student: one day and one heat map +h.$location.search({user: 's5a1', group: 'class:5a'}); +assert.strictEqual(h.$scope.page, 'user'); +urls = h.requests.slice(before + 1).map((r) => r[1]); +assert.deepStrictEqual(urls, ['/api/lmn/squid-activity/query/day', '/api/lmn/squid-activity/query/timeline']); +assert.strictEqual(h.$scope.sessions.length, 2, 'a gap of 8 minutes splits the sessions'); +assert.deepStrictEqual([h.$scope.sessions[0].start, h.$scope.sessions[0].end, h.$scope.sessions[0].minutes], [t0, t0 + 120, 2]); +assert.strictEqual(h.$scope.blockedTicks.length, 1); +assert.deepStrictEqual(h.$scope.domainsShown.rows.map((d) => d.domain), ['a.example'], 'background services hidden'); +h.$scope.sel.background = true; +h.$scope.refreshDomains(); +assert.strictEqual(h.$scope.domainsShown.rows.length, 2); +assert.strictEqual(h.$scope.categoryLabel('gambling'), 'Glücksspiel'); +assert.strictEqual(h.$scope.heat.length, 7); +assert.strictEqual(h.$scope.heat[6].cells.length, 24); +// a session of 4-minute gaps stays one +assert.strictEqual(h.$scope.buildSessions([[0, 1, 0, 1], [300, 1, 0, 1]]).length, 1); +assert.strictEqual(h.$scope.buildSessions([[0, 1, 0, 1], [360, 1, 0, 1]]).length, 2); +// live delta: minutes from the cursor on replace the last ones +h.$scope.mergeLive({display: 'Anna', minutes: [[t0 + 600, 4, 0, 1], [t0 + 660, 1, 0, 1]], domains: [], other: {count: 0}, + totals: {active_minutes: 4, requests: 9, blocked: 1, domains: 2, first: t0, last: t0 + 660}, cursor: (t0 + 660) / 60}); +assert.deepStrictEqual(h.$scope.dayData.minutes.map((m) => [m[0] - t0, m[1]]), [[0, 3], [60, 2], [600, 4], [660, 1]]); +// the domain drill-down asks for that domain's minutes +h.$scope.openDomain({domain: 'a.example', first: t0, last: t0 + 60, category: 'gambling', categories: []}); +const drill = h.requests[h.requests.length - 1]; +assert.strictEqual(drill[2].domain, 'a.example'); +assert.strictEqual(drill[2].resolution, 'minute'); +assert.strictEqual(h.$scope.domainDetail.label, 'Glücksspiel'); +// a part of the day: school hours of the proxies' zone +h.$scope.setPart('lesson'); +const lessonBody = h.requests[h.requests.length - 1][2]; +assert.strictEqual(T.format(lessonBody.start, 'Europe/Berlin', 'time'), '07:45'); +assert.strictEqual(T.format(lessonBody.end, 'Europe/Berlin', 'time'), '16:00'); +// the date navigation stops at the oldest stored day +h.$scope.sel.day = '2026-11-20'; +assert.strictEqual(h.$scope.canGoBack(), false); +h.$scope.sel.day = '2026-11-21'; +assert.strictEqual(h.$scope.canGoBack(), true); console.log('activity controller ok'); diff --git a/webui/tests/js/controller_check.js b/webui/tests/js/controller_check.js index 35f0573..560678b 100644 --- a/webui/tests/js/controller_check.js +++ b/webui/tests/js/controller_check.js @@ -12,6 +12,8 @@ const controllers = {}; const mod = { config() { return mod; }, controller(name, fn) { controllers[name] = fn; return mod; }, + factory() { return mod; }, + filter() { return mod; }, }; global.angular = { module: () => mod, diff --git a/webui/tests/test_build.py b/webui/tests/test_build.py index e3f2423..e5dd52e 100644 --- a/webui/tests/test_build.py +++ b/webui/tests/test_build.py @@ -45,6 +45,7 @@ def test_build_produces_what_the_webui_serves(tmp_path: Path) -> None: "resources/css/dialogs.css", "resources/js/controllers/activity.controller.es", "resources/js/controllers/index.controller.es", + "resources/js/filters.es", "resources/js/module.es", "resources/js/routing.es", "resources/partial/activity.html", From a67c696ce87fc43a5f14651a4269c420fb17ba3d Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 14:22:32 +0100 Subject: [PATCH 16/45] feat(webui): management page with sections, one actions menu per instance, the instance as a page - Sections "Servers and instances", "Internet use: settings" and "Access log of the internet use" (E1: switching on with the privacy notice, retention, switching off with deletion; the proxies' audit log per server, 100 per page, kinds in words). A failed switch-on says that nothing changed (lab A1) instead of "500". - Toolbar in one row at 1366 px: filters, view, reload, filter per school and one "Add" menu (new instance, new VM, existing host). - One row template for both views: name (opens the instance), state with a direct "Create keytab" link when the keytab is missing, filter summary, internet use on/off with its retention, a Filter button and one actions menu (open, start/stop/restart, update/roll back, edit, delete); the server actions in one Server menu. - The instance is a page (?conn=&name=&tab=) instead of a dialog with seven tabs: Overview, Filter, Lists (blocklist, exceptions, without proxy login as pills), Logs (container, access), Internet use; reload and links keep it, Back leaves it; unsaved filter changes are not lost silently (asked before a tab change, closing or leaving). List changes apply at once. - German numbers and times in the settings (no raw UTC timestamps). --- webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 102 ++++++ webui/lmn_squid/plugin.yml | 2 + .../js/controllers/index.controller.es | 245 ++++++++++++- webui/lmn_squid/resources/partial/index.html | 339 +++++++++++------- .../resources/partial/instance-row.html | 45 +++ .../resources/partial/server-menu.html | 20 ++ webui/tests/js/controller_check.js | 58 ++- webui/tests/test_build.py | 2 + 8 files changed, 681 insertions(+), 132 deletions(-) create mode 100644 webui/lmn_squid/resources/partial/instance-row.html create mode 100644 webui/lmn_squid/resources/partial/server-menu.html diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index 3553c71..e77d342 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -1566,3 +1566,105 @@ msgstr "zu viele Personen auf einmal" msgid "version too old for this function (update linuxmuster-squid)" msgstr "Version zu alt für diese Funktion (linuxmuster-squid aktualisieren)" + +msgid "Access log of the internet use" +msgstr "Zugriffsprotokoll der Internetnutzung" + +msgid "Actions" +msgstr "Aktionen" + +msgid "Add" +msgstr "Hinzufügen" + +msgid "Class list" +msgstr "Klassenliste" + +msgid "Confirm the privacy notice first." +msgstr "Bitte zuerst den Datenschutz-Hinweis bestätigen." + +msgid "Create keytab" +msgstr "Keytab erzeugen" + +msgid "Data deleted" +msgstr "Daten gelöscht" + +msgid "Discard" +msgstr "Verwerfen" + +msgid "Discard the unsaved filter changes?" +msgstr "Ungespeicherte Filteränderungen verwerfen?" + +msgid "Export" +msgstr "Export" + +msgid "Heat map or minutes" +msgstr "Heatmap oder Minuten" + +msgid "Internet use switched off" +msgstr "Internetnutzung ausgeschaltet" + +msgid "Internet use switched on" +msgstr "Internetnutzung eingeschaltet" + +msgid "Internet use: settings" +msgstr "Internetnutzung: Einstellungen" + +msgid "Lists" +msgstr "Listen" + +msgid "Most visited domains" +msgstr "Häufigste Domains" + +msgid "No proxy instance on this server yet." +msgstr "Noch keine Proxy-Instanz auf diesem Server." + +msgid "No proxy server connected yet." +msgstr "Noch kein Proxy-Server verbunden." + +msgid "Open" +msgstr "Öffnen" + +msgid "Open the internet use view" +msgstr "Ansicht „Internetnutzung“ öffnen" + +msgid "Refused requests of the view and those without data are in the school server's system log:" +msgstr "Abgelehnte Abrufe der Ansicht und solche ohne Daten stehen im Systemprotokoll des Schulservers:" + +msgid "Server" +msgstr "Server" + +msgid "Servers and instances" +msgstr "Server und Instanzen" + +msgid "Settings changed" +msgstr "Einstellungen geändert" + +msgid "Student day" +msgstr "Schülertag" + +msgid "Switch the internet use off" +msgstr "Internetnutzung ausschalten" + +msgid "Switch the internet use on" +msgstr "Internetnutzung einschalten" + +msgid "The internet use is recorded for no instance until it is switched on here. Switching it on or off restarts the instance (a few seconds). The retention applies at once." +msgstr "Die Internetnutzung wird für keine Instanz erfasst, bis sie hier eingeschaltet wird. Ein- und Ausschalten startet die Instanz neu (einige Sekunden). Die Aufbewahrung gilt sofort." + +msgid "The internet use is stored per user, domain and minute (no full addresses). These are personal data." +msgstr "Die Internetnutzung wird je Benutzer, Domain und Minute gespeichert (keine vollständigen Adressen). Das sind personenbezogene Daten." + +msgid "The internet use was not changed; the instance runs as before." +msgstr "Die Internetnutzung wurde nicht geändert; die Instanz läuft wie vorher." + +msgid "Try again" +msgstr "Erneut versuchen" + +msgid "all kinds" +msgstr "alle Arten" + +msgid "days" +msgstr "Tage" + +msgid "live" +msgstr "live" diff --git a/webui/lmn_squid/plugin.yml b/webui/lmn_squid/plugin.yml index b17fecf..457ed2c 100644 --- a/webui/lmn_squid/plugin.yml +++ b/webui/lmn_squid/plugin.yml @@ -17,6 +17,8 @@ resources: - 'resources/js/filters.es' - 'resources/js/controllers/index.controller.es' - 'resources/partial/index.html' + - 'resources/partial/instance-row.html' + - 'resources/partial/server-menu.html' - 'resources/css/dialogs.css' - 'resources/js/controllers/activity.controller.es' - 'resources/partial/activity.html' diff --git a/webui/lmn_squid/resources/js/controllers/index.controller.es b/webui/lmn_squid/resources/js/controllers/index.controller.es index 4da2ff0..af1261b 100644 --- a/webui/lmn_squid/resources/js/controllers/index.controller.es +++ b/webui/lmn_squid/resources/js/controllers/index.controller.es @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later // ES5 on purpose (no arrow functions, template strings, let/const, classes): the package build // concatenates the sources without babel. webui/build_plugin.py refuses ES2015 syntax. -angular.module('lmn.squid').controller('LMNSquidIndexController', function ($scope, $http, $window, $interval, messagebox, pageTitle, gettext, notify) { +angular.module('lmn.squid').controller('LMNSquidIndexController', function ($scope, $http, $window, $interval, messagebox, pageTitle, gettext, notify, $location) { 'use strict'; pageTitle.set(gettext('Squid proxy')); @@ -64,7 +64,6 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco $scope.closeInstForm = function () { $scope.instForm = null; }; $scope.closeDelete = function () { $scope.deleteDialog = null; }; $scope.closeRemoveConn = function () { $scope.removeConnDialog = null; }; - $scope.closeDetail = function () { $scope.detail = null; }; function enc(value) { return encodeURIComponent(value); @@ -217,6 +216,8 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco server.version = resp.data.version; server.instances = resp.data.instances; rebuildGroups(); + loadActivity(name); + openRoutedDetail(); return server.instances; }, function (resp) { server.loading = false; @@ -716,12 +717,245 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco } }; - // ------------------------------------------- details: status, logs, lists + // ---------------------------------------- page sections (E1: internet use, its audit log) + var SECTIONS = ['servers', 'activity', 'audit']; + function route() { + return ($location && $location.search()) || {}; + } + function setRoute(params, replace) { + if (!$location) { + return; + } + var loc = $location.search(params); + if (replace && loc && loc.replace) { + loc.replace(); + } + } + $scope.section = SECTIONS.indexOf(route().section) >= 0 ? route().section : 'servers'; + $scope.setSection = function (name) { + $scope.section = name; + setRoute(name === 'servers' ? {} : {section: name}); + if (name === 'activity') { + $scope.connections.forEach(function (conn) { loadActivity(conn.name); }); + } else if (name === 'audit' && !$scope.audit.loaded) { + $scope.loadAudit(0); + } + }; + + // ---------------------------------------------- internet use per server (ADR-023) + function loadActivity(name) { + var server = $scope.servers[name] || {}; + $scope.servers[name] = server; + return $http.get(API + '/' + enc(name) + '/activity', {ignoreLoadingBar: true}).then(function (resp) { + var data = resp.data || {}; + var byName = {}; + (data.instances || []).forEach(function (a) { + a.newRetention = a.retention_days; + byName[a.name] = a; + }); + server.activity = data; + server.activityError = null; + (server.instances || []).forEach(function (inst) { inst.activity = byName[inst.name] || null; }); + if ($scope.detail && $scope.detail.conn.name === name) { + $scope.detail.activity = byName[$scope.detail.inst.name] || null; + $scope.detail.activityTz = data.timezone; + } + }, function (resp) { + server.activity = null; + server.activityError = $scope.errorText(resp); + }); + } + + function activityError(resp) { + var detail = (resp && resp.data && resp.data.detail) || {}; + if (detail.code === 'ack_missing') { + return gettext('Confirm the privacy notice first.'); + } + if (detail.code === 'apply_failed') { + return gettext('The internet use was not changed; the instance runs as before.') + ' ' + (detail.message || ''); + } + return $scope.errorText(resp); + } + + function putActivity(conn, a, body) { + return $http.put(API + '/' + enc(conn.name) + '/instances/' + enc(a.name) + '/activity', body); + } + + $scope.saveRetention = function (conn, a) { + putActivity(conn, a, {enabled: a.enabled, retention_days: a.newRetention}).then(function () { + notify.success(gettext('Retention saved')); + loadActivity(conn.name); + }, function (resp) { + notify.error(activityError(resp)); + }); + }; + $scope.askEnable = function (conn, a) { + $scope.enableDialog = {conn: conn, inst: a, retention: a.newRetention || a.retention_days, confirmed: false, busy: false, error: ''}; + }; + $scope.closeEnable = function () { $scope.enableDialog = null; }; + $scope.confirmEnable = function () { + var dlg = $scope.enableDialog; + dlg.busy = true; + dlg.error = ''; + putActivity(dlg.conn, dlg.inst, {enabled: true, retention_days: dlg.retention, privacy_confirmed: dlg.confirmed === true}).then(function () { + $scope.enableDialog = null; + notify.success(gettext('Internet use switched on')); + loadActivity(dlg.conn.name); + }, function (resp) { + dlg.busy = false; + dlg.error = activityError(resp); + }); + }; + $scope.askDisable = function (conn, a) { + $scope.disableDialog = {conn: conn, inst: a, deleteData: false, busy: false, error: ''}; + }; + $scope.closeDisable = function () { $scope.disableDialog = null; }; + $scope.confirmDisable = function () { + var dlg = $scope.disableDialog; + dlg.busy = true; + dlg.error = ''; + putActivity(dlg.conn, dlg.inst, {enabled: false, delete_data: dlg.deleteData === true}).then(function () { + $scope.disableDialog = null; + notify.success(gettext('Internet use switched off')); + loadActivity(dlg.conn.name); + }, function (resp) { + dlg.busy = false; + dlg.error = activityError(resp); + }); + }; + + // ----------------------------------------------------------- audit log (per server) + $scope.auditActions = [ + {id: 'users', label: gettext('Class list')}, + {id: 'day', label: gettext('Student day')}, + {id: 'timeline', label: gettext('Heat map or minutes')}, + {id: 'domains', label: gettext('Most visited domains')}, + {id: 'blocked', label: gettext('Blocked attempts')}, + {id: 'search', label: gettext('Domain search')}, + {id: 'export', label: gettext('Export')}, + {id: 'settings', label: gettext('Settings changed')}, + {id: 'delete_data', label: gettext('Data deleted')} + ]; + $scope.auditActionLabel = function (id) { + var found = $scope.auditActions.filter(function (k) { return k.id === id; })[0]; + return found ? found.label : id; + }; + $scope.audit = {conn: '', days: 7, actor: '', action: '', offset: 0, entries: [], total: 0, loaded: false}; + $scope.loadAudit = function (offset) { + var a = $scope.audit; + if (!a.conn && $scope.connections.length) { + a.conn = $scope.connections[0].name; + } + if (!a.conn) { + return; + } + var params = {days: a.days || 7, offset: offset || 0}; + if (a.actor) { + params.actor = a.actor; + } + a.error = null; + $http.get(API + '/' + enc(a.conn) + '/activity/audit', {params: params}).then(function (resp) { + a.entries = resp.data.entries || []; + a.total = resp.data.total || 0; + a.offset = offset || 0; + a.loaded = true; + a.tz = (($scope.servers[a.conn] || {}).activity || {}).timezone; + }, function (resp) { + a.error = $scope.errorText(resp); + }); + }; + + $scope.safesearchOn = function (inst) { + var ss = ((inst.state || {}).filter || {}).safesearch || {}; + return Object.keys(ss).some(function (k) { return ss[k] && ss[k] !== 'off'; }); + }; + + // ------------------------------------------- details: a page of its own (?conn=&name=&tab=) + var TABS = ['status', 'filter', 'blocklist', 'allowlist', 'noauth', 'logs', 'access', 'activity']; + // a thenable that goes on at once (nothing to confirm) + var GO_ON = {then: function (fn) { fn(); }}; + + function filterDirty() { + var d = $scope.detail; + return !!(d && d.tab === 'filter' && d.filter && d.filter.dirty); + } + function confirmDiscard() { + if (!filterDirty()) { + return GO_ON; + } + return messagebox.show({text: gettext('Discard the unsaved filter changes?'), positive: gettext('Discard'), negative: gettext('Cancel')}).then(function () { + $scope.detail.filter.dirty = false; + }); + } + $scope.openDetail = function (conn, inst, tab) { $scope.detail = {conn: conn, inst: inst, tab: tab || 'status', logQuery: {tail: 200, grep: ''}, newDomain: ''}; + var server = $scope.servers[conn.name] || {}; + if (server.activity) { + $scope.detail.activity = (server.activity.instances || []).filter(function (a) { return a.name === inst.name; })[0] || null; + $scope.detail.activityTz = server.activity.timezone; + } + setRoute({conn: conn.name, name: inst.name, tab: $scope.detail.tab}); $scope.loadTab($scope.detail.tab); }; + $scope.showTab = function (tab) { + if (!$scope.detail || tab === $scope.detail.tab) { + return; + } + confirmDiscard().then(function () { + setRoute({conn: $scope.detail.conn.name, name: $scope.detail.inst.name, tab: tab}, true); + $scope.loadTab(tab); + }); + }; + + $scope.closeDetail = function () { + confirmDiscard().then(function () { + $scope.detail = null; + setRoute({}); + }); + }; + + // opens the instance named in the address once its server has loaded (reload, a link) + function openRoutedDetail() { + var r = route(); + if (!r.conn || !r.name || ($scope.detail && $scope.detail.conn.name === r.conn && $scope.detail.inst.name === r.name)) { + return; + } + var conn = $scope.connByName(r.conn); + var server = $scope.servers[r.conn] || {}; + var inst = (server.instances || []).filter(function (i) { return i.name === r.name; })[0]; + if (conn && inst) { + $scope.detail = null; + $scope.openDetail(conn, inst, TABS.indexOf(r.tab) >= 0 ? r.tab : 'status'); + } + } + + $scope.$on('$routeUpdate', function () { + var r = route(); + if (!r.conn) { + $scope.detail = null; + $scope.section = SECTIONS.indexOf(r.section) >= 0 ? r.section : 'servers'; + } else if ($scope.detail && $scope.detail.conn.name === r.conn && $scope.detail.inst.name === r.name) { + if (r.tab && r.tab !== $scope.detail.tab && TABS.indexOf(r.tab) >= 0) { + $scope.loadTab(r.tab); + } + } else { + openRoutedDetail(); + } + }); + + // leaving the instance page with unsaved filter changes: ask first + $scope.$on('$locationChangeStart', function (event, next) { + if (!filterDirty() || (next || '').indexOf('tab=filter') >= 0) { + return; + } + event.preventDefault(); + confirmDiscard().then(function () { + $window.location.href = next; + }); + }); + $scope.loadTab = function (tab) { var d = $scope.detail; d.tab = tab; @@ -733,6 +967,9 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco var failed = function (resp) { d.loading = false; d.error = $scope.errorText(resp); }; if (tab === 'filter') { loadFilterTab(d); + } else if (tab === 'activity') { + d.loading = false; + loadActivity(d.conn.name); } else if (tab === 'status') { $http.get(base + '/status').then(done, failed); } else if (tab === 'logs' || tab === 'access') { @@ -757,6 +994,7 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco d.data = resp.data; d.newDomain = ''; d.dirty = true; + $scope.reloadList(); // applied at once, no second step }, function (resp) { d.error = $scope.errorText(resp) + ' ' + gettext('Enter a domain such as example.org.'); }); @@ -768,6 +1006,7 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco del(base + '/' + enc(domain)).then(function (resp) { d.data = resp.data; d.dirty = true; + $scope.reloadList(); }, function (resp) { d.error = $scope.errorText(resp); }); }; diff --git a/webui/lmn_squid/resources/partial/index.html b/webui/lmn_squid/resources/partial/index.html index 55f7fcb..fac39cc 100644 --- a/webui/lmn_squid/resources/partial/index.html +++ b/webui/lmn_squid/resources/partial/index.html @@ -12,7 +12,14 @@
{{loadError}}
-
+
+ + +
@@ -37,13 +44,14 @@ -
@@ -57,7 +65,11 @@
-
No proxy server connected yet. Enable the TLS listener on the proxy host (docs/install.md), then add it here with its URL, token and certificate fingerprint.
+
+ No proxy server connected yet. + + +
@@ -68,68 +80,29 @@ {{s}} {{servers[conn.name].version}} not reachable - -
- - - - -
+ +
-
-
{{servers[conn.name].error}}
-
-

- {{(servers[conn.name].instances || []).length}} proxy instance(s) - - - - -

- - - - - - - - - - - - - - - - - -
InstanceSchoolRolePortContainer state
{{inst.name}}{{inst.school}}{{inst.role}}{{inst.http_port}}{{stateText(inst)}} - filter problem - - -
- - - - - -
- -
-
+
+
{{servers[conn.name].error}} Try again
+
+
+ No proxy instance on this server yet. +
+ + + + + + + + + + + + +
InstanceSchoolRolePortContainer stateFilterInternet use
@@ -143,22 +116,12 @@ {{conn.display_name}} {{conn.url}} {{s}} - + {{servers[conn.name].version}} not reachable {{(servers[conn.name].instances || []).length}} proxy instance(s) - - -
- - - - - - -
- +
@@ -173,7 +136,7 @@
School {{g.school}} {{g.rows.length}} proxy instance(s) - +
No proxy instance for this school yet. @@ -185,44 +148,95 @@ Role Port Container state + Filter + Internet use - - - {{row.inst.name}} - {{row.conn.display_name}} - {{row.inst.role}} - {{row.inst.http_port}} - {{stateText(row.inst)}} - filter problem - - - -
- - - - - -
- + + +
+
+
+ + +
+

The internet use is recorded for no instance until it is switched on here. Switching it on or off restarts the instance (a few seconds). The retention applies at once.

+
+
+ {{conn.display_name}} + {{servers[conn.name].activity.timezone}} · School hours {{servers[conn.name].activity.lesson_hours.join('–')}} + {{servers[conn.name].activityError}} +
+ + + + + + + + + + + + + + + +
InstanceInternet useRetention (days)Stored dataConfirmed by
{{a.name}}{{a.enabled ? ('on' | translate) : ('off' | translate)}} + + + {{a.usage.days | lmnNum}} days · {{a.usage.bytes / 1048576 | lmnNum}} MB{{a.ack_by}}, {{a.ack_at | lmnTime:servers[conn.name].activity.timezone:'datetime'}} + +
+ + +
+
+ + + + + + + +
+
{{audit.error}}
+ + + + + + + + + + + + + + + + + +
Time of accessRead byRoleQuery typeWhose dataQueried time range
{{e.ts | lmnTime:audit.tz:'datetime'}}{{e.actor}}{{e.role}}{{auditActionLabel(e.action) | translate}} {{e.domain || e.user || e.instance}} live{{e.scope}} ({{e.users_count | lmnNum}}){{e.since | lmnTime:audit.tz:'short'}} – {{e.until | lmnTime:audit.tz:'short'}}
+

No entries.

+
+ + {{audit.offset + 1 | lmnNum}}–{{audit.offset + audit.entries.length | lmnNum}} / {{audit.total | lmnNum}} + +
+

Refused requests of the view and those without data are in the school server's system log: journalctl -t lmn-squid-activity

+
@@ -565,20 +579,35 @@

Delete instance {{deleteDialog.inst.name}} ({{deleteD

- - + @@ -962,3 +1007,47 @@
Own sources a
+ + + + + + + + + + + + + + diff --git a/webui/lmn_squid/resources/partial/instance-row.html b/webui/lmn_squid/resources/partial/instance-row.html new file mode 100644 index 0000000..c9d3abf --- /dev/null +++ b/webui/lmn_squid/resources/partial/instance-row.html @@ -0,0 +1,45 @@ + +{{row.inst.name}} +{{row.inst.school}} +{{row.conn.display_name}} +{{row.inst.role}} +{{row.inst.http_port}} + + {{stateText(row.inst)}} + Create keytab + + + {{row.inst.state.filter.categories}} categories · SafeSearch + not set up + filter problem + + + {{'on' | translate}} · {{row.inst.activity.retention_days}} days + {{'off' | translate}} + + + + + + diff --git a/webui/lmn_squid/resources/partial/server-menu.html b/webui/lmn_squid/resources/partial/server-menu.html new file mode 100644 index 0000000..60be398 --- /dev/null +++ b/webui/lmn_squid/resources/partial/server-menu.html @@ -0,0 +1,20 @@ + + diff --git a/webui/tests/js/controller_check.js b/webui/tests/js/controller_check.js index 560678b..8b5ff2e 100644 --- a/webui/tests/js/controller_check.js +++ b/webui/tests/js/controller_check.js @@ -37,7 +37,7 @@ function settled(ok, value) { }; } -function harness(routes, stored) { +function harness(routes, stored, opts) { const calls = []; const bodies = []; const respond = (method, url, body) => { @@ -61,14 +61,17 @@ function harness(routes, stored) { const scope = {$watch: (expr, fn) => watchers.push(fn), $on() {}}; const notes = []; const notify = {success: (t) => notes.push(['ok', t]), warning: (t) => notes.push(['warn', t]), error: (t) => notes.push(['err', t])}; - const messagebox = {show: () => settled(true)}; + const shows = []; + const messagebox = {show: (o) => { shows.push(o); return settled(!opts || opts.confirm !== false); }}; const intervals = []; const $interval = (fn) => { intervals.push(fn); return fn; }; $interval.cancel = (fn) => { const i = intervals.indexOf(fn); if (i >= 0) { intervals.splice(i, 1); } }; - controllers.LMNSquidIndexController(scope, $http, $window, $interval, messagebox, {set() {}}, (s) => s, notify); + let search = {}; + const $location = {search(set) { if (set === undefined) { return search; } search = Object.assign({}, set); return {replace() {}}; }}; + controllers.LMNSquidIndexController(scope, $http, $window, $interval, messagebox, {set() {}}, (s) => s, notify, $location); const digest = () => watchers.forEach((fn) => fn()); const tick = () => intervals.slice().forEach((fn) => fn()); - return {scope, calls, bodies, store, notes, digest, tick, intervals, routes}; + return {scope, calls, bodies, store, notes, digest, tick, intervals, routes, shows}; } const SCHEMA = {instance: {properties: { @@ -452,4 +455,51 @@ fs_.detail.filter.catalog.categories.filter((c) => c.defaultVariant).forEach((c) assert.ok(c.id in fs_.detail.filter.variants, 'variant chosen for ' + c.id); }); +// --- round 2: internet use settings (E1), audit, the instance as a page, unsaved filter guard -- +const ACT = Object.assign({}, ROUTES, { + 'GET /api/lmn/squid/a/activity': {status: 200, data: {timezone: 'Europe/Berlin', lesson_hours: ['07:45', '16:00'], instances: [ + {name: 'default-school-teachers', enabled: false, retention_days: 7, usage: {days: 0, bytes: 0}}]}}, + 'PUT /api/lmn/squid/a/instances/default-school-teachers/activity': {status: 500, data: {error: 'http', status: 500, detail: {code: 'apply_failed', message: 'activity log not changed: x'}}}, + 'GET /api/lmn/squid/a/activity/audit': {status: 200, data: {total: 1, entries: [{ts: 1, actor: 'dslehr01', action: 'day'}]}}, + 'GET /api/lmn/squid/a/instances/default-school-teachers/status': {status: 200, data: {exists: true}}, +}); +const ha = harness(ACT, {}); +const sa = ha.scope; +const teachers = sa.servers.a.instances.find((i) => i.name === 'default-school-teachers'); +assert.strictEqual(teachers.activity.enabled, false, 'the row knows the internet use state'); +sa.askEnable(sa.connections[0], sa.servers.a.activity.instances[0]); +sa.enableDialog.confirmed = true; +sa.confirmEnable(); +const put = ha.bodies[ha.calls.indexOf('PUT /api/lmn/squid/a/instances/default-school-teachers/activity')]; +assert.deepStrictEqual(put, {enabled: true, retention_days: 7, privacy_confirmed: true}); +assert.ok(/not changed; the instance runs as before/.test(sa.enableDialog.error), sa.enableDialog.error); +sa.setSection('audit'); +assert.strictEqual(sa.audit.entries.length, 1); +assert.strictEqual(sa.auditActionLabel('day'), 'Student day'); +// the instance page: opened from the address after its server loaded +let hd = harness(ACT, {}); +hd.scope.openDetail(hd.scope.connections[0], teachers, 'status'); +assert.ok(hd.scope.detail); +hd.scope.showTab('blocklist'); +assert.strictEqual(hd.scope.detail.tab, 'blocklist'); +hd.scope.closeDetail(); +assert.strictEqual(hd.scope.detail, null); +// unsaved filter changes: the guard asks; "cancel" keeps the page and the changes +hd = harness(ACT, {}, {confirm: false}); +hd.scope.openDetail(hd.scope.connections[0], teachers, 'status'); +hd.scope.detail.tab = 'filter'; +hd.scope.detail.filter = {dirty: true}; +hd.scope.closeDetail(); +assert.strictEqual(hd.shows.length, 1); +assert.ok(hd.scope.detail && hd.scope.detail.filter.dirty, 'cancel keeps the unsaved changes'); +hd.scope.showTab('status'); +assert.strictEqual(hd.scope.detail.tab, 'filter'); +// confirmed: leaves +hd = harness(ACT, {}); +hd.scope.openDetail(hd.scope.connections[0], teachers, 'status'); +hd.scope.detail.tab = 'filter'; +hd.scope.detail.filter = {dirty: true}; +hd.scope.closeDetail(); +assert.strictEqual(hd.scope.detail, null); + console.log('controller checks: ok'); diff --git a/webui/tests/test_build.py b/webui/tests/test_build.py index e5dd52e..850e17a 100644 --- a/webui/tests/test_build.py +++ b/webui/tests/test_build.py @@ -50,6 +50,8 @@ def test_build_produces_what_the_webui_serves(tmp_path: Path) -> None: "resources/js/routing.es", "resources/partial/activity.html", "resources/partial/index.html", + "resources/partial/instance-row.html", + "resources/partial/server-menu.html", "runtime.py", "setup_runner.py", "sitefacts.py", From 9bf28d0a3eb9835a6019ee71227523f1d228424c Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 14:27:20 +0100 Subject: [PATCH 17/45] docs: ADR-023 addendum (E1-E4, the student-centred view, performance, lab fixes), operations, threat model, test strategy, changelog; load script measures the new queries The load script measures the day query, the drill-down, blocked attempts, the one-statement partial-day search and the same queries through the API including the audit line; --queries-only reuses generated data. --- README.md | 2 +- debian/changelog | 34 ++++++--- docs/decisions.md | 52 ++++++++++++- docs/operations.md | 77 +++++++++++++++----- docs/test-strategy.md | 25 +++++-- docs/threat-model.md | 4 +- scripts/tests/activity_load.py | 129 ++++++++++++++++++++++++++++++++- 7 files changed, 279 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 44593b5..afbb257 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ the same AD/Kerberos infrastructure the school already operates. - **WebUI plugin (optional):** `linuxmuster-squid-webui` adds the page *Squid proxy* to the linuxmuster.net 7.3 WebUI for global administrators; it manages one or more proxy hosts over their opt-in TLS listener with a pinned certificate. - A second page *Internetprotokoll* shows the optional activity log (ADR-023, off by default per + A second page *Internetnutzung* (under Klassenzimmer) shows the optional activity log (ADR-023, off by default per instance, domain and minute, no URLs): teachers see the students of their own classes and projects, school administrators their school, global administrators everything; every access is audited. diff --git a/debian/changelog b/debian/changelog index 30ad00d..7ef6200 100644 --- a/debian/changelog +++ b/debian/changelog @@ -169,17 +169,29 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium through the API and "lmnsquid activity ..." are limited and written to an audit log first (kept 365 days, activity_audit_retention_days). Takes effect with a data-plane image built from this release; an - instance is restarted once when the log is switched on or off. - * WebUI plugin: new page "Internetprotokoll" (permission - lm:squid:activity) for teachers, school and global administrators: - per class or project the students with activity now/today, requests, - domains and blocked attempts, top domains, "who was on X", a heat map - of the last 7 days per student with the minutes of an hour, live - reload, CSV export for administrators; settings with the privacy - notice and the audit log for global administrators. Teachers see only - students of their own classes and projects, school administrators - their school; the server decides this from the AD on every request. - Log out and in again after the upgrade (new permission). + instance is restarted once when the log is switched on or off (a + failure changes nothing). The collector logs only runs that stored + something. + * WebUI plugin: new page "Internetnutzung" under Klassenzimmer + (permission lm:squid:activity) for teachers, school and global + administrators, centred on one student: find a student or open a + class; a class lists its students (last seen, requests, blocked + attempts) with its blocked attempts, most used domains and "who was + on ..." on request; a student's page shows one day as sessions with + blocked minutes, the domains with their minutes and category, a 7-day + heat map and date navigation; live updates pause while the tab is + hidden. CSV export for administrators. Teachers see only students of + their own classes and projects, school administrators their school + (teachers of a class on request); the server decides this from the AD + on every request, and logs every request of the page to the system log + (journalctl -t lmn-squid-activity). Log out and in again after the + upgrade (new permission). + * WebUI plugin, page "Squid proxy": sections for the internet use + settings (switching on with the privacy notice, retention, switching + off with deletion) and its access log; one actions menu per instance; + the instance opens as a page with Overview, Filter, Lists, Logs and + Internet use (no more dialog with seven tabs); unsaved filter changes + are no longer lost silently; list changes apply at once. -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium diff --git a/docs/decisions.md b/docs/decisions.md index 3972ec9..042ed6b 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -665,7 +665,7 @@ for, time range, instances, the users list up to 200 names, the user of a timeli search); a query whose audit line cannot be written is refused (503). Own retention (`activity_audit_retention_days`, default 365). `GET /v1/activity/audit`; in the WebUI only for global administrators. -**WebUI:** a second page "Internetprotokoll" with its own permission `lm:squid:activity` (true for +**WebUI:** a second page (first "Internetprotokoll", now "Internetnutzung", see the addendum) with its own permission `lm:squid:activity` (true for globaladministrator, schooladministrator and teacher); the management keeps its global-admin-only permissions. The scope is computed on the school server from the AD on every request (cached 10 s for the person, 60 s for the school's users), the way the official plugins read it @@ -698,6 +698,56 @@ is known. **Price:** a few minutes of the day can sit in the spool when the coll (the receiver stops accepting at 1 GiB waiting per instance); a multi-day query opens one file per day and instance. +**Addendum (2026-11-25, Kevin: "improve all views, the menu etc. again, centre the view of the web +sites on individual students, mind performance when viewing"; spec +`work/linuxmuster-squid/ux-ueberarbeitung.md`, lab test `lab-activity-2026-11-25.md`):** +- **E1:** the settings (switching on with the privacy notice, retention, switching off with + deletion) and the proxies' audit log moved into the management page *Squid proxy* (global + administrators): sections "Internet use: settings" and "Access log of the internet use", and + the instance's tab "Internet use". The activity page is a pure view (supersedes deviation 3). +- **E2:** the menu entry is *Internetnutzung* (msgid "Internet use") under upstream's category + *Klassenzimmer* (`category:class`, weight 30, after *Einschreiben*); the management stays under + *Software*. Category, name and weight are kept in one place (`webui/lmn_squid/main.py`), since + upstream's category name cannot be changed by the plugin. +- **E3:** for school and global administrators the teachers of a class are hidden unless "show + teachers" is chosen (amends deviation 4); a teacher never sees teachers. +- **E4:** every query stays one audit line, also the live updates (no merging); live updates are + sparing instead: only the visible student (30 s, a delta of minutes) or class list (60 s), + paused while the tab is hidden, ended after 15 minutes. +- **The view, centred on one student:** start page = find a student (from the AD, no proxy + request) and tiles of the person's classes and projects; no "all users" query any more by + default. Class = one cheap list from the hour table (no distinct-domain count) plus blocked + attempts, top domains and "who was on …" of the class, each on request. Student page = one + `POST /v1/activity/day` (the active minutes and the domains with their minutes, from the + primary key user + minute only; sessions are computed by the browser from the minutes, gaps up + to 4 minutes) plus one hourly timeline for the 7-day heat map; a domain's minutes on click + (timeline per minute with a domain). Categories also for allowed domains (catalog and own + lists, looked up for the shown domains only) with a background flag (catalog groups ads, + telemetry), labels from the catalog description. +- **Performance:** the WebUI caches the computed scope (10 s), a project's member groups (300 s) + and every proxy's light overview (`GET /v1/activity?usage=false`, 60 s, dropped on a settings + change), never activity data; one request per proxy and view; all proxies in parallel from one + pool with an overall deadline of 5 s (2 s connect, 5 s read); a failure is typed (unreachable, + timeout, too old, token, certificate, limit with the proxy's code, error). Day and timeline + answers carry an ETag; a repeated request is audited and then answered 304 (the browser keeps + its copy). The domain search over a partial day is one statement instead of one per candidate. + Queries over 1 s are logged without names. Measured numbers: operations.md. +- **Lab findings fixed:** (A1) the spool is 1733 without a set-group-id bit, the receiver's files + 0644 behind the 0750 parent: the service's `RestrictSUIDSGID=yes` refused 3733 and switching on + ended in a 500; switching on or off now writes the definition only after the container matches + it (a failure changes nothing and says so), and switching on again applies a definition the + container lacks; switching off removes the empty spool. (A2) limits and errors of a proxy reach + the page with their reason; an export is refused as a whole when a proxy cannot deliver its + part. (A4) the WebUI writes every request of the view, refused ones and those that needed no + proxy included, to the system log (tag `lmn-squid-activity`, authpriv). One HTTPS visit is one + request: squid's `NONE_NONE` side line (SNI peek, error page of a refused CONNECT; logged by + squid 6.14 next to the CONNECT) goes with its CONNECT line and only marks it blocked. The + collector unit runs with `LogLevelMax=notice`, so idle runs (every 30 s) leave no journal lines. +- **Not done (spec "Could"):** filter tab in two columns with a sticky save bar, filter per school + as a matrix tab, setup wizard in steps, own lists with generated ids, bulk dialog with selects, + TLS connection reuse, "active now" on the class tiles (it would read activity data on the start + page). + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/operations.md b/docs/operations.md index 2a8ce00..4c4071c 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -683,19 +683,28 @@ lmnsquid activity disable default-school-students [--delete-data] lmnsquid activity delete-data default-school-students ``` -or in the WebUI, page *Internetprotokoll*, tab *Einstellungen* (global administrators). Switching +or in the WebUI, page *Squid proxy* (Software), section *Internet use: settings*, or the tab +*Internet use* of an instance (global administrators). A switch-on that fails (the container does +not come up, the spool cannot be made) changes nothing and says why; switching on again applies +a definition the running container lacks. Switching on needs the confirmation of the privacy notice (below); who confirmed it and when is stored in the instance definition (`activity_ack_by`, `activity_ack_at`, in its git change log). Needs a data-plane image built from 7.3.11 or later (`image_capable` in `GET /v1/instances//activity`). **Where the data are:** squid sends each line over UDP to a receiver in the container, which writes finished files into `/var/spool/linuxmuster-squid/activity//` (at the latest every -30 s); `linuxmuster-squid-activity.timer` runs `lmnsquid-activity collect` every 30 s as -`lmnsquid`, which sums them into `/var/lib/linuxmuster-squid/activity//.sqlite` -(local day of `filter_timezone`) and deletes them. Data appear in queries about 30–70 s after -the request. `journalctl -u linuxmuster-squid-activity` shows one line per run with work -(files, lines, used, without user, broken, too old). If the collector stops, the receiver keeps -at most 1 GiB per instance waiting and then drops new lines (logged in the container log). +30 s; the directory is 1733, the files 0644, behind `/var/spool/linuxmuster-squid` 0750 +lmnsquid; no set-group-id bit, which the service's `RestrictSUIDSGID=yes` refuses); +`linuxmuster-squid-activity.timer` runs `lmnsquid-activity collect` every 30 s as `lmnsquid`, +which sums them into `/var/lib/linuxmuster-squid/activity//.sqlite` (local day +of `filter_timezone`) and deletes them. Data appear in queries about 30–70 s after the request. +`journalctl -u linuxmuster-squid-activity` shows only runs with work (files, lines, used, without +user, side lines, broken, too old) and errors; idle runs leave nothing, also not systemd's +"Starting/Finished" lines (`LogLevelMax=notice`). An HTTPS visit is one request: squid's +`NONE_NONE` side line (the SNI peek, the error page of a refused CONNECT) goes with its CONNECT +line. If the collector stops, the receiver keeps at most 1 GiB per instance waiting and then +drops new lines (logged in the container log). The spool of an instance whose log is off is +removed once empty. **Retention:** 1–365 days per instance (default 7; 1 = today only). Whole day files are deleted by the collector; a query never reads a file older than the retention, even before it is @@ -703,9 +712,13 @@ deleted. Switching off keeps the data until they expire, unless deleted at once. deletes the instance's activity data (also with `--keep-logs`); `apt-get purge` deletes all. **Queries** (API, CLI, WebUI), always with a time range: users active in the range -(`lmnsquid activity users --range today|hour|7d|30d [--user …]`), one user's timeline per hour or -per minute (`timeline [--minute]`), top domains (`domains`), who was on a domain or a -subdomain of it (`search `), CSV per minute (`export`, at most 31 days). Limits: 366 days +(`lmnsquid activity users --range today|hour|7d|30d [--user …]`), one user's day with active +minutes and domains (`day [--date YYYY-MM-DD]`), one user's timeline per hour or per minute +(`timeline [--minute [--domain d]]`), top domains (`domains`), blocked attempts per domain +(`blocked`), who was on a domain or a subdomain of it (`search `), CSV per minute +(`export`, at most 31 days). Domains carry the catalog's categories (also when allowed) and a +background flag (ads, trackers, telemetry). "School hours" of the view: `activity_lesson_hours` +in config.yml (default `07:45-16:00`, local time of `filter_timezone`). Limits: 366 days per query (minute timeline 2 days), 10 000 users per request, 1 million export rows, 20 s per query ("query too large": choose a shorter range or fewer users). @@ -714,17 +727,32 @@ query ("query too large": choose a shorter range or fewer users). (the WebUI user, or `cli:`), role, what for (class, project, user), time range, instances, the users (up to 200 names), the domain of a search. A query whose audit line cannot be written is refused. Kept `activity_audit_retention_days` days (config.yml, default 365, 1–3650). -`lmnsquid activity audit [--days 30] [--actor …]`; in the WebUI tab *Zugriffsprotokoll* (global -administrators only). +`lmnsquid activity audit [--days 30] [--actor …]`; in the WebUI page *Squid proxy*, section +*Access log of the internet use* (global administrators only). The WebUI writes its own line for +every request of the view, also for refused ones and for those that needed no proxy (an empty +scope), to the school server's system log: `journalctl -t lmn-squid-activity` (facility +authpriv). + +**The view in the WebUI:** *Internetnutzung* under *Klassenzimmer* (teachers, school and global +administrators). Start: find a student, or a tile per class or project; a class lists its +students (last seen, requests, blocked attempts), with the blocked attempts, the most used +domains and "who was on …" of the class on request; a student's page shows one day (date +navigation down to the oldest stored day; whole day, school hours, this hour) as sessions with +blocked minutes, the domains with their active minutes and category, a domain's minutes, and a +heat map of 7 days. Live updates (class 60 s, student 30 s as a delta) pause while the tab is +hidden and end after 15 minutes. **Who sees what in the WebUI** (decided on the school server from the AD on every request, never -in the browser): global administrators everything (optionally one school); school administrators -every user of their school; teachers only users with the role student of their own school who are -in a class or project the teacher is a member or admin of (also through a project's member -groups), never other teachers; students and every other role nothing. Export only for school and -global administrators. Only the proxies whose instances belong to the school are asked; one that -does not answer is named on the page. With several proxy servers the domain counts per user are -added up per server. +in the browser): global administrators everything (one school at a time); school administrators +every user of their school (teachers of a class only with "Lehrkräfte anzeigen"); teachers only +users with the role student of their own school who are in a class or project the teacher is a +member or admin of (also through a project's member groups), never other teachers; students and +every other role nothing. Export only for school and global administrators; it is refused as a +whole when a proxy cannot deliver its part. Only the proxies whose instances belong to the school +are asked, all at once with a deadline of 5 s; one that does not answer in time, refuses or +reports a limit is named with the reason. With several proxy servers the domain counts per user +are added up per server. The WebUI caches the scope (10 s) and the proxies' instance lists (60 s), +never activity data: every read is audited on the proxy. **Load (measured locally, `scripts/tests/activity_load.py`):** 1000 students, 8 school hours a day, about 2.5 million requests per day (5 days a week in practice; measured with 7 days in a row), @@ -733,7 +761,7 @@ Xeon E5-2609 v3 1.9 GHz, one core, SSD, 2026-11-25: | What | Measured | |---|---| | collector, one 30-second file (≈ 2 600 lines, what the timer sees at peak) | 0.05 s (+ ≈ 0.3 s Python start) | -| collector, a whole day as a backlog (960 files, 2.5 million lines) | 66 s, RSS 44 MiB | +| collector, a whole day as a backlog (960 files, 2.5 million lines) | 66 s, RSS 44 MiB (69 s since HTTPS side lines are paired, 2026-11-25) | | day file | 28.7 MiB (957 000 minute rows, 91 500 user-domain rows, 17 600 domains) | | overview of a class (30 students), today / 90 minutes / 7 days | 0.007 / 0.013 / 0.055 s | | one student: 7 days per hour (heat map) / one hour per minute / one day per minute | 0.006 / 0.001 / 0.005 s | @@ -742,6 +770,15 @@ Xeon E5-2609 v3 1.9 GHz, one core, SSD, 2026-11-25: | all 1000 users today / 7 days (with distinct domains; 7 days without them 0.06 s) | 0.21 / 1.49 s | | top domains of everyone today / who of everyone was on a domain today | 0.35 / 0.012 s | | CSV of a class for a day (28 500 rows) | 0.28 s | +| **student page:** one day / school hours / live delta (answer 24.5 KiB) | 0.004 / 0.004 / 0.004 s | +| **student page:** one domain's minutes of a day | 0.002 s | +| **class list** without domain counts (30 students, today) | 0.002 s | +| blocked attempts of a class today / "who was on" in 90 minutes (one statement) | 0.007 / 0.012 s | +| through the API incl. the audit line: class list / day / heat map 7 days / blocked | 0.012 / 0.014 / 0.015 / 0.017 s | + +The WebUI adds its TLS round trip per proxy and the AD scope (cached; a school of 1000 users, +40 classes, 20 projects: `/scope` < 50 ms warm, < 20 KB, `webui/tests/test_activity_views.py`); +the lab measures the end-to-end times. **Disk:** about 29 MiB per school day per 1000 active students at this rate, i.e. with 190 school days a year about 5.5 GiB per 1000 students at 365 days' retention (10.5 GiB if every diff --git a/docs/test-strategy.md b/docs/test-strategy.md index 22e1a60..68d6d29 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -240,8 +240,12 @@ acceptance list in `deployment-gpo.md`. `%40`, blocked by 403/TCP_DENIED/category, no user; broken and cut lines counted; collector: per-minute sums, a file collected twice counted once, restart between files, stale parts taken once under the finished file's name, split at local midnight, future lines, retention by whole - day files and dropped old lines, spool mode 3733, purge, lock; the image's UDP receiver as a - process: finished files on time and on SIGTERM, mode 0640, lines dropped while 1 GiB waits, + day files and dropped old lines, spool mode 1733 never with a set-id bit (mocked, and run by + `systemd-run --user` with the service's own restrictions incl. `RestrictSUIDSGID=yes`, which + refuses the old 3733), purge, lock, one HTTPS visit = one request (squid 6.14's side lines), + the empty spool of a disabled instance removed, day/blocked/drill-down queries, categories of + allowed domains and the background flag; the image's UDP receiver as a + process: finished files on time and on SIGTERM, mode 0644, lines dropped while 1 GiB waits, survives a missing directory; queries: scope by user list, partial and whole days, active now, hour and minute timeline, top domains with users and category, subdomain search with literal LIKE characters, CSV, limits, time budget, retention also before deletion), @@ -250,15 +254,24 @@ acceptance list in `deployment-gpo.md`. every query audited with person/scope/users before reading, unwritable audit log → 503, input checks, 401/403, the instance's deletion removes its activity data, PATCH cannot switch it on, spool mounted only while on and the fingerprint independent of retention), `test_cli.py` - (`lmnsquid activity …`), webui `test_activity_views.py` (real control plane, fake AD shaped like + (`lmnsquid activity …`), `test_activity_api.py` round 2 (a failed switch-on changes nothing and + names the cause, switching on again applies a missing log, the empty spool goes on switching + off, the light overview, day query audited and 304 after the audit, blocked and drill-down, + limit codes), webui `test_activity_views.py` (real control plane, fake AD shaped like linuxmusterTools: teacher sees only students of own classes and projects incl. a project's member group, never a teacher of the same class, never another school, role groups ignored; out-of-scope group/user/school 403 before any proxy is asked; school administrator the whole school, export allowed, audit not; students/staff 403 also with the permission granted by hand; role from the AD not the session; global settings with the confirmation; a proxy that does not - answer is named; CSRF), `test_permissions.py` (`lm:squid:activity` for the three roles only, - management unchanged), node `webui/tests/js/activity_check.js` (ranges, class members without - activity, heat map). **E2E** (`squid-filter` with `ACTIVITY_LOG_ENABLED=1`): the spool holds + answer is named; CSRF; round 2: people search only in the scope and without proxy request, + teachers of a class only on request for administrators, the day merged and revalidated, limits + named as limits, export refused when a proxy cannot deliver, refused and empty-scope requests in + the system log, a hanging proxy costs at most the deadline, `/scope` of 1000 users < 50 ms and + < 20 KB), `test_permissions.py` (`lm:squid:activity` for the three roles only, + management unchanged), node `webui/tests/js/activity_check.js` (the page from the query string and the requests each + page makes, ranges in the proxies' zone from a browser in another zone, sessions, heat map, + live delta, German numbers and times), `controller_check.js` (settings and audit in the + management, the instance page and the unsaved-changes guard). **E2E** (`squid-filter` with `ACTIVITY_LOG_ENABLED=1`): the spool holds the Kerberos user, the domain, 403 and the category of a blocked request, no URL and no client address; the production collector turns it into a day file and empties the spool. Measured locally with squid 6.14: a killed receiver does not stop squid (the `daemon:` module did). diff --git a/docs/threat-model.md b/docs/threat-model.md index dc458f8..9d5280d 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -45,8 +45,8 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T22 | **Helper denial of service / crash** (ADR-022): many distinct host names (cache misses), a hand-broken `filter.json`, a damaged catalog, a crashing helper making the deny line be skipped (squid treats a helper error like "no match") | the helper never answers `BH`: any internal error gives the fail-closed answer when a youth protection category is active, else no block, and is logged in `cache.log`; squid caches answers 60 s and runs up to 4 + 2 helper processes per instance (measured 13 000–14 000 lookups/s per process); squid restarts helpers that exit; a broken `filter.json` (only written atomically by the control plane) fails closed; the catalog is opened read-only (`immutable`) so a container cannot write it (read-only mount) | controlplane/tests/test_filter_helper.py (protocol, broken files, fail-closed, rate); measured in the image (work/tasks/squid-filterkategorien.md) | | T23 | **Fail-open vs. fail-closed of the filter** (ADR-022): during a missing catalog youth protection would silently stop | SafeSearch switched on for an engine without any known address blocks that engine (`safesearch_unresolved`) instead of leaving it unfiltered; an image without the filter is reported (`image_without_filter`), not shown as filtering; fail-closed for the categories marked `fail_closed` (youth protection): every request but exceptions and the protected list refused while the catalog is unusable, shown in `status`/WebUI; other categories fail open (ads, telemetry, distraction: availability first). The noauth path is filtered too (T16 amended). Bypass of the proxy (direct 443/853/QUIC) defeats every filter and SafeSearch: firewall's job (operations.md) | test_filterdecision.py, test_filter_helper.py, E2E (fail-closed without catalog) | | T24 | **Activity log = profile of browsing per person** (ADR-023): data of students and staff, a teacher looking at students of other classes or at colleagues, an exported CSV passed on | off by default per instance; switching on needs who confirmed the privacy notice (stored with the time in the instance's git log); minute and domain only, no URL, no client address; retention 1–365 days as whole day files (deleted before a query could read them); scope computed on the school server from the AD on every request, only the allowed users list goes to the proxy, which filters every SQL statement on it; teachers only students of their own classes/projects and school, never teachers; export only for administrators; every read and every settings change audited (person, scope, users, range) before data is read, 503 if the audit log cannot be written; the audit log only for global administrators, own retention | `test_activity.py`, `test_activity_api.py`, webui `test_activity_views.py`, E2E spool check | -| T25 | **The users list comes from the WebUI** (ADR-023): the proxy cannot check who asks; a stolen token reads everything | the token is the global administrator's credential already (T5, T18); the list is computed on the server, never taken from the browser; the audit names the person the WebUI reports and, for the CLI, `cli:` | `test_activity_views.py` (out-of-scope requests never reach a proxy) | -| T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 3733 (squid's proxy user can create, not list), files 0640 to the control plane's group; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured) | `test_activity.py` (receiver), local squid 6.14 test | +| T25 | **The users list comes from the WebUI** (ADR-023): the proxy cannot check who asks; a stolen token reads everything | the token is the global administrator's credential already (T5, T18); the list is computed on the server, never taken from the browser; the audit names the person the WebUI reports and, for the CLI, `cli:`; the WebUI logs every request of the view, refused ones and those without a proxy request included, to its system log (`journalctl -t lmn-squid-activity`) | `test_activity_views.py` (out-of-scope requests never reach a proxy) | +| T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 1733 (squid's proxy user can create, not list; no set-group-id, which `RestrictSUIDSGID=yes` refuses), files 0644 unreachable for other host users behind the 0750 parent; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured) | `test_activity.py` (receiver), local squid 6.14 test | ## Non-goals (deliberate) diff --git a/scripts/tests/activity_load.py b/scripts/tests/activity_load.py index 245cc6a..a25a676 100755 --- a/scripts/tests/activity_load.py +++ b/scripts/tests/activity_load.py @@ -130,12 +130,107 @@ def timed(fn, repeat: int = 3) -> tuple[float, object]: # type: ignore[no-untyp return best, result +def api_times( + work: Path, data: str, now: float, today: datetime.date, klass: list[str] +) -> dict[str, float]: + """The same queries through the control plane's API (FastAPI, audit line written first), + as the WebUI asks them; the WebUI adds its TLS round trip and the merge.""" + from unittest import mock + + from fastapi import FastAPI + from lmnsquid import activity_api + from lmnsquid.config import Settings + from lmnsquid.store import Store + from starlette.testclient import TestClient + + instances = work / "instances" + store = Store(str(instances)) + if store.get(NAME) is None: + store.put(instance(365)) + settings = Settings( + api_token="x" * 32, + instances_dir=str(instances), + activity_dir=data, + activity_spool_dir=str(work / "spool"), + catalog_dir=str(work / "catalog"), + ) + app = FastAPI() + activity_api.register( + app, + settings, + store, + [], + lambda n: store.get(n), # type: ignore[arg-type,return-value] + lambda i: {}, + lambda n: {}, + lambda i: True, + ) + client = TestClient(app) + audit = {"actor": "load", "role": "teacher", "scope": "class load"} + day_start = int( + datetime.datetime.combine(today, datetime.time(0, 0), ZONE).timestamp() + ) + week_start = day_start - 6 * 86400 + end = int(now) + 60 + calls = { + "POST /v1/activity/users (class list, today)": ( + "/v1/activity/users", + { + "since": day_start, + "until": end, + "users": klass, + "with_domains": False, + "audit": audit, + }, + ), + "POST /v1/activity/day (student)": ( + "/v1/activity/day", + { + "user": "schueler0007", + "day": today.isoformat(), + "users": klass, + "audit": audit, + }, + ), + "POST /v1/activity/timeline (heat map 7 days)": ( + "/v1/activity/timeline", + { + "user": "schueler0007", + "since": week_start, + "until": end, + "users": klass, + "audit": audit, + }, + ), + "POST /v1/activity/blocked (class, today)": ( + "/v1/activity/blocked", + {"since": day_start, "until": end, "users": klass, "audit": audit}, + ), + } + out: dict[str, float] = {} + with ( + mock.patch("lmnsquid.activity_query.time.time", return_value=now), + mock.patch("lmnsquid.activity.time.time", return_value=now), + ): + for label, (path, body) in calls.items(): + seconds, resp = timed(lambda p=path, b=body: client.post(p, json=b)) + assert resp.status_code == 200, (path, resp.text) # type: ignore[union-attr] + out[label] = round(seconds, 4) + print(label, out[label], flush=True) + return out + + def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--users", type=int, default=1000) parser.add_argument("--days", type=int, default=7) parser.add_argument("--rate", type=float, default=8.0) parser.add_argument("--work", default="") + parser.add_argument( + "--queries-only", + action="store_true", + help="reuse the data in --work, only measure", + ) args = parser.parse_args() work = Path(args.work or tempfile.mkdtemp(prefix="activity-load-")) data, spool_root = str(work / "data"), str(work / "spool") @@ -149,7 +244,7 @@ def main() -> int: "rate": args.rate, } per_day = [] - for i in range(args.days): + for i in range(0 if args.queries_only else args.days): day = today - datetime.timedelta(days=args.days - 1 - i) t = time.monotonic() lines = generate_day(spool, day, args.users, args.rate, seed=i) @@ -204,6 +299,15 @@ def main() -> int: int(datetime.datetime.combine(today, datetime.time(10, 30), ZONE).timestamp()), ) klass = [f"schueler{u:04d}" for u in range(30)] + lesson_day = ( + int(datetime.datetime.combine(today, datetime.time(7, 45), ZONE).timestamp()), + int(datetime.datetime.combine(today, datetime.time(16, 0), ZONE).timestamp()), + ) + first_day = q.day("schueler0007", today) + drill_domain = ( + first_day["domains"][0]["domain"] if first_day["domains"] else "h1.example1.org" + ) + report["day_answer_kib"] = round(len(json.dumps(first_day)) / 1024, 1) end = int(now) + 60 queries = { "class_overview_today (30 users)": lambda: q.users(day_start, end, klass), @@ -231,8 +335,26 @@ def main() -> int: "search_domain_all_today": lambda: q.search( "h5.example5.org", day_start, end, None ), - "export_class_day_rows": lambda: sum( - 1 for _ in q.export(day_start, end, klass) + "export_class_day_rows": lambda: ( + sum(c.count("\n") for c in q.export(day_start, end, klass)) - 1 + ), + # round 2: the student page and the class list without domain counts + "class_list_today_without_domains (30 users)": lambda: q.users( + day_start, end, klass, with_domains=False + ), + "day_student_whole_day": lambda: q.day("schueler0007", today), + "day_student_school_hours": lambda: q.day( + "schueler0007", today, start=lesson_day[0], end=lesson_day[1] + ), + "day_student_live_delta": lambda: q.day( + "schueler0007", today, since_minute=int(now) // 60 - 5 + ), + "drill_down_one_domain_day": lambda: q.timeline( + "schueler0007", day_start, day_start + 86400, "minute", domain=drill_domain + ), + "blocked_class_today": lambda: q.blocked(day_start, end, klass), + "search_class_90min_partial_day": lambda: q.search( + "example3.org", *lesson, klass ), } times = {} @@ -242,6 +364,7 @@ def main() -> int: times[label] = {"seconds": round(seconds, 3), "total": size} print(label, times[label], flush=True) report["queries"] = times + report["api"] = api_times(work, data, now, today, klass) total = sum(f.stat().st_size for f in (Path(data) / NAME).iterdir()) report["data_mib"] = round(total / 1048576, 1) report["maxrss_self_mib"] = round( From ae1541ee4fb104fe58c7780c5a056dd682b61575 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 14:32:49 +0100 Subject: [PATCH 18/45] test(e2e): one HTTPS attempt to a category name is one blocked request --- scripts/tests/e2e_kerberos.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/tests/e2e_kerberos.sh b/scripts/tests/e2e_kerberos.sh index 6ee8ff9..6e5afb9 100755 --- a/scripts/tests/e2e_kerberos.sh +++ b/scripts/tests/e2e_kerberos.sh @@ -358,6 +358,10 @@ rows = db.execute("SELECT us.name, ho.name, sum(n), sum(x), max(c) FROM act JOIN print(" collected:", rows) assert ("teacher1", "origin.example.internal") in {(r[0], r[1]) for r in rows}, rows assert any(r[4] == "porn" and r[3] > 0 for r in rows), rows +# one HTTPS attempt is one request: squid logs the refused CONNECT and the error page inside TLS +# (NONE_NONE/403) for it, the collector pairs them (squid 6.14) +by = {(r[0], r[1]): r[2:] for r in rows} +assert by[("teacher1", "secure.example.internal")] == (1, 1, "porn"), by assert not list((base / "activity").glob("act-*")), "spool not emptied" PYEOF then From e3b1e475c8ca95359ed13501deb035134ebee9f2 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 14:36:44 +0100 Subject: [PATCH 19/45] fix(controlplane): the collector's journal line names the HTTPS side lines it paired --- controlplane/lmnsquid/activity.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/controlplane/lmnsquid/activity.py b/controlplane/lmnsquid/activity.py index c726cce..f3eaf4f 100644 --- a/controlplane/lmnsquid/activity.py +++ b/controlplane/lmnsquid/activity.py @@ -698,12 +698,13 @@ def main(argv: list[str] | None = None) -> int: if c.used or c.broken: logger.info( "activity: %s: %d file(s), %d line(s), %d used, %d without user, " - "%d broken, %d too old, %d row(s) into %s (%.2f s)", + "%d HTTPS side line(s), %d broken, %d too old, %d row(s) into %s (%.2f s)", name, c.files, c.lines, c.used, c.anonymous, + c.side, c.broken, c.dropped_old, c.rows, From 0aad14a871e9be99cb2fdc955d98f7fdb52f050c Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 16:17:20 +0100 Subject: [PATCH 20/45] feat(webui): serve the activity view through a local root bridge Teachers' WebUI workers run with the teacher's UID and cannot read the proxies' tokens (lab A7, 409); the worker's module-level thread pool did not survive aj's gevent fork (lab A6, 'operation on destroyed loop'). The view logic moves to activity_core.py, run by bridge.py (root, unix socket): the caller's identity comes from SO_PEERCRED, only root callers (administrators' workers) name the person, the scope is computed from the AD in the bridge, requests are size, time and rate limited. The WebUI endpoints only forward over the socket (cooperative under gevent) and map a missing bridge to 503. Proxies tagged for other schools are not asked and old control planes no longer fail an export (lab A8). --- webui/build_plugin.py | 2 + webui/lmn_squid/activity_core.py | 790 ++++++++++++++++++++++++++++ webui/lmn_squid/activity_views.py | 803 ++++------------------------- webui/lmn_squid/bridge.py | 278 ++++++++++ webui/tests/test_activity_views.py | 70 ++- webui/tests/test_bridge.py | 250 +++++++++ webui/tests/test_build.py | 2 + 7 files changed, 1484 insertions(+), 711 deletions(-) create mode 100644 webui/lmn_squid/activity_core.py create mode 100644 webui/lmn_squid/bridge.py create mode 100644 webui/tests/test_bridge.py diff --git a/webui/build_plugin.py b/webui/build_plugin.py index 41208ed..d58c457 100644 --- a/webui/build_plugin.py +++ b/webui/build_plugin.py @@ -42,6 +42,8 @@ "setup_runner.py", "activity_scope.py", "activity_views.py", + "activity_core.py", + "bridge.py", ) META_FILES = ("plugin.yml", "permissions.yml") SKIP_LOCALES = ("en",) # English is the source language (msgid), as upstream diff --git a/webui/lmn_squid/activity_core.py b/webui/lmn_squid/activity_core.py new file mode 100644 index 0000000..f51c885 --- /dev/null +++ b/webui/lmn_squid/activity_core.py @@ -0,0 +1,790 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The logic of the activity view ("Internetnutzung", ADR-023), free of the WebUI core. + +It runs in the bridge (``bridge.py``, root, one process, threads), never in a WebUI worker: +teachers' workers run with the teacher's own UID and cannot read the proxies' tokens, and +Ajenti's gevent workers are forked after the plugins are imported (lab 2026-11-25, A6/A7). The +caller's identity comes from the bridge (SO_PEERCRED); the scope is computed here from the AD +(:mod:`activity_scope`) and only the users of that scope go to the proxies, which filter on them +and audit every read before it happens. Every request is written to the system log as well +(tag ``lmn-squid-activity``, authpriv), refused ones and those that needed no proxy included. + +Performance (spec ``ux-ueberarbeitung.md`` §4): the scope and the proxies' instance lists are +cached briefly (never activity data); all relevant proxies are asked in parallel with an +overall deadline of 5 s; a proxy that does not answer in time, refuses or reports a limit is +named with the kind of failure, the others' data are shown. Proxies that cannot hold data of +the asked school (tagged with other schools, or too old for the activity log) are left out and +never make a request fail (A8). +""" + +from __future__ import annotations + +import logging +import os +import re +import syslog +import threading +import time +from concurrent import futures +from typing import Any, Callable + +from .activity_scope import ( + SCHOOL_RE, + USER_RE, + DirectoryError, + LdapDirectory, + Scope, + ScopeDenied, + cached_scope, +) +from .client import LONG, NOT_MODIFIED, ControlPlaneClient, ControlPlaneError +from .connections import CONFIG_PATH, Connection, ConnectionFileError, ConnectionStore + +logger = logging.getLogger("lmn_squid.activity") + +MAX_RANGE = 366 * 86400 +WORKERS = 8 +DEADLINE = 5.0 # all proxies of one view request, seconds +VIEW_TIMEOUTS = (2.0, 5.0) # connect, read per proxy request +INSTANCES_TTL = 60.0 +PEOPLE_MAX = 10 +SORTS = ("requests", "blocked", "last", "name", "bytes") +# connection name -> (fetched at, light overview of GET /v1/activity?usage=false) +_INSTANCES: dict[str, tuple[float, Any]] = {} +_INSTANCES_LOCK = threading.Lock() +_POOL: futures.ThreadPoolExecutor | None = None +_POOL_PID = 0 +_POOL_LOCK = threading.Lock() + + +class ServiceError(Exception): + """An answer other than 200: the HTTP status and the JSON body for the page.""" + + def __init__(self, status: int, data: dict[str, Any]) -> None: + super().__init__(status) + self.status = status + self.data = data + + +def _pool() -> futures.ThreadPoolExecutor: + """The thread pool of this process, made on first use (never before a fork).""" + global _POOL, _POOL_PID + with _POOL_LOCK: + if _POOL is None or _POOL_PID != os.getpid(): + _POOL = futures.ThreadPoolExecutor( + max_workers=WORKERS, thread_name_prefix="lmn-squid-activity" + ) + _POOL_PID = os.getpid() + return _POOL + + +def forget_instances(conn: str | None = None) -> None: + """Drop the cached instance list (after a settings change in the management page).""" + with _INSTANCES_LOCK: + if conn is None: + _INSTANCES.clear() + else: + _INSTANCES.pop(conn, None) + + +def audit_line(text: str) -> None: + """One line in the system log (authpriv, tag lmn-squid-activity); replaceable in tests.""" + syslog.openlog("lmn-squid-activity", syslog.LOG_PID, syslog.LOG_AUTHPRIV) + syslog.syslog(syslog.LOG_INFO, text) + + +def _int(body: dict[str, Any], key: str, default: int | None = None) -> int: + value = body.get(key, default) + if isinstance(value, bool) or value is None: + raise ServiceError(422, {"error": "invalid", "field": key, "message": f"{key} missing"}) + try: + return int(value) + except (TypeError, ValueError): + raise ServiceError( + 422, {"error": "invalid", "field": key, "message": f"{key} must be a number"} + ) from None + + +def _range(body: dict[str, Any]) -> tuple[int, int]: + since, until = _int(body, "since"), _int(body, "until") + if since < 0 or until <= since or until - since > MAX_RANGE: + raise ServiceError( + 422, {"error": "invalid", "field": "until", "message": "invalid time range"} + ) + return since, until + + +def _school(value: Any) -> str | None: + if value in (None, ""): + return None + if not isinstance(value, str) or not SCHOOL_RE.match(value): + raise ServiceError(422, {"error": "invalid", "field": "school", "message": "school"}) + return value + + +def _user(value: Any) -> str: + user = str(value or "").lower() + if not USER_RE.match(user): + raise ServiceError(422, {"error": "invalid", "field": "user", "message": "user"}) + return user + + +def _failure(conn: Connection, exc: Exception) -> dict[str, Any]: + """A failed proxy as the page shows it: the kind of failure and the proxy's own words.""" + name = conn.display_name or conn.name + if isinstance(exc, ControlPlaneError): + detail = exc.detail if isinstance(exc.detail, dict) else {} + if exc.kind == "http" and exc.status == 422 and detail.get("code"): + return { + "connection": name, + "kind": "limit", + "code": detail.get("code"), + "message": str(detail.get("message") or exc.message), + } + if exc.kind == "http" and isinstance(detail, dict) and detail.get("message"): + return {"connection": name, "kind": "error", "message": str(detail["message"])} + kind = exc.kind if exc.kind != "http" else "error" + return {"connection": name, "kind": kind, "message": exc.message} + return {"connection": name, "kind": "error", "message": str(exc)[:300]} + + +class ActivityService: + """The activity view's logic; runs in the bridge (root), one instance for all callers.""" + + def __init__( + self, + store: ConnectionStore | None = None, + directory_factory: Callable[[], Any] = LdapDirectory, + audit: Callable[[str], None] | None = None, + ) -> None: + self.store = store or ConnectionStore(CONFIG_PATH) + self.directory_factory = directory_factory + self._audit_sink = audit or audit_line + + # ------------------------------------------------------------------ helpers + def audit(self, text: str) -> None: + try: + self._audit_sink(text) + except OSError as exc: # no /dev/log (tests, containers): the WebUI's own log + logger.warning("activity audit line not written (%s): %s", exc, text) + + def _scope(self, identity: str, school: str | None = None) -> Scope: + return cached_scope(identity, self.directory_factory(), school) + + def _audit_info(self, scope: Scope, label: str) -> dict[str, Any]: + return {"actor": scope.user, "role": scope.role, "scope": label[:256]} + + def _log(self, scope: Scope, what: str, label: str, result: str = "asked") -> None: + self.audit( + f"user={scope.user} role={scope.role} school={scope.school or '-'} {what} " + f"scope={label} result={result}" + ) + + def _fan_out( + self, + call: Callable[[Connection, ControlPlaneClient], Any], + deadline: float = DEADLINE, + school: str | None = None, + ) -> tuple[list[tuple[Connection, Any, float]], list[dict[str, Any]]]: + """``call`` on every connection in parallel within ``deadline``: (results with their + time in ms, failures with their kind). With ``school``, a connection tagged with other + schools only (its ``schools``) is not asked.""" + conns = [ + c + for c in self.store.load().values() + if school is None or not c.schools or school in c.schools + ] + results: list[tuple[Connection, Any, float]] = [] + failed: list[dict[str, Any]] = [] + if not conns: + return results, failed + + def timed(conn: Connection) -> tuple[Any, float]: + started = time.monotonic() + value = call(conn, ControlPlaneClient(conn)) + return value, (time.monotonic() - started) * 1000 + + jobs = {_pool().submit(timed, c): c for c in conns} + done, pending = futures.wait(jobs, timeout=deadline) + for job in done: + conn = jobs[job] + try: + value, ms = job.result() + results.append((conn, value, ms)) + except Exception as exc: # noqa: BLE001 - one proxy never blocks the view + failed.append(_failure(conn, exc)) + for job in pending: + conn = jobs[job] + failed.append( + { + "connection": conn.display_name or conn.name, + "kind": "timeout", + "message": f"no answer within {deadline:.0f} s", + } + ) + results.sort(key=lambda item: item[0].name) + failed.sort(key=lambda f: f["connection"]) + return results, failed + + @staticmethod + def _overview(conn: Connection, client: ControlPlaneClient) -> Any: + now = time.monotonic() + with _INSTANCES_LOCK: + hit = _INSTANCES.get(conn.name) + if hit is not None and now - hit[0] < INSTANCES_TTL: + return hit[1] + data = client.request( + "GET", "/v1/activity", query={"usage": "false"}, timeouts=VIEW_TIMEOUTS + ) + with _INSTANCES_LOCK: + _INSTANCES[conn.name] = (now, data) + return data + + @staticmethod + def _instances(overview: Any, scope: Scope) -> list[str]: + """The instances of one proxy that hold activity data of the scope's school.""" + found = [] + for inst in (overview or {}).get("instances") or []: + if not isinstance(inst, dict): + continue + if not (inst.get("enabled") or inst.get("days")): + continue + if scope.school is not None and inst.get("school") != scope.school: + continue + found.append(str(inst.get("name"))) + return found + + def _query( + self, + scope: Scope, + path: str, + body: dict[str, Any], + timeouts: tuple[float, float] = VIEW_TIMEOUTS, + text: bool = False, + etags: dict[str, str] | None = None, + deadline: float = DEADLINE, + ) -> tuple[list[tuple[Connection, Any]], list[dict[str, Any]], dict[str, Any]]: + """POST ``body`` to ``path`` of every proxy with matching instances: (answers, failures, + timing). With ``etags`` (connection -> ETag) a proxy may answer NOT_MODIFIED.""" + started = time.monotonic() + + def call(conn: Connection, client: ControlPlaneClient) -> Any: + names = self._instances(self._overview(conn, client), scope) + if not names: + return None + return client.request( + "POST", + path, + {**body, "instances": names}, + timeouts=timeouts, + text=text, + etag=(etags or {}).get(conn.name), + ) + + results, failed = self._fan_out(call, deadline, scope.school) + # a control plane without the activity log holds no activity data: not a failure (A8); + # the management page names old servers + failed = [f for f in failed if f.get("kind") != "too_old"] + timing = { + "total_ms": round((time.monotonic() - started) * 1000), + "proxies": {c.name: round(ms) for c, _r, ms in results}, + } + return [(c, r) for c, r, _ms in results if r is not None], failed, timing + + def _users_for(self, scope: Scope, body: dict[str, Any]) -> tuple[list[str] | None, str, Any]: + """The users list sent to the proxies, a label for the audit, the group (or None). + + A class or project of a school or global administrator lists its teachers only on + request (``teachers``: true, decision E3); a teacher's scope never holds teachers. + """ + group = body.get("group") + if isinstance(group, dict) and group.get("name"): + g = scope.group(str(group.get("kind") or ""), str(group.get("name"))) + with_teachers = body.get("teachers") is True and scope.role != "teacher" + members = [m["user"] for m in g.members if with_teachers or m.get("role") != "teacher"] + return scope.restrict(members), f"{g.kind} {g.name}", g + if scope.users is None: + return None, f"school {scope.school}" if scope.school else "all schools", None + return sorted(scope.users), f"all visible users ({scope.school})", None + + def _empty(self, scope: Scope, what: str, label: str, **extra: Any) -> dict[str, Any]: + self._log(scope, what, label, "empty scope, no proxy asked") + return {"unreachable": [], "timing": {"total_ms": 0, "proxies": {}}, **extra} + + def _labels(self) -> dict[str, Any]: + """Category labels, background categories and lesson hours from the cached overviews.""" + labels: dict[str, str] = {} + background: set[str] = set() + lesson: list[str] | None = None + timezone: str | None = None + with _INSTANCES_LOCK: + cached = [v for _t, v in _INSTANCES.values()] + for overview in cached: + labels.update((overview or {}).get("category_labels") or {}) + background |= set((overview or {}).get("background_categories") or []) + lesson = lesson or (overview or {}).get("lesson_hours") + timezone = timezone or (overview or {}).get("timezone") + return { + "category_labels": labels, + "background_categories": sorted(background), + "lesson_hours": lesson or ["07:45", "16:00"], + "timezone": timezone, + } + + # ------------------------------------------------------------------ scope + def handle_scope(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """What the person may look at: role, school and the classes and projects (counts only; + members per group on request). Asks the proxies only for their (cached) overview.""" + started = time.monotonic() + school = _school(query.get("school")) + scope = self._scope(identity, school) + results, failed = self._fan_out(self._overview, school=scope.school) + failed = [f for f in failed if f.get("kind") != "too_old"] + schools = sorted( + { + str(i.get("school")) + for _c, r, _ms in results + for i in (r or {}).get("instances") or [] + if isinstance(i, dict) and i.get("school") + } + ) + oldest = sorted( + str(i.get("oldest")) + for _c, r, _ms in results + for i in (r or {}).get("instances") or [] + if isinstance(i, dict) + and i.get("oldest") + and (scope.school is None or i.get("school") == scope.school) + ) + return { + "user": scope.user, + "role": scope.role, + "school": scope.school, + "oldest": oldest[0] if oldest else None, + "schools": schools if scope.is_global else [], + "can_export": scope.can_export, + "is_global": scope.is_global, + "groups": [ + { + **g.brief(), + "students": sum(1 for m in g.members if m.get("role") != "teacher"), + } + for g in scope.groups + ], + **self._labels(), + "unreachable": failed, + "timing": {"total_ms": round((time.monotonic() - started) * 1000)}, + } + + def handle_members( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + kind: str = "", + name: str = "", + ) -> Any: + """The visible members of one class or project (teachers only for administrators and + only with ``teachers=1``). From the AD only: no proxy, no activity data.""" + query = query + scope = self._scope(identity, _school(query.get("school"))) + g = scope.group(kind, name) + with_teachers = str(query.get("teachers") or "") == "1" and scope.role != "teacher" + members = [m for m in g.members if with_teachers or m.get("role") != "teacher"] + return { + "kind": g.kind, + "name": g.name, + "members": members, + "teachers_hidden": sum(1 for m in g.members if m.get("role") == "teacher") + if not with_teachers + else 0, + } + + def handle_people(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """Up to 10 people of the scope whose login or name contains ``q`` (at least 2 + characters). From the AD only: no proxy, no activity data, no audit needed.""" + query = query + q = str(query.get("q") or "").strip().lower() + if len(q) < 2 or len(q) > 64: + return {"people": []} + scope = self._scope(identity, _school(query.get("school"))) + found = [] + for user, display in sorted(scope.names.items(), key=lambda kv: kv[1].lower()): + if q in user or q in display.lower(): + found.append( + {"user": user, "display": display, "classes": scope.classes_of.get(user, [])} + ) + if len(found) >= PEOPLE_MAX: + break + return {"people": found} + + # ---------------------------------------------------------------- queries + def handle_users(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """Per user of a class (or the scope): requests, blocked, last seen, active now; the + distinct domains only with ``with_domains`` (expensive, off by default).""" + body = body + scope = self._scope(identity, _school(body.get("school"))) + since, until = _range(body) + users, label, _g = self._users_for(scope, body) + sort = body.get("sort") if body.get("sort") in SORTS else "requests" + if users == []: + return self._empty(scope, "users", label, users=[]) + self._log(scope, "users", label) + results, failed, timing = self._query( + scope, + "/v1/activity/users", + { + "since": since, + "until": until, + "users": users, + "limit": max(1, min(len(users) if users else 1000, 1000)), + "sort": sort, + "with_domains": body.get("with_domains") is True, + "audit": self._audit_info(scope, label), + }, + ) + merged: dict[str, dict[str, Any]] = {} + for _conn, result in results: + for row in result.get("users") or []: + cur = merged.get(row["user"]) + if cur is None: + merged[row["user"]] = dict(row) + continue + for key in ("requests", "bytes", "blocked"): + cur[key] = int(cur.get(key) or 0) + int(row.get(key) or 0) + if row.get("domains") is not None: + cur["domains"] = int(cur.get("domains") or 0) + int(row["domains"]) + cur["last"] = max(int(cur.get("last") or 0), int(row.get("last") or 0)) + cur["active_now"] = bool(cur.get("active_now") or row.get("active_now")) + for name, row in merged.items(): + row["display"] = scope.names.get(name, name) + return {"users": list(merged.values()), "unreachable": failed, "timing": timing} + + def handle_day(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """One student's day (the student page): minutes and domains, merged over the proxies. + + ``etags`` (connection -> ETag of the browser's last answer): when no proxy has anything + new the answer is ``{"not_modified": true}``; the proxies audit every one of these. + """ + body = body + scope = self._scope(identity, _school(body.get("school"))) + user = _user(body.get("user")) + scope.check_user(user) + day = str(body.get("day") or "") + if len(day) != 10: + raise ServiceError(422, {"error": "invalid", "field": "day", "message": "day"}) + payload: dict[str, Any] = { + "user": user, + "day": day, + "users": None if scope.users is None else [user], + "audit": self._audit_info(scope, f"user {user}"), + } + for key in ("start", "end", "since_minute"): + if body.get(key) not in (None, ""): + payload[key] = _int(body, key) + etags = body.get("etags") if isinstance(body.get("etags"), dict) else None + self._log(scope, "day", f"user {user} {day}") + results, failed, timing = self._query(scope, "/v1/activity/day", payload, etags=etags) + if etags and results and all(r is NOT_MODIFIED for _c, r in results): + return {"not_modified": True, "unreachable": failed, "timing": timing} + if any(r is NOT_MODIFIED for _c, r in results): + # some proxies have news: everything again, without ETags + results, failed, timing = self._query(scope, "/v1/activity/day", payload) + return { + **merge_days([r for _c, r in results]), + "user": user, + "display": scope.names.get(user, user), + "classes": scope.classes_of.get(user, []), + "day": day, + "etags": {c.name: r.get("_etag") for c, r in results if isinstance(r, dict)}, + "unreachable": failed, + "timing": timing, + } + + def handle_timeline(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """One user's activity per hour (heat map) or per minute, optionally of one domain.""" + body = body + scope = self._scope(identity, _school(body.get("school"))) + since, until = _range(body) + user = _user(body.get("user")) + scope.check_user(user) + resolution = "minute" if body.get("resolution") == "minute" else "hour" + domain = str(body.get("domain") or "").strip().lower() or None + if domain is not None and (len(domain) > 253 or any(c.isspace() for c in domain)): + raise ServiceError(422, {"error": "invalid", "field": "domain", "message": "domain"}) + label = f"user {user}" + (f" domain {domain}" if domain else "") + self._log(scope, f"timeline {resolution}", label) + payload = { + "since": since, + "until": until, + "user": user, + "users": None if scope.users is None else [user], + "resolution": resolution, + "limit": 5000 if resolution == "minute" else 1000, + "domain": domain, + "audit": self._audit_info(scope, label), + } + etags = body.get("etags") if isinstance(body.get("etags"), dict) else None + results, failed, timing = self._query(scope, "/v1/activity/timeline", payload, etags=etags) + if etags and results and all(r is NOT_MODIFIED for _c, r in results): + return {"not_modified": True, "unreachable": failed, "timing": timing} + if any(r is NOT_MODIFIED for _c, r in results): + results, failed, timing = self._query(scope, "/v1/activity/timeline", payload) + rows: dict[tuple[Any, ...], dict[str, Any]] = {} + for _conn, result in results: + for row in result.get("rows") or []: + key = (row.get("t"), row.get("domain")) + cur = rows.get(key) + if cur is None: + rows[key] = dict(row) + continue + for k in ("requests", "bytes", "blocked"): + cur[k] = int(cur.get(k) or 0) + int(row.get(k) or 0) + ordered = [rows[k] for k in sorted(rows, key=lambda k: (k[0] or 0, k[1] or ""))] + return { + "user": user, + "display": scope.names.get(user, user), + "resolution": resolution, + "rows": ordered, + "etags": {c.name: r.get("_etag") for c, r in results if isinstance(r, dict)}, + "unreachable": failed, + "timing": timing, + } + + def handle_domains(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """Top domains of a group or of one user (background services hidden on request).""" + body = body + scope = self._scope(identity, _school(body.get("school"))) + since, until = _range(body) + if body.get("user"): + user = _user(body.get("user")) + scope.check_user(user) + users: list[str] | None = [user] + label = f"user {user}" + else: + users, label, _g = self._users_for(scope, body) + if users == []: + return self._empty(scope, "domains", label, domains=[]) + self._log(scope, "domains", label) + results, failed, timing = self._query( + scope, + "/v1/activity/domains", + { + "since": since, + "until": until, + "users": users, + "limit": 50, + "hide_background": body.get("hide_background") is True, + "audit": self._audit_info(scope, label), + }, + ) + merged: dict[str, dict[str, Any]] = {} + for _conn, result in results: + for row in result.get("domains") or []: + cur = merged.get(row["domain"]) + if cur is None: + merged[row["domain"]] = dict(row) + continue + for k in ("requests", "bytes", "blocked", "users"): + cur[k] = int(cur.get(k) or 0) + int(row.get(k) or 0) + cur["category"] = cur.get("category") or row.get("category") + ordered = sorted(merged.values(), key=lambda r: (-int(r["requests"]), r["domain"])) + return {"domains": ordered[:50], "unreachable": failed, "timing": timing} + + def handle_blocked(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """Blocked attempts of a group per domain: how often, by how many, the category.""" + body = body + scope = self._scope(identity, _school(body.get("school"))) + since, until = _range(body) + users, label, _g = self._users_for(scope, body) + if users == []: + return self._empty(scope, "blocked", label, domains=[]) + self._log(scope, "blocked", label) + results, failed, timing = self._query( + scope, + "/v1/activity/blocked", + { + "since": since, + "until": until, + "users": users, + "limit": 100, + "audit": self._audit_info(scope, label), + }, + ) + merged: dict[str, dict[str, Any]] = {} + for _conn, result in results: + for row in result.get("domains") or []: + cur = merged.get(row["domain"]) + if cur is None: + merged[row["domain"]] = dict(row) + continue + cur["blocked"] = int(cur["blocked"]) + int(row["blocked"]) + cur["users"] = int(cur["users"]) + int(row["users"]) + cur["category"] = cur.get("category") or row.get("category") + ordered = sorted( + merged.values(), key=lambda r: (-int(r["users"]), -int(r["blocked"]), r["domain"]) + ) + return {"domains": ordered, "unreachable": failed, "timing": timing} + + def handle_search(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """Who of the group (or the scope) was on a domain (or a subdomain of it).""" + body = body + scope = self._scope(identity, _school(body.get("school"))) + since, until = _range(body) + domain = str(body.get("domain") or "").strip().lower() + if not domain or len(domain) > 253 or any(c.isspace() for c in domain): + raise ServiceError(422, {"error": "invalid", "field": "domain", "message": "domain"}) + users, label, _g = self._users_for(scope, body) + if users == []: + return self._empty(scope, "search", f"{label} domain {domain}", users=[]) + self._log(scope, "search", f"{label} domain {domain}") + results, failed, timing = self._query( + scope, + "/v1/activity/search", + { + "since": since, + "until": until, + "users": users, + "domain": domain, + "limit": 1000, + "audit": self._audit_info(scope, label), + }, + ) + merged: dict[str, dict[str, Any]] = {} + for _conn, result in results: + for row in result.get("users") or []: + cur = merged.get(row["user"]) + if cur is None: + merged[row["user"]] = dict(row) + continue + cur["requests"] = int(cur["requests"]) + int(row["requests"]) + cur["blocked"] = int(cur["blocked"]) + int(row["blocked"]) + cur["first"] = min(int(cur["first"]), int(row["first"])) + cur["last"] = max(int(cur["last"]), int(row["last"])) + cur["domains"] = sorted(set(cur["domains"]) | set(row["domains"]))[:10] + for name, row in merged.items(): + row["display"] = scope.names.get(name, name) + ordered = sorted(merged.values(), key=lambda r: (-int(r["requests"]), r["user"])) + return {"domain": domain, "users": ordered, "unreachable": failed, "timing": timing} + + def handle_export(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """CSV per minute, user and domain: school and global administrators only. Refused as a + whole when a proxy cannot deliver its part (never a CSV with rows missing).""" + body = body + scope = self._scope(identity, _school(body.get("school"))) + if not scope.can_export: + raise ScopeDenied("export is for school and global administrators") + since, until = _range(body) + users, label, _g = self._users_for(scope, body) + header = "time,user,domain,requests,bytes,blocked,category\n" + if users == []: + return {**self._empty(scope, "export", label), "csv": header} + self._log(scope, "export", label) + results, failed, timing = self._query( + scope, + "/v1/activity/export", + { + "since": since, + "until": until, + "users": users, + "audit": self._audit_info(scope, label), + }, + timeouts=LONG, + text=True, + deadline=LONG[1], + ) + if failed: + self._log(scope, "export", label, "refused: a proxy failed") + raise ServiceError( + 409, {"error": "export_incomplete", "message": "", "unreachable": failed} + ) + parts = [header] + truncated = False + for _conn, text in results: + body_text = str(text or "") + truncated = truncated or "# truncated" in body_text or "# stopped" in body_text + parts.append(body_text[len(header) :] if body_text.startswith(header) else body_text) + if truncated: + raise ServiceError(409, {"error": "export_too_large", "message": "", "unreachable": []}) + return {"csv": "".join(parts), "unreachable": [], "timing": timing} + + # ------------------------------------------------------------------ dispatch + ROUTES: dict[tuple[str, str], str] = { + ("GET", "scope"): "handle_scope", + ("GET", "people"): "handle_people", + ("POST", "query/users"): "handle_users", + ("POST", "query/day"): "handle_day", + ("POST", "query/timeline"): "handle_timeline", + ("POST", "query/domains"): "handle_domains", + ("POST", "query/blocked"): "handle_blocked", + ("POST", "query/search"): "handle_search", + ("POST", "export"): "handle_export", + } + MEMBERS = re.compile( + r"^group/(?Pclass|project)/(?P[A-Za-z0-9][\w\-]{0,63})/members$" + ) + + def dispatch( + self, identity: str, method: str, path: str, query: dict[str, Any], body: dict[str, Any] + ) -> tuple[int, Any]: + """One request of the view for ``identity`` (from the bridge): (status, JSON body).""" + try: + match = self.MEMBERS.match(path) + if method == "GET" and match: + return 200, self.handle_members(identity, query, body, **match.groupdict()) + name = self.ROUTES.get((method, path)) + if name is None: + return 404, {"error": "not_found", "message": path[:100]} + return 200, getattr(self, name)(identity, query, body) + except ServiceError as exc: + return exc.status, exc.data + except ScopeDenied as exc: + self.audit(f"user={identity} refused path={path} reason={exc}") + return 403, {"error": "scope", "message": str(exc)} + except DirectoryError as exc: + return 503, {"error": "directory", "message": str(exc)} + except ControlPlaneError as exc: + return exc.http_status(), exc.as_dict() + except ConnectionFileError as exc: + return 409, {"error": "config", "message": exc.message} + + +def merge_days(answers: list[dict[str, Any]]) -> dict[str, Any]: + """The day answers of several proxies as one: minutes and domains added up, totals again.""" + minutes: dict[int, list[int]] = {} + domains: dict[str, dict[str, Any]] = {} + other = {"count": 0, "requests": 0} + for answer in answers: + for t, n, x, d in answer.get("minutes") or []: + row = minutes.setdefault(int(t), [0, 0, 0]) + row[0] += int(n) + row[1] += int(x) + row[2] = max(row[2], int(d)) + for dom in answer.get("domains") or []: + cur = domains.get(dom["domain"]) + if cur is None: + domains[dom["domain"]] = dict(dom) + continue + for k in ("minutes", "requests", "blocked"): + cur[k] = int(cur.get(k) or 0) + int(dom.get(k) or 0) + cur["category"] = cur.get("category") or dom.get("category") + cur["first"] = min(int(cur["first"]), int(dom["first"])) + cur["last"] = max(int(cur["last"]), int(dom["last"])) + for k in ("count", "requests"): + other[k] += int((answer.get("other") or {}).get(k) or 0) + ordered = sorted(domains.values(), key=lambda d: (-int(d["minutes"]), -int(d["requests"]))) + return { + "minutes": [[t, n, x, d] for t, (n, x, d) in sorted(minutes.items())], + "domains": ordered, + "other": other, + "totals": { + "active_minutes": len(minutes), + "requests": sum(r[0] for r in minutes.values()), + "blocked": sum(r[1] for r in minutes.values()), + "domains": len(domains) + other["count"], + "first": min(minutes) if minutes else None, + "last": max(minutes) if minutes else None, + }, + "cursor": max(minutes) // 60 if minutes else None, + } diff --git a/webui/lmn_squid/activity_views.py b/webui/lmn_squid/activity_views.py index 8e435c6..68aeea7 100644 --- a/webui/lmn_squid/activity_views.py +++ b/webui/lmn_squid/activity_views.py @@ -1,33 +1,22 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later """HTTP endpoints of the activity view ("Internetnutzung", ADR-023) under -``/api/lmn/squid-activity/``: a pure view for teachers, school and global administrators. - -Every endpoint carries ``@authorize('lm:squid:activity')`` and computes the person's scope from -the AD on the server (:mod:`activity_scope`): a teacher's requests carry exactly the students of -their classes and projects as the ``users`` list to the proxies, which filter on it and audit the -query before reading; a user or group outside the scope is 403 before any proxy is asked. -Students and other roles get 403 also with the permission granted by hand. Export is for school -and global administrators. The settings and the proxies' audit log are in the management page -(global administrators, ``views.py``, ADR-023 addendum E1). - -The plugin writes its own audit line for every request of this view, also for refused ones and -for those that needed no proxy (an empty scope), to the system log with the tag -``lmn-squid-activity`` (facility authpriv: ``journalctl -t lmn-squid-activity``). - -Performance (spec ``ux-ueberarbeitung.md`` §4): the scope and the proxies' instance lists are -cached briefly (never activity data, which must be audited on the proxy at every read); all -proxies are asked in parallel with an overall deadline of 5 s; a proxy that does not answer in -time, refuses or reports a limit is named with the kind of failure, the others' data are shown. +``/api/lmn/squid-activity/``: thin forwarders to the local bridge (``bridge.py``). + +Every endpoint carries ``@authorize('lm:squid:activity')`` and, for state-changing methods, the +same-origin check of the management page. Everything else happens in the bridge (root, +socket-activated), for every role the same way: it learns the caller from the kernel +(SO_PEERCRED: a teacher's worker runs with the teacher's UID, an administrator's as root and +names the logged-in person), computes the scope from the AD, asks the proxies with their +tokens and returns only what the person may see. The WebUI worker never reads the tokens, never +starts threads (Ajenti forks its gevent workers after the plugins are imported, lab A6) and +never decides a scope itself. The socket is a cooperative gevent socket inside the worker. """ from __future__ import annotations -import logging -import syslog -import threading -import time -from concurrent import futures +import json +import socket from functools import wraps from typing import Any, Callable @@ -36,750 +25,162 @@ from aj.auth import authorize from jadi import component -from .activity_scope import ( - SCHOOL_RE, - USER_RE, - DirectoryError, - LdapDirectory, - Scope, - ScopeDenied, - cached_scope, -) -from .client import LONG, NOT_MODIFIED, ControlPlaneClient, ControlPlaneError -from .connections import CONFIG_PATH, Connection, ConnectionFileError, ConnectionStore from .views import STATE_CHANGING, _body, check_same_origin -logger = logging.getLogger("lmn_squid.activity") - PERM_ACTIVITY = "lm:squid:activity" PREFIX = r"/api/lmn/squid-activity" -MAX_RANGE = 366 * 86400 -WORKERS = 8 -DEADLINE = 5.0 # all proxies of one view request, seconds -VIEW_TIMEOUTS = (2.0, 5.0) # connect, read per proxy request -INSTANCES_TTL = 60.0 -PEOPLE_MAX = 10 -SORTS = ("requests", "blocked", "last", "name", "bytes") -_POOL = futures.ThreadPoolExecutor(max_workers=WORKERS, thread_name_prefix="lmn-squid-activity") -# connection name -> (fetched at, light overview of GET /v1/activity?usage=false) -_INSTANCES: dict[str, tuple[float, Any]] = {} -_INSTANCES_LOCK = threading.Lock() - - -def forget_instances(conn: str | None = None) -> None: - """Drop the cached instance list (after a settings change in the management page).""" - with _INSTANCES_LOCK: - if conn is None: - _INSTANCES.clear() - else: - _INSTANCES.pop(conn, None) - - -def audit_line(text: str) -> None: - """One line in the system log (authpriv, tag lmn-squid-activity); replaceable in tests.""" - syslog.openlog("lmn-squid-activity", syslog.LOG_PID, syslog.LOG_AUTHPRIV) - syslog.syslog(syslog.LOG_INFO, text) - - -def _identity(handler: Any) -> str: - return str(getattr(handler.context, "identity", None) or "-") - - -def activity_endpoint(fx: Callable[..., Any]) -> Callable[..., Any]: - """Same-origin check of state-changing requests, scope errors as 403 (audited), AD and - plugin errors as readable answers (never a traceback).""" - - @wraps(fx) - def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: - if str(getattr(http_context, "method", "")).upper() in STATE_CHANGING: - check_same_origin(http_context) - try: - return fx(self, http_context, **kwargs) - except ScopeDenied as exc: - self.audit(f"user={_identity(self)} refused path={http_context.path} reason={exc}") - raise EndpointReturn(403, {"error": "scope", "message": str(exc)}) from None - except DirectoryError as exc: - raise EndpointReturn(503, {"error": "directory", "message": str(exc)}) from None - except ControlPlaneError as exc: - raise EndpointReturn(exc.http_status(), exc.as_dict()) from None - except ConnectionFileError as exc: - raise EndpointReturn(409, {"error": "config", "message": exc.message}) from None - - return wrapper - - -def _int(body: dict[str, Any], key: str, default: int | None = None) -> int: - value = body.get(key, default) - if isinstance(value, bool) or value is None: - raise EndpointReturn(422, {"error": "invalid", "field": key, "message": f"{key} missing"}) +SOCKET_PATH = "/run/linuxmuster-squid-webui/activity.sock" +VIEW_TIMEOUT = 15.0 +EXPORT_TIMEOUT = 900.0 +MAX_ANSWER = 64 * 1024 * 1024 + + +def bridge_call( + identity: str, + method: str, + path: str, + query: dict[str, Any], + body: dict[str, Any], + timeout: float = VIEW_TIMEOUT, + socket_path: str | None = None, +) -> tuple[int, Any]: + """One request to the bridge: (status, data); a bridge that is not there is a 503.""" + request = json.dumps( + {"v": 1, "identity": identity, "method": method, "path": path, "query": query, "body": body} + ).encode("utf-8") + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(timeout) try: - return int(value) - except (TypeError, ValueError): - raise EndpointReturn( - 422, {"error": "invalid", "field": key, "message": f"{key} must be a number"} - ) from None - - -def _range(body: dict[str, Any]) -> tuple[int, int]: - since, until = _int(body, "since"), _int(body, "until") - if since < 0 or until <= since or until - since > MAX_RANGE: - raise EndpointReturn( - 422, {"error": "invalid", "field": "until", "message": "invalid time range"} - ) - return since, until - + sock.connect(socket_path or SOCKET_PATH) + sock.sendall(request) + sock.shutdown(socket.SHUT_WR) + chunks: list[bytes] = [] + size = 0 + while True: + data = sock.recv(65536) + if not data: + break + size += len(data) + if size > MAX_ANSWER: + return 502, {"error": "bridge", "message": "answer too large"} + chunks.append(data) + except (FileNotFoundError, ConnectionRefusedError): + return 503, {"error": "bridge_down", "message": "activity bridge not running"} + except (socket.timeout, TimeoutError): + return 504, {"error": "bridge_timeout", "message": "activity bridge did not answer"} + except OSError as exc: + return 503, {"error": "bridge_down", "message": str(exc)[:200]} + finally: + sock.close() + try: + answer = json.loads(b"".join(chunks).decode("utf-8")) + return int(answer["status"]), answer["data"] + except (ValueError, KeyError, TypeError): + return 502, {"error": "bridge", "message": "unreadable answer"} -def _school(value: Any) -> str | None: - if value in (None, ""): - return None - if not isinstance(value, str) or not SCHOOL_RE.match(value): - raise EndpointReturn(422, {"error": "invalid", "field": "school", "message": "school"}) - return value +def forward(path: str, timeout: float = VIEW_TIMEOUT) -> Callable[..., Any]: + """An endpoint that hands the request to the bridge (``path`` may use the URL's groups).""" -def _user(value: Any) -> str: - user = str(value or "").lower() - if not USER_RE.match(user): - raise EndpointReturn(422, {"error": "invalid", "field": "user", "message": "user"}) - return user + def decorator(fx: Callable[..., Any]) -> Callable[..., Any]: + @wraps(fx) + def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: + method = str(getattr(http_context, "method", "GET")).upper() + if method in STATE_CHANGING: + check_same_origin(http_context) + body = _body(http_context) if method in STATE_CHANGING else {} + query = {str(k): str(v) for k, v in (http_context.query or {}).items()} + identity = str(getattr(self.context, "identity", "") or "") + status, data = self.call(identity, method, path.format(**kwargs), query, body, timeout) + if status != 200: + raise EndpointReturn(status, data) + return data + return wrapper -def _failure(conn: Connection, exc: Exception) -> dict[str, Any]: - """A failed proxy as the page shows it: the kind of failure and the proxy's own words.""" - name = conn.display_name or conn.name - if isinstance(exc, ControlPlaneError): - detail = exc.detail if isinstance(exc.detail, dict) else {} - if exc.kind == "http" and exc.status == 422 and detail.get("code"): - return { - "connection": name, - "kind": "limit", - "code": detail.get("code"), - "message": str(detail.get("message") or exc.message), - } - if exc.kind == "http" and isinstance(detail, dict) and detail.get("message"): - return {"connection": name, "kind": "error", "message": str(detail["message"])} - kind = exc.kind if exc.kind != "http" else "error" - return {"connection": name, "kind": kind, "message": exc.message} - return {"connection": name, "kind": "error", "message": str(exc)[:300]} + return decorator @component(HttpPlugin) class ActivityHandler(HttpPlugin): - # Replaceable in tests (a fake AD with the same shape). - directory_factory: Callable[[], Any] = LdapDirectory + # Replaceable in tests: how a request reaches the bridge. + call: Callable[..., tuple[int, Any]] = staticmethod(bridge_call) def __init__(self, context: Any) -> None: self.context = context - self.store = ConnectionStore(CONFIG_PATH) - - # ------------------------------------------------------------------ helpers - def audit(self, text: str) -> None: - try: - audit_line(text) - except OSError as exc: # no /dev/log (tests, containers): the WebUI's own log - logger.warning("activity audit line not written (%s): %s", exc, text) - - def _scope(self, school: str | None = None) -> Scope: - return cached_scope( - getattr(self.context, "identity", None), self.directory_factory(), school - ) - - def _audit_info(self, scope: Scope, label: str) -> dict[str, Any]: - return {"actor": scope.user, "role": scope.role, "scope": label[:256]} - - def _log(self, scope: Scope, what: str, label: str, result: str = "asked") -> None: - self.audit( - f"user={scope.user} role={scope.role} school={scope.school or '-'} {what} " - f"scope={label} result={result}" - ) - - def _fan_out( - self, call: Callable[[Connection, ControlPlaneClient], Any], deadline: float = DEADLINE - ) -> tuple[list[tuple[Connection, Any, float]], list[dict[str, Any]]]: - """``call`` on every connection in parallel within ``deadline``: (results with their - time in ms, failures with their kind).""" - conns = list(self.store.load().values()) - results: list[tuple[Connection, Any, float]] = [] - failed: list[dict[str, Any]] = [] - if not conns: - return results, failed - - def timed(conn: Connection) -> tuple[Any, float]: - started = time.monotonic() - value = call(conn, ControlPlaneClient(conn)) - return value, (time.monotonic() - started) * 1000 - - jobs = {_POOL.submit(timed, c): c for c in conns} - done, pending = futures.wait(jobs, timeout=deadline) - for job in done: - conn = jobs[job] - try: - value, ms = job.result() - results.append((conn, value, ms)) - except Exception as exc: # noqa: BLE001 - one proxy never blocks the view - failed.append(_failure(conn, exc)) - for job in pending: - conn = jobs[job] - failed.append( - { - "connection": conn.display_name or conn.name, - "kind": "timeout", - "message": f"no answer within {deadline:.0f} s", - } - ) - results.sort(key=lambda item: item[0].name) - failed.sort(key=lambda f: f["connection"]) - return results, failed - - @staticmethod - def _overview(conn: Connection, client: ControlPlaneClient) -> Any: - now = time.monotonic() - with _INSTANCES_LOCK: - hit = _INSTANCES.get(conn.name) - if hit is not None and now - hit[0] < INSTANCES_TTL: - return hit[1] - data = client.request( - "GET", "/v1/activity", query={"usage": "false"}, timeouts=VIEW_TIMEOUTS - ) - with _INSTANCES_LOCK: - _INSTANCES[conn.name] = (now, data) - return data - - @staticmethod - def _instances(overview: Any, scope: Scope) -> list[str]: - """The instances of one proxy that hold activity data of the scope's school.""" - found = [] - for inst in (overview or {}).get("instances") or []: - if not isinstance(inst, dict): - continue - if not (inst.get("enabled") or inst.get("days")): - continue - if scope.school is not None and inst.get("school") != scope.school: - continue - found.append(str(inst.get("name"))) - return found - def _query( - self, - scope: Scope, - path: str, - body: dict[str, Any], - timeouts: tuple[float, float] = VIEW_TIMEOUTS, - text: bool = False, - etags: dict[str, str] | None = None, - deadline: float = DEADLINE, - ) -> tuple[list[tuple[Connection, Any]], list[dict[str, Any]], dict[str, Any]]: - """POST ``body`` to ``path`` of every proxy with matching instances: (answers, failures, - timing). With ``etags`` (connection -> ETag) a proxy may answer NOT_MODIFIED.""" - started = time.monotonic() - - def call(conn: Connection, client: ControlPlaneClient) -> Any: - names = self._instances(self._overview(conn, client), scope) - if not names: - return None - return client.request( - "POST", - path, - {**body, "instances": names}, - timeouts=timeouts, - text=text, - etag=(etags or {}).get(conn.name), - ) - - results, failed = self._fan_out(call, deadline) - timing = { - "total_ms": round((time.monotonic() - started) * 1000), - "proxies": {c.name: round(ms) for c, _r, ms in results}, - } - return [(c, r) for c, r, _ms in results if r is not None], failed, timing - - def _users_for(self, scope: Scope, body: dict[str, Any]) -> tuple[list[str] | None, str, Any]: - """The users list sent to the proxies, a label for the audit, the group (or None). - - A class or project of a school or global administrator lists its teachers only on - request (``teachers``: true, decision E3); a teacher's scope never holds teachers. - """ - group = body.get("group") - if isinstance(group, dict) and group.get("name"): - g = scope.group(str(group.get("kind") or ""), str(group.get("name"))) - with_teachers = body.get("teachers") is True and scope.role != "teacher" - members = [m["user"] for m in g.members if with_teachers or m.get("role") != "teacher"] - return scope.restrict(members), f"{g.kind} {g.name}", g - if scope.users is None: - return None, f"school {scope.school}" if scope.school else "all schools", None - return sorted(scope.users), f"all visible users ({scope.school})", None - - def _empty(self, scope: Scope, what: str, label: str, **extra: Any) -> dict[str, Any]: - self._log(scope, what, label, "empty scope, no proxy asked") - return {"unreachable": [], "timing": {"total_ms": 0, "proxies": {}}, **extra} - - def _labels(self) -> dict[str, Any]: - """Category labels, background categories and lesson hours from the cached overviews.""" - labels: dict[str, str] = {} - background: set[str] = set() - lesson: list[str] | None = None - timezone: str | None = None - with _INSTANCES_LOCK: - cached = [v for _t, v in _INSTANCES.values()] - for overview in cached: - labels.update((overview or {}).get("category_labels") or {}) - background |= set((overview or {}).get("background_categories") or []) - lesson = lesson or (overview or {}).get("lesson_hours") - timezone = timezone or (overview or {}).get("timezone") - return { - "category_labels": labels, - "background_categories": sorted(background), - "lesson_hours": lesson or ["07:45", "16:00"], - "timezone": timezone, - } - - # ------------------------------------------------------------------ scope @get(PREFIX + r"/scope") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("scope") def handle_scope(self, http_context: Any) -> Any: - """What the person may look at: role, school and the classes and projects (counts only; - members per group on request). Asks the proxies only for their (cached) overview.""" - started = time.monotonic() - school = _school((http_context.query or {}).get("school")) - scope = self._scope(school) - results, failed = self._fan_out(self._overview) - schools = sorted( - { - str(i.get("school")) - for _c, r, _ms in results - for i in (r or {}).get("instances") or [] - if isinstance(i, dict) and i.get("school") - } - ) - oldest = sorted( - str(i.get("oldest")) - for _c, r, _ms in results - for i in (r or {}).get("instances") or [] - if isinstance(i, dict) - and i.get("oldest") - and (scope.school is None or i.get("school") == scope.school) - ) - return { - "user": scope.user, - "role": scope.role, - "school": scope.school, - "oldest": oldest[0] if oldest else None, - "schools": schools if scope.is_global else [], - "can_export": scope.can_export, - "is_global": scope.is_global, - "groups": [ - { - **g.brief(), - "students": sum(1 for m in g.members if m.get("role") != "teacher"), - } - for g in scope.groups - ], - **self._labels(), - "unreachable": failed, - "timing": {"total_ms": round((time.monotonic() - started) * 1000)}, - } + """What the person may look at: role, school, classes and projects (counts).""" @get(PREFIX + r"/group/(?Pclass|project)/(?P[^/]+)/members") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("group/{kind}/{name}/members") def handle_members(self, http_context: Any, kind: str = "", name: str = "") -> Any: - """The visible members of one class or project (teachers only for administrators and - only with ``teachers=1``). From the AD only: no proxy, no activity data.""" - query = http_context.query or {} - scope = self._scope(_school(query.get("school"))) - g = scope.group(kind, name) - with_teachers = str(query.get("teachers") or "") == "1" and scope.role != "teacher" - members = [m for m in g.members if with_teachers or m.get("role") != "teacher"] - return { - "kind": g.kind, - "name": g.name, - "members": members, - "teachers_hidden": sum(1 for m in g.members if m.get("role") == "teacher") - if not with_teachers - else 0, - } + """The visible members of one class or project.""" @get(PREFIX + r"/people") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("people") def handle_people(self, http_context: Any) -> Any: - """Up to 10 people of the scope whose login or name contains ``q`` (at least 2 - characters). From the AD only: no proxy, no activity data, no audit needed.""" - query = http_context.query or {} - q = str(query.get("q") or "").strip().lower() - if len(q) < 2 or len(q) > 64: - return {"people": []} - scope = self._scope(_school(query.get("school"))) - found = [] - for user, display in sorted(scope.names.items(), key=lambda kv: kv[1].lower()): - if q in user or q in display.lower(): - found.append( - {"user": user, "display": display, "classes": scope.classes_of.get(user, [])} - ) - if len(found) >= PEOPLE_MAX: - break - return {"people": found} + """Up to 10 people of the scope by login or name.""" - # ---------------------------------------------------------------- queries @post(PREFIX + r"/query/users") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("query/users") def handle_users(self, http_context: Any) -> Any: - """Per user of a class (or the scope): requests, blocked, last seen, active now; the - distinct domains only with ``with_domains`` (expensive, off by default).""" - body = _body(http_context) - scope = self._scope(_school(body.get("school"))) - since, until = _range(body) - users, label, _g = self._users_for(scope, body) - sort = body.get("sort") if body.get("sort") in SORTS else "requests" - if users == []: - return self._empty(scope, "users", label, users=[]) - self._log(scope, "users", label) - results, failed, timing = self._query( - scope, - "/v1/activity/users", - { - "since": since, - "until": until, - "users": users, - "limit": max(1, min(len(users) if users else 1000, 1000)), - "sort": sort, - "with_domains": body.get("with_domains") is True, - "audit": self._audit_info(scope, label), - }, - ) - merged: dict[str, dict[str, Any]] = {} - for _conn, result in results: - for row in result.get("users") or []: - cur = merged.get(row["user"]) - if cur is None: - merged[row["user"]] = dict(row) - continue - for key in ("requests", "bytes", "blocked"): - cur[key] = int(cur.get(key) or 0) + int(row.get(key) or 0) - if row.get("domains") is not None: - cur["domains"] = int(cur.get("domains") or 0) + int(row["domains"]) - cur["last"] = max(int(cur.get("last") or 0), int(row.get("last") or 0)) - cur["active_now"] = bool(cur.get("active_now") or row.get("active_now")) - for name, row in merged.items(): - row["display"] = scope.names.get(name, name) - return {"users": list(merged.values()), "unreachable": failed, "timing": timing} + """The class list.""" @post(PREFIX + r"/query/day") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("query/day") def handle_day(self, http_context: Any) -> Any: - """One student's day (the student page): minutes and domains, merged over the proxies. - - ``etags`` (connection -> ETag of the browser's last answer): when no proxy has anything - new the answer is ``{"not_modified": true}``; the proxies audit every one of these. - """ - body = _body(http_context) - scope = self._scope(_school(body.get("school"))) - user = _user(body.get("user")) - scope.check_user(user) - day = str(body.get("day") or "") - if len(day) != 10: - raise EndpointReturn(422, {"error": "invalid", "field": "day", "message": "day"}) - payload: dict[str, Any] = { - "user": user, - "day": day, - "users": None if scope.users is None else [user], - "audit": self._audit_info(scope, f"user {user}"), - } - for key in ("start", "end", "since_minute"): - if body.get(key) not in (None, ""): - payload[key] = _int(body, key) - etags = body.get("etags") if isinstance(body.get("etags"), dict) else None - self._log(scope, "day", f"user {user} {day}") - results, failed, timing = self._query(scope, "/v1/activity/day", payload, etags=etags) - if etags and results and all(r is NOT_MODIFIED for _c, r in results): - return {"not_modified": True, "unreachable": failed, "timing": timing} - if any(r is NOT_MODIFIED for _c, r in results): - # some proxies have news: everything again, without ETags - results, failed, timing = self._query(scope, "/v1/activity/day", payload) - return { - **merge_days([r for _c, r in results]), - "user": user, - "display": scope.names.get(user, user), - "classes": scope.classes_of.get(user, []), - "day": day, - "etags": {c.name: r.get("_etag") for c, r in results if isinstance(r, dict)}, - "unreachable": failed, - "timing": timing, - } + """One student's day.""" @post(PREFIX + r"/query/timeline") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("query/timeline") def handle_timeline(self, http_context: Any) -> Any: - """One user's activity per hour (heat map) or per minute, optionally of one domain.""" - body = _body(http_context) - scope = self._scope(_school(body.get("school"))) - since, until = _range(body) - user = _user(body.get("user")) - scope.check_user(user) - resolution = "minute" if body.get("resolution") == "minute" else "hour" - domain = str(body.get("domain") or "").strip().lower() or None - if domain is not None and (len(domain) > 253 or any(c.isspace() for c in domain)): - raise EndpointReturn(422, {"error": "invalid", "field": "domain", "message": "domain"}) - label = f"user {user}" + (f" domain {domain}" if domain else "") - self._log(scope, f"timeline {resolution}", label) - payload = { - "since": since, - "until": until, - "user": user, - "users": None if scope.users is None else [user], - "resolution": resolution, - "limit": 5000 if resolution == "minute" else 1000, - "domain": domain, - "audit": self._audit_info(scope, label), - } - etags = body.get("etags") if isinstance(body.get("etags"), dict) else None - results, failed, timing = self._query(scope, "/v1/activity/timeline", payload, etags=etags) - if etags and results and all(r is NOT_MODIFIED for _c, r in results): - return {"not_modified": True, "unreachable": failed, "timing": timing} - if any(r is NOT_MODIFIED for _c, r in results): - results, failed, timing = self._query(scope, "/v1/activity/timeline", payload) - rows: dict[tuple[Any, ...], dict[str, Any]] = {} - for _conn, result in results: - for row in result.get("rows") or []: - key = (row.get("t"), row.get("domain")) - cur = rows.get(key) - if cur is None: - rows[key] = dict(row) - continue - for k in ("requests", "bytes", "blocked"): - cur[k] = int(cur.get(k) or 0) + int(row.get(k) or 0) - ordered = [rows[k] for k in sorted(rows, key=lambda k: (k[0] or 0, k[1] or ""))] - return { - "user": user, - "display": scope.names.get(user, user), - "resolution": resolution, - "rows": ordered, - "etags": {c.name: r.get("_etag") for c, r in results if isinstance(r, dict)}, - "unreachable": failed, - "timing": timing, - } + """Heat map or a domain's minutes.""" @post(PREFIX + r"/query/domains") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("query/domains") def handle_domains(self, http_context: Any) -> Any: - """Top domains of a group or of one user (background services hidden on request).""" - body = _body(http_context) - scope = self._scope(_school(body.get("school"))) - since, until = _range(body) - if body.get("user"): - user = _user(body.get("user")) - scope.check_user(user) - users: list[str] | None = [user] - label = f"user {user}" - else: - users, label, _g = self._users_for(scope, body) - if users == []: - return self._empty(scope, "domains", label, domains=[]) - self._log(scope, "domains", label) - results, failed, timing = self._query( - scope, - "/v1/activity/domains", - { - "since": since, - "until": until, - "users": users, - "limit": 50, - "hide_background": body.get("hide_background") is True, - "audit": self._audit_info(scope, label), - }, - ) - merged: dict[str, dict[str, Any]] = {} - for _conn, result in results: - for row in result.get("domains") or []: - cur = merged.get(row["domain"]) - if cur is None: - merged[row["domain"]] = dict(row) - continue - for k in ("requests", "bytes", "blocked", "users"): - cur[k] = int(cur.get(k) or 0) + int(row.get(k) or 0) - cur["category"] = cur.get("category") or row.get("category") - ordered = sorted(merged.values(), key=lambda r: (-int(r["requests"]), r["domain"])) - return {"domains": ordered[:50], "unreachable": failed, "timing": timing} + """Top domains of a group or a user.""" @post(PREFIX + r"/query/blocked") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("query/blocked") def handle_blocked(self, http_context: Any) -> Any: - """Blocked attempts of a group per domain: how often, by how many, the category.""" - body = _body(http_context) - scope = self._scope(_school(body.get("school"))) - since, until = _range(body) - users, label, _g = self._users_for(scope, body) - if users == []: - return self._empty(scope, "blocked", label, domains=[]) - self._log(scope, "blocked", label) - results, failed, timing = self._query( - scope, - "/v1/activity/blocked", - { - "since": since, - "until": until, - "users": users, - "limit": 100, - "audit": self._audit_info(scope, label), - }, - ) - merged: dict[str, dict[str, Any]] = {} - for _conn, result in results: - for row in result.get("domains") or []: - cur = merged.get(row["domain"]) - if cur is None: - merged[row["domain"]] = dict(row) - continue - cur["blocked"] = int(cur["blocked"]) + int(row["blocked"]) - cur["users"] = int(cur["users"]) + int(row["users"]) - cur["category"] = cur.get("category") or row.get("category") - ordered = sorted( - merged.values(), key=lambda r: (-int(r["users"]), -int(r["blocked"]), r["domain"]) - ) - return {"domains": ordered, "unreachable": failed, "timing": timing} + """Blocked attempts of a group.""" @post(PREFIX + r"/query/search") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("query/search") def handle_search(self, http_context: Any) -> Any: - """Who of the group (or the scope) was on a domain (or a subdomain of it).""" - body = _body(http_context) - scope = self._scope(_school(body.get("school"))) - since, until = _range(body) - domain = str(body.get("domain") or "").strip().lower() - if not domain or len(domain) > 253 or any(c.isspace() for c in domain): - raise EndpointReturn(422, {"error": "invalid", "field": "domain", "message": "domain"}) - users, label, _g = self._users_for(scope, body) - if users == []: - return self._empty(scope, "search", f"{label} domain {domain}", users=[]) - self._log(scope, "search", f"{label} domain {domain}") - results, failed, timing = self._query( - scope, - "/v1/activity/search", - { - "since": since, - "until": until, - "users": users, - "domain": domain, - "limit": 1000, - "audit": self._audit_info(scope, label), - }, - ) - merged: dict[str, dict[str, Any]] = {} - for _conn, result in results: - for row in result.get("users") or []: - cur = merged.get(row["user"]) - if cur is None: - merged[row["user"]] = dict(row) - continue - cur["requests"] = int(cur["requests"]) + int(row["requests"]) - cur["blocked"] = int(cur["blocked"]) + int(row["blocked"]) - cur["first"] = min(int(cur["first"]), int(row["first"])) - cur["last"] = max(int(cur["last"]), int(row["last"])) - cur["domains"] = sorted(set(cur["domains"]) | set(row["domains"]))[:10] - for name, row in merged.items(): - row["display"] = scope.names.get(name, name) - ordered = sorted(merged.values(), key=lambda r: (-int(r["requests"]), r["user"])) - return {"domain": domain, "users": ordered, "unreachable": failed, "timing": timing} + """Who of the group was on a domain.""" @post(PREFIX + r"/export") @authorize(PERM_ACTIVITY) @endpoint(api=True) - @activity_endpoint + @forward("export", timeout=EXPORT_TIMEOUT) def handle_export(self, http_context: Any) -> Any: - """CSV per minute, user and domain: school and global administrators only. Refused as a - whole when a proxy cannot deliver its part (never a CSV with rows missing).""" - body = _body(http_context) - scope = self._scope(_school(body.get("school"))) - if not scope.can_export: - raise ScopeDenied("export is for school and global administrators") - since, until = _range(body) - users, label, _g = self._users_for(scope, body) - header = "time,user,domain,requests,bytes,blocked,category\n" - if users == []: - return {**self._empty(scope, "export", label), "csv": header} - self._log(scope, "export", label) - results, failed, timing = self._query( - scope, - "/v1/activity/export", - { - "since": since, - "until": until, - "users": users, - "audit": self._audit_info(scope, label), - }, - timeouts=LONG, - text=True, - deadline=LONG[1], - ) - if failed: - self._log(scope, "export", label, "refused: a proxy failed") - raise EndpointReturn( - 409, {"error": "export_incomplete", "message": "", "unreachable": failed} - ) - parts = [header] - truncated = False - for _conn, text in results: - body_text = str(text or "") - truncated = truncated or "# truncated" in body_text or "# stopped" in body_text - parts.append(body_text[len(header) :] if body_text.startswith(header) else body_text) - if truncated: - raise EndpointReturn( - 409, {"error": "export_too_large", "message": "", "unreachable": []} - ) - return {"csv": "".join(parts), "unreachable": [], "timing": timing} + """CSV for school and global administrators.""" -def merge_days(answers: list[dict[str, Any]]) -> dict[str, Any]: - """The day answers of several proxies as one: minutes and domains added up, totals again.""" - minutes: dict[int, list[int]] = {} - domains: dict[str, dict[str, Any]] = {} - other = {"count": 0, "requests": 0} - for answer in answers: - for t, n, x, d in answer.get("minutes") or []: - row = minutes.setdefault(int(t), [0, 0, 0]) - row[0] += int(n) - row[1] += int(x) - row[2] = max(row[2], int(d)) - for dom in answer.get("domains") or []: - cur = domains.get(dom["domain"]) - if cur is None: - domains[dom["domain"]] = dict(dom) - continue - for k in ("minutes", "requests", "blocked"): - cur[k] = int(cur.get(k) or 0) + int(dom.get(k) or 0) - cur["category"] = cur.get("category") or dom.get("category") - cur["first"] = min(int(cur["first"]), int(dom["first"])) - cur["last"] = max(int(cur["last"]), int(dom["last"])) - for k in ("count", "requests"): - other[k] += int((answer.get("other") or {}).get(k) or 0) - ordered = sorted(domains.values(), key=lambda d: (-int(d["minutes"]), -int(d["requests"]))) - return { - "minutes": [[t, n, x, d] for t, (n, x, d) in sorted(minutes.items())], - "domains": ordered, - "other": other, - "totals": { - "active_minutes": len(minutes), - "requests": sum(r[0] for r in minutes.values()), - "blocked": sum(r[1] for r in minutes.values()), - "domains": len(domains) + other["count"], - "first": min(minutes) if minutes else None, - "last": max(minutes) if minutes else None, - }, - "cursor": max(minutes) // 60 if minutes else None, - } +def forget_instances(conn: str | None = None) -> None: + """The management page changed settings: the bridge drops its cached instance lists (only a + root worker, i.e. a global administrator's, may ask; best effort, the cache lasts 60 s).""" + bridge_call("root", "POST", "admin/forget", {}, {"connection": conn or ""}, timeout=3.0) diff --git a/webui/lmn_squid/bridge.py b/webui/lmn_squid/bridge.py new file mode 100644 index 0000000..6229278 --- /dev/null +++ b/webui/lmn_squid/bridge.py @@ -0,0 +1,278 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Local bridge of the activity view (ADR-023 addendum 2): the only process that talks to the +proxies for the view "Internetnutzung". + +Why: the WebUI runs the workers of teachers (and students) with the person's own UID; they +cannot read ``/etc/linuxmuster-squid-webui/config.yml`` with the proxies' tokens (0600 root), +and must not. Global and school administrators' workers run as root. One code path for all: +every activity request of the WebUI goes to this bridge over a unix socket. + +Trust: the bridge runs as root (systemd, socket-activated). It takes the caller's identity from +the kernel (``SO_PEERCRED``): a non-root caller is the user of its UID (``getpwuid``, the +winbind domain prefix removed); an identity the caller claims must be that one. Only a root +caller (a WebUI worker of an administrator, which could read the tokens anyway) names the +logged-in person. The scope is computed here from the AD (``activity_scope``); a users list from +the caller is never trusted. The proxies audit every read; the bridge writes one system log +line per request (tag ``lmn-squid-activity``), refused ones included. + +Limits: request ≤ 256 KiB, one request per connection, 10 s to send it, at most 32 requests at +once, per UID at most 60 requests in 10 s (root: 600), answers of views as produced by the +service (the proxies bound them), no shell, no file the caller names. + +Protocol: one JSON object ``{"v": 1, "identity", "method", "path", "query", "body"}``, then the +client shuts its sending side; the answer is ``{"status": int, "data": ...}``, then EOF. +""" + +from __future__ import annotations + +import argparse +import collections +import importlib +import json +import logging +import os +import pwd +import socket +import socketserver +import struct +import sys +import threading +import time +import types +from typing import Any + +SOCKET_PATH = "/run/linuxmuster-squid-webui/activity.sock" +MAX_REQUEST = 256 * 1024 +READ_TIMEOUT = 10.0 +MAX_CONCURRENT = 32 +RATE_WINDOW = 10.0 +RATE_USER = 60 +RATE_ROOT = 600 +IDENTITY_MAX = 64 + +log = logging.getLogger("lmn_squid.bridge") + + +def _load_package() -> Any: + """The plugin's modules without its ``__init__`` (which needs the WebUI core).""" + here = os.path.dirname(os.path.abspath(__file__)) + if "lmn_squid" not in sys.modules: + pkg = types.ModuleType("lmn_squid") + pkg.__path__ = [here] + sys.modules["lmn_squid"] = pkg + return importlib.import_module("lmn_squid.activity_core") + + +def peer_uid(sock: socket.socket) -> int: + creds = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")) + _pid, uid, _gid = struct.unpack("3i", creds) + return int(uid) + + +def account_name(uid: int) -> str | None: + """The AD login of a UID as the WebUI knows it: ``DEV\\dslehr01`` -> ``dslehr01``.""" + try: + name = pwd.getpwuid(uid).pw_name + except KeyError: + return None + for sep in ("\\", "+"): + if sep in name: + name = name.rsplit(sep, 1)[1] + return name.strip().lower() or None + + +class RateLimit: + def __init__(self) -> None: + self.lock = threading.Lock() + self.seen: dict[int, collections.deque[float]] = {} + + def allow(self, uid: int) -> bool: + now = time.monotonic() + limit = RATE_ROOT if uid == 0 else RATE_USER + with self.lock: + q = self.seen.setdefault(uid, collections.deque()) + while q and now - q[0] > RATE_WINDOW: + q.popleft() + if len(q) >= limit: + return False + q.append(now) + return True + + +class Bridge: + def __init__(self, service: Any) -> None: + self.service = service + self.rate = RateLimit() + self.slots = threading.BoundedSemaphore(MAX_CONCURRENT) + self.core = sys.modules["lmn_squid.activity_core"] + + def identity_of(self, uid: int, claimed: Any) -> str: + """Who asks; raises PermissionError with the reason when it cannot be told.""" + user_re = self.core.USER_RE + if uid == 0: + if claimed == "root" or (isinstance(claimed, str) and user_re.match(claimed)): + return str(claimed).lower() if claimed != "root" else "root" + raise PermissionError("no identity") + name = account_name(uid) + if name is None or not user_re.match(name): + raise PermissionError(f"unknown uid {uid}") + if claimed not in (None, "") and str(claimed).lower() != name: + raise PermissionError(f"uid {uid} is {name}, not {str(claimed)[:IDENTITY_MAX]!r}") + return name + + def handle(self, uid: int, raw: bytes) -> tuple[int, Any]: + if not self.rate.allow(uid): + self.service.audit(f"uid={uid} refused reason=rate limit") + return 429, {"error": "rate", "message": "too many requests"} + try: + req = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + return 400, {"error": "invalid", "message": "request is not JSON"} + if not isinstance(req, dict) or req.get("v") != 1: + return 400, {"error": "invalid", "message": "unknown request"} + method = req.get("method") + path = req.get("path") + query = req.get("query") or {} + body = req.get("body") or {} + if ( + method not in ("GET", "POST") + or not isinstance(path, str) + or len(path) > 200 + or not isinstance(query, dict) + or not isinstance(body, dict) + ): + return 400, {"error": "invalid", "message": "bad request"} + if path == "admin/forget": + if uid != 0: + return 403, {"error": "identity", "message": "root only"} + self.core.forget_instances(str(body.get("connection") or "") or None) + return 200, {"forgotten": True} + try: + identity = self.identity_of(uid, req.get("identity")) + except PermissionError as exc: + self.service.audit(f"uid={uid} refused path={path[:100]} reason={exc}") + return 403, {"error": "identity", "message": str(exc)} + query = {str(k): str(v)[:200] for k, v in list(query.items())[:20]} + status, data = self.service.dispatch(identity, method, path, query, body) + # who (kernel UID and person), what, result; never data (journal of the bridge) + log.info("uid=%d identity=%s %s %s -> %d", uid, identity, method, path[:100], status) + return status, data + + +class _Handler(socketserver.BaseRequestHandler): + server: _Server + + def handle(self) -> None: + sock: socket.socket = self.request + bridge = self.server.bridge + if not bridge.slots.acquire(blocking=False): + self._send(503, {"error": "busy", "message": "bridge busy"}) + return + try: + uid = peer_uid(sock) + sock.settimeout(READ_TIMEOUT) + chunks: list[bytes] = [] + size = 0 + started = time.monotonic() + while True: + if time.monotonic() - started > READ_TIMEOUT: + raise TimeoutError + data = sock.recv(65536) + if not data: + break + size += len(data) + if size > MAX_REQUEST: + self._send(413, {"error": "too_large", "message": "request too large"}) + return + chunks.append(data) + sock.settimeout(None) + status, payload = bridge.handle(uid, b"".join(chunks)) + self._send(status, payload) + except (TimeoutError, socket.timeout): + self._send(408, {"error": "timeout", "message": "request not complete in time"}) + except Exception as exc: # noqa: BLE001 - one answer, never a traceback to the page + log.exception("bridge request failed") + self._send(500, {"error": "bridge", "message": type(exc).__name__}) + finally: + bridge.slots.release() + + def _send(self, status: int, data: Any) -> None: + try: + self.request.sendall(json.dumps({"status": status, "data": data}).encode("utf-8")) + except OSError: + pass + + +class _Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): + daemon_threads = True + bridge: Bridge + + +def _systemd_socket() -> socket.socket | None: + if os.environ.get("LISTEN_PID") != str(os.getpid()) or os.environ.get("LISTEN_FDS") != "1": + return None + return socket.socket(fileno=3) + + +class JsonDirectory: + """A fixed directory from a JSON file (tests of the bridge without an AD; root-only option).""" + + def __init__(self, path: str) -> None: + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + self.users = {u["sAMAccountName"]: u for u in data.get("users", [])} + self.projects = data.get("projects", {}) + + def person(self, name: str) -> dict[str, Any] | None: + return self.users.get(name) + + def school_users(self, school: str) -> list[dict[str, Any]]: + return [u for u in self.users.values() if u.get("sophomorixSchoolname") == school] + + def project_groups(self, school: str, project: str) -> list[str]: + return list(self.projects.get(project, [])) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="lmn-squid-activity-bridge") + parser.add_argument( + "--socket", default=None, help=f"bind here (default: systemd or {SOCKET_PATH})" + ) + parser.add_argument( + "--config", default=None, help="the connection file (default: the plugin's)" + ) + parser.add_argument("--directory-json", default=None, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + logging.basicConfig(level=logging.INFO, format="%(message)s") + core = _load_package() + connections = importlib.import_module("lmn_squid.connections") + store = connections.ConnectionStore(args.config or connections.CONFIG_PATH) + if args.directory_json: + directory = JsonDirectory(args.directory_json) + service = core.ActivityService(store, lambda: directory) + else: + service = core.ActivityService(store) + sock = None if args.socket else _systemd_socket() + if sock is not None: + server = _Server(SOCKET_PATH, _Handler, bind_and_activate=False) + server.socket.close() + server.socket = sock + else: + path = args.socket or SOCKET_PATH + if os.path.exists(path): + os.unlink(path) + server = _Server(path, _Handler) + os.chmod(path, 0o666) # who may ask is decided per request (SO_PEERCRED) + server.bridge = Bridge(service) + log.info("lmn-squid activity bridge ready") + try: + server.serve_forever() + except KeyboardInterrupt: + pass + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/webui/tests/test_activity_views.py b/webui/tests/test_activity_views.py index 0802b1c..ca3ee9e 100644 --- a/webui/tests/test_activity_views.py +++ b/webui/tests/test_activity_views.py @@ -20,7 +20,9 @@ import pytest from conftest import SAME_ORIGIN, WebUI, control_plane, free_port, needs_openssl -from lmn_squid import activity_scope, activity_views +import json + +from lmn_squid import activity_core, activity_scope, activity_views, bridge pytestmark = needs_openssl @@ -82,12 +84,59 @@ def project_groups(self, school: str, project: str) -> list[str]: return ["7c"] if project == "p_robotik" else [] +# As in the lab: the WebUI runs administrators' workers as root and teachers' and students' +# workers with their own UID; the bridge learns the UID from the kernel (here: from this map). +UIDS = { + "dslehr01": 2001, + "dslehr02": 2002, + "dslehr03": 2003, + "dslehr04": 2004, + "s5a1": 3001, + "s6b1": 3002, + "dsstaff01": 4001, + "onelehr": 2101, +} +NAMES = {uid: name for name, uid in UIDS.items()} + + +def use_bridge(webui: WebUI, fake: Any, monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Route the view through a real Bridge (identity from the UID, scope from the fake AD).""" + lines: list[str] = [] + service = activity_core.ActivityService(webui.handler.store, lambda: fake, lines.append) + br = bridge.Bridge(service) + monkeypatch.setattr(bridge, "account_name", lambda uid: NAMES.get(uid)) + + def call( + identity: str, + method: str, + path: str, + query: dict, + body: dict, + timeout: float = 15.0, + socket_path: str | None = None, + ) -> tuple[int, Any]: + raw = json.dumps( + { + "v": 1, + "identity": identity, + "method": method, + "path": path, + "query": query, + "body": body, + } + ).encode() + return br.handle(UIDS.get(identity, 0), raw) + + webui.activity.call = call # type: ignore[method-assign,assignment] + return lines + + @pytest.fixture -def ad(webui: WebUI) -> Iterator[FakeDirectory]: +def ad(webui: WebUI, monkeypatch: pytest.MonkeyPatch) -> Iterator[FakeDirectory]: fake = FakeDirectory() activity_scope.CACHE.clear() - activity_views.forget_instances() - webui.activity.directory_factory = lambda: fake # type: ignore[method-assign] + activity_core.forget_instances() + fake.audit = use_bridge(webui, fake, monkeypatch) # type: ignore[attr-defined] yield fake activity_scope.CACHE.clear() @@ -579,8 +628,7 @@ def test_refusals_and_empty_scopes_are_audited( webui: WebUI, ad: FakeDirectory, cp: dict[str, Any], monkeypatch: pytest.MonkeyPatch ) -> None: """Lab A4: refused requests and those without a proxy request were in no log.""" - lines: list[str] = [] - monkeypatch.setattr(activity_views, "audit_line", lines.append) + lines: list[str] = ad.audit # type: ignore[attr-defined] now = setup_proxy(webui, cp, seed=False) login(webui, "dslehr02", "teacher") ad.users["dslehr02"]["schoolclasses"] = [] @@ -590,7 +638,7 @@ def test_refusals_and_empty_scopes_are_audited( webui.call("POST", f"{PREFIX}/query/day", {"user": "s5a1", "day": "2026-11-25"})[0] == 403 ) assert any("dslehr02" in ln and "empty scope" in ln for ln in lines), lines - assert any("dslehr02" in ln and "refused" in ln and "/query/day" in ln for ln in lines), lines + assert any("dslehr02" in ln and "refused" in ln and "query/day" in ln for ln in lines), lines login(webui, "dslehr01", "teacher") users_of(webui, now, group={"kind": "class", "name": "5a"}) assert any("dslehr01" in ln and "class 5a" in ln for ln in lines) @@ -627,7 +675,7 @@ def accept() -> None: "fingerprint": cp["fingerprint"], } assert webui.call("POST", "/api/lmn/squid/connections", body)[0] == 200 - monkeypatch.setattr(activity_views, "DEADLINE", 1.0) + monkeypatch.setattr(activity_core, "DEADLINE", 1.0) login(webui, "dslehr01", "teacher") started = time.monotonic() status, data = users_of(webui, now) @@ -642,7 +690,9 @@ def accept() -> None: assert set(data["timing"]["proxies"]) == {"proxy1"} -def test_scope_of_a_large_school_is_fast_and_small(webui: WebUI) -> None: +def test_scope_of_a_large_school_is_fast_and_small( + webui: WebUI, monkeypatch: pytest.MonkeyPatch +) -> None: """Fake AD: 1000 users, 40 classes, 20 projects; /scope without LDAP < 50 ms, < 20 KB.""" import json as jsonlib @@ -653,7 +703,7 @@ def test_scope_of_a_large_school_is_fast_and_small(webui: WebUI) -> None: f"s{i:04d}", "student", classes=[f"k{i % 40:02d}"], projects=[f"p{i % 20:02d}"] ) activity_scope.CACHE.clear() - webui.activity.directory_factory = lambda: fake # type: ignore[method-assign] + use_bridge(webui, fake, monkeypatch) login(webui, "pgmadmin", "schooladministrator") status, info = webui.call("GET", f"{PREFIX}/scope") # cold: builds the scope assert status == 200 and len(info["groups"]) == 60 diff --git a/webui/tests/test_bridge.py b/webui/tests/test_bridge.py new file mode 100644 index 0000000..79ed43d --- /dev/null +++ b/webui/tests/test_bridge.py @@ -0,0 +1,250 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The activity bridge (ADR-023 addendum 2): the caller's identity comes from the kernel +(SO_PEERCRED), never from the request (except for root, the administrators' workers); limits; +the real unix socket; proxies of other schools and old control planes never fail a request. + +Different UIDs on one socket need root: ``scripts/tests/webui_bridge_uids.sh`` runs that in a +container (teacher, student and root clients against one bridge).""" + +from __future__ import annotations + +import json +import os +import socket +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import pytest +from conftest import WEBUI + +from lmn_squid import activity_core, activity_scope, activity_views, bridge +from lmn_squid.client import ControlPlaneClient, ControlPlaneError +from lmn_squid.connections import ConnectionStore + +USERS = [ + { + "sAMAccountName": "dslehr01", + "sophomorixRole": "teacher", + "sophomorixSchoolname": "default-school", + "schoolclasses": ["5a"], + "projects": [], + }, + { + "sAMAccountName": "s5a1", + "sophomorixRole": "student", + "sophomorixSchoolname": "default-school", + "schoolclasses": ["5a"], + "projects": [], + }, + { + "sAMAccountName": "pgmadmin", + "sophomorixRole": "schooladministrator", + "sophomorixSchoolname": "default-school", + "schoolclasses": [], + "projects": [], + }, +] + + +class Dir: + def person(self, name: str) -> Any: + return next((u for u in USERS if u["sAMAccountName"] == name), None) + + def school_users(self, school: str) -> Any: + return [u for u in USERS if u["sophomorixSchoolname"] == school] + + def project_groups(self, school: str, project: str) -> Any: + return [] + + +@pytest.fixture +def br(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any: + activity_scope.CACHE.clear() + activity_core.forget_instances() + lines: list[str] = [] + store = ConnectionStore(str(tmp_path / "config.yml")) + service = activity_core.ActivityService(store, Dir, lines.append) + b = bridge.Bridge(service) + b.lines = lines # type: ignore[attr-defined] + b.store = store # type: ignore[attr-defined] + names = {2001: "dslehr01", 3001: "s5a1"} + monkeypatch.setattr(bridge, "account_name", lambda uid: names.get(uid)) + yield b + activity_scope.CACHE.clear() + + +def ask( + b: Any, + uid: int, + path: str = "scope", + identity: Any = None, + method: str = "GET", + body: dict[str, Any] | None = None, +) -> tuple[int, Any]: + raw = json.dumps( + { + "v": 1, + "identity": identity, + "method": method, + "path": path, + "query": {}, + "body": body or {}, + } + ).encode() + return b.handle(uid, raw) + + +def test_the_identity_comes_from_the_uid(br: Any) -> None: + status, data = ask(br, 2001) + assert status == 200 and data["role"] == "teacher" and data["user"] == "dslehr01" + # a teacher's worker cannot claim to be someone else + status, data = ask(br, 2001, identity="pgmadmin") + assert status == 403 and data["error"] == "identity" + assert any("uid=2001 refused" in ln for ln in br.lines) + # the student gets nothing; an unknown UID neither + assert ask(br, 3001)[0] == 403 + assert ask(br, 4242)[0] == 403 + # root (an administrator's worker) names the person, and must name one + status, data = ask(br, 0, identity="pgmadmin") + assert status == 200 and data["role"] == "schooladministrator" + assert ask(br, 0)[0] == 403 + assert ask(br, 0, identity="../x")[0] == 403 + + +def test_a_users_list_from_the_caller_is_never_trusted(br: Any) -> None: + """The teacher's own students only, whatever list the request carries.""" + body = { + "since": int(time.time()) - 60, + "until": int(time.time()), + "users": ["pgmadmin", "dslehr01"], + } + status, data = ask(br, 2001, path="query/users", method="POST", body=body) + assert status == 200 and data["users"] == [] + assert any("all visible users" in ln and "dslehr01" in ln for ln in br.lines) + + +def test_only_root_drops_the_cache(br: Any) -> None: + assert ask(br, 2001, path="admin/forget", method="POST")[0] == 403 + assert ask(br, 0, path="admin/forget", method="POST")[0] == 200 + + +def test_rate_limit_per_uid(br: Any) -> None: + statuses = [ask(br, 2001)[0] for _ in range(bridge.RATE_USER + 3)] + assert statuses[: bridge.RATE_USER] == [200] * bridge.RATE_USER + assert statuses[-1] == 429 + assert ask(br, 0, identity="pgmadmin")[0] == 200, "another UID is not limited by it" + + +def test_bad_requests(br: Any) -> None: + assert br.handle(2001, b"not json")[0] == 400 + assert br.handle(2001, json.dumps({"v": 2}).encode())[0] == 400 + assert ask(br, 2001, method="DELETE")[0] == 400 + assert ask(br, 2001, path="nothing/here")[0] == 404 + assert ask(br, 2001, path="group/class/../../etc/members")[0] == 404 + + +def test_other_schools_and_old_servers_never_fail_an_export( + br: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Lab A8: an old proxy (no activity log) or one tagged for another school blocked every + export. Only a proxy that may hold data of the school counts.""" + store = br.store + store.add({"name": "old", "url": "https://127.0.0.1:1", "token": "t" * 32}) + store.add({"name": "one", "url": "https://127.0.0.1:2", "token": "t" * 32, "schools": ["one"]}) + asked: list[str] = [] + + def request(self: ControlPlaneClient, method: str, path: str, *a: Any, **k: Any) -> Any: + asked.append(self.conn.name) + if self.conn.name == "old": + raise ControlPlaneError("too_old", "control plane too old", 404) + raise ControlPlaneError("unreachable", "down") + + monkeypatch.setattr(ControlPlaneClient, "request", request) + body = {"since": int(time.time()) - 3600, "until": int(time.time())} + status, data = ask(br, 0, identity="pgmadmin", path="export", method="POST", body=body) + assert status == 200, data + assert data["csv"].startswith("time,user,domain") + assert "one" not in asked, "a proxy of another school is not asked" + # a proxy of this school that is down still refuses the export + store.add( + { + "name": "here", + "url": "https://127.0.0.1:3", + "token": "t" * 32, + "schools": ["default-school"], + } + ) + status, data = ask(br, 0, identity="pgmadmin", path="export", method="POST", body=body) + assert status == 409 and [f["connection"] for f in data["unreachable"]] == ["here"] + + +def test_bridge_down_is_a_readable_503(tmp_path: Path) -> None: + status, data = activity_views.bridge_call( + "x", "GET", "scope", {}, {}, socket_path=str(tmp_path / "none.sock") + ) + assert (status, data["error"]) == (503, "bridge_down") + + +def test_the_real_socket(tmp_path: Path) -> None: + """bridge.py as a process on a unix socket, asked from this process (its own UID).""" + users = [ + *USERS, + { + "sAMAccountName": os.environ.get("USER", "x"), + "sophomorixRole": "student", + "sophomorixSchoolname": "default-school", + "schoolclasses": [], + "projects": [], + }, + ] + directory = tmp_path / "ad.json" + directory.write_text(json.dumps({"users": users})) + sock = tmp_path / "activity.sock" + proc = subprocess.Popen( + [ + sys.executable, + str(WEBUI / "lmn_squid" / "bridge.py"), + "--socket", + str(sock), + "--config", + str(tmp_path / "config.yml"), + "--directory-json", + str(directory), + ], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + try: + for _ in range(100): + if sock.exists(): + break + time.sleep(0.05) + assert oct(sock.stat().st_mode & 0o777) == "0o666" + status, data = activity_views.bridge_call("", "GET", "scope", {}, {}, socket_path=str(sock)) + # this process's UID maps to a student (or to no AD user at all): nothing + assert status == 403, data + status, data = activity_views.bridge_call( + "pgmadmin", "GET", "scope", {}, {}, socket_path=str(sock) + ) + assert os.getuid() == 0 or (status == 403 and data["error"] == "identity") + # an oversized request is cut off, the bridge stays up + big = socket.socket(socket.AF_UNIX) + big.connect(str(sock)) + try: + big.sendall(b"x" * (bridge.MAX_REQUEST + 10)) + except OSError: + pass + big.shutdown(socket.SHUT_WR) + answer = json.loads(big.recv(65536) or b"{}") + big.close() + assert answer.get("status") == 413 + assert ( + activity_views.bridge_call("", "GET", "scope", {}, {}, socket_path=str(sock))[0] == 403 + ) + finally: + proc.terminate() + proc.wait(timeout=10) diff --git a/webui/tests/test_build.py b/webui/tests/test_build.py index 850e17a..1662a95 100644 --- a/webui/tests/test_build.py +++ b/webui/tests/test_build.py @@ -26,8 +26,10 @@ def test_build_produces_what_the_webui_serves(tmp_path: Path) -> None: files = sorted(str(p.relative_to(dest)) for p in dest.rglob("*") if p.is_file()) assert files == [ "__init__.py", + "activity_core.py", "activity_scope.py", "activity_views.py", + "bridge.py", "client.py", "connections.py", "jobs.py", From e66220a55f2f64df7a74505876498ae3e7d36334 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 16:17:20 +0100 Subject: [PATCH 21/45] feat(packaging): socket-activated activity bridge in the webui package linuxmuster-squid-webui-activity.socket (0666, authorisation per request) starts the bridge service as root with systemd hardening. The maintainer scripts enable and start the socket on install, restart the service on upgrade, stop it on remove and drop its state on purge. --- debian/linuxmuster-squid-webui.install | 3 ++ debian/linuxmuster-squid-webui.postinst | 17 +++++++++ debian/linuxmuster-squid-webui.postrm | 5 +++ debian/linuxmuster-squid-webui.prerm | 5 +++ .../linuxmuster-squid-webui-activity.service | 37 +++++++++++++++++++ .../linuxmuster-squid-webui-activity.socket | 17 +++++++++ 6 files changed, 84 insertions(+) create mode 100644 packaging/systemd/linuxmuster-squid-webui-activity.service create mode 100644 packaging/systemd/linuxmuster-squid-webui-activity.socket diff --git a/debian/linuxmuster-squid-webui.install b/debian/linuxmuster-squid-webui.install index cdc949b..f31f043 100644 --- a/debian/linuxmuster-squid-webui.install +++ b/debian/linuxmuster-squid-webui.install @@ -5,3 +5,6 @@ # assembled by webui/build_plugin.py (debian/rules), the bundled control-plane .deb by # execute_before_dh_builddeb-indep. scripts/provision-keytab.sh usr/share/linuxmuster-squid-webui/ +# The bridge of the internet use view (ADR-023 addendum 2): socket-activated, root. +packaging/systemd/linuxmuster-squid-webui-activity.socket lib/systemd/system/ +packaging/systemd/linuxmuster-squid-webui-activity.service lib/systemd/system/ diff --git a/debian/linuxmuster-squid-webui.postinst b/debian/linuxmuster-squid-webui.postinst index 2e465fd..8cbf712 100644 --- a/debian/linuxmuster-squid-webui.postinst +++ b/debian/linuxmuster-squid-webui.postinst @@ -61,6 +61,23 @@ case "$1" in [ "$(stat -c '%u %a %F' /run/lmn_squid)" != "0 700 directory" ]; }; then rm -rf /run/lmn_squid fi + # The bridge of the internet use view (ADR-023 addendum 2), by Debian's rules: enabled on + # a new installation, the admin's decision kept afterwards; restarted on an upgrade so + # it runs this package's code. + SOCKET=linuxmuster-squid-webui-activity.socket + deb-systemd-helper unmask "$SOCKET" >/dev/null || true + if deb-systemd-helper --quiet was-enabled "$SOCKET"; then + deb-systemd-helper enable "$SOCKET" >/dev/null || true + else + deb-systemd-helper update-state "$SOCKET" >/dev/null || true + fi + if [ -d /run/systemd/system ]; then + systemctl daemon-reload || true + if [ "$(systemctl is-enabled "$SOCKET" 2>/dev/null)" = enabled ]; then + deb-systemd-invoke start "$SOCKET" || true + deb-systemd-invoke try-restart linuxmuster-squid-webui-activity.service || true + fi + fi refresh_webui echo "linuxmuster-squid-webui: log out of the WebUI and in again to see 'Squid proxy'" ;; diff --git a/debian/linuxmuster-squid-webui.postrm b/debian/linuxmuster-squid-webui.postrm index 7dbe425..30f4aff 100644 --- a/debian/linuxmuster-squid-webui.postrm +++ b/debian/linuxmuster-squid-webui.postrm @@ -3,6 +3,10 @@ # SPDX-License-Identifier: GPL-3.0-or-later set -e +if [ -d /run/systemd/system ]; then + systemctl daemon-reload || true +fi + case "$1" in remove) # The plugin files are gone: drop its permissions from the merged file and LDAP and @@ -23,6 +27,7 @@ case "$1" in rm -rf /run/lmn_squid ;; purge) + deb-systemd-helper purge linuxmuster-squid-webui-activity.socket >/dev/null || true # The connection list with the control planes' tokens. The service accounts # squid- and their SPNs in AD stay: remove them with samba-tool (docs/install.md). rm -rf /etc/linuxmuster-squid-webui /run/lmn_squid diff --git a/debian/linuxmuster-squid-webui.prerm b/debian/linuxmuster-squid-webui.prerm index 0366276..1132467 100644 --- a/debian/linuxmuster-squid-webui.prerm +++ b/debian/linuxmuster-squid-webui.prerm @@ -9,5 +9,10 @@ if [ "$1" = remove ] || [ "$1" = upgrade ] || [ "$1" = deconfigure ]; then rm -rf /usr/lib/linuxmuster-webui/plugins/lmn_squid/__pycache__ fi +if [ "$1" = remove ] && [ -d /run/systemd/system ]; then + deb-systemd-invoke stop linuxmuster-squid-webui-activity.socket \ + linuxmuster-squid-webui-activity.service >/dev/null || true +fi + #DEBHELPER# exit 0 diff --git a/packaging/systemd/linuxmuster-squid-webui-activity.service b/packaging/systemd/linuxmuster-squid-webui-activity.service new file mode 100644 index 0000000..9ca1cbf --- /dev/null +++ b/packaging/systemd/linuxmuster-squid-webui-activity.service @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +[Unit] +Description=linuxmuster-squid WebUI: bridge of the internet use view +Documentation=https://github.com/faircomp/linuxmuster-squid +Requires=linuxmuster-squid-webui-activity.socket +After=network-online.target + +[Service] +Type=simple +# Root: it reads the proxies' tokens (/etc/linuxmuster-squid-webui/config.yml, 0600 root) and the +# AD the way the WebUI's root workers do (linuxmusterTools). The interpreter of the WebUI's venv +# (linuxmusterTools and python-ldap come from its system site packages). +ExecStart=/bin/sh -c 'PY=/opt/linuxmuster/bin/python3; [ -x "$PY" ] || PY=/usr/bin/python3; exec "$PY" -I /usr/lib/linuxmuster-webui/plugins/lmn_squid/bridge.py' +Restart=on-failure +RestartSec=2 +MemoryMax=256M +TasksMax=128 + +NoNewPrivileges=yes +# full, not strict: linuxmusterTools runs "net conf list" when imported, which opens Samba's +# tdb files under /var/lib/samba (the WebUI's root workers run it without any sandbox). +ProtectSystem=full +ProtectHome=yes +PrivateTmp=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native diff --git a/packaging/systemd/linuxmuster-squid-webui-activity.socket b/packaging/systemd/linuxmuster-squid-webui-activity.socket new file mode 100644 index 0000000..0896625 --- /dev/null +++ b/packaging/systemd/linuxmuster-squid-webui-activity.socket @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +[Unit] +Description=linuxmuster-squid WebUI: bridge of the internet use view (socket) +Documentation=https://github.com/faircomp/linuxmuster-squid + +[Socket] +ListenStream=/run/linuxmuster-squid-webui/activity.sock +# Every local process may connect: the bridge decides per request from the caller's UID +# (SO_PEERCRED) what it may see; the WebUI runs teachers' workers with their AD UIDs, which a +# local group cannot list in advance (ADR-023 addendum 2). +SocketMode=0666 +DirectoryMode=0755 +RemoveOnStop=yes + +[Install] +WantedBy=sockets.target From c9a1145cde0ec448c5916cf71035eef3107cb86a Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 16:17:20 +0100 Subject: [PATCH 22/45] fix(webui): depend on lmn_common and never break the sidebar The core builds the sidebar in plugin load order and fails on a missing attachment point; with only 'core' as dependency aj loaded lmn_squid before lmn_common and the whole menu answered 500 (lab A5). Depend on lmn_common like every upstream lmn_* plugin, and attach to category:class only when lmn_common was imported first (Software otherwise). --- webui/lmn_squid/main.py | 19 +++++++- webui/lmn_squid/plugin.yml | 7 +++ webui/tests/test_worker_side.py | 81 +++++++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 webui/tests/test_worker_side.py diff --git a/webui/lmn_squid/main.py b/webui/lmn_squid/main.py index 0296314..269cad6 100644 --- a/webui/lmn_squid/main.py +++ b/webui/lmn_squid/main.py @@ -31,6 +31,23 @@ MANAGEMENT_NAME = _("Squid proxy") +def _classroom_available() -> bool: + """Whether category:class exists when the core reaches this plugin's sidebar items: lmn_common + defines it and must have been imported before lmn_squid (the core builds the sidebar in load + order and raises on a missing attachment point, lab A5; lmn_common can fail at import while + its dependents still load).""" + try: + import aj + from aj.plugins import PluginManager + + loaded = list(PluginManager.get(aj.context).get_loaded_plugins_list()) + return "lmn_common" in loaded and ( + "lmn_squid" not in loaded or loaded.index("lmn_common") < loaded.index("lmn_squid") + ) + except Exception: # noqa: BLE001 - tests and tools without the WebUI core + return False + + @component(SidebarItemProvider) class ItemProvider(SidebarItemProvider): def __init__(self, context: Any) -> None: @@ -46,7 +63,7 @@ def provide(self) -> list[dict[str, Any]]: "children": [], }, { - "attach": ACTIVITY_CATEGORY, + "attach": ACTIVITY_CATEGORY if _classroom_available() else "category:software", "name": ACTIVITY_NAME, "icon": "fas fa-globe", "url": ACTIVITY_URL, diff --git a/webui/lmn_squid/plugin.yml b/webui/lmn_squid/plugin.yml index 457ed2c..c11dbf1 100644 --- a/webui/lmn_squid/plugin.yml +++ b/webui/lmn_squid/plugin.yml @@ -11,6 +11,13 @@ dependencies: - !PluginDependency { plugin_name: core } + # lmn_common defines the sidebar category "Klassenzimmer" (category:class) the view attaches + # to; the core builds the sidebar in plugin load order and fails on a missing category (lab + # 2026-11-25, A5). A hard dependency like every upstream lmn_* plugin: aj 2.2.16 orders an + # OptionalPluginDependency unreliably (it put lmn_squid first in the integration test). + - !PluginDependency { + plugin_name: lmn_common + } resources: - 'resources/js/module.es' - 'resources/js/routing.es' diff --git a/webui/tests/test_worker_side.py b/webui/tests/test_worker_side.py new file mode 100644 index 0000000..85f8568 --- /dev/null +++ b/webui/tests/test_worker_side.py @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""What runs inside the WebUI's workers (lab 2026-11-25, A5/A6). The real check is +``scripts/tests/webui_ajenti_it.sh`` (aj 2.2.16, real lmn_common, forked gevent workers); +these are the fast guards of the same mistakes.""" + +from __future__ import annotations + +import ast +import sys +from typing import Any + +import pytest +from conftest import WEBUI + +from lmn_squid import main + +WORKER_MODULES = ["activity_views.py", "views.py", "main.py", "__init__.py"] + + +@pytest.mark.parametrize("name", WORKER_MODULES) +def test_no_thread_pools_in_the_worker(name: str) -> None: + """A6: a ThreadPoolExecutor of the worker broke after aj forked it ("operation on destroyed + loop"). The worker does not run threads for the activity view; the bridge does.""" + tree = ast.parse((WEBUI / "lmn_squid" / name).read_text()) + imported = { + n.module if isinstance(n, ast.ImportFrom) else a.name + for n in ast.walk(tree) + if isinstance(n, (ast.Import, ast.ImportFrom)) + for a in (n.names if isinstance(n, ast.Import) else [n]) + } + assert not {"concurrent.futures", "threading", "multiprocessing"} & { + str(m) for m in imported + }, f"{name} imports thread machinery" + + +def _with_load_order(monkeypatch: pytest.MonkeyPatch, order: list[str]) -> None: + aj = sys.modules["aj"] + plugins = sys.modules["aj.plugins"] + + class PM: + @staticmethod + def get(_ctx: Any) -> Any: + return PM() + + def get_loaded_plugins_list(self) -> Any: + return iter(order) + + monkeypatch.setattr(plugins, "PluginManager", PM, raising=False) + monkeypatch.setattr(aj, "context", object(), raising=False) + + +@pytest.mark.parametrize( + ("order", "attach"), + [ + (["core", "lmn_common", "lmn_squid"], "category:class"), + # lmn_squid before lmn_common: the core would not find category:class yet (lab A5) + (["core", "lmn_squid", "lmn_common"], "category:software"), + # lmn_common failed at import + (["core", "lmn_squid"], "category:software"), + ], +) +def test_the_entry_attaches_only_where_the_core_finds_it( + monkeypatch: pytest.MonkeyPatch, order: list[str], attach: str +) -> None: + _with_load_order(monkeypatch, order) + items = {i["url"]: i["attach"] for i in main.ItemProvider(None).provide()} + assert items == {main.URL: "category:software", main.ACTIVITY_URL: attach} + + +def test_no_core_means_software(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delattr(sys.modules["aj.plugins"], "PluginManager", raising=False) + assert main._classroom_available() is False + + +def test_the_plugin_depends_on_lmn_common_like_upstream() -> None: + """aj 2.2.16 orders an OptionalPluginDependency unreliably; upstream lmn_* plugins use a + hard one.""" + text = (WEBUI / "lmn_squid" / "plugin.yml").read_text() + assert "!PluginDependency {\n plugin_name: lmn_common" in text + assert "- !OptionalPluginDependency" not in text From 2d758fc8a9feffeabf80487fc0c01e7cc2c3ca99 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 16:17:20 +0100 Subject: [PATCH 23/45] fix(webui): German failure texts, translated when shown The proxies' failure details were translated when the controller started, before the catalogue arrived, and stayed English. Translate at display time; German texts for a bridge that does not answer, the rate limit, an unreadable AD, a missing keytab and an unhealthy container. --- webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 15 ++++++ .../js/controllers/activity.controller.es | 53 ++++++++++++------- .../js/controllers/index.controller.es | 8 ++- 3 files changed, 57 insertions(+), 19 deletions(-) diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index e77d342..0f3f0f0 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -1668,3 +1668,18 @@ msgstr "Tage" msgid "live" msgstr "live" + +msgid "The keytab of the instance is missing (create it with the keytab button of the server)." +msgstr "Die Keytab der Instanz fehlt (mit dem Keytab-Knopf des Servers erzeugen)." + +msgid "The new container did not become healthy; the previous one runs on." +msgstr "Der neue Container wurde nicht gesund; der bisherige läuft weiter." + +msgid "The service of the internet use on the school server does not answer (linuxmuster-squid-webui-activity)." +msgstr "Der Dienst der Internetnutzung auf dem Schulserver antwortet nicht (linuxmuster-squid-webui-activity)." + +msgid "The user directory (AD) could not be read." +msgstr "Das Benutzerverzeichnis (AD) konnte nicht gelesen werden." + +msgid "Too many requests in a short time; please wait a moment." +msgstr "Zu viele Anfragen in kurzer Zeit; bitte einen Moment warten." diff --git a/webui/lmn_squid/resources/js/controllers/activity.controller.es b/webui/lmn_squid/resources/js/controllers/activity.controller.es index c660970..07d73d8 100644 --- a/webui/lmn_squid/resources/js/controllers/activity.controller.es +++ b/webui/lmn_squid/resources/js/controllers/activity.controller.es @@ -75,27 +75,35 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ return Math.floor(Date.now() / 1000); } - var FAILURE_TEXT = { - unreachable: gettext('not reachable'), - timeout: gettext('does not answer in time (5 s)'), - too_old: gettext('version too old for this function (update linuxmuster-squid)'), - auth: gettext('token refused'), - allowlist: gettext('refuses this server (tls_allowed_clients)'), - tls: gettext('certificate does not match the stored fingerprint'), - fingerprint: gettext('certificate does not match the stored fingerprint'), - too_large: gettext('answer too large: choose a shorter range or one class') - }; - var LIMIT_TEXT = { - range_too_long: gettext('time range too long'), - too_many_users: gettext('too many people at once'), - too_many_hits: gettext('too many hits: choose a shorter range or a longer domain name'), - query_too_large: gettext('query too large: choose a shorter range or fewer people') - }; + // Translated when shown, not when the controller starts: on a page opened directly the + // catalogue may arrive after this controller ran (lab: details stayed English). + function failureKindText(kind) { + switch (kind) { + case 'unreachable': return gettext('not reachable'); + case 'timeout': return gettext('does not answer in time (5 s)'); + case 'too_old': return gettext('version too old for this function (update linuxmuster-squid)'); + case 'auth': return gettext('token refused'); + case 'allowlist': return gettext('refuses this server (tls_allowed_clients)'); + case 'tls': + case 'fingerprint': return gettext('certificate does not match the stored fingerprint'); + case 'too_large': return gettext('answer too large: choose a shorter range or one class'); + default: return gettext('error'); + } + } + function limitText(code) { + switch (code) { + case 'range_too_long': return gettext('time range too long'); + case 'too_many_users': return gettext('too many people at once'); + case 'too_many_hits': return gettext('too many hits: choose a shorter range or a longer domain name'); + case 'query_too_large': return gettext('query too large: choose a shorter range or fewer people'); + default: return ''; + } + } $scope.failureText = function (f) { if (f.kind === 'limit') { - return LIMIT_TEXT[f.code] || f.message; + return limitText(f.code) || f.message; } - return (FAILURE_TEXT[f.kind] || gettext('error')) + (f.kind === 'error' && f.message ? ': ' + f.message : ''); + return failureKindText(f.kind) + (f.kind === 'error' && f.message ? ': ' + f.message : ''); }; $scope.toggleFailures = function () { $scope.showFailures = !$scope.showFailures; }; @@ -115,6 +123,15 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ if (data && data.error === 'scope') { return gettext('Not in your classes and projects.'); } + if (data && (data.error === 'bridge_down' || data.error === 'bridge_timeout' || data.error === 'bridge')) { + return gettext('The service of the internet use on the school server does not answer (linuxmuster-squid-webui-activity).'); + } + if (data && data.error === 'rate') { + return gettext('Too many requests in a short time; please wait a moment.'); + } + if (data && data.error === 'directory') { + return gettext('The user directory (AD) could not be read.'); + } if (data && data.message) { return data.message; } diff --git a/webui/lmn_squid/resources/js/controllers/index.controller.es b/webui/lmn_squid/resources/js/controllers/index.controller.es index af1261b..de34fde 100644 --- a/webui/lmn_squid/resources/js/controllers/index.controller.es +++ b/webui/lmn_squid/resources/js/controllers/index.controller.es @@ -772,7 +772,13 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco return gettext('Confirm the privacy notice first.'); } if (detail.code === 'apply_failed') { - return gettext('The internet use was not changed; the instance runs as before.') + ' ' + (detail.message || ''); + var why = detail.message || ''; + if (why.indexOf('KeytabMissing') >= 0) { + why = gettext('The keytab of the instance is missing (create it with the keytab button of the server).'); + } else if (why.indexOf('did not become healthy') >= 0) { + why = gettext('The new container did not become healthy; the previous one runs on.'); + } + return gettext('The internet use was not changed; the instance runs as before.') + ' ' + why; } return $scope.errorText(resp); } From b8d2745de71d2d15879ff5fad116ccf1f53f75bf Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 16:17:20 +0100 Subject: [PATCH 24/45] test(webui): the plugin in the real WebUI core with the bridge webui_ajenti_it.sh loads the plugin into aj 2.2.16 with the real lmn_common and linuxmusterTools (lmn73), builds the sidebar for every role and calls the activity view in forked gevent workers demoted to the teacher's and the student's UIDs, through the bridge against a real control plane; then asks the bridge directly under those UIDs. Fails against the previous commit with the lab's A5, A6 and A7 errors. Part of the e2e tier. --- scripts/tests/run.sh | 8 + scripts/tests/webui_ajenti_it.sh | 101 +++++++ scripts/tests/webui_ajenti_it/Dockerfile | 20 ++ scripts/tests/webui_ajenti_it/cp_server.py | 75 +++++ scripts/tests/webui_ajenti_it/it.py | 266 ++++++++++++++++++ .../tests/webui_ajenti_it/it_auth/__init__.py | 81 ++++++ .../tests/webui_ajenti_it/it_auth/plugin.yml | 14 + scripts/tests/webui_ajenti_it/peer.py | 39 +++ 8 files changed, 604 insertions(+) create mode 100755 scripts/tests/webui_ajenti_it.sh create mode 100644 scripts/tests/webui_ajenti_it/Dockerfile create mode 100644 scripts/tests/webui_ajenti_it/cp_server.py create mode 100644 scripts/tests/webui_ajenti_it/it.py create mode 100644 scripts/tests/webui_ajenti_it/it_auth/__init__.py create mode 100644 scripts/tests/webui_ajenti_it/it_auth/plugin.yml create mode 100644 scripts/tests/webui_ajenti_it/peer.py diff --git a/scripts/tests/run.sh b/scripts/tests/run.sh index 225317c..d069a66 100755 --- a/scripts/tests/run.sh +++ b/scripts/tests/run.sh @@ -130,6 +130,14 @@ e2e(){ # same compose file, so they run one after the other, after the Kerberos suite). run_step "provision-keytab-smoke" docker bash scripts/tests/provision_keytab_smoke.sh run_step "discover-ad-facts-smoke" docker bash scripts/tests/discover_ad_facts_smoke.sh + # The WebUI plugin in the real WebUI core (aj 2.2.16, real lmn_common, forked workers under + # the teacher's and the student's UIDs, the activity bridge): needs the upstream checkouts. + if [ -d "$ROOT/../../upstream/linuxmuster-webui7" ]; then # the hub layout + run_step "webui-ajenti-it" docker bash scripts/tests/webui_ajenti_it.sh + run_step "webui-ajenti-it (lmn_common broken)" docker bash scripts/tests/webui_ajenti_it.sh broken + else + skip "webui-ajenti-it" "upstream linuxmuster-webui7/-tools/sophomorix4 checkouts missing" + fi # Docker directly, or via sudo when the user is not (yet) in the docker group (crabbox). local asroot=(); docker info >/dev/null 2>&1 || asroot=(sudo) # Build broken image (FROM :dev) for the auto-rollback test. diff --git a/scripts/tests/webui_ajenti_it.sh b/scripts/tests/webui_ajenti_it.sh new file mode 100755 index 0000000..5246d26 --- /dev/null +++ b/scripts/tests/webui_ajenti_it.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The WebUI plugin in the real WebUI core (aj 2.2.16 like the lab, with the real upstream +# lmn_common and linuxmusterTools), in a throw-away container: the sidebar for every role, +# the activity view in forked gevent workers demoted to the teacher's and the student's UIDs, +# through the activity bridge (root, SO_PEERCRED) against a real control plane. +# Argument "broken": lmn_common fails at import; the sidebar must still build. +# Needs Docker and the upstream checkouts in ../../upstream (linuxmuster-webui7 and +# linuxmuster-tools at lmn73, sophomorix4 at bionic). Exit code = failed checks. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +HUB="$(cd "$ROOT/../.." && pwd)" +UPSTREAM="${LMNSQUID_UPSTREAM:-$HUB/upstream}" +IMG=lmnsquid-ajenti-it:aj2.2.16 +docker image inspect "$IMG" >/dev/null 2>&1 || docker build -q -t "$IMG" "$ROOT/scripts/tests/webui_ajenti_it" >/dev/null +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT +# the upstream plugin and tools at lmn73, exported from git (no working-tree changes) +git -C "$UPSTREAM/linuxmuster-webui7" archive origin/lmn73 usr/lib/linuxmuster-webui/plugins/lmn_common \ + | tar -C "$WORK" -x +git -C "$UPSTREAM/linuxmuster-tools" archive origin/lmn73 usr/lib/python3/dist-packages/linuxmusterTools \ + | tar -C "$WORK" -x +# sophomorix.ini, which linuxmusterTools reads when imported (sophomorix4, branch bionic) +git -C "$UPSTREAM/sophomorix4" archive origin/bionic sophomorix-samba/config-devel/sophomorix.ini \ + | tar -C "$WORK" -x +docker run --rm -v "$ROOT:/src:ro" -v "$WORK:/upstream:ro" -e TZ=Europe/Berlin "$IMG" bash -c ' +set -e +PY=/opt/linuxmuster/bin/python3 +SITE=$($PY -c "import site; print(site.getsitepackages()[0])") +cp -r /upstream/usr/lib/python3/dist-packages/linuxmusterTools "$SITE/" +mkdir -p /plugins /etc/linuxmuster/webui /etc/samba /var/lib/linuxmuster /usr/share/sophomorix/devel +cp /upstream/sophomorix-samba/config-devel/sophomorix.ini /usr/share/sophomorix/devel/ +mkdir -p /etc/linuxmuster/sophomorix/default-school +: > /etc/linuxmuster/sophomorix/default-school/devices.csv +printf "[setup]\nschoolname = Test\n" > /var/lib/linuxmuster/setup.ini +cp -r /upstream/usr/lib/linuxmuster-webui/plugins/lmn_common /plugins/ +cp -r /src/scripts/tests/webui_ajenti_it/it_auth /plugins/ +[ "${1:-}" = broken ] && sed -i "1i raise RuntimeError(\"lmn_common broken on purpose\")" /plugins/lmn_common/__init__.py +$PY -I /src/webui/build_plugin.py /src/webui/lmn_squid /plugins/lmn_squid +# what lmn_common and linuxmusterTools read when they are imported +printf "linuxmuster:\n ldap:\n binddn: cn=x\n bindpw: x\n searchdn: dc=dev,dc=lmschule,dc=de\n" > /etc/linuxmuster/webui/config.yml +printf "[global]\n realm = DEV.LMSCHULE.DE\n workgroup = DEV\n netbios name = SERVER\n" > /etc/samba/smb.conf +printf "#!/bin/sh\nexit 0\n" > /usr/bin/net && chmod 755 /usr/bin/net +useradd -u 2001 -M dslehr01; useradd -u 3001 -M dsextra01 +# the proxies: one real control plane; the connection file root-only, as on the server +$PY /src/scripts/tests/webui_ajenti_it/cp_server.py > /var/tmp/cp.log 2>&1 & +for i in $(seq 1 50); do $PY -c "import socket; socket.create_connection((\"127.0.0.1\", 18080))" 2>/dev/null && break; sleep 0.2; done +mkdir -p /etc/linuxmuster-squid-webui && chmod 700 /etc/linuxmuster-squid-webui +printf "version: 1\nconnections:\n- name: lab\n url: http://127.0.0.1:18080\n token: it-token-0123456789abcdef0123456789\n schools: [default-school]\n" > /etc/linuxmuster-squid-webui/config.yml +chmod 600 /etc/linuxmuster-squid-webui/config.yml +cat > /var/tmp/ad.json < /var/tmp/bridge.log 2>&1 & +for i in $(seq 1 50); do [ -S /run/linuxmuster-squid-webui/activity.sock ] && break; sleep 0.1; done +rc=0 +if [ "${1:-}" = broken ]; then + $PY /src/scripts/tests/webui_ajenti_it/it.py --broken-lmn-common || rc=$? +else + $PY /src/scripts/tests/webui_ajenti_it/it.py || rc=$? + # the bridge on its own, asked by processes running as the teacher and the student (SO_PEERCRED) + PEER="$PY -I /src/scripts/tests/webui_ajenti_it/peer.py" + T=$(date +%s); B="{\"since\": $((T - 3600)), \"until\": $((T + 60))}" + expect() { # + want=$1; user=$2; shift 2 + got=$(runuser -u "$user" -- $PEER "$@" 2>&1 | tail -1) + if [ "$got" = "$want" ]; then echo " [PASS] bridge as $user: $* -> $got" + else echo " [FAIL] bridge as $user: $* -> $got (want $want)"; rc=$((rc + 1)); fi + } + expect "200 - 3" dslehr01 "" POST query/users "$B" + expect "200 - 3" dslehr01 dslehr01 POST query/users "$B" + expect "403 identity -" dslehr01 pgmadmin POST query/users "$B" + expect "403 identity -" dslehr01 root GET scope + expect "403 identity -" dslehr01 "" POST admin/forget + expect "403 scope -" dsextra01 "" GET scope + expect "403 scope -" dsextra01 "" POST query/users "$B" + expect "403 scope -" nobody "" GET scope + # school-wide without a group: the whole school as the proxies saw it, the teacher who + # browsed included (E3 hides teachers in class and project lists only; reported 2026-11-25) + expect "200 - 5" root pgmadmin POST query/users "$B" + echo "-- bridge log (kernel UID per request)"; cat /var/tmp/bridge.log + if grep -q "uid=2001 identity=dslehr01 POST query/day" /var/tmp/bridge.log \ + && grep -q "uid=0 identity=pgmadmin POST query/users" /var/tmp/bridge.log; then + echo " [PASS] the WebUI workers reached the bridge with the teacher UID and root for the admin" + else + echo " [FAIL] bridge UIDs"; rc=$((rc + 1)) + fi +fi +exit $rc +' -- "${1:-}" diff --git a/scripts/tests/webui_ajenti_it/Dockerfile b/scripts/tests/webui_ajenti_it/Dockerfile new file mode 100644 index 0000000..6df3df6 --- /dev/null +++ b/scripts/tests/webui_ajenti_it/Dockerfile @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The WebUI core as on a linuxmuster.net 7.3 server (lab: aj 2.2.16), for +# scripts/tests/webui_ajenti_it.sh: a venv like /opt/linuxmuster (system site packages) with aj, +# the core, ace and filesystem plugins (lmn_common depends on them) and what lmn_common and +# linuxmusterTools import; the control plane's dependencies for a real proxy API in the test. +FROM ubuntu:24.04@sha256:008173c23f95b170204355c12626cb5a965d779a7e1283b09e9cffbb1bf33ca3 +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update -qq \ + && apt-get install -y -qq --no-install-recommends python3-venv python3-dev gcc \ + libldap2-dev libsasl2-dev libmagic1 libffi-dev libssl-dev python3-ldap ca-certificates \ + >/dev/null \ + && rm -rf /var/lib/apt/lists/* +RUN python3 -m venv --system-site-packages /opt/linuxmuster \ + && /opt/linuxmuster/bin/pip install -q --no-cache-dir \ + aj==2.2.16 ajenti-panel==2.2.16 ajenti.plugin.core==0.116 ajenti.plugin.ace==0.32 \ + ajenti.plugin.filesystem==0.51 configobj dpath==2.0.6 paramiko python-magic pexpect \ + pyyaml simplejson pytest \ + fastapi uvicorn pydantic pydantic-settings docker httpx typer diff --git a/scripts/tests/webui_ajenti_it/cp_server.py b/scripts/tests/webui_ajenti_it/cp_server.py new file mode 100644 index 0000000..38eef09 --- /dev/null +++ b/scripts/tests/webui_ajenti_it/cp_server.py @@ -0,0 +1,75 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""A real control plane (fake Docker) with activity data, on 127.0.0.1:18080, for the test.""" + +import importlib.util +import os +import sys +import time +from zoneinfo import ZoneInfo + +import uvicorn + +sys.path.insert(0, "/src/controlplane") +from lmnsquid import activity +from lmnsquid.api import create_app +from lmnsquid.config import Settings +from lmnsquid.models import Instance +from lmnsquid.reconciler import Reconciler +from lmnsquid.store import Store +from lmnsquid.updater import Updater + +spec = importlib.util.spec_from_file_location( + "cpt", "/src/controlplane/tests/conftest.py" +) +cpt = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cpt) + +base = "/var/tmp/cp" +os.makedirs(base, exist_ok=True) +settings = Settings( + api_token="it-token-0123456789abcdef0123456789", + instances_dir=f"{base}/instances", + secrets_dir=f"{base}/secrets", + blocklists_dir=f"{base}/blocklists", + catalog_dir=f"{base}/catalog", + activity_dir=f"{base}/activity", + activity_spool_dir=f"{base}/spool", +) +store = Store(settings.instances_dir) +docker = cpt.FakeDockerService( + secrets_dir=settings.secrets_dir, blocklists_dir=settings.blocklists_dir +) +inst = Instance( + school="default-school", + role="students", + ad_group="students", + realm="EX.LAN", + visible_hostname="proxy.ex.lan", + keytab_secret="proxy.keytab", + image="x/y:1", + activity_log_enabled=True, + activity_ack_by="it", + activity_ack_at="now", +) +store.put(inst) +docker.ensure_running(inst) +now = int(time.time()) +spool = activity.ensure_spool(settings.activity_spool_dir, inst.name) +lines = "".join( + f"{now - 120} {u}@EX.LAN site-{u}.example 200 TCP_TUNNEL 100 -\n" + for u in ("s5a1", "s5a2", "s6b1", "dslehr01", "dsextra01") +) +lines += f"{now - 60} s5a1@EX.LAN lotto.example 403 TCP_DENIED 10 gambling\n" +(spool / f"act-{now:010d}-it000000-000001.log").write_text(lines) +activity.collect_instance( + inst, settings.activity_dir, settings.activity_spool_dir, ZoneInfo("Europe/Berlin") +) +app = create_app( + settings, + store, + Reconciler(store, docker), + docker, + Updater(store, docker, Reconciler(store, docker)), +) +uvicorn.run(app, host="127.0.0.1", port=18080, log_level="warning") diff --git a/scripts/tests/webui_ajenti_it/it.py b/scripts/tests/webui_ajenti_it/it.py new file mode 100644 index 0000000..cb26894 --- /dev/null +++ b/scripts/tests/webui_ajenti_it/it.py @@ -0,0 +1,266 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The plugin in the real WebUI core (aj 2.2.16 as in the lab), run by webui_ajenti_it.sh. + +Loads core, ace, filesystem, the real upstream lmn_common (with the real linuxmusterTools), +the test authentication provider and lmn_squid the way ajenti-panel does, then opens real +sessions through the gate: every session is a forked gevent worker (gipc) that logs in and is +demoted like lmn_auth does it (administrators stay root, the teacher and the student run with +their own UIDs). Checks: the sidebar builds for every role (lab A5); the activity endpoints +answer in the forked workers, several times in a row (A6); a teacher's worker, which cannot read +the proxies' tokens, gets its students' data through the bridge, which saw the teacher's UID +(A7); the student gets nothing. + +``--broken-lmn-common``: lmn_common fails at import (it does when the server's files are +missing); lmn_squid still loads, its entry falls back to Software instead of breaking the sidebar. +""" + +import io +import json +import os +import sys +import time + +import aj +import aj.core # gevent monkey patch, as ajenti-panel does +from aj.config import AjentiUsers, BaseConfig, TFAConfig +from aj.gate.middleware import GateMiddleware +from aj.http import HttpContext +from aj.plugins import DirectoryPluginProvider, PluginManager, PythonPathPluginProvider +from jadi import Context + +FAILS = [] + + +def check(cond, what): + print((" [PASS] " if cond else " [FAIL] ") + what, flush=True) + if not cond: + FAILS.append(what) + + +class Config(BaseConfig): + def load(self): + self.data = { + "auth": {"provider": "it", "users_file": "/var/tmp/users.yml"}, + "bind": {"mode": "tcp", "host": "127.0.0.1", "port": 0}, + } + + def save(self): + pass + + +def setup(): + aj.product = "ajenti" + aj.debug = False + aj.dev = False + aj.dev_autologin = False + aj.init() + aj.context = Context() + aj.config = Config() + aj.config.load() + aj.config.ensure_structure() + with open("/var/tmp/users.yml", "w") as fh: + fh.write("users: {}\n") + aj.users = AjentiUsers("/var/tmp/users.yml") + aj.users.load() + aj.tfa_config = TFAConfig() + aj.tfa_config.data = {"users": {}} + import builtins + + builtins._ = lambda x: x + aj.plugin_providers = [ + DirectoryPluginProvider("/plugins"), + PythonPathPluginProvider(), + ] + PluginManager.get(aj.context).load_all_from(aj.plugin_providers) + + +def request(gm, session, method, path, body=None, query=""): + raw = json.dumps(body).encode() if body is not None else b"" + env = { + "REQUEST_METHOD": method, + "PATH_INFO": path, + "QUERY_STRING": query, + "HTTP_COOKIE": f"session={session.key}", + "HTTP_HOST": "server.lmn.lan", + "SERVER_NAME": "server.lmn.lan", + "SERVER_PORT": 443, + "HTTP_ORIGIN": "https://server.lmn.lan", + "SSL": True, + "SSL_CLIENT_AUTH_FORCE": False, # what aj's RequestHandler sets for every request + "SSL_CLIENT_VALID": False, + "SSL_CLIENT_USER": None, + "wsgi.url_scheme": "https", + "REMOTE_ADDR": "127.0.0.1", + "CONTENT_TYPE": "application/json;charset=utf-8", + "CONTENT_LENGTH": str(len(raw)), + "wsgi.input": io.BytesIO(raw), + } + ctx = HttpContext(env) + content = gm.handle(ctx) + status = int(str(ctx.status).split()[0]) + text = b"".join(c if isinstance(c, bytes) else c.encode() for c in content).decode() + try: + data = json.loads(text) + except ValueError: + data = text + return status, data + + +def find_entry(tree, url, path=()): + for child in tree.get("children", []): + here = path + (child.get("id") or child.get("name"),) + if child.get("url") == url: + return here + found = find_entry(child, url, here) + if found: + return found + return None + + +def main(): + without = "--broken-lmn-common" in sys.argv + setup() + pm = PluginManager.get(aj.context) + order = list(pm) + print("load order:", order, flush=True) + check("lmn_squid" in order, "lmn_squid loaded") + if without: + check("lmn_common" not in order, "lmn_common failed at import (as intended)") + else: + check("lmn_common" in order, "the real lmn_common loaded") + check( + order.index("lmn_common") < order.index("lmn_squid"), + "lmn_common loads first", + ) + gm = GateMiddleware.get(aj.context) + sessions = {} + for user in ("global-admin", "pgmadmin", "dslehr01", "dsextra01"): + sessions[user] = gm.open_session( + {"REMOTE_ADDR": "127.0.0.1"}, initial_identity=user + ) + time.sleep(2) + + # --- A5: the sidebar for every role + for user, session in sessions.items(): + status, data = request(gm, session, "GET", "/api/core/sidebar") + check( + status == 200, + f"sidebar for {user}: {status} {str(data)[:200] if status != 200 else ''}", + ) + if status != 200: + continue + where = find_entry(data.get("sidebar", {}), "/view/lmn/squid-activity") + if user == "dsextra01": + check(where is None, "student: no Internetnutzung entry") + else: + want = "category:software" if without else "category:class" + check( + where is not None and where[0] == want, + f"{user}: entry under {want} ({where})", + ) + if without: + return + + # --- A6/A7: the activity view in forked workers, through the bridge + now = int(time.time()) + day = time.strftime("%Y-%m-%d", time.localtime(now)) + t = sessions["dslehr01"] + status, data = request(gm, t, "GET", "/api/lmn/squid-activity/scope") + check( + status == 200 and data.get("role") == "teacher", + f"teacher /scope: {status} {str(data)[:200]}", + ) + for i in range(3): # the second request after the fork failed in the lab + status, data = request( + gm, + t, + "POST", + "/api/lmn/squid-activity/query/users", + { + "since": now - 3600, + "until": now + 60, + "group": {"kind": "class", "name": "5a"}, + }, + ) + users = ( + sorted(u["user"] for u in data.get("users", [])) if status == 200 else data + ) + check( + status == 200 and users == ["dsextra01", "s5a1", "s5a2"], + f"teacher class list #{i + 1}: {status} {users}", + ) + status, data = request( + gm, t, "POST", "/api/lmn/squid-activity/query/day", {"user": "s5a1", "day": day} + ) + check( + status == 200 and data.get("totals", {}).get("blocked") == 1, + f"teacher: own student's day: {status} {str(data)[:160]}", + ) + status, data = request( + gm, t, "POST", "/api/lmn/squid-activity/query/day", {"user": "s6b1", "day": day} + ) + check(status == 403, f"teacher: another class's student: {status}") + status, data = request( + gm, + t, + "POST", + "/api/lmn/squid-activity/export", + {"since": now - 3600, "until": now + 60}, + ) + check(status == 403, f"teacher: no export: {status}") + # the teacher's worker cannot read the tokens (why the bridge exists) + status, data = request(gm, t, "GET", "/api/lmn/squid/connections") + check(status == 403, f"teacher: management refused: {status}") + + a = sessions["pgmadmin"] + for i in range(3): + status, data = request( + gm, + a, + "POST", + "/api/lmn/squid-activity/query/users", + { + "since": now - 3600, + "until": now + 60, + "group": {"kind": "class", "name": "6b"}, + }, + ) + users = ( + sorted(u["user"] for u in data.get("users", [])) if status == 200 else data + ) + check( + status == 200 and users == ["s6b1"], + f"school admin class list #{i + 1}: {status} {users}", + ) + status, data = request( + gm, + a, + "POST", + "/api/lmn/squid-activity/export", + { + "since": now - 3600, + "until": now + 60, + "group": {"kind": "class", "name": "5a"}, + }, + ) + check( + status == 200 and "lotto.example" in data.get("csv", ""), + f"school admin export: {status}", + ) + + s = sessions["dsextra01"] + status, data = request(gm, s, "GET", "/api/lmn/squid-activity/scope") + check(status == 403, f"student /scope: {status}") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: # noqa: BLE001 - the workers must not keep the test alive + import traceback + + traceback.print_exc() + FAILS.append(f"crashed: {exc!r}") + print(f"{len(FAILS)} failed", flush=True) + os._exit(1 if FAILS else 0) diff --git a/scripts/tests/webui_ajenti_it/it_auth/__init__.py b/scripts/tests/webui_ajenti_it/it_auth/__init__.py new file mode 100644 index 0000000..600799d --- /dev/null +++ b/scripts/tests/webui_ajenti_it/it_auth/__init__.py @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Authentication provider of the integration test: like lmn_auth for what matters here. + +Permissions per role from the plugins' permissions.yml (as merge-permissions.py and +sophomorix-ui would write them to LDAP); workers of administrators stay root, workers of +teachers and students are demoted to the person's own UID (lmn_auth's get_isolation_uid). +""" + +import os +import pwd + +import yaml +from aj.auth import AuthenticationProvider +from jadi import component + +ROLES = { + "global-admin": "globaladministrator", + "pgmadmin": "schooladministrator", + "dslehr01": "teacher", + "dsextra01": "student", +} + + +def _permissions(): + out = {} + for name in ("lmn_squid",): + path = os.path.join("/plugins", name, "permissions.yml") + with open(path) as fh: + for role, entries in (yaml.safe_load(fh) or {}).items(): + for entry in entries: + key, value = entry.split(": ") + out.setdefault(role, {})[key] = value == "true" + return out + + +PERMS = _permissions() + + +@component(AuthenticationProvider) +class ItAuthenticationProvider(AuthenticationProvider): + id = "it" + name = "integration test" + + def __init__(self, context): + self.context = context + + def authenticate(self, username, password): + return username in ROLES + + def authorize(self, username, permission): + # as lmn_auth: the permission comes as a dict, unknown permissions are refused + if username == "root": + return True + return PERMS.get(ROLES.get(username, ""), {}).get(permission["id"], False) + + def get_isolation_uid(self, username): + # as lmn_auth: administrators' workers stay root, everybody else runs with the own UID + if username == "root" or ROLES.get(username, "").endswith("administrator"): + return 0 + try: + return pwd.getpwnam(username).pw_uid + except KeyError: + return pwd.getpwnam("nobody").pw_uid + + def get_isolation_gid(self, username): + if self.get_isolation_uid(username) == 0: + return 0 + try: + return pwd.getpwnam(username).pw_gid + except KeyError: + return pwd.getpwnam("nobody").pw_gid + + def get_profile(self, username): + return {"sophomorixRole": ROLES.get(username, "")} + + def prepare_environment(self, username): + self.context.profile = self.get_profile(username) + + def signout(self): + pass diff --git a/scripts/tests/webui_ajenti_it/it_auth/plugin.yml b/scripts/tests/webui_ajenti_it/it_auth/plugin.yml new file mode 100644 index 0000000..07cb858 --- /dev/null +++ b/scripts/tests/webui_ajenti_it/it_auth/plugin.yml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +name: it_auth +author: test +email: test@example.invalid +url: https://example.invalid +version: '1.0' +title: 'Test authentication' +icon: key +dependencies: + - !PluginDependency { + plugin_name: core + } +resources: [] diff --git a/scripts/tests/webui_ajenti_it/peer.py b/scripts/tests/webui_ajenti_it/peer.py new file mode 100644 index 0000000..213df53 --- /dev/null +++ b/scripts/tests/webui_ajenti_it/peer.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""A raw bridge client for webui_ajenti_it.sh, run under another UID (runuser). + +usage: peer.py [json body] +prints: """ + +import json +import socket +import sys + +identity, method, path = sys.argv[1:4] +body = json.loads(sys.argv[4]) if len(sys.argv) > 4 else {} +s = socket.socket(socket.AF_UNIX) +s.connect("/run/linuxmuster-squid-webui/activity.sock") +s.sendall( + json.dumps( + { + "v": 1, + "identity": identity, + "method": method, + "path": path, + "query": {}, + "body": body, + } + ).encode() +) +s.shutdown(socket.SHUT_WR) +raw = b"" +while chunk := s.recv(65536): + raw += chunk +answer = json.loads(raw) +data = answer["data"] +users = data.get("users") if isinstance(data, dict) else None +print( + answer["status"], + data.get("error", "-") if isinstance(data, dict) else "-", + len(users) if isinstance(users, list) else "-", +) From 3646717935431bab4e1d318c9a2add6a97d69af3 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 16:17:20 +0100 Subject: [PATCH 25/45] docs: activity bridge (ADR-023 addendum 2, T27, operations, tests) --- debian/changelog | 10 +++++++++ docs/decisions.md | 47 +++++++++++++++++++++++++++++++++++++++++++ docs/operations.md | 23 +++++++++++++++++++++ docs/test-strategy.md | 21 +++++++++++++++++++ docs/threat-model.md | 1 + 5 files changed, 102 insertions(+) diff --git a/debian/changelog b/debian/changelog index 7ef6200..822e24e 100644 --- a/debian/changelog +++ b/debian/changelog @@ -192,6 +192,16 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium the instance opens as a page with Overview, Filter, Lists, Logs and Internet use (no more dialog with seven tabs); unsaved filter changes are no longer lost silently; list changes apply at once. + * WebUI plugin: the page "Internetnutzung" reaches the proxies through a + local service, linuxmuster-squid-webui-activity (socket-activated, + root, /run/linuxmuster-squid-webui/activity.sock): teachers' WebUI + sessions run with their own user id and cannot read the proxies' + tokens. The service takes the caller from the kernel, computes what + the person may see from the AD itself and answers only that; the + package enables and starts the socket. The plugin now depends on + lmn_common (like every lmn_* plugin), so its menu entry can no longer + break the whole WebUI menu; proxies of other schools and proxies + without the activity log no longer block an export. -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium diff --git a/docs/decisions.md b/docs/decisions.md index 042ed6b..afbee65 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -748,6 +748,53 @@ sites on individual students, mind performance when viewing"; spec TLS connection reuse, "active now" on the class tiles (it would read activity data on the start page). +**Addendum 2 (2026-11-25, lab recheck of the WebUI, `lab-activity-2026-11-25.md` section +"Nachtest Runde 2"):** three blockers of the real WebUI that the plugin's unit tests could not see. +- **A7, the activity bridge (new trust boundary):** the WebUI runs the workers of teachers (and + students) with the person's own UID (lmn_auth `get_isolation_uid`); administrators' workers run + as root. A teacher's worker cannot read `/etc/linuxmuster-squid-webui/config.yml` (0600 root, + the proxies' root-equivalent tokens, T18) and must not. Every request of the view, of every role, + now goes through one code path: the WebUI endpoint (`activity_views.py`, a thin forwarder that + checks the permission and the origin) sends `{"v": 1, identity, method, path, query, body}` over + the unix socket `/run/linuxmuster-squid-webui/activity.sock` to the bridge + `linuxmuster-squid-webui-activity.service` (root, socket-activated, `bridge.py`), which runs + the whole view logic (`activity_core.py`: scope from the AD, proxy requests with the tokens, + audit, merging). The bridge takes the caller from the kernel (`SO_PEERCRED`): a non-root + caller *is* the account of its UID (`getpwuid`, winbind domain prefix removed); a claimed + identity must be that one. Only root callers (administrators' workers, which can read the + tokens anyway) name the logged-in person. The scope is computed in the bridge from the AD; a + users list of the caller is never trusted. Limits: 256 KiB per request, 10 s to send it, one + request per connection, at most 32 at once, per UID 60 requests in 10 s (root 600), no shell, + no path from the caller. The socket is 0666: a local group cannot list the AD's teacher UIDs in + advance, and the authorisation is per request from the UID (a local process of a student or of + `nobody` gets 403). Considered and rejected: sudo for teacher workers (upstream gives teachers + `sudo ALL` through `webui-sudoers`, so it would work on today's servers, but it would tie the + view to a sudo rule upstream may narrow, and a sudo helper started per request is slower and + parses arguments from the caller); a token readable by a group (exposes the tokens to every + teacher process); a fixed per-teacher token on the proxy (the proxies would need the AD). +- **A6:** the worker held a module-level `ThreadPoolExecutor`; aj forks the workers with gevent + (gipc), and the pool's threads did not survive: from the second request on "operation on + destroyed loop" (500). The worker now does only a cooperative socket call; the bridge, a normal + threaded process, fans out to the proxies (its pool is created lazily per process). A bridge + that is down or slow becomes a German message on the page (503/504), never an empty table. +- **A5:** the entry under `category:class` broke the whole sidebar (500 "Attachment point not + found") whenever aj loaded the plugin before lmn_common, which defines the category. The plugin + now depends on lmn_common with a hard `!PluginDependency` like every upstream `lmn_*` plugin + (aj 2.2.16 orders an `!OptionalPluginDependency` unreliably: its "less strict" pass put + lmn_squid first in the integration test), and attaches to `category:class` only when + lmn_common was imported before it; otherwise under *Software* (lmn_common can fail at import + while its dependents still load). +- **A8:** a proxy holding no instance of the requested school (its connection is tagged with + other schools) is not asked, and a proxy whose control plane predates the activity log + (`too_old`) holds no data; neither refuses an export any more. A proxy of the school that does + not answer still refuses it. +- **Tests that would have caught them:** `scripts/tests/webui_ajenti_it.sh` (e2e tier) loads the + plugin into the real aj 2.2.16 with ajenti.plugin.core 0.116 and the real upstream lmn_common + and linuxmusterTools (lmn73), builds the sidebar for every role and calls the view in forked + gevent workers demoted to the teacher's and the student's UIDs, through the bridge, against a + real control plane; then talks to the bridge directly as those UIDs. Against 54448dc it fails + with exactly the lab's A5, A6 and A7 errors. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/operations.md b/docs/operations.md index 4c4071c..14d8df7 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -785,6 +785,29 @@ school days a year about 5.5 GiB per 1000 students at 365 days' retention (10.5 day of the year were a school day), 0.2 GiB at the default 7 days. Scale linearly with users and requests; plan the space of `/var/lib/linuxmuster-squid` accordingly. +### The bridge of the view on the school server + +The page *Internetnutzung* reaches the proxies through a local service of the plugin package +(ADR-023 addendum 2): `linuxmuster-squid-webui-activity.socket` listens on +`/run/linuxmuster-squid-webui/activity.sock` and starts `linuxmuster-squid-webui-activity.service` +(root) on the first request. It reads the connection list with the tokens and the AD; the WebUI's +workers (teachers run with their own UID) only talk to the socket. The package enables and starts +the socket; an upgrade restarts the service. + +```bash +systemctl status linuxmuster-squid-webui-activity.socket linuxmuster-squid-webui-activity.service +journalctl -u linuxmuster-squid-webui-activity.service # one line per request: uid, identity, path, status +journalctl -t lmn-squid-activity # the audit lines of the view (who looked at whom) +``` + +The page says "Der Dienst der Internetnutzung auf dem Schulserver antwortet nicht" when the +socket is stopped or the service fails: `systemctl restart linuxmuster-squid-webui-activity.socket`. +"Zu viele Anfragen" = more than 60 requests of one person in 10 s (the page's live updates stay far +below). Overhead of the bridge on top of the proxies: about 1 ms per request (local measurement, +`/scope` from a fixed directory, median 0.95 ms). After changing the connection list by hand, +the bridge sees the change at once (it reads the file per request); its cache of the proxies' +overviews lasts 60 s, a change in the management page drops it. + ### ⚠️ Data protection (GDPR) Access logs show **who visited/was blocked from which site** = personal data diff --git a/docs/test-strategy.md b/docs/test-strategy.md index 68d6d29..43d2feb 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -144,6 +144,27 @@ directories `deploy/e2e/lists-noauth/`, `deploy/e2e/lists-legacy/` for the noaut 403) is proven against a real domain in the lab (7.3.1 campaign fix) and is part of the acceptance list in `deployment-gpo.md`. +## Heavy tier — the WebUI plugin in the real WebUI core (Docker) + +`scripts/tests/webui_ajenti_it.sh` (in `run.sh e2e`/`all` when the hub's upstream checkouts are +there; image `scripts/tests/webui_ajenti_it/Dockerfile`): aj 2.2.16 and ajenti.plugin.core 0.116 +(the lab's versions) in a venv like `/opt/linuxmuster`, the real upstream `lmn_common` and +`linuxmusterTools` exported from `upstream/linuxmuster-webui7` and `upstream/linuxmuster-tools` +at `lmn73` (`sophomorix.ini` from sophomorix4), a test authentication provider that demotes +workers like lmn_auth (administrators root, teacher and student with their own UIDs), the bridge +(root, fixed directory), a real control plane with activity data, the connection file 0600 root. +Checks: load order (lmn_common before lmn_squid); `GET /api/core/sidebar` for global admin, +school admin, teacher and student (200; *Internetnutzung* under *Klassenzimmer*, not for the +student); the view's endpoints in the forked gevent workers, three times in a row; teacher scope +(own class yes, other class 403, export 403, management 403); school admin lists and export; +student 403; then the bridge directly from processes running as the teacher, the student, +`nobody` and root (`SO_PEERCRED`: claiming another identity 403, students and unknown accounts +403). `webui_ajenti_it.sh broken` makes lmn_common fail at import: the sidebar still builds, the +entry goes under *Software*. Against 54448dc the test fails with the lab's A5 (sidebar 500), A6 +("operation on destroyed loop" from the second request on) and A7 (teacher 409, config not +readable) — evidence in the hub, `work/linuxmuster-squid/lab-activity-2026-11-25/runde3-it/`. +Not covered: the browser (Angular) side and real AD/LDAP; the lab recheck does those. + ## Negative/security catalog (grows per phase; part of the DoD) - **P1:** no ticket→407; student→403; SPN mismatch/FQDN-as-IP → no 200. diff --git a/docs/threat-model.md b/docs/threat-model.md index 9d5280d..6a25641 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -47,6 +47,7 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T24 | **Activity log = profile of browsing per person** (ADR-023): data of students and staff, a teacher looking at students of other classes or at colleagues, an exported CSV passed on | off by default per instance; switching on needs who confirmed the privacy notice (stored with the time in the instance's git log); minute and domain only, no URL, no client address; retention 1–365 days as whole day files (deleted before a query could read them); scope computed on the school server from the AD on every request, only the allowed users list goes to the proxy, which filters every SQL statement on it; teachers only students of their own classes/projects and school, never teachers; export only for administrators; every read and every settings change audited (person, scope, users, range) before data is read, 503 if the audit log cannot be written; the audit log only for global administrators, own retention | `test_activity.py`, `test_activity_api.py`, webui `test_activity_views.py`, E2E spool check | | T25 | **The users list comes from the WebUI** (ADR-023): the proxy cannot check who asks; a stolen token reads everything | the token is the global administrator's credential already (T5, T18); the list is computed on the server, never taken from the browser; the audit names the person the WebUI reports and, for the CLI, `cli:`; the WebUI logs every request of the view, refused ones and those without a proxy request included, to its system log (`journalctl -t lmn-squid-activity`) | `test_activity_views.py` (out-of-scope requests never reach a proxy) | | T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 1733 (squid's proxy user can create, not list; no set-group-id, which `RestrictSUIDSGID=yes` refuses), files 0644 unreachable for other host users behind the 0750 parent; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured) | `test_activity.py` (receiver), local squid 6.14 test | +| T27 | **The activity bridge** (ADR-023 addendum 2): a root service on a socket every local process can open; a teacher's worker (or any local user) claims to be someone else, asks for students outside its classes, floods the bridge, or sends a huge or slow request; a bug in the bridge leaks the tokens | the identity of a non-root caller comes from the kernel (`SO_PEERCRED` → `getpwuid`), a claimed identity must match it; only root names a person; the scope is computed in the bridge from the AD, a users list of the caller is ignored; tokens never leave the bridge (answers carry activity data and typed errors only); request ≤ 256 KiB, 10 s, 32 at once, 60 per UID in 10 s; no shell, no path from the caller; systemd hardening (`ProtectSystem=full`, `NoNewPrivileges`, `ProtectHome`, private /tmp, kernel protections); one log line per request with UID and identity, refusals audited (tag `lmn-squid-activity`). Residual: upstream gives teachers `sudo ALL` (`webui-sudoers`), so a teacher with a shell on the server is root anyway; the bridge does not make that worse | `webui/tests/test_bridge.py`; `scripts/tests/webui_ajenti_it.sh` (bridge asked as teacher, student, `nobody` and root UIDs) | ## Non-goals (deliberate) From 840572f5e11997bab752a67039650ffa966825d8 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 16:29:53 +0100 Subject: [PATCH 26/45] test(packaging): the activity bridge of the built package under systemd webui_bridge_systemd.sh installs linuxmuster-squid-webui in a container with systemd as PID 1 and checks the socket, socket activation as root, SO_PEERCRED through the systemd-passed socket, reinstall, remove and purge. --- docs/test-strategy.md | 6 +++ scripts/tests/webui_bridge_systemd.sh | 65 +++++++++++++++++++++++++++ webui/tests/test_bridge.py | 5 ++- 3 files changed, 74 insertions(+), 2 deletions(-) create mode 100755 scripts/tests/webui_bridge_systemd.sh diff --git a/docs/test-strategy.md b/docs/test-strategy.md index 43d2feb..3e03120 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -164,6 +164,12 @@ entry goes under *Software*. Against 54448dc the test fails with the lab's A5 (s ("operation on destroyed loop" from the second request on) and A7 (teacher 409, config not readable) — evidence in the hub, `work/linuxmuster-squid/lab-activity-2026-11-25/runde3-it/`. Not covered: the browser (Angular) side and real AD/LDAP; the lab recheck does those. +`scripts/tests/webui_bridge_systemd.sh ` (by hand after `make deb`) +installs the built package in a container with systemd as PID 1: the socket enabled and active +(0666), the service started by the first connection (socket activation, root), `SO_PEERCRED` +through the systemd-passed socket (a local user claiming another identity: 403), no traceback +without an AD (503 "directory"), reinstall keeps it working, remove stops it, purge leaves +nothing. ## Negative/security catalog (grows per phase; part of the DoD) diff --git a/scripts/tests/webui_bridge_systemd.sh b/scripts/tests/webui_bridge_systemd.sh new file mode 100755 index 0000000..ea3193a --- /dev/null +++ b/scripts/tests/webui_bridge_systemd.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The built linuxmuster-squid-webui .deb with real systemd (container with systemd as PID 1): +# install enables and starts the bridge's socket; the first connection starts the service as +# root through socket activation (LISTEN_FDS); the bridge takes the caller from SO_PEERCRED of +# the systemd-passed socket (a local user claiming someone else: 403; an unknown UID: 403; root +# without the AD: a German-mappable 503 'directory', no traceback); an upgrade (reinstall) +# keeps it running; remove stops it; purge leaves nothing. +# usage: webui_bridge_systemd.sh Exit code = failed checks. +set -euo pipefail +DEB="$(readlink -f "${1:?usage: $0 }")" +NAME="lmnsquid-bridge-sd-$$" +IMG=ubuntu:24.04@sha256:008173c23f95b170204355c12626cb5a965d779a7e1283b09e9cffbb1bf33ca3 +cleanup() { docker rm -f "$NAME" >/dev/null 2>&1 || true; } +trap cleanup EXIT +docker run -d --name "$NAME" --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \ + -v "$DEB:/pkg/webui.deb:ro" --tmpfs /run --tmpfs /run/lock "$IMG" \ + bash -c 'apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq systemd systemd-sysv python3-yaml >/dev/null && exec /sbin/init' >/dev/null +for _ in $(seq 1 120); do + docker exec "$NAME" sh -c 'systemctl is-system-running 2>/dev/null | grep -qE "running|degraded"' && break + sleep 2 +done +docker exec -i "$NAME" bash -s <<'IN' +set -u +fails=0 +ok() { echo " [PASS] $*"; } +no() { echo " [FAIL] $*"; fails=$((fails + 1)); } +ask() { # -> " " + runuser -u "$1" -- python3 -I -c ' +import json, socket, sys +s = socket.socket(socket.AF_UNIX); s.connect("/run/linuxmuster-squid-webui/activity.sock") +s.sendall(json.dumps({"v": 1, "identity": sys.argv[1], "method": "GET", "path": "scope", "query": {}, "body": {}}).encode()) +s.shutdown(socket.SHUT_WR); raw = b"" +while (c := s.recv(65536)): raw += c +a = json.loads(raw); print(a["status"], a["data"].get("error", "-"))' "$2" 2>&1 | tail -1 +} +useradd -M -u 2001 dslehr01 +# Docker's Ubuntu images forbid starting services from maintainer scripts; a server does not +rm -f /usr/sbin/policy-rc.d +# install (its dependencies are the WebUI's; the bridge needs python3 and yaml only) +DEBIAN_FRONTEND=noninteractive dpkg -i --force-depends /pkg/webui.deb >/var/tmp/install.log 2>&1 || true +[ "$(systemctl is-enabled linuxmuster-squid-webui-activity.socket)" = enabled ] && ok "socket enabled" || no "socket not enabled" +[ "$(systemctl is-active linuxmuster-squid-webui-activity.socket)" = active ] && ok "socket active" || no "socket not active" +[ "$(systemctl is-active linuxmuster-squid-webui-activity.service)" = inactive ] && ok "service waits for the first request" || no "service already running" +mode=$(stat -c %a /run/linuxmuster-squid-webui/activity.sock); [ "$mode" = 666 ] && ok "socket 0666" || no "socket mode $mode" +r=$(ask dslehr01 pgmadmin); [ "$r" = "403 identity" ] && ok "local user claiming another identity: $r" || no "claim: $r" +[ "$(systemctl is-active linuxmuster-squid-webui-activity.service)" = active ] && ok "service started by socket activation" || no "service not started" +[ "$(systemctl show -p User --value linuxmuster-squid-webui-activity.service)" = "" ] && ok "service runs as root" || no "service user" +r=$(ask nobody ""); case "$r" in "403 "*|"503 directory") ok "nobody gets no data: $r";; *) no "nobody: $r";; esac # 403 with an AD +r=$(ask root pgmadmin); [ "$r" = "503 directory" ] && ok "root without an AD: $r" || no "root: $r" +journalctl -u linuxmuster-squid-webui-activity.service --no-pager | grep -q "Traceback" && no "traceback in the journal" || ok "no traceback in the journal" +# upgrade = reinstall of the same package: still enabled, answers +DEBIAN_FRONTEND=noninteractive dpkg -i --force-depends /pkg/webui.deb >>/var/tmp/install.log 2>&1 || true +r=$(ask dslehr01 pgmadmin); [ "$r" = "403 identity" ] && ok "after upgrade: $r" || no "after upgrade: $r" +dpkg -r --force-depends linuxmuster-squid-webui >/dev/null 2>&1 || true +[ "$(systemctl is-active linuxmuster-squid-webui-activity.socket)" != active ] && ok "remove stops the socket" || no "socket still active after remove" +[ ! -e /run/linuxmuster-squid-webui/activity.sock ] && ok "socket file gone" || no "socket file left" +dpkg -P --force-depends linuxmuster-squid-webui >/dev/null 2>&1 || true +left=$(find /etc/systemd /var/lib/systemd/deb-systemd-helper-enabled /etc/linuxmuster-squid-webui -name '*squid-webui*' 2>/dev/null | tr '\n' ' ') +[ -z "$left" ] && ok "purge leaves nothing" || no "left after purge: $left" +echo "$fails failed" +exit "$fails" +IN diff --git a/webui/tests/test_bridge.py b/webui/tests/test_bridge.py index 79ed43d..74758b6 100644 --- a/webui/tests/test_bridge.py +++ b/webui/tests/test_bridge.py @@ -4,8 +4,9 @@ (SO_PEERCRED), never from the request (except for root, the administrators' workers); limits; the real unix socket; proxies of other schools and old control planes never fail a request. -Different UIDs on one socket need root: ``scripts/tests/webui_bridge_uids.sh`` runs that in a -container (teacher, student and root clients against one bridge).""" +Different UIDs on one socket need root: ``scripts/tests/webui_ajenti_it.sh`` runs that in a +container (teacher, student, nobody and root clients against one bridge), and +``scripts/tests/webui_bridge_systemd.sh`` with the built package under real systemd.""" from __future__ import annotations From 129b0ca0c5d8e377ff341e04acf93aa8b7a15493 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 17:29:55 +0100 Subject: [PATCH 27/45] fix(webui): German errors of the activity bridge, logged with UID A failing linuxmusterTools import (lab B1: 'net conf list' in the sandbox) escaped as a 500 with the exception class 'CalledProcessError', Ajenti added its English 'Server error' dialog, and the journal line of the failed request had no UID or identity. Any failure of the AD becomes a German 503 'directory', any unexpected error a German 502 'bridge'; class and traceback go to the journal only. Every request is logged with UID and identity, failed ones included. The worker maps any other 5xx of the bridge to 502. The activity page's helpers also tolerate undefined arguments. --- webui/lmn_squid/activity_core.py | 13 +++++- webui/lmn_squid/activity_scope.py | 18 ++++++-- webui/lmn_squid/activity_views.py | 4 ++ webui/lmn_squid/bridge.py | 15 ++++--- webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 8 +++- .../js/controllers/activity.controller.es | 17 +++++-- webui/tests/test_bridge.py | 44 +++++++++++++++++++ 7 files changed, 104 insertions(+), 15 deletions(-) diff --git a/webui/lmn_squid/activity_core.py b/webui/lmn_squid/activity_core.py index f51c885..b1420f9 100644 --- a/webui/lmn_squid/activity_core.py +++ b/webui/lmn_squid/activity_core.py @@ -43,6 +43,12 @@ logger = logging.getLogger("lmn_squid.activity") +# What the page shows for an error of the bridge itself (the details are in its journal) +INTERNAL_MESSAGE = ( + "Interner Fehler des Dienstes der Internetnutzung; Einzelheiten im Journal " + "(journalctl -u linuxmuster-squid-webui-activity)." +) + MAX_RANGE = 366 * 86400 WORKERS = 8 DEADLINE = 5.0 # all proxies of one view request, seconds @@ -146,7 +152,9 @@ def _failure(conn: Connection, exc: Exception) -> dict[str, Any]: return {"connection": name, "kind": "error", "message": str(detail["message"])} kind = exc.kind if exc.kind != "http" else "error" return {"connection": name, "kind": kind, "message": exc.message} - return {"connection": name, "kind": "error", "message": str(exc)[:300]} + # an unexpected error: its class and text go to the journal, not to the page + logger.warning("proxy %s: %s: %s", name, type(exc).__name__, str(exc)[:300]) + return {"connection": name, "kind": "error", "message": ""} class ActivityService: @@ -748,6 +756,9 @@ def dispatch( return exc.http_status(), exc.as_dict() except ConnectionFileError as exc: return 409, {"error": "config", "message": exc.message} + except Exception: # noqa: BLE001 - one German answer; class and traceback to the journal + logger.exception("request of %s failed: %s %s", identity, method, path[:100]) + return 502, {"error": "bridge", "message": INTERNAL_MESSAGE} def merge_days(answers: list[dict[str, Any]]) -> dict[str, Any]: diff --git a/webui/lmn_squid/activity_scope.py b/webui/lmn_squid/activity_scope.py index ad22ab6..e8ab64d 100644 --- a/webui/lmn_squid/activity_scope.py +++ b/webui/lmn_squid/activity_scope.py @@ -20,6 +20,7 @@ class or project the teacher is a member or admin of (sophomorix writes members from __future__ import annotations +import logging import re import threading import time @@ -45,6 +46,15 @@ class ScopeDenied(Exception): """The person may not see activity data (or not this user/group).""" +logger = logging.getLogger("lmn_squid.activity") + +# What the page shows when the AD cannot be read (the reason is in the bridge's journal) +DIRECTORY_MESSAGE = ( + "Das Benutzerverzeichnis (AD) konnte nicht gelesen werden; Einzelheiten im Journal " + "(journalctl -u linuxmuster-squid-webui-activity)." +) + + class DirectoryError(Exception): """The AD could not be read (the page says so instead of showing anyone's data).""" @@ -291,15 +301,17 @@ class LdapDirectory: def __init__(self) -> None: try: from linuxmusterTools.ldapconnector import LMNLdapReader - except ImportError as exc: - raise DirectoryError(f"linuxmusterTools missing ({exc})") from None + except Exception as exc: # noqa: BLE001 - missing, or failing at import (lab B1: net conf list) + logger.error("linuxmusterTools cannot be imported: %s: %s", type(exc).__name__, exc) + raise DirectoryError(DIRECTORY_MESSAGE) from None self.lr = LMNLdapReader def _get(self, url: str, **kwargs: Any) -> Any: try: return self.lr.get(url, **kwargs) except Exception as exc: # noqa: BLE001 - ldap errors, an unknown route: one message - raise DirectoryError(f"the AD could not be read ({type(exc).__name__})") from None + logger.error("the AD could not be read (%s): %s: %s", url, type(exc).__name__, exc) + raise DirectoryError(DIRECTORY_MESSAGE) from None def person(self, name: str) -> dict[str, Any] | None: found = self._get(f"/users/{name}", attributes=self.ATTRS) diff --git a/webui/lmn_squid/activity_views.py b/webui/lmn_squid/activity_views.py index 68aeea7..c8121d8 100644 --- a/webui/lmn_squid/activity_views.py +++ b/webui/lmn_squid/activity_views.py @@ -92,6 +92,10 @@ def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: query = {str(k): str(v) for k, v in (http_context.query or {}).items()} identity = str(getattr(self.context, "identity", "") or "") status, data = self.call(identity, method, path.format(**kwargs), query, body, timeout) + if status >= 500 and status not in (502, 503, 504): + # never a 500 to the page: Ajenti answers it with its English "server error" + # dialog (lab B1); the page shows the bridge's German text instead + status = 502 if status != 200: raise EndpointReturn(status, data) return data diff --git a/webui/lmn_squid/bridge.py b/webui/lmn_squid/bridge.py index 6229278..077bea1 100644 --- a/webui/lmn_squid/bridge.py +++ b/webui/lmn_squid/bridge.py @@ -153,10 +153,15 @@ def handle(self, uid: int, raw: bytes) -> tuple[int, Any]: identity = self.identity_of(uid, req.get("identity")) except PermissionError as exc: self.service.audit(f"uid={uid} refused path={path[:100]} reason={exc}") + log.info("uid=%d identity=- %s %s -> 403", uid, method, path[:100]) return 403, {"error": "identity", "message": str(exc)} query = {str(k): str(v)[:200] for k, v in list(query.items())[:20]} - status, data = self.service.dispatch(identity, method, path, query, body) - # who (kernel UID and person), what, result; never data (journal of the bridge) + try: + status, data = self.service.dispatch(identity, method, path, query, body) + except Exception: # noqa: BLE001 - dispatch answers itself; this is the last resort + log.exception("uid=%d identity=%s %s %s failed", uid, identity, method, path[:100]) + status, data = 502, {"error": "bridge", "message": self.core.INTERNAL_MESSAGE} + # who (kernel UID and person), what, result, for every request; never data (journal) log.info("uid=%d identity=%s %s %s -> %d", uid, identity, method, path[:100], status) return status, data @@ -192,9 +197,9 @@ def handle(self) -> None: self._send(status, payload) except (TimeoutError, socket.timeout): self._send(408, {"error": "timeout", "message": "request not complete in time"}) - except Exception as exc: # noqa: BLE001 - one answer, never a traceback to the page - log.exception("bridge request failed") - self._send(500, {"error": "bridge", "message": type(exc).__name__}) + except Exception: # noqa: BLE001 - one answer, never a traceback to the page + log.exception("bridge request failed (uid=%s)", locals().get("uid", "?")) + self._send(502, {"error": "bridge", "message": bridge.core.INTERNAL_MESSAGE}) finally: bridge.slots.release() diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index 0f3f0f0..96ee8dc 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -1678,8 +1678,12 @@ msgstr "Der neue Container wurde nicht gesund; der bisherige läuft weiter." msgid "The service of the internet use on the school server does not answer (linuxmuster-squid-webui-activity)." msgstr "Der Dienst der Internetnutzung auf dem Schulserver antwortet nicht (linuxmuster-squid-webui-activity)." -msgid "The user directory (AD) could not be read." -msgstr "Das Benutzerverzeichnis (AD) konnte nicht gelesen werden." msgid "Too many requests in a short time; please wait a moment." msgstr "Zu viele Anfragen in kurzer Zeit; bitte einen Moment warten." + +msgid "Internal error of the service of the internet use; details in its journal (journalctl -u linuxmuster-squid-webui-activity)." +msgstr "Interner Fehler des Dienstes der Internetnutzung; Einzelheiten im Journal (journalctl -u linuxmuster-squid-webui-activity)." + +msgid "The user directory (AD) could not be read; details in the journal (journalctl -u linuxmuster-squid-webui-activity)." +msgstr "Das Benutzerverzeichnis (AD) konnte nicht gelesen werden; Einzelheiten im Journal (journalctl -u linuxmuster-squid-webui-activity)." diff --git a/webui/lmn_squid/resources/js/controllers/activity.controller.es b/webui/lmn_squid/resources/js/controllers/activity.controller.es index 07d73d8..b6e45e4 100644 --- a/webui/lmn_squid/resources/js/controllers/activity.controller.es +++ b/webui/lmn_squid/resources/js/controllers/activity.controller.es @@ -100,6 +100,9 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ } } $scope.failureText = function (f) { + if (!f) { + return ''; + } if (f.kind === 'limit') { return limitText(f.code) || f.message; } @@ -123,14 +126,17 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ if (data && data.error === 'scope') { return gettext('Not in your classes and projects.'); } - if (data && (data.error === 'bridge_down' || data.error === 'bridge_timeout' || data.error === 'bridge')) { + if (data && (data.error === 'bridge_down' || data.error === 'bridge_timeout')) { return gettext('The service of the internet use on the school server does not answer (linuxmuster-squid-webui-activity).'); } + if (data && data.error === 'bridge') { + return gettext('Internal error of the service of the internet use; details in its journal (journalctl -u linuxmuster-squid-webui-activity).'); + } if (data && data.error === 'rate') { return gettext('Too many requests in a short time; please wait a moment.'); } if (data && data.error === 'directory') { - return gettext('The user directory (AD) could not be read.'); + return gettext('The user directory (AD) could not be read; details in the journal (journalctl -u linuxmuster-squid-webui-activity).'); } if (data && data.message) { return data.message; @@ -302,7 +308,7 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ // ------------------------------------------------------------------ start page $scope.tileVisible = function (g) { var f = ($scope.tiles.filter || '').toLowerCase(); - return !f || g.name.toLowerCase().indexOf(f) >= 0; + return !!g && (!f || String(g.name || '').toLowerCase().indexOf(f) >= 0); }; $scope.findPeople = function (q) { @@ -345,7 +351,10 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ $scope.rowVisible = function (r) { var text = ($scope.tableFilter.text || '').toLowerCase(); - if (text && (r.display || '').toLowerCase().indexOf(text) < 0 && r.user.indexOf(text) < 0) { + if (!r) { + return false; + } + if (text && (r.display || '').toLowerCase().indexOf(text) < 0 && String(r.user || '').indexOf(text) < 0) { return false; } if ($scope.tableFilter.activeOnly && !r.requests) { diff --git a/webui/tests/test_bridge.py b/webui/tests/test_bridge.py index 74758b6..65eb617 100644 --- a/webui/tests/test_bridge.py +++ b/webui/tests/test_bridge.py @@ -249,3 +249,47 @@ def test_the_real_socket(tmp_path: Path) -> None: finally: proc.terminate() proc.wait(timeout=10) + + +def test_a_failing_ad_import_is_a_german_503(monkeypatch: pytest.MonkeyPatch) -> None: + """Lab B1: importing linuxmusterTools ran `net conf list`, which failed in the unit's + sandbox; the CalledProcessError reached the page as a 500 with the class name.""" + import builtins + import subprocess as sp + + real_import = builtins.__import__ + + def failing(name: str, *a: Any, **k: Any) -> Any: + if name.startswith("linuxmusterTools"): + raise sp.CalledProcessError(1, ["/usr/bin/net", "conf", "list"]) + return real_import(name, *a, **k) + + monkeypatch.setattr(builtins, "__import__", failing) + with pytest.raises(activity_scope.DirectoryError) as err: + activity_scope.LdapDirectory() + assert "CalledProcessError" not in str(err.value) + assert str(err.value).startswith("Das Benutzerverzeichnis (AD) konnte nicht gelesen werden") + + +def test_an_unexpected_error_is_logged_with_uid_and_never_shown( + br: Any, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + def boom(*a: Any, **k: Any) -> Any: + raise RuntimeError("secret detail") + + monkeypatch.setattr(activity_core.ActivityService, "handle_scope", boom) + caplog.set_level("INFO") + status, data = ask(br, 2001) + assert status == 502 and data["error"] == "bridge" + assert "RuntimeError" not in json.dumps(data) and "secret" not in json.dumps(data) + assert data["message"].startswith("Interner Fehler des Dienstes der Internetnutzung") + assert "uid=2001 identity=dslehr01 GET scope -> 502" in caplog.text + assert "RuntimeError: secret detail" in caplog.text, "the detail goes to the journal" + + +def test_the_worker_never_passes_a_500_on(webui: Any) -> None: + """Ajenti answers a 500 with its English 'Server error occured' dialog (lab B1).""" + webui.activity.call = lambda *a, **k: (500, {"error": "bridge", "message": "x"}) + webui.as_role("teacher", granted={activity_views.PERM_ACTIVITY}, user="dslehr01") + status, data = webui.call("GET", "/api/lmn/squid-activity/scope") + assert status == 502 and data["error"] == "bridge" From 4c5eb9a8a5c80b342c2822082d05c144a45c513d Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 17:29:55 +0100 Subject: [PATCH 28/45] fix(packaging): netlink for the activity bridge, clean removal samba's 'net conf list', run when linuxmusterTools is imported, lists the network interfaces over netlink; the unit refused AF_NETLINK and the bridge could not read the AD (lab B1). Allow it. Removing the package left the socket's enable symlink behind; replacing it by a build without the bridge left the socket listening (lab rollback). postrm remove/purge stop both units and drop their enable state; postrm upgrade starts a transient job that does the same once dpkg is done, if the new version has no socket unit. webui_bridge_systemd.sh imports the real linuxmusterTools with samba's net under exactly the unit's sandbox and checks remove, purge and the downgrade. --- debian/linuxmuster-squid-webui.postrm | 53 ++++++- .../linuxmuster-squid-webui-activity.service | 4 +- scripts/tests/webui_bridge_systemd.sh | 131 ++++++++++++++---- 3 files changed, 158 insertions(+), 30 deletions(-) diff --git a/debian/linuxmuster-squid-webui.postrm b/debian/linuxmuster-squid-webui.postrm index 30f4aff..4f61a44 100644 --- a/debian/linuxmuster-squid-webui.postrm +++ b/debian/linuxmuster-squid-webui.postrm @@ -3,12 +3,63 @@ # SPDX-License-Identifier: GPL-3.0-or-later set -e +BRIDGE_SOCKET=linuxmuster-squid-webui-activity.socket +BRIDGE_SERVICE=linuxmuster-squid-webui-activity.service + +# Stop the bridge of the internet use view and forget its enable state (no symlink in +# sockets.target.wants pointing at a unit that is gone, nothing left listening). +drop_bridge() { + if [ -d /run/systemd/system ]; then + systemctl stop "$BRIDGE_SOCKET" "$BRIDGE_SERVICE" >/dev/null 2>&1 || true + fi + deb-systemd-helper purge "$BRIDGE_SOCKET" >/dev/null 2>&1 || true + rm -f "/etc/systemd/system/sockets.target.wants/$BRIDGE_SOCKET" + if [ -d /run/systemd/system ]; then + systemctl daemon-reload || true + systemctl reset-failed "$BRIDGE_SOCKET" "$BRIDGE_SERVICE" >/dev/null 2>&1 || true + fi +} + if [ -d /run/systemd/system ]; then systemctl daemon-reload || true fi case "$1" in + upgrade) + # Replaced by a version without the bridge (a downgrade to a build before it): that + # version's scripts do not know the units, and dpkg deletes our unit files only after + # this script. A transient job waits until dpkg is done with the package: unit file gone + # -> stop both units and drop their enable state; still there -> nothing to do. + if [ -d /run/systemd/system ] && command -v systemd-run >/dev/null 2>&1; then + # in /run, not a file of this package: those may be gone when the job runs + CHECK=/run/linuxmuster-squid-webui-bridge-check.sh + cat > "$CHECK" <<'EOF_CHECK' +#!/bin/sh +S=linuxmuster-squid-webui-activity.socket +for _ in $(seq 1 720); do + if [ ! -e /lib/systemd/system/$S ] && [ ! -e /usr/lib/systemd/system/$S ]; then + systemctl stop $S linuxmuster-squid-webui-activity.service + DPKG_MAINTSCRIPT_PACKAGE=linuxmuster-squid-webui deb-systemd-helper purge $S + rm -f /etc/systemd/system/sockets.target.wants/$S \ + /var/lib/systemd/deb-systemd-helper-enabled/sockets.target.wants/$S \ + /var/lib/systemd/deb-systemd-helper-enabled/$S.dsh-also + systemctl daemon-reload + systemctl reset-failed $S linuxmuster-squid-webui-activity.service + break + fi + case "$(dpkg-query -W -f '${Status}' linuxmuster-squid-webui 2>/dev/null)" in + *" installed") break ;; + esac + sleep 5 +done +rm -f /run/linuxmuster-squid-webui-bridge-check.sh +EOF_CHECK + systemd-run --quiet --no-block --collect \ + --unit="linuxmuster-squid-webui-bridge-check-$$" /bin/sh "$CHECK" >/dev/null 2>&1 || true + fi + ;; remove) + drop_bridge # The plugin files are gone: drop its permissions from the merged file and LDAP and # restart the WebUI without it (the same three steps as the postinst, best effort). MERGE=/usr/lib/linuxmuster-webui/etc/update_scripts/merge-permissions.py @@ -27,7 +78,7 @@ case "$1" in rm -rf /run/lmn_squid ;; purge) - deb-systemd-helper purge linuxmuster-squid-webui-activity.socket >/dev/null || true + drop_bridge # The connection list with the control planes' tokens. The service accounts # squid- and their SPNs in AD stay: remove them with samba-tool (docs/install.md). rm -rf /etc/linuxmuster-squid-webui /run/lmn_squid diff --git a/packaging/systemd/linuxmuster-squid-webui-activity.service b/packaging/systemd/linuxmuster-squid-webui-activity.service index 9ca1cbf..bfc17b5 100644 --- a/packaging/systemd/linuxmuster-squid-webui-activity.service +++ b/packaging/systemd/linuxmuster-squid-webui-activity.service @@ -29,7 +29,9 @@ ProtectKernelLogs=yes ProtectControlGroups=yes ProtectClock=yes ProtectHostname=yes -RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +# AF_NETLINK: samba's "net conf list" (run when linuxmusterTools is imported) lists the network +# interfaces over netlink and fails without it (lab 2026-11-25, B1) +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK RestrictNamespaces=yes RestrictRealtime=yes RestrictSUIDSGID=yes diff --git a/scripts/tests/webui_bridge_systemd.sh b/scripts/tests/webui_bridge_systemd.sh index ea3193a..4db275c 100755 --- a/scripts/tests/webui_bridge_systemd.sh +++ b/scripts/tests/webui_bridge_systemd.sh @@ -2,23 +2,35 @@ # SPDX-FileCopyrightText: Kevin Stenzel # SPDX-License-Identifier: GPL-3.0-or-later # -# The built linuxmuster-squid-webui .deb with real systemd (container with systemd as PID 1): -# install enables and starts the bridge's socket; the first connection starts the service as -# root through socket activation (LISTEN_FDS); the bridge takes the caller from SO_PEERCRED of -# the systemd-passed socket (a local user claiming someone else: 403; an unknown UID: 403; root -# without the AD: a German-mappable 503 'directory', no traceback); an upgrade (reinstall) -# keeps it running; remove stops it; purge leaves nothing. +# The built linuxmuster-squid-webui .deb with real systemd (container with systemd as PID 1) and +# the real linuxmusterTools (lmn73) plus samba's `net`: +# * install enables and starts the bridge's socket; the first connection starts the service as +# root through socket activation; SO_PEERCRED through the systemd-passed socket; +# * the AD part under the shipped unit's sandbox (lab B1): linuxmusterTools is imported (it runs +# `net conf list`) by systemd-run with exactly the [Service] sandbox options of the unit, and +# a bridge request reaches the LDAP step (no LDAP server here: 503 "directory", German text); +# * failures are logged with UID and identity, never a raw exception class to the caller; +# * reinstall keeps it working; remove, purge and a downgrade to a build without the bridge +# leave nothing listening and no dangling symlink. # usage: webui_bridge_systemd.sh Exit code = failed checks. +# Needs Docker and the hub's upstream checkouts (linuxmuster-tools at lmn73, sophomorix4). set -euo pipefail DEB="$(readlink -f "${1:?usage: $0 }")" +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +UPSTREAM="${LMNSQUID_UPSTREAM:-$(cd "$ROOT/../.." && pwd)/upstream}" NAME="lmnsquid-bridge-sd-$$" IMG=ubuntu:24.04@sha256:008173c23f95b170204355c12626cb5a965d779a7e1283b09e9cffbb1bf33ca3 -cleanup() { docker rm -f "$NAME" >/dev/null 2>&1 || true; } +WORK="$(mktemp -d)" +cleanup() { docker rm -f "$NAME" >/dev/null 2>&1 || true; rm -rf "$WORK"; } trap cleanup EXIT +git -C "$UPSTREAM/linuxmuster-tools" archive origin/lmn73 usr/lib/python3/dist-packages/linuxmusterTools \ + | tar -C "$WORK" -x +git -C "$UPSTREAM/sophomorix4" archive origin/bionic sophomorix-samba/config-devel/sophomorix.ini \ + | tar -C "$WORK" -x docker run -d --name "$NAME" --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \ - -v "$DEB:/pkg/webui.deb:ro" --tmpfs /run --tmpfs /run/lock "$IMG" \ - bash -c 'apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq systemd systemd-sysv python3-yaml >/dev/null && exec /sbin/init' >/dev/null -for _ in $(seq 1 120); do + -v "$DEB:/pkg/webui.deb:ro" -v "$WORK:/upstream:ro" --tmpfs /run --tmpfs /run/lock "$IMG" \ + bash -c 'apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends systemd systemd-sysv python3-yaml python3-ldap python3-configobj python3-magic python3-pexpect samba-common-bin iproute2 dbus >/dev/null && exec /sbin/init' >/dev/null +for _ in $(seq 1 150); do docker exec "$NAME" sh -c 'systemctl is-system-running 2>/dev/null | grep -qE "running|degraded"' && break sleep 2 done @@ -27,39 +39,102 @@ set -u fails=0 ok() { echo " [PASS] $*"; } no() { echo " [FAIL] $*"; fails=$((fails + 1)); } -ask() { # -> " " +ask() { # -> " " runuser -u "$1" -- python3 -I -c ' import json, socket, sys s = socket.socket(socket.AF_UNIX); s.connect("/run/linuxmuster-squid-webui/activity.sock") s.sendall(json.dumps({"v": 1, "identity": sys.argv[1], "method": "GET", "path": "scope", "query": {}, "body": {}}).encode()) s.shutdown(socket.SHUT_WR); raw = b"" while (c := s.recv(65536)): raw += c -a = json.loads(raw); print(a["status"], a["data"].get("error", "-"))' "$2" 2>&1 | tail -1 +a = json.loads(raw); print(a["status"], a["data"].get("error", "-"), a["data"].get("message", ""))' "$2" 2>&1 | tail -1 } +UNIT=/lib/systemd/system/linuxmuster-squid-webui-activity.service +SOCKET=linuxmuster-squid-webui-activity.socket +SERVICE=linuxmuster-squid-webui-activity.service +nothing_left() { # + if ss -xlH | grep -q activity.sock; then no "$1: something still listens"; else ok "$1: nothing listens"; fi + [ "$(systemctl is-active "$SOCKET" 2>/dev/null)" != active ] && ok "$1: socket unit not active" || no "$1: socket unit active" + dangling=$(find /etc/systemd/system -xtype l 2>/dev/null | tr '\n' ' ') + [ -z "$dangling" ] && ok "$1: no dangling symlink" || no "$1: dangling symlinks: $dangling" + left=$(find /etc/systemd /var/lib/systemd/deb-systemd-helper-enabled -name '*squid-webui*' 2>/dev/null | tr '\n' ' ') + [ -z "$left" ] && ok "$1: no enable state left" || no "$1: left: $left" +} +# the school server's files linuxmusterTools reads when it is imported +cp -r /upstream/usr/lib/python3/dist-packages/linuxmusterTools /usr/lib/python3/dist-packages/ +mkdir -p /usr/share/sophomorix/devel /etc/linuxmuster/sophomorix/default-school /etc/linuxmuster/webui \ + /var/lib/linuxmuster /etc/linuxmuster/.secret +cp /upstream/sophomorix-samba/config-devel/sophomorix.ini /usr/share/sophomorix/devel/ +: > /etc/linuxmuster/sophomorix/default-school/devices.csv +printf '[setup]\nschoolname = Test\n' > /var/lib/linuxmuster/setup.ini +printf 'linuxmuster:\n ldap:\n binddn: cn=x\n bindpw: x\n searchdn: dc=dev,dc=lmschule,dc=de\n' > /etc/linuxmuster/webui/config.yml +printf 'Muster!\n' > /etc/linuxmuster/.secret/administrator; chmod 600 /etc/linuxmuster/.secret/administrator +printf '[global]\n realm = DEV.LMSCHULE.DE\n workgroup = DEV\n netbios name = SERVER\n server role = active directory domain controller\n' > /etc/samba/smb.conf useradd -M -u 2001 dslehr01 # Docker's Ubuntu images forbid starting services from maintainer scripts; a server does not rm -f /usr/sbin/policy-rc.d -# install (its dependencies are the WebUI's; the bridge needs python3 and yaml only) + DEBIAN_FRONTEND=noninteractive dpkg -i --force-depends /pkg/webui.deb >/var/tmp/install.log 2>&1 || true -[ "$(systemctl is-enabled linuxmuster-squid-webui-activity.socket)" = enabled ] && ok "socket enabled" || no "socket not enabled" -[ "$(systemctl is-active linuxmuster-squid-webui-activity.socket)" = active ] && ok "socket active" || no "socket not active" -[ "$(systemctl is-active linuxmuster-squid-webui-activity.service)" = inactive ] && ok "service waits for the first request" || no "service already running" +[ "$(systemctl is-enabled $SOCKET)" = enabled ] && ok "socket enabled" || no "socket not enabled" +[ "$(systemctl is-active $SOCKET)" = active ] && ok "socket active" || no "socket not active" +[ "$(systemctl is-active $SERVICE)" = inactive ] && ok "service waits for the first request" || no "service already running" mode=$(stat -c %a /run/linuxmuster-squid-webui/activity.sock); [ "$mode" = 666 ] && ok "socket 0666" || no "socket mode $mode" -r=$(ask dslehr01 pgmadmin); [ "$r" = "403 identity" ] && ok "local user claiming another identity: $r" || no "claim: $r" -[ "$(systemctl is-active linuxmuster-squid-webui-activity.service)" = active ] && ok "service started by socket activation" || no "service not started" -[ "$(systemctl show -p User --value linuxmuster-squid-webui-activity.service)" = "" ] && ok "service runs as root" || no "service user" -r=$(ask nobody ""); case "$r" in "403 "*|"503 directory") ok "nobody gets no data: $r";; *) no "nobody: $r";; esac # 403 with an AD -r=$(ask root pgmadmin); [ "$r" = "503 directory" ] && ok "root without an AD: $r" || no "root: $r" -journalctl -u linuxmuster-squid-webui-activity.service --no-pager | grep -q "Traceback" && no "traceback in the journal" || ok "no traceback in the journal" -# upgrade = reinstall of the same package: still enabled, answers + +# --- B1: the AD part under exactly the shipped unit's sandbox +props=() +while IFS= read -r line; do props+=(-p "$line"); done < <( + sed -n '/^\[Service\]/,/^\[/p' "$UNIT" | grep -E '^[A-Z][A-Za-z]+=' \ + | grep -vE '^(Type|ExecStart|Restart|RestartSec)=') +echo " sandbox of the unit: ${props[*]}" +out=$(systemd-run --quiet --wait --pipe --collect "${props[@]}" /usr/bin/python3 -I -c \ + 'import linuxmusterTools.ldapconnector; print("imported")' 2>&1 | tail -3) +case "$out" in *imported*) ok "linuxmusterTools (net conf list) imports under the unit's sandbox";; + *) no "linuxmusterTools import under the unit's sandbox: $out";; esac +r=$(ask root pgmadmin) +case "$r" in "503 directory Das Benutzerverzeichnis"*) ok "root, AD without LDAP server: $r";; *) no "root: $r";; esac +journalctl -u $SERVICE --no-pager > /var/tmp/journal.txt +grep -q "the AD could not be read (/users/pgmadmin)" /var/tmp/journal.txt \ + && ok "the bridge got to the LDAP step (import and net conf list worked)" \ + || no "the bridge did not reach LDAP: $(grep -E 'cannot be imported|Error' /var/tmp/journal.txt | tail -2)" +grep -q "Could not determine network interfaces" /var/tmp/journal.txt && no "net conf list failed in the unit" || ok "no netlink failure" +grep -q "uid=0 identity=pgmadmin GET scope -> 503" /var/tmp/journal.txt && ok "failed request logged with UID and identity" || no "failed request without UID/identity in the journal" +grep -qE "CalledProcessError|Traceback" <<<"$r" && no "exception class reaches the caller: $r" || ok "no exception class in the answer" + +# --- identity from the kernel through the systemd socket +r=$(ask dslehr01 pgmadmin); case "$r" in "403 identity"*) ok "local user claiming another identity: 403";; *) no "claim: $r";; esac +[ "$(systemctl is-active $SERVICE)" = active ] && ok "service started by socket activation" || no "service not started" +[ "$(systemctl show -p User --value $SERVICE)" = "" ] && ok "service runs as root" || no "service user" +r=$(ask nobody ""); case "$r" in "403 "*|"503 directory"*) ok "nobody gets no data: ${r%% *}";; *) no "nobody: $r";; esac +grep -q "uid=2001 identity=- GET scope -> 403" <(journalctl -u $SERVICE --no-pager) && ok "refusal logged with the UID" || no "refusal not logged" + +# --- reinstall (upgrade to the same version) DEBIAN_FRONTEND=noninteractive dpkg -i --force-depends /pkg/webui.deb >>/var/tmp/install.log 2>&1 || true -r=$(ask dslehr01 pgmadmin); [ "$r" = "403 identity" ] && ok "after upgrade: $r" || no "after upgrade: $r" +r=$(ask dslehr01 pgmadmin); case "$r" in "403 identity"*) ok "after reinstall: 403";; *) no "after reinstall: $r";; esac + +# --- remove, purge dpkg -r --force-depends linuxmuster-squid-webui >/dev/null 2>&1 || true -[ "$(systemctl is-active linuxmuster-squid-webui-activity.socket)" != active ] && ok "remove stops the socket" || no "socket still active after remove" -[ ! -e /run/linuxmuster-squid-webui/activity.sock ] && ok "socket file gone" || no "socket file left" +nothing_left "remove" dpkg -P --force-depends linuxmuster-squid-webui >/dev/null 2>&1 || true -left=$(find /etc/systemd /var/lib/systemd/deb-systemd-helper-enabled /etc/linuxmuster-squid-webui -name '*squid-webui*' 2>/dev/null | tr '\n' ' ') -[ -z "$left" ] && ok "purge leaves nothing" || no "left after purge: $left" +nothing_left "purge" +[ ! -e /etc/linuxmuster-squid-webui ] && ok "purge: configuration gone" || no "purge: /etc/linuxmuster-squid-webui left" + +# --- downgrade to a build without the bridge (same name, no units): as the lab did +DEBIAN_FRONTEND=noninteractive dpkg -i --force-depends /pkg/webui.deb >>/var/tmp/install.log 2>&1 || true +ask dslehr01 "" >/dev/null +mkdir -p /var/tmp/old/DEBIAN /var/tmp/old/usr/lib/linuxmuster-webui/plugins/lmn_squid +v=$(dpkg-query -W -f '${Version}' linuxmuster-squid-webui) +printf 'Package: linuxmuster-squid-webui\nVersion: %s\nArchitecture: all\nMaintainer: test \nDescription: build without the bridge\n' "$v" > /var/tmp/old/DEBIAN/control +echo "name: lmn_squid" > /var/tmp/old/usr/lib/linuxmuster-webui/plugins/lmn_squid/plugin.yml +dpkg-deb --root-owner-group -b /var/tmp/old /var/tmp/old.deb >/dev/null +DEBIAN_FRONTEND=noninteractive dpkg -i --force-depends /var/tmp/old.deb >>/var/tmp/install.log 2>&1 || true +# the postrm's check job: done when its script is gone and no such job runs any more +for _ in $(seq 1 30); do + [ ! -e /run/linuxmuster-squid-webui-bridge-check.sh ] \ + && ! systemctl list-units --no-legend 'linuxmuster-squid-webui-bridge-check-*' | grep -q . && break + sleep 1 +done +journalctl --no-pager -u 'linuxmuster-squid-webui-bridge-check-*' | tail -5 | sed 's/^/ job: /' +grep -iE "warn|error|postrm" /var/tmp/install.log | tail -5 | sed 's/^/ dpkg: /' +nothing_left "downgrade to a build without the bridge" echo "$fails failed" exit "$fails" IN From d8ad69848ac4934a75cbff228d4c43b9e494b304 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 17:29:55 +0100 Subject: [PATCH 29/45] fix(webui): the management page boots again stateText(detail.inst) threw on every digest while no instance page was open; Ajenti turned each exception into a toast, the toast into the next digest: infdig, 'Angular bootstrap has failed' (lab B2). Every helper a template evaluates now answers on undefined arguments, and the school menu iterates a list kept with the groups instead of a new array per digest. A node check calls every helper the templates evaluate on the freshly started page of both controllers. --- .../js/controllers/index.controller.es | 60 +++++++++++++----- webui/lmn_squid/resources/partial/index.html | 2 +- webui/tests/js/activity_check.js | 5 ++ webui/tests/js/controller_check.js | 9 ++- webui/tests/js/template_helpers.js | 63 +++++++++++++++++++ 5 files changed, 121 insertions(+), 18 deletions(-) create mode 100644 webui/tests/js/template_helpers.js diff --git a/webui/lmn_squid/resources/js/controllers/index.controller.es b/webui/lmn_squid/resources/js/controllers/index.controller.es index de34fde..201c203 100644 --- a/webui/lmn_squid/resources/js/controllers/index.controller.es +++ b/webui/lmn_squid/resources/js/controllers/index.controller.es @@ -280,11 +280,18 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco return g; }); $scope.downServers = down; + var list = schools(); + if (!angular.equals(list, $scope.schoolList)) { + $scope.schoolList = list; + } } $scope.rebuildGroups = rebuildGroups; $scope.$watch('filter', rebuildGroups, true); - $scope.schools = function () { + // the schools of the filter menu: rebuilt with the groups (a template must not get a new + // array per digest) + $scope.schoolList = []; + function schools() { var seen = {}; $scope.connections.forEach(function (conn) { conn.schools.forEach(function (s) { seen[s] = true; }); @@ -292,13 +299,16 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco ((server && server.instances) || []).forEach(function (i) { seen[i.school] = true; }); }); return Object.keys(seen).sort(schoolOrder); - }; + } $scope.serverVisible = function (conn) { + if (!conn) { + return false; + } if ($scope.filter.server && $scope.filter.server !== conn.name) { return false; } - if (!$scope.filter.school || conn.schools.indexOf($scope.filter.school) >= 0) { + if (!$scope.filter.school || (conn.schools || []).indexOf($scope.filter.school) >= 0) { return true; } var server = $scope.servers[conn.name]; @@ -306,7 +316,7 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco }; $scope.instanceVisible = function (inst) { - return !$scope.filter.school || inst.school === $scope.filter.school; + return !!inst && (!$scope.filter.school || inst.school === $scope.filter.school); }; // Bootstrap label class of a container state: green healthy/running, orange starting or @@ -338,7 +348,7 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco }; $scope.stateText = function (inst) { - var s = inst.state; + var s = inst && inst.state; if (!s) { return gettext('unknown'); } @@ -872,7 +882,7 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco }; $scope.safesearchOn = function (inst) { - var ss = ((inst.state || {}).filter || {}).safesearch || {}; + var ss = (((inst && inst.state) || {}).filter || {}).safesearch || {}; return Object.keys(ss).some(function (k) { return ss[k] && ss[k] !== 'off'; }); }; @@ -1190,10 +1200,13 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco return text.join(' ').toLowerCase().indexOf(q) >= 0; }; $scope.groupVisible = function (g) { - return g.categories.some($scope.catMatches); + return !!g && (g.categories || []).some($scope.catMatches); }; $scope.groupOpen = function (g) { - var f = $scope.detail.filter; + var f = $scope.detail && $scope.detail.filter; + if (!f || !f.ui || !g || !g.group) { + return false; + } return !!(f.ui.query || f.ui.open[g.group.id]); }; $scope.toggleGroup = function (g) { @@ -1214,8 +1227,11 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco return (f && ((f.view && f.view.timezone) || (f.catalog && f.catalog.timezone))) || 'Europe/Berlin'; }; $scope.groupActive = function (g, f) { - f = f || $scope.detail.filter; - return g.categories.filter(function (c) { return f.checked[c.id]; }).length; + f = f || ($scope.detail && $scope.detail.filter); + if (!g || !f) { + return 0; + } + return (g.categories || []).filter(function (c) { return f.checked[c.id]; }).length; }; // "all on" / "all off" of a group (the visible categories of a search only) $scope.setGroup = function (g, on) { @@ -1225,18 +1241,21 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco }; // "why blocked?": the variants of a category that list the name, by their labels $scope.variantLabels = function (row) { - var f = $scope.detail.filter; + var f = ($scope.detail && $scope.detail.filter) || {}; + if (!row) { + return ''; + } var cat = f.catalog && f.catalog.byId[row.category]; return (row.variants || []).map(function (v) { return (cat && cat.variantById[v] && cat.variantById[v].label) || v; }).join(', '); }; $scope.catState = function (c, f) { - f = f || $scope.detail.filter; - if (!f.checked[c.id]) { + f = f || ($scope.detail && $scope.detail.filter); + if (!c || !f || !f.checked[c.id]) { return 'off'; } - return (f.schedules[c.id] || []).length ? 'scheduled' : 'on'; + return ((f.schedules || {})[c.id] || []).length ? 'scheduled' : 'on'; }; $scope.catStateText = function (state) { return {on: gettext('on'), off: gettext('off'), scheduled: gettext('time-controlled')}[state]; @@ -1245,8 +1264,11 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco return {on: 'success', off: 'default', scheduled: 'info'}[state]; }; $scope.variantOf = function (c, f) { - f = f || $scope.detail.filter; - return c.variantById[f.variants[c.id]] || c.defaultVariant; + f = f || ($scope.detail && $scope.detail.filter); + if (!c) { + return null; + } + return (f && c.variantById[(f.variants || {})[c.id]]) || c.defaultVariant; }; $scope.variantChanged = function () { $scope.detail.filter.dirty = true; @@ -1465,6 +1487,9 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco $scope.closeBulk = function () { $scope.bulk = null; }; $scope.bulkRowVisible = function (r) { var q = String(($scope.bulk && $scope.bulk.query) || '').toLowerCase().trim(); + if (!r || !r.inst || !r.conn) { + return false; + } return !q || [r.inst.name, r.inst.school, r.inst.role, r.conn.display_name].join(' ').toLowerCase().indexOf(q) >= 0; }; $scope.bulkSelectRole = function () { @@ -1503,6 +1528,9 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco }); }; $scope.bulkResultText = function (r) { + if (!r) { + return ''; + } if (!r.ok) { return (r.message || r.error || '') + (r.detail ? ' ' + (typeof r.detail === 'string' ? r.detail : angular.toJson(r.detail)) : ''); } diff --git a/webui/lmn_squid/resources/partial/index.html b/webui/lmn_squid/resources/partial/index.html index fac39cc..27f0149 100644 --- a/webui/lmn_squid/resources/partial/index.html +++ b/webui/lmn_squid/resources/partial/index.html @@ -33,7 +33,7 @@
diff --git a/webui/tests/js/activity_check.js b/webui/tests/js/activity_check.js index ee18cee..e3d3fb9 100644 --- a/webui/tests/js/activity_check.js +++ b/webui/tests/js/activity_check.js @@ -25,6 +25,7 @@ global.angular = { isArray: Array.isArray, copy: (x) => (x === undefined ? x : JSON.parse(JSON.stringify(x))), toJson: JSON.stringify, + equals: (a, b) => JSON.stringify(a) === JSON.stringify(b), extend: Object.assign, forEach: (obj, fn) => { if (!obj) { return; } if (Array.isArray(obj)) { obj.forEach(fn); } else { Object.keys(obj).forEach((k) => fn(obj[k], k)); } }, }; @@ -165,4 +166,8 @@ h.$scope.sel.day = '2026-11-20'; assert.strictEqual(h.$scope.canGoBack(), false); h.$scope.sel.day = '2026-11-21'; assert.strictEqual(h.$scope.canGoBack(), true); +// ---- every helper the template evaluates answers on the started page (lab B2) +const helpers = require('./template_helpers.js'); +const checked = helpers(harness({}).$scope, ['activity.html'], 'internet use'); +console.log('template helpers of the internet use page: ' + checked.length); console.log('activity controller ok'); diff --git a/webui/tests/js/controller_check.js b/webui/tests/js/controller_check.js index 8b5ff2e..501066c 100644 --- a/webui/tests/js/controller_check.js +++ b/webui/tests/js/controller_check.js @@ -20,6 +20,7 @@ global.angular = { isArray: Array.isArray, copy: (x) => JSON.parse(JSON.stringify(x)), toJson: JSON.stringify, + equals: (a, b) => JSON.stringify(a) === JSON.stringify(b), }; // The bundle wraps nothing itself; each file starts with 'use strict' like babel's output. new Function(fs.readFileSync(process.argv[2], 'utf8'))(); @@ -114,7 +115,7 @@ assert.deepStrictEqual(one.rows.map((r) => r.conn.display_name + ':' + r.inst.na ['Server B:one-students', 'Server A:one-teachers']); assert.deepStrictEqual(s.groups.find((g) => g.school === 'zeta').rows, []); assert.deepStrictEqual(s.downServers.map((c) => c.name), ['c']); -assert.deepStrictEqual(s.schools(), ['default-school', 'beta', 'one', 'zeta']); +assert.deepStrictEqual(s.schoolList, ['default-school', 'beta', 'one', 'zeta']); // filters work in the school view s.filter.school = 'one'; h.digest(); @@ -502,4 +503,10 @@ hd.scope.detail.filter = {dirty: true}; hd.scope.closeDetail(); assert.strictEqual(hd.scope.detail, null); +// --- every helper a template evaluates answers on the started page (lab B2) +const helpers = require('./template_helpers.js'); +const fresh = harness(ROUTES, {}); +const checked = helpers(fresh.scope, ['index.html', 'instance-row.html', 'server-menu.html'], 'management'); +console.log('template helpers of the management page: ' + checked.length); + console.log('controller checks: ok'); diff --git a/webui/tests/js/template_helpers.js b/webui/tests/js/template_helpers.js new file mode 100644 index 0000000..d7662c9 --- /dev/null +++ b/webui/tests/js/template_helpers.js @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Lab 2026-11-25, B2: a function the template evaluates on every digest threw on an undefined +// argument (stateText(detail.inst) while no instance page was open); each throw became an +// error toast, the toast a new digest: "infdig", the page never started. Every function a +// template evaluates in a binding (not in ng-click and the like) must therefore answer on the +// freshly started page with undefined arguments, and a function an ng-repeat iterates must +// return the same collection twice (no new array per digest). +'use strict'; +const fs = require('fs'); +const path = require('path'); +const assert = require('assert'); + +const PARTIALS = path.join(__dirname, '..', '..', 'lmn_squid', 'resources', 'partial'); +const EVALUATED = /(?:ng[:-](?:show|hide|if|class|style|repeat|disabled|readonly|checked|selected|href|src|bind|switch|options|value|attr-[a-z-]+)|class|title|href|style|value|placeholder)="([^"]*)"|\{\{([^}]*)\}\}/g; + +function evaluatedCalls(files) { + const any = new Set(); + const repeated = new Set(); + files.forEach((f) => { + const text = fs.readFileSync(path.join(PARTIALS, f), 'utf8'); + let m; + while ((m = EVALUATED.exec(text)) !== null) { + const expr = m[1] !== undefined ? m[1] : m[2]; + const isRepeat = /^ng[:-]repeat=/.test(m[0]); + (expr.match(/\b([A-Za-z_$][\w$]*)\s*\(/g) || []).forEach((call) => { + const name = call.replace(/\s*\($/, ''); + any.add(name); + if (isRepeat) { repeated.add(name); } + }); + } + }); + return {any, repeated}; +} + +module.exports = function checkTemplateHelpers(scope, files, label) { + const {any, repeated} = evaluatedCalls(files); + const checked = []; + const failed = []; + any.forEach((name) => { + if (typeof scope[name] !== 'function') { return; } + checked.push(name); + [[], [undefined, undefined, undefined]].forEach((args) => { + try { + scope[name](...args); + } catch (e) { + failed.push(`${name}(${args.length ? 'undefined' : ''}): ${e.message}`); + } + }); + if (repeated.has(name)) { + try { + const a = scope[name](); + if (a !== null && typeof a === 'object' && scope[name]() !== a) { + failed.push(`${name}(): a new collection per digest in ng-repeat`); + } + } catch (e) { /* reported above */ } + } + }); + assert.deepStrictEqual(failed, [], `${label}: template helpers that fail on the started page`); + assert.ok(checked.length > 5, `${label}: template helpers found (${checked.length})`); + return checked; +}; From 2222c831d21859e965b38af8ae0a8ecc151072f4 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 17:29:55 +0100 Subject: [PATCH 30/45] test(webui): every plugin page in a real browser webui_ajenti_it.sh now runs the real ajenti-panel and drives headless Chromium through every page, tab and dialog of the plugin as global admin, school admin, teacher and student. Console errors, page errors, bootstrap failures, Ajenti's error dialog, 5xx and unexpected 4xx fail a step. Red against e77bf1e (the lab's B2). --- scripts/tests/webui_ajenti_it.sh | 27 ++- scripts/tests/webui_ajenti_it/Dockerfile | 6 + scripts/tests/webui_ajenti_it/browser.py | 269 +++++++++++++++++++++++ 3 files changed, 300 insertions(+), 2 deletions(-) create mode 100644 scripts/tests/webui_ajenti_it/browser.py diff --git a/scripts/tests/webui_ajenti_it.sh b/scripts/tests/webui_ajenti_it.sh index 5246d26..6fc8832 100755 --- a/scripts/tests/webui_ajenti_it.sh +++ b/scripts/tests/webui_ajenti_it.sh @@ -25,7 +25,9 @@ git -C "$UPSTREAM/linuxmuster-tools" archive origin/lmn73 usr/lib/python3/dist-p # sophomorix.ini, which linuxmusterTools reads when imported (sophomorix4, branch bionic) git -C "$UPSTREAM/sophomorix4" archive origin/bionic sophomorix-samba/config-devel/sophomorix.ini \ | tar -C "$WORK" -x -docker run --rm -v "$ROOT:/src:ro" -v "$WORK:/upstream:ro" -e TZ=Europe/Berlin "$IMG" bash -c ' +OUT=() # LMNSQUID_IT_OUT=: screenshots of failed browser steps +if [ -n "${LMNSQUID_IT_OUT:-}" ]; then mkdir -p "$LMNSQUID_IT_OUT"; OUT=(-v "$(readlink -f "$LMNSQUID_IT_OUT"):/out"); fi +docker run --rm "${OUT[@]}" -v "$ROOT:/src:ro" -v "$WORK:/upstream:ro" -e TZ=Europe/Berlin "$IMG" bash -c ' set -e PY=/opt/linuxmuster/bin/python3 SITE=$($PY -c "import site; print(site.getsitepackages()[0])") @@ -34,7 +36,7 @@ mkdir -p /plugins /etc/linuxmuster/webui /etc/samba /var/lib/linuxmuster /usr/sh cp /upstream/sophomorix-samba/config-devel/sophomorix.ini /usr/share/sophomorix/devel/ mkdir -p /etc/linuxmuster/sophomorix/default-school : > /etc/linuxmuster/sophomorix/default-school/devices.csv -printf "[setup]\nschoolname = Test\n" > /var/lib/linuxmuster/setup.ini +printf "[setup]\nschoolname = Test\nservername = server\ndomainname = dev.lmschule.de\nrealm = DEV.LMSCHULE.DE\nserverip = 10.0.0.1\n" > /var/lib/linuxmuster/setup.ini cp -r /upstream/usr/lib/linuxmuster-webui/plugins/lmn_common /plugins/ cp -r /src/scripts/tests/webui_ajenti_it/it_auth /plugins/ [ "${1:-}" = broken ] && sed -i "1i raise RuntimeError(\"lmn_common broken on purpose\")" /plugins/lmn_common/__init__.py @@ -90,6 +92,27 @@ else # browsed included (E3 hides teachers in class and project lists only; reported 2026-11-25) expect "200 - 5" root pgmadmin POST query/users "$B" echo "-- bridge log (kernel UID per request)"; cat /var/tmp/bridge.log + # every page in a real browser against the real ajenti-panel (same flags as linuxmuster-webui) + mkdir -p /etc/ajenti + cat > /etc/ajenti/config.yml < /var/tmp/panel.log 2>&1 & + for i in $(seq 1 60); do $PY -c "import socket; socket.create_connection((\"127.0.0.1\", 8000))" 2>/dev/null && break; sleep 0.5; done + echo "-- browser (headless Chromium, every page and role)" + $PY /src/scripts/tests/webui_ajenti_it/browser.py || rc=$((rc + 1)) + grep -E "Traceback|ERROR" /var/tmp/panel.log | grep -v "Samba doesn" | head -5 if grep -q "uid=2001 identity=dslehr01 POST query/day" /var/tmp/bridge.log \ && grep -q "uid=0 identity=pgmadmin POST query/users" /var/tmp/bridge.log; then echo " [PASS] the WebUI workers reached the bridge with the teacher UID and root for the admin" diff --git a/scripts/tests/webui_ajenti_it/Dockerfile b/scripts/tests/webui_ajenti_it/Dockerfile index 6df3df6..a00c907 100644 --- a/scripts/tests/webui_ajenti_it/Dockerfile +++ b/scripts/tests/webui_ajenti_it/Dockerfile @@ -18,3 +18,9 @@ RUN python3 -m venv --system-site-packages /opt/linuxmuster \ ajenti.plugin.filesystem==0.51 configobj dpath==2.0.6 paramiko python-magic pexpect \ pyyaml simplejson pytest \ fastapi uvicorn pydantic pydantic-settings docker httpx typer +# The browser check (browser.py): headless Chromium driven by Playwright, the real ajenti-panel +# serving the real frontend bundles (core, lmn_common, this plugin). +RUN /opt/linuxmuster/bin/pip install -q --no-cache-dir playwright==1.49.1 \ + && PLAYWRIGHT_BROWSERS_PATH=/opt/pw /opt/linuxmuster/bin/playwright install --with-deps chromium >/dev/null \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/pw diff --git a/scripts/tests/webui_ajenti_it/browser.py b/scripts/tests/webui_ajenti_it/browser.py new file mode 100644 index 0000000..64d72db --- /dev/null +++ b/scripts/tests/webui_ajenti_it/browser.py @@ -0,0 +1,269 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Every page of the plugin in a real browser (headless Chromium) against the real ajenti-panel, +for every role; run by webui_ajenti_it.sh (lab 2026-11-25, B2: the management page did not +boot, which no test without a browser could see). + +A step fails on: a console error, an uncaught page error, an Angular bootstrap failure or +digest loop, Ajenti's "Server error occured" dialog, any HTTP 5xx, and any 4xx the role does not +expect (a teacher is refused the management page: 403 there is expected). Dialogs are opened +through the page controller's own functions, the way their buttons do; nothing is confirmed. +""" + +import os +import re +import sys + +from playwright.sync_api import sync_playwright + +BASE = "http://127.0.0.1:8000" +FAILS: list[str] = [] +COVERED: list[str] = [] +MGMT = "/view/lmn/squid" +ACT = "/view/lmn/squid-activity" + + +def scope_call(page, expr): + """Run ``expr`` with ``s`` = the plugin controller's scope, inside $apply.""" + page.evaluate( + """(expr) => { + let s = null; + document.querySelectorAll('.ng-scope').forEach((e) => { + const sc = angular.element(e).scope(); + if (!s && sc && (typeof sc.setSection === 'function' || typeof sc.toggleAgg === 'function')) { s = sc; } + }); + if (!s) { throw new Error('plugin scope not found'); } + s.$apply(() => { (new Function('s', expr))(s); }); + }""", + expr, + ) + + +class Probe: + def __init__(self, page, role): + self.page = page + self.role = role + self.errors: list[str] = [] + page.on("console", self._console) + page.on( + "pageerror", lambda e: self.errors.append(f"page error: {str(e)[:300]}") + ) + page.on("response", self._response) + self.allowed: set[int] = set() + + def _console(self, msg): + if msg.type != "error": + return + if msg.text.startswith("Failed to load resource"): + return # judged by _response with the URL and status + self.errors.append(f"console: {msg.text[:300]}") + + def _response(self, resp): + if "/api/" not in resp.url and resp.status < 500: + return + if resp.status >= 500 or ( + resp.status >= 400 and resp.status not in self.allowed + ): + self.errors.append( + f"HTTP {resp.status} {resp.request.method} {resp.url[len(BASE) :]}" + ) + + def step(self, label, url=None, action=None, allowed=(), wait=900, expect=None): + self.errors.clear() + self.allowed = set(allowed) + try: + if url is not None: + self.page.goto(BASE + url, wait_until="networkidle") + if action is not None: + action(self.page) + self.page.wait_for_load_state("networkidle") + self.page.wait_for_timeout(wait) + except Exception as exc: # noqa: BLE001 - a step that cannot run is a failure + self.errors.append(f"step failed: {str(exc)[:300]}") + try: + body = str( + self.page.evaluate("() => document.body ? document.body.innerText : ''") + ).lower() + except Exception as exc: # noqa: BLE001 - a page that does not answer is a failure + body = "" + self.errors.append(f"page does not answer: {str(exc)[:200]}") + if expect and expect.lower() not in body: + self.errors.append(f"expected text missing: {expect!r}") + if "likely a bug" in body: + self.errors.append("Ajenti's 'Server error occured' dialog") + if "bootstrap" in body and ( + "fehler" in body or "error" in body or "failed" in body + ): + self.errors.append("bootstrap failure shown") + name = f"{self.role}: {label}" + COVERED.append(name) + if self.errors: + FAILS.append(name) + print(f" [FAIL] {name}") + if os.path.isdir("/out"): + shot = "/out/" + re.sub(r"[^A-Za-z0-9]+", "-", name)[:80] + ".png" + try: + self.page.screenshot(path=shot, timeout=5000) + except Exception as exc: # noqa: BLE001 - evidence only + print(f" (no screenshot: {str(exc)[:80]})") + for e in sorted(set(self.errors))[:8]: + print(f" {e}") + else: + print(f" [PASS] {name}") + + +def login(page, user): + page.goto(BASE + "/view/login/normal", wait_until="networkidle") + r = page.request.post( + BASE + "/api/core/auth", + data={"username": user, "password": "x", "mode": "normal"}, + ) + if r.status != 200 or not r.json().get("success"): + raise RuntimeError(f"login {user}: {r.status} {r.text()[:200]}") + + +def dialog(probe, label, opener, var): + probe.step(f"management dialog: {label}", action=lambda p: scope_call(p, opener)) + scope_call(probe.page, f"s.{var} = null;") + + +def management_admin(probe): + probe.step("management: servers", MGMT, expect="default-school") + probe.step("management: section internet use settings", MGMT + "?section=activity") + probe.step( + "management: section access log of the internet use", MGMT + "?section=audit" + ) + inst = probe.page.evaluate( + """() => { let n = null; document.querySelectorAll('.ng-scope').forEach((e) => { + const s = angular.element(e).scope(); + if (!n && s && s.servers && s.servers.lab && (s.servers.lab.instances || []).length) { + n = s.servers.lab.instances[0].name; } }); return n; }""" + ) + if not inst: + FAILS.append(f"{probe.role}: management: no instance listed") + print(" [FAIL] management lists no instance") + return + for tab in ( + "status", + "filter", + "blocklist", + "allowlist", + "noauth", + "logs", + "access", + "activity", + ): + probe.step( + f"instance page, tab {tab}", f"{MGMT}?conn=lab&name={inst}&tab={tab}" + ) + # the bulk dialog lives on the filter tab (it starts from the open instance's filter) + probe.step( + "instance page, tab filter again", f"{MGMT}?conn=lab&name={inst}&tab=filter" + ) + dialog( + probe, "apply the filter to several instances (bulk)", "s.openBulk();", "bulk" + ) + probe.step("management: servers again", MGMT) + c = "s.connections[0]" + i = "s.servers[s.connections[0].name].instances[0]" + a = f"({i}.activity || {{name: {i}.name, retention_days: 7}})" + for label, opener, var in [ + ("add connection", "s.addConnection();", "connForm"), + ("edit connection", f"s.editConnection({c});", "connForm"), + ("remove connection", f"s.removeConnection({c});", "removeConnDialog"), + ("keytab", f"s.openKeytab({c});", "keytabForm"), + ("set up a new server (wizard)", "s.openWizard();", "wizard"), + ("create instance", f"s.createInstance({c}.name);", "instForm"), + ("edit instance", f"s.editInstance({c}, {i});", "instForm"), + ("delete instance", f"s.deleteInstance({c}, {i});", "deleteDialog"), + ("filter overview", "s.openFilterOverview();", "filterOverview"), + ("own categories and sources", f"s.openOwn({c});", "own"), + ("switch internet use on", f"s.askEnable({c}, {a});", "enableDialog"), + ("switch internet use off", f"s.askDisable({c}, {a});", "disableDialog"), + ]: + dialog(probe, label, opener, var) + + +def management_refused(probe): + probe.step("management page refused", MGMT, allowed=(403,)) + + +def activity_views(probe, teacher=False, school=""): + # a global administrator chooses the school first (the page's links then carry it) + q = f"school={school}&" if school else "" + probe.step("internet use: start", ACT + (f"?school={school}" if school else "")) + probe.step("internet use: class 5a", ACT + f"?{q}group=class:5a", expect="s5a1") + for kind in ("blocked", "domains"): + probe.step( + f"internet use: class 5a, {kind}", + action=lambda p, k=kind: scope_call(p, f"s.toggleAgg('{k}');"), + ) + probe.step( + "internet use: class 5a, who was on", + action=lambda p: scope_call(p, "s.searchFor('lotto.example');"), + ) + if not teacher: + probe.step( + "internet use: class 5a with teachers", + action=lambda p: scope_call(p, "s.toggleTeachers();"), + ) + probe.step( + "internet use: student s5a1, day", + ACT + f"?{q}user=s5a1", + expect="lotto.example", + ) + probe.step( + "internet use: student s5a1, school hours", + action=lambda p: scope_call(p, "s.setPart('school');"), + ) + probe.step( + "internet use: student s5a1, a domain", + action=lambda p: scope_call(p, "s.openDomain({domain: 'lotto.example'});"), + ) + probe.step( + "internet use: student s5a1, previous day", + action=lambda p: scope_call(p, "s.shiftDay(-1);"), + ) + if teacher: + probe.step( + "internet use: student of another class refused", + ACT + "?user=s6b1", + allowed=(403,), + ) + else: + probe.step("internet use: student s6b1", ACT + f"?{q}user=s6b1") + + +def main(): + with sync_playwright() as pw: + browser = pw.chromium.launch() + plans = { + "global-admin": lambda p: ( + management_admin(p), + activity_views(p, school="default-school"), + ), + "pgmadmin": lambda p: (management_refused(p), activity_views(p)), + "dslehr01": lambda p: ( + management_refused(p), + activity_views(p, teacher=True), + ), + "dsextra01": lambda p: ( + management_refused(p), + p.step("internet use page refused", ACT, allowed=(403,)), + ), + } + for user, plan in plans.items(): + ctx = browser.new_context( + locale="de-DE", viewport={"width": 1366, "height": 768} + ) + page = ctx.new_page() + login(page, user) + plan(Probe(page, user)) + ctx.close() + browser.close() + print(f"browser: {len(COVERED)} steps, {len(FAILS)} failed") + return 1 if FAILS else 0 + + +if __name__ == "__main__": + sys.exit(main()) From 4bdc383fd9b51c28004fd3e62f619dc66b69ea42 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 17:29:55 +0100 Subject: [PATCH 31/45] docs: activity bridge round 3 (ADR-023 addendum 3, operations, tests) --- debian/changelog | 6 ++++++ docs/decisions.md | 34 ++++++++++++++++++++++++++++++++++ docs/operations.md | 19 ++++++++++++++++++- docs/test-strategy.md | 23 +++++++++++++++++++---- docs/threat-model.md | 2 +- 5 files changed, 78 insertions(+), 6 deletions(-) diff --git a/debian/changelog b/debian/changelog index 822e24e..260de96 100644 --- a/debian/changelog +++ b/debian/changelog @@ -202,6 +202,12 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium lmn_common (like every lmn_* plugin), so its menu entry can no longer break the whole WebUI menu; proxies of other schools and proxies without the activity log no longer block an export. + * WebUI plugin: the service of "Internetnutzung" can read the AD under + its systemd sandbox (samba's "net conf list" needs netlink); its + errors are German messages with the details in its journal. The page + "Squid-Proxy" starts again (it ended in an endless update loop). + Removing the package, or going back to a build without the service, + stops it and leaves no unit enabled. -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium diff --git a/docs/decisions.md b/docs/decisions.md index afbee65..2409b43 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -795,6 +795,40 @@ sites on individual students, mind performance when viewing"; spec real control plane; then talks to the bridge directly as those UIDs. Against 54448dc it fails with exactly the lab's A5, A6 and A7 errors. +**Addendum 3 (2026-11-25, lab round 3 against e77bf1e, `lab-activity-2026-11-25.md` section +"Runde 3"):** +- **B1, the bridge could not read the AD:** importing linuxmusterTools runs samba's + `net conf list`, which lists the network interfaces over netlink; the unit's + `RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6` refused that ("Could not determine network + interfaces"), every request ended in a 500 with the class name `CalledProcessError`. The unit + now allows `AF_NETLINK`. The rest of the sandbox was checked against what linuxmusterTools + needs as root: LDAPS to `localhost:636` (AF_INET), reading `/etc/linuxmuster/webui/config.yml`, + `/etc/linuxmuster/.secret/administrator`, `sophomorix.ini`, `devices.csv` and `smb.conf`, and + samba's registry and lock files under `/var/lib/samba` and `/run/samba` + (`ProtectSystem=full` keeps `/var` and `/run` writable). Errors of the bridge are German texts + on the page and details in its journal, never an exception class; every request, a failed + one included, is logged with UID and identity; the WebUI never passes a 500 on (Ajenti would + show its English "Server error occured" dialog), a bridge error is 502. +- **B2, the management page did not start:** `stateText(detail.inst)` in the (hidden) instance + page threw on every digest while no instance was open; Ajenti turned each exception into an + error toast, the toast started the next digest: `$rootScope:infdig`, "Angular bootstrap has + failed". It was already in 54448dc, hidden behind A5. Every function a template evaluates now + answers on undefined arguments, and no template iterates a function that builds a new array per + digest (`schools()` became `schoolList`, kept with the groups). +- **Packaging:** removing the plugin package left the enable symlink of the socket behind, and + replacing it by a build without the bridge (the lab's way back to an older build of the same + version) left the socket listening: dpkg deletes our unit files only after our `postrm + upgrade`, and the older build's scripts do not know them. `postrm remove`/`purge` now stop both + units and drop their enable state; `postrm upgrade` starts a transient job that waits until + dpkg is done with the package and, if the socket unit is gone, stops and forgets both units. + debhelper's own `dh_installsystemd` snippets would not cover that downgrade either. +- **Tests:** `webui_ajenti_it.sh` now also runs the real ajenti-panel with headless Chromium + (every page, tab and dialog of the plugin for global admin, school admin, teacher and student; + any console error, page error, bootstrap failure, Ajenti error dialog, 5xx or unexpected 4xx + fails); `webui_bridge_systemd.sh` imports the real linuxmusterTools with samba's `net` under + exactly the unit's sandbox and checks remove, purge and the downgrade. Both are red against + e77bf1e. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/operations.md b/docs/operations.md index 14d8df7..89f849a 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -801,13 +801,30 @@ journalctl -t lmn-squid-activity # the audit lines of t ``` The page says "Der Dienst der Internetnutzung auf dem Schulserver antwortet nicht" when the -socket is stopped or the service fails: `systemctl restart linuxmuster-squid-webui-activity.socket`. +socket is stopped, "Interner Fehler des Dienstes der Internetnutzung" or "Das Benutzerverzeichnis +(AD) konnte nicht gelesen werden" with the reason in `journalctl -u +linuxmuster-squid-webui-activity` (e.g. samba's `net conf list` failing when linuxmusterTools is +imported); when the service fails: `systemctl restart linuxmuster-squid-webui-activity.socket`. "Zu viele Anfragen" = more than 60 requests of one person in 10 s (the page's live updates stay far below). Overhead of the bridge on top of the proxies: about 1 ms per request (local measurement, `/scope` from a fixed directory, median 0.95 ms). After changing the connection list by hand, the bridge sees the change at once (it reads the file per request); its cache of the proxies' overviews lasts 60 s, a change in the management page drops it. +**Removing or going back to an older build:** removing the package stops the socket and the +service and drops their enable state. Replacing it by a build without the bridge (an older build +of the same version) is cleaned up by a short job after dpkg has finished +(`linuxmuster-squid-webui-bridge-check-*`). A build of 2026-11-25 up to e77bf1e did not do that; +after going back from one of those, clean up by hand: + +```bash +systemctl stop linuxmuster-squid-webui-activity.socket linuxmuster-squid-webui-activity.service +rm -f /etc/systemd/system/sockets.target.wants/linuxmuster-squid-webui-activity.socket \ + /var/lib/systemd/deb-systemd-helper-enabled/sockets.target.wants/linuxmuster-squid-webui-activity.socket \ + /var/lib/systemd/deb-systemd-helper-enabled/linuxmuster-squid-webui-activity.socket.dsh-also +systemctl daemon-reload +``` + ### ⚠️ Data protection (GDPR) Access logs show **who visited/was blocked from which site** = personal data diff --git a/docs/test-strategy.md b/docs/test-strategy.md index 3e03120..2b57190 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -163,13 +163,28 @@ student 403; then the bridge directly from processes running as the teacher, the entry goes under *Software*. Against 54448dc the test fails with the lab's A5 (sidebar 500), A6 ("operation on destroyed loop" from the second request on) and A7 (teacher 409, config not readable) — evidence in the hub, `work/linuxmuster-squid/lab-activity-2026-11-25/runde3-it/`. -Not covered: the browser (Angular) side and real AD/LDAP; the lab recheck does those. +Then the same container runs the real `ajenti-panel` (the flags of linuxmuster-webui, the real +core, lmn_common and plugin bundles) and `browser.py` drives headless Chromium (Playwright) +through every page of the plugin as global admin, school admin, teacher and student: the +management page (servers, both internet-use sections, the instance page with all eight tabs and +all thirteen dialogs, opened through the controller's own functions, nothing confirmed), the +internet use page (start, class with its blocked attempts, domains, "who was on", teachers on, +the student's day, school hours, a domain, the previous day, another class's student) and the +refusals. A step fails on a console error, an uncaught page error, an Angular bootstrap failure +or digest loop, Ajenti's "Server error occured" dialog, any 5xx and any 4xx the role does not +expect; some steps also need their data on the page. `LMNSQUID_IT_OUT=` keeps screenshots of +failed steps. Against e77bf1e it fails with the lab's B2 (digest loop on the management page). +Not covered: real AD/LDAP (fixed directory in the bridge); the lab recheck does that. `scripts/tests/webui_bridge_systemd.sh ` (by hand after `make deb`) -installs the built package in a container with systemd as PID 1: the socket enabled and active +installs the built package in a container with systemd as PID 1, with the real linuxmusterTools +(lmn73) and samba's `net`: linuxmusterTools is imported by `systemd-run` with exactly the +`[Service]` sandbox options of the shipped unit (lab B1: `net conf list` needs netlink), a bridge +request reaches the LDAP step (503 "directory" in German, logged with UID and identity); the socket enabled and active (0666), the service started by the first connection (socket activation, root), `SO_PEERCRED` through the systemd-passed socket (a local user claiming another identity: 403), no traceback -without an AD (503 "directory"), reinstall keeps it working, remove stops it, purge leaves -nothing. +reinstall keeps it working; remove, purge and a downgrade to a build without the bridge leave +nothing listening, no dangling symlink and no enable state. Against e77bf1e: red (B1 and the +leftovers of the lab's rollback). ## Negative/security catalog (grows per phase; part of the DoD) diff --git a/docs/threat-model.md b/docs/threat-model.md index 6a25641..e817d64 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -47,7 +47,7 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T24 | **Activity log = profile of browsing per person** (ADR-023): data of students and staff, a teacher looking at students of other classes or at colleagues, an exported CSV passed on | off by default per instance; switching on needs who confirmed the privacy notice (stored with the time in the instance's git log); minute and domain only, no URL, no client address; retention 1–365 days as whole day files (deleted before a query could read them); scope computed on the school server from the AD on every request, only the allowed users list goes to the proxy, which filters every SQL statement on it; teachers only students of their own classes/projects and school, never teachers; export only for administrators; every read and every settings change audited (person, scope, users, range) before data is read, 503 if the audit log cannot be written; the audit log only for global administrators, own retention | `test_activity.py`, `test_activity_api.py`, webui `test_activity_views.py`, E2E spool check | | T25 | **The users list comes from the WebUI** (ADR-023): the proxy cannot check who asks; a stolen token reads everything | the token is the global administrator's credential already (T5, T18); the list is computed on the server, never taken from the browser; the audit names the person the WebUI reports and, for the CLI, `cli:`; the WebUI logs every request of the view, refused ones and those without a proxy request included, to its system log (`journalctl -t lmn-squid-activity`) | `test_activity_views.py` (out-of-scope requests never reach a proxy) | | T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 1733 (squid's proxy user can create, not list; no set-group-id, which `RestrictSUIDSGID=yes` refuses), files 0644 unreachable for other host users behind the 0750 parent; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured) | `test_activity.py` (receiver), local squid 6.14 test | -| T27 | **The activity bridge** (ADR-023 addendum 2): a root service on a socket every local process can open; a teacher's worker (or any local user) claims to be someone else, asks for students outside its classes, floods the bridge, or sends a huge or slow request; a bug in the bridge leaks the tokens | the identity of a non-root caller comes from the kernel (`SO_PEERCRED` → `getpwuid`), a claimed identity must match it; only root names a person; the scope is computed in the bridge from the AD, a users list of the caller is ignored; tokens never leave the bridge (answers carry activity data and typed errors only); request ≤ 256 KiB, 10 s, 32 at once, 60 per UID in 10 s; no shell, no path from the caller; systemd hardening (`ProtectSystem=full`, `NoNewPrivileges`, `ProtectHome`, private /tmp, kernel protections); one log line per request with UID and identity, refusals audited (tag `lmn-squid-activity`). Residual: upstream gives teachers `sudo ALL` (`webui-sudoers`), so a teacher with a shell on the server is root anyway; the bridge does not make that worse | `webui/tests/test_bridge.py`; `scripts/tests/webui_ajenti_it.sh` (bridge asked as teacher, student, `nobody` and root UIDs) | +| T27 | **The activity bridge** (ADR-023 addendum 2): a root service on a socket every local process can open; a teacher's worker (or any local user) claims to be someone else, asks for students outside its classes, floods the bridge, or sends a huge or slow request; a bug in the bridge leaks the tokens | the identity of a non-root caller comes from the kernel (`SO_PEERCRED` → `getpwuid`), a claimed identity must match it; only root names a person; the scope is computed in the bridge from the AD, a users list of the caller is ignored; tokens never leave the bridge (answers carry activity data and typed errors only); request ≤ 256 KiB, 10 s, 32 at once, 60 per UID in 10 s; no shell, no path from the caller; systemd hardening (`ProtectSystem=full`, `NoNewPrivileges`, `ProtectHome`, private /tmp, kernel protections, address families AF_UNIX/AF_INET/AF_INET6/AF_NETLINK — netlink for samba's interface list); one log line per request with UID and identity, refusals audited (tag `lmn-squid-activity`). Residual: upstream gives teachers `sudo ALL` (`webui-sudoers`), so a teacher with a shell on the server is root anyway; the bridge does not make that worse | `webui/tests/test_bridge.py`; `scripts/tests/webui_ajenti_it.sh` (bridge asked as teacher, student, `nobody` and root UIDs) | ## Non-goals (deliberate) From f51fe90c38b391edb09d63c2e8de6231ec2ad2fc Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 18:36:53 +0100 Subject: [PATCH 32/45] fix(webui): an export over a proxy's size limit is export_too_large When every failing proxy refused the export for its answer size, the page said a proxy could not deliver its part; it is the same case as a merged CSV that is too large and now gets that message. --- webui/lmn_squid/activity_core.py | 4 ++++ webui/tests/test_bridge.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/webui/lmn_squid/activity_core.py b/webui/lmn_squid/activity_core.py index b1420f9..8c94a1e 100644 --- a/webui/lmn_squid/activity_core.py +++ b/webui/lmn_squid/activity_core.py @@ -702,6 +702,10 @@ def handle_export(self, identity: str, query: dict[str, Any], body: dict[str, An text=True, deadline=LONG[1], ) + if failed and all(f.get("kind") == "too_large" for f in failed): + # the proxies' own size limit: the same answer as the merged CSV being too large + self._log(scope, "export", label, "refused: too large") + raise ServiceError(409, {"error": "export_too_large", "message": "", "unreachable": []}) if failed: self._log(scope, "export", label, "refused: a proxy failed") raise ServiceError( diff --git a/webui/tests/test_bridge.py b/webui/tests/test_bridge.py index 65eb617..5e521f0 100644 --- a/webui/tests/test_bridge.py +++ b/webui/tests/test_bridge.py @@ -293,3 +293,18 @@ def test_the_worker_never_passes_a_500_on(webui: Any) -> None: webui.as_role("teacher", granted={activity_views.PERM_ACTIVITY}, user="dslehr01") status, data = webui.call("GET", "/api/lmn/squid-activity/scope") assert status == 502 and data["error"] == "bridge" + + +def test_a_proxy_answer_too_large_is_export_too_large( + br: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Lab round 4: the proxies' size limit read 'a proxy cannot deliver its part'.""" + br.store.add({"name": "big", "url": "https://127.0.0.1:1", "token": "t" * 32}) + + def request(self: ControlPlaneClient, method: str, path: str, *a: Any, **k: Any) -> Any: + raise ControlPlaneError("too_large", "answer too large") + + monkeypatch.setattr(ControlPlaneClient, "request", request) + body = {"since": int(time.time()) - 3600, "until": int(time.time())} + status, data = ask(br, 0, identity="pgmadmin", path="export", method="POST", body=body) + assert (status, data["error"]) == (409, "export_too_large") From be94da567243f0a6fbe8968c94df887560917a35 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 18:36:53 +0100 Subject: [PATCH 33/45] fix(packaging): let linuxmusterTools read the AD in the bridge's sandbox linuxmusterTools' YAML loader chmods every file it opens as root, also for reading: the WebUI's config.yml and any school's custom_fields.yml under /etc. ProtectSystem=full made /etc read-only and every AD read failed with EROFS (lab B3). Use ProtectSystem=true (/usr and /boot stay read-only); a list of writable paths would have to follow the loader's internals, and a single-file ReadWritePaths pins the inode so a config replaced by rename would stay stale. ADR-023 addendum 4. webui_bridge_systemd.sh now runs real requests through the installed unit against an OpenLDAP stand-in of the AD (LDAPS, sophomorix-like tree, a school with custom_fields.yml) and checks that a connection added by rename is used by the running bridge. --- debian/changelog | 4 + docs/decisions.md | 32 +++++++ docs/operations.md | 8 +- docs/test-strategy.md | 8 +- docs/threat-model.md | 2 +- .../linuxmuster-squid-webui-activity.service | 11 ++- scripts/tests/webui_bridge_systemd.sh | 88 ++++++++++++++++--- .../tests/webui_bridge_systemd/slapd-stub.sh | 70 +++++++++++++++ .../sophomorix-stub.schema | 27 ++++++ 9 files changed, 229 insertions(+), 21 deletions(-) create mode 100755 scripts/tests/webui_bridge_systemd/slapd-stub.sh create mode 100644 scripts/tests/webui_bridge_systemd/sophomorix-stub.schema diff --git a/debian/changelog b/debian/changelog index 260de96..2065715 100644 --- a/debian/changelog +++ b/debian/changelog @@ -208,6 +208,10 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium "Squid-Proxy" starts again (it ended in an endless update loop). Removing the package, or going back to a build without the service, stops it and leaves no unit enabled. + * WebUI plugin: the service of "Internetnutzung" can read the AD again + (linuxmusterTools changes the mode of the files it reads under /etc, + which its sandbox refused). An export too large for a proxy reads + "Export zu groß" instead of "a proxy cannot deliver its part". -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium diff --git a/docs/decisions.md b/docs/decisions.md index 2409b43..1f85724 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -829,6 +829,38 @@ sites on individual students, mind performance when viewing"; spec exactly the unit's sandbox and checks remove, purge and the downgrade. Both are red against e77bf1e. +**Addendum 4 (2026-11-25, lab round 4 against 7045c2a, B3):** the bridge still read no AD: +linuxmusterTools' YAML loader (`lmnfile.py`, `YAMLLoader.__enter__`) chmods every file it opens to +0600 when it runs as root, also for reading, and creates it if it is missing. Under +`ProtectSystem=full` `/etc` is read-only: `chmod /etc/linuxmuster/webui/config.yml` failed with +EROFS before the LDAP bind. The same loader opens `/etc/linuxmuster/sophomorix// +custom_fields.yml` on every LDAP read when the school has one (linuxmusterTools outside the +WebUI: `WEBUI_IMPORT` is false in the bridge). **Decision: `ProtectSystem=true`** (`/usr` and +`/boot` read-only, `/etc` writable). Considered: +- `ReadWritePaths=/etc/linuxmuster/webui/config.yml` (one file): a bind mount of the inode; a + config.yml replaced by rename would stay stale in the running bridge, and custom_fields.yml + of a school would still fail. +- `ReadWritePaths=/etc/linuxmuster/webui` (+ `/etc/linuxmuster/sophomorix`): works today, but the + list has to follow linuxmusterTools' internals (every YAML file it may open as root), and a + missed path is the next outage on one school only. +- reading the AD without linuxmusterTools' loader (own LDAP code or patching it): diverges from + the official plugins and breaks with linuxmusterTools upgrades. +- what `ProtectSystem=full` would add: protection of `/etc` against the bridge itself. The bridge + runs as root and reads the AD with the domain's Administrator password + (`/etc/linuxmuster/.secret/administrator`); a compromised bridge owns the domain whether or not + `/etc` is read-only, so the read-only `/etc` buys little against what it breaks. The other + protections stay (`NoNewPrivileges`, `ProtectHome`, private `/tmp`, kernel and control-group + protections, address families, `RestrictNamespaces`, `RestrictSUIDSGID`). +The bridge process lives from the first request until the service is stopped (socket +activation, no idle exit); it reads the plugin's connection file on every request and the WebUI's +config.yml on every AD read, so a new connection, a rotated token or a changed LDAP setting +needs no restart (tested: a connection added by rename is used by the running process). An export +refused by the proxies' own size limit now reads "Export zu groß" (`export_too_large`) instead of +"a proxy cannot deliver its part". **Test:** `webui_bridge_systemd.sh` runs real requests through +the installed unit against an OpenLDAP stand-in of the AD (LDAPS, sophomorix attributes, a +school with custom_fields.yml): linuxmusterTools opens config.yml with its own loader, binds and +reads the scope and a class. Red against 7045c2a with the lab's EROFS, green at HEAD. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/operations.md b/docs/operations.md index 89f849a..e6444b3 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -807,9 +807,11 @@ linuxmuster-squid-webui-activity` (e.g. samba's `net conf list` failing when lin imported); when the service fails: `systemctl restart linuxmuster-squid-webui-activity.socket`. "Zu viele Anfragen" = more than 60 requests of one person in 10 s (the page's live updates stay far below). Overhead of the bridge on top of the proxies: about 1 ms per request (local measurement, -`/scope` from a fixed directory, median 0.95 ms). After changing the connection list by hand, -the bridge sees the change at once (it reads the file per request); its cache of the proxies' -overviews lasts 60 s, a change in the management page drops it. +`/scope` from a fixed directory, median 0.95 ms). The bridge process runs from the first request until +the service is stopped. It reads the connection list on every request and the WebUI's +config.yml on every AD read: a new connection, a rotated token or a changed LDAP setting needs no +restart. Its cache of the proxies' overviews lasts 60 s, a change in the management page drops +it. **Removing or going back to an older build:** removing the package stops the socket and the service and drops their enable state. Replacing it by a build without the bridge (an older build diff --git a/docs/test-strategy.md b/docs/test-strategy.md index 2b57190..8f57f47 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -177,7 +177,13 @@ failed steps. Against e77bf1e it fails with the lab's B2 (digest loop on the man Not covered: real AD/LDAP (fixed directory in the bridge); the lab recheck does that. `scripts/tests/webui_bridge_systemd.sh ` (by hand after `make deb`) installs the built package in a container with systemd as PID 1, with the real linuxmusterTools -(lmn73) and samba's `net`: linuxmusterTools is imported by `systemd-run` with exactly the +(lmn73), samba's `net` and an OpenLDAP stand-in of the AD (`webui_bridge_systemd/`: LDAPS on +localhost:636 with a trusted certificate, the bind DN and password linuxmusterTools uses, a +sophomorix-like tree, a school with custom_fields.yml). Real requests go through the installed +unit: linuxmusterTools opens the WebUI's config.yml with its own loader (which chmods it, lab B3) +and reads the scope of a school admin and of a teacher (by UID) and a class; a connection added +to the plugin's config.yml by rename is used by the running bridge (same PID); with the AD +stopped, a German 503 logged with UID and identity. Also: linuxmusterTools is imported by `systemd-run` with exactly the `[Service]` sandbox options of the shipped unit (lab B1: `net conf list` needs netlink), a bridge request reaches the LDAP step (503 "directory" in German, logged with UID and identity); the socket enabled and active (0666), the service started by the first connection (socket activation, root), `SO_PEERCRED` diff --git a/docs/threat-model.md b/docs/threat-model.md index e817d64..827c7c5 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -47,7 +47,7 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T24 | **Activity log = profile of browsing per person** (ADR-023): data of students and staff, a teacher looking at students of other classes or at colleagues, an exported CSV passed on | off by default per instance; switching on needs who confirmed the privacy notice (stored with the time in the instance's git log); minute and domain only, no URL, no client address; retention 1–365 days as whole day files (deleted before a query could read them); scope computed on the school server from the AD on every request, only the allowed users list goes to the proxy, which filters every SQL statement on it; teachers only students of their own classes/projects and school, never teachers; export only for administrators; every read and every settings change audited (person, scope, users, range) before data is read, 503 if the audit log cannot be written; the audit log only for global administrators, own retention | `test_activity.py`, `test_activity_api.py`, webui `test_activity_views.py`, E2E spool check | | T25 | **The users list comes from the WebUI** (ADR-023): the proxy cannot check who asks; a stolen token reads everything | the token is the global administrator's credential already (T5, T18); the list is computed on the server, never taken from the browser; the audit names the person the WebUI reports and, for the CLI, `cli:`; the WebUI logs every request of the view, refused ones and those without a proxy request included, to its system log (`journalctl -t lmn-squid-activity`) | `test_activity_views.py` (out-of-scope requests never reach a proxy) | | T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 1733 (squid's proxy user can create, not list; no set-group-id, which `RestrictSUIDSGID=yes` refuses), files 0644 unreachable for other host users behind the 0750 parent; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured) | `test_activity.py` (receiver), local squid 6.14 test | -| T27 | **The activity bridge** (ADR-023 addendum 2): a root service on a socket every local process can open; a teacher's worker (or any local user) claims to be someone else, asks for students outside its classes, floods the bridge, or sends a huge or slow request; a bug in the bridge leaks the tokens | the identity of a non-root caller comes from the kernel (`SO_PEERCRED` → `getpwuid`), a claimed identity must match it; only root names a person; the scope is computed in the bridge from the AD, a users list of the caller is ignored; tokens never leave the bridge (answers carry activity data and typed errors only); request ≤ 256 KiB, 10 s, 32 at once, 60 per UID in 10 s; no shell, no path from the caller; systemd hardening (`ProtectSystem=full`, `NoNewPrivileges`, `ProtectHome`, private /tmp, kernel protections, address families AF_UNIX/AF_INET/AF_INET6/AF_NETLINK — netlink for samba's interface list); one log line per request with UID and identity, refusals audited (tag `lmn-squid-activity`). Residual: upstream gives teachers `sudo ALL` (`webui-sudoers`), so a teacher with a shell on the server is root anyway; the bridge does not make that worse | `webui/tests/test_bridge.py`; `scripts/tests/webui_ajenti_it.sh` (bridge asked as teacher, student, `nobody` and root UIDs) | +| T27 | **The activity bridge** (ADR-023 addendum 2): a root service on a socket every local process can open; a teacher's worker (or any local user) claims to be someone else, asks for students outside its classes, floods the bridge, or sends a huge or slow request; a bug in the bridge leaks the tokens | the identity of a non-root caller comes from the kernel (`SO_PEERCRED` → `getpwuid`), a claimed identity must match it; only root names a person; the scope is computed in the bridge from the AD, a users list of the caller is ignored; tokens never leave the bridge (answers carry activity data and typed errors only); request ≤ 256 KiB, 10 s, 32 at once, 60 per UID in 10 s; no shell, no path from the caller; systemd hardening (`ProtectSystem=true`: /usr and /boot read-only, /etc writable because linuxmusterTools chmods the files it reads as root, ADR-023 addendum 4; `NoNewPrivileges`, `ProtectHome`, private /tmp, kernel protections, address families AF_UNIX/AF_INET/AF_INET6/AF_NETLINK — netlink for samba's interface list); one log line per request with UID and identity, refusals audited (tag `lmn-squid-activity`). Residual: upstream gives teachers `sudo ALL` (`webui-sudoers`), so a teacher with a shell on the server is root anyway; the bridge does not make that worse | `webui/tests/test_bridge.py`; `scripts/tests/webui_ajenti_it.sh` (bridge asked as teacher, student, `nobody` and root UIDs) | ## Non-goals (deliberate) diff --git a/packaging/systemd/linuxmuster-squid-webui-activity.service b/packaging/systemd/linuxmuster-squid-webui-activity.service index bfc17b5..5283ffc 100644 --- a/packaging/systemd/linuxmuster-squid-webui-activity.service +++ b/packaging/systemd/linuxmuster-squid-webui-activity.service @@ -18,9 +18,14 @@ MemoryMax=256M TasksMax=128 NoNewPrivileges=yes -# full, not strict: linuxmusterTools runs "net conf list" when imported, which opens Samba's -# tdb files under /var/lib/samba (the WebUI's root workers run it without any sandbox). -ProtectSystem=full +# true (/usr, /boot read-only), not full or strict: linuxmusterTools writes under /etc while it +# only reads. Its YAML loader chmods every file it opens as root (lmnfile.py: config.yml of the +# WebUI, custom_fields.yml of every school), and "net conf list" at import opens samba's tdb +# files under /var/lib/samba (lab 2026-11-25, B3). A list of writable paths would have to follow +# linuxmusterTools' internals, and a single-file ReadWritePaths pins the inode: a config.yml +# replaced by rename would stay stale in the running bridge. The bridge reads the AD with the +# Administrator password anyway (ADR-023 addendum 4). +ProtectSystem=true ProtectHome=yes PrivateTmp=yes ProtectKernelTunables=yes diff --git a/scripts/tests/webui_bridge_systemd.sh b/scripts/tests/webui_bridge_systemd.sh index 4db275c..805762d 100755 --- a/scripts/tests/webui_bridge_systemd.sh +++ b/scripts/tests/webui_bridge_systemd.sh @@ -6,9 +6,13 @@ # the real linuxmusterTools (lmn73) plus samba's `net`: # * install enables and starts the bridge's socket; the first connection starts the service as # root through socket activation; SO_PEERCRED through the systemd-passed socket; -# * the AD part under the shipped unit's sandbox (lab B1): linuxmusterTools is imported (it runs -# `net conf list`) by systemd-run with exactly the [Service] sandbox options of the unit, and -# a bridge request reaches the LDAP step (no LDAP server here: 503 "directory", German text); +# * the AD part under the shipped unit's sandbox (lab B1, B3): linuxmusterTools is imported (it +# runs `net conf list`) by systemd-run with exactly the [Service] sandbox options of the unit; +# then real requests through the installed unit: linuxmusterTools opens the WebUI's config.yml +# (and a school's custom_fields.yml) with its own loader, which chmods them, binds over LDAPS +# and reads users and classes from an OpenLDAP stand-in of the AD (webui_bridge_systemd/); +# * a connection added to the plugin's config.yml (replaced by rename, as the plugin writes it) +# is used by the running bridge without a restart; # * failures are logged with UID and identity, never a raw exception class to the caller; # * reinstall keeps it working; remove, purge and a downgrade to a build without the bridge # leave nothing listening and no dangling symlink. @@ -28,8 +32,9 @@ git -C "$UPSTREAM/linuxmuster-tools" archive origin/lmn73 usr/lib/python3/dist-p git -C "$UPSTREAM/sophomorix4" archive origin/bionic sophomorix-samba/config-devel/sophomorix.ini \ | tar -C "$WORK" -x docker run -d --name "$NAME" --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \ - -v "$DEB:/pkg/webui.deb:ro" -v "$WORK:/upstream:ro" --tmpfs /run --tmpfs /run/lock "$IMG" \ - bash -c 'apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends systemd systemd-sysv python3-yaml python3-ldap python3-configobj python3-magic python3-pexpect samba-common-bin iproute2 dbus >/dev/null && exec /sbin/init' >/dev/null + -v "$DEB:/pkg/webui.deb:ro" -v "$WORK:/upstream:ro" \ + -v "$ROOT/scripts/tests/webui_bridge_systemd:/stub:ro" --tmpfs /run --tmpfs /run/lock "$IMG" \ + bash -c 'echo "slapd slapd/no_configuration boolean true" | debconf-set-selections && apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends systemd systemd-sysv python3-yaml python3-ldap python3-configobj python3-magic python3-pexpect samba-common-bin iproute2 dbus slapd ldap-utils libldap-common openssl ca-certificates >/dev/null && exec /sbin/init' >/dev/null for _ in $(seq 1 150); do docker exec "$NAME" sh -c 'systemctl is-system-running 2>/dev/null | grep -qE "running|degraded"' && break sleep 2 @@ -39,6 +44,16 @@ set -u fails=0 ok() { echo " [PASS] $*"; } no() { echo " [FAIL] $*"; fails=$((fails + 1)); } +req() { # [json body] -> " " + runuser -u "$1" -- python3 -I -c ' +import json, socket, sys +s = socket.socket(socket.AF_UNIX); s.connect("/run/linuxmuster-squid-webui/activity.sock") +body = json.loads(sys.argv[4]) if len(sys.argv) > 4 else {} +s.sendall(json.dumps({"v": 1, "identity": sys.argv[1], "method": sys.argv[2], "path": sys.argv[3], "query": {}, "body": body}).encode()) +s.shutdown(socket.SHUT_WR); raw = b"" +while (c := s.recv(65536)): raw += c +a = json.loads(raw); print(a["status"], json.dumps(a["data"], separators=(",", ":"), sort_keys=True))' "${@:2}" 2>&1 | tail -1 +} ask() { # -> " " runuser -u "$1" -- python3 -I -c ' import json, socket, sys @@ -69,7 +84,11 @@ printf '[setup]\nschoolname = Test\n' > /var/lib/linuxmuster/setup.ini printf 'linuxmuster:\n ldap:\n binddn: cn=x\n bindpw: x\n searchdn: dc=dev,dc=lmschule,dc=de\n' > /etc/linuxmuster/webui/config.yml printf 'Muster!\n' > /etc/linuxmuster/.secret/administrator; chmod 600 /etc/linuxmuster/.secret/administrator printf '[global]\n realm = DEV.LMSCHULE.DE\n workgroup = DEV\n netbios name = SERVER\n server role = active directory domain controller\n' > /etc/samba/smb.conf +# a school that uses custom fields: linuxmusterTools opens this file on every LDAP read too +printf 'custom: {}\n' > /etc/linuxmuster/sophomorix/default-school/custom_fields.yml useradd -M -u 2001 dslehr01 +# the AD: OpenLDAP with the sophomorix attributes the view reads +/stub/slapd-stub.sh && ok "LDAP stand-in of the AD runs (LDAPS, localhost:636)" || no "LDAP stand-in" # Docker's Ubuntu images forbid starting services from maintainer scripts; a server does not rm -f /usr/sbin/policy-rc.d @@ -89,21 +108,64 @@ out=$(systemd-run --quiet --wait --pipe --collect "${props[@]}" /usr/bin/python3 'import linuxmusterTools.ldapconnector; print("imported")' 2>&1 | tail -3) case "$out" in *imported*) ok "linuxmusterTools (net conf list) imports under the unit's sandbox";; *) no "linuxmusterTools import under the unit's sandbox: $out";; esac -r=$(ask root pgmadmin) -case "$r" in "503 directory Das Benutzerverzeichnis"*) ok "root, AD without LDAP server: $r";; *) no "root: $r";; esac +# --- B3: real requests through the installed unit (linuxmusterTools reads config.yml with its own +# loader, which chmods it, then reads the AD over LDAPS) +mkdir -p /etc/linuxmuster-squid-webui && chmod 700 /etc/linuxmuster-squid-webui +printf 'version: 1\nconnections:\n- name: lab\n url: http://127.0.0.1:1\n token: it-token-0123456789abcdef0123456789\n schools: [default-school]\n' \ + > /etc/linuxmuster-squid-webui/config.yml +chmod 600 /etc/linuxmuster-squid-webui/config.yml +r=$(req root pgmadmin GET scope) +case "$r" in '200 '*'"role":"schooladministrator"'*) ok "school admin: /scope from the AD (200)";; *) no "school admin /scope: ${r:0:300}";; esac +r=$(req dslehr01 "" GET scope) +case "$r" in '200 '*'"name":"5a"'*'"role":"teacher"'*) ok "teacher by UID: /scope with class 5a from the AD";; *) no "teacher /scope: ${r:0:300}";; esac +r=$(req root pgmadmin GET group/class/5a/members) +case "$r" in '200 '*'"s5a1"'*'"s5a2"'*) ok "class 5a members from the AD";; *) no "members: ${r:0:300}";; esac +case "$r" in *s6b1*) no "members of 5a include s6b1";; *) ok "no member of another class";; esac journalctl -u $SERVICE --no-pager > /var/tmp/journal.txt -grep -q "the AD could not be read (/users/pgmadmin)" /var/tmp/journal.txt \ - && ok "the bridge got to the LDAP step (import and net conf list worked)" \ - || no "the bridge did not reach LDAP: $(grep -E 'cannot be imported|Error' /var/tmp/journal.txt | tail -2)" +grep -qE "Read-only file system|could not be read|cannot be imported" /var/tmp/journal.txt \ + && no "AD read failed in the unit: $(grep -E 'Read-only|could not be read|cannot be imported' /var/tmp/journal.txt | tail -1)" \ + || ok "no AD error in the bridge's journal" grep -q "Could not determine network interfaces" /var/tmp/journal.txt && no "net conf list failed in the unit" || ok "no netlink failure" -grep -q "uid=0 identity=pgmadmin GET scope -> 503" /var/tmp/journal.txt && ok "failed request logged with UID and identity" || no "failed request without UID/identity in the journal" -grep -qE "CalledProcessError|Traceback" <<<"$r" && no "exception class reaches the caller: $r" || ok "no exception class in the answer" +grep -q "uid=0 identity=pgmadmin GET scope -> 200" /var/tmp/journal.txt && ok "request logged with UID and identity" || no "request not logged" + +# --- a changed connection file reaches the running bridge (no restart) +pid=$(systemctl show -p MainPID --value $SERVICE) +q='{"since": '$(( $(date +%s) - 3600 ))', "until": '$(date +%s)', "group": {"kind": "class", "name": "5a"}}' +r=$(req root pgmadmin POST query/users "$q") +case "$r" in '200 '*'"connection":"lab"'*) ok "the bridge asks the configured proxy";; *) no "query/users: ${r:0:300}";; esac +cat > /etc/linuxmuster-squid-webui/config.yml.tmp <<'YML' +version: 1 +connections: +- name: lab + url: http://127.0.0.1:1 + token: it-token-0123456789abcdef0123456789 + schools: [default-school] +- name: added + url: http://127.0.0.1:2 + token: it-token-added-0123456789abcdef012345 + schools: [default-school] +YML +chmod 600 /etc/linuxmuster-squid-webui/config.yml.tmp +mv /etc/linuxmuster-squid-webui/config.yml.tmp /etc/linuxmuster-squid-webui/config.yml +r=$(req root pgmadmin POST query/users "$q") +case "$r" in '200 '*'"connection":"added"'*) ok "a connection added by rename is used at once";; *) no "new connection not seen: ${r:0:300}";; esac +[ "$(systemctl show -p MainPID --value $SERVICE)" = "$pid" ] && ok "same bridge process (pid $pid), no restart" || no "bridge restarted" + +# --- the AD down: a German 503, logged with UID and identity, no exception class +systemctl stop slapd-stub +r=$(ask root s6b1) # not asked before: not in the bridge's 10-second scope cache +case "$r" in "503 directory Das Benutzerverzeichnis"*) ok "AD down: German 503";; *) no "AD down: $r";; esac +grep -qE "CalledProcessError|Traceback|OSError" <<<"$r" && no "exception class reaches the caller: $r" || ok "no exception class in the answer" +grep -q "uid=0 identity=s6b1 GET scope -> 503" <(journalctl -u $SERVICE --no-pager) && ok "failed request logged with UID and identity" || no "failed request without UID/identity in the journal" +systemd-run --quiet --unit=slapd-stub-again /usr/sbin/slapd -d 0 -u openldap -g openldap \ + -f /var/tmp/slapd/slapd.conf -h "ldaps:///" +sleep 1 # --- identity from the kernel through the systemd socket r=$(ask dslehr01 pgmadmin); case "$r" in "403 identity"*) ok "local user claiming another identity: 403";; *) no "claim: $r";; esac [ "$(systemctl is-active $SERVICE)" = active ] && ok "service started by socket activation" || no "service not started" [ "$(systemctl show -p User --value $SERVICE)" = "" ] && ok "service runs as root" || no "service user" -r=$(ask nobody ""); case "$r" in "403 "*|"503 directory"*) ok "nobody gets no data: ${r%% *}";; *) no "nobody: $r";; esac +r=$(ask nobody ""); case "$r" in "403 "*) ok "nobody gets no data: ${r%% *}";; *) no "nobody: $r";; esac grep -q "uid=2001 identity=- GET scope -> 403" <(journalctl -u $SERVICE --no-pager) && ok "refusal logged with the UID" || no "refusal not logged" # --- reinstall (upgrade to the same version) diff --git a/scripts/tests/webui_bridge_systemd/slapd-stub.sh b/scripts/tests/webui_bridge_systemd/slapd-stub.sh new file mode 100755 index 0000000..7801008 --- /dev/null +++ b/scripts/tests/webui_bridge_systemd/slapd-stub.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# An OpenLDAP stand-in for the school server's AD, for webui_bridge_systemd.sh (runs inside its +# container): LDAPS on localhost:636 with a certificate the system trusts, bind DN and password as +# linuxmusterTools uses them (CN=Administrator,CN=Users,, /etc/linuxmuster/.secret/ +# administrator), a minimal sophomorix-like tree for default-school. +set -euo pipefail +D=/var/tmp/slapd +B="DC=dev,DC=lmschule,DC=de" +S="OU=default-school,OU=SCHOOLS,$B" +mkdir -p "$D/db" +# a CA the system trusts and a server certificate for localhost signed by it +openssl req -x509 -newkey rsa:2048 -nodes -days 2 -subj "/CN=slapd stub CA" \ + -keyout "$D/ca.key" -out "$D/ca.pem" 2>/dev/null +openssl req -newkey rsa:2048 -nodes -subj "/CN=localhost" -keyout "$D/key.pem" -out "$D/req.pem" 2>/dev/null +printf 'basicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1\n' > "$D/ext.cnf" +openssl x509 -req -in "$D/req.pem" -CA "$D/ca.pem" -CAkey "$D/ca.key" -CAcreateserial -days 2 \ + -extfile "$D/ext.cnf" -out "$D/cert.pem" 2>/dev/null +cp "$D/ca.pem" /usr/local/share/ca-certificates/slapd-stub.crt +update-ca-certificates >/dev/null 2>&1 +chown -R openldap:openldap "$D" +cat > "$D/slapd.conf" < [classes..] + local cn=$1 ou=$2 role=$3; shift 3 + printf 'dn: CN=%s,%s\nobjectClass: user\ncn: %s\nsAMAccountName: %s\nsophomorixRole: %s\nsophomorixSchoolname: default-school\ndistinguishedName: CN=%s,%s\ndisplayName: %s\n' \ + "$cn" "$ou" "$cn" "$cn" "$role" "$cn" "$ou" "$cn" + for c in "$@"; do member "$c"; done + echo +} +ou() { printf 'dn: %s\nobjectClass: organizationalUnit\nou: %s\n\n' "$1" "$2"; } +{ + printf 'dn: %s\nobjectClass: organization\nobjectClass: dcObject\no: dev\ndc: dev\n\n' "$B" + ou "OU=SCHOOLS,$B" SCHOOLS; ou "$S" default-school + ou "OU=Management,$S" Management; ou "OU=Teachers,$S" Teachers; ou "OU=Students,$S" Students + ou "OU=5a,OU=Students,$S" 5a; ou "OU=6b,OU=Students,$S" 6b + person pgmadmin "OU=Management,$S" schooladministrator + person dslehr01 "OU=Teachers,$S" teacher 5a + person s5a1 "OU=5a,OU=Students,$S" student 5a + person s5a2 "OU=5a,OU=Students,$S" student 5a + person s6b1 "OU=6b,OU=Students,$S" student 6b +} > "$D/tree.ldif" +runuser -u openldap -- slapadd -f "$D/slapd.conf" -l "$D/tree.ldif" +systemd-run --quiet --unit=slapd-stub /usr/sbin/slapd -d 0 -u openldap -g openldap \ + -f "$D/slapd.conf" -h "ldaps:///" +for _ in $(seq 1 50); do + # the certificate check linuxmusterTools does (OPT_X_TLS_REQUIRE_CERT: allow) + LDAPTLS_REQCERT=allow ldapsearch -LLL -H ldaps://localhost:636 -x -b "$B" -s base dn \ + >/dev/null 2>&1 && exit 0 + sleep 0.2 +done +echo "slapd stub did not start" >&2 +journalctl -u slapd-stub --no-pager | tail -5 >&2 +exit 1 diff --git a/scripts/tests/webui_bridge_systemd/sophomorix-stub.schema b/scripts/tests/webui_bridge_systemd/sophomorix-stub.schema new file mode 100644 index 0000000..172f747 --- /dev/null +++ b/scripts/tests/webui_bridge_systemd/sophomorix-stub.schema @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The part of the AD's (Samba + sophomorix) schema linuxmusterTools reads for the activity view, +# for an OpenLDAP stand-in in webui_bridge_systemd.sh. OIDs from OpenLDAP's experimental arc. +attributetype ( 1.3.6.1.4.1.4203.666.11.1 NAME 'sAMAccountName' + EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch + SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) +attributetype ( 1.3.6.1.4.1.4203.666.11.2 NAME 'sophomorixRole' + EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) +attributetype ( 1.3.6.1.4.1.4203.666.11.3 NAME 'sophomorixSchoolname' + EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) +attributetype ( 1.3.6.1.4.1.4203.666.11.4 NAME 'memberOf' + EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) +# distinguishedName: slapd's own (2.5.4.49, DN syntax) +attributetype ( 1.3.6.1.4.1.4203.666.11.6 NAME 'displayName' + EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) +attributetype ( 1.3.6.1.4.1.4203.666.11.7 NAME 'sophomorixType' + EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) +attributetype ( 1.3.6.1.4.1.4203.666.11.8 NAME 'sophomorixMemberGroups' + EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) +objectclass ( 1.3.6.1.4.1.4203.666.12.1 NAME 'user' SUP top STRUCTURAL MUST cn + MAY ( sAMAccountName $ sophomorixRole $ sophomorixSchoolname $ memberOf $ + distinguishedName $ displayName $ givenName $ sn ) ) +objectclass ( 1.3.6.1.4.1.4203.666.12.2 NAME 'group' SUP top STRUCTURAL MUST cn + MAY ( sAMAccountName $ sophomorixType $ sophomorixSchoolname $ distinguishedName $ + sophomorixMemberGroups $ member ) ) From bdfccb52b57bdd62394a5b830932cbb1defda557 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 20:13:49 +0100 Subject: [PATCH 34/45] fix(controlplane): stream spool files with bounded memory, quarantine failures The collector read a spool file whole and kept every parsed line: about 285 MiB for a 16-MiB file under the unit's MemoryMax=256M; a bigger file was OOM-killed in every run and stopped the collection of every instance (cold check M1). Files are now read line by line and stored in chunks of 20 000 lines, each chunk per day in one transaction with the ledger name #, so a run killed mid-file continues without counting twice. HTTPS side lines pair with their CONNECT line across chunks through a short time window; a partner stored with an earlier chunk is corrected in the current chunk's transaction. Peak RSS stays at 63-74 MiB from 16 to 200 MiB. Each file is attempted on its own (counted before it is read); a failing file stops neither the other files nor the other instances, and after three attempts it moves to the instance's quarantine folder with an error in the journal; usage reports the number. Removing the data removes the quarantine. --- controlplane/lmnsquid/activity.py | 314 +++++++++++++++++++-- controlplane/tests/test_activity_stream.py | 244 ++++++++++++++++ scripts/tests/activity_memory.sh | 44 +++ 3 files changed, 581 insertions(+), 21 deletions(-) create mode 100644 controlplane/tests/test_activity_stream.py create mode 100755 scripts/tests/activity_memory.sh diff --git a/controlplane/lmnsquid/activity.py b/controlplane/lmnsquid/activity.py index f3eaf4f..8b79f74 100644 --- a/controlplane/lmnsquid/activity.py +++ b/controlplane/lmnsquid/activity.py @@ -21,6 +21,7 @@ import datetime import errno import fcntl +import json import logging import os import shutil @@ -205,6 +206,9 @@ def delete_data(data_root: str, spool_root: str, name: str) -> int: files = day_files(data_dir(data_root, name)) for _day, path in files: remove_day_file(path) + # what the collector gave up on is activity data too + shutil.rmtree(data_dir(data_root, name) / QUARANTINE_DIR, ignore_errors=True) + _unlink(data_dir(data_root, name) / ATTEMPTS_FILE) spool = spool_dir(spool_root, name) try: for entry in os.scandir(spool): @@ -244,6 +248,7 @@ def usage(data_root: str, spool_root: str, name: str) -> dict[str, object]: "newest": files[-1][0].isoformat() if files else None, "spool_files": waiting, "spool_bytes": waiting_bytes, + "quarantined": len(quarantined(data_root, name)), } @@ -329,6 +334,18 @@ def day(self, minute: int) -> datetime.date: # A side line belongs to the CONNECT line of the same user and domain within this many seconds. SIDE_WINDOW = 2 +# Streaming (cold check 2026-11-25, M1): a spool file is read in chunks of this many lines; each +# chunk goes into the day files in its own transaction (ledger name "#"), so memory +# does not grow with the file and a run cut short continues where it stopped. +CHUNK_LINES = 20_000 +# squid writes lines in completion order; a side line and its CONNECT line may be this many +# seconds out of order and still be paired across chunks. +PAIR_SLACK = 30 +# A spool file whose collection failed (or killed the run) this many times goes to quarantine. +MAX_ATTEMPTS = 3 +QUARANTINE_DIR = "quarantine" +ATTEMPTS_FILE = ".attempts.json" + def aggregate( lines: Iterable[bytes], @@ -452,15 +469,27 @@ def _ids(db: sqlite3.Connection, table: str, names: Iterable[str]) -> dict[str, return ids -def store_day(db: sqlite3.Connection, source: str, rows: dict[Key, list]) -> bool: - """Add one spool file's rows of one day in one transaction; ``False`` if it was already in.""" +def store_day( + db: sqlite3.Connection, + source: str, + rows: dict[Key, list], + adjust: dict[Key, list] | None = None, + legacy: str | None = None, +) -> bool: + """Add one spool file's (or one chunk's) rows of one day in one transaction; ``False`` if it + was already in. ``adjust``: rows stored by an earlier chunk that a side line of this chunk + marks blocked (``[blocked to add, category]``). ``legacy``: the file's ledger name of a + collector before the chunks (a file it stored whole is not stored again).""" + adjust = adjust or {} db.execute("BEGIN IMMEDIATE") try: - if db.execute("SELECT 1 FROM ingested WHERE f = ?", (source,)).fetchone(): + names = (source,) if legacy is None else (source, legacy) + marks = ",".join("?" * len(names)) + if db.execute(f"SELECT 1 FROM ingested WHERE f IN ({marks})", names).fetchone(): db.execute("ROLLBACK") return False - users = _ids(db, "users", (k[0] for k in rows)) - hosts = _ids(db, "hosts", (k[2] for k in rows)) + users = _ids(db, "users", [k[0] for k in rows] + [k[0] for k in adjust]) + hosts = _ids(db, "hosts", [k[2] for k in rows] + [k[2] for k in adjust]) act = [] hourly: dict[tuple[int, int], list[int]] = {} daily: dict[tuple[int, int], list] = {} @@ -509,6 +538,17 @@ def store_day(db: sqlite3.Connection, source: str, rows: dict[Key, list]) -> boo "first = min(first, excluded.first), last = max(last, excluded.last)", [(u, h, *v) for (u, h), v in sorted(daily.items())], ) + for (user, minute, host), (blocked, c) in sorted(adjust.items()): + u, h = users[user], hosts[host] + db.execute( + "UPDATE act SET x = x + ?, c = coalesce(?, c) WHERE u = ? AND m = ? AND h = ?", + (blocked, c, u, minute, h), + ) + db.execute("UPDATE uh SET x = x + ? WHERE u = ? AND hr = ?", (blocked, u, minute // 60)) + db.execute( + "UPDATE uhd SET x = x + ?, c = coalesce(?, c) WHERE u = ? AND h = ?", + (blocked, c, u, h), + ) db.execute("INSERT INTO ingested(f, at) VALUES (?, ?)", (source, int(time.time()))) db.execute("COMMIT") except BaseException: @@ -559,6 +599,204 @@ def _source_name(path: Path) -> str: return name +class _FileCollector: + """One spool file, streamed: what :func:`aggregate` computes for the whole file, in chunks of + :data:`CHUNK_LINES` lines with memory bound by the chunk and the pairing window, each chunk + stored per day in one transaction (ledger ``#``).""" + + def __init__( + self, + target: Path, + source: str, + days: DayMapper, + counters: Counters, + keep_from: datetime.date | None, + now: float, + ) -> None: + self.target = target + self.source = source + self.days = days + self.counters = counters + self.keep_from = keep_from + self.now = now + self.chunk = 0 + self.lines_in_chunk = 0 + self.rows: Agg = {} + self.adjust: dict[datetime.date, dict[Key, list]] = {} + # (user, host) -> CONNECT/plain lines of the last seconds: [ts, blocked, day, key, chunk] + self.recent: dict[tuple[str, str], list[list]] = {} + self.pending: list[Parsed] = [] # side lines waiting for a CONNECT that may follow + self.max_ts = 0 + + def _add( + self, ts: int, user: str, host: str, size: int, blocked: int, cat: str | None + ) -> tuple: + minute = ts // 60 + day = self.days.day(minute) + key = (user, minute, host) + bucket = self.rows.setdefault(day, {}) + row = bucket.get(key) + if row is None: + row = bucket[key] = [0, 0, 0, None] + row[0] += 1 + row[1] += size + row[2] += blocked + if cat is not None: + row[3] = cat + self.counters.used += 1 + return day, key + + def _mark_blocked(self, partner: list, cat: str | None) -> None: + partner[1] = 1 + day, key = partner[2], partner[3] + row = self.rows.get(day, {}).get(key) if partner[4] == self.chunk else None + if row is not None: + row[2] += 1 + if cat is not None: + row[3] = cat + return + # the row went into the day file with an earlier chunk: correct it with this chunk + adj = self.adjust.setdefault(day, {}).setdefault(key, [0, None]) + adj[0] += 1 + if cat is not None: + adj[1] = cat + + def _resolve(self, side: Parsed) -> None: + ts, user, host, size, blocked, cat, _side = side + partner = next( + (p for p in self.recent.get((user, host), ()) if abs(p[0] - ts) <= SIDE_WINDOW), None + ) + if partner is not None: + self.counters.side += 1 + if blocked and not partner[1]: + self._mark_blocked(partner, cat) + return + if not blocked: + self.counters.side += 1 + return + self._add(ts, user, host, size, blocked, cat) + + def _settle(self, final: bool = False) -> None: + """Resolve the side lines no later CONNECT can pair any more; forget old partners.""" + horizon = self.max_ts - SIDE_WINDOW - PAIR_SLACK + waiting: list[Parsed] = [] + for side in self.pending: + if final or side[0] < horizon: + self._resolve(side) + else: + waiting.append(side) + self.pending = waiting + if final: + return + oldest_needed = horizon - SIDE_WINDOW - PAIR_SLACK + for k in list(self.recent): + kept = [p for p in self.recent[k] if p[0] >= oldest_needed] + if kept: + self.recent[k] = kept + else: + del self.recent[k] + + def line(self, raw: bytes) -> None: + c = self.counters + c.lines += 1 + self.lines_in_chunk += 1 + try: + parsed = parse_line(raw) + except (ValueError, UnicodeDecodeError): + c.broken += 1 + parsed = None + else: + if parsed is None: + c.anonymous += 1 + if parsed is not None: + ts = parsed[0] + if ts > self.now + FUTURE_SLACK_SECONDS or ts <= 0: + c.broken += 1 + elif self.keep_from is not None and self.days.day(ts // 60) < self.keep_from: + c.dropped_old += 1 + else: + self.max_ts = max(self.max_ts, ts) + if parsed[6]: + self.pending.append(parsed) + else: + ts, user, host, size, blocked, cat, _side = parsed + day, key = self._add(ts, user, host, size, blocked, cat) + self.recent.setdefault((user, host), []).append( + [ts, blocked, day, key, self.chunk] + ) + if self.lines_in_chunk >= CHUNK_LINES: + self._settle() + self.flush() + + def flush(self) -> None: + name = f"{self.source}#{self.chunk}" + for day in sorted(set(self.rows) | set(self.adjust)): + rows = self.rows.get(day, {}) + db = connect_day(self.target / day_name(day), create=True) + try: + if store_day(db, name, rows, self.adjust.get(day), legacy=self.source): + self.counters.rows += len(rows) + self.counters.days.add(day.isoformat()) + finally: + db.close() + self.rows = {} + self.adjust = {} + self.chunk += 1 + self.lines_in_chunk = 0 + + def run(self, fh: Iterable[bytes]) -> None: + for raw in fh: + if not raw.endswith(b"\n"): + if raw.strip(): + self.counters.broken += 1 # a write cut short + continue + if raw.strip(): + self.line(raw) + self._settle(final=True) + if self.rows or self.adjust or self.chunk == 0: + self.flush() + + +def _read_attempts(directory: Path) -> dict[str, int]: + try: + data = json.loads((directory / ATTEMPTS_FILE).read_text()) + except (FileNotFoundError, ValueError): + return {} + return {str(k): int(v) for k, v in data.items()} if isinstance(data, dict) else {} + + +def _write_attempts(directory: Path, attempts: dict[str, int]) -> None: + path = directory / ATTEMPTS_FILE + if not attempts: + _unlink(path) + return + tmp = directory / (ATTEMPTS_FILE + ".tmp") + tmp.write_text(json.dumps(attempts, sort_keys=True)) + os.replace(tmp, path) + + +def quarantined(data_root: str, name: str) -> list[str]: + """Spool files of ``name`` the collector gave up on (oldest first).""" + try: + return sorted(e.name for e in os.scandir(data_dir(data_root, name) / QUARANTINE_DIR)) + except FileNotFoundError: + return [] + + +def _quarantine(path: Path, target: Path, inst: str, attempts: int) -> None: + directory = target / QUARANTINE_DIR + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + shutil.move(str(path), str(directory / path.name)) + logger.error( + "activity: %s: spool file %s failed %d times, moved to %s (not counted; delete it or " + "move it back into the spool to try again)", + inst, + path.name, + attempts, + directory, + ) + + def collect_instance( inst: Instance, data_root: str, @@ -567,29 +805,61 @@ def collect_instance( now: float | None = None, counters: Counters | None = None, ) -> Counters: - """Collect the spool of ``inst`` into its day files and apply its retention.""" + """Collect the spool of ``inst`` into its day files and apply its retention. + + Every file on its own: a file that fails is counted (before it is read, so a run killed by + it counts too), the others go on; after :data:`MAX_ATTEMPTS` the file goes to quarantine.""" counters = counters or Counters() now = time.time() if now is None else now days = DayMapper(zone) keep_from = oldest_kept(today_in(zone, now), inst.activity_retention_days) target = data_dir(data_root, inst.name) - for path in spool_files(spool_dir(spool_root, inst.name), now): + files = spool_files(spool_dir(spool_root, inst.name), now) + if files: + target.mkdir(mode=0o700, parents=True, exist_ok=True) + attempts = _read_attempts(target) + for path in files: + source = _source_name(path) + tried = attempts.get(source, 0) + if tried >= MAX_ATTEMPTS: + try: + _quarantine(path, target, inst.name, tried) + except OSError as exc: + logger.error("activity: %s: quarantine of %s failed: %s", inst.name, path.name, exc) + attempts.pop(source, None) + _write_attempts(target, attempts) + continue + attempts[source] = tried + 1 + _write_attempts(target, attempts) try: - data = path.read_bytes() + with open(path, "rb") as fh: + counters.files += 1 + _FileCollector(target, source, days, counters, keep_from, now).run(fh) except FileNotFoundError: + attempts.pop(source, None) + _write_attempts(target, attempts) + continue + except Exception as exc: # noqa: BLE001 - one file must not stop the others + logger.error( + "activity: %s: collecting %s failed (attempt %d of %d): %s: %s", + inst.name, + path.name, + tried + 1, + MAX_ATTEMPTS, + type(exc).__name__, + exc, + ) continue - counters.files += 1 - grouped = aggregate(complete_lines(data, counters), days, counters, keep_from, now) - source = _source_name(path) - for day, rows in sorted(grouped.items()): - db = connect_day(target / day_name(day), create=True) - try: - if store_day(db, source, rows): - counters.rows += len(rows) - counters.days.add(day.isoformat()) - finally: - db.close() _unlink(path) + attempts.pop(source, None) + _write_attempts(target, attempts) + # files that left the spool (collected by an older run, deleted by hand) need no counter + waiting = {_source_name(p) for p in spool_files(spool_dir(spool_root, inst.name), now)} + stale = [k for k in attempts if k not in waiting] + if stale: + for k in stale: + attempts.pop(k) + _write_attempts(target, attempts) apply_retention(data_root, inst.name, inst.activity_retention_days, zone, now) return counters @@ -617,8 +887,10 @@ def collect_all( ) if not inst.activity_log_enabled and has_spool: remove_spool_if_empty(paths.spool_root, inst.name) - except (OSError, sqlite3.Error) as exc: - logger.error("activity: collecting %s failed: %s", inst.name, exc) + except Exception as exc: # noqa: BLE001 - one instance must not stop the others + logger.error( + "activity: collecting %s failed: %s: %s", inst.name, type(exc).__name__, exc + ) return results diff --git a/controlplane/tests/test_activity_stream.py b/controlplane/tests/test_activity_stream.py new file mode 100644 index 0000000..88dc096 --- /dev/null +++ b/controlplane/tests/test_activity_stream.py @@ -0,0 +1,244 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The collector streams a spool file (cold check 2026-11-25, M1): memory does not grow with the +file, a run cut short continues without counting twice, one failing file stops neither the other +files nor the other instances, and a file that keeps failing goes to quarantine.""" + +from __future__ import annotations + +import json +import random +import resource +import sqlite3 +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest +from test_activity import T0, ZONE, Env, _inst, line + +from lmnsquid import activity + + +@pytest.fixture +def env(tmp_path: Path) -> Env: + return Env(tmp_path) + + +def _dump(env: Env, day: str = "2026-11-25") -> dict[str, Any]: + db = env.db(day) + q = { + "act": "SELECT us.name, a.m, ho.name, a.n, a.b, a.x, a.c FROM act a " + "JOIN users us ON us.id = a.u JOIN hosts ho ON ho.id = a.h ORDER BY 1, 2, 3", + "uh": "SELECT us.name, hr, n, b, x, last FROM uh JOIN users us ON us.id = u ORDER BY 1, 2", + "uhd": "SELECT us.name, ho.name, n, b, x, c, first, last FROM uhd " + "JOIN users us ON us.id = u JOIN hosts ho ON ho.id = h ORDER BY 1, 2", + } + return {k: db.execute(v).fetchall() for k, v in q.items()} + + +def _traffic(seed: int, count: int) -> str: + """Lines as squid writes them: CONNECTs with their side lines next to them (either order), + refused CONNECTs, SNI categories behind allowed CONNECTs, blocked side lines alone.""" + rnd = random.Random(seed) + out = [] + ts = T0 + for i in range(count): + ts += rnd.choice((0, 0, 1, 2)) + user = f"s{rnd.randrange(4)}" + host = f"h{rnd.randrange(6)}.example" + kind = rnd.randrange(5) + pair = [] + if kind == 0: + pair = [line(ts, user, host, 200, "NONE_NONE", 0), line(ts, user, host)] + elif kind == 1: + pair = [ + line(ts, user, host, 200, "TCP_DENIED", 0), + line(ts + 1, user, host, 403, "NONE_NONE", 30), + ] + elif kind == 2: + pair = [line(ts, user, host, 200, "NONE_NONE", 0, cat="porn"), line(ts + 1, user, host)] + elif kind == 3: + pair = [line(ts, user, host, 403, "NONE_NONE", 10, cat="gambling")] + else: + pair = [line(ts, user, host, 200, "TCP_MISS", 500 + i)] + if rnd.random() < 0.5: + pair.reverse() + out.extend(pair) + return "".join(out) + + +@pytest.mark.parametrize("chunk", [1, 3, 7, 50]) +def test_chunks_give_what_the_whole_file_gives( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, chunk: int +) -> None: + """Side lines and their CONNECT lines across chunk boundaries pair as in one piece.""" + text = _traffic(7, 400) + whole = Env(tmp_path / "whole") + whole.put(text) + monkeypatch.setattr(activity, "CHUNK_LINES", 10**9) + c1 = whole.collect() + streamed = Env(tmp_path / "streamed") + streamed.put(text) + monkeypatch.setattr(activity, "CHUNK_LINES", chunk) + c2 = streamed.collect() + a, b = _dump(streamed), _dump(whole) + # every count the same; with several categories for one user and domain in one minute (or + # one day), which of them is stored depends on the order of the lines, also across files: + # it must be one of them + assert [r[:6] for r in a["act"]] == [r[:6] for r in b["act"]] + assert a["uh"] == b["uh"] + assert [r[:5] + r[6:] for r in a["uhd"]] == [r[:5] + r[6:] for r in b["uhd"]] + cats: dict[tuple[str, int, str], set[Any]] = {} + for raw in text.splitlines(): + ts, user, host, *_r, cat = raw.split() + cats.setdefault((user, int(ts) // 60, host), {None}).add(None if cat == "-" else cat) + assert all(r[6] in cats[(r[0], r[1], r[2])] for r in a["act"]) + per_day = {(u, h): c for (u, _m, h), cs in cats.items() for c in cs} + assert all(r[5] is None or (r[0], r[1]) in per_day for r in a["uhd"]) + assert (c2.lines, c2.used, c2.side, c2.broken) == (c1.lines, c1.used, c1.side, c1.broken) + # and both equal the reference: aggregate() over all lines at once + ref = activity.aggregate( + [ln.encode() + b"\n" for ln in text.splitlines()], + activity.DayMapper(ZONE), + activity.Counters(), + None, + T0 + 3600, + ) + rows = sum(r[0] for day in ref.values() for r in day.values()) + assert rows == whole.total() + + +def test_a_run_cut_short_counts_nothing_twice(env: Env, monkeypatch: pytest.MonkeyPatch) -> None: + text = _traffic(3, 300) + env.put(text) + monkeypatch.setattr(activity, "CHUNK_LINES", 40) + real = activity.store_day + calls = {"n": 0} + + def dies_on_the_fifth(*a: Any, **k: Any) -> bool: + calls["n"] += 1 + if calls["n"] == 5: + raise MemoryError("killed") + return real(*a, **k) + + monkeypatch.setattr(activity, "store_day", dies_on_the_fifth) + env.collect() + monkeypatch.setattr(activity, "store_day", real) + assert list(env.spool.glob("act-*")), "the file stays for the next run" + env.collect() + assert not list(env.spool.glob("act-*")) + reference = Env(env.spool.parents[1] / "ref") + reference.put(text) + monkeypatch.setattr(activity, "CHUNK_LINES", 40) + reference.collect() + assert _dump(env) == _dump(reference) + + +def test_a_failing_file_stops_neither_files_nor_instances( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + data, spool = str(tmp_path / "activity"), str(tmp_path / "spool") + students = _inst(role="students", ad_group="students") + teachers = _inst(role="teachers", ad_group="teachers") + paths = activity.Paths(data, spool, ZONE) + bad = activity.ensure_spool(spool, students.name) / f"act-{T0:010d}-bad00000-000001.log" + bad.write_text(line(T0, "s1", "a.example")) + good = activity.ensure_spool(spool, students.name) / f"act-{T0 + 1:010d}-ok000000-000002.log" + good.write_text(line(T0, "s2", "b.example")) + other = activity.ensure_spool(spool, teachers.name) / f"act-{T0:010d}-t0000000-000001.log" + other.write_text(line(T0, "t1", "c.example")) + real = activity._FileCollector.run + + def poisoned(self: Any, fh: Any) -> None: + if self.source == bad.name: + raise RuntimeError("poisoned") + real(self, fh) + + monkeypatch.setattr(activity._FileCollector, "run", poisoned) + caplog.set_level("INFO") + for run in range(1, activity.MAX_ATTEMPTS + 1): + res = activity.collect_all([students, teachers], paths, now=T0 + 3600) + assert res[teachers.name].used == (1 if run == 1 else 0) + assert bad.exists() and not good.exists() + attempts = json.loads((Path(data) / students.name / activity.ATTEMPTS_FILE).read_text()) + assert attempts == {bad.name: activity.MAX_ATTEMPTS} + activity.collect_all([students, teachers], paths, now=T0 + 3600) + assert not bad.exists() + assert activity.quarantined(data, students.name) == [bad.name] + assert activity.usage(data, spool, students.name)["quarantined"] == 1 + assert "moved to" in caplog.text and bad.name in caplog.text + assert not (Path(data) / students.name / activity.ATTEMPTS_FILE).exists() + # switching off with deletion removes the quarantine too (personal data) + activity.delete_data(data, spool, students.name) + assert activity.quarantined(data, students.name) == [] + + +def test_a_run_killed_by_a_file_counts_as_an_attempt(env: Env) -> None: + """A file that kills the process (out of memory) is counted before it is read.""" + path = env.put(line(T0, "s1", "a.example")) + target = Path(env.data) / env.inst.name + target.mkdir(parents=True) + (target / activity.ATTEMPTS_FILE).write_text(json.dumps({path.name: activity.MAX_ATTEMPTS})) + env.collect() + assert activity.quarantined(env.data, env.inst.name) == [path.name] + + +def _big_file(path: Path, mib: int) -> int: + """About ``mib`` MiB of lines of 2000 students on 3000 domains over 6 hours.""" + rnd = random.Random(1) + lines = 0 + with open(path, "w") as fh: + size = 0 + while size < mib * 1024 * 1024: + chunk = [] + for _ in range(10_000): + ts = T0 + rnd.randrange(6 * 3600) + chunk.append( + f"{ts} s{rnd.randrange(2000)}@EX.LAN host{rnd.randrange(3000)}.lasttest.example" + f" 200 TCP_TUNNEL {rnd.randrange(100000)} -\n" + ) + text = "".join(chunk) + fh.write(text) + size += len(text) + lines += len(chunk) + return lines + + +RUNNER = """ +import resource, sys, time +from zoneinfo import ZoneInfo +from lmnsquid import activity +from test_activity import _inst +inst = _inst() +c = activity.collect_instance(inst, sys.argv[1], sys.argv[2], ZoneInfo("Europe/Berlin"), now=float(sys.argv[3])) +print(c.lines, c.used, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024) +""" + + +def test_memory_does_not_grow_with_the_file(tmp_path: Path) -> None: + """A 24 MiB file (the collector before streaming: 409 MiB, over the unit's 256 MB) in a + process of its own: peak RSS at most half the limit.""" + env = Env(tmp_path) + expected = _big_file(env.spool / f"act-{T0:010d}-big00000-000001.log", 24) + out = subprocess.run( + [sys.executable, "-c", RUNNER, env.data, env.spool_root, str(T0 + 7 * 3600)], + capture_output=True, + text=True, + cwd=Path(__file__).parent, + env={"PYTHONPATH": f"{Path(__file__).parents[1]}:{Path(__file__).parent}"}, + timeout=600, + check=True, + ) + lines, used, peak_mib = (int(v) for v in out.stdout.split()) + assert lines == used == expected + # alone 64 MiB, inside the whole suite about 100 MiB (cause not found); half the unit's + # limit separates both from the collector before streaming (409 MiB for this file) + assert peak_mib < 128, f"peak RSS {peak_mib} MiB" + total = sum( + sqlite3.connect(p).execute("SELECT sum(n) FROM act").fetchone()[0] + for p in (Path(env.data) / env.inst.name).glob("*.sqlite") + ) + assert total == expected + _ = resource # the runner measures in its own process diff --git a/scripts/tests/activity_memory.sh b/scripts/tests/activity_memory.sh new file mode 100755 index 0000000..c9836c4 --- /dev/null +++ b/scripts/tests/activity_memory.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The activity collector under the memory limit of its unit (cold check 2026-11-25, M1): one spool +# file of ${1:-200} MiB is collected by systemd-run with MemoryMax and no swap, exactly the +# limit of linuxmuster-squid-activity.service; it must finish (no OOM kill) and count every line. +# Prints the peak RSS and systemd's memory peak. Needs a systemd user manager with the memory +# controller (systemd-run --user). Exit code: 0 ok, 1 failed, 3 cannot run here. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +MIB="${1:-200}" +PY="${LMNSQUID_PYTHON:-$ROOT/.venv/bin/python}" +LIMIT=$(sed -n 's/^MemoryMax=//p' "$ROOT/packaging/systemd/linuxmuster-squid-activity.service") +systemd-run --user --quiet --wait --pipe -p MemoryMax=16M true 2>/dev/null \ + || { echo "SKIP: no systemd user manager with the memory controller"; exit 3; } +# on disk, like /var/lib on the proxy host: files on a tmpfs (/tmp here) are charged to the +# unit's memory and cannot be reclaimed without swap +WORK="$(mktemp -d /var/tmp/lmnsquid-activity-memory.XXXXXX)" +trap 'rm -rf "$WORK"' EXIT +cd "$ROOT/controlplane/tests" +expected=$(PYTHONPATH="$ROOT/controlplane:$PWD" "$PY" -c " +import sys +from pathlib import Path +from test_activity import Env, T0 +from test_activity_stream import _big_file +e = Env(Path('$WORK')) +print(_big_file(e.spool / f'act-{T0:010d}-big00000-000001.log', $MIB), e.data, e.spool_root, T0 + 7 * 3600)") +read -r lines data spool now <<<"$expected" +echo "spool file: $MIB MiB, $lines lines; unit limit MemoryMax=$LIMIT, no swap" +start=$(date +%s) +out=$(systemd-run --user --wait --pipe -p MemoryMax="$LIMIT" -p MemorySwapMax=0 \ + -E PYTHONPATH="$ROOT/controlplane:$PWD" --working-directory="$PWD" \ + "$PY" -c "$(PYTHONPATH="$ROOT/controlplane:$PWD" "$PY" -c 'from test_activity_stream import RUNNER; print(RUNNER)')" \ + "$data" "$spool" "$now" 2>&1) && rc=0 || rc=$? +echo "$out" | sed 's/^/ /' +read -r got used peak < <(echo "$out" | grep -E '^[0-9]+ [0-9]+ [0-9]+$' | tail -1) || true +echo "collect: $(( $(date +%s) - start )) s" +if [ "$rc" = 0 ] && [ "${got:-}" = "$lines" ] && [ "${used:-}" = "$lines" ]; then + echo " [PASS] $MIB MiB collected under MemoryMax=$LIMIT: $lines lines, peak RSS ${peak} MiB" + exit 0 +fi +echo " [FAIL] collector under MemoryMax=$LIMIT: rc=$rc, lines ${got:-?}/${used:-?} of $lines" +exit 1 From 3295de7629372a49db2196de434aebe7aa555208 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 20:13:49 +0100 Subject: [PATCH 35/45] fix(webui): refuse state-changing requests without Origin and Referer Browsers send at least one of them for the plugin's POST, PUT, PATCH and DELETE requests; a request with neither was accepted (cold check m4). --- webui/lmn_squid/views.py | 8 ++++++-- webui/tests/test_csrf.py | 4 +++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/webui/lmn_squid/views.py b/webui/lmn_squid/views.py index e88e715..f462f85 100644 --- a/webui/lmn_squid/views.py +++ b/webui/lmn_squid/views.py @@ -119,8 +119,9 @@ def check_same_origin(http_context: Any) -> None: without a CORS preflight, which aj does not answer. 2. If the browser sends ``Origin`` (every current browser does for POST/PUT/PATCH/DELETE), it must be this WebUI (scheme, host and port of the request's ``Host``) or one of aj's - ``trusted_domains``; without ``Origin`` a ``Referer``, if present, must match the same - way. ``Origin: null`` (sandboxed frame, privacy redirect) is refused. + ``trusted_domains``; without ``Origin`` the ``Referer`` must match the same way. + ``Origin: null`` (sandboxed frame, privacy redirect) is refused, and so is a request + with neither header (cold check m4: the WebUI's own pages always send one). """ env = getattr(http_context, "env", None) or {} ctype = str(env.get("CONTENT_TYPE") or "").split(";", 1)[0].strip().lower() @@ -146,6 +147,9 @@ def check_same_origin(http_context: Any) -> None: {"error": "origin", "message": f"request from another site refused ({header[5:]})"}, ) return + raise EndpointReturn( + 403, {"error": "origin", "message": "request without Origin and Referer refused"} + ) def global_admin_only(fx: Callable[..., Any]) -> Callable[..., Any]: diff --git a/webui/tests/test_csrf.py b/webui/tests/test_csrf.py index 3af31af..f0fb1df 100644 --- a/webui/tests/test_csrf.py +++ b/webui/tests/test_csrf.py @@ -60,6 +60,9 @@ def test_every_state_changing_endpoint_is_guarded() -> None: ({"HTTP_ORIGIN": "https://server.lmn.lan:8443"}, 403, "origin"), # other port ({"HTTP_ORIGIN": "null"}, 403, "origin"), ({"HTTP_ORIGIN": None, "HTTP_REFERER": "https://evil.example/page"}, 403, "origin"), + # neither Origin nor Referer (cold check m4): the WebUI's own pages always send one + ({"HTTP_ORIGIN": None}, 403, "origin"), + ({"HTTP_ORIGIN": "", "HTTP_REFERER": ""}, 403, "origin"), ], ) def test_cross_site_requests_are_refused_before_anything_happens( @@ -87,7 +90,6 @@ def test_cross_site_requests_are_refused_before_anything_happens( {}, # what the plugin's page sends {"HTTP_ORIGIN": "https://server.lmn.lan:443"}, {"HTTP_ORIGIN": "https://SERVER.lmn.lan", "HTTP_HOST": "server.lmn.lan:443"}, - {"HTTP_ORIGIN": None}, # no Origin, no Referer: nothing to compare {"HTTP_ORIGIN": None, "HTTP_REFERER": "https://server.lmn.lan/view/lmn/squid"}, {"CONTENT_TYPE": "Application/JSON"}, ], From 927fba3a3dbd027ee169901494b156058348a975 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 20:13:49 +0100 Subject: [PATCH 36/45] fix(webui): no Ajenti toast for a person outside one's classes Ajenti answers every 403 with an English 'Security error' toast on top of the page's German message (cold check m1). The WebUI now answers a scope refusal of the bridge with 404, like a person that does not exist for the caller; aj's own permission refusals stay 403. The browser test fails on such a toast. --- scripts/tests/webui_ajenti_it/browser.py | 25 +++++++++++++--- scripts/tests/webui_ajenti_it/it.py | 7 +++-- webui/lmn_squid/activity_views.py | 5 ++++ webui/tests/test_activity_views.py | 36 +++++++++++++++--------- 4 files changed, 54 insertions(+), 19 deletions(-) diff --git a/scripts/tests/webui_ajenti_it/browser.py b/scripts/tests/webui_ajenti_it/browser.py index 64d72db..fb8760c 100644 --- a/scripts/tests/webui_ajenti_it/browser.py +++ b/scripts/tests/webui_ajenti_it/browser.py @@ -68,7 +68,16 @@ def _response(self, resp): f"HTTP {resp.status} {resp.request.method} {resp.url[len(BASE) :]}" ) - def step(self, label, url=None, action=None, allowed=(), wait=900, expect=None): + def step( + self, + label, + url=None, + action=None, + allowed=(), + wait=900, + expect=None, + core_refusal=False, + ): self.errors.clear() self.allowed = set(allowed) try: @@ -89,6 +98,12 @@ def step(self, label, url=None, action=None, allowed=(), wait=900, expect=None): self.errors.append(f"page does not answer: {str(exc)[:200]}") if expect and expect.lower() not in body: self.errors.append(f"expected text missing: {expect!r}") + # a 403 of aj's own permission check (a page the role may not use, opened by its URL) + # shows the core's "Security error" toast: upstream, not the plugin's (cold check m2) + if not core_refusal and ( + "sicherheitsfehler" in body or "security error" in body + ): + self.errors.append("Ajenti's 'Security error' toast") if "likely a bug" in body: self.errors.append("Ajenti's 'Server error occured' dialog") if "bootstrap" in body and ( @@ -185,7 +200,7 @@ def management_admin(probe): def management_refused(probe): - probe.step("management page refused", MGMT, allowed=(403,)) + probe.step("management page refused", MGMT, allowed=(403,), core_refusal=True) def activity_views(probe, teacher=False, school=""): @@ -228,7 +243,7 @@ def activity_views(probe, teacher=False, school=""): probe.step( "internet use: student of another class refused", ACT + "?user=s6b1", - allowed=(403,), + allowed=(404,), ) else: probe.step("internet use: student s6b1", ACT + f"?{q}user=s6b1") @@ -249,7 +264,9 @@ def main(): ), "dsextra01": lambda p: ( management_refused(p), - p.step("internet use page refused", ACT, allowed=(403,)), + p.step( + "internet use page refused", ACT, allowed=(403,), core_refusal=True + ), ), } for user, plan in plans.items(): diff --git a/scripts/tests/webui_ajenti_it/it.py b/scripts/tests/webui_ajenti_it/it.py index cb26894..42c1917 100644 --- a/scripts/tests/webui_ajenti_it/it.py +++ b/scripts/tests/webui_ajenti_it/it.py @@ -200,7 +200,10 @@ def main(): status, data = request( gm, t, "POST", "/api/lmn/squid-activity/query/day", {"user": "s6b1", "day": day} ) - check(status == 403, f"teacher: another class's student: {status}") + check( + status == 404, + f"teacher: another class's student (404, no Ajenti toast): {status}", + ) status, data = request( gm, t, @@ -208,7 +211,7 @@ def main(): "/api/lmn/squid-activity/export", {"since": now - 3600, "until": now + 60}, ) - check(status == 403, f"teacher: no export: {status}") + check(status == 404, f"teacher: no export (404): {status}") # the teacher's worker cannot read the tokens (why the bridge exists) status, data = request(gm, t, "GET", "/api/lmn/squid/connections") check(status == 403, f"teacher: management refused: {status}") diff --git a/webui/lmn_squid/activity_views.py b/webui/lmn_squid/activity_views.py index c8121d8..ed50d09 100644 --- a/webui/lmn_squid/activity_views.py +++ b/webui/lmn_squid/activity_views.py @@ -92,6 +92,11 @@ def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: query = {str(k): str(v) for k, v in (http_context.query or {}).items()} identity = str(getattr(self.context, "identity", "") or "") status, data = self.call(identity, method, path.format(**kwargs), query, body, timeout) + if status == 403 and isinstance(data, dict) and data.get("error") == "scope": + # outside the caller's classes: 404, as for a person that does not exist for + # them; Ajenti answers every 403 with an English "Security error" toast on top + # of the page's own German message (cold check m1) + status = 404 if status >= 500 and status not in (502, 503, 504): # never a 500 to the page: Ajenti answers it with its English "server error" # dialog (lab B1); the page shows the bridge's German text instead diff --git a/webui/tests/test_activity_views.py b/webui/tests/test_activity_views.py index ca3ee9e..423fc6a 100644 --- a/webui/tests/test_activity_views.py +++ b/webui/tests/test_activity_views.py @@ -27,6 +27,9 @@ pytestmark = needs_openssl TOKEN = "cp-token-0123456789abcdef0123456789" +# A request outside the caller's classes and projects: 404, so Ajenti adds no "Security +# error" toast to the page's own message (cold check m1); refusals by aj's permission stay 403. +SCOPE_REFUSED = 404 PREFIX = "/api/lmn/squid-activity" @@ -256,21 +259,24 @@ def test_teacher_is_refused_outside_the_scope( {"group": {"kind": "class", "name": "students"}}, {"school": "one"}, ): - assert users_of(webui, now, **body)[0] == 403, body + assert users_of(webui, now, **body)[0] == SCOPE_REFUSED, body for user in ("s6b1", "dslehr03", "o5a1", "pgmadmin"): status, _ = webui.call( "POST", f"{PREFIX}/query/timeline", {"user": user, "since": now - 3600, "until": now + 60}, ) - assert status == 403, user + assert status == SCOPE_REFUSED, user status, _ = webui.call( "POST", f"{PREFIX}/query/domains", {"user": user, "since": now - 3600, "until": now + 60}, ) - assert status == 403, user - assert webui.call("POST", f"{PREFIX}/export", {"since": now - 60, "until": now})[0] == 403 + assert status == SCOPE_REFUSED, user + assert ( + webui.call("POST", f"{PREFIX}/export", {"since": now - 60, "until": now})[0] + == SCOPE_REFUSED + ) assert webui.call("GET", "/api/lmn/squid/proxy1/activity/audit")[0] == 403 assert webui.call("GET", "/api/lmn/squid/proxy1/activity")[0] == 403 status, _ = webui.call( @@ -279,7 +285,7 @@ def test_teacher_is_refused_outside_the_scope( {"enabled": False}, ) assert status == 403 - assert webui.call("GET", f"{PREFIX}/group/class/6b/members")[0] == 403 + assert webui.call("GET", f"{PREFIX}/group/class/6b/members")[0] == SCOPE_REFUSED assert len(cp["recorder"].seen) == asked, "nothing reached a proxy" @@ -319,7 +325,7 @@ def test_school_admin_sees_the_school_and_nothing_else( found = {u["user"] for u in data["users"]} assert "dslehr03" in found and "s6b1" in found and "pgmadmin" in found assert not found & {"o5a1", "onelehr", "global-admin"} - assert users_of(webui, now, school="one")[0] == 403 + assert users_of(webui, now, school="one")[0] == SCOPE_REFUSED status, data = webui.call( "POST", f"{PREFIX}/export", @@ -342,13 +348,13 @@ def test_students_and_other_roles_get_nothing( for user, role in (("s5a1", "student"), ("dsstaff01", "staff")): # also with the permission granted by hand login(webui, user, role, granted={activity_views.PERM_ACTIVITY}) - assert webui.call("GET", f"{PREFIX}/scope")[0] == 403 - assert users_of(webui, now)[0] == 403 + assert webui.call("GET", f"{PREFIX}/scope")[0] == SCOPE_REFUSED + assert users_of(webui, now)[0] == SCOPE_REFUSED assert ( webui.call( "POST", f"{PREFIX}/query/timeline", {"user": user, "since": now - 60, "until": now} )[0] - == 403 + == SCOPE_REFUSED ) # and without it, aj's authorize refuses first login(webui, user, role) @@ -362,13 +368,13 @@ def test_the_role_comes_from_the_ad_not_from_the_session( now = setup_proxy(webui, cp, seed=False) # a session that claims globaladministrator for a user the AD knows as a student login(webui, "s5a1", "globaladministrator") - assert users_of(webui, now)[0] == 403 + assert users_of(webui, now)[0] == SCOPE_REFUSED # a teacher removed from a class loses it at once (cache cleared like after its ttl) login(webui, "dslehr01", "teacher") ad.users["dslehr01"]["schoolclasses"] = [] ad.users["dslehr01"]["projects"] = [] activity_scope.CACHE.clear() - assert users_of(webui, now, group={"kind": "class", "name": "5a"})[0] == 403 + assert users_of(webui, now, group={"kind": "class", "name": "5a"})[0] == SCOPE_REFUSED def test_global_admin_all_schools_and_settings( @@ -569,7 +575,10 @@ def test_student_day_merged_and_revalidated( assert [r["domain"] for r in rows["rows"]] == ["bad.example"] # out of scope for user in ("s6b1", "dslehr03"): - assert webui.call("POST", f"{PREFIX}/query/day", {"user": user, "day": day})[0] == 403 + assert ( + webui.call("POST", f"{PREFIX}/query/day", {"user": user, "day": day})[0] + == SCOPE_REFUSED + ) def test_blocked_attempts_of_a_class(webui: WebUI, ad: FakeDirectory, cp: dict[str, Any]) -> None: @@ -635,7 +644,8 @@ def test_refusals_and_empty_scopes_are_audited( activity_scope.CACHE.clear() assert users_of(webui, now)[1]["users"] == [] assert ( - webui.call("POST", f"{PREFIX}/query/day", {"user": "s5a1", "day": "2026-11-25"})[0] == 403 + webui.call("POST", f"{PREFIX}/query/day", {"user": "s5a1", "day": "2026-11-25"})[0] + == SCOPE_REFUSED ) assert any("dslehr02" in ln and "empty scope" in ln for ln in lines), lines assert any("dslehr02" in ln and "refused" in ln and "query/day" in ln for ln in lines), lines From 8e3f3263f29591d803a907cac1cf78e1b80be562 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 20:13:49 +0100 Subject: [PATCH 37/45] fix(webui): quarantine hint, German access log, filter overview width The management page shows spool files the collector quarantined (count per instance, German hint where they are and what to do). Whose data an access log line concerns is stored machine-readable and now shown in German (cold check m3). The catalog column of 'Filter per school' wraps instead of being cut off at 1366 px (m5). --- webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 27 +++++++++++++++++++ .../js/controllers/index.controller.es | 19 +++++++++++++ webui/lmn_squid/resources/partial/index.html | 17 +++++++++--- webui/tests/js/controller_check.js | 11 ++++++++ 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index 96ee8dc..5c8cad1 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -1687,3 +1687,30 @@ msgstr "Interner Fehler des Dienstes der Internetnutzung; Einzelheiten im Journa msgid "The user directory (AD) could not be read; details in the journal (journalctl -u linuxmuster-squid-webui-activity)." msgstr "Das Benutzerverzeichnis (AD) konnte nicht gelesen werden; Einzelheiten im Journal (journalctl -u linuxmuster-squid-webui-activity)." + +msgid "spool file(s) in quarantine" +msgstr "Spool-Datei(en) in Quarantäne" + +msgid "The collector gave up on these files of the proxy (journalctl -u linuxmuster-squid-activity on the proxy host); their requests are missing in the view." +msgstr "Der Sammler hat diese Dateien des Proxys aufgegeben (journalctl -u linuxmuster-squid-activity auf dem Proxy-Host); ihre Anfragen fehlen in der Ansicht." + +msgid "They are in the quarantine folder of the instance's activity data; move them back into the spool to try again, or delete them." +msgstr "Sie liegen im Ordner quarantine der Aktivitätsdaten der Instanz; zum erneuten Versuch zurück in den Spool verschieben oder löschen." + +msgid "all visible people" +msgstr "alle sichtbaren Personen" + +msgid "school" +msgstr "Schule" + +msgid "class" +msgstr "Klasse" + +msgid "project" +msgstr "Projekt" + +msgid "person" +msgstr "Person" + +msgid "domain" +msgstr "Domain" diff --git a/webui/lmn_squid/resources/js/controllers/index.controller.es b/webui/lmn_squid/resources/js/controllers/index.controller.es index 201c203..cc76475 100644 --- a/webui/lmn_squid/resources/js/controllers/index.controller.es +++ b/webui/lmn_squid/resources/js/controllers/index.controller.es @@ -852,6 +852,25 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco {id: 'settings', label: gettext('Settings changed')}, {id: 'delete_data', label: gettext('Data deleted')} ]; + // "Whose data" of an audit line, stored machine-readable by the bridge ("class 5a", + // "user s5a1 domain x.example", ...), shown in German (cold check m3) + $scope.auditScopeText = function (text) { + var t = String(text || ''); + var m; + if ((m = /^all visible users \((.*)\)$/.exec(t))) { + return gettext('all visible people') + ' (' + m[1] + ')'; + } + if (t === 'all schools') { + return gettext('all schools'); + } + if ((m = /^(school|class|project) (.+)$/.exec(t))) { + return {school: gettext('school'), class: gettext('class'), project: gettext('project')}[m[1]] + ' ' + m[2]; + } + if ((m = /^user (\S+)(?: domain (\S+))?(?: (\d{4}-\d{2}-\d{2}))?$/.exec(t))) { + return gettext('person') + ' ' + m[1] + (m[2] ? ', ' + gettext('domain') + ' ' + m[2] : '') + (m[3] ? ', ' + m[3] : ''); + } + return t; + }; $scope.auditActionLabel = function (id) { var found = $scope.auditActions.filter(function (k) { return k.id === id; })[0]; return found ? found.label : id; diff --git a/webui/lmn_squid/resources/partial/index.html b/webui/lmn_squid/resources/partial/index.html index 27f0149..822699b 100644 --- a/webui/lmn_squid/resources/partial/index.html +++ b/webui/lmn_squid/resources/partial/index.html @@ -183,7 +183,9 @@ - {{a.usage.days | lmnNum}} days · {{a.usage.bytes / 1048576 | lmnNum}} MB + {{a.usage.days | lmnNum}} days · {{a.usage.bytes / 1048576 | lmnNum}} MB +
{{a.usage.quarantined | lmnNum}} spool file(s) in quarantine
+ {{a.ack_by}}, {{a.ack_at | lmnTime:servers[conn.name].activity.timezone:'datetime'}} @@ -225,7 +227,7 @@ {{e.actor}} {{e.role}} {{auditActionLabel(e.action) | translate}} {{e.domain || e.user || e.instance}} live - {{e.scope}} ({{e.users_count | lmnNum}}) + {{auditScopeText(e.scope)}} ({{e.users_count | lmnNum}}) {{e.since | lmnTime:audit.tz:'short'}} – {{e.until | lmnTime:audit.tz:'short'}} @@ -653,6 +655,11 @@

Delete instance {{deleteDialog.inst.name}} ({{deleteD Confirmed by {{detail.activity.ack_by}}, {{detail.activity.ack_at | lmnTime:detail.activityTz:'datetime'}}

Stored data: {{detail.activity.usage.days | lmnNum}} days · {{detail.activity.usage.bytes / 1048576 | lmnNum}} MB

+
+ {{detail.activity.usage.quarantined | lmnNum}} spool file(s) in quarantine: + The collector gave up on these files of the proxy (journalctl -u linuxmuster-squid-activity on the proxy host); their requests are missing in the view. + They are in the quarantine folder of the instance's activity data; move them back into the spool to try again, or delete them. +
@@ -910,6 +917,9 @@

Apply the filter to other instances

Filter per school and group

diff --git a/webui/tests/js/controller_check.js b/webui/tests/js/controller_check.js index 501066c..8a4089b 100644 --- a/webui/tests/js/controller_check.js +++ b/webui/tests/js/controller_check.js @@ -503,6 +503,17 @@ hd.scope.detail.filter = {dirty: true}; hd.scope.closeDetail(); assert.strictEqual(hd.scope.detail, null); +// --- "whose data" of the audit log: stored machine-readable, shown through gettext (cold check m3) +{ + const a = harness(ROUTES, {}).scope.auditScopeText; + assert.strictEqual(a('all visible users (default-school)'), 'all visible people (default-school)'); + assert.strictEqual(a('user s5a1 domain x.example'), 'person s5a1, domain x.example'); + assert.strictEqual(a('class extraklasse'), 'class extraklasse'); + assert.strictEqual(a('project p1'), 'project p1'); + assert.strictEqual(a('all schools'), 'all schools'); + assert.strictEqual(a(undefined), ''); +} + // --- every helper a template evaluates answers on the started page (lab B2) const helpers = require('./template_helpers.js'); const fresh = harness(ROUTES, {}); From 981ae14105b3619d72cbade26f5451b48cb64b12 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 20:13:49 +0100 Subject: [PATCH 38/45] docs: collector streaming and quarantine, cold check findings (ADR-023 addendum 5) --- debian/changelog | 8 ++++++++ docs/decisions.md | 29 +++++++++++++++++++++++++++++ docs/operations.md | 9 +++++++++ docs/test-strategy.md | 10 ++++++++++ docs/threat-model.md | 2 +- 5 files changed, 57 insertions(+), 1 deletion(-) diff --git a/debian/changelog b/debian/changelog index 2065715..5e66b1e 100644 --- a/debian/changelog +++ b/debian/changelog @@ -212,6 +212,14 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium (linuxmusterTools changes the mode of the files it reads under /etc, which its sandbox refused). An export too large for a proxy reads "Export zu groß" instead of "a proxy cannot deliver its part". + * Activity collector: reads a spool file in chunks, so its memory no + longer grows with the file (a big file was killed by the unit's + memory limit and stopped the collection of every instance). A file + that fails three times is moved to the instance's quarantine folder, + named in the journal and shown in the WebUI; the others go on. + * WebUI plugin: a person outside one's classes no longer adds an English + "Security error" toast; the access log names whose data in German; + a request without Origin and Referer is refused. -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium diff --git a/docs/decisions.md b/docs/decisions.md index 1f85724..e8c3824 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -861,6 +861,35 @@ the installed unit against an OpenLDAP stand-in of the AD (LDAPS, sophomorix att school with custom_fields.yml): linuxmusterTools opens config.yml with its own loader, binds and reads the scope and a class. Red against 7045c2a with the lab's EROFS, green at HEAD. +**Addendum 5 (2026-11-25, cold check of 8a9e458, `kalte-pruefung-activity-2026-11-25.md`):** +- **M1, the collector's memory:** it read a spool file whole and kept every parsed line: 209 MB + (cold check) to 285 MiB (here) for one 16-MiB file under `MemoryMax=256M`; a bigger file + killed every run and with it the collection of the other instances. It now streams: a file is + read line by line and stored in chunks of 20 000 lines, each chunk per day in one transaction + with the ledger name `#` (chunk boundaries depend only on the file's content, so + a run killed mid-file continues where it stopped and counts nothing twice; a ledger entry of a + whole file from the earlier collector is honoured). The pairing of HTTPS side lines with their + CONNECT line works across chunks: the CONNECT lines of the last seconds stay in a window (lines + up to 30 s out of order), a side line waits until no partner can follow, and marks a partner + stored with an earlier chunk blocked within the current chunk's transaction. Every count is the + same as reading the file whole; where a user had several categories on one domain in one minute + (or day), which of them is stored can depend on the chunking, as it already depended on the + file order. Peak RSS: 63 MiB for 16 MiB, 64 MiB for 24 MiB, 68 MiB for 100 MiB; a 200-MiB + file is collected under the unit's own limit (`scripts/tests/activity_memory.sh`). + Every file on its own: an attempt is counted before the file is read (so a run the file kills + counts too); a failing file does not stop the other files or instances; after 3 attempts it + goes to `//quarantine/` with an error line in the journal, and the WebUI shows + "N Spool-Datei(en) in Quarantäne" on the instance (removing the data removes the quarantine). + The receiver already rolls a file at 16 MiB and stops writing at 1 GiB waiting; no change in + the image. +- **m1:** a request outside the caller's classes is answered 404 by the WebUI (the bridge keeps + 403 `scope`): Ajenti adds a "Sicherheitsfehler" toast with English JSON to every 403; the page + shows its own German message as before. aj's own permission refusals stay 403. +- **m3:** "whose data" of the access log is stored machine-readable (`class 5a`, `user s5a1`, + `all visible users (default-school)`) and shown in German. +- **m4:** a state-changing request (every query of the view is a POST) without `Origin` and + without `Referer` is refused; browsers send at least one of them for these requests. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/operations.md b/docs/operations.md index e6444b3..6d747a0 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -762,6 +762,8 @@ Xeon E5-2609 v3 1.9 GHz, one core, SSD, 2026-11-25: |---|---| | collector, one 30-second file (≈ 2 600 lines, what the timer sees at peak) | 0.05 s (+ ≈ 0.3 s Python start) | | collector, a whole day as a backlog (960 files, 2.5 million lines) | 66 s, RSS 44 MiB (69 s since HTTPS side lines are paired, 2026-11-25) | +| collector, one spool file of 16 / 24 / 100 MiB (240 000 / 350 000 / 1.46 million lines) | peak RSS 63 / 64 / 68 MiB (streamed in chunks of 20 000 lines; before: 285 / 409 MiB) | +| collector, one spool file of 200 MiB (2.9 million lines) under the unit's `MemoryMax=256M`, no swap | collected, no OOM kill (`scripts/tests/activity_memory.sh`) | | day file | 28.7 MiB (957 000 minute rows, 91 500 user-domain rows, 17 600 domains) | | overview of a class (30 students), today / 90 minutes / 7 days | 0.007 / 0.013 / 0.055 s | | one student: 7 days per hour (heat map) / one hour per minute / one day per minute | 0.006 / 0.001 / 0.005 s | @@ -785,6 +787,13 @@ school days a year about 5.5 GiB per 1000 students at 365 days' retention (10.5 day of the year were a school day), 0.2 GiB at the default 7 days. Scale linearly with users and requests; plan the space of `/var/lib/linuxmuster-squid` accordingly. +**Quarantine:** a spool file the collector could not take three times (an error, or a run that +ended with it) is moved to `/var/lib/linuxmuster-squid/activity//quarantine/` and named +in the journal (`journalctl -u linuxmuster-squid-activity`); the other files and instances go on. +The WebUI shows "Spool-Datei(en) in Quarantäne" on the instance. Its requests are missing in the +view: move the file back into the instance's spool to try again (after fixing the cause), or +delete it. Removing the instance's data (switching off with deletion) removes the quarantine. + ### The bridge of the view on the school server The page *Internetnutzung* reaches the proxies through a local service of the plugin package diff --git a/docs/test-strategy.md b/docs/test-strategy.md index 8f57f47..eaf7a8b 100644 --- a/docs/test-strategy.md +++ b/docs/test-strategy.md @@ -192,6 +192,16 @@ reinstall keeps it working; remove, purge and a downgrade to a build without the nothing listening, no dangling symlink and no enable state. Against e77bf1e: red (B1 and the leftovers of the lab's rollback). +## Collector memory (systemd user manager) + +`scripts/tests/activity_memory.sh [MiB]` (default 200): one spool file of that size (2000 users, +3000 domains, 6 hours) is collected by `systemd-run --user` with the `MemoryMax` of +`linuxmuster-squid-activity.service` and no swap, in a directory on disk (a tmpfs would charge the +day files to the unit's memory); it must finish and count every line. The fast tier has +`controlplane/tests/test_activity_stream.py`: chunks give what the whole file gives (side lines +across chunk boundaries), a run cut short counts nothing twice, a failing file stops neither the +other files nor the other instance and goes to quarantine, peak RSS of a 24-MiB file under 96 MiB. + ## Negative/security catalog (grows per phase; part of the DoD) - **P1:** no ticket→407; student→403; SPN mismatch/FQDN-as-IP → no 200. diff --git a/docs/threat-model.md b/docs/threat-model.md index 827c7c5..70f356e 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -46,7 +46,7 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T23 | **Fail-open vs. fail-closed of the filter** (ADR-022): during a missing catalog youth protection would silently stop | SafeSearch switched on for an engine without any known address blocks that engine (`safesearch_unresolved`) instead of leaving it unfiltered; an image without the filter is reported (`image_without_filter`), not shown as filtering; fail-closed for the categories marked `fail_closed` (youth protection): every request but exceptions and the protected list refused while the catalog is unusable, shown in `status`/WebUI; other categories fail open (ads, telemetry, distraction: availability first). The noauth path is filtered too (T16 amended). Bypass of the proxy (direct 443/853/QUIC) defeats every filter and SafeSearch: firewall's job (operations.md) | test_filterdecision.py, test_filter_helper.py, E2E (fail-closed without catalog) | | T24 | **Activity log = profile of browsing per person** (ADR-023): data of students and staff, a teacher looking at students of other classes or at colleagues, an exported CSV passed on | off by default per instance; switching on needs who confirmed the privacy notice (stored with the time in the instance's git log); minute and domain only, no URL, no client address; retention 1–365 days as whole day files (deleted before a query could read them); scope computed on the school server from the AD on every request, only the allowed users list goes to the proxy, which filters every SQL statement on it; teachers only students of their own classes/projects and school, never teachers; export only for administrators; every read and every settings change audited (person, scope, users, range) before data is read, 503 if the audit log cannot be written; the audit log only for global administrators, own retention | `test_activity.py`, `test_activity_api.py`, webui `test_activity_views.py`, E2E spool check | | T25 | **The users list comes from the WebUI** (ADR-023): the proxy cannot check who asks; a stolen token reads everything | the token is the global administrator's credential already (T5, T18); the list is computed on the server, never taken from the browser; the audit names the person the WebUI reports and, for the CLI, `cli:`; the WebUI logs every request of the view, refused ones and those without a proxy request included, to its system log (`journalctl -t lmn-squid-activity`) | `test_activity_views.py` (out-of-scope requests never reach a proxy) | -| T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 1733 (squid's proxy user can create, not list; no set-group-id, which `RestrictSUIDSGID=yes` refuses), files 0644 unreachable for other host users behind the 0750 parent; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured) | `test_activity.py` (receiver), local squid 6.14 test | +| T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 1733 (squid's proxy user can create, not list; no set-group-id, which `RestrictSUIDSGID=yes` refuses), files 0644 unreachable for other host users behind the 0750 parent; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured); the collector streams a file in chunks (memory independent of its size) and quarantines a file that fails three times, so one file cannot stop the collection of the other instances (cold check M1) | `test_activity.py` (receiver), local squid 6.14 test | | T27 | **The activity bridge** (ADR-023 addendum 2): a root service on a socket every local process can open; a teacher's worker (or any local user) claims to be someone else, asks for students outside its classes, floods the bridge, or sends a huge or slow request; a bug in the bridge leaks the tokens | the identity of a non-root caller comes from the kernel (`SO_PEERCRED` → `getpwuid`), a claimed identity must match it; only root names a person; the scope is computed in the bridge from the AD, a users list of the caller is ignored; tokens never leave the bridge (answers carry activity data and typed errors only); request ≤ 256 KiB, 10 s, 32 at once, 60 per UID in 10 s; no shell, no path from the caller; systemd hardening (`ProtectSystem=true`: /usr and /boot read-only, /etc writable because linuxmusterTools chmods the files it reads as root, ADR-023 addendum 4; `NoNewPrivileges`, `ProtectHome`, private /tmp, kernel protections, address families AF_UNIX/AF_INET/AF_INET6/AF_NETLINK — netlink for samba's interface list); one log line per request with UID and identity, refusals audited (tag `lmn-squid-activity`). Residual: upstream gives teachers `sudo ALL` (`webui-sudoers`), so a teacher with a shell on the server is root anyway; the bridge does not make that worse | `webui/tests/test_bridge.py`; `scripts/tests/webui_ajenti_it.sh` (bridge asked as teacher, student, `nobody` and root UIDs) | ## Non-goals (deliberate) From 1b0d61e2b0c87140f65554405b9ce634b41f47f7 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 22:02:07 +0100 Subject: [PATCH 39/45] fix(controlplane): update-all never moves an instance onto an older or poorer image Every package upgrade runs update-all onto DEFAULT_IMAGE. While that pin still names an older image (the log rotation build, without the filter and activity labels), the upgrade moved the instances onto it and turned the category filter and the activity log off without a word (cold recheck N1). update-all now inspects the target image first and keeps an instance on its image when the target is older, has an older capability label, or lacks the category filter (categories or SafeSearch in use) or the activity log (on) the instance uses. The result says why, the audit log warns, lmnsquid update-all exits 1 and the postinst shows the reason in the apt output. An explicit 'lmnsquid update NAME IMAGE' still applies. RELEASE.md: the pin comes before the tag. --- RELEASE.md | 10 +++ controlplane/lmnsquid/cli.py | 13 ++- controlplane/lmnsquid/docker_service.py | 18 +++++ controlplane/lmnsquid/main.py | 11 ++- controlplane/lmnsquid/updater.py | 73 ++++++++++++++++- controlplane/tests/conftest.py | 6 ++ controlplane/tests/test_cli.py | 19 +++++ controlplane/tests/test_docker_integration.py | 56 +++++++++++++ controlplane/tests/test_updater.py | 79 +++++++++++++++++++ debian/linuxmuster-squid.postinst | 2 +- 10 files changed, 283 insertions(+), 4 deletions(-) diff --git a/RELEASE.md b/RELEASE.md index feaa11d..487e91c 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -71,6 +71,16 @@ changed template that is not pinned never reaches an installed system. Order: me digest") → a PR sets `DEFAULT_IMAGE` to that `@sha256:` digest (by hand while Renovate is disabled) → CI green → set the changelog version and tag. The package upgrade then moves every instance onto the new image (`update-all` in the postinst, health-gated with rollback). +**The pin comes before the tag, never after.** `update-all` never moves an instance onto an +older image, nor onto one without the category filter (filter in use) or the activity log +(log on): it keeps the instance on its image and says so (`lmnsquid update-all` exits 1, the +postinst shows "kept on its image" in the apt output; cold check 2026-11-25, N1). A build of a +branch whose image changed but whose `DEFAULT_IMAGE` still points at an older image therefore +leaves the instances where they are instead of silently turning the filter or the activity +log off; the instances reach the new image only through the pin (or `lmnsquid update NAME +IMAGE` by hand). The category filter (`feat/filter-categories`) and the activity log +(`feat/activity-log`) both need that pin before their release: their `DEFAULT_IMAGE` is still +the log rotation build (`…@sha256:acf552…`) without either label. The release with the **category filter (ADR-022)** is one too: the helper, the template and the block page live in the image, and the containers get the catalog mount; the `update-all` of the package upgrade replaces every container once (health-gated) when it moves them onto the diff --git a/controlplane/lmnsquid/cli.py b/controlplane/lmnsquid/cli.py index 8c44c91..3fcc7b7 100644 --- a/controlplane/lmnsquid/cli.py +++ b/controlplane/lmnsquid/cli.py @@ -774,7 +774,18 @@ def update_all() -> None: resp = c.post("/v1/update-all") _emit(resp) results = resp.json().get("results", []) - _fail_if([r["name"] for r in results if "error" in r or "rolled_back_to" in r], "update-all") + for r in results: + if r.get("kept"): + # never a silent downgrade: the package's postinst shows these lines in apt + typer.secho( + f"update-all: {r['name']} kept on its image {r.get('image')}: {r.get('reason')}", + fg=typer.colors.YELLOW, + err=True, + ) + _fail_if( + [r["name"] for r in results if "error" in r or "rolled_back_to" in r or r.get("kept")], + "update-all", + ) @app.command() diff --git a/controlplane/lmnsquid/docker_service.py b/controlplane/lmnsquid/docker_service.py index 0ed7f67..413eeaf 100644 --- a/controlplane/lmnsquid/docker_service.py +++ b/controlplane/lmnsquid/docker_service.py @@ -572,6 +572,24 @@ def status(self, name: str) -> dict[str, Any]: "activity_capable": bool(labels.get(activity.ACTIVITY_LABEL)), } + def image_info(self, image: str, pull: bool = True) -> Optional[dict[str, Any]]: + """Creation time and labels of ``image`` (pulled first when missing and ``pull``); + ``None`` when it cannot be had. Used by update-all, before any container changes.""" + try: + obj = self.client.images.get(image) + except ImageNotFound: + if not pull: + return None + try: + self._pull(image) + obj = self.client.images.get(image) + except (ImageNotFound, APIError): + return None + except APIError: + return None + attrs = getattr(obj, "attrs", None) or {} + return {"created": attrs.get("Created"), "labels": dict(obj.labels or {})} + def logs( self, name: str, diff --git a/controlplane/lmnsquid/main.py b/controlplane/lmnsquid/main.py index 98fa962..4e37faf 100644 --- a/controlplane/lmnsquid/main.py +++ b/controlplane/lmnsquid/main.py @@ -20,6 +20,7 @@ from .reconciler import Reconciler from .store import Store from .tls import ClientAllowlist, Network, TLSConfigError, check_tls_settings +from .filters import FilterStore from .updater import Updater log = logging.getLogger("lmnsquid") @@ -65,7 +66,15 @@ def main() -> None: activity_spool_dir=settings.activity_spool_dir, ) reconciler = Reconciler(store, docker) - updater = Updater(store, docker, reconciler) + filters = FilterStore(settings.blocklists_dir, settings.filter_timezone) + + def uses_filter(name: str) -> bool: + """Categories or SafeSearch on: the instance needs an image with the filter.""" + data = filters.read(name) or {} + safesearch = data.get("safesearch") or {} + return bool(data.get("categories")) or any(v and v != "off" for v in safesearch.values()) + + updater = Updater(store, docker, reconciler, uses_filter=uses_filter) app = create_app(settings, store, reconciler, docker, updater) _warn_if_insecure_bind(settings.bind_host) if not settings.tls_bind_host: diff --git a/controlplane/lmnsquid/updater.py b/controlplane/lmnsquid/updater.py index 76a1658..a504616 100644 --- a/controlplane/lmnsquid/updater.py +++ b/controlplane/lmnsquid/updater.py @@ -13,9 +13,12 @@ import logging import time from pathlib import Path -from typing import Any +from typing import Any, Callable +from . import activity +from .docker_service import FILTER_LABEL from .docker_service import DockerService +from .models import Instance from .reconciler import Reconciler from .store import Store @@ -32,8 +35,11 @@ def __init__( reconciler: Reconciler, health_timeout: float = 90.0, poll_interval: float = 3.0, + uses_filter: Callable[[str], bool] | None = None, ) -> None: self.store = store + # whether an instance's filter settings need the category filter of the image + self.uses_filter = uses_filter or (lambda _name: False) self.docker = docker self.reconciler = reconciler self.health_timeout = health_timeout @@ -98,10 +104,31 @@ def update_all(self, target_image: str) -> list[dict[str, Any]]: so a no-op run (e.g. a ``.deb`` upgrade whose default did not move) does not needlessly recreate any container.""" results: list[dict[str, Any]] = [] + target = self.docker.image_info(target_image) for inst in self.store.list(): if inst.image == target_image: results.append({"name": inst.name, "updated": False, "skipped": True}) continue + reason = self._keep_reason(inst, target) + if reason: + audit.warning( + "update-all keeps name=%s on image=%s (target %s): %s", + inst.name, + inst.image, + target_image, + reason, + ) + results.append( + { + "name": inst.name, + "updated": False, + "kept": True, + "image": inst.image, + "target": target_image, + "reason": reason, + } + ) + continue try: results.append(self.update(inst.name, target_image)) except Exception as exc: @@ -111,6 +138,42 @@ def update_all(self, target_image: str) -> list[dict[str, Any]]: results.append({"name": inst.name, "updated": False, "error": str(exc)}) return results + def _keep_reason(self, inst: Instance, target: dict[str, Any] | None) -> str | None: + """Why update-all must leave ``inst`` on its image, or ``None``. + + A package upgrade runs update-all onto the maintained default image (postinst). That + default is bumped by a separate release step; until then it may be older than what an + instance runs, or lack what the instance uses. update-all never downgrades: an older + image, or one without the category filter (filter in use) or without the activity + log receiver (log on), is not applied; ``lmnsquid update NAME IMAGE`` still is.""" + if target is None: + return None # cannot inspect it: update() pulls and rolls back on its own + labels = target.get("labels") or {} + if self.uses_filter(inst.name) and not labels.get(FILTER_LABEL): + return "the target image has no category filter, which this instance uses" + if inst.activity_log_enabled and not labels.get(activity.ACTIVITY_LABEL): + return "the target image has no activity log, which is on for this instance" + current = self.docker.image_info(inst.image, pull=False) + if current is None: + return None + for label, what in ( + (FILTER_LABEL, "category filter"), + (activity.ACTIVITY_LABEL, "activity log"), + ): + have, get = _version(current["labels"].get(label)), _version(labels.get(label)) + if have is not None and (get is None or get < have): + return f"the target image has an older {what} (version {get}, instance {have})" + if ( + current.get("created") + and target.get("created") + and target["created"] < current["created"] + ): + return ( + f"the target image is older than the instance's " + f"({target['created'][:19]} < {current['created'][:19]})" + ) + return None + def rollback(self, name: str) -> dict[str, Any]: """Revert ``name`` to the image recorded before the last update.""" inst = self.store.get(name) @@ -139,3 +202,11 @@ def _wait_healthy(self, name: str) -> bool: if time.monotonic() >= deadline: return False time.sleep(self.poll_interval) + + +def _version(value: Any) -> int | None: + """A capability label's value as a number (``"2"`` -> 2); ``None`` when absent.""" + try: + return int(str(value)) if value not in (None, "") else None + except ValueError: + return 1 diff --git a/controlplane/tests/conftest.py b/controlplane/tests/conftest.py index 948dfcb..e80e438 100644 --- a/controlplane/tests/conftest.py +++ b/controlplane/tests/conftest.py @@ -53,6 +53,12 @@ def __init__( # Opt-in: refuse a missing keytab like the real ensure_running (most tests name # keytabs that do not exist on disk). self.check_secrets = False + # image -> {"created": iso, "labels": {...}} for image_info (update-all's checks); + # an image not listed cannot be inspected (None), as an unpullable one + self.images: dict[str, dict[str, Any]] = {} + + def image_info(self, image: str, pull: bool = True) -> dict[str, Any] | None: + return self.images.get(image) def env_for(self, inst: Instance) -> dict[str, str]: # The real one (it touches no Docker), so API tests see the env a container gets. diff --git a/controlplane/tests/test_cli.py b/controlplane/tests/test_cli.py index 2c5b2b4..97f9339 100644 --- a/controlplane/tests/test_cli.py +++ b/controlplane/tests/test_cli.py @@ -148,6 +148,25 @@ def test_cli_update_all(patch_client: None, instance_data: dict[str, Any]) -> No assert DEFAULT_IMAGE in runner.invoke(cli.app, ["show", "default-school-teachers"]).output +def test_cli_update_all_names_kept_instances( + patch_client: None, instance_data: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """update-all that leaves an instance on its image says so and exits 1 (the package's + postinst then shows the line in the apt output; cold recheck N1).""" + from lmnsquid.updater import Updater + + def kept(self: Updater, target: str) -> list[dict[str, Any]]: + return [ + {"name": "s-students", "updated": False, "kept": True, "image": "x:new", + "target": target, "reason": "the target image has no activity log"} + ] # fmt: skip + + monkeypatch.setattr(Updater, "update_all", kept) + r = runner.invoke(cli.app, ["update-all"]) + assert r.exit_code == 1 + assert "s-students kept on its image x:new: the target image has no activity log" in r.output + + def test_cli_edit_and_version(patch_client: None, instance_data: dict[str, Any]) -> None: runner.invoke( cli.app, diff --git a/controlplane/tests/test_docker_integration.py b/controlplane/tests/test_docker_integration.py index d8b675d..c46ccb9 100644 --- a/controlplane/tests/test_docker_integration.py +++ b/controlplane/tests/test_docker_integration.py @@ -491,3 +491,59 @@ def test_log_rotation_error_reported(tmp_path: Path) -> None: ) finally: svc.remove(inst.name) + + +def test_update_all_keeps_instances_on_a_newer_real_image(tmp_path: Path) -> None: + """A package upgrade with an older default pin (cold recheck N1), with real images: the + instance's image carries the filter and activity labels, the 'default' is older and has + neither; update-all reads both from Docker and keeps the instance where it is.""" + import docker as docker_sdk + + from lmnsquid.docker_service import DockerService + from lmnsquid.models import Instance + from lmnsquid.reconciler import Reconciler + from lmnsquid.store import Store + from lmnsquid.updater import Updater + + client = docker_sdk.from_env() + ctx = tmp_path / "ctx" + ctx.mkdir() + old_ref, new_ref = "lmnsquid-it-n1:old", "lmnsquid-it-n1:new" + (ctx / "Dockerfile").write_text("FROM busybox:1.36\nLABEL org.example.n1=old\n") + client.images.build(path=str(ctx), tag=old_ref, rm=True) + time.sleep(1.1) # Created has second resolution in the comparison + (ctx / "Dockerfile").write_text( + "FROM busybox:1.36\n" + 'LABEL org.faircomp.linuxmuster-squid.filter="2" org.faircomp.linuxmuster-squid.activity="1"\n' + ) + client.images.build(path=str(ctx), tag=new_ref, rm=True, nocache=True) + try: + ds = DockerService( + None, str(tmp_path / "secrets"), "127.0.0.1", "1m", 1, str(tmp_path / "bl") + ) + store = Store(str(tmp_path / "instances")) + inst = Instance( + school="s", + role="teachers", + ad_group="teachers", + realm="EX.LAN", + visible_hostname="proxy.example.lan", + keytab_secret="proxy.keytab", + image=new_ref, + activity_log_enabled=True, + activity_ack_by="admin", + activity_ack_at="2026-11-25T09:00:00+00:00", + ) + store.put(inst) + up = Updater(store, ds, Reconciler(store, ds), uses_filter=lambda n: True) + [res] = up.update_all(old_ref) + assert res.get("kept") is True, res + assert store.get(inst.name).image == new_ref # type: ignore[union-attr] + info = ds.image_info(new_ref, pull=False) + assert info and info["labels"].get("org.faircomp.linuxmuster-squid.activity") == "1" + finally: + for ref in (old_ref, new_ref): + try: + client.images.remove(ref, force=True) + except docker_sdk.errors.APIError: + pass diff --git a/controlplane/tests/test_updater.py b/controlplane/tests/test_updater.py index a7cae90..c903a66 100644 --- a/controlplane/tests/test_updater.py +++ b/controlplane/tests/test_updater.py @@ -147,3 +147,82 @@ def _inst(school: str, image: str) -> Instance: assert results[name]["updated"] is False assert store.get(name).image == "ghcr.io/example/lmnsquid:v1" # type: ignore[union-attr] assert docker.status(name)["health"] == "healthy" + + +# -- update-all never downgrades (cold recheck N1) ------------------------------------------ +NEW = "ghcr.io/example/lmnsquid:activity" # what the instances run: filter and activity log +OLD_DEFAULT = "ghcr.io/example/lmnsquid@sha256:" + "a" * 64 # an older maintained pin +FULL = { + "org.faircomp.linuxmuster-squid.filter": "2", + "org.faircomp.linuxmuster-squid.activity": "1", +} + + +def _images(docker: Any) -> None: + docker.images[NEW] = {"created": "2026-11-25T10:00:00Z", "labels": dict(FULL)} + docker.images[OLD_DEFAULT] = {"created": "2026-11-01T10:00:00Z", "labels": {}} + + +def test_update_all_keeps_instances_on_a_newer_image( + store: Store, docker: Any, reconciler: Reconciler, instance: Instance +) -> None: + """A package upgrade whose default pin is older than what runs: nothing is replaced, the + filter and the activity log stay on, the result says why (the postinst shows it).""" + _images(docker) + inst = instance.model_copy( + update={ + "image": NEW, + "activity_log_enabled": True, + "activity_ack_by": "admin", + "activity_ack_at": "2026-11-25T09:00:00+00:00", + } + ) + reconciler.apply(inst) + up = Updater( + store, docker, reconciler, health_timeout=1.0, poll_interval=0.0, uses_filter=lambda n: True + ) + calls = len(docker.ensure_calls) + [res] = up.update_all(OLD_DEFAULT) + assert res["kept"] is True and res["updated"] is False + assert "category filter" in res["reason"] + kept = store.get(inst.name) + assert kept is not None and kept.image == NEW and kept.activity_log_enabled + assert docker.status(inst.name)["image"] == NEW + assert len(docker.ensure_calls) == calls, "no container replaced" + + +def test_update_all_keeps_an_activity_log_or_a_newer_image( + store: Store, docker: Any, reconciler: Reconciler, instance: Instance +) -> None: + _images(docker) + up = _updater(store, docker, reconciler) + on = instance.model_copy( + update={ + "image": NEW, + "activity_log_enabled": True, + "activity_ack_by": "admin", + "activity_ack_at": "2026-11-25T09:00:00+00:00", + } + ) + reconciler.apply(on) + [res] = up.update_all(OLD_DEFAULT) + assert res["kept"] and "activity log" in res["reason"] + # nothing in use, but the default is older than the running image: kept as well + store.put(on.model_copy(update={"activity_log_enabled": False})) + docker.images[OLD_DEFAULT]["labels"] = dict(FULL) + [res] = up.update_all(OLD_DEFAULT) + assert res["kept"] and "older" in res["reason"] + + +def test_update_all_moves_onto_a_newer_default( + store: Store, docker: Any, reconciler: Reconciler, instance: Instance +) -> None: + _images(docker) + newer = "ghcr.io/example/lmnsquid@sha256:" + "b" * 64 + docker.images[newer] = {"created": "2026-12-01T10:00:00Z", "labels": dict(FULL)} + reconciler.apply(instance.model_copy(update={"image": NEW})) + up = Updater( + store, docker, reconciler, health_timeout=1.0, poll_interval=0.0, uses_filter=lambda n: True + ) + [res] = up.update_all(newer) + assert res["updated"] is True and store.get(instance.name).image == newer # type: ignore[union-attr] diff --git a/debian/linuxmuster-squid.postinst b/debian/linuxmuster-squid.postinst index f051da0..822dbd6 100644 --- a/debian/linuxmuster-squid.postinst +++ b/debian/linuxmuster-squid.postinst @@ -242,7 +242,7 @@ if [ -d /run/systemd/system ]; then # The CLI names the affected instances on stderr and carries the reason # per instance; show those lines here so they reach the apt output, the # full result stays in the journal. - printf '%s\n' "$out" | grep -E 'instance\(s\) failed|"error": ' \ + printf '%s\n' "$out" | grep -E 'instance\(s\) failed|"error": |kept on its image' \ | head -n 5 | sed 's/^/ /' >&2 echo " Full output: journalctl -t linuxmuster-squid; state: lmnsquid list" >&2 fi From 78a84eae60b23cdbdc669c20bd52dd5f1318ca5f Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 22:02:13 +0100 Subject: [PATCH 40/45] fix(controlplane): no race between switching on and the collector; spool repair; quarantine beside the spool Switching the activity log on creates the spool, replaces the container (~10 s) and only then writes 'on'. A collector run in between took the definition's 'off' and removed the fresh spool; Docker then created the mount source as root, squid could not write, every collector run and every update failed (cold recheck N2). The control plane now holds the collector's lock while it switches the log (waits up to 120 s for a busy run, else 409 busy). Start, restart, update and reconcile repair a missing spool or one that is not the control plane's (removed or put aside, created again, a running container restarted so its mount sees it). The overview reports spool_ok and last_data. The quarantine moves beside the spools (/.quarantine//, same filesystem): an atomic rename that also works for a file the collector cannot read, and leaves no copy behind; a failed move keeps the attempt counter (N3). A file stored completely is never a failed attempt, even when it cannot be removed (N4). --- controlplane/lmnsquid/activity.py | 119 ++++++++++++++++--- controlplane/lmnsquid/activity_api.py | 28 +++++ controlplane/lmnsquid/api.py | 8 ++ controlplane/lmnsquid/docker_service.py | 6 + controlplane/tests/test_activity_race.py | 131 +++++++++++++++++++++ controlplane/tests/test_activity_stream.py | 61 +++++++++- controlplane/tests/test_docker_service.py | 26 ++++ 7 files changed, 361 insertions(+), 18 deletions(-) create mode 100644 controlplane/tests/test_activity_race.py diff --git a/controlplane/lmnsquid/activity.py b/controlplane/lmnsquid/activity.py index 8b79f74..f489868 100644 --- a/controlplane/lmnsquid/activity.py +++ b/controlplane/lmnsquid/activity.py @@ -116,6 +116,22 @@ def ensure_spool(root: str, name: str) -> Path: base = Path(root) base.mkdir(mode=0o750, parents=True, exist_ok=True) path = spool_dir(root, name) + try: + st = path.lstat() + except FileNotFoundError: + st = None + if st is not None and (not stat.S_ISDIR(st.st_mode) or st.st_uid != os.geteuid()): + # Docker created it (root:root 0755) because the spool was missing when the container + # was started: squid cannot write into it and chmod is refused (cold recheck N2, B). + # The parent is ours: an empty one goes, a non-empty one is put aside. + try: + path.rmdir() if stat.S_ISDIR(st.st_mode) else path.unlink() + except OSError: + aside = base / f".stale-{_safe(name)}-{int(time.time())}" + os.rename(path, aside) + logger.warning("activity: %s: spool not ours, put aside as %s", name, aside) + else: + logger.warning("activity: %s: spool not ours (uid %d), created again", name, st.st_uid) try: path.mkdir(mode=0o700) except FileExistsError: @@ -125,6 +141,21 @@ def ensure_spool(root: str, name: str) -> Path: return path +def spool_ok(root: str, name: str) -> bool | None: + """Whether the spool is ours with its mode (``None``: there is none).""" + try: + st = spool_dir(root, name).lstat() + except FileNotFoundError: + return None + except OSError: + return False + return ( + stat.S_ISDIR(st.st_mode) + and st.st_uid == os.geteuid() + and stat.S_IMODE(st.st_mode) == SPOOL_MODE + ) + + def day_name(day: datetime.date) -> str: return f"{day.isoformat()}{DAY_SUFFIX}" @@ -198,6 +229,7 @@ def purge_instance(data_root: str, spool_root: str, name: str) -> None: """Delete everything the activity log holds of ``name``: day files and spool.""" shutil.rmtree(data_dir(data_root, name), ignore_errors=True) shutil.rmtree(spool_dir(spool_root, name), ignore_errors=True) + shutil.rmtree(quarantine_dir(spool_root, name), ignore_errors=True) def delete_data(data_root: str, spool_root: str, name: str) -> int: @@ -208,6 +240,7 @@ def delete_data(data_root: str, spool_root: str, name: str) -> int: remove_day_file(path) # what the collector gave up on is activity data too shutil.rmtree(data_dir(data_root, name) / QUARANTINE_DIR, ignore_errors=True) + shutil.rmtree(quarantine_dir(spool_root, name), ignore_errors=True) _unlink(data_dir(data_root, name) / ATTEMPTS_FILE) spool = spool_dir(spool_root, name) try: @@ -234,11 +267,20 @@ def usage(data_root: str, spool_root: str, name: str) -> dict[str, object]: pass waiting = 0 waiting_bytes = 0 + last = 0.0 + for _day, path in files[-1:]: + try: + last = max(last, os.stat(f"{path}-wal").st_mtime) + except FileNotFoundError: + pass + last = max(last, os.stat(path).st_mtime) try: for entry in os.scandir(spool_dir(spool_root, name)): if entry.name.startswith(("act-", ".part-")): + st = entry.stat(follow_symlinks=False) waiting += 1 - waiting_bytes += entry.stat(follow_symlinks=False).st_size + waiting_bytes += st.st_size + last = max(last, st.st_mtime) except (FileNotFoundError, PermissionError): pass return { @@ -248,7 +290,11 @@ def usage(data_root: str, spool_root: str, name: str) -> dict[str, object]: "newest": files[-1][0].isoformat() if files else None, "spool_files": waiting, "spool_bytes": waiting_bytes, - "quarantined": len(quarantined(data_root, name)), + "quarantined": len(quarantined(data_root, name, spool_root)), + # when lines last arrived (newest spool file or day file); with the log on and nothing + # for long, the WebUI says so (cold recheck N2) + "last_data": int(last) if last else None, + "spool_ok": spool_ok(spool_root, name), } @@ -775,18 +821,35 @@ def _write_attempts(directory: Path, attempts: dict[str, int]) -> None: os.replace(tmp, path) -def quarantined(data_root: str, name: str) -> list[str]: - """Spool files of ``name`` the collector gave up on (oldest first).""" - try: - return sorted(e.name for e in os.scandir(data_dir(data_root, name) / QUARANTINE_DIR)) - except FileNotFoundError: - return [] +def quarantine_dir(spool_root: str, name: str) -> Path: + """Where the collector puts a spool file it gave up on: beside the instance spools, on the + same filesystem (a rename, also for a file the collector cannot read; cold recheck N3), not + in the directory the container mounts.""" + return Path(spool_root) / ".quarantine" / _safe(name) + + +def quarantined(data_root: str, name: str, spool_root: str | None = None) -> list[str]: + """Spool files of ``name`` the collector gave up on (also those a build before the move + put into the data directory).""" + found: set[str] = set() + places = [data_dir(data_root, name) / QUARANTINE_DIR] + if spool_root is not None: + places.append(quarantine_dir(spool_root, name)) + for place in places: + try: + found.update(e.name for e in os.scandir(place)) + except (FileNotFoundError, PermissionError): + pass + return sorted(found) -def _quarantine(path: Path, target: Path, inst: str, attempts: int) -> None: - directory = target / QUARANTINE_DIR - directory.mkdir(mode=0o700, parents=True, exist_ok=True) - shutil.move(str(path), str(directory / path.name)) +def _quarantine(path: Path, spool_root: str, inst: str, attempts: int) -> None: + """Move ``path`` into the quarantine by rename: atomic, nothing left behind on failure (a + copy whose source could not be removed reported data as missing that were there, N4).""" + directory = quarantine_dir(spool_root, inst) + directory.parent.mkdir(mode=0o700, exist_ok=True) + directory.mkdir(mode=0o700, exist_ok=True) + os.replace(path, directory / path.name) logger.error( "activity: %s: spool file %s failed %d times, moved to %s (not counted; delete it or " "move it back into the spool to try again)", @@ -823,9 +886,11 @@ def collect_instance( tried = attempts.get(source, 0) if tried >= MAX_ATTEMPTS: try: - _quarantine(path, target, inst.name, tried) + _quarantine(path, spool_root, inst.name, tried) except OSError as exc: + # the counter stays: the next run tries the move again (N3) logger.error("activity: %s: quarantine of %s failed: %s", inst.name, path.name, exc) + continue attempts.pop(source, None) _write_attempts(target, attempts) continue @@ -850,9 +915,16 @@ def collect_instance( exc, ) continue - _unlink(path) + # stored completely: whether or not it can be removed now, it is no failed attempt (a + # file that stays is skipped by the ledger next time, and never quarantined; N4) attempts.pop(source, None) _write_attempts(target, attempts) + try: + _unlink(path) + except OSError as exc: + logger.error( + "activity: %s: %s is collected but cannot be removed: %s", inst.name, path.name, exc + ) # files that left the spool (collected by an older run, deleted by hand) need no counter waiting = {_source_name(p) for p in spool_files(spool_dir(spool_root, inst.name), now)} stale = [k for k in attempts if k not in waiting] @@ -918,6 +990,23 @@ def release(self) -> None: self.fd = -1 +def collect_lock(data_root: str) -> Lock: + """The collector's lock; the control plane holds it while it switches the log on or off, + so no collector run sees the definition in between (cold recheck N2).""" + return Lock(Path(data_root) / ".collect.lock") + + +def hold_collect_lock(data_root: str, timeout: float) -> Lock | None: + """Wait up to ``timeout`` seconds for the collector's lock; ``None`` if a run keeps it.""" + lock = collect_lock(data_root) + deadline = time.monotonic() + timeout + while not lock.acquire(): + if time.monotonic() >= deadline: + return None + time.sleep(0.2) + return lock + + def iter_instances(instances_dir: str) -> Iterator[Instance]: from .store import Store @@ -950,7 +1039,7 @@ def main(argv: list[str] | None = None) -> int: paths = Paths( settings.activity_dir, settings.activity_spool_dir, ZoneInfo(settings.filter_timezone) ) - lock = Lock(Path(settings.activity_dir) / ".collect.lock") + lock = collect_lock(settings.activity_dir) if not lock.acquire(): logger.info("activity: another collector run is still working") return 0 diff --git a/controlplane/lmnsquid/activity_api.py b/controlplane/lmnsquid/activity_api.py index e712a5e..b3f62d3 100644 --- a/controlplane/lmnsquid/activity_api.py +++ b/controlplane/lmnsquid/activity_api.py @@ -187,6 +187,10 @@ def _v_actor(cls, v: str) -> str: return _printable(v, 128) or "api" +# How long switching the log waits for a collector run to finish (seconds). +COLLECT_LOCK_WAIT = 120.0 + + def register( app: FastAPI, settings: Settings, @@ -389,6 +393,30 @@ def put_activity(name: str, body: ActivitySettings) -> dict[str, Any]: ) toggled = merged.activity_log_enabled != inst.activity_log_enabled result: dict[str, Any] | None = None + # No collector run while the log is switched: the container needs the spool for ~10 s + # before the definition says "on", and a run in between took the definition's "off" + # and removed the fresh spool (cold recheck N2). A run that is busy is waited for. + lock = activity.hold_collect_lock(settings.activity_dir, COLLECT_LOCK_WAIT) + if lock is None: + _fail( + "busy", + "the activity collector is working through a backlog; try again in a minute", + status.HTTP_409_CONFLICT, + ) + try: + return _switch(name, body, inst, merged, switching_on, toggled, result) + finally: + lock.release() # type: ignore[union-attr] + + def _switch( + name: str, + body: ActivitySettings, + inst: Instance, + merged: Instance, + switching_on: bool, + toggled: bool, + result: dict[str, Any] | None, + ) -> dict[str, Any]: try: # The definition is written only after the container matches it: a failure leaves # the instance as it was (lab 2026-11-25: the definition said "on", the container diff --git a/controlplane/lmnsquid/api.py b/controlplane/lmnsquid/api.py index 9f79b1c..b687597 100644 --- a/controlplane/lmnsquid/api.py +++ b/controlplane/lmnsquid/api.py @@ -779,6 +779,10 @@ def start_instance(name: str) -> dict[str, Any]: audit.info("start instance name=%s", name) if not docker.status(name).get("exists"): return _ensure(inst) + if inst.activity_log_enabled: + # a missing or foreign spool is repaired before the container mounts it again + # (cold recheck N2) + activity.ensure_spool(settings.activity_spool_dir, name) return docker.start(name) @app.post("/v1/instances/{name}/stop", dependencies=auth) @@ -793,6 +797,10 @@ def restart_instance(name: str) -> dict[str, Any]: audit.info("restart instance name=%s", name) if not docker.status(name).get("exists"): return _ensure(inst) + if inst.activity_log_enabled: + # a missing or foreign spool is repaired before the container mounts it again + # (cold recheck N2) + activity.ensure_spool(settings.activity_spool_dir, name) return docker.restart(name) @app.get("/v1/instances/{name}/status", dependencies=auth) diff --git a/controlplane/lmnsquid/docker_service.py b/controlplane/lmnsquid/docker_service.py index 413eeaf..2340731 100644 --- a/controlplane/lmnsquid/docker_service.py +++ b/controlplane/lmnsquid/docker_service.py @@ -286,7 +286,9 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: # The catalog directory must exist before Docker mounts it (else Docker creates a # root-owned one); SafeSearch addresses are resolved again for a new container. os.makedirs(self.catalog_dir, mode=0o755, exist_ok=True) + spool_repaired = False if inst.activity_log_enabled: + spool_repaired = activity.spool_ok(self.activity_spool_dir, inst.name) is not True activity.ensure_spool(self.activity_spool_dir, inst.name) self.filters.refresh_safesearch(inst.name) @@ -296,6 +298,10 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: existing.reload() if not (existing.attrs.get("State") or {}).get("Running", False): existing.start() + elif spool_repaired: + # the spool was missing or Docker's (root): the running container still has + # the old directory mounted; a restart mounts the repaired one (cold recheck N2) + existing.restart() return self.status(inst.name) # Leftovers of an interrupted replacement. diff --git a/controlplane/tests/test_activity_race.py b/controlplane/tests/test_activity_race.py new file mode 100644 index 0000000..ef821b4 --- /dev/null +++ b/controlplane/tests/test_activity_race.py @@ -0,0 +1,131 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Switching the activity log on while the collector runs (cold recheck N2): the container +switch takes seconds before the definition says "on"; a collector run in between must not take +the definition's "off" and remove the fresh spool. And a spool Docker created as root (because +it was missing) is repaired on the next start instead of failing every update.""" + +from __future__ import annotations + +import os +import stat +from pathlib import Path +from typing import Any + +import pytest +from starlette.testclient import TestClient +from test_activity_api import NAME, _create, _enable + +from lmnsquid import activity +from lmnsquid.config import Settings +from lmnsquid.store import Store + + +def _collector_run(settings: Settings) -> str: + """What one run of the timer does (lmnsquid-activity collect): take the lock or skip.""" + lock = activity.Lock(Path(settings.activity_dir) / ".collect.lock") + if not lock.acquire(): + return "skipped" + try: + paths = activity.Paths(settings.activity_dir, settings.activity_spool_dir, activity_zone()) + activity.collect_all(list(Store(settings.instances_dir).list()), paths) + return "ran" + finally: + lock.release() + + +def activity_zone() -> Any: + from zoneinfo import ZoneInfo + + return ZoneInfo("Europe/Berlin") + + +def test_a_collector_run_during_switching_on_keeps_the_spool( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, + docker: Any, + monkeypatch: pytest.MonkeyPatch, +) -> None: + _create(client, auth_headers, instance_data) + runs: list[str] = [] + real = docker.ensure_running + + def slow_switch(inst: Any) -> Any: + # the container is being replaced; the timer fires now + runs.append(_collector_run(settings)) + return real(inst) + + monkeypatch.setattr(docker, "ensure_running", slow_switch) + r = _enable(client, auth_headers) + assert r.status_code == 200, r.text + assert "ran" not in runs, "no collector run while the log is switched" + spool = activity.spool_dir(settings.activity_spool_dir, NAME) + assert spool.is_dir() and stat.S_IMODE(spool.stat().st_mode) == activity.SPOOL_MODE + # afterwards the collector runs again and leaves the spool of an instance that is on + monkeypatch.setattr(docker, "ensure_running", real) + assert _collector_run(settings) == "ran" + assert spool.is_dir() + view = client.get(f"/v1/instances/{NAME}/activity", headers=auth_headers).json() + assert view["usage"]["spool_ok"] is True and view["usage"]["last_data"] is None + + +def test_switching_waits_for_a_running_collector( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from lmnsquid import activity_api + + _create(client, auth_headers, instance_data) + busy = activity.Lock(Path(settings.activity_dir) / ".collect.lock") + assert busy.acquire() + monkeypatch.setattr(activity_api, "COLLECT_LOCK_WAIT", 0.5) + try: + r = _enable(client, auth_headers) + finally: + busy.release() + assert r.status_code == 409 and r.json()["detail"]["code"] == "busy" + assert not Store(settings.instances_dir).get(NAME).activity_log_enabled # type: ignore[union-attr] + + +def test_a_spool_that_is_not_ours_is_repaired(tmp_path: Path) -> None: + """Docker made the missing spool root:root 0755 (cold recheck N2, B). Simulated with a + file in its place and with a directory of another owner (needs root to chown).""" + root = str(tmp_path / "spool") + path = activity.spool_dir(root, NAME) + path.parent.mkdir(parents=True) + path.write_text("not a directory") + assert activity.spool_ok(root, NAME) is False + activity.ensure_spool(root, NAME) + assert path.is_dir() and activity.spool_ok(root, NAME) is True + if os.geteuid() == 0: + path.rmdir() + path.mkdir(mode=0o755) + os.chown(path, 65534, 65534) + (path / "x").write_text("left by someone") + os.chown(path / "x", 65534, 65534) + activity.ensure_spool(root, NAME) + assert activity.spool_ok(root, NAME) is True + assert list(path.parent.glob(f".stale-{NAME}-*")) + + +def test_restart_repairs_a_missing_spool( + client: TestClient, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Settings, +) -> None: + """What the WebUI's hint asks for (restart the instance) repairs the spool.""" + _create(client, auth_headers, instance_data) + assert _enable(client, auth_headers).status_code == 200 + spool = activity.spool_dir(settings.activity_spool_dir, NAME) + spool.rmdir() # removed by a collector run of an older version, or by hand + view = client.get(f"/v1/instances/{NAME}/activity", headers=auth_headers).json() + assert view["usage"]["spool_ok"] is None + r = client.post(f"/v1/instances/{NAME}/restart", headers=auth_headers) + assert r.status_code == 200, r.text + assert activity.spool_ok(settings.activity_spool_dir, NAME) is True diff --git a/controlplane/tests/test_activity_stream.py b/controlplane/tests/test_activity_stream.py index 88dc096..d820b79 100644 --- a/controlplane/tests/test_activity_stream.py +++ b/controlplane/tests/test_activity_stream.py @@ -7,6 +7,7 @@ from __future__ import annotations import json +import os import random import resource import sqlite3 @@ -166,13 +167,13 @@ def poisoned(self: Any, fh: Any) -> None: assert attempts == {bad.name: activity.MAX_ATTEMPTS} activity.collect_all([students, teachers], paths, now=T0 + 3600) assert not bad.exists() - assert activity.quarantined(data, students.name) == [bad.name] + assert activity.quarantined(data, students.name, spool) == [bad.name] assert activity.usage(data, spool, students.name)["quarantined"] == 1 assert "moved to" in caplog.text and bad.name in caplog.text assert not (Path(data) / students.name / activity.ATTEMPTS_FILE).exists() # switching off with deletion removes the quarantine too (personal data) activity.delete_data(data, spool, students.name) - assert activity.quarantined(data, students.name) == [] + assert activity.quarantined(data, students.name, spool) == [] def test_a_run_killed_by_a_file_counts_as_an_attempt(env: Env) -> None: @@ -182,7 +183,7 @@ def test_a_run_killed_by_a_file_counts_as_an_attempt(env: Env) -> None: target.mkdir(parents=True) (target / activity.ATTEMPTS_FILE).write_text(json.dumps({path.name: activity.MAX_ATTEMPTS})) env.collect() - assert activity.quarantined(env.data, env.inst.name) == [path.name] + assert activity.quarantined(env.data, env.inst.name, env.spool_root) == [path.name] def _big_file(path: Path, mib: int) -> int: @@ -242,3 +243,57 @@ def test_memory_does_not_grow_with_the_file(tmp_path: Path) -> None: ) assert total == expected _ = resource # the runner measures in its own process + + +@pytest.mark.skipif(os.geteuid() == 0, reason="root reads a file of mode 000") +def test_an_unreadable_file_reaches_the_quarantine( + env: Env, monkeypatch: pytest.MonkeyPatch +) -> None: + """Cold recheck N3: under the unit, spool and data directory are separate mounts; moving a + file the collector cannot read to the data directory meant copying it, which failed, and the + counter started again. The quarantine is beside the spool now: a rename.""" + path = env.put(line(T0, "s1", "a.example")) + path.chmod(0) + for _ in range(activity.MAX_ATTEMPTS): + env.collect() + assert path.exists() + # a move that fails keeps the counter; the next run moves it + real = os.replace + + def fails_once(src: Any, dst: Any) -> None: + monkeypatch.setattr(os, "replace", real) + raise OSError(18, "Invalid cross-device link") + + monkeypatch.setattr(os, "replace", fails_once) + env.collect() + assert path.exists() and activity.quarantined(env.data, env.inst.name, env.spool_root) == [] + env.collect() + assert not path.exists() + assert activity.quarantined(env.data, env.inst.name, env.spool_root) == [path.name] + assert activity.usage(env.data, env.spool_root, env.inst.name)["quarantined"] == 1 + target = activity.quarantine_dir(env.spool_root, env.inst.name) / path.name + assert target.exists() + (target).chmod(0o600) + + +def test_a_collected_file_that_cannot_be_removed_is_no_loss( + env: Env, monkeypatch: pytest.MonkeyPatch +) -> None: + """Cold recheck N4: a file stored completely whose removal fails is not a failed attempt: + never quarantined (the WebUI would report data as missing that are there), never counted + twice.""" + path = env.put(line(T0, "s1", "a.example") + line(T0 + 1, "s2", "b.example")) + + real = activity._unlink + + def refuse(p: Any) -> None: + if Path(p).parent == env.spool: # the spool file, not the collector's own files + raise PermissionError(13, "Permission denied", str(p)) + real(p) + + monkeypatch.setattr(activity, "_unlink", refuse) + for _ in range(activity.MAX_ATTEMPTS + 2): + env.collect() + assert path.exists() + assert activity.quarantined(env.data, env.inst.name, env.spool_root) == [] + assert env.total() == 2 diff --git a/controlplane/tests/test_docker_service.py b/controlplane/tests/test_docker_service.py index 8a43aee..a90dc90 100644 --- a/controlplane/tests/test_docker_service.py +++ b/controlplane/tests/test_docker_service.py @@ -281,3 +281,29 @@ def test_wait_healthy_fails_fast_on_exit(tmp_path: Path) -> None: "State": {"Running": True, "Health": {"Status": "starting"}}, } assert "not healthy after" in (ds._wait_healthy(c) or "") + + +def test_a_repaired_spool_restarts_the_running_container(tmp_path: Path) -> None: + """The spool of a running instance with the log on was missing (a collector run removed + it during switching on; cold recheck N2): ensure_running creates it again and restarts the + container so its mount sees the new directory; a sound spool restarts nothing.""" + from lmnsquid import activity + + ds = _service(tmp_path) + ds.activity_spool_dir = str(tmp_path / "spool") + inst = _inst( + activity_log_enabled=True, + activity_ack_by="admin", + activity_ack_at="2026-11-25T09:00:00+00:00", + ) + digest = ds.fingerprint(ds.spec_for(inst)) + existing = _container("lmnsquid-s-teachers", {SPEC_LABEL: digest}, running=True) + _registry(ds, {"lmnsquid-s-teachers": existing}) + + ds.ensure_running(inst) + assert activity.spool_ok(ds.activity_spool_dir, inst.name) is True + existing.restart.assert_called_once() + ds.client.containers.create.assert_not_called() + + ds.ensure_running(inst) + existing.restart.assert_called_once() # nothing to repair the second time From 5257094bda512290478983d925503abc593555a3 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Wed, 25 Nov 2026 22:04:14 +0100 Subject: [PATCH 41/45] fix(webui): out-of-scope person inline again; kept, no-data and spool hints; filter overview actions in view The page took only a 403 as 'not in your classes'; since the WebUI answers such a refusal with 404 it showed two toasts and an empty student page (cold recheck m1). It now recognises the error 'scope'. The browser test opens a person outside the scope for every role and requires the inline message without a toast. update-all results name instances kept on their image (N1). An instance with the log on shows 'An, aber keine Daten seit ...' or a missing spool (N2); the quarantine hint names its new place (N3). The action column of 'Filter per school' stays in view when the table scrolls sideways (m5), checked by the browser test with a long server name. --- scripts/tests/webui_ajenti_it.sh | 9 ++- scripts/tests/webui_ajenti_it/browser.py | 67 +++++++++++++++++-- webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 16 ++++- webui/lmn_squid/resources/css/dialogs.css | 9 +++ .../js/controllers/activity.controller.es | 10 ++- .../js/controllers/index.controller.es | 27 +++++++- webui/lmn_squid/resources/partial/index.html | 13 ++-- webui/tests/js/activity_check.js | 20 +++++- 8 files changed, 152 insertions(+), 19 deletions(-) diff --git a/scripts/tests/webui_ajenti_it.sh b/scripts/tests/webui_ajenti_it.sh index 6fc8832..a894a8f 100755 --- a/scripts/tests/webui_ajenti_it.sh +++ b/scripts/tests/webui_ajenti_it.sh @@ -32,6 +32,11 @@ set -e PY=/opt/linuxmuster/bin/python3 SITE=$($PY -c "import site; print(site.getsitepackages()[0])") cp -r /upstream/usr/lib/python3/dist-packages/linuxmusterTools "$SITE/" +# the control plane reads its version from the package metadata (importlib.metadata); a tree +# without an installed lmnsquid (an export, not a checkout with .venv) gets it from the changelog +VER=$(sed -n "1s/.*(\(.*\)).*/\1/p" /src/debian/changelog) +mkdir -p "$SITE/lmnsquid-$VER.dist-info" +printf "Metadata-Version: 2.1\nName: lmnsquid\nVersion: %s\n" "$VER" > "$SITE/lmnsquid-$VER.dist-info/METADATA" mkdir -p /plugins /etc/linuxmuster/webui /etc/samba /var/lib/linuxmuster /usr/share/sophomorix/devel cp /upstream/sophomorix-samba/config-devel/sophomorix.ini /usr/share/sophomorix/devel/ mkdir -p /etc/linuxmuster/sophomorix/default-school @@ -50,7 +55,9 @@ useradd -u 2001 -M dslehr01; useradd -u 3001 -M dsextra01 $PY /src/scripts/tests/webui_ajenti_it/cp_server.py > /var/tmp/cp.log 2>&1 & for i in $(seq 1 50); do $PY -c "import socket; socket.create_connection((\"127.0.0.1\", 18080))" 2>/dev/null && break; sleep 0.2; done mkdir -p /etc/linuxmuster-squid-webui && chmod 700 /etc/linuxmuster-squid-webui -printf "version: 1\nconnections:\n- name: lab\n url: http://127.0.0.1:18080\n token: it-token-0123456789abcdef0123456789\n schools: [default-school]\n" > /etc/linuxmuster-squid-webui/config.yml +# a long display name without a break opportunity (like a host name): the table of "Filter per +# school" is then wider than the dialog and scrolls sideways (browser.py checks its buttons) +printf "version: 1\nconnections:\n- name: lab\n display_name: proxygesamtschulemusterstadt.gebaeudenord.schulnetz.example\n url: http://127.0.0.1:18080\n token: it-token-0123456789abcdef0123456789\n schools: [default-school]\n" > /etc/linuxmuster-squid-webui/config.yml chmod 600 /etc/linuxmuster-squid-webui/config.yml cat > /var/tmp/ad.json < { + const out = []; + let scrolls = false; + document.querySelectorAll('dialog.lmn-squid-dialog div[style*="overflow-x"]').forEach((box) => { + if (box.offsetParent === null) { return; } + scrolls = scrolls || box.scrollWidth > box.clientWidth + 1; + const c = box.getBoundingClientRect(); + box.querySelectorAll('td.lmn-squid-sticky-action button, td:last-child button').forEach((b) => { + const r = b.getBoundingClientRect(); + if (r.right > c.right + 1 || r.left < c.left - 1) { out.push(b.innerText.trim()); } + }); + }); + if (mustScroll && !scrolls) { out.push('(the table does not scroll: nothing checked)'); } + return out; + }""" + off = page.evaluate(probe_js, False) + size = page.viewport_size + page.set_viewport_size({"width": 900, "height": 768}) + page.wait_for_timeout(400) + off += [f"{t} (900 px)" for t in page.evaluate(probe_js, True)] + page.set_viewport_size(size) + if off: + raise AssertionError(f"row buttons outside the visible area: {off}") + + def management_admin(probe): probe.step("management: servers", MGMT, expect="default-school") probe.step("management: section internet use settings", MGMT + "?section=activity") @@ -182,7 +224,7 @@ def management_admin(probe): c = "s.connections[0]" i = "s.servers[s.connections[0].name].instances[0]" a = f"({i}.activity || {{name: {i}.name, retention_days: 7}})" - for label, opener, var in [ + for entry in [ ("add connection", "s.addConnection();", "connForm"), ("edit connection", f"s.editConnection({c});", "connForm"), ("remove connection", f"s.removeConnection({c});", "removeConnDialog"), @@ -191,12 +233,17 @@ def management_admin(probe): ("create instance", f"s.createInstance({c}.name);", "instForm"), ("edit instance", f"s.editInstance({c}, {i});", "instForm"), ("delete instance", f"s.deleteInstance({c}, {i});", "deleteDialog"), - ("filter overview", "s.openFilterOverview();", "filterOverview"), + ( + "filter overview", + "s.openFilterOverview();", + "filterOverview", + actions_in_view, + ), ("own categories and sources", f"s.openOwn({c});", "own"), ("switch internet use on", f"s.askEnable({c}, {a});", "enableDialog"), ("switch internet use off", f"s.askDisable({c}, {a});", "disableDialog"), ]: - dialog(probe, label, opener, var) + dialog(probe, *entry) def management_refused(probe): @@ -244,9 +291,19 @@ def activity_views(probe, teacher=False, school=""): "internet use: student of another class refused", ACT + "?user=s6b1", allowed=(404,), + expect=NOT_YOURS, + forbid=(NO_TOAST,), ) else: probe.step("internet use: student s6b1", ACT + f"?{q}user=s6b1") + # a person outside the scope: the page's own message, no toast (cold recheck m1) + probe.step( + "internet use: person outside the scope refused", + ACT + f"?{q}user=global-admin", + allowed=(404,), + expect=NOT_YOURS, + forbid=(NO_TOAST,), + ) def main(): diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index 5c8cad1..80d0804 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -1694,8 +1694,8 @@ msgstr "Spool-Datei(en) in Quarantäne" msgid "The collector gave up on these files of the proxy (journalctl -u linuxmuster-squid-activity on the proxy host); their requests are missing in the view." msgstr "Der Sammler hat diese Dateien des Proxys aufgegeben (journalctl -u linuxmuster-squid-activity auf dem Proxy-Host); ihre Anfragen fehlen in der Ansicht." -msgid "They are in the quarantine folder of the instance's activity data; move them back into the spool to try again, or delete them." -msgstr "Sie liegen im Ordner quarantine der Aktivitätsdaten der Instanz; zum erneuten Versuch zurück in den Spool verschieben oder löschen." +msgid "They are in /var/spool/linuxmuster-squid/activity/.quarantine/ on the proxy host; move them back into the instance's spool to try again, or delete them." +msgstr "Sie liegen auf dem Proxy-Host in /var/spool/linuxmuster-squid/activity/.quarantine/; zum erneuten Versuch zurück in den Spool der Instanz verschieben oder löschen." msgid "all visible people" msgstr "alle sichtbaren Personen" @@ -1714,3 +1714,15 @@ msgstr "Person" msgid "domain" msgstr "Domain" + +msgid "Kept on their image (the maintained image is older or lacks the filter or the activity log they use):" +msgstr "Auf ihrem Image belassen (das gepflegte Image ist älter oder hat den Filter bzw. die Internetnutzung nicht, die sie verwenden):" + +msgid "On, but the spool on the proxy host is missing or not writable: restart the instance, the control plane repairs it then." +msgstr "An, aber der Spool auf dem Proxy-Host fehlt oder ist nicht beschreibbar: Instanz neu starten, die Control Plane repariert ihn dabei." + +msgid "On, but no data since it was switched on" +msgstr "An, aber noch keine Daten seit dem Einschalten" + +msgid "On, but no data since" +msgstr "An, aber keine Daten seit" diff --git a/webui/lmn_squid/resources/css/dialogs.css b/webui/lmn_squid/resources/css/dialogs.css index 52ac27f..db2e4ba 100644 --- a/webui/lmn_squid/resources/css/dialogs.css +++ b/webui/lmn_squid/resources/css/dialogs.css @@ -61,3 +61,12 @@ dialog.lmn-squid-dialog .lmn-squid-scroll-log { max-height: max(140px, calc(100vh - 330px)); overflow: auto; } + +/* The actions of a table row that scrolls sideways inside a dialog stay in view (cold check m5: + * "Filter per school" at 1366 px). */ +dialog.lmn-squid-dialog .lmn-squid-sticky-action { + position: sticky; + right: 0; + background: #fff; + box-shadow: -6px 0 6px -6px rgba(0, 0, 0, 0.3); +} diff --git a/webui/lmn_squid/resources/js/controllers/activity.controller.es b/webui/lmn_squid/resources/js/controllers/activity.controller.es index b6e45e4..ca5838f 100644 --- a/webui/lmn_squid/resources/js/controllers/activity.controller.es +++ b/webui/lmn_squid/resources/js/controllers/activity.controller.es @@ -499,6 +499,12 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ $scope.refreshDomains(); } + // A person outside the caller's classes: the WebUI answers 404 with error "scope" (a 403 + // would add Ajenti's "Security error" toast); the page says so once, inline. + function outOfScope(resp) { + return !!resp && (resp.status === 403 || resp.status === 404) && !!resp.data && resp.data.error === 'scope'; + } + function loadDay() { $scope.dayLoading = true; return $http.post(API + '/query/day', dayBody()).then(function (resp) { @@ -506,7 +512,7 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ showDay(resp.data); noteFailures(resp.data.unreachable); }, function (resp) { - if (resp.status === 403) { + if (outOfScope(resp)) { $scope.person.denied = true; } else { notify.error(errorText(resp)); @@ -530,7 +536,7 @@ angular.module('lmn.squid').controller('LMNSquidActivityController', function ($ $scope.heatUser = $scope.person.user; $scope.heat = buildHeat(resp.data.rows || [], $scope.today); }, function (resp) { - if (resp.status !== 403) { + if (!outOfScope(resp)) { notify.error(errorText(resp)); } }); diff --git a/webui/lmn_squid/resources/js/controllers/index.controller.es b/webui/lmn_squid/resources/js/controllers/index.controller.es index cc76475..22be3b2 100644 --- a/webui/lmn_squid/resources/js/controllers/index.controller.es +++ b/webui/lmn_squid/resources/js/controllers/index.controller.es @@ -382,9 +382,15 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco var failed = data.failed || (data.results || []).filter(function (r) { return r.error || r.failed_image; }).map(function (r) { return r.name; }); + // update-all never downgrades: an instance on a newer image, or one using the + // filter or the activity log the maintained image lacks, stays (cold recheck N1) + var kept = (data.results || []).filter(function (r) { return r.kept; }).map(function (r) { return r.name; }); + if (kept.length) { + notify.warning(gettext('Kept on their image (the maintained image is older or lacks the filter or the activity log they use):') + ' ' + kept.join(', ')); + } if (failed.length) { notify.warning(gettext('Failed instances:') + ' ' + failed.join(', ')); - } else { + } else if (!kept.length) { notify.success(gettext('Done.')); } $scope.loadServer(conn.name); @@ -852,6 +858,25 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco {id: 'settings', label: gettext('Settings changed')}, {id: 'delete_data', label: gettext('Data deleted')} ]; + // An instance with the log on whose data do not arrive (cold recheck N2): the spool on the + // proxy host is missing or not the control plane's (squid cannot write), or nothing came for + // long. A string (a template must not get a new object per digest); '' when all is well. + $scope.activityProblem = function (a, tz) { + if (!a || !a.enabled || !a.usage) { + return ''; + } + if (a.usage.spool_ok !== true) { + return gettext('On, but the spool on the proxy host is missing or not writable: restart the instance, the control plane repairs it then.'); + } + var nowSec = Date.now() / 1000; + var since = a.usage.last_data; + if (!since) { + var on = a.ack_at ? Date.parse(a.ack_at) / 1000 : 0; + return on && nowSec - on > 3600 ? gettext('On, but no data since it was switched on') + ' (' + $scope.timeText(on, tz) + ')' : ''; + } + return nowSec - since > 86400 ? gettext('On, but no data since') + ' ' + $scope.timeText(since, tz) : ''; + }; + // "Whose data" of an audit line, stored machine-readable by the bridge ("class 5a", // "user s5a1 domain x.example", ...), shown in German (cold check m3) $scope.auditScopeText = function (text) { diff --git a/webui/lmn_squid/resources/partial/index.html b/webui/lmn_squid/resources/partial/index.html index 822699b..ffeaaa2 100644 --- a/webui/lmn_squid/resources/partial/index.html +++ b/webui/lmn_squid/resources/partial/index.html @@ -184,6 +184,7 @@ {{a.usage.days | lmnNum}} days · {{a.usage.bytes / 1048576 | lmnNum}} MB +
{{activityProblem(a, servers[conn.name].activity.timezone)}}
{{a.usage.quarantined | lmnNum}} spool file(s) in quarantine
{{a.ack_by}}, {{a.ack_at | lmnTime:servers[conn.name].activity.timezone:'datetime'}} @@ -655,10 +656,11 @@

Delete instance {{deleteDialog.inst.name}} ({{deleteD Confirmed by {{detail.activity.ack_by}}, {{detail.activity.ack_at | lmnTime:detail.activityTz:'datetime'}}

Stored data: {{detail.activity.usage.days | lmnNum}} days · {{detail.activity.usage.bytes / 1048576 | lmnNum}} MB

+
{{activityProblem(detail.activity, detail.activityTz)}}
{{detail.activity.usage.quarantined | lmnNum}} spool file(s) in quarantine: The collector gave up on these files of the proxy (journalctl -u linuxmuster-squid-activity on the proxy host); their requests are missing in the view. - They are in the quarantine folder of the instance's activity data; move them back into the spool to try again, or delete them. + They are in /var/spool/linuxmuster-squid/activity/.quarantine/ on the proxy host; move them back into the instance's spool to try again, or delete them.
@@ -917,11 +919,12 @@

Apply the filter to other instances

Filter per school and group