From e781b72dd01ce8d734eef14ad110c89e1257df82 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 14:14:19 +0100 Subject: [PATCH 01/19] feat(controlplane): host-wide category catalog built from UT1 and HaGeZi lists lmnsquid-catalog update downloads the sources described in the packaged sources.yml (extendable in /etc/linuxmuster-squid/catalog.yml) with conditional GETs, parses them streaming (domains, hosts, wildcard, adblock, rpz, UT1 archive), sorts on disk and writes one SQLite file (domain -> category and source bit masks). A source below min_entries or a category shrinking by more than half stops the build and keeps the active catalog; the new file is checked and switched in by an atomic symlink, the previous one kept. filterdecision.py is the decision (exam mode, exceptions, protected list, categories, schedules, fail-closed) shared with the image's helper. Measured: 5.6 million domains, 195 MiB, 70 s, 44 MiB RSS plus 64 MiB for sort. --- controlplane/lmnsquid/catalog.py | 731 ++++++++++++++++++ controlplane/lmnsquid/config.py | 8 + controlplane/lmnsquid/data/ai-extra.domains | 18 + controlplane/lmnsquid/data/google-domains.txt | 192 +++++ controlplane/lmnsquid/data/protected.domains | 59 ++ controlplane/lmnsquid/data/sources.yml | 148 ++++ controlplane/lmnsquid/filterdecision.py | 283 +++++++ controlplane/pyproject.toml | 5 + controlplane/tests/conftest.py | 51 ++ controlplane/tests/test_catalog.py | 447 +++++++++++ controlplane/tests/test_filterdecision.py | 169 ++++ image/lmn_filterdecision.py | 283 +++++++ 12 files changed, 2394 insertions(+) create mode 100644 controlplane/lmnsquid/catalog.py create mode 100644 controlplane/lmnsquid/data/ai-extra.domains create mode 100644 controlplane/lmnsquid/data/google-domains.txt create mode 100644 controlplane/lmnsquid/data/protected.domains create mode 100644 controlplane/lmnsquid/data/sources.yml create mode 100644 controlplane/lmnsquid/filterdecision.py create mode 100644 controlplane/tests/test_catalog.py create mode 100644 controlplane/tests/test_filterdecision.py create mode 100644 image/lmn_filterdecision.py diff --git a/controlplane/lmnsquid/catalog.py b/controlplane/lmnsquid/catalog.py new file mode 100644 index 0000000..a0d54f9 --- /dev/null +++ b/controlplane/lmnsquid/catalog.py @@ -0,0 +1,731 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The host-wide category catalog: download the list sources, build one SQLite file (ADR-022). + +``/current.sqlite`` (a symlink to ``catalog-.sqlite``) maps every listed +domain to a bit mask of school categories and a bit mask of the sources that list it. The +directory is mounted read-only into every instance container at ``/etc/squid/catalog``; the +external ACL helper there opens the file read-only and notices a new version by itself. + +The build streams: each source is parsed line by line into ``namecategory bitsource +bit`` lines on disk, GNU ``sort`` (external merge sort, bounded buffer) orders them, and the +sorted stream is merged and inserted in order. No list is held in memory, whatever its size. + +Safety (decision 7 of the task): a source that cannot be downloaded falls back to its last +download; a source with fewer entries than its ``min_entries`` or a category that shrinks by more +than half against the active catalog stops the build, and the active catalog stays. A new file is +checked (``PRAGMA quick_check``, a lookup) before the symlink is switched atomically; the previous +version is kept for a rollback. + +Runs as ``lmnsquid-catalog update`` (systemd timer, as user lmnsquid) or started by the API +(``POST /v1/catalog/update``); one build at a time (flock). +""" + +from __future__ import annotations + +import argparse +import contextlib +import fcntl +import json +import logging +import os +import re +import resource +import sqlite3 +import subprocess +import sys +import tarfile +import tempfile +import time +import urllib.error +import urllib.request +from collections.abc import Iterable, Iterator +from dataclasses import dataclass +from importlib.metadata import PackageNotFoundError +from importlib.metadata import version as dist_version +from pathlib import Path +from typing import IO, Any + +import yaml + +from . import filterdecision + +log = logging.getLogger("lmnsquid.catalog") + +DATA_DIR = Path(__file__).parent / "data" +CURRENT = "current.sqlite" +STATUS = "status.json" +MAX_DOWNLOAD = 512 * 1024 * 1024 +MAX_AGE_DAYS = 7 +SHRINK_LIMIT = 0.5 # a category below half of its previous size stops the build +_LABEL = r"[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?" +_NAME_RE = re.compile(rf"^{_LABEL}(?:\.{_LABEL})+$") +_IPV4_RE = re.compile(r"^\d{1,3}(\.\d{1,3}){3}$") +_SOURCE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,40}$") +_CATEGORY_ID_RE = re.compile(r"^[a-z][a-z0-9_]{0,40}$") + + +class CatalogError(Exception): + """A build that must not replace the active catalog (the reason is reported).""" + + +class Busy(Exception): + """Another build holds the lock.""" + + +# --------------------------------------------------------------------------- configuration +@dataclass +class Config: + groups: list[dict[str, Any]] + categories: list[dict[str, Any]] + sources: list[dict[str, Any]] + profiles: dict[str, dict[str, Any]] + + def category(self, cat_id: str) -> dict[str, Any] | None: + return next((c for c in self.categories if c["id"] == cat_id), None) + + @property + def category_ids(self) -> list[str]: + return [c["id"] for c in self.categories] + + @property + def fail_closed(self) -> set[str]: + return {c["id"] for c in self.categories if c.get("fail_closed")} + + +def load_config(admin_file: str | None = None) -> Config: + """The packaged ``sources.yml`` with the admin's ``catalog.yml`` laid over it. + + Admin keys: ``sources`` (an entry with a known id replaces it, a new id is added), + ``disable_sources`` (ids), ``categories`` (new ones or new labels), ``profiles``. + """ + data = yaml.safe_load((DATA_DIR / "sources.yml").read_text(encoding="utf-8")) + extra: dict[str, Any] = {} + if admin_file and os.path.isfile(admin_file): + loaded = yaml.safe_load(Path(admin_file).read_text(encoding="utf-8")) or {} + if not isinstance(loaded, dict): + raise CatalogError(f"{admin_file}: not a mapping") + extra = loaded + categories = {c["id"]: dict(c) for c in data["categories"]} + for cat in extra.get("categories") or []: + categories[str(cat["id"])] = {**categories.get(str(cat["id"]), {}), **cat} + sources = {s["id"]: dict(s) for s in data["sources"]} + for src in extra.get("sources") or []: + sources[str(src["id"])] = dict(src) + for sid in extra.get("disable_sources") or []: + sources.pop(str(sid), None) + profiles = {**data.get("profiles", {}), **(extra.get("profiles") or {})} + config = Config( + list(data["groups"]), list(categories.values()), list(sources.values()), profiles + ) + _validate(config) + return config + + +def source_targets(src: dict[str, Any]) -> list[str]: + """The school categories a source feeds.""" + return list((src.get("map") or {}).values()) or [src.get("category")] + + +def _validate(config: Config) -> None: + ids = config.category_ids + if len(ids) > 62: + raise CatalogError("at most 62 categories") + groups = {g["id"] for g in config.groups} + for cat in config.categories: + if not _CATEGORY_ID_RE.match(str(cat.get("id", ""))) or cat.get("group") not in groups: + raise CatalogError(f"invalid category {cat!r}") + if len(config.sources) > 62: + raise CatalogError("at most 62 sources") + for src in config.sources: + if not _SOURCE_ID_RE.match(str(src.get("id", ""))): + raise CatalogError(f"invalid source id {src.get('id')!r}") + for target in source_targets(src): + if target not in ids: + raise CatalogError(f"source {src['id']}: unknown category {target!r}") + if src.get("format") not in ("ut1-tar", "domains", "adblock", "rpz"): + raise CatalogError(f"source {src['id']}: unknown format {src.get('format')!r}") + if bool(src.get("url")) == bool(src.get("path")): + raise CatalogError(f"source {src['id']}: needs exactly one of url and path") + if src.get("url") and not str(src["url"]).startswith("https://"): + raise CatalogError(f"source {src['id']}: only https:// URLs") + + +# ----------------------------------------------------------------------------- parsing +def normalize_name(raw: str) -> str | None: + """One list entry as a lower-case ASCII domain with at least two labels, or ``None``. + + IP addresses and single labels are dropped: a single label (``com``) would put a whole + top-level domain into a category. + """ + name = raw.strip().lower().strip(".") + if not name or len(name) > 253: + return None + if not name.isascii(): + try: + name = name.encode("idna").decode("ascii") + except UnicodeError: + return None + if _IPV4_RE.match(name) or not _NAME_RE.match(name): + return None + return name + + +def parse_line(line: str, fmt: str) -> str | None: + """The domain a line of a ``domains``/``adblock``/``rpz`` list names, else ``None``.""" + text = line.strip() + if not text or text[0] in "#!;": + return None + if fmt == "adblock": + if text.startswith("@@") or not text.startswith("||"): + return None + text = text[2:].split("^", 1)[0] + if "/" in text or "*" in text: + return None + return normalize_name(text) + if fmt == "rpz": + parts = text.split() + if len(parts) < 3 or parts[0].startswith("$") or parts[0] == "@": + return None + if parts[1].upper() != "CNAME" or parts[2] not in (".", "*."): + if not (len(parts) > 3 and parts[2].upper() == "CNAME" and parts[3] in (".", "*.")): + return None + return normalize_name(parts[0].removeprefix("*.")) + # domains: tolerant of hosts lines, wildcards, adblock style and inline comments + text = text.split("#", 1)[0].strip() + parts = text.split() + if not parts: + return None + if len(parts) >= 2 and (parts[0] in ("0.0.0.0", "127.0.0.1", "::", "::1")): + text = parts[1] + else: + text = parts[0] + if text.startswith("||"): + text = text[2:].split("^", 1)[0] + return normalize_name(text.removeprefix("*.")) + + +def iter_lines(stream: IO[bytes]) -> Iterator[str]: + for raw in stream: + yield raw.decode("utf-8", errors="replace") + + +def iter_source(src: dict[str, Any], path: str) -> Iterator[tuple[str, str]]: + """``(domain, category id)`` of every entry of a downloaded source.""" + if src["format"] == "ut1-tar": + mapping: dict[str, str] = src["map"] + with tarfile.open(path, "r|gz") as tar: + for member in tar: + parts = member.name.split("/") + if not member.isfile() or len(parts) != 3 or parts[2] != "domains": + continue + category = mapping.get(parts[1]) + if category is None: + continue + stream = tar.extractfile(member) + if stream is None: + continue + for line in iter_lines(stream): + name = parse_line(line, "domains") + if name: + yield name, category + return + with open(path, "rb") as fh: + for line in iter_lines(fh): + name = parse_line(line, src["format"]) + if name: + yield name, src["category"] + + +# ----------------------------------------------------------------------------- download +class _HttpsOnly(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001 + if not str(newurl).startswith("https://"): + raise urllib.error.HTTPError(newurl, code, "redirect away from https", headers, fp) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +def _user_agent() -> str: + try: + return f"linuxmuster-squid/{dist_version('lmnsquid')}" + except PackageNotFoundError: + return "linuxmuster-squid" + + +def fetch(src: dict[str, Any], cache_dir: Path, state: dict[str, Any]) -> tuple[str, str]: + """Download ``src`` into the cache (conditional GET); return (path, how). + + ``how`` is ``downloaded``, ``unchanged`` (304) or ``cached: `` (download failed, + the previous one is used). Raises :class:`CatalogError` when there is nothing to use. + """ + if src.get("path"): + path = src["path"] + return (path if os.path.isabs(path) else str(DATA_DIR / path)), "local" + target = cache_dir / f"{src['id']}.download" + known = state.get(src["id"]) or {} + request = urllib.request.Request(src["url"], headers={"User-Agent": _user_agent()}) + if target.is_file() and known.get("url") == src["url"]: + if known.get("etag"): + request.add_header("If-None-Match", known["etag"]) + if known.get("last_modified"): + request.add_header("If-Modified-Since", known["last_modified"]) + opener = urllib.request.build_opener(_HttpsOnly()) + try: + with opener.open(request, timeout=120) as resp: + fd, tmp = tempfile.mkstemp(dir=cache_dir, prefix=f".{src['id']}.", suffix=".tmp") + size = 0 + try: + with os.fdopen(fd, "wb") as out: + while chunk := resp.read(1 << 20): + size += len(chunk) + if size > MAX_DOWNLOAD: + raise CatalogError(f"{src['id']}: larger than {MAX_DOWNLOAD} bytes") + out.write(chunk) + os.replace(tmp, target) + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp) + state[src["id"]] = { + "url": src["url"], + "etag": resp.headers.get("ETag"), + "last_modified": resp.headers.get("Last-Modified"), + "fetched": time.time(), + } + return str(target), "downloaded" + except urllib.error.HTTPError as exc: + if exc.code == 304 and target.is_file(): + known["checked"] = time.time() + return str(target), "unchanged" + error = f"HTTP {exc.code}" + except (OSError, urllib.error.URLError) as exc: + error = str(getattr(exc, "reason", exc)) + if target.is_file() and known.get("url") == src["url"]: + return str(target), f"cached: {error}" + raise CatalogError(f"{src['id']}: download failed ({error}) and no earlier download") + + +# ----------------------------------------------------------------------------- building +def _previous_counts(catalog_dir: Path) -> dict[str, int]: + current = catalog_dir / CURRENT + if not current.exists(): + return {} + try: + db = sqlite3.connect(f"file:{current}?mode=ro", uri=True) + try: + return {str(i): int(n) for i, n in db.execute("SELECT id, count FROM cats")} + finally: + db.close() + except sqlite3.Error: + return {} + + +def _merge(sorted_file: str) -> Iterator[tuple[str, int, int]]: + name: str | None = None + cats = srcs = 0 + with open(sorted_file, encoding="ascii") as fh: + for line in fh: + n, c, s = line.rstrip("\n").split("\t") + if n != name: + if name is not None: + yield name, cats, srcs + name, cats, srcs = n, 0, 0 + cats |= 1 << int(c) + srcs |= 1 << int(s) + if name is not None: + yield name, cats, srcs + + +def build_file( + config: Config, inputs: Iterable[tuple[dict[str, Any], str]], target: Path, work: Path +) -> dict[str, Any]: + """Write the catalog of ``inputs`` (source, downloaded path) to ``target``; return counts.""" + bits = {cat_id: i for i, cat_id in enumerate(config.category_ids)} + unsorted = work / "entries.tsv" + source_rows: list[tuple[str, int, str, str, str, int]] = [] + with open(unsorted, "w", encoding="ascii") as out: + for sbit, (src, path) in enumerate(inputs): + n = 0 + for name, category in iter_source(src, path): + out.write(f"{name}\t{bits[category]}\t{sbit}\n") + n += 1 + if n < int(src.get("min_entries", 1)): + raise CatalogError( + f"{src['id']}: {n} entries, fewer than min_entries {src.get('min_entries')}" + ) + source_rows.append( + (src["id"], sbit, src["name"], src["license"], src.get("url") or "", n) + ) + sorted_file = work / "entries.sorted" + subprocess.run( + [ + "sort", + "-S", + "64M", + "-T", + str(work), + "-t", + "\t", + "-k1,1", + "-o", + str(sorted_file), + str(unsorted), + ], + check=True, + env={"LC_ALL": "C", "PATH": "/usr/bin:/bin"}, + ) + unsorted.unlink() + counts = dict.fromkeys(bits, 0) + db = sqlite3.connect(target) + try: + db.executescript( + "PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-16000;" + "CREATE TABLE meta(k TEXT PRIMARY KEY, v TEXT);" + "CREATE TABLE cats(id TEXT PRIMARY KEY, bit INTEGER, label TEXT, grp TEXT," + " fail_closed INTEGER, count INTEGER);" + "CREATE TABLE srcs(id TEXT PRIMARY KEY, bit INTEGER, name TEXT, license TEXT," + " url TEXT, count INTEGER);" + "CREATE TABLE d(n TEXT PRIMARY KEY, c INTEGER, s INTEGER) WITHOUT ROWID;" + ) + + def rows() -> Iterator[tuple[str, int, int]]: + for name, cats, srcs in _merge(str(sorted_file)): + for cat_id, bit in bits.items(): + if cats & (1 << bit): + counts[cat_id] += 1 + yield name, cats, srcs + + db.executemany("INSERT INTO d VALUES (?, ?, ?)", rows()) + total = db.execute("SELECT count(*) FROM d").fetchone()[0] + db.executemany( + "INSERT INTO cats VALUES (?, ?, ?, ?, ?, ?)", + [ + ( + c["id"], + bits[c["id"]], + c["label"], + c["group"], + int(bool(c.get("fail_closed"))), + counts[c["id"]], + ) + for c in config.categories + ], + ) + db.executemany("INSERT INTO srcs VALUES (?, ?, ?, ?, ?, ?)", source_rows) + db.executemany( + "INSERT INTO meta VALUES (?, ?)", + [ + ("format", str(filterdecision.FORMAT)), + ("built", str(time.time())), + ("domains", str(total)), + ("builder", _user_agent()), + ], + ) + db.commit() + if db.execute("PRAGMA quick_check").fetchone()[0] != "ok": + raise CatalogError("the new catalog failed the SQLite quick_check") + finally: + db.close() + sorted_file.unlink(missing_ok=True) + return {"domains": total, "categories": counts} + + +def check_shrink(new: dict[str, int], old: dict[str, int]) -> None: + for cat_id, before in old.items(): + after = new.get(cat_id, 0) + if before >= 100 and after < before * SHRINK_LIMIT: + raise CatalogError( + f"category {cat_id} would shrink from {before} to {after} entries " + f"(more than {int((1 - SHRINK_LIMIT) * 100)} %): download suspicious, " + "the active catalog stays" + ) + + +def publish(catalog_dir: Path, built: Path) -> Path: + """Move ``built`` into place and switch ``current.sqlite`` atomically; keep one previous.""" + stamp = time.strftime("%Y%m%d%H%M%S") + final = catalog_dir / f"catalog-{stamp}.sqlite" + os.chmod(built, 0o644) + os.replace(built, final) + link_tmp = catalog_dir / f".{CURRENT}.tmp" + link_tmp.unlink(missing_ok=True) + os.symlink(final.name, link_tmp) + os.replace(link_tmp, catalog_dir / CURRENT) + versions = sorted(catalog_dir.glob("catalog-*.sqlite")) + for old in versions[:-2]: + old.unlink(missing_ok=True) + return final + + +def write_protected(catalog_dir: Path, admin_file: str | None) -> list[str]: + """Merge the packaged and the admin's protected list into the catalog directory.""" + names: set[str] = set() + for path in [str(DATA_DIR / "protected.domains"), admin_file]: + if path: + names |= { + n for n in (normalize_name(x) for x in filterdecision.read_domains(path)) if n + } + content = "".join(f"{n}\n" for n in sorted(names)) + target = catalog_dir / "protected.domains" + catalog_dir.mkdir(parents=True, exist_ok=True) + if target.is_file() and target.read_text(encoding="utf-8") == content: + return sorted(names) + fd, tmp = tempfile.mkstemp(dir=catalog_dir, prefix=".protected.", suffix=".tmp") + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(content) + os.chmod(tmp, 0o644) + os.replace(tmp, target) + return sorted(names) + + +# ----------------------------------------------------------------------------- the run +@dataclass +class Paths: + catalog_dir: Path + cache_dir: Path + admin_config: str | None = None + protected_file: str | None = None + catalog_url: str | None = None + + +def _write_json(path: Path, data: dict[str, Any]) -> None: + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(data, fh, indent=1) + os.chmod(tmp, 0o644) + os.replace(tmp, path) + + +@contextlib.contextmanager +def build_lock(cache_dir: Path) -> Iterator[None]: + cache_dir.mkdir(parents=True, exist_ok=True) + with open(cache_dir / "build.lock", "w") as fh: + try: + fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + raise Busy("a catalog build is already running") from None + yield + + +def is_building(cache_dir: Path) -> bool: + try: + with build_lock(cache_dir): + return False + except Busy: + return True + + +def update(paths: Paths) -> dict[str, Any]: + """One complete update; the result is also written to ``/status.json``.""" + started = time.time() + with build_lock(paths.cache_dir): + status_file = paths.cache_dir / STATUS + previous = read_json(status_file) + _write_json(status_file, {**previous, "state": "running", "started": started}) + result: dict[str, Any] = {"started": started} + try: + paths.catalog_dir.mkdir(parents=True, exist_ok=True) + write_protected(paths.catalog_dir, paths.protected_file) + if paths.catalog_url: + result.update(_update_from_mirror(paths)) + else: + result.update(_update_from_sources(paths)) + result["state"] = "ok" + result["last_success"] = time.time() + except Exception as exc: # noqa: BLE001 - every failure keeps the active catalog + log.error("catalog update failed: %s", exc) + result["state"] = "failed" + result["error"] = str(exc) + result["last_success"] = previous.get("last_success") + result["finished"] = time.time() + result["duration"] = round(result["finished"] - started, 1) + result["peak_rss_kib"] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + result["peak_rss_children_kib"] = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss + _write_json(status_file, result) + return result + + +def _update_from_sources(paths: Paths) -> dict[str, Any]: + config = load_config(paths.admin_config) + state_file = paths.cache_dir / "sources-state.json" + state = read_json(state_file) + inputs: list[tuple[dict[str, Any], str]] = [] + fetched: dict[str, str] = {} + for src in config.sources: + path, how = fetch(src, paths.cache_dir, state) + inputs.append((src, path)) + fetched[src["id"]] = how + _write_json(state_file, state) + with tempfile.TemporaryDirectory(dir=paths.cache_dir, prefix="build.") as work: + target = Path(work) / "catalog.sqlite" + built = build_file(config, inputs, target, Path(work)) + check_shrink(built["categories"], _previous_counts(paths.catalog_dir)) + filterdecision.Catalog(str(target)).close() # opens like the helper does + final = publish(paths.catalog_dir, target) + return {**built, "file": final.name, "size": final.stat().st_size, "sources": fetched} + + +def _update_from_mirror(paths: Paths) -> dict[str, Any]: + assert paths.catalog_url + src = {"id": "mirror", "url": paths.catalog_url} + state = read_json(paths.cache_dir / "sources-state.json") + path, how = fetch(src, paths.cache_dir, state) + _write_json(paths.cache_dir / "sources-state.json", state) + with tempfile.TemporaryDirectory(dir=paths.cache_dir, prefix="build.") as work: + target = Path(work) / "catalog.sqlite" + with open(path, "rb") as src_fh, open(target, "wb") as dst: + while chunk := src_fh.read(1 << 20): + dst.write(chunk) + try: + cat = filterdecision.Catalog(str(target)) + cat.close() + db = sqlite3.connect(f"file:{target}?mode=ro", uri=True) + counts = {str(i): int(n) for i, n in db.execute("SELECT id, count FROM cats")} + ok = db.execute("PRAGMA quick_check").fetchone()[0] == "ok" + db.close() + except (sqlite3.Error, ValueError) as exc: + raise CatalogError(f"catalog from {paths.catalog_url} unusable: {exc}") from None + if not ok: + raise CatalogError(f"catalog from {paths.catalog_url} failed the quick_check") + check_shrink(counts, _previous_counts(paths.catalog_dir)) + final = publish(paths.catalog_dir, target) + return { + "categories": counts, + "file": final.name, + "size": final.stat().st_size, + "sources": {"mirror": how}, + } + + +def read_json(path: Path) -> dict[str, Any]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def status(paths: Paths, config: Config | None = None) -> dict[str, Any]: + """Everything a client shows about the catalog: age, sizes, sources, licences, last run.""" + run = read_json(paths.cache_dir / STATUS) + building = is_building(paths.cache_dir) + if run.get("state") == "running" and not building: + run["state"] = "failed" + run["error"] = "the build ended without a result (killed?)" + info: dict[str, Any] = { + "available": False, + "building": building, + "last_run": run, + "categories": [], + "sources": [], + "groups": [], + "profiles": {}, + } + if config is not None: + info["groups"] = config.groups + info["profiles"] = config.profiles + counts: dict[str, int] = {} + current = paths.catalog_dir / CURRENT + try: + cat = filterdecision.Catalog(str(current)) + try: + counts = {str(i): int(n) for i, n in cat.db.execute("SELECT id, count FROM cats")} + src_rows = list(cat.db.execute("SELECT id, name, license, url, count FROM srcs")) + domains = cat.db.execute("SELECT v FROM meta WHERE k='domains'").fetchone() + finally: + cat.close() + age = (time.time() - cat.built) / 86400 + info.update( + available=True, + built=cat.built, + age_days=round(age, 2), + old=age > MAX_AGE_DAYS, + domains=int(domains[0]) if domains else None, + file=os.path.basename(os.path.realpath(current)), + size=current.stat().st_size, + sources=[ + {"id": s, "name": n, "license": lic, "url": u, "count": c} + for s, n, lic, u, c in src_rows + ], + ) + except (OSError, sqlite3.Error, ValueError) as exc: + info["error"] = "no catalog yet" if not current.exists() else f"catalog unusable: {exc}" + if config is not None: + info["categories"] = [ + { + **c, + "count": counts.get(c["id"]), + "sources": [ + {"id": s["id"], "name": s["name"], "license": s["license"]} + for s in config.sources + if c["id"] in source_targets(s) + ], + } + for c in config.categories + ] + if not info["sources"] and config is not None: + info["sources"] = [ + { + "id": s["id"], + "name": s["name"], + "license": s["license"], + "url": s.get("url") or "", + "count": None, + } + for s in config.sources + ] + return info + + +def catalog_needed(blocklists_dir: Path, catalog_dir: Path) -> bool: + """Whether the timer should build: a catalog exists, or an instance has categories.""" + if (catalog_dir / CURRENT).exists(): + return True + for path in blocklists_dir.glob("*/filter.json"): + data = read_json(path) + if data.get("categories"): + return True + return False + + +def paths_from_settings(settings: Any) -> Paths: + return Paths( + catalog_dir=Path(settings.catalog_dir), + cache_dir=Path(settings.catalog_cache_dir), + admin_config=settings.catalog_config, + protected_file=settings.protected_file, + catalog_url=settings.catalog_url, + ) + + +def main(argv: list[str] | None = None) -> int: + """``lmnsquid-catalog update [--if-needed]``: the timer's and the API's entry point.""" + from .config import load_settings + + parser = argparse.ArgumentParser(prog="lmnsquid-catalog") + parser.add_argument("command", choices=["update", "status"]) + parser.add_argument( + "--if-needed", + action="store_true", + help="do nothing while no instance uses categories and no catalog exists", + ) + args = parser.parse_args(argv) + logging.basicConfig(level=logging.INFO, format="%(message)s") + settings = load_settings() + paths = paths_from_settings(settings) + if args.command == "status": + print(json.dumps(status(paths), indent=1)) + return 0 + if args.if_needed and not catalog_needed(Path(settings.blocklists_dir), paths.catalog_dir): + log.info("no instance uses filter categories and there is no catalog: nothing to do") + return 0 + try: + result = update(paths) + except Busy as exc: + log.error("%s", exc) + return 75 + print(json.dumps(result, indent=1)) + return 0 if result["state"] == "ok" else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/controlplane/lmnsquid/config.py b/controlplane/lmnsquid/config.py index 7f0859f..b722e97 100644 --- a/controlplane/lmnsquid/config.py +++ b/controlplane/lmnsquid/config.py @@ -26,6 +26,14 @@ class Settings(BaseSettings): instances_dir: str = "/etc/linuxmuster-squid/instances" secrets_dir: str = "/etc/linuxmuster-squid/secrets" blocklists_dir: str = "/etc/linuxmuster-squid/blocklists" # /blocked.domains per instance + # Category filter (ADR-022): the catalog (mounted read-only into every container), the + # downloads and build state (never mounted), the admin's additions. + catalog_dir: str = "/var/lib/linuxmuster-squid/catalog" + catalog_cache_dir: str = "/var/lib/linuxmuster-squid/catalog-cache" + catalog_config: str = "/etc/linuxmuster-squid/catalog.yml" + protected_file: str = "/etc/linuxmuster-squid/protected.domains" + catalog_url: str | None = None # a finished catalog from an internal mirror instead + filter_timezone: str | None = None # schedules; None = the host's /etc/timezone docker_host: str | None = None bind_host: str = "127.0.0.1" bind_port: int = 8080 diff --git a/controlplane/lmnsquid/data/ai-extra.domains b/controlplane/lmnsquid/data/ai-extra.domains new file mode 100644 index 0000000..82065f4 --- /dev/null +++ b/controlplane/lmnsquid/data/ai-extra.domains @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Host names of AI services that UT1 `ai` does not cover as a whole domain (2026-11-24). Only +# names: a path such as deepl.com/write cannot be filtered without decrypting HTTPS, and AI +# features inside allowed services (Copilot in Microsoft 365, Gemini in Google Workspace, +# AI answers in Google search) cannot be told apart by name. +chat.openai.com +api.openai.com +chat.mistral.ai +le-chat.mistral.ai +copilot.cloud.microsoft +gemini.google +aistudio.google.com +notebooklm.google.com +meta.ai +chat.deepseek.com +chat.qwen.ai diff --git a/controlplane/lmnsquid/data/google-domains.txt b/controlplane/lmnsquid/data/google-domains.txt new file mode 100644 index 0000000..fa021f5 --- /dev/null +++ b/controlplane/lmnsquid/data/google-domains.txt @@ -0,0 +1,192 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Google search domains for SafeSearch (ADR-022), from https://www.google.com/supported_domains +# (fetched 2026-11-24). Updated with releases; squid hosts_file needs exact names. +google.com +google.ad +google.ae +google.com.af +google.com.ag +google.al +google.am +google.co.ao +google.com.ar +google.as +google.at +google.com.au +google.az +google.ba +google.com.bd +google.be +google.bf +google.bg +google.com.bh +google.bi +google.bj +google.com.bn +google.com.bo +google.com.br +google.bs +google.bt +google.co.bw +google.by +google.com.bz +google.ca +google.cd +google.cf +google.cg +google.ch +google.ci +google.co.ck +google.cl +google.cm +google.cn +google.com.co +google.co.cr +google.com.cu +google.cv +google.com.cy +google.cz +google.de +google.dj +google.dk +google.dm +google.com.do +google.dz +google.com.ec +google.ee +google.com.eg +google.es +google.com.et +google.fi +google.com.fj +google.fm +google.fr +google.ga +google.ge +google.gg +google.com.gh +google.com.gi +google.gl +google.gm +google.gr +google.com.gt +google.gy +google.com.hk +google.hn +google.hr +google.ht +google.hu +google.co.id +google.ie +google.co.il +google.im +google.co.in +google.iq +google.is +google.it +google.je +google.com.jm +google.jo +google.co.jp +google.co.ke +google.com.kh +google.ki +google.kg +google.co.kr +google.com.kw +google.kz +google.la +google.com.lb +google.li +google.lk +google.co.ls +google.lt +google.lu +google.lv +google.com.ly +google.co.ma +google.md +google.me +google.mg +google.mk +google.ml +google.com.mm +google.mn +google.com.mt +google.mu +google.mv +google.mw +google.com.mx +google.com.my +google.co.mz +google.com.na +google.com.ng +google.com.ni +google.ne +google.nl +google.no +google.com.np +google.nr +google.nu +google.co.nz +google.com.om +google.com.pa +google.com.pe +google.com.pg +google.com.ph +google.com.pk +google.pl +google.pn +google.com.pr +google.ps +google.pt +google.com.py +google.com.qa +google.ro +google.ru +google.rw +google.com.sa +google.com.sb +google.sc +google.se +google.com.sg +google.sh +google.si +google.sk +google.com.sl +google.sn +google.so +google.sm +google.sr +google.st +google.com.sv +google.td +google.tg +google.co.th +google.com.tj +google.tl +google.tm +google.tn +google.to +google.com.tr +google.tt +google.com.tw +google.co.tz +google.com.ua +google.co.ug +google.co.uk +google.com.uy +google.co.uz +google.com.vc +google.co.ve +google.co.vi +google.com.vn +google.vu +google.ws +google.rs +google.co.za +google.co.zm +google.co.zw +google.cat diff --git a/controlplane/lmnsquid/data/protected.domains b/controlplane/lmnsquid/data/protected.domains new file mode 100644 index 0000000..a46230e --- /dev/null +++ b/controlplane/lmnsquid/data/protected.domains @@ -0,0 +1,59 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Never blocked by a CATEGORY (ADR-022): a name here and its subdomains pass the category filter +# whatever a downloaded list says. The instance's own blocklist and the exam mode still apply. +# Extend it in /etc/linuxmuster-squid/protected.domains (same format); both are merged into +# /var/lib/linuxmuster-squid/catalog/protected.domains on every catalog update and filter change. +# Sources: Microsoft "Manage connection endpoints for Windows 11 Enterprise" (2026-06-16) and +# "Microsoft 365 URLs and IP address ranges", Google Workspace for Education / YouTube admin help, +# work/linuxmuster-squid/recherche-filterlisten.md section 2.3. + +# linuxmuster.net, edulution, IServ +linuxmuster.net +edulution.io +iserv.de + +# Windows Update, Delivery Optimization, activation, Defender, root certificates +update.microsoft.com +windowsupdate.com +delivery.mp.microsoft.com +prod.do.dsp.mp.microsoft.com +tsfe.trafficshaping.dsp.mp.microsoft.com +licensing.mp.microsoft.com +wdcp.microsoft.com +smartscreen-prod.microsoft.com +definitionupdates.microsoft.com +login.live.com + +# Microsoft 365 / Teams (core endpoints, "Optimize" and "Allow") +login.microsoftonline.com +login.microsoft.com +office.com +office.net +office365.com +outlook.office.com +outlook.office365.com +sharepoint.com +onedrive.com +teams.microsoft.com +lync.com +microsoftonline.com + +# Google Workspace for Education; YouTube stays reachable (Restricted Mode through SafeSearch) +accounts.google.com +googleapis.com +gstatic.com +youtube.com +ytimg.com +googlevideo.com +youtubeeducation.com + +# Certificate status (OCSP/CRL) of the big CAs +ocsp.digicert.com +crl3.digicert.com +crl4.digicert.com +lencr.org +ocsp.sectigo.com +ocsp.globalsign.com +ocsp.pki.goog diff --git a/controlplane/lmnsquid/data/sources.yml b/controlplane/lmnsquid/data/sources.yml new file mode 100644 index 0000000..786d4d3 --- /dev/null +++ b/controlplane/lmnsquid/data/sources.yml @@ -0,0 +1,148 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Category catalog of the filter (ADR-022): the school categories offered, the list sources they +# are built from and the two profiles. The package ships no list content, only this description; +# `lmnsquid catalog update` downloads the sources on the proxy host. An admin extends or overrides +# it in /etc/linuxmuster-squid/catalog.yml (same keys; sources with the same id replace these, +# `disable_sources: [id, ...]` drops some). Basis: work/linuxmuster-squid/recherche-filterlisten.md +# (2026-11-24), section 2.1. +# +# Category ids are stable (they are stored per instance in filter.json); bits are given at build +# time. fail_closed: requests are refused while the catalog is missing or broken and such a +# category is active (youth protection, decision 7 of the task). + +groups: + - {id: youth, label: "Jugendschutz"} + - {id: security, label: "Sicherheit"} + - {id: bypass, label: "Umgehung"} + - {id: ads, label: "Werbung und Tracking"} + - {id: telemetry, label: "Telemetrie (je Hersteller)"} + - {id: distraction, label: "Ablenkung"} + - {id: misc, label: "Weitere"} + +categories: + - {id: porn, group: youth, label: "Pornografie", fail_closed: true} + - {id: gambling, group: youth, label: "Glücksspiel", fail_closed: true} + - {id: violence, group: youth, label: "Gewalt, Hass und Extremismus", fail_closed: true} + - {id: drugs, group: youth, label: "Drogen", fail_closed: true} + - {id: dating, group: youth, label: "Dating", fail_closed: true} + - {id: security, group: security, label: "Malware und Phishing"} + - {id: vpn_proxy, group: bypass, label: "VPN, Proxys und Anonymisierer"} + - {id: doh, group: bypass, label: "DNS-over-HTTPS-Resolver"} + - {id: nosafesearch, group: bypass, label: "Suchmaschinen ohne SafeSearch"} + - {id: ads, group: ads, label: "Werbung und Tracking"} + - {id: telemetry_microsoft, group: telemetry, label: "Telemetrie Microsoft (Windows, Office)"} + - {id: telemetry_apple, group: telemetry, label: "Telemetrie Apple"} + - {id: telemetry_amazon, group: telemetry, label: "Telemetrie Amazon"} + - {id: telemetry_samsung, group: telemetry, label: "Telemetrie Samsung"} + - {id: telemetry_huawei, group: telemetry, label: "Telemetrie Huawei"} + - {id: telemetry_xiaomi, group: telemetry, label: "Telemetrie Xiaomi"} + - {id: telemetry_tiktok, group: telemetry, label: "Telemetrie TikTok"} + - {id: social, group: distraction, label: "Soziale Netzwerke"} + - {id: games, group: distraction, label: "Spiele"} + - {id: chat, group: distraction, label: "Chat und Messenger"} + - {id: streaming, group: distraction, label: "Streaming und Video"} + - {id: warez, group: misc, label: "Downloads, Warez und Filehoster"} + - {id: ai, group: misc, label: "KI-Dienste"} + - {id: cheating, group: misc, label: "Prüfungsbetrug"} + +# format: ut1-tar (UT1 archive, `map` from UT1 category to school category) | domains (one name +# per line; also accepts hosts lines, `*.name`, `||name^` and leading dots) | adblock | rpz. +# Every entry means the domain and all its subdomains. min_entries: a download with fewer +# entries is refused (the previous catalog stays). +hagezi: &hagezi + name: "HaGeZi DNS Blocklists" + license: "GPL-3.0" + homepage: "https://github.com/hagezi/dns-blocklists" + format: domains + +sources: + - id: ut1 + name: "UT1 Université Toulouse Capitole" + license: "CC BY-SA 4.0" + homepage: "https://dsi.ut-capitole.fr/blacklists/" + url: "https://dsi.ut-capitole.fr/blacklists/download/blacklists.tar.gz" + format: ut1-tar + min_entries: 1000000 + map: + adult: porn + lingerie: porn + gambling: gambling + agressif: violence + sect: violence + dangerous_material: violence + drogue: drugs + dating: dating + malware: security + phishing: security + cryptojacking: security + stalkerware: security + ddos: security + vpn: vpn_proxy + redirector: vpn_proxy + residential-proxies: vpn_proxy + doh: doh + social_networks: social + games: games + chat: chat + audio-video: streaming + warez: warez + filehosting: warez + download: warez + ai: ai + tricheur: cheating + - {<<: *hagezi, id: hagezi-nsfw, category: porn, min_entries: 10000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/nsfw-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-gambling, category: gambling, min_entries: 10000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/gambling.medium-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-tif, category: security, min_entries: 50000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/tif.medium-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-bypass, category: vpn_proxy, min_entries: 1000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/doh-vpn-proxy-bypass-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-doh, category: doh, min_entries: 500, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/doh-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-nosafesearch, category: nosafesearch, min_entries: 20, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/nosafesearch-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-light, category: ads, min_entries: 10000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/light-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-microsoft, category: telemetry_microsoft, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.winoffice-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-apple, category: telemetry_apple, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.apple-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-amazon, category: telemetry_amazon, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.amazon-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-samsung, category: telemetry_samsung, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.samsung-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-huawei, category: telemetry_huawei, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.huawei-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-xiaomi, category: telemetry_xiaomi, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.xiaomi-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-tiktok, category: telemetry_tiktok, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.tiktok-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-social, category: social, min_entries: 500, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/social-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-antipiracy, category: warez, min_entries: 1000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/anti.piracy-onlydomains.txt"} + # Host names of AI services UT1 `ai` does not name (paths such as deepl.com/write cannot be + # filtered without decrypting); maintained in the package. + - id: lmn-ai + name: "linuxmuster-squid (Ergänzung KI-Dienste)" + license: "GPL-3.0-or-later" + homepage: "https://github.com/faircomp/linuxmuster-squid" + path: "ai-extra.domains" + format: domains + category: ai + min_entries: 1 + +# Proposed when an instance is set up ("Vorlage anwenden"); never applied automatically to an +# existing instance (an upgrade changes nothing). +profiles: + students: + label: "Schüler" + categories: [porn, gambling, violence, drugs, dating, security, vpn_proxy, doh, nosafesearch] + safesearch: {google: true, youtube: strict, bing: true, duckduckgo: true} + teachers: + label: "Lehrkräfte" + categories: [security, vpn_proxy, doh] + safesearch: {google: false, youtube: "off", bing: false, duckduckgo: false} diff --git a/controlplane/lmnsquid/filterdecision.py b/controlplane/lmnsquid/filterdecision.py new file mode 100644 index 0000000..0b0b5f3 --- /dev/null +++ b/controlplane/lmnsquid/filterdecision.py @@ -0,0 +1,283 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The filter decision for one host name: the same code in the control plane and the proxy. + +Standard library only. ``image/lmn_filterdecision.py`` is a byte-identical copy that the +image's external ACL helper (``image/lmn-filter-acl``) imports; ``tests/test_filterdecision.py`` +fails when the two differ, so the "why is X blocked?" answer of the control plane is the +decision squid makes. + +Inputs, all files (ADR-022): + +* the instance's ``filter.json`` (written by the control plane only): active categories, + schedules per category, the categories that fail closed, the time zone and the exam mode; +* the instance's ``allowed.domains`` (the admin's exceptions) and the host-wide + ``protected.domains`` ("never block" for categories); +* the host-wide catalog ``current.sqlite`` (domain -> category bit mask, source bit mask). + +Order: exam mode (only its own list) -> exceptions -> protected list -> categories. The own +blocklist (``blocked.domains``) is not decided here: squid matches it natively, as before. +""" + +from __future__ import annotations + +import datetime +import json +import os +import sqlite3 +from dataclasses import dataclass, field +from typing import Any + +FORMAT = 1 +DAYS = ("mo", "tu", "we", "th", "fr", "sa", "su") +# Decisions. BLOCK_* block the request; the others let it pass to the rest of squid's chain. +EXAM = "exam" +EXAM_ALLOWED = "exam_allowed" +EXCEPTION = "exception" +PROTECTED = "protected" +CATEGORY = "category" +CATALOG_UNAVAILABLE = "catalog_unavailable" +NONE = "none" +BLOCKING = (EXAM, CATEGORY, CATALOG_UNAVAILABLE) + + +def host_of(value: str) -> str: + """Lower-cased host without trailing dot or IPv6 brackets; '' for squid's '-' (none).""" + host = value.strip().lower() + if host in ("", "-"): + return "" + if host.startswith("[") and host.endswith("]"): + host = host[1:-1] + return host.rstrip(".") + + +def suffixes(host: str) -> list[str]: + """``a.b.example.org`` -> ``[a.b.example.org, b.example.org, example.org, org]``.""" + labels = host.split(".") + return [".".join(labels[i:]) for i in range(len(labels))] + + +def read_domains(path: str) -> frozenset[str]: + """The names of a ``.domains`` file (one per line, ``#`` comments, leading dot optional).""" + names: set[str] = set() + try: + with open(path, encoding="utf-8", errors="replace") as fh: + for raw in fh: + word = raw.split("#", 1)[0].strip().lower().strip(".") + if word: + names.add(word.split()[0]) + except OSError: + return frozenset() + return frozenset(names) + + +def listed(host: str, names: frozenset[str] | set[str]) -> str | None: + """The entry of ``names`` that covers ``host`` (itself or a parent domain), if any.""" + for suffix in suffixes(host): + if suffix in names: + return suffix + return None + + +def _minutes(value: str) -> int: + hours, _, minutes = value.partition(":") + return int(hours) * 60 + int(minutes) + + +@dataclass +class Policy: + """The parsed ``filter.json`` of one instance plus its exception list.""" + + categories: list[str] = field(default_factory=list) + schedules: dict[str, list[dict[str, Any]]] = field(default_factory=dict) + fail_closed: frozenset[str] = frozenset() + timezone: str = "UTC" + exam_until: float | None = None + exam_allowed: frozenset[str] = frozenset() + allowed: frozenset[str] = frozenset() + broken: str | None = None # why filter.json could not be used (then: fail closed) + + @classmethod + def load(cls, filter_path: str, allowed_path: str) -> "Policy": + """Read both files. A missing ``filter.json`` = no filter; an unreadable one = broken.""" + allowed = read_domains(allowed_path) + try: + with open(filter_path, encoding="utf-8") as fh: + data = json.load(fh) + except FileNotFoundError: + return cls(allowed=allowed) + except (OSError, ValueError) as exc: + return cls(allowed=allowed, broken=f"filter.json unreadable: {exc}") + try: + return cls.from_dict(data, allowed) + except (TypeError, ValueError, KeyError, AttributeError) as exc: + return cls(allowed=allowed, broken=f"filter.json invalid: {exc}") + + @classmethod + def from_dict(cls, data: dict[str, Any], allowed: frozenset[str]) -> "Policy": + if data.get("format") != FORMAT: + raise ValueError(f"format {data.get('format')!r}, expected {FORMAT}") + exam = data.get("exam") or None + return cls( + categories=[str(c) for c in data.get("categories") or []], + schedules={str(k): list(v) for k, v in (data.get("schedules") or {}).items()}, + fail_closed=frozenset(str(c) for c in data.get("fail_closed") or []), + timezone=str(data.get("timezone") or "UTC"), + exam_until=float(exam["until"]) if exam else None, + exam_allowed=frozenset( + str(d).lower().strip(".") for d in (exam or {}).get("allowed") or [] + ), + allowed=allowed, + ) + + def exam_active(self, now: float) -> bool: + return self.exam_until is not None and now < self.exam_until + + def _local(self, now: float) -> datetime.datetime: + try: + from zoneinfo import ZoneInfo + + return datetime.datetime.fromtimestamp(now, ZoneInfo(self.timezone)) + except Exception: # noqa: BLE001 - unknown zone or no tzdata: UTC, never an error + return datetime.datetime.fromtimestamp(now, datetime.timezone.utc) + + def active_categories(self, now: float) -> list[str]: + """The categories in force at ``now``: those without a schedule always, the others + only inside one of their windows (weekday + start <= time < end, local time).""" + local = None + active: list[str] = [] + for category in self.categories: + windows = self.schedules.get(category) + if not windows: + active.append(category) + continue + if local is None: + local = self._local(now) + day = DAYS[local.weekday()] + minute = local.hour * 60 + local.minute + for window in windows: + if day in window.get("days", ()) and ( + _minutes(window["start"]) <= minute < _minutes(window["end"]) + ): + active.append(category) + break + return active + + +class Catalog: + """The read-only category catalog (SQLite, built by ``lmnsquid.catalog``).""" + + def __init__(self, path: str) -> None: + self.path = path + self.db = sqlite3.connect(f"file:{path}?mode=ro&immutable=1", uri=True) + self.db.execute("PRAGMA query_only = 1") + meta = dict(self.db.execute("SELECT k, v FROM meta")) + if str(meta.get("format")) != str(FORMAT): + raise ValueError(f"catalog format {meta.get('format')!r}, expected {FORMAT}") + self.built = float(meta.get("built") or 0) + self.bits: dict[str, int] = {} + self.labels: dict[str, str] = {} + for cat_id, bit, label in self.db.execute("SELECT id, bit, label FROM cats ORDER BY bit"): + self.bits[str(cat_id)] = int(bit) + self.labels[str(cat_id)] = str(label) + self.sources: dict[int, tuple[str, str, str]] = { + int(bit): (str(sid), str(name), str(lic)) + for sid, bit, name, lic in self.db.execute("SELECT id, bit, name, license FROM srcs") + } + + def lookup(self, host: str) -> tuple[int, int, dict[str, int]]: + """(category mask, source mask, {listed name: its category mask}) of ``host``.""" + names = suffixes(host) + marks = ",".join("?" * len(names)) + cmask = smask = 0 + hits: dict[str, int] = {} + for name, cats, srcs in self.db.execute( + f"SELECT n, c, s FROM d WHERE n IN ({marks})", names + ): + cmask |= int(cats) + smask |= int(srcs) + hits[str(name)] = int(cats) + return cmask, smask, hits + + def close(self) -> None: + self.db.close() + + +@dataclass +class Decision: + decision: str + category: str | None = None + entry: str | None = None # the list entry or catalog name that decided + detail: str = "" + + @property + def blocked(self) -> bool: + return self.decision in BLOCKING + + +def decide( + host: str, + policy: Policy, + catalog: Catalog | None, + now: float, + catalog_error: str = "", +) -> Decision: + """The filter's verdict for ``host``; see the module docstring for the order.""" + if not host: + return Decision(NONE) + if policy.broken: + # The control plane writes filter.json atomically; a broken one was edited by hand. + return Decision(CATALOG_UNAVAILABLE, detail=policy.broken) + if policy.exam_active(now): + entry = listed(host, policy.exam_allowed) + if entry: + return Decision(EXAM_ALLOWED, entry=entry) + return Decision(EXAM) + entry = listed(host, policy.allowed) + if entry: + return Decision(EXCEPTION, entry=entry) + active = policy.active_categories(now) + if not active: + return Decision(NONE) + protected = _protected(catalog) + entry = listed(host, protected) + if entry: + return Decision(PROTECTED, entry=entry) + if catalog is None: + closed = [c for c in active if c in policy.fail_closed] + if closed: + return Decision(CATALOG_UNAVAILABLE, category=closed[0], detail=catalog_error) + return Decision(NONE, detail=f"catalog unavailable, not failing closed: {catalog_error}") + cmask, _smask, hits = catalog.lookup(host) + for category in active: + bit = catalog.bits.get(category) + if bit is not None and cmask & (1 << bit): + entry = next((n for n, c in hits.items() if c & (1 << bit)), None) + return Decision(CATEGORY, category=category, entry=entry) + return Decision(NONE) + + +# The protected list lives next to the catalog (written with it); read once per file change. +_PROTECTED: dict[str, tuple[float, frozenset[str]]] = {} + + +def protected_path(catalog: Catalog | None, catalog_dir: str | None = None) -> str: + base = catalog_dir or (os.path.dirname(catalog.path) if catalog else "") + return os.path.join(base, "protected.domains") + + +def _protected(catalog: Catalog | None) -> frozenset[str]: + path = PROTECTED_FILE or protected_path(catalog) + try: + mtime = os.stat(path).st_mtime + except OSError: + return frozenset() + cached = _PROTECTED.get(path) + if cached is None or cached[0] != mtime: + cached = (mtime, read_domains(path)) + _PROTECTED[path] = cached + return cached[1] + + +# Set by callers that keep the protected list somewhere else than next to the catalog. +PROTECTED_FILE: str | None = None diff --git a/controlplane/pyproject.toml b/controlplane/pyproject.toml index b57e648..ed5c55d 100644 --- a/controlplane/pyproject.toml +++ b/controlplane/pyproject.toml @@ -43,10 +43,15 @@ dev = [ [project.scripts] lmnsquid-api = "lmnsquid.main:main" lmnsquid = "lmnsquid.cli:main" +lmnsquid-catalog = "lmnsquid.catalog:main" [tool.setuptools.packages.find] include = ["lmnsquid*"] +[tool.setuptools.package-data] +# Category catalog description and the packaged lists (ADR-022). +lmnsquid = ["data/*.yml", "data/*.domains", "data/*.txt"] + [tool.ruff] line-length = 100 diff --git a/controlplane/tests/conftest.py b/controlplane/tests/conftest.py index 5754505..b489ede 100644 --- a/controlplane/tests/conftest.py +++ b/controlplane/tests/conftest.py @@ -120,6 +120,19 @@ def noauth_active(self, name: str) -> bool: raise LookupError(f"instance {name!r} is not running") return bool(container["noauth_active"]) + def filter_active(self, name: str) -> bool: + container = self.containers.get(name) + if container is None or not container["running"]: + raise LookupError(f"instance {name!r} is not running") + # An image tagged "old" also stands for one from before the category filter (ADR-022). + return bool(container["noauth_active"]) + + def filter_stats(self, name: str) -> str: + container = self.containers.get(name) + if container is None or not container["running"]: + raise LookupError(f"instance {name!r} is not running") + return str(container.get("filter_stats", "")) + def reload(self, name: str) -> dict[str, Any]: container = self.containers.get(name) if container is None or not container["running"]: @@ -190,6 +203,11 @@ def settings(tmp_path: Any, token: str) -> Settings: instances_dir=str(tmp_path / "instances"), secrets_dir=str(tmp_path / "secrets"), blocklists_dir=str(tmp_path / "blocklists"), + catalog_dir=str(tmp_path / "catalog"), + catalog_cache_dir=str(tmp_path / "catalog-cache"), + catalog_config=str(tmp_path / "catalog.yml"), + protected_file=str(tmp_path / "protected.domains"), + filter_timezone="Europe/Berlin", ) @@ -256,3 +274,36 @@ def instance_data() -> dict[str, Any]: @pytest.fixture def instance(instance_data: dict[str, Any]) -> Instance: return Instance(**instance_data) + + +def make_catalog(catalog_dir: Any, entries: dict[str, list[str]], work: Any = None) -> Any: + """Build and publish a real catalog from ``{category id: [domain, ...]}`` (one local source + per category) into ``catalog_dir``; return the path of current.sqlite.""" + from pathlib import Path + + from lmnsquid import catalog as catalog_mod + + catalog_dir = Path(catalog_dir) + work = Path(work or catalog_dir.parent / "catalog-work") + work.mkdir(parents=True, exist_ok=True) + catalog_dir.mkdir(parents=True, exist_ok=True) + config = catalog_mod.load_config() + inputs = [] + for cat_id, names in entries.items(): + path = work / f"{cat_id}.domains" + with open(path, "w", encoding="utf-8") as fh: + for n in names: + fh.write(f"{n}\n") + src = { + "id": f"src-{cat_id.replace('_', '-')}", + "name": f"Source {cat_id}", + "license": "CC0", + "path": str(path), + "format": "domains", + "category": cat_id, + } + inputs.append((src, str(path))) + target = work / "catalog.sqlite" + catalog_mod.build_file(config, inputs, target, work) + catalog_mod.publish(catalog_dir, target) + return catalog_dir / catalog_mod.CURRENT diff --git a/controlplane/tests/test_catalog.py b/controlplane/tests/test_catalog.py new file mode 100644 index 0000000..ea3982c --- /dev/null +++ b/controlplane/tests/test_catalog.py @@ -0,0 +1,447 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Catalog builder (ADR-022): list formats, streaming build, size floors, atomic publish, +the update run with its fallbacks, status and the protected list.""" + +from __future__ import annotations + +import io +import json +import os +import sqlite3 +import tarfile +import time +import tracemalloc +import urllib.error +from pathlib import Path +from typing import Any + +import pytest +import yaml +from conftest import make_catalog + +from lmnsquid import catalog as cm +from lmnsquid import filterdecision as fd + + +# ---------------------------------------------------------------- formats / normalisation +@pytest.mark.parametrize( + ("line", "fmt", "expected"), + [ + ("example.org", "domains", "example.org"), + (" Example.ORG. ", "domains", "example.org"), + (".example.org", "domains", "example.org"), + ("*.example.org", "domains", "example.org"), + ("0.0.0.0 ads.example.org", "domains", "ads.example.org"), + ("127.0.0.1 ads.example.org # comment", "domains", "ads.example.org"), + ("||ads.example.org^", "domains", "ads.example.org"), + ("# comment", "domains", None), + ("", "domains", None), + ("10.0.0.1", "domains", None), # IP addresses are dropped + ("com", "domains", None), # a single label would block a whole TLD + ("müller.de", "domains", "xn--mller-kva.de"), + ("bad_name!.org", "domains", None), + ("||tracker.example^", "adblock", "tracker.example"), + ("||tracker.example^$third-party", "adblock", "tracker.example"), + ("@@||allowed.example^", "adblock", None), + ("||path.example/ads^", "adblock", None), + ("example.org##.ad", "adblock", None), + ("bad.example CNAME .", "rpz", "bad.example"), + ("*.bad.example CNAME .", "rpz", "bad.example"), + ("bad.example 300 CNAME .", "rpz", "bad.example"), + ("$TTL 300", "rpz", None), + ("ok.example CNAME rpz-passthru.", "rpz", None), + ], +) +def test_parse_line(line: str, fmt: str, expected: str | None) -> None: + assert cm.parse_line(line, fmt) == expected + + +def _ut1_tar(path: Path, categories: dict[str, list[str]]) -> None: + with tarfile.open(path, "w:gz") as tar: + for cat, names in categories.items(): + data = "".join(f"{n}\n" for n in names).encode() + info = tarfile.TarInfo(f"blacklists/{cat}/domains") + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + urls = tarfile.TarInfo(f"blacklists/{cat}/urls") + urls.size = 4 + tar.addfile(urls, io.BytesIO(b"x/y\n")) + link = tarfile.TarInfo("blacklists/porn") + link.type = tarfile.SYMTYPE + link.linkname = "adult" + tar.addfile(link) + + +def test_ut1_archive_maps_categories_and_skips_symlinks_and_urls(tmp_path: Path) -> None: + _ut1_tar( + tmp_path / "ut1.tgz", + {"adult": ["a.example", "b.example"], "games": ["g.example"], "jobsearch": ["j.example"]}, + ) + src = {"format": "ut1-tar", "map": {"adult": "porn", "games": "games"}} + got = sorted(cm.iter_source(src, str(tmp_path / "ut1.tgz"))) + assert got == [("a.example", "porn"), ("b.example", "porn"), ("g.example", "games")] + + +# ---------------------------------------------------------------- configuration +def test_packaged_config_is_valid_and_complete() -> None: + config = cm.load_config() + ids = config.category_ids + for wanted in ( + "porn", + "gambling", + "violence", + "drugs", + "dating", + "security", + "vpn_proxy", + "doh", + "nosafesearch", + "ads", + "telemetry_microsoft", + "social", + "games", + "chat", + "streaming", + "warez", + "ai", + "cheating", + ): + assert wanted in ids + assert config.fail_closed == {"porn", "gambling", "violence", "drugs", "dating"} + # not offered: "DO NOT USE" and the expert categories of the research (section 2.1) + ut1 = next(s for s in config.sources if s["id"] == "ut1") + for never in ( + "examen_pix", + "tricheur_pix", + "update", + "liste_blanche", + "jobsearch", + "webmail", + "remote-control", + "shortener", + "mixed_adult", + ): + assert never not in ut1["map"] + for profile in ("students", "teachers"): + assert set(config.profiles[profile]["categories"]) <= set(ids) + assert {s["license"] for s in config.sources} >= {"CC BY-SA 4.0", "GPL-3.0"} + + +def test_admin_config_adds_replaces_and_disables_sources(tmp_path: Path) -> None: + admin = tmp_path / "catalog.yml" + admin.write_text( + yaml.safe_dump( + { + "disable_sources": ["hagezi-light"], + "sources": [ + { + "id": "own", + "name": "Own", + "license": "CC0", + "path": "/x.domains", + "format": "domains", + "category": "games", + } + ], + "categories": [{"id": "games", "label": "Computerspiele"}], + } + ) + ) + config = cm.load_config(str(admin)) + ids = [s["id"] for s in config.sources] + assert "hagezi-light" not in ids and "own" in ids + assert config.category("games")["label"] == "Computerspiele" + + +@pytest.mark.parametrize( + "bad", + [ + { + "sources": [ + { + "id": "x", + "name": "X", + "license": "?", + "url": "http://plain.example/x", + "format": "domains", + "category": "ads", + } + ] + }, + { + "sources": [ + { + "id": "x", + "name": "X", + "license": "?", + "path": "/x", + "format": "domains", + "category": "nope", + } + ] + }, + { + "sources": [ + { + "id": "x", + "name": "X", + "license": "?", + "path": "/x", + "format": "csv", + "category": "ads", + } + ] + }, + { + "sources": [ + { + "id": "../x", + "name": "X", + "license": "?", + "path": "/x", + "format": "domains", + "category": "ads", + } + ] + }, + ], +) +def test_admin_config_is_validated(tmp_path: Path, bad: dict[str, Any]) -> None: + admin = tmp_path / "catalog.yml" + admin.write_text(yaml.safe_dump(bad)) + with pytest.raises(cm.CatalogError): + cm.load_config(str(admin)) + + +# ---------------------------------------------------------------- building +def test_build_merges_sources_and_categories(tmp_path: Path) -> None: + current = make_catalog( + tmp_path / "cat", + {"porn": ["a.example", "b.example", "a.example"], "ads": ["a.example", "c.example"]}, + ) + cat = fd.Catalog(str(current)) + try: + cmask, smask, hits = cat.lookup("www.a.example") + assert cmask == (1 << cat.bits["porn"]) | (1 << cat.bits["ads"]) + assert len([b for b in cat.sources if smask & (1 << b)]) == 2 + counts = dict(cat.db.execute("SELECT id, count FROM cats")) + assert counts["porn"] == 2 and counts["ads"] == 2 and counts["games"] == 0 + assert cat.db.execute("SELECT count(*) FROM d").fetchone()[0] == 3 + finally: + cat.close() + assert oct(os.stat(current).st_mode & 0o777) == "0o644" + + +def test_build_streams_instead_of_holding_the_lists(tmp_path: Path) -> None: + # 300 000 entries: a dict of them alone needs ~40 MB; the streaming build stays far below. + names = [f"host{i}.example{i % 1000}.org" for i in range(300_000)] + tracemalloc.start() + make_catalog(tmp_path / "cat", {"porn": names}, work=tmp_path / "work") + _current, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + assert peak < 15 * 1024 * 1024, peak + + +def test_min_entries_refuses_a_short_source(tmp_path: Path) -> None: + config = cm.load_config() + path = tmp_path / "few.domains" + path.write_text("a.example\n") + src = { + "id": "few", + "name": "Few", + "license": "?", + "format": "domains", + "category": "ads", + "path": str(path), + "min_entries": 5, + } + with pytest.raises(cm.CatalogError, match="min_entries"): + cm.build_file(config, [(src, str(path))], tmp_path / "x.sqlite", tmp_path) + + +def test_shrink_check() -> None: + cm.check_shrink({"porn": 600}, {"porn": 1000}) + cm.check_shrink({"ai": 10}, {"ai": 90}) # small categories may move freely + with pytest.raises(cm.CatalogError, match="shrink"): + cm.check_shrink({"porn": 499}, {"porn": 1000}) + with pytest.raises(cm.CatalogError): + cm.check_shrink({}, {"porn": 1000}) + + +def test_publish_switches_atomically_and_keeps_one_previous(tmp_path: Path) -> None: + catalog_dir = tmp_path / "cat" + for i in range(3): + make_catalog(catalog_dir, {"ads": [f"v{i}.example"]}) + time.sleep(1.05) # file names carry the second + versions = sorted(p.name for p in catalog_dir.glob("catalog-*.sqlite")) + assert len(versions) == 2 + assert os.readlink(catalog_dir / cm.CURRENT) == versions[-1] + cat = fd.Catalog(str(catalog_dir / cm.CURRENT)) + assert cat.lookup("v2.example")[0] + cat.close() + + +# ---------------------------------------------------------------- the update run +def _paths(tmp_path: Path, admin: dict[str, Any] | None = None) -> cm.Paths: + admin_file = tmp_path / "catalog.yml" + if admin is not None: + admin_file.write_text(yaml.safe_dump(admin)) + return cm.Paths( + tmp_path / "catalog", + tmp_path / "cache", + str(admin_file), + str(tmp_path / "protected.domains"), + ) + + +def _local_sources(tmp_path: Path, n: int) -> dict[str, Any]: + """An admin config whose only sources are local files (no network in tests).""" + from lmnsquid.catalog import load_config + + lists = tmp_path / "lists" + lists.mkdir(exist_ok=True) + (lists / "p.domains").write_text("".join(f"p{i}.example\n" for i in range(n))) + return { + "disable_sources": [s["id"] for s in load_config().sources], + "sources": [ + { + "id": "local-p", + "name": "Local", + "license": "CC0", + "path": str(lists / "p.domains"), + "format": "domains", + "category": "porn", + } + ], + } + + +def test_update_builds_publishes_and_reports(tmp_path: Path) -> None: + paths = _paths(tmp_path, _local_sources(tmp_path, 300)) + (tmp_path / "protected.domains").write_text("own-school.example\n") + result = cm.update(paths) + assert result["state"] == "ok", result + assert result["categories"]["porn"] == 300 + assert result["peak_rss_kib"] > 0 + info = cm.status(paths, cm.load_config(paths.admin_config)) + assert info["available"] and not info["old"] and info["domains"] == 300 + assert info["last_run"]["state"] == "ok" + porn = next(c for c in info["categories"] if c["id"] == "porn") + assert porn["count"] == 300 and porn["sources"][0]["license"] == "CC0" + protected = (paths.catalog_dir / "protected.domains").read_text().split() + assert "own-school.example" in protected and "windowsupdate.com" in protected + + +def test_failed_update_keeps_the_active_catalog(tmp_path: Path) -> None: + paths = _paths(tmp_path, _local_sources(tmp_path, 300)) + assert cm.update(paths)["state"] == "ok" + first = os.readlink(paths.catalog_dir / cm.CURRENT) + _paths(tmp_path, _local_sources(tmp_path, 100)) # shrinks by two thirds + result = cm.update(paths) + assert result["state"] == "failed" and "shrink" in result["error"] + assert os.readlink(paths.catalog_dir / cm.CURRENT) == first + info = cm.status(paths) + assert info["available"] and info["last_run"]["state"] == "failed" + assert info["last_run"]["last_success"] + + +def test_one_build_at_a_time(tmp_path: Path) -> None: + paths = _paths(tmp_path, _local_sources(tmp_path, 10)) + with cm.build_lock(paths.cache_dir): + assert cm.is_building(paths.cache_dir) + with pytest.raises(cm.Busy): + cm.update(paths) + assert not cm.is_building(paths.cache_dir) + + +def test_status_without_catalog_and_with_a_stale_run(tmp_path: Path) -> None: + paths = _paths(tmp_path) + paths.cache_dir.mkdir() + (paths.cache_dir / cm.STATUS).write_text(json.dumps({"state": "running"})) + info = cm.status(paths, cm.load_config()) + assert not info["available"] and info["error"] == "no catalog yet" + assert info["last_run"]["state"] == "failed" # running, but nobody holds the lock + assert info["sources"] and info["categories"] + + +def test_status_marks_an_old_catalog(tmp_path: Path) -> None: + current = make_catalog(tmp_path / "catalog", {"ads": ["a.example"]}) + db = sqlite3.connect(os.path.realpath(current)) + db.execute("UPDATE meta SET v=? WHERE k='built'", (str(time.time() - 8 * 86400),)) + db.commit() + db.close() + info = cm.status(_paths(tmp_path)) + assert info["old"] and info["age_days"] > 7 + + +def test_broken_catalog_is_reported(tmp_path: Path) -> None: + (tmp_path / "catalog").mkdir() + (tmp_path / "catalog" / "current.sqlite").write_text("garbage") + info = cm.status(_paths(tmp_path)) + assert not info["available"] and "unusable" in info["error"] + + +def test_catalog_needed(tmp_path: Path) -> None: + lists, catalog_dir = tmp_path / "lists", tmp_path / "catalog" + (lists / "s-students").mkdir(parents=True) + assert not cm.catalog_needed(lists, catalog_dir) + (lists / "s-students" / "filter.json").write_text('{"categories": []}') + assert not cm.catalog_needed(lists, catalog_dir) + (lists / "s-students" / "filter.json").write_text('{"categories": ["porn"]}') + assert cm.catalog_needed(lists, catalog_dir) + + +# ---------------------------------------------------------------- downloading +class _Resp(io.BytesIO): + def __init__(self, data: bytes, headers: dict[str, str]) -> None: + super().__init__(data) + self.headers = headers + + def __enter__(self) -> "_Resp": + return self + + def __exit__(self, *a: Any) -> None: + self.close() + + +class _Opener: + def __init__(self, outcome: Any) -> None: + self.outcome = outcome + self.requests: list[Any] = [] + + def open(self, request: Any, timeout: float) -> Any: + self.requests.append(request) + if isinstance(self.outcome, Exception): + raise self.outcome + return self.outcome + + +SRC = {"id": "s", "url": "https://lists.example/s.txt"} + + +def test_fetch_conditional_get_and_fallbacks(tmp_path: Path, monkeypatch: Any) -> None: + state: dict[str, Any] = {} + opener = _Opener(_Resp(b"a.example\n", {"ETag": '"v1"', "Last-Modified": "Mon"})) + monkeypatch.setattr(cm.urllib.request, "build_opener", lambda *_: opener) + path, how = cm.fetch(SRC, tmp_path, state) + assert how == "downloaded" and Path(path).read_bytes() == b"a.example\n" + assert state["s"]["etag"] == '"v1"' + # second run: conditional, 304 -> unchanged + opener.outcome = urllib.error.HTTPError(SRC["url"], 304, "Not Modified", {}, None) # type: ignore[arg-type] + assert cm.fetch(SRC, tmp_path, state)[1] == "unchanged" + sent = opener.requests[-1] + assert sent.get_header("If-none-match") == '"v1"' + assert sent.get_header("If-modified-since") == "Mon" + # network down: the previous download is used, and said so + opener.outcome = urllib.error.URLError("no route") + assert cm.fetch(SRC, tmp_path, state)[1].startswith("cached:") + # nothing downloaded before: the build stops + with pytest.raises(cm.CatalogError): + cm.fetch({"id": "other", "url": "https://x.example/o"}, tmp_path, {}) + + +def test_redirect_away_from_https_is_refused() -> None: + handler = cm._HttpsOnly() + with pytest.raises(urllib.error.HTTPError): + handler.redirect_request(None, None, 302, "Found", {}, "http://plain.example/") diff --git a/controlplane/tests/test_filterdecision.py b/controlplane/tests/test_filterdecision.py new file mode 100644 index 0000000..395f3e0 --- /dev/null +++ b/controlplane/tests/test_filterdecision.py @@ -0,0 +1,169 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The filter decision (ADR-022): order exam -> exceptions -> protected -> categories, schedules, +fail-closed, and that the image's copy is the control plane's module byte for byte.""" + +from __future__ import annotations + +import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import pytest +from conftest import make_catalog + +from lmnsquid import filterdecision as fd + +ROOT = Path(__file__).resolve().parents[2] + + +def test_image_copy_is_identical() -> None: + # The helper in the container must decide exactly what "why is X blocked?" explains. + assert (ROOT / "image" / "lmn_filterdecision.py").read_bytes() == ( + ROOT / "controlplane" / "lmnsquid" / "filterdecision.py" + ).read_bytes() + + +@pytest.fixture +def catalog(tmp_path: Path) -> fd.Catalog: + current = make_catalog( + tmp_path / "catalog", + { + "porn": ["adult.example", "deep.sub.mixed.example"], + "ads": ["ads.example", "adult.example"], + "social": ["social.example"], + "telemetry_microsoft": ["v10.events.data.microsoft.com"], + }, + ) + (tmp_path / "catalog" / "protected.domains").write_text("microsoft.com\n") + fd.PROTECTED_FILE = str(tmp_path / "catalog" / "protected.domains") + cat = fd.Catalog(str(current)) + yield cat + cat.close() + fd.PROTECTED_FILE = None + + +def _policy(**kw: object) -> fd.Policy: + data = {"format": 1, "categories": ["porn"], "fail_closed": ["porn"], "timezone": "UTC"} + data.update(kw) + return fd.Policy.from_dict(data, frozenset(kw.pop("_allowed", ()))) # type: ignore[arg-type] + + +NOW = datetime.datetime(2026, 11, 24, 10, 0, tzinfo=ZoneInfo("Europe/Berlin")).timestamp() # Tue + + +def test_suffixes_and_host_normalisation() -> None: + assert fd.suffixes("a.b.c") == ["a.b.c", "b.c", "c"] + assert fd.host_of(" WWW.Example.ORG. ") == "www.example.org" + assert fd.host_of("-") == "" + assert fd.host_of("[2001:db8::1]") == "2001:db8::1" + + +def test_category_matches_domain_and_subdomains(catalog: fd.Catalog) -> None: + policy = _policy() + hit = fd.decide("www.adult.example", policy, catalog, NOW) + assert (hit.decision, hit.category, hit.entry) == ("category", "porn", "adult.example") + assert fd.decide("x.deep.sub.mixed.example", policy, catalog, NOW).blocked + assert not fd.decide("sub.mixed.example", policy, catalog, NOW).blocked + assert not fd.decide("notadult.example", policy, catalog, NOW).blocked + # a category the instance does not use blocks nothing + assert not fd.decide("social.example", policy, catalog, NOW).blocked + + +def test_first_active_category_in_the_instance_order_is_reported(catalog: fd.Catalog) -> None: + policy = _policy(categories=["ads", "porn"]) + assert fd.decide("adult.example", policy, catalog, NOW).category == "ads" + + +def test_exception_beats_category_but_not_exam(catalog: fd.Catalog) -> None: + policy = fd.Policy.from_dict( + {"format": 1, "categories": ["porn"], "timezone": "UTC"}, frozenset({"adult.example"}) + ) + assert fd.decide("www.adult.example", policy, catalog, NOW).decision == "exception" + exam = fd.Policy.from_dict( + { + "format": 1, + "categories": ["porn"], + "timezone": "UTC", + "exam": {"until": NOW + 60, "allowed": ["school.lan"]}, + }, + frozenset({"adult.example", "wiki.example"}), + ) + assert fd.decide("wiki.example", exam, catalog, NOW).decision == "exam" + assert fd.decide("moodle.school.lan", exam, catalog, NOW).decision == "exam_allowed" + + +def test_exam_ends_by_itself(catalog: fd.Catalog) -> None: + exam = _policy(exam={"until": NOW + 60, "allowed": []}) + assert fd.decide("example.org", exam, catalog, NOW).decision == "exam" + assert not fd.decide("example.org", exam, catalog, NOW + 61).blocked + + +def test_protected_list_beats_categories(catalog: fd.Catalog) -> None: + policy = _policy(categories=["telemetry_microsoft"], fail_closed=[]) + verdict = fd.decide("v10.events.data.microsoft.com", policy, catalog, NOW) + assert (verdict.decision, verdict.entry) == ("protected", "microsoft.com") + + +def test_fail_closed_only_for_fail_closed_categories() -> None: + closed = _policy(categories=["porn", "ads"]) + verdict = fd.decide("example.org", closed, None, NOW, "missing") + assert (verdict.decision, verdict.category) == ("catalog_unavailable", "porn") + opened = _policy(categories=["ads"], fail_closed=["porn"]) + assert not fd.decide("example.org", opened, None, NOW, "missing").blocked + # exceptions still pass while closed + allowed = fd.Policy.from_dict( + {"format": 1, "categories": ["porn"], "fail_closed": ["porn"]}, frozenset({"ok.example"}) + ) + assert fd.decide("ok.example", allowed, None, NOW).decision == "exception" + + +def test_no_filter_json_means_no_filter(tmp_path: Path) -> None: + policy = fd.Policy.load(str(tmp_path / "filter.json"), str(tmp_path / "allowed.domains")) + assert not fd.decide("anything.example", policy, None, NOW).blocked + + +def test_broken_filter_json_fails_closed(tmp_path: Path) -> None: + (tmp_path / "filter.json").write_text("{not json") + policy = fd.Policy.load(str(tmp_path / "filter.json"), str(tmp_path / "allowed.domains")) + assert policy.broken + assert fd.decide("anything.example", policy, None, NOW).blocked + (tmp_path / "filter.json").write_text('{"format": 99}') + assert fd.Policy.load(str(tmp_path / "filter.json"), "").broken + + +def test_schedule_windows_in_local_time(catalog: fd.Catalog) -> None: + policy = _policy( + categories=["social"], + timezone="Europe/Berlin", + schedules={"social": [{"days": ["mo", "tu"], "start": "07:45", "end": "13:15"}]}, + ) + tue = datetime.datetime(2026, 11, 24, tzinfo=ZoneInfo("Europe/Berlin")) + at = lambda h, m: (tue + datetime.timedelta(hours=h, minutes=m)).timestamp() # noqa: E731 + assert fd.decide("social.example", policy, catalog, at(7, 45)).blocked + assert fd.decide("social.example", policy, catalog, at(13, 14)).blocked + assert not fd.decide("social.example", policy, catalog, at(13, 15)).blocked + assert not fd.decide("social.example", policy, catalog, at(7, 44)).blocked + wed = at(24 + 9, 0) + assert not fd.decide("social.example", policy, catalog, wed).blocked + + +def test_unknown_timezone_falls_back_to_utc(catalog: fd.Catalog) -> None: + policy = _policy( + categories=["social"], + timezone="Mars/Olympus", + schedules={"social": [{"days": list(fd.DAYS), "start": "00:00", "end": "24:00"}]}, + ) + assert fd.decide("social.example", policy, catalog, NOW).blocked + + +def test_catalog_refuses_another_format(tmp_path: Path) -> None: + current = make_catalog(tmp_path / "c", {"ads": ["a.example"]}) + import sqlite3 + + db = sqlite3.connect(current) + db.execute("UPDATE meta SET v='2' WHERE k='format'") + db.commit() + db.close() + with pytest.raises(ValueError): + fd.Catalog(str(current)) diff --git a/image/lmn_filterdecision.py b/image/lmn_filterdecision.py new file mode 100644 index 0000000..0b0b5f3 --- /dev/null +++ b/image/lmn_filterdecision.py @@ -0,0 +1,283 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The filter decision for one host name: the same code in the control plane and the proxy. + +Standard library only. ``image/lmn_filterdecision.py`` is a byte-identical copy that the +image's external ACL helper (``image/lmn-filter-acl``) imports; ``tests/test_filterdecision.py`` +fails when the two differ, so the "why is X blocked?" answer of the control plane is the +decision squid makes. + +Inputs, all files (ADR-022): + +* the instance's ``filter.json`` (written by the control plane only): active categories, + schedules per category, the categories that fail closed, the time zone and the exam mode; +* the instance's ``allowed.domains`` (the admin's exceptions) and the host-wide + ``protected.domains`` ("never block" for categories); +* the host-wide catalog ``current.sqlite`` (domain -> category bit mask, source bit mask). + +Order: exam mode (only its own list) -> exceptions -> protected list -> categories. The own +blocklist (``blocked.domains``) is not decided here: squid matches it natively, as before. +""" + +from __future__ import annotations + +import datetime +import json +import os +import sqlite3 +from dataclasses import dataclass, field +from typing import Any + +FORMAT = 1 +DAYS = ("mo", "tu", "we", "th", "fr", "sa", "su") +# Decisions. BLOCK_* block the request; the others let it pass to the rest of squid's chain. +EXAM = "exam" +EXAM_ALLOWED = "exam_allowed" +EXCEPTION = "exception" +PROTECTED = "protected" +CATEGORY = "category" +CATALOG_UNAVAILABLE = "catalog_unavailable" +NONE = "none" +BLOCKING = (EXAM, CATEGORY, CATALOG_UNAVAILABLE) + + +def host_of(value: str) -> str: + """Lower-cased host without trailing dot or IPv6 brackets; '' for squid's '-' (none).""" + host = value.strip().lower() + if host in ("", "-"): + return "" + if host.startswith("[") and host.endswith("]"): + host = host[1:-1] + return host.rstrip(".") + + +def suffixes(host: str) -> list[str]: + """``a.b.example.org`` -> ``[a.b.example.org, b.example.org, example.org, org]``.""" + labels = host.split(".") + return [".".join(labels[i:]) for i in range(len(labels))] + + +def read_domains(path: str) -> frozenset[str]: + """The names of a ``.domains`` file (one per line, ``#`` comments, leading dot optional).""" + names: set[str] = set() + try: + with open(path, encoding="utf-8", errors="replace") as fh: + for raw in fh: + word = raw.split("#", 1)[0].strip().lower().strip(".") + if word: + names.add(word.split()[0]) + except OSError: + return frozenset() + return frozenset(names) + + +def listed(host: str, names: frozenset[str] | set[str]) -> str | None: + """The entry of ``names`` that covers ``host`` (itself or a parent domain), if any.""" + for suffix in suffixes(host): + if suffix in names: + return suffix + return None + + +def _minutes(value: str) -> int: + hours, _, minutes = value.partition(":") + return int(hours) * 60 + int(minutes) + + +@dataclass +class Policy: + """The parsed ``filter.json`` of one instance plus its exception list.""" + + categories: list[str] = field(default_factory=list) + schedules: dict[str, list[dict[str, Any]]] = field(default_factory=dict) + fail_closed: frozenset[str] = frozenset() + timezone: str = "UTC" + exam_until: float | None = None + exam_allowed: frozenset[str] = frozenset() + allowed: frozenset[str] = frozenset() + broken: str | None = None # why filter.json could not be used (then: fail closed) + + @classmethod + def load(cls, filter_path: str, allowed_path: str) -> "Policy": + """Read both files. A missing ``filter.json`` = no filter; an unreadable one = broken.""" + allowed = read_domains(allowed_path) + try: + with open(filter_path, encoding="utf-8") as fh: + data = json.load(fh) + except FileNotFoundError: + return cls(allowed=allowed) + except (OSError, ValueError) as exc: + return cls(allowed=allowed, broken=f"filter.json unreadable: {exc}") + try: + return cls.from_dict(data, allowed) + except (TypeError, ValueError, KeyError, AttributeError) as exc: + return cls(allowed=allowed, broken=f"filter.json invalid: {exc}") + + @classmethod + def from_dict(cls, data: dict[str, Any], allowed: frozenset[str]) -> "Policy": + if data.get("format") != FORMAT: + raise ValueError(f"format {data.get('format')!r}, expected {FORMAT}") + exam = data.get("exam") or None + return cls( + categories=[str(c) for c in data.get("categories") or []], + schedules={str(k): list(v) for k, v in (data.get("schedules") or {}).items()}, + fail_closed=frozenset(str(c) for c in data.get("fail_closed") or []), + timezone=str(data.get("timezone") or "UTC"), + exam_until=float(exam["until"]) if exam else None, + exam_allowed=frozenset( + str(d).lower().strip(".") for d in (exam or {}).get("allowed") or [] + ), + allowed=allowed, + ) + + def exam_active(self, now: float) -> bool: + return self.exam_until is not None and now < self.exam_until + + def _local(self, now: float) -> datetime.datetime: + try: + from zoneinfo import ZoneInfo + + return datetime.datetime.fromtimestamp(now, ZoneInfo(self.timezone)) + except Exception: # noqa: BLE001 - unknown zone or no tzdata: UTC, never an error + return datetime.datetime.fromtimestamp(now, datetime.timezone.utc) + + def active_categories(self, now: float) -> list[str]: + """The categories in force at ``now``: those without a schedule always, the others + only inside one of their windows (weekday + start <= time < end, local time).""" + local = None + active: list[str] = [] + for category in self.categories: + windows = self.schedules.get(category) + if not windows: + active.append(category) + continue + if local is None: + local = self._local(now) + day = DAYS[local.weekday()] + minute = local.hour * 60 + local.minute + for window in windows: + if day in window.get("days", ()) and ( + _minutes(window["start"]) <= minute < _minutes(window["end"]) + ): + active.append(category) + break + return active + + +class Catalog: + """The read-only category catalog (SQLite, built by ``lmnsquid.catalog``).""" + + def __init__(self, path: str) -> None: + self.path = path + self.db = sqlite3.connect(f"file:{path}?mode=ro&immutable=1", uri=True) + self.db.execute("PRAGMA query_only = 1") + meta = dict(self.db.execute("SELECT k, v FROM meta")) + if str(meta.get("format")) != str(FORMAT): + raise ValueError(f"catalog format {meta.get('format')!r}, expected {FORMAT}") + self.built = float(meta.get("built") or 0) + self.bits: dict[str, int] = {} + self.labels: dict[str, str] = {} + for cat_id, bit, label in self.db.execute("SELECT id, bit, label FROM cats ORDER BY bit"): + self.bits[str(cat_id)] = int(bit) + self.labels[str(cat_id)] = str(label) + self.sources: dict[int, tuple[str, str, str]] = { + int(bit): (str(sid), str(name), str(lic)) + for sid, bit, name, lic in self.db.execute("SELECT id, bit, name, license FROM srcs") + } + + def lookup(self, host: str) -> tuple[int, int, dict[str, int]]: + """(category mask, source mask, {listed name: its category mask}) of ``host``.""" + names = suffixes(host) + marks = ",".join("?" * len(names)) + cmask = smask = 0 + hits: dict[str, int] = {} + for name, cats, srcs in self.db.execute( + f"SELECT n, c, s FROM d WHERE n IN ({marks})", names + ): + cmask |= int(cats) + smask |= int(srcs) + hits[str(name)] = int(cats) + return cmask, smask, hits + + def close(self) -> None: + self.db.close() + + +@dataclass +class Decision: + decision: str + category: str | None = None + entry: str | None = None # the list entry or catalog name that decided + detail: str = "" + + @property + def blocked(self) -> bool: + return self.decision in BLOCKING + + +def decide( + host: str, + policy: Policy, + catalog: Catalog | None, + now: float, + catalog_error: str = "", +) -> Decision: + """The filter's verdict for ``host``; see the module docstring for the order.""" + if not host: + return Decision(NONE) + if policy.broken: + # The control plane writes filter.json atomically; a broken one was edited by hand. + return Decision(CATALOG_UNAVAILABLE, detail=policy.broken) + if policy.exam_active(now): + entry = listed(host, policy.exam_allowed) + if entry: + return Decision(EXAM_ALLOWED, entry=entry) + return Decision(EXAM) + entry = listed(host, policy.allowed) + if entry: + return Decision(EXCEPTION, entry=entry) + active = policy.active_categories(now) + if not active: + return Decision(NONE) + protected = _protected(catalog) + entry = listed(host, protected) + if entry: + return Decision(PROTECTED, entry=entry) + if catalog is None: + closed = [c for c in active if c in policy.fail_closed] + if closed: + return Decision(CATALOG_UNAVAILABLE, category=closed[0], detail=catalog_error) + return Decision(NONE, detail=f"catalog unavailable, not failing closed: {catalog_error}") + cmask, _smask, hits = catalog.lookup(host) + for category in active: + bit = catalog.bits.get(category) + if bit is not None and cmask & (1 << bit): + entry = next((n for n, c in hits.items() if c & (1 << bit)), None) + return Decision(CATEGORY, category=category, entry=entry) + return Decision(NONE) + + +# The protected list lives next to the catalog (written with it); read once per file change. +_PROTECTED: dict[str, tuple[float, frozenset[str]]] = {} + + +def protected_path(catalog: Catalog | None, catalog_dir: str | None = None) -> str: + base = catalog_dir or (os.path.dirname(catalog.path) if catalog else "") + return os.path.join(base, "protected.domains") + + +def _protected(catalog: Catalog | None) -> frozenset[str]: + path = PROTECTED_FILE or protected_path(catalog) + try: + mtime = os.stat(path).st_mtime + except OSError: + return frozenset() + cached = _PROTECTED.get(path) + if cached is None or cached[0] != mtime: + cached = (mtime, read_domains(path)) + _PROTECTED[path] = cached + return cached[1] + + +# Set by callers that keep the protected list somewhere else than next to the catalog. +PROTECTED_FILE: str | None = None From 8621bdc6dde373616c02a5baffe5476c430ff7de Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 14:14:31 +0100 Subject: [PATCH 02/19] feat(image): category filter helper, exceptions, SafeSearch hosts and block page squid asks the external ACL helper lmn-filter-acl (%DST and the TLS SNI, concurrency, ttl 60 s) whether a request falls under the instance's filter: exam mode, exceptions, protected list, catalog categories and schedules from /etc/squid/lists/filter.json and the catalog mounted at /etc/squid/catalog. Without filter.json it blocks nothing. HTTP gets a German block page with the reason; HTTPS stays as before (certificate warning / terminate). allowed.domains (exceptions) beat the own blocklist; an empty list changes nothing. hosts_file = /etc/hosts plus safesearch.hosts, so squid connects to the SafeSearch addresses (also for CONNECT). filter.log holds day and category of filtered requests only. Verified against squid 6.14 in the image: notes reach the log on cached answers, reconfigure empties the helper cache, %o needs ASCII. --- controlplane/tests/test_filter_helper.py | 139 +++++++++++++++++++++++ controlplane/tests/test_lists_sync.py | 29 +++++ image/Dockerfile | 15 ++- image/entrypoint.sh | 13 +++ image/errors/ERR_LMN_BLOCKED | 23 ++++ image/lists-sync.sh | 20 ++++ image/lmn-filter-acl | 135 ++++++++++++++++++++++ image/templates/squid.conf.template | 32 +++++- 8 files changed, 401 insertions(+), 5 deletions(-) create mode 100644 controlplane/tests/test_filter_helper.py create mode 100644 image/errors/ERR_LMN_BLOCKED create mode 100755 image/lmn-filter-acl diff --git a/controlplane/tests/test_filter_helper.py b/controlplane/tests/test_filter_helper.py new file mode 100644 index 0000000..245e9f5 --- /dev/null +++ b/controlplane/tests/test_filter_helper.py @@ -0,0 +1,139 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The image's external ACL helper ``image/lmn-filter-acl`` run as squid runs it: the protocol +with channel ids (concurrency), files changing under it, fail-closed, the message text.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import pytest +from conftest import make_catalog + +HELPER = Path(__file__).resolve().parents[2] / "image" / "lmn-filter-acl" + + +class Helper: + def __init__(self, lists: Path, catalog: Path) -> None: + env = { + "LMN_FILTER_LISTS": str(lists), + "LMN_FILTER_CATALOG": str(catalog), + "LMN_FILTER_CHECK_SECONDS": "0", + "PATH": os.environ.get("PATH", ""), + } + self.proc = subprocess.Popen( + [sys.executable, "-I", str(HELPER)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=env, + ) + + def ask(self, *lines: str) -> list[str]: + assert self.proc.stdin and self.proc.stdout + for line in lines: + self.proc.stdin.write(line + "\n") + self.proc.stdin.flush() + return [self.proc.stdout.readline().rstrip("\n") for _ in lines] + + def close(self) -> str: + assert self.proc.stdin and self.proc.stderr + self.proc.stdin.close() + self.proc.wait(timeout=10) + return self.proc.stderr.read() + + +def _filter(lists: Path, **data: Any) -> None: + body = {"format": 1, "categories": ["porn", "ai"], "fail_closed": ["porn"], "timezone": "UTC"} + body.update(data) + tmp = lists / ".filter.json.tmp" + tmp.write_text(json.dumps(body)) + os.replace(tmp, lists / "filter.json") + + +@pytest.fixture +def env(tmp_path: Path) -> Any: + lists, catalog = tmp_path / "lists", tmp_path / "catalog" + lists.mkdir() + make_catalog(catalog, {"porn": ["adult.example"], "ai": ["chat.example"]}) + (catalog / "protected.domains").write_text("adult-but-protected.example\n") + helper = Helper(lists, catalog) + yield lists, catalog, helper + helper.close() + + +def test_without_filter_json_everything_passes(env: Any) -> None: + _lists, _catalog, helper = env + assert helper.ask("0 adult.example", "1 example.org") == ["0 ERR", "1 ERR"] + + +def test_protocol_with_channel_ids_and_message(env: Any) -> None: + lists, _catalog, helper = env + _filter(lists) + answers = helper.ask("7 www.adult.example", "3 example.org", "12 chat.example", "4 -") + assert answers[0] == '7 OK tag=lmnfilter category=porn message="Pornografie"' + assert answers[1] == "3 ERR" + assert answers[2] == '12 OK tag=lmnfilter category=ai message="KI-Dienste"' + assert answers[3] == "4 ERR" # no SNI + + +def test_umlauts_become_ascii_for_the_block_page(env: Any) -> None: + lists, _catalog, helper = env + _filter(lists, exam={"until": time.time() + 60, "allowed": []}) + (answer,) = helper.ask("0 example.org") + assert 'message="Pruefungsmodus: nur freigegebene Seiten"' in answer + assert answer.isascii() + + +def test_changes_are_picked_up_without_restart(env: Any) -> None: + lists, catalog, helper = env + assert helper.ask("0 chat.example") == ["0 ERR"] + _filter(lists) + assert helper.ask("0 chat.example")[0].startswith("0 OK") + (lists / "allowed.domains").write_text(".chat.example\n") + assert helper.ask("1 chat.example") == ["1 ERR"] + # a new catalog version behind the symlink is used at once + make_catalog(catalog, {"porn": ["adult.example", "new.example"], "ai": ["chat.example"]}) + assert helper.ask("2 new.example")[0].startswith("2 OK tag=lmnfilter category=porn") + + +def test_missing_and_broken_catalog_fail_closed(env: Any) -> None: + lists, catalog, helper = env + _filter(lists) + for f in catalog.glob("catalog-*.sqlite"): + f.unlink() + (catalog / "current.sqlite").unlink() + assert helper.ask("0 example.org")[0].startswith("0 OK tag=lmnfilter category=porn") + (catalog / "current.sqlite").write_text("garbage") + (answer,) = helper.ask("1 example.org") + assert "Filterkatalog nicht verfuegbar" in answer + # the protected list and the exceptions are no lookups: they still pass + assert helper.ask("2 adult-but-protected.example") == ["2 ERR"] + # only non-fail-closed categories: open + _filter(lists, categories=["ai"]) + assert helper.ask("3 example.org") == ["3 ERR"] + assert "unusable" in helper.close() + + +def test_hand_broken_filter_json_fails_closed(env: Any) -> None: + lists, _catalog, helper = env + (lists / "filter.json").write_text("{") + assert helper.ask("0 example.org")[0].startswith("0 OK") + + +def test_lookup_rate(env: Any) -> None: + lists, _catalog, helper = env + _filter(lists) + n = 5000 + start = time.perf_counter() + answers = helper.ask(*(f"{i} host{i}.sub.example.org" for i in range(n))) + rate = n / (time.perf_counter() - start) + assert all(a.endswith(" ERR") for a in answers) + assert rate > 2000, rate # measured ~10 000/s with LMN_FILTER_CHECK_SECONDS=0 diff --git a/controlplane/tests/test_lists_sync.py b/controlplane/tests/test_lists_sync.py index 1278f97..55c2145 100644 --- a/controlplane/tests/test_lists_sync.py +++ b/controlplane/tests/test_lists_sync.py @@ -110,3 +110,32 @@ def test_crlf_line_endings_in_both_lists(tmp_path: Path) -> None: assert (dst / "blocked.domains").read_text() == ".blocked.example.org\n" assert (dst / "noauth.domains").read_text().split() == [".office.com", ".sharepoint.com"] assert "not a domain name" not in stderr + + +def test_exceptions_list_is_synced_and_missing_is_empty(tmp_path: Path) -> None: + dst, _ = _sync(tmp_path, blocked=b".example.org\n") + assert (dst / "allowed.domains").read_text() == "" + (tmp_path / "src" / "allowed.domains").write_bytes(b".a.wiki.org\r\n.wiki.org\n") + dst, _ = _sync(tmp_path, blocked=b".example.org\n") + assert (dst / "allowed.domains").read_text() == ".wiki.org\n" + + +def test_hosts_file_for_safesearch(tmp_path: Path) -> None: + # /etc/hosts of the container first (localhost, its own FQDN), then the valid lines only. + dst, stderr = _sync(tmp_path) + plain = (tmp_path / "hosts").read_text() + assert plain == Path("/etc/hosts").read_text() + (tmp_path / "src" / "safesearch.hosts").write_bytes( + b"216.239.38.120 www.google.de\n216.239.38.120 WWW.GOOGLE.COM # c\n" + b"999 bad\n1.2.3.4 two names.example\n; rm -rf /\n\n" + ) + dst, stderr = _sync(tmp_path) + hosts = (tmp_path / "hosts").read_text() + assert hosts.startswith(plain) + tail = hosts[len(plain) :].splitlines() + assert tail == [ + "# SafeSearch (linuxmuster-squid)", + "216.239.38.120 www.google.de", + "216.239.38.120 www.google.com", + ] + assert stderr.count("safesearch.hosts: ignored") == 3 diff --git a/image/Dockerfile b/image/Dockerfile index 20b5bc1..3379d4c 100644 --- a/image/Dockerfile +++ b/image/Dockerfile @@ -26,11 +26,14 @@ RUN apt-get update \ libsasl2-modules-gssapi-mit \ openssl \ logrotate \ + python3 \ + tzdata \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /etc/squid/lists /etc/squid/templates /var/log/squid /var/spool/squid \ && chown -R proxy:proxy /var/log/squid /var/spool/squid \ && : > /etc/squid/lists/blocked.domains \ - && : > /etc/squid/lists/noauth.domains + && : > /etc/squid/lists/noauth.domains \ + && mkdir -p /etc/squid/catalog # Fail the build early if a helper we rely on is missing (all verified present in # the noble squid-openssl / squidclient packages). NOTE: ntlm_auth (if ever needed @@ -50,8 +53,16 @@ COPY entrypoint.sh /usr/local/bin/entrypoint.sh COPY healthcheck.sh /usr/local/bin/healthcheck.sh COPY sni-sent.sh /usr/local/bin/sni-sent.sh COPY lists-sync.sh /usr/local/bin/lists-sync.sh +# Category filter (ADR-022): the external ACL helper, its decision module (a byte-identical copy +# of controlplane/lmnsquid/filterdecision.py) and the HTTP block page. python3 brings sqlite3; +# tzdata the zones for the schedules. +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 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/lists-sync.sh /usr/local/bin/lmn-filter-acl \ + && chmod 0644 /usr/local/bin/lmn_filterdecision.py \ + && /usr/bin/python3 -I -c 'import sqlite3, zoneinfo; zoneinfo.ZoneInfo("Europe/Berlin")' EXPOSE 3128 HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=3 \ diff --git a/image/entrypoint.sh b/image/entrypoint.sh index 311b927..56905f3 100644 --- a/image/entrypoint.sh +++ b/image/entrypoint.sh @@ -170,6 +170,19 @@ fi } EOF fi + # The anonymous filter statistics (day + category, ADR-022), kept as long as the access log. + cat < + + + + +Seite gesperrt + + +

Diese Seite ist im Schulnetz gesperrt

+
+

Adresse: %U

+

Grund: %o

+
+

Wenn die Seite für den Unterricht gebraucht wird, wende dich an die Schul-IT oder die +Lehrkraft und nenne Adresse und Grund. Die Schul-IT kann eine Ausnahme eintragen.

+

Filterkategorien nach Listen von UT1 (Université Toulouse Capitole, CC BY-SA 4.0) und +HaGeZi DNS Blocklists (GPL-3.0). Proxy %h, %T.

+ diff --git a/image/lists-sync.sh b/image/lists-sync.sh index b61d704..dd50f92 100755 --- a/image/lists-sync.sh +++ b/image/lists-sync.sh @@ -82,3 +82,23 @@ sync_list() { sync_list blocked.domains blocklist sync_list noauth.domains noauth +sync_list allowed.domains blocklist + +# SafeSearch (ADR-022): squid's hosts_file = the container's /etc/hosts (localhost, its own FQDN) +# plus the instance's safesearch.hosts (written by the control plane: " " lines). +# Anything else in that file is dropped, so a hand edit cannot break squid's start. +HOSTS_DST="$(dirname "${DST}")/hosts" # /run/lmnsquid/hosts +HOSTS_SRC="${LISTS_SYNC_ETC_HOSTS:-/etc/hosts}" +{ + cat "${HOSTS_SRC}" 2>/dev/null || true + if [ -f "${SRC}/safesearch.hosts" ]; then + echo "# SafeSearch (linuxmuster-squid)" + sed -e 's/#.*//' "${SRC}/safesearch.hosts" | awk ' + NF == 2 && $1 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ \ + && tolower($2) ~ /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/ \ + { print $1, tolower($2); next } + NF > 0 { print "linuxmuster-squid: safesearch.hosts: ignored: " $0 > "/dev/stderr" }' + fi +} > "${HOSTS_DST}.tmp" +chmod 0644 "${HOSTS_DST}.tmp" +mv -f "${HOSTS_DST}.tmp" "${HOSTS_DST}" diff --git a/image/lmn-filter-acl b/image/lmn-filter-acl new file mode 100755 index 0000000..346c599 --- /dev/null +++ b/image/lmn-filter-acl @@ -0,0 +1,135 @@ +#!/usr/bin/python3 -I +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Squid external ACL helper of the category filter (ADR-022). + +squid.conf: ``external_acl_type lmn_filter ... concurrency=N %DST /usr/local/bin/lmn-filter-acl`` +(and the same with ``%ssl::>sni``). Squid sends `` `` per line; the answer is +`` OK tag=lmnfilter category= message=""`` when the request is to be +blocked (the ACL matches, ``http_access deny filter_blocked``) and `` ERR`` otherwise. +The decision is ``lmn_filterdecision.decide`` (the control plane's ``lmnsquid.filterdecision``, +byte-identical). Files are re-read when they change (checked every few seconds), so a new +catalog or a changed filter needs no squid reconfigure; squid caches answers for its ttl. +The helper never answers BH: an internal error becomes the fail-closed answer when a +fail-closed category is active, else ERR, and is written to stderr (cache.log). +""" + +from __future__ import annotations + +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import lmn_filterdecision as fd # noqa: E402 + +LISTS = os.environ.get("LMN_FILTER_LISTS", "/etc/squid/lists") +CATALOG_DIR = os.environ.get("LMN_FILTER_CATALOG", "/etc/squid/catalog") +FILTER = os.path.join(LISTS, "filter.json") +ALLOWED = os.path.join(LISTS, "allowed.domains") +CATALOG = os.path.join(CATALOG_DIR, "current.sqlite") +fd.PROTECTED_FILE = os.path.join(CATALOG_DIR, "protected.domains") +CHECK_EVERY = float(os.environ.get("LMN_FILTER_CHECK_SECONDS", "5")) + +TEXT = { + fd.EXAM: "Prüfungsmodus: nur freigegebene Seiten", + fd.CATALOG_UNAVAILABLE: "Filterkatalog nicht verfügbar (gesperrt aus Sicherheitsgründen)", +} + + +def log(message: str) -> None: + sys.stderr.write(f"lmn-filter-acl: {message}\n") + sys.stderr.flush() + + +def stamp(path: str) -> tuple[int, float, int] | None: + try: + st = os.stat(path) # follows current.sqlite -> catalog-.sqlite + except OSError: + return None + return (st.st_ino, st.st_mtime, st.st_size) + + +class State: + def __init__(self) -> None: + self.policy = fd.Policy() + self.catalog: fd.Catalog | None = None + self.catalog_error = "not loaded" + self.stamps: tuple[object, ...] = () + self.checked = 0.0 + + def refresh(self, now: float) -> None: + if now - self.checked < CHECK_EVERY: + return + self.checked = now + stamps = (stamp(FILTER), stamp(ALLOWED), stamp(CATALOG)) + if stamps == self.stamps: + return + if stamps[:2] != self.stamps[:2]: + self.policy = fd.Policy.load(FILTER, ALLOWED) + if self.policy.broken: + log(self.policy.broken) + if not self.stamps or stamps[2] != self.stamps[2]: + self.open_catalog() + self.stamps = stamps + + def open_catalog(self) -> None: + if self.catalog is not None: + self.catalog.close() + self.catalog = None + if not os.path.exists(CATALOG): + self.catalog_error = f"{CATALOG} missing" + return + try: + self.catalog = fd.Catalog(CATALOG) + self.catalog_error = "" + log(f"catalog loaded ({len(self.catalog.bits)} categories)") + except Exception as exc: # noqa: BLE001 - any broken file: fail closed below + self.catalog_error = f"{CATALOG} unusable: {exc}" + log(self.catalog_error) + + +# squid writes %o of the block page byte by byte as HTML entities: UTF-8 becomes mojibake. +_ASCII = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss"}) + + +def quote(text: str) -> str: + """The message as a quoted helper value, ASCII only (see _ASCII).""" + plain = text.translate(_ASCII).encode("ascii", "replace").decode("ascii") + return '"' + plain.replace("\\", "/").replace('"', "'") + '"' + + +def answer(state: State, value: str, now: float) -> str: + host = fd.host_of(value) + try: + verdict = fd.decide(host, state.policy, state.catalog, now, state.catalog_error) + except Exception as exc: # noqa: BLE001 - e.g. sqlite error on a damaged file + log(f"lookup of {host!r} failed: {exc}") + state.catalog = None + state.catalog_error = f"lookup failed: {exc}" + state.stamps = () + verdict = fd.decide(host, state.policy, None, now, state.catalog_error) + if not verdict.blocked: + return "ERR" + category = verdict.category or verdict.decision + label = TEXT.get(verdict.decision) + if label is None and state.catalog is not None: + label = state.catalog.labels.get(category, category) + return f"OK tag=lmnfilter category={category} message={quote(label or category)}" + + +def main() -> None: + state = State() + for line in sys.stdin: + parts = line.split() + if not parts: + continue + channel, value = (parts[0], parts[1] if len(parts) > 1 else "-") + now = time.time() + state.refresh(now) + sys.stdout.write(f"{channel} {answer(state, value, now)}\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/image/templates/squid.conf.template b/image/templates/squid.conf.template index c22f119..3f62130 100644 --- a/image/templates/squid.conf.template +++ b/image/templates/squid.conf.template @@ -62,6 +62,25 @@ acl blocked_domains dstdomain "/run/lmnsquid/lists/blocked.domains" # whoever owns the address and must never put an IP on this list. acl noauth_domains dstdomain -n "/run/lmnsquid/lists/noauth.domains" +# --- Category filter, exceptions, exam mode (ADR-022) --- +# allowed.domains = the instance's exceptions: they beat its own blocklist (empty = no change). +# The helper decides exam mode, exceptions, the protected list and the catalog categories from +# /etc/squid/lists/filter.json and /etc/squid/catalog (both read-only mounts); without a +# filter.json it answers ERR (no match) for everything. OK = block, with the category as a +# transaction annotation (note) for the block page and the statistics log. +acl allowed_domains dstdomain "/run/lmnsquid/lists/allowed.domains" +acl allowed_sni ssl::server_name "/run/lmnsquid/lists/allowed.domains" +external_acl_type lmn_filter ttl=60 negative_ttl=60 concurrency=100 children-max=4 children-startup=1 %DST /usr/local/bin/lmn-filter-acl +acl filter_blocked external lmn_filter +external_acl_type lmn_filter_sni ttl=60 negative_ttl=60 concurrency=100 children-max=2 children-startup=1 %ssl::>sni /usr/local/bin/lmn-filter-acl +acl filter_blocked_sni external lmn_filter_sni +acl filter_categorised note category +# HTTP: a German block page with the reason (%o = the helper's message). HTTPS: unchanged (ADR-002). +deny_info ERR_LMN_BLOCKED filter_blocked +# SafeSearch (ADR-022): the container's /etc/hosts plus the instance's safesearch.hosts, built by +# lists-sync.sh; squid connects to the SafeSearch address for these names (also for CONNECT). +hosts_file /run/lmnsquid/hosts + # --- HTTPS: SNI peek + splice (NO decryption of allowed traffic) --- # step1 reads the TLS ClientHello (SNI); blocked SNIs are disconnected (terminate), # everything else is tunneled (splice, no MITM). Also catches cases where the @@ -77,7 +96,8 @@ acl noauth_sni ssl::server_name --client-requested "/run/lmnsquid/lists/noauth.d external_acl_type sni_sent ttl=3600 negative_ttl=3600 children-max=2 %ssl::>sni /usr/local/bin/sni-sent.sh acl tls_sni_sent external sni_sent ssl_bump peek step1 -ssl_bump terminate blocked_sni +ssl_bump terminate blocked_sni !allowed_sni +ssl_bump terminate filter_blocked_sni ssl_bump terminate noauth_domains !noauth_sni ssl_bump terminate noauth_domains !tls_sni_sent ssl_bump splice all @@ -99,10 +119,12 @@ http_access deny CONNECT connect_ip_literal http_access deny CONNECT connect_ip6_literal http_access allow localhost manager # cache manager from localhost (manual debug; healthcheck uses a 407 probe) http_access deny manager -http_access deny noauth_domains blocked_domains # listed AND blocked: the blocklist wins -> 403 +http_access deny noauth_domains blocked_domains !allowed_domains # listed AND blocked: the blocklist wins -> 403 +http_access deny noauth_domains filter_blocked # categories and exam mode apply here too (ADR-022) http_access allow noauth_domains school_net # listed + school subnet -> no proxy auth (ADR-016) http_access deny !authenticated # no ticket -> 407 (Negotiate challenge) -http_access deny blocked_domains # blocked domain -> 403 (also for teachers) +http_access deny blocked_domains !allowed_domains # blocked domain -> 403 (also for teachers), unless an exception +http_access deny filter_blocked # category / exam mode -> 403 with the block page (ADR-022) http_access allow authenticated role_group ${INTERNET_ACL_REF} school_net # in role (+internet) group + subnet -> 200 http_access deny all # authenticated, but not in group -> 403 @@ -111,6 +133,10 @@ http_access deny all # authenticated, but not in group -> # proxy, /proc/self/fd is no longer reachable -> /dev/stdout fails. The entrypoint # mirrors the access log via `tail -F` to the container stdout (-> docker/lmnsquid logs). cache_dir ufs /var/spool/squid ${CACHE_SIZE_MB} 16 256 +# Statistics without persons (ADR-022): only the day and the category of a filtered request, no +# 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 ${ACCESS_LOG_DIRECTIVE} cache_log /var/log/squid/cache.log From 4ef43d5fe58d307dac79930c898a5ab206caeaf2 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 14:14:31 +0100 Subject: [PATCH 03/19] feat(controlplane): filter settings, exam mode, exceptions, lookup and statistics per instance API: GET/PUT /v1/instances/{name}/filter (categories, schedules, SafeSearch; applied at once with a reconfigure), POST/DELETE .../exam (refused unless the running image has the filter), .../filter/lookup ("why is X blocked"), .../filter/stats, .../allowlist like the blocklist, GET /v1/catalog, POST /v1/catalog/update, /v1/catalog/lookup; /v1/status gains a filter summary. CLI: lmnsquid filter|allowlist|catalog. Containers get the catalog directory as a read-only mount (one replacement each, done by the update-all of the release that pins the image); SafeSearch addresses are resolved at every change and container creation, the last known one is kept. --- controlplane/lmnsquid/api.py | 273 ++++++++++++- controlplane/lmnsquid/cli.py | 261 +++++++++++++ controlplane/lmnsquid/docker_service.py | 41 ++ controlplane/lmnsquid/filters.py | 450 ++++++++++++++++++++++ controlplane/lmnsquid/main.py | 2 + controlplane/tests/test_cli.py | 66 ++++ controlplane/tests/test_docker_service.py | 14 +- controlplane/tests/test_filter_api.py | 326 ++++++++++++++++ webui/tests/conftest.py | 5 + 9 files changed, 1432 insertions(+), 6 deletions(-) create mode 100644 controlplane/lmnsquid/filters.py create mode 100644 controlplane/tests/test_filter_api.py diff --git a/controlplane/lmnsquid/api.py b/controlplane/lmnsquid/api.py index 99bb28d..036318c 100644 --- a/controlplane/lmnsquid/api.py +++ b/controlplane/lmnsquid/api.py @@ -6,6 +6,9 @@ import logging import re +import subprocess +import sys +import time from importlib.metadata import version as dist_version from typing import Any @@ -15,9 +18,13 @@ from fastapi.responses import JSONResponse, Response from pydantic import ValidationError +from . import catalog as catalog_mod from .blocklist import Blocklist, noauth_list from .config import Settings from .docker_service import DockerService, KeytabMissing, keytab_problem +from .filters import ExamStart, FilterSettings, FilterStore, allowed_list, explain, parse_stats +from .filters import summary as filter_summary +from .blocklist import normalize_domain from .models import ( DEFAULT_IMAGE, BlocklistEntry, @@ -39,6 +46,19 @@ _NAME_PARAM_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{1,62}$") +def spawn_catalog_update() -> None: + """Start ``lmnsquid-catalog update`` detached (it takes about a minute, ADR-022). + + The build takes its own lock and writes its result to ``status.json`` of the cache + directory, which ``GET /v1/catalog`` reports; its output goes to the journal. + """ + subprocess.Popen( + [sys.executable, "-m", "lmnsquid.catalog", "update"], + stdin=subprocess.DEVNULL, + start_new_session=True, + ) + + def create_app( settings: Settings, store: Store, @@ -50,7 +70,12 @@ def create_app( verify = make_verify_token(settings) blocklist = Blocklist(settings.blocklists_dir) noauth = noauth_list(settings.blocklists_dir) + allowed = allowed_list(settings.blocklists_dir) + filters = FilterStore(settings.blocklists_dir, settings.filter_timezone) + catalog_paths = catalog_mod.paths_from_settings(settings) app = FastAPI(title="linuxmuster-squid control plane") + # Replaceable in tests: starts the catalog build in the background. + app.state.spawn_catalog_update = spawn_catalog_update @app.exception_handler(DockerException) async def _docker_unreachable(_request: Request, exc: DockerException) -> JSONResponse: @@ -94,18 +119,74 @@ def _apply(inst: Instance) -> dict[str, Any]: status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) ) from exc - def _status(inst: Instance) -> dict[str, Any]: + def _catalog_config() -> catalog_mod.Config: + try: + return catalog_mod.load_config(settings.catalog_config) + except (catalog_mod.CatalogError, OSError, ValueError, KeyError, TypeError) as exc: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"catalog configuration unusable ({settings.catalog_config}): {exc}", + ) from exc + + def _catalog_brief() -> dict[str, Any]: + info = catalog_mod.status(catalog_paths) + return {"available": info["available"], "old": info.get("old", False)} + + def _status(inst: Instance, catalog_brief: dict[str, Any] | None = None) -> dict[str, Any]: """Container state plus what keeps the definition from running (additive fields). ``problem`` is ``"keytab"`` (with ``problem_detail``) when the keytab is not a usable - file in secrets_dir, else ``None``. + file in secrets_dir, else ``None``. ``filter`` summarises the category filter. """ result = docker.status(inst.name) problem = keytab_problem(docker.secrets_dir, inst.keytab_secret) result["problem"] = "keytab" if problem else None result["problem_detail"] = problem + result["filter"] = filter_summary( + filters.read(inst.name), catalog_brief or _catalog_brief(), time.time() + ) return result + def _apply_filter(name: str) -> dict[str, Any]: + """Make the running squid use the written filter files now (reconfigure, which also + empties squid's cache of helper answers, measured with squid 6.14).""" + catalog_mod.write_protected(catalog_paths.catalog_dir, settings.protected_file) + try: + if not docker.filter_active(name): + return { + "applied": False, + "reason": "image", + "detail": f"the data-plane image of {name!r} has no category filter yet; " + "the settings are stored and take effect once the instance runs an image " + "with it (lmnsquid update)", + } + result = docker.reload(name) + except LookupError as exc: + return { + "applied": False, + "reason": "not_running", + "detail": f"{exc}; the settings take effect when it starts", + } + except RuntimeError as exc: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) + ) from exc + return {"applied": True, "notices": result.get("notices", [])} + + def _filter_view(name: str) -> dict[str, Any]: + data = filters.read(name) + now = time.time() + exam = (data or {}).get("exam") or None + return { + "name": name, + "configured": data is not None, + "broken": bool(data and data.get("broken")), + "settings": filters.settings(name).model_dump(), + "exam": None if not exam else {**exam, "active": float(exam.get("until", 0)) > now}, + "timezone": (data or {}).get("timezone") or filters.timezone, + "summary": filter_summary(data, _catalog_brief(), now), + } + def _ensure(inst: Instance) -> dict[str, Any]: """Create (or re-create) the container of a stored definition, health-gated.""" try: @@ -167,7 +248,8 @@ def update_all() -> dict[str, Any]: @app.get("/v1/status", dependencies=auth) def all_status() -> list[dict[str, Any]]: """Container state of every stored instance in one call (overview of the WebUI plugin).""" - return [_status(inst) for inst in store.list()] + brief = _catalog_brief() + return [_status(inst, brief) for inst in store.list()] @app.get("/v1/schema", dependencies=auth) async def schema() -> dict[str, Any]: @@ -178,8 +260,44 @@ async def schema() -> dict[str, Any]: return { "instance": Instance.model_json_schema(), "instance_patch": InstancePatch.model_json_schema(), + "filter_settings": FilterSettings.model_json_schema(), + "exam_start": ExamStart.model_json_schema(), } + # ------------------------------------------------- category catalog (ADR-022) + @app.get("/v1/catalog", dependencies=auth) + def get_catalog() -> dict[str, Any]: + """Catalog state (age, sizes, last run), categories with groups, sources, licences, + and the profiles.""" + return catalog_mod.status(catalog_paths, _catalog_config()) + + @app.post("/v1/catalog/update", dependencies=auth, status_code=status.HTTP_202_ACCEPTED) + def update_catalog() -> dict[str, Any]: + """Start a catalog build in the background; ``GET /v1/catalog`` shows its result.""" + if catalog_mod.is_building(catalog_paths.cache_dir): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, detail="a catalog build is already running" + ) + audit.info("catalog update started") + app.state.spawn_catalog_update() + return {"started": True} + + @app.get("/v1/catalog/lookup", dependencies=auth) + def catalog_lookup(domain: str) -> dict[str, Any]: + """The categories and sources that list ``domain`` (or a parent of it).""" + config = _catalog_config() + labels = {c["id"]: c["label"] for c in config.categories} + host = _domain_param(domain) + result = explain( + host, + None, + filters.lists.root / "-none-", + catalog_paths.catalog_dir, + labels, + time.time(), + ) + return {k: result[k] for k in ("host", "listed_in", "sources")} + # ---------------------------------------------------- write-only secrets (ADR-020) @app.put( "/v1/secrets/{name}", @@ -386,6 +504,155 @@ def reload_noauth(name: str) -> dict[str, Any]: status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) ) from exc + # ------------------------------------------- category filter per instance (ADR-022) + def _domain_param(domain: str) -> str: + try: + return normalize_domain(domain)[1:] + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc) + ) from exc + + @app.get("/v1/instances/{name}/filter", dependencies=auth) + def get_filter(name: str) -> dict[str, Any]: + _require(name) + return _filter_view(name) + + @app.put("/v1/instances/{name}/filter", dependencies=auth) + def put_filter(name: str, body: FilterSettings) -> dict[str, Any]: + """Set categories, schedules and SafeSearch; applied at once to a running instance.""" + _require(name) + config = _catalog_config() + unknown = [c for c in body.categories if c not in config.category_ids] + if unknown: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=f"unknown categories: {', '.join(unknown)}", + ) + filters.write(name, body, config.fail_closed) + audit.info( + "filter set name=%s categories=%s safesearch=%s", + name, + ",".join(body.categories) or "-", + body.safesearch.model_dump(), + ) + return {**_filter_view(name), **_apply_filter(name)} + + @app.post("/v1/instances/{name}/exam", dependencies=auth) + def start_exam(name: str, body: ExamStart) -> dict[str, Any]: + """Exam mode: only ``allowed`` (and their subdomains) until ``minutes`` from now. + + Refused (409, nothing stored) unless the instance runs an image with the filter: an + exam mode that silently does nothing must not exist. + """ + _require(name) + try: + if not docker.filter_active(name): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"the data-plane image of {name!r} has no exam mode yet " + "(lmnsquid update)", + ) + except LookupError as exc: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc + except RuntimeError as exc: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) + ) from exc + until = time.time() + body.minutes * 60 + filters.set_exam( + name, _catalog_config().fail_closed, {"until": until, "allowed": body.allowed} + ) + audit.info( + "exam start name=%s minutes=%d allowed=%s", name, body.minutes, ",".join(body.allowed) + ) + return {**_filter_view(name), **_apply_filter(name)} + + @app.delete("/v1/instances/{name}/exam", dependencies=auth) + def stop_exam(name: str) -> dict[str, Any]: + _require(name) + if filters.read(name) is None: + return {**_filter_view(name), "applied": True} + filters.set_exam(name, _catalog_config().fail_closed, None) + audit.info("exam stop name=%s", name) + return {**_filter_view(name), **_apply_filter(name)} + + @app.get("/v1/instances/{name}/filter/lookup", dependencies=auth) + def filter_lookup(name: str, domain: str) -> dict[str, Any]: + """Why ``domain`` is or is not blocked for this instance ("Warum ist X gesperrt?").""" + _require(name) + host = _domain_param(domain) + labels = {c["id"]: c["label"] for c in _catalog_config().categories} + return explain( + host, + filters.read(name), + filters.lists.dir_for(name), + catalog_paths.catalog_dir, + labels, + time.time(), + ) + + @app.get("/v1/instances/{name}/filter/stats", dependencies=auth) + def filter_stats(name: str, days: int = 30) -> dict[str, Any]: + """Filtered requests per day and category, without users or addresses.""" + _require(name) + if not 1 <= days <= 3650: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="days must be between 1 and 3650", + ) + try: + text = docker.filter_stats(name) + except LookupError as exc: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc + except RuntimeError as exc: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) + ) from exc + return {"name": name, **parse_stats(text, days, time.time())} + + # ---------------------------------------------- exceptions (allowed.domains) + @app.get("/v1/instances/{name}/allowlist", dependencies=auth) + async def get_allowlist(name: str) -> dict[str, Any]: + _require(name) + return {"name": name, "domains": allowed.read(name)} + + @app.post("/v1/instances/{name}/allowlist", dependencies=auth) + async def add_allowed_domain(name: str, entry: BlocklistEntry) -> dict[str, Any]: + """Except ``entry.domain`` and its subdomains from blocklist and categories (after + ``reload``); not from the exam mode.""" + _require(name) + domains = allowed.add(name, entry.domain) + audit.info("allowlist add name=%s domain=%s", name, entry.domain) + return {"name": name, "domains": domains} + + @app.delete("/v1/instances/{name}/allowlist/{domain}", dependencies=auth) + async def remove_allowed_domain(name: str, domain: str) -> dict[str, Any]: + _require(name) + try: + domains = allowed.remove(name, domain) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc) + ) from exc + except KeyError as exc: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"{domain!r} is not on the exception list of {name!r}", + ) from exc + audit.info("allowlist remove name=%s domain=%s", name, domain) + return {"name": name, "domains": domains} + + @app.post("/v1/instances/{name}/allowlist/reload", dependencies=auth) + def reload_allowlist(name: str) -> dict[str, Any]: + """Apply the exceptions now; 409 when the image does not know them.""" + _require(name) + audit.info("allowlist reload name=%s", name) + result = _apply_filter(name) + if not result["applied"]: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=result["detail"]) + return {"name": name, "reloaded": True, "notices": result["notices"]} + # ----------------------------------------------------------- lifecycle ops # start/restart of an instance WITHOUT a container (never created, its creation failed, e.g. # for a missing keytab, or removed by hand) create it from the stored definition, like diff --git a/controlplane/lmnsquid/cli.py b/controlplane/lmnsquid/cli.py index 9b93a34..4354dfd 100644 --- a/controlplane/lmnsquid/cli.py +++ b/controlplane/lmnsquid/cli.py @@ -10,6 +10,7 @@ import os import stat import tempfile +import time from pathlib import Path from typing import Any, Optional from urllib.parse import quote @@ -231,6 +232,266 @@ def noauth_reload(ctx: typer.Context) -> None: _emit(c.post(f"/v1/instances/{ctx.obj}/noauth/reload")) +allowlist_app = typer.Typer( + help="Per-instance exceptions (ADR-022): a listed domain and its subdomains are let through " + "although the instance's blocklist or a filter category names them. Not in exam mode. " + "Changes take effect after `reload`.", + no_args_is_help=True, +) +app.add_typer(allowlist_app, name="allowlist") + + +@allowlist_app.callback() +def _allowlist(ctx: typer.Context, name: str = typer.Argument(..., help="instance name")) -> None: + """Manage the exceptions of one instance: list | add | remove | reload.""" + ctx.obj = name + + +@allowlist_app.command("list") +def allowlist_list(ctx: typer.Context) -> None: + """Show the exceptions.""" + with _get_client() as c: + _emit(c.get(f"/v1/instances/{ctx.obj}/allowlist")) + + +@allowlist_app.command("add") +def allowlist_add(ctx: typer.Context, domain: str) -> None: + """Except a domain and all its subdomains (then `reload`).""" + with _get_client() as c: + _emit(c.post(f"/v1/instances/{ctx.obj}/allowlist", json={"domain": domain})) + + +@allowlist_app.command("remove") +def allowlist_remove(ctx: typer.Context, domain: str) -> None: + """Remove an exception (then `reload`).""" + with _get_client() as c: + _emit(c.delete(f"/v1/instances/{ctx.obj}/allowlist/{quote(domain, safe='')}")) + + +@allowlist_app.command("reload") +def allowlist_reload(ctx: typer.Context) -> None: + """Apply the exceptions without a restart; fails if the instance's image ignores them.""" + with _get_client() as c: + _emit(c.post(f"/v1/instances/{ctx.obj}/allowlist/reload")) + + +catalog_app = typer.Typer( + help="The host-wide category catalog of the filter (ADR-022): UT1 (CC BY-SA 4.0) and " + "HaGeZi (GPL-3.0) lists, downloaded on this host, rebuilt nightly by a systemd timer.", + no_args_is_help=True, +) +app.add_typer(catalog_app, name="catalog") + + +@catalog_app.command("status") +def catalog_status() -> None: + """Age, size, categories, sources and licences, the last update run and the profiles.""" + with _get_client() as c: + _emit(c.get("/v1/catalog")) + + +@catalog_app.command("update") +def catalog_update( + wait: bool = typer.Option(False, "--wait", help="wait for the build and show its result"), +) -> None: + """Download the sources and build a new catalog (in the background, about a minute).""" + with _get_client() as c: + resp = c.post("/v1/catalog/update") + if not wait or resp.status_code >= 400: + _emit(resp) + return + for _ in range(1800): + time.sleep(2) + info = c.get("/v1/catalog") + if info.status_code >= 400 or not info.json().get("building"): + break + if info.status_code >= 400: + _emit(info) + last = info.json().get("last_run", {}) + typer.echo(json.dumps(last, indent=2, ensure_ascii=False)) + if last.get("state") != "ok": + raise typer.Exit(1) + + +@catalog_app.command("lookup") +def catalog_lookup(domain: str) -> None: + """The categories and sources that list a domain (independent of an instance).""" + with _get_client() as c: + _emit(c.get("/v1/catalog/lookup", params={"domain": domain})) + + +filter_app = typer.Typer( + help="Per-instance filter (ADR-022): categories, schedules, SafeSearch, exam mode, " + '"why is X blocked?" and statistics. Changes apply at once to a running instance.', + no_args_is_help=True, +) +app.add_typer(filter_app, name="filter") + + +@filter_app.callback() +def _filter(ctx: typer.Context, name: str = typer.Argument(..., help="instance name")) -> None: + """Manage the filter of one instance.""" + ctx.obj = name + + +@filter_app.command("show") +def filter_show(ctx: typer.Context) -> None: + """Show categories, schedules, SafeSearch and the exam mode.""" + with _get_client() as c: + _emit(c.get(f"/v1/instances/{ctx.obj}/filter")) + + +def _put_settings(c: httpx.Client, name: str, settings: dict[str, Any]) -> None: + _emit(c.put(f"/v1/instances/{name}/filter", json=settings)) + + +def _current(c: httpx.Client, name: str) -> dict[str, Any]: + resp = c.get(f"/v1/instances/{name}/filter") + if resp.status_code >= 400: + _emit(resp) + return dict(resp.json()["settings"]) + + +@filter_app.command("set") +def filter_set( + ctx: typer.Context, + category: list[str] = typer.Option( + [], "--category", help="category id (repeat); replaces the active set" + ), + add: list[str] = typer.Option([], "--add", help="activate a category (repeat)"), + remove: list[str] = typer.Option([], "--remove", help="deactivate a category (repeat)"), + none: bool = typer.Option(False, "--none", help="deactivate every category"), + google: Optional[bool] = typer.Option(None, help="SafeSearch for Google search"), + youtube: Optional[str] = typer.Option( + None, help="YouTube restricted mode: off|strict|moderate" + ), + bing: Optional[bool] = typer.Option(None, help="SafeSearch for Bing"), + duckduckgo: Optional[bool] = typer.Option(None, help="SafeSearch for DuckDuckGo"), +) -> None: + """Change categories and SafeSearch; only what you pass changes. Ids: `catalog status`.""" + with _get_client() as c: + settings = _current(c, ctx.obj) + cats: list[str] = [] if none else (list(category) or list(settings["categories"])) + cats += [x for x in add if x not in cats] + cats = [x for x in cats if x not in remove] + settings["categories"] = cats + settings["schedules"] = {k: v for k, v in settings["schedules"].items() if k in cats} + safe = settings["safesearch"] + for key, value in ( + ("google", google), + ("youtube", youtube), + ("bing", bing), + ("duckduckgo", duckduckgo), + ): + if value is not None: + safe[key] = value + _put_settings(c, ctx.obj, settings) + + +@filter_app.command("profile") +def filter_profile( + ctx: typer.Context, profile: str = typer.Argument(..., help="students | teachers") +) -> None: + """Apply a profile: its categories and SafeSearch replace the current ones.""" + with _get_client() as c: + catalog = c.get("/v1/catalog") + if catalog.status_code >= 400: + _emit(catalog) + profiles = catalog.json().get("profiles", {}) + if profile not in profiles: + typer.secho( + f"unknown profile {profile!r}; known: {', '.join(profiles)}", + fg=typer.colors.RED, + err=True, + ) + raise typer.Exit(1) + chosen = profiles[profile] + _put_settings( + c, + ctx.obj, + { + "categories": chosen["categories"], + "schedules": {}, + "safesearch": chosen.get("safesearch", {}), + }, + ) + + +@filter_app.command("schedule") +def filter_schedule( + ctx: typer.Context, + category: str, + days: str = typer.Option(..., help="e.g. mo,tu,we,th,fr"), + start: str = typer.Option(..., "--from", help="HH:MM"), + end: str = typer.Option(..., "--to", help="HH:MM"), + replace: bool = typer.Option(False, help="replace the category's windows instead of adding"), +) -> None: + """Block an active category only inside time windows (local time of the proxy host).""" + with _get_client() as c: + settings = _current(c, ctx.obj) + window = { + "days": [d.strip() for d in days.split(",") if d.strip()], + "start": start, + "end": end, + } + windows = [] if replace else list(settings["schedules"].get(category, [])) + settings["schedules"][category] = [*windows, window] + _put_settings(c, ctx.obj, settings) + + +@filter_app.command("unschedule") +def filter_unschedule(ctx: typer.Context, category: str) -> None: + """Block the category all the time again (drop its windows).""" + with _get_client() as c: + settings = _current(c, ctx.obj) + settings["schedules"].pop(category, None) + _put_settings(c, ctx.obj, settings) + + +@filter_app.command("exam-start") +def filter_exam_start( + ctx: typer.Context, + minutes: int = typer.Option(..., help="duration; the exam mode ends by itself"), + allow: list[str] = typer.Option([], "--allow", help="reachable domain (repeat)"), + school_server: bool = typer.Option( + True, help="also allow the school's AD domain (the realm in lower case)" + ), +) -> None: + """Exam mode: only the allowed domains, at once, until the time is up. Domains without + proxy login (noauth) are NOT reachable in exam mode.""" + with _get_client() as c: + domains = list(allow) + if school_server: + inst = c.get(f"/v1/instances/{ctx.obj}") + if inst.status_code >= 400: + _emit(inst) + domains.append(str(inst.json()["realm"]).lower()) + _emit( + c.post(f"/v1/instances/{ctx.obj}/exam", json={"minutes": minutes, "allowed": domains}) + ) + + +@filter_app.command("exam-stop") +def filter_exam_stop(ctx: typer.Context) -> None: + """End the exam mode now.""" + with _get_client() as c: + _emit(c.delete(f"/v1/instances/{ctx.obj}/exam")) + + +@filter_app.command("lookup") +def filter_lookup(ctx: typer.Context, domain: str) -> None: + """Why is a domain blocked (or not) for this instance: rule, category, list entry, source.""" + with _get_client() as c: + _emit(c.get(f"/v1/instances/{ctx.obj}/filter/lookup", params={"domain": domain})) + + +@filter_app.command("stats") +def filter_stats(ctx: typer.Context, days: int = typer.Option(30)) -> None: + """Filtered requests per day and category (no users, no addresses).""" + with _get_client() as c: + _emit(c.get(f"/v1/instances/{ctx.obj}/filter/stats", params={"days": days})) + + @app.command() def start(name: str) -> None: """Start the instance container.""" diff --git a/controlplane/lmnsquid/docker_service.py b/controlplane/lmnsquid/docker_service.py index 8e72a7d..c3a575b 100644 --- a/controlplane/lmnsquid/docker_service.py +++ b/controlplane/lmnsquid/docker_service.py @@ -18,6 +18,7 @@ from docker.types import LogConfig, Mount from .blocklist import CONTAINER_DIR, Blocklist, noauth_list +from .filters import FilterStore from .models import KRB5_CLOCKSKEW_DEFAULT, Instance logger = logging.getLogger("lmnsquid.docker") @@ -81,6 +82,14 @@ def keytab_problem(secrets_dir: str, keytab_secret: str) -> Optional[str]: f"exec squid -k reconfigure -f {_SQUID_CONF}" ) _NOTICE_PREFIX = "linuxmuster-squid: " +# The host-wide category catalog, mounted read-only into every container (ADR-022). +CATALOG_CONTAINER_DIR = "/etc/squid/catalog" +# Anonymous filter statistics (day + category per filtered request) summed per day; the +# category ids are the catalog's ([a-z0-9_]), nothing from a request is in this text. +_FILTER_STATS = ( + "zcat -f /var/log/squid/filter.log* 2>/dev/null" + " | awk 'NF == 2 { c[$1 \" \" $2]++ } END { for (k in c) print k, c[k] }'" +) # Container label carrying the fingerprint of everything the container was created # from; a container whose label matches the desired spec is left alone by # ensure_running (reconcile is a no-op for it), one without or with another @@ -105,6 +114,8 @@ def __init__( blocklists_dir: str = "/etc/linuxmuster-squid/blocklists", health_timeout: float = 90.0, poll_interval: float = 2.0, + catalog_dir: str = "/var/lib/linuxmuster-squid/catalog", + filter_timezone: Optional[str] = None, ) -> None: self.docker_host: Optional[str] = docker_host self.secrets_dir: str = secrets_dir @@ -113,6 +124,8 @@ def __init__( self.log_max_file: int = log_max_file self.blocklist = Blocklist(blocklists_dir) self.noauth = noauth_list(blocklists_dir) + self.filters = FilterStore(blocklists_dir, filter_timezone) + self.catalog_dir = catalog_dir self.health_timeout = health_timeout self.poll_interval = poll_interval self.client: docker.DockerClient = ( @@ -214,6 +227,9 @@ def spec_for(self, inst: Instance) -> dict[str, Any]: "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"}, }, @@ -255,6 +271,10 @@ def ensure_running(self, inst: Instance) -> dict[str, Any]: # one is an empty list to lists-sync.sh, which reads it again on every reload). self.blocklist.ensure(inst.name) self.noauth.ensure(inst.name) + # 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) + self.filters.refresh_safesearch(inst.name) cname = inst.container_name existing = self._get(inst.name) @@ -437,6 +457,27 @@ def noauth_active(self, name: str) -> bool: raise RuntimeError(f"cannot read {_SQUID_CONF} (exit {exit_code}): {text.strip()}") return exit_code == 0 + def filter_active(self, name: str) -> bool: + """Whether the running squid has the category filter (ADR-022) in its configuration. + + Not so for an image from before it; same preconditions and errors as :meth:`reload`. + """ + container = self._running(name) + exit_code, text = self._exec( + container, ["grep", "-qF", "external_acl_type lmn_filter ", _SQUID_CONF] + ) + if exit_code not in (0, 1): + raise RuntimeError(f"cannot read {_SQUID_CONF} (exit {exit_code}): {text.strip()}") + return exit_code == 0 + + def filter_stats(self, name: str) -> str: + """`` `` lines from the filter statistics log (needs exec).""" + container = self._running(name) + exit_code, text = self._exec(container, ["sh", "-c", _FILTER_STATS]) + if exit_code != 0: + raise RuntimeError(f"filter statistics exited {exit_code}: {text.strip()}") + return text + def reload(self, name: str) -> dict[str, Any]: """Make the running squid re-read squid.conf and its ACL list files (both lists). diff --git a/controlplane/lmnsquid/filters.py b/controlplane/lmnsquid/filters.py new file mode 100644 index 0000000..1f0c80e --- /dev/null +++ b/controlplane/lmnsquid/filters.py @@ -0,0 +1,450 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Filter settings of one instance: categories, schedules, SafeSearch, exceptions, exam mode. + +Everything lives in the instance's list directory (``//``, mounted +read-only at ``/etc/squid/lists``, ADR-014), so no container spec changes for it: + +* ``filter.json``: what the helper reads (``lmnsquid.filterdecision``), written atomically by + this module only. No file = the instance has no filter (the state of every instance after + the upgrade: nothing changes until an admin sets categories). +* ``allowed.domains``: the admin's exceptions, managed like the blocklist. +* ``safesearch.hosts``: ``
`` lines for squid's ``hosts_file``; the addresses of + the SafeSearch services are resolved here, at every change and every container (re)creation; + a failed lookup keeps the last known address. +""" + +from __future__ import annotations + +import json +import os +import re +import socket +import tempfile +import time +from collections.abc import Callable +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, field_validator, model_validator + +from . import catalog as catalog_mod +from . import filterdecision as fd +from .blocklist import Blocklist, normalize_domain + +FILTER_FILE = "filter.json" +ALLOWED_FILE = "allowed.domains" +SAFESEARCH_FILE = "safesearch.hosts" +EXAM_MAX_MINUTES = 12 * 60 +_TIME_RE = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$|^24:00$") + +# The documented SafeSearch services (work/linuxmuster-squid/recherche-filterlisten.md, 3.1). +GOOGLE_VIP = "forcesafesearch.google.com" +YOUTUBE_VIP = {"strict": "restrict.youtube.com", "moderate": "restrictmoderate.youtube.com"} +YOUTUBE_HOSTS = ( + "www.youtube.com", + "m.youtube.com", + "youtubei.googleapis.com", + "youtube.googleapis.com", + "www.youtube-nocookie.com", +) +BING_VIP = "strict.bing.com" +BING_HOSTS = ("www.bing.com", "bing.com") +DDG_VIP = "safe.duckduckgo.com" +DDG_HOSTS = ("duckduckgo.com", "www.duckduckgo.com") +# Last resort when neither a lookup nor an earlier one gave an address (Google's documented +# example address); Bing and DuckDuckGo document no fixed address, so they get none. +FALLBACK = { + GOOGLE_VIP: "216.239.38.120", + "restrict.youtube.com": "216.239.38.120", + "restrictmoderate.youtube.com": "216.239.38.119", +} + + +def allowed_list(root: str) -> Blocklist: + """The exceptions of the instances under ``root`` (same format as the blocklist).""" + return Blocklist(root, ALLOWED_FILE, normalize_domain) + + +def google_domains() -> list[str]: + text = (catalog_mod.DATA_DIR / "google-domains.txt").read_text(encoding="utf-8") + return [line.strip() for line in text.splitlines() if line.strip() and line[0] != "#"] + + +def host_timezone() -> str: + """The proxy host's zone name (schedules are local school time).""" + try: + name = Path("/etc/timezone").read_text(encoding="utf-8").strip() + if name: + return name + except OSError: + pass + try: + target = os.readlink("/etc/localtime") + if "zoneinfo/" in target: + return target.split("zoneinfo/", 1)[1] + except OSError: + pass + return "UTC" + + +# ------------------------------------------------------------------------------- models +class Window(BaseModel): + """A time window of a schedule: the category blocks only inside it (local time).""" + + days: list[Literal["mo", "tu", "we", "th", "fr", "sa", "su"]] + start: str + end: str + + @field_validator("days") + @classmethod + def _v_days(cls, v: list[str]) -> list[str]: + if not v: + raise ValueError("at least one day") + return [d for d in fd.DAYS if d in v] + + @field_validator("start", "end") + @classmethod + def _v_time(cls, v: str) -> str: + if not _TIME_RE.match(v): + raise ValueError("time as HH:MM") + return v + + @model_validator(mode="after") + def _v_order(self) -> "Window": + if fd._minutes(self.start) >= fd._minutes(self.end): + raise ValueError("start must be before end") + return self + + +class SafeSearch(BaseModel): + google: bool = False + youtube: Literal["off", "strict", "moderate"] = "off" + bing: bool = False + duckduckgo: bool = False + + @property + def on(self) -> bool: + return self.google or self.youtube != "off" or self.bing or self.duckduckgo + + +class FilterSettings(BaseModel): + """Body of ``PUT /v1/instances/{name}/filter`` (the exam mode has its own endpoint).""" + + categories: list[str] = [] + schedules: dict[str, list[Window]] = {} + safesearch: SafeSearch = SafeSearch() + + @model_validator(mode="after") + def _v_schedules(self) -> "FilterSettings": + self.categories = list(dict.fromkeys(self.categories)) + for category, windows in self.schedules.items(): + if category not in self.categories: + raise ValueError(f"schedule for {category!r}, which is not an active category") + if len(windows) > 20: + raise ValueError("at most 20 windows per category") + self.schedules = {k: v for k, v in self.schedules.items() if v} + return self + + +class ExamStart(BaseModel): + """Body of ``POST /v1/instances/{name}/exam``: only ``allowed`` is reachable until the end.""" + + minutes: int + allowed: list[str] = [] + + @field_validator("minutes") + @classmethod + def _v_minutes(cls, v: int) -> int: + if not 1 <= v <= EXAM_MAX_MINUTES: + raise ValueError(f"minutes must be between 1 and {EXAM_MAX_MINUTES}") + return v + + @field_validator("allowed") + @classmethod + def _v_allowed(cls, v: list[str]) -> list[str]: + if len(v) > 200: + raise ValueError("at most 200 domains") + return sorted({normalize_domain(d)[1:] for d in v}) + + +# ------------------------------------------------------------------------------- store +Resolver = Callable[[str], str | None] + + +def resolve_ipv4(name: str) -> str | None: + try: + infos = socket.getaddrinfo(name, 443, socket.AF_INET, socket.SOCK_STREAM) + except OSError: + return None + return str(infos[0][4][0]) if infos else None + + +def _atomic_write(path: Path, text: str) -> None: + fd_, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") + try: + with os.fdopen(fd_, "w", encoding="utf-8") as fh: + fh.write(text) + os.chmod(tmp, 0o644) + os.replace(tmp, path) + except BaseException: + if os.path.exists(tmp): + os.unlink(tmp) + raise + + +class FilterStore: + """Read and write the filter files of the instances under ``root``.""" + + def __init__( + self, + root: str, + timezone: str | None = None, + resolver: Resolver = resolve_ipv4, + ) -> None: + self.lists = Blocklist(root) # for dir_for/ensure (name check, modes) + self.allowed = allowed_list(root) + self.timezone = timezone or host_timezone() + self.resolver = resolver + + def path(self, name: str) -> Path: + return self.lists.dir_for(name) / FILTER_FILE + + def read(self, name: str) -> dict[str, Any] | None: + try: + data = json.loads(self.path(name).read_text(encoding="utf-8")) + except FileNotFoundError: + return None + except (OSError, ValueError): + return {"broken": True} + return data if isinstance(data, dict) else {"broken": True} + + def settings(self, name: str) -> FilterSettings: + data = self.read(name) or {} + if data.get("broken"): + return FilterSettings() + return FilterSettings.model_validate( + {k: data.get(k) for k in ("categories", "schedules", "safesearch") if k in data} + ) + + def write( + self, + name: str, + settings: FilterSettings, + fail_closed: set[str], + exam: dict[str, Any] | None | Literal["keep"] = "keep", + ) -> dict[str, Any]: + """Write ``filter.json`` and ``safesearch.hosts``; return what was written.""" + self.lists.ensure(name) + previous = self.read(name) or {} + if exam == "keep": + exam = previous.get("exam") if not previous.get("broken") else None + if exam and float(exam.get("until", 0)) <= time.time(): + exam = None # an expired exam is cleared on the next write + resolved, hosts = self.safesearch_hosts(settings.safesearch, previous.get("resolved")) + data = { + "format": fd.FORMAT, + "categories": settings.categories, + "schedules": {k: [w.model_dump() for w in v] for k, v in settings.schedules.items()}, + "safesearch": settings.safesearch.model_dump(), + "fail_closed": sorted(fail_closed & set(settings.categories)), + "timezone": self.timezone, + "exam": exam, + "resolved": resolved, + "updated": time.time(), + } + directory = self.lists.dir_for(name) + _atomic_write(directory / SAFESEARCH_FILE, hosts) + _atomic_write(directory / FILTER_FILE, json.dumps(data, indent=1) + "\n") + return data + + def refresh_safesearch(self, name: str) -> bool: + """Resolve the SafeSearch addresses again (container (re)creation); True if changed.""" + data = self.read(name) + if not data or data.get("broken"): + return False + safesearch = SafeSearch.model_validate(data.get("safesearch") or {}) + if not safesearch.on: + return False + resolved, hosts = self.safesearch_hosts(safesearch, data.get("resolved")) + target = self.lists.dir_for(name) / SAFESEARCH_FILE + try: + unchanged = target.read_text(encoding="utf-8") == hosts + except OSError: + unchanged = False + if unchanged: + return False + data["resolved"] = resolved + _atomic_write(target, hosts) + _atomic_write(self.path(name), json.dumps(data, indent=1) + "\n") + return True + + def safesearch_hosts( + self, safesearch: SafeSearch, known: dict[str, str] | None + ) -> tuple[dict[str, str], str]: + """(resolved VIP addresses, content of safesearch.hosts) for ``safesearch``.""" + known = dict(known or {}) + resolved: dict[str, str] = {} + + def address(vip: str) -> str | None: + found = self.resolver(vip) or known.get(vip) or FALLBACK.get(vip) + if found: + resolved[vip] = found + return found + + lines: list[str] = [] + if safesearch.google: + ip = address(GOOGLE_VIP) + if ip: + for domain in google_domains(): + lines += [f"{ip} {domain}", f"{ip} www.{domain}", f"{ip} images.{domain}"] + if safesearch.youtube != "off": + ip = address(YOUTUBE_VIP[safesearch.youtube]) + if ip: + lines += [f"{ip} {host}" for host in YOUTUBE_HOSTS] + for on, vip, hosts in ( + (safesearch.bing, BING_VIP, BING_HOSTS), + (safesearch.duckduckgo, DDG_VIP, DDG_HOSTS), + ): + if on: + ip = address(vip) + if ip: + lines += [f"{ip} {host}" for host in hosts] + # One address per name in squid's hosts_file: a later line would replace an earlier one. + seen: set[str] = set() + unique: list[str] = [] + for line in lines: + host = line.split()[1] + if host not in seen: + seen.add(host) + unique.append(line) + return resolved, "".join(f"{line}\n" for line in unique) + + def set_exam( + self, name: str, fail_closed: set[str], exam: dict[str, Any] | None + ) -> dict[str, Any]: + return self.write(name, self.settings(name), fail_closed, exam) + + +# ------------------------------------------------------------------------------- views +def summary( + data: dict[str, Any] | None, catalog_info: dict[str, Any], now: float +) -> dict[str, Any]: + """The per-instance filter state for status lists (additive fields of /v1/status).""" + if data is None: + return {"configured": False, "categories": 0, "exam_until": None, "problem": None} + if data.get("broken"): + return {"configured": True, "categories": 0, "exam_until": None, "problem": "broken"} + exam = data.get("exam") or {} + until = float(exam["until"]) if exam.get("until") and float(exam["until"]) > now else None + problem = None + if data.get("categories"): + if not catalog_info.get("available"): + problem = ( + "catalog_missing_fail_closed" if data.get("fail_closed") else "catalog_missing" + ) + elif catalog_info.get("old"): + problem = "catalog_old" + return { + "configured": True, + "categories": len(data.get("categories") or []), + "safesearch": (data.get("safesearch") or {}), + "exam_until": until, + "problem": problem, + } + + +def explain( + host: str, + data: dict[str, Any] | None, + directory: Path, + catalog_dir: Path, + labels: dict[str, str], + now: float, +) -> dict[str, Any]: + """Why ``host`` is (not) blocked for the instance whose list directory is ``directory``.""" + name = fd.host_of(host) + blocked_own = fd.listed(name, fd.read_domains(str(directory / "blocked.domains"))) + noauth = fd.listed(name, fd.read_domains(str(directory / "noauth.domains"))) + allowed = fd.read_domains(str(directory / ALLOWED_FILE)) + if data is None: + policy = fd.Policy(allowed=allowed) + elif data.get("broken"): + policy = fd.Policy(allowed=allowed, broken="filter.json unreadable") + else: + policy = fd.Policy.from_dict(data, allowed) + current = catalog_dir / catalog_mod.CURRENT + cat: fd.Catalog | None = None + error = "" + try: + cat = fd.Catalog(str(current)) + except Exception as exc: # noqa: BLE001 - reported as "catalog unavailable" + error = "no catalog" if not current.exists() else str(exc) + fd.PROTECTED_FILE = str(catalog_dir / "protected.domains") + try: + verdict = fd.decide(name, policy, cat, now, error) + listed_in: list[dict[str, Any]] = [] + if cat is not None: + cmask, smask, hits = cat.lookup(name) + listed_in = [ + { + "category": cid, + "label": labels.get(cid, cid), + "active": cid in policy.categories, + "entries": sorted(n for n, c in hits.items() if c & (1 << bit)), + } + for cid, bit in cat.bits.items() + if cmask & (1 << bit) + ] + sources = [ + {"id": sid, "name": sname, "license": lic} + for bit, (sid, sname, lic) in cat.sources.items() + if smask & (1 << bit) + ] + else: + sources = [] + finally: + if cat is not None: + cat.close() + blocked = bool(blocked_own and verdict.decision != fd.EXCEPTION) or verdict.blocked + if blocked_own and verdict.decision == fd.EXCEPTION: + rule = "exception" # an exception beats the own blocklist (squid.conf) + elif verdict.blocked: + rule = verdict.decision + elif blocked_own: + rule = "blocklist" + else: + rule = verdict.decision + return { + "host": name, + "blocked": blocked, + "rule": rule, + "category": verdict.category, + "category_label": labels.get(verdict.category or "", verdict.category), + "entry": verdict.entry or blocked_own, + "detail": verdict.detail, + "own_blocklist": blocked_own, + "noauth": noauth, + "listed_in": listed_in, + "sources": sources, + "exam_active": policy.exam_active(now), + "active_categories": policy.active_categories(now), + } + + +def parse_stats(text: str, days: int, now: float) -> dict[str, Any]: + """`` `` lines -> per day and in total, newest day first.""" + first = time.strftime("%Y-%m-%d", time.localtime(now - (days - 1) * 86400)) + per_day: dict[str, dict[str, int]] = {} + total: dict[str, int] = {} + for line in text.splitlines(): + parts = line.split() + if len(parts) != 3 or not parts[2].isdigit() or parts[0] < first: + continue + day, category, count = parts[0], parts[1], int(parts[2]) + per_day.setdefault(day, {})[category] = per_day.get(day, {}).get(category, 0) + count + total[category] = total.get(category, 0) + count + return { + "days": [{"date": d, "categories": per_day[d]} for d in sorted(per_day, reverse=True)], + "total": total, + } diff --git a/controlplane/lmnsquid/main.py b/controlplane/lmnsquid/main.py index f97dcac..92df61d 100644 --- a/controlplane/lmnsquid/main.py +++ b/controlplane/lmnsquid/main.py @@ -60,6 +60,8 @@ def main() -> None: settings.log_max_size, settings.log_max_file, settings.blocklists_dir, + catalog_dir=settings.catalog_dir, + filter_timezone=settings.filter_timezone, ) reconciler = Reconciler(store, docker) updater = Updater(store, docker, reconciler) diff --git a/controlplane/tests/test_cli.py b/controlplane/tests/test_cli.py index 37ce07e..311c18a 100644 --- a/controlplane/tests/test_cli.py +++ b/controlplane/tests/test_cli.py @@ -191,3 +191,69 @@ def test_cli_edit_and_version(patch_client: None, instance_data: dict[str, Any]) v = runner.invoke(cli.app, ["version"]) assert v.exit_code == 0 and "version" in v.output + + +def test_cli_filter_catalog_and_allowlist( + patch_client: None, + client: Any, + auth_headers: dict[str, str], + instance_data: dict[str, Any], + settings: Any, +) -> None: + import json as _json + from pathlib import Path + + client.post("/v1/instances", json=instance_data, headers=auth_headers) + name = "default-school-teachers" + r = runner.invoke(cli.app, ["filter", name, "profile", "students"]) + assert r.exit_code == 0, r.output + data = _json.loads((Path(settings.blocklists_dir) / name / "filter.json").read_text()) + assert "porn" in data["categories"] and data["safesearch"]["youtube"] == "strict" + r = runner.invoke( + cli.app, + ["filter", name, "set", "--add", "games", "--remove", "dating", "--youtube", "moderate"], + ) + assert r.exit_code == 0, r.output + data = _json.loads((Path(settings.blocklists_dir) / name / "filter.json").read_text()) + assert "games" in data["categories"] and "dating" not in data["categories"] + assert data["safesearch"]["youtube"] == "moderate" and data["safesearch"]["google"] is True + r = runner.invoke( + cli.app, + [ + "filter", + name, + "schedule", + "games", + "--days", + "mo,tu", + "--from", + "08:00", + "--to", + "13:00", + ], + ) + assert r.exit_code == 0, r.output + data = _json.loads((Path(settings.blocklists_dir) / name / "filter.json").read_text()) + assert data["schedules"]["games"][0]["start"] == "08:00" + assert runner.invoke(cli.app, ["filter", name, "unschedule", "games"]).exit_code == 0 + r = runner.invoke( + cli.app, ["filter", name, "exam-start", "--minutes", "30", "--allow", "moodle.example.org"] + ) + assert r.exit_code == 0, r.output + data = _json.loads((Path(settings.blocklists_dir) / name / "filter.json").read_text()) + assert data["exam"]["allowed"] == ["example.lan", "moodle.example.org"] # + the realm + assert runner.invoke(cli.app, ["filter", name, "exam-stop"]).exit_code == 0 + assert runner.invoke(cli.app, ["filter", name, "profile", "nope"]).exit_code == 1 + assert runner.invoke(cli.app, ["filter", name, "set", "--add", "nope"]).exit_code == 1 + assert runner.invoke(cli.app, ["filter", name, "set", "--none"]).exit_code == 0 + r = runner.invoke(cli.app, ["filter", name, "lookup", "example.org"]) + assert r.exit_code == 0 and '"rule": "none"' in r.output + assert runner.invoke(cli.app, ["filter", name, "show"]).exit_code == 0 + assert runner.invoke(cli.app, ["filter", name, "stats"]).exit_code == 0 + assert runner.invoke(cli.app, ["allowlist", name, "add", "wiki.example"]).exit_code == 0 + assert ".wiki.example" in runner.invoke(cli.app, ["allowlist", name, "list"]).output + assert runner.invoke(cli.app, ["allowlist", name, "reload"]).exit_code == 0 + assert runner.invoke(cli.app, ["allowlist", name, "remove", "wiki.example"]).exit_code == 0 + r = runner.invoke(cli.app, ["catalog", "status"]) + assert r.exit_code == 0 and '"available": false' in r.output + assert runner.invoke(cli.app, ["catalog", "lookup", "a.example"]).exit_code == 0 diff --git a/controlplane/tests/test_docker_service.py b/controlplane/tests/test_docker_service.py index 4097255..8a43aee 100644 --- a/controlplane/tests/test_docker_service.py +++ b/controlplane/tests/test_docker_service.py @@ -14,6 +14,7 @@ from lmnsquid.blocklist import Blocklist, noauth_list from lmnsquid.docker_service import SPEC_LABEL, DockerService +from lmnsquid.filters import FilterStore from lmnsquid.models import Instance @@ -27,6 +28,8 @@ def _service(tmp_path: Path) -> DockerService: (tmp_path / "secrets" / "proxy.keytab").chmod(0o600) ds.blocklist = Blocklist(str(tmp_path / "blocklists")) ds.noauth = noauth_list(str(tmp_path / "blocklists")) + ds.filters = FilterStore(str(tmp_path / "blocklists")) + ds.catalog_dir = str(tmp_path / "catalog") ds.container_bind_ip = "0.0.0.0" ds.log_max_size = "20m" ds.log_max_file = 5 @@ -79,9 +82,14 @@ def test_fingerprint_is_stable_and_sensitive(tmp_path: Path) -> None: spec = ds.spec_for(_inst()) blocklist_dir = str(tmp_path / "blocklists" / "s-teachers") assert spec["volumes"][blocklist_dir]["bind"] == "/etc/squid/lists" - # The noauth list lives in the same mounted directory: no mount of its own, so the - # spec (and with it every container an upgrade would otherwise replace) is unchanged. - assert len(spec["volumes"]) == 4 + # The noauth list lives in the same mounted directory: no mount of its own. The category + # catalog (ADR-022) is the fifth mount: one replacement per container, done by the + # update-all of the release that pins the image with the filter. + assert len(spec["volumes"]) == 5 + assert spec["volumes"][str(tmp_path / "catalog")] == { + "bind": "/etc/squid/catalog", + "mode": "ro", + } assert not any("noauth" in str(k) or "noauth" in str(v) for k, v in spec.items()) diff --git a/controlplane/tests/test_filter_api.py b/controlplane/tests/test_filter_api.py new file mode 100644 index 0000000..f515a8d --- /dev/null +++ b/controlplane/tests/test_filter_api.py @@ -0,0 +1,326 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Category filter through the API (ADR-022): settings, apply/reload, exam mode, exceptions, +lookup, statistics, catalog endpoints; plus the filter store (SafeSearch hosts, models).""" + +from __future__ import annotations + +import json +import time +from pathlib import Path +from typing import Any + +import pytest +from conftest import make_catalog +from pydantic import ValidationError + +from lmnsquid import filters as fm + +NAME = "default-school-teachers" + + +@pytest.fixture +def created(client: Any, auth_headers: dict[str, str], instance_data: dict[str, Any]) -> str: + assert client.post("/v1/instances", json=instance_data, headers=auth_headers).status_code == 201 + return NAME + + +def _put(client: Any, headers: dict[str, str], **body: Any) -> Any: + return client.put(f"/v1/instances/{NAME}/filter", json=body, headers=headers) + + +def _filter_file(settings: Any) -> dict[str, Any]: + return json.loads((Path(settings.blocklists_dir) / NAME / "filter.json").read_text()) + + +# ---------------------------------------------------------------- auth +@pytest.mark.parametrize( + ("method", "path"), + [ + ("get", "/v1/catalog"), + ("post", "/v1/catalog/update"), + ("get", "/v1/catalog/lookup?domain=a.example"), + ("get", f"/v1/instances/{NAME}/filter"), + ("put", f"/v1/instances/{NAME}/filter"), + ("post", f"/v1/instances/{NAME}/exam"), + ("delete", f"/v1/instances/{NAME}/exam"), + ("get", f"/v1/instances/{NAME}/filter/lookup?domain=a.example"), + ("get", f"/v1/instances/{NAME}/filter/stats"), + ("get", f"/v1/instances/{NAME}/allowlist"), + ("post", f"/v1/instances/{NAME}/allowlist/reload"), + ], +) +def test_new_endpoints_need_the_token(client: Any, method: str, path: str) -> None: + assert getattr(client, method)(path).status_code == 401 + + +# ---------------------------------------------------------------- settings +def test_unconfigured_instance_has_no_filter( + client: Any, auth_headers: Any, created: str, settings: Any +) -> None: + view = client.get(f"/v1/instances/{NAME}/filter", headers=auth_headers).json() + assert view["configured"] is False and view["settings"]["categories"] == [] + assert not (Path(settings.blocklists_dir) / NAME / "filter.json").exists() + state = client.get("/v1/status", headers=auth_headers).json()[0] + assert state["filter"] == { + "configured": False, + "categories": 0, + "exam_until": None, + "problem": None, + } + + +def test_set_categories_writes_and_reloads( + client: Any, auth_headers: Any, created: str, settings: Any, docker: Any +) -> None: + resp = _put( + client, + auth_headers, + categories=["porn", "ads", "porn"], + safesearch={"google": True, "youtube": "strict"}, + ) + assert resp.status_code == 200, resp.text + body = resp.json() + assert body["applied"] is True and docker.reloaded == [NAME] + data = _filter_file(settings) + assert data["categories"] == ["porn", "ads"] + assert data["fail_closed"] == ["porn"] + assert data["timezone"] == "Europe/Berlin" and data["exam"] is None + # the protected list is put next to the catalog for the helper + assert (Path(settings.catalog_dir) / "protected.domains").is_file() + # no catalog yet: the status says requests are refused + state = client.get("/v1/status", headers=auth_headers).json()[0] + assert state["filter"]["problem"] == "catalog_missing_fail_closed" + + +def test_unknown_category_and_bad_schedule_are_422( + client: Any, auth_headers: Any, created: str +) -> None: + assert _put(client, auth_headers, categories=["nope"]).status_code == 422 + bad = {"social": [{"days": ["mo"], "start": "13:00", "end": "08:00"}]} + assert _put(client, auth_headers, categories=["social"], schedules=bad).status_code == 422 + other = {"games": [{"days": ["mo"], "start": "08:00", "end": "13:00"}]} + assert _put(client, auth_headers, categories=["social"], schedules=other).status_code == 422 + assert _put(client, auth_headers, safesearch={"youtube": "loose"}).status_code == 422 + + +def test_old_image_stores_but_does_not_apply( + client: Any, auth_headers: Any, instance_data: dict[str, Any], docker: Any +) -> None: + client.post( + "/v1/instances", json={**instance_data, "image": "ghcr.io/x/old:1"}, headers=auth_headers + ) + body = _put(client, auth_headers, categories=["ads"]).json() + assert body["applied"] is False and body["reason"] == "image" + assert body["settings"]["categories"] == ["ads"] and docker.reloaded == [] + + +def test_stopped_instance_stores_for_the_next_start( + client: Any, auth_headers: Any, created: str +) -> None: + client.post(f"/v1/instances/{NAME}/stop", headers=auth_headers) + body = _put(client, auth_headers, categories=["ads"]).json() + assert body["applied"] is False and body["reason"] == "not_running" + + +# ---------------------------------------------------------------- exam mode +def test_exam_start_and_stop( + client: Any, auth_headers: Any, created: str, settings: Any, docker: Any +) -> None: + _put(client, auth_headers, categories=["porn"]) + resp = client.post( + f"/v1/instances/{NAME}/exam", + json={"minutes": 45, "allowed": ["Moodle.School.LAN", "example.lan"]}, + headers=auth_headers, + ) + assert resp.status_code == 200, resp.text + exam = resp.json()["exam"] + assert exam["active"] and exam["allowed"] == ["example.lan", "moodle.school.lan"] + assert 44 * 60 < exam["until"] - time.time() <= 45 * 60 + assert _filter_file(settings)["categories"] == ["porn"] # settings kept + # a later settings change keeps the running exam + _put(client, auth_headers, categories=["porn", "ads"]) + assert _filter_file(settings)["exam"]["allowed"] == ["example.lan", "moodle.school.lan"] + state = client.get("/v1/status", headers=auth_headers).json()[0] + assert state["filter"]["exam_until"] + resp = client.delete(f"/v1/instances/{NAME}/exam", headers=auth_headers) + assert resp.status_code == 200 and resp.json()["exam"] is None + assert docker.reloaded.count(NAME) == 4 + + +def test_exam_refused_without_a_running_filter_image( + client: Any, auth_headers: Any, instance_data: dict[str, Any], settings: Any +) -> None: + client.post( + "/v1/instances", json={**instance_data, "image": "ghcr.io/x/old:1"}, headers=auth_headers + ) + resp = client.post(f"/v1/instances/{NAME}/exam", json={"minutes": 10}, headers=auth_headers) + assert resp.status_code == 409 + client.post(f"/v1/instances/{NAME}/stop", headers=auth_headers) + resp = client.post(f"/v1/instances/{NAME}/exam", json={"minutes": 10}, headers=auth_headers) + assert resp.status_code == 409 + assert not (Path(settings.blocklists_dir) / NAME / "filter.json").exists() + + +@pytest.mark.parametrize( + "body", [{"minutes": 0}, {"minutes": 721}, {"minutes": 5, "allowed": ["bad domain"]}] +) +def test_exam_body_validation( + client: Any, auth_headers: Any, created: str, body: dict[str, Any] +) -> None: + assert ( + client.post(f"/v1/instances/{NAME}/exam", json=body, headers=auth_headers).status_code + == 422 + ) + + +def test_expired_exam_is_cleared_on_the_next_write(tmp_path: Path) -> None: + store = fm.FilterStore(str(tmp_path), "UTC", resolver=lambda _n: None) + store.write("s-students", fm.FilterSettings(), set(), {"until": time.time() - 1, "allowed": []}) + assert store.read("s-students")["exam"] is None + + +# ---------------------------------------------------------------- exceptions +def test_allowlist_crud_and_reload( + client: Any, auth_headers: Any, created: str, settings: Any, docker: Any +) -> None: + base = f"/v1/instances/{NAME}/allowlist" + assert client.get(base, headers=auth_headers).json()["domains"] == [] + resp = client.post(base, json={"domain": "Wiki.Example.ORG"}, headers=auth_headers) + assert resp.json()["domains"] == [".wiki.example.org"] + assert (Path(settings.blocklists_dir) / NAME / "allowed.domains").read_text() == ( + ".wiki.example.org\n" + ) + assert client.post(base + "/reload", headers=auth_headers).status_code == 200 + assert client.delete(base + "/wiki.example.org", headers=auth_headers).json()["domains"] == [] + assert client.delete(base + "/wiki.example.org", headers=auth_headers).status_code == 404 + assert client.post(base, json={"domain": "../etc"}, headers=auth_headers).status_code == 422 + + +def test_allowlist_reload_refused_on_an_old_image( + client: Any, auth_headers: Any, instance_data: dict[str, Any] +) -> None: + client.post( + "/v1/instances", json={**instance_data, "image": "ghcr.io/x/old:1"}, headers=auth_headers + ) + resp = client.post(f"/v1/instances/{NAME}/allowlist/reload", headers=auth_headers) + assert resp.status_code == 409 + + +# ---------------------------------------------------------------- lookup, stats, catalog +def test_lookup_explains_the_rule( + client: Any, auth_headers: Any, created: str, settings: Any +) -> None: + make_catalog(settings.catalog_dir, {"porn": ["adult.example"], "ads": ["adult.example"]}) + _put(client, auth_headers, categories=["porn"]) + client.post( + f"/v1/instances/{NAME}/blocklist", json={"domain": "own.example"}, headers=auth_headers + ) + url = f"/v1/instances/{NAME}/filter/lookup" + hit = client.get(url, params={"domain": "www.adult.example"}, headers=auth_headers).json() + assert hit["blocked"] and hit["rule"] == "category" and hit["category_label"] == "Pornografie" + assert {c["category"] for c in hit["listed_in"]} == {"porn", "ads"} + assert [c["active"] for c in hit["listed_in"] if c["category"] == "ads"] == [False] + assert hit["sources"] and hit["sources"][0]["license"] == "CC0" + own = client.get(url, params={"domain": "x.own.example"}, headers=auth_headers).json() + assert own["blocked"] and own["rule"] == "blocklist" + client.post( + f"/v1/instances/{NAME}/allowlist", json={"domain": "own.example"}, headers=auth_headers + ) + own = client.get(url, params={"domain": "x.own.example"}, headers=auth_headers).json() + assert not own["blocked"] and own["rule"] == "exception" + free = client.get(url, params={"domain": "free.example"}, headers=auth_headers).json() + assert not free["blocked"] and free["rule"] == "none" + bad = client.get(url, params={"domain": "not a domain"}, headers=auth_headers) + assert bad.status_code == 422 + host = client.get( + "/v1/catalog/lookup", params={"domain": "adult.example"}, headers=auth_headers + ).json() + assert {c["category"] for c in host["listed_in"]} == {"porn", "ads"} + + +def test_stats(client: Any, auth_headers: Any, created: str, docker: Any) -> None: + today = time.strftime("%Y-%m-%d") + docker.containers[NAME]["filter_stats"] = ( + f"{today} porn 5\n{today} ads 2\n2001-01-01 porn 9\ngarbage\n" + ) + body = client.get( + f"/v1/instances/{NAME}/filter/stats", params={"days": 7}, headers=auth_headers + ).json() + assert body["total"] == {"porn": 5, "ads": 2} + assert body["days"] == [{"date": today, "categories": {"porn": 5, "ads": 2}}] + assert ( + client.get( + f"/v1/instances/{NAME}/filter/stats", params={"days": 0}, headers=auth_headers + ).status_code + == 422 + ) + + +def test_catalog_endpoints(client: Any, auth_headers: Any, app: Any, settings: Any) -> None: + info = client.get("/v1/catalog", headers=auth_headers).json() + assert info["available"] is False and info["profiles"]["students"]["label"] == "Schüler" + assert any(g["id"] == "youth" for g in info["groups"]) + started: list[int] = [] + app.state.spawn_catalog_update = lambda: started.append(1) + assert client.post("/v1/catalog/update", headers=auth_headers).status_code == 202 + assert started == [1] + from lmnsquid import catalog as cm + + with cm.build_lock(Path(settings.catalog_cache_dir)): + assert client.post("/v1/catalog/update", headers=auth_headers).status_code == 409 + schema = client.get("/v1/schema", headers=auth_headers).json() + assert "filter_settings" in schema and "exam_start" in schema + + +# ---------------------------------------------------------------- store details +def test_safesearch_hosts(tmp_path: Path) -> None: + answers = { + "forcesafesearch.google.com": "216.239.38.120", + "restrictmoderate.youtube.com": "216.239.38.119", + "strict.bing.com": None, + } + store = fm.FilterStore(str(tmp_path), "UTC", resolver=lambda n: answers.get(n)) + settings = fm.FilterSettings( + safesearch=fm.SafeSearch(google=True, youtube="moderate", bing=True) + ) + data = store.write("s-students", settings, set()) + hosts = (tmp_path / "s-students" / "safesearch.hosts").read_text().splitlines() + assert "216.239.38.120 www.google.de" in hosts and "216.239.38.120 google.co.uk" in hosts + assert "216.239.38.119 www.youtube.com" in hosts + assert not any("bing" in h for h in hosts) # no address known for Bing: not redirected + assert len({h.split()[1] for h in hosts}) == len(hosts) # one address per name + assert data["resolved"]["forcesafesearch.google.com"] == "216.239.38.120" + # the next lookup fails: the last known address stays + store.resolver = lambda _n: None + answers["forcesafesearch.google.com"] = None + store.write("s-students", settings, set()) + assert ( + "216.239.38.120 www.google.de" in (tmp_path / "s-students" / "safesearch.hosts").read_text() + ) + # off: the file is empty + store.write("s-students", fm.FilterSettings(), set()) + assert (tmp_path / "s-students" / "safesearch.hosts").read_text() == "" + + +def test_refresh_safesearch_on_container_creation(tmp_path: Path) -> None: + store = fm.FilterStore(str(tmp_path), "UTC", resolver=lambda _n: "1.2.3.4") + assert store.refresh_safesearch("s-students") is False # nothing configured + store.write("s-students", fm.FilterSettings(safesearch=fm.SafeSearch(google=True)), set()) + assert store.refresh_safesearch("s-students") is False # same address + store.resolver = lambda _n: "5.6.7.8" + assert store.refresh_safesearch("s-students") is True + assert "5.6.7.8 www.google.com" in (tmp_path / "s-students" / "safesearch.hosts").read_text() + + +def test_window_model() -> None: + w = fm.Window(days=["fr", "mo"], start="07:45", end="24:00") + assert w.days == ["mo", "fr"] + for bad in ( + {"days": [], "start": "07:00", "end": "08:00"}, + {"days": ["mo"], "start": "7:00", "end": "08:00"}, + {"days": ["xx"], "start": "07:00", "end": "08:00"}, + {"days": ["mo"], "start": "09:00", "end": "09:00"}, + ): + with pytest.raises(ValidationError): + fm.Window(**bad) diff --git a/webui/tests/conftest.py b/webui/tests/conftest.py index d9e64c8..2a768e7 100644 --- a/webui/tests/conftest.py +++ b/webui/tests/conftest.py @@ -315,6 +315,11 @@ def control_plane(tmp_path: Path, token: str) -> Iterator[dict[str, Any]]: instances_dir=str(tmp_path / "instances"), secrets_dir=str(tmp_path / "secrets"), blocklists_dir=str(tmp_path / "blocklists"), + catalog_dir=str(tmp_path / "catalog"), + catalog_cache_dir=str(tmp_path / "catalog-cache"), + catalog_config=str(tmp_path / "catalog.yml"), + protected_file=str(tmp_path / "protected.domains"), + filter_timezone="Europe/Berlin", ) store = Store(settings.instances_dir) docker = cp.FakeDockerService( From 692245baff046f081710c4b411936d847ac3dce0 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 14:14:31 +0100 Subject: [PATCH 04/19] build(debian): nightly catalog timer, catalog directories, purge linuxmuster-squid-catalog.timer (01:30 + up to 2 h random delay, persistent) runs lmnsquid-catalog update --if-needed as lmnsquid with MemoryMax=400M; it downloads nothing while no instance uses categories. Enabled like the service (the admin's decision kept), stopped on remove, forgotten on purge; purge already removes /var/lib/linuxmuster-squid with the catalog. --- debian/linuxmuster-squid.install | 2 ++ debian/linuxmuster-squid.postinst | 19 +++++++++- debian/linuxmuster-squid.postrm | 3 ++ debian/linuxmuster-squid.prerm | 2 ++ .../systemd/linuxmuster-squid-catalog.service | 36 +++++++++++++++++++ .../systemd/linuxmuster-squid-catalog.timer | 14 ++++++++ 6 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 packaging/systemd/linuxmuster-squid-catalog.service create mode 100644 packaging/systemd/linuxmuster-squid-catalog.timer diff --git a/debian/linuxmuster-squid.install b/debian/linuxmuster-squid.install index 246a548..7514219 100644 --- a/debian/linuxmuster-squid.install +++ b/debian/linuxmuster-squid.install @@ -5,6 +5,8 @@ # (debian/rules); these are the files next to it. The unit keeps its 7.3 place in # /lib/systemd/system (the maintainer scripts handle it by hand, dh_installsystemd is off). 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/ # 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 d90b52c..f8cbfdd 100644 --- a/debian/linuxmuster-squid.postinst +++ b/debian/linuxmuster-squid.postinst @@ -13,7 +13,11 @@ if getent group docker >/dev/null 2>&1; then fi mkdir -p /etc/linuxmuster-squid/secrets /etc/linuxmuster-squid/blocklists \ - /var/lib/linuxmuster-squid/instances + /var/lib/linuxmuster-squid/instances \ + /var/lib/linuxmuster-squid/catalog /var/lib/linuxmuster-squid/catalog-cache +# The catalog directory is mounted read-only into every container, where squid's helper reads +# it as user proxy (ADR-022). +chmod 755 /var/lib/linuxmuster-squid /var/lib/linuxmuster-squid/catalog # Config with a random API token (only if it does not exist yet) CFG=/etc/linuxmuster-squid/config.yml @@ -164,8 +168,21 @@ else deb-systemd-helper update-state "$UNIT" >/dev/null || true fi +# The nightly catalog timer (ADR-022), by the same rules: enabled on a new installation, the +# admin's decision kept afterwards. It downloads nothing while no instance uses categories. +TIMER=linuxmuster-squid-catalog.timer +deb-systemd-helper unmask "$TIMER" >/dev/null || true +if deb-systemd-helper --quiet was-enabled "$TIMER"; then + deb-systemd-helper enable "$TIMER" >/dev/null || true +else + deb-systemd-helper update-state "$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 # 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 dfef95b..3141e8e 100644 --- a/debian/linuxmuster-squid.postrm +++ b/debian/linuxmuster-squid.postrm @@ -12,7 +12,10 @@ if [ "$1" = "purge" ]; then # remove, no unmask on purge since debhelper 13.10). deb-systemd-helper comes with # 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 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 # The safe.directory entry the postinst added for the instances repo. if command -v git >/dev/null 2>&1; then diff --git a/debian/linuxmuster-squid.prerm b/debian/linuxmuster-squid.prerm index 2f92977..07ffc6a 100644 --- a/debian/linuxmuster-squid.prerm +++ b/debian/linuxmuster-squid.prerm @@ -9,6 +9,8 @@ set -e # (postrm). Up to 7.3.6 remove also disabled it. 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 fi #DEBHELPER# exit 0 diff --git a/packaging/systemd/linuxmuster-squid-catalog.service b/packaging/systemd/linuxmuster-squid-catalog.service new file mode 100644 index 0000000..0e0f0b9 --- /dev/null +++ b/packaging/systemd/linuxmuster-squid-catalog.service @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +[Unit] +Description=linuxmuster-squid: update the category catalog of the filter (UT1, HaGeZi) +Documentation=https://github.com/faircomp/linuxmuster-squid +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +User=lmnsquid +# Only when an instance uses filter categories or a catalog exists (a fresh host downloads nothing). +ExecStart=/opt/linuxmuster-squid/venv/bin/lmnsquid-catalog update --if-needed +Environment=LMNSQUID_CONFIG=/etc/linuxmuster-squid/config.yml +# Measured: about 45 MiB (Python) plus 64 MiB (sort) for 5.6 million domains (ADR-022). +MemoryMax=400M +Nice=10 +IOSchedulingClass=idle +TimeoutStartSec=1h + +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +RestrictNamespaces=yes +LockPersonality=yes +RestrictSUIDSGID=yes +ProtectClock=yes +ProtectHostname=yes +SystemCallArchitectures=native +ReadWritePaths=/var/lib/linuxmuster-squid diff --git a/packaging/systemd/linuxmuster-squid-catalog.timer b/packaging/systemd/linuxmuster-squid-catalog.timer new file mode 100644 index 0000000..1ece295 --- /dev/null +++ b/packaging/systemd/linuxmuster-squid-catalog.timer @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +[Unit] +Description=linuxmuster-squid: nightly update of the filter's category catalog + +[Timer] +# Night, spread over two hours so schools do not all hit the list servers at once (UT1 is +# rate-limited); a missed run (host off) is caught up after boot. +OnCalendar=*-*-* 01:30 +RandomizedDelaySec=2h +Persistent=true + +[Install] +WantedBy=timers.target From 7bb79dfa2996b6c0a12c99b3dd1232ad3d750049 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 14:21:01 +0100 Subject: [PATCH 05/19] feat(webui): filter tab, exam mode, exceptions, catalog state, bulk apply and overview Per instance a "Filter" tab: exam mode with duration, domain list and the template "school server only" (visible state, end now), categories by group with size, sources and licences, time windows per category, profiles (the one matching the role suggested), SafeSearch (switching it on pre-selects "search engines without SafeSearch"), the catalog state of the proxy server with "update now", "why is X blocked?" and the statistics as bars. Exceptions get their own tab (allowlist, like the blocklist). "Apply to other instances" sends the settings to any instances on any connected proxy servers (one result each, e.g. every students instance); "Filter per school" lists all instances with their filter, SafeSearch, exam and catalog state. Same rules as before: global administrators only on the server, JSON + same-origin for every change, German texts, lmn73 buttons. --- webui/lmn_squid/locale/de/LC_MESSAGES/app.po | 294 ++++++++++++++ .../js/controllers/index.controller.es | 384 +++++++++++++++++- webui/lmn_squid/resources/partial/index.html | 190 ++++++++- webui/lmn_squid/views.py | 175 +++++++- webui/tests/js/controller_check.js | 75 ++++ webui/tests/test_control_plane.py | 62 +++ webui/tests/test_permissions.py | 10 + 7 files changed, 1181 insertions(+), 9 deletions(-) diff --git a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po index 2618477..12c2622 100644 --- a/webui/lmn_squid/locale/de/LC_MESSAGES/app.po +++ b/webui/lmn_squid/locale/de/LC_MESSAGES/app.po @@ -702,3 +702,297 @@ msgstr "Ohne diese Option enthält die Keytab auch den bisherigen Schlüssel, da msgid "Optional: the keytab, new instances and disabling the service account use it." msgstr "Optional: Keytab, neue Instanzen und das Deaktivieren des Dienstkontos verwenden ihn." + +msgid "A domain listed here and its subdomains are reachable although the blocklist or a filter category names them. Not during the exam mode." +msgstr "Eine hier eingetragene Domain und ihre Subdomains sind erreichbar, auch wenn die Sperrliste oder eine Filterkategorie sie nennt. Nicht im Prüfungsmodus." + +msgid "Applied to every chosen instance." +msgstr "Auf alle gewählten Instanzen angewendet." + +msgid "Apply" +msgstr "Anwenden" + +msgid "Apply a profile:" +msgstr "Vorlage anwenden:" + +msgid "Apply the filter to other instances" +msgstr "Filter auf weitere Instanzen anwenden" + +msgid "Apply to other instances" +msgstr "Auf weitere Instanzen anwenden" + +msgid "Bing" +msgstr "Bing" + +msgid "Block only at these times" +msgstr "Nur zu diesen Zeiten sperren" + +msgid "Catalog" +msgstr "Katalog" + +msgid "Catalog update started; it takes about a minute. Reload the catalog state afterwards." +msgstr "Katalog-Aktualisierung gestartet; sie dauert etwa eine Minute. Danach den Katalogstatus neu laden." + +msgid "Categories:" +msgstr "Kategorien:" + +msgid "Changed: save to apply" +msgstr "Geändert: zum Übernehmen speichern" + +msgid "Check" +msgstr "Prüfen" + +msgid "Choose every instance with this role" +msgstr "Alle Instanzen mit dieser Rolle wählen" + +msgid "DuckDuckGo" +msgstr "DuckDuckGo" + +msgid "Duration (minutes)" +msgstr "Dauer (Minuten)" + +msgid "End exam mode now" +msgstr "Prüfungsmodus jetzt beenden" + +msgid "Exam mode" +msgstr "Prüfungsmodus" + +msgid "Exam mode active until" +msgstr "Prüfungsmodus aktiv bis" + +msgid "Exam mode ended." +msgstr "Prüfungsmodus beendet." + +msgid "Exam mode is active." +msgstr "Prüfungsmodus ist aktiv." + +msgid "Exceptions" +msgstr "Ausnahmen" + +msgid "Exceptions: tab \"Exceptions\". Block page for HTTP only; HTTPS shows a certificate warning." +msgstr "Ausnahmen: Reiter „Ausnahmen“. Sperrseite nur bei HTTP; bei HTTPS erscheint eine Zertifikatswarnung." + +msgid "Filter" +msgstr "Filter" + +msgid "Filter categories, SafeSearch, exam mode" +msgstr "Filterkategorien, SafeSearch, Prüfungsmodus" + +msgid "Filter not set up yet." +msgstr "Filter noch nicht eingerichtet." + +msgid "Filter per school" +msgstr "Filter je Schule" + +msgid "Filter per school and group" +msgstr "Filter je Schule und Gruppe" + +msgid "Filter saved and active on the proxy." +msgstr "Filter gespeichert und auf dem Proxy aktiv." + +msgid "Filter saved, but this instance runs an image without the category filter: it takes effect after \"Update image\"." +msgstr "Filter gespeichert, aber diese Instanz läuft mit einem Image ohne Kategorienfilter: er wirkt erst nach „Image aktualisieren“." + +msgid "Filter saved. The instance is not running: it takes effect when it starts." +msgstr "Filter gespeichert. Die Instanz läuft nicht: er wirkt, sobald sie startet." + +msgid "Fri" +msgstr "Fr" + +msgid "Google search" +msgstr "Google-Suche" + +msgid "Last 30 days" +msgstr "Letzte 30 Tage" + +msgid "Last update failed:" +msgstr "Letzte Aktualisierung fehlgeschlagen:" + +msgid "Listed in categories" +msgstr "Gelistet in Kategorien" + +msgid "Matching entry" +msgstr "Passender Eintrag" + +msgid "Mon" +msgstr "Mo" + +msgid "No catalog: requests are refused (youth protection fails closed). Update the catalog." +msgstr "Kein Katalog: Anfragen werden abgelehnt (Jugendschutz sperrt im Fehlerfall). Katalog aktualisieren." + +msgid "No catalog: the categories do not work yet. Update the catalog." +msgstr "Kein Katalog: die Kategorien wirken noch nicht. Katalog aktualisieren." + +msgid "No filtered requests in this period." +msgstr "Keine gefilterten Anfragen in diesem Zeitraum." + +msgid "No proxy instances." +msgstr "Keine Proxy-Instanzen." + +msgid "Not applied everywhere, see the list." +msgstr "Nicht überall angewendet, siehe Liste." + +msgid "Only the listed domains (and their subdomains) are reachable through this instance until the time is up; it ends by itself. Domains without proxy login are blocked too." +msgstr "Bis zum Ablauf sind über diese Instanz nur die eingetragenen Domains (und ihre Subdomains) erreichbar; der Modus endet von selbst. Domains ohne Proxy-Anmeldung sind ebenfalls gesperrt." + +msgid "Reachable domains (one per line)" +msgstr "Erreichbare Domains (eine pro Zeile)" + +msgid "Reachable:" +msgstr "Erreichbar:" + +msgid "Reload catalog state" +msgstr "Katalogstatus neu laden" + +msgid "Result" +msgstr "Ergebnis" + +msgid "SafeSearch" +msgstr "SafeSearch" + +msgid "Sat" +msgstr "Sa" + +msgid "Save filter" +msgstr "Filter speichern" + +msgid "Search engines without SafeSearch are now blocked too (recommended). Uncheck the category if you do not want that." +msgstr "Suchmaschinen ohne SafeSearch werden jetzt ebenfalls gesperrt (empfohlen). Kategorie abwählen, wenn das nicht gewünscht ist." + +msgid "Sources" +msgstr "Quellen" + +msgid "Start exam mode" +msgstr "Prüfungsmodus starten" + +msgid "Start the exam mode now? Until it ends only the listed domains are reachable through this instance, for every user, also for domains without proxy login." +msgstr "Prüfungsmodus jetzt starten? Bis zum Ende sind über diese Instanz nur die eingetragenen Domains erreichbar, für alle Benutzer, auch bei Domains ohne Proxy-Anmeldung." + +msgid "Statistics" +msgstr "Statistik" + +msgid "Sun" +msgstr "So" + +msgid "Template: school server only" +msgstr "Vorlage: nur Schulserver" + +msgid "The catalog is older than 7 days: check the nightly update." +msgstr "Der Katalog ist älter als 7 Tage: nächtliche Aktualisierung prüfen." + +msgid "The exam mode is not copied." +msgstr "Der Prüfungsmodus wird nicht übertragen." + +msgid "The proxy connects to the SafeSearch address of the service; the certificate stays valid, nothing is decrypted. Search engines that cannot be forced are in the category \"Search engines without SafeSearch\"." +msgstr "Der Proxy verbindet zur SafeSearch-Adresse des Dienstes; das Zertifikat bleibt gültig, nichts wird entschlüsselt. Suchmaschinen, bei denen sich SafeSearch nicht erzwingen lässt, stehen in der Kategorie „Suchmaschinen ohne SafeSearch“." + +msgid "This instance blocks only its own blocklist. Apply a profile, check it and save." +msgstr "Diese Instanz sperrt nur ihre eigene Sperrliste. Vorlage anwenden, prüfen und speichern." + +msgid "Thu" +msgstr "Do" + +msgid "Tue" +msgstr "Di" + +msgid "Update catalog now" +msgstr "Katalog jetzt aktualisieren" + +msgid "Wed" +msgstr "Mi" + +msgid "Why is a site blocked?" +msgstr "Warum ist eine Seite gesperrt?" + +msgid "YouTube" +msgstr "YouTube" + +msgid "active" +msgstr "aktiv" + +msgid "allowed: exception of this instance" +msgstr "erlaubt: Ausnahme dieser Instanz" + +msgid "allowed: on the list of the running exam" +msgstr "erlaubt: auf der Liste der laufenden Prüfung" + +msgid "allowed: on the protected list (never blocked by a category)" +msgstr "erlaubt: auf der Schutzliste (nie durch eine Kategorie gesperrt)" + +msgid "blocked: exam mode (only the exam domains are reachable)" +msgstr "gesperrt: Prüfungsmodus (nur die Prüfungsdomains sind erreichbar)" + +msgid "blocked: filter category" +msgstr "gesperrt: Filterkategorie" + +msgid "blocked: own blocklist of this instance" +msgstr "gesperrt: eigene Sperrliste dieser Instanz" + +msgid "blocked: the catalog is missing or broken and a youth protection category is active (fail-closed)" +msgstr "gesperrt: der Katalog fehlt oder ist defekt und eine Jugendschutz-Kategorie ist aktiv (fail-closed)" + +msgid "categories" +msgstr "Kategorien" + +msgid "domains" +msgstr "Domains" + +msgid "e.g. moodle.school.example" +msgstr "z. B. moodle.schule.example" + +msgid "exam until" +msgstr "Prüfung bis" + +msgid "filter problem" +msgstr "Filterproblem" + +msgid "filter.json on the proxy host is damaged: requests are refused. Save the filter again." +msgstr "filter.json auf dem Proxy-Host ist beschädigt: Anfragen werden abgelehnt. Filter erneut speichern." + +msgid "filtered requests per category, without users or addresses" +msgstr "gefilterte Anfragen je Kategorie, ohne Benutzer oder Adressen" + +msgid "missing" +msgstr "fehlt" + +msgid "not active" +msgstr "nicht aktiv" + +msgid "not available" +msgstr "nicht verfügbar" + +msgid "not blocked by the filter" +msgstr "nicht durch den Filter gesperrt" + +msgid "not set up" +msgstr "nicht eingerichtet" + +msgid "off" +msgstr "aus" + +msgid "problem" +msgstr "Problem" + +msgid "restricted (moderate)" +msgstr "eingeschränkt (moderat)" + +msgid "restricted (strict)" +msgstr "eingeschränkt (streng)" + +msgid "saved, image without the filter" +msgstr "gespeichert, Image ohne Filter" + +msgid "saved, instance not running" +msgstr "gespeichert, Instanz läuft nicht" + +msgid "suggested" +msgstr "empfohlen" + +msgid "time window" +msgstr "Zeitfenster" + +msgid "until" +msgstr "bis" + +msgid "update running" +msgstr "Aktualisierung läuft" diff --git a/webui/lmn_squid/resources/js/controllers/index.controller.es b/webui/lmn_squid/resources/js/controllers/index.controller.es index 618d4d5..821294b 100644 --- a/webui/lmn_squid/resources/js/controllers/index.controller.es +++ b/webui/lmn_squid/resources/js/controllers/index.controller.es @@ -730,7 +730,9 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco var base = API + '/' + enc(d.conn.name) + '/instances/' + enc(d.inst.name); var done = function (resp) { d.loading = false; d.data = resp.data || {}; }; var failed = function (resp) { d.loading = false; d.error = $scope.errorText(resp); }; - if (tab === 'status') { + if (tab === 'filter') { + loadFilterTab(d); + } else if (tab === 'status') { $http.get(base + '/status').then(done, failed); } else if (tab === 'logs' || tab === 'access') { var params = {tail: d.logQuery.tail}; @@ -778,6 +780,386 @@ angular.module('lmn.squid').controller('LMNSquidIndexController', function ($sco }, function (resp) { d.error = $scope.errorText(resp); }); }; + // ------------------------------------------------ category filter (ADR-022) + var DAY_IDS = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']; + $scope.dayIds = DAY_IDS; + $scope.dayNames = {mo: gettext('Mon'), tu: gettext('Tue'), we: gettext('Wed'), th: gettext('Thu'), fr: gettext('Fri'), sa: gettext('Sat'), su: gettext('Sun')}; + $scope.catalogs = {}; + + // The catalog of one proxy server, with its categories grouped for the page. + function loadCatalog(connName) { + return $http.get(API + '/' + enc(connName) + '/catalog', {ignoreLoadingBar: true}).then(function (resp) { + var info = resp.data || {}; + info.grouped = (info.groups || []).map(function (g) { + return {group: g, categories: (info.categories || []).filter(function (c) { return c.group === g.id; })}; + }).filter(function (g) { return g.categories.length; }); + $scope.catalogs[connName] = info; + return info; + }); + } + // "Reload catalog state" in the filter tab: the new state, the admin's checks kept. + $scope.refreshCatalog = function () { + var d = $scope.detail; + loadCatalog(d.conn.name).then(function (info) { + if (d.filter) { + d.filter.catalog = info; + } + }, fail); + }; + + // The profile that fits an instance's role: students for pupils, teachers for staff. + $scope.suggestedProfile = function (inst) { + var role = String((inst && inst.role) || '').toLowerCase(); + if (/student|schueler|schuler|pupil/.test(role)) { + return 'students'; + } + if (/teacher|lehrer|staff/.test(role)) { + return 'teachers'; + } + return null; + }; + + function filterForm(view, catalog) { + var settings = view.settings || {categories: [], schedules: {}, safesearch: {}}; + var checked = {}; + (settings.categories || []).forEach(function (c) { checked[c] = true; }); + var schedules = {}; + Object.keys(settings.schedules || {}).forEach(function (c) { + schedules[c] = settings.schedules[c].map(function (w) { + var days = {}; + (w.days || []).forEach(function (day) { days[day] = true; }); + return {days: days, start: w.start, end: w.end}; + }); + }); + return { + view: view, + catalog: catalog, + checked: checked, + schedules: schedules, + safesearch: angular.copy(settings.safesearch || {google: false, youtube: 'off', bing: false, duckduckgo: false}), + exam: {minutes: 45, allowedText: ''}, + lookup: {domain: '', result: null}, + stats: null, + dirty: false + }; + } + + function loadFilterTab(d) { + var base = API + '/' + enc(d.conn.name) + '/instances/' + enc(d.inst.name); + $http.get(base + '/filter').then(function (resp) { + var view = resp.data || {}; + return loadCatalog(d.conn.name).then(function (catalog) { + d.loading = false; + d.filter = filterForm(view, catalog); + }); + }).then(null, function (resp) { + d.loading = false; + d.error = $scope.errorText(resp); + }); + } + + function filterBody(f) { + var cats = ((f.catalog && f.catalog.categories) || []).map(function (c) { return c.id; }).filter(function (id) { return f.checked[id]; }); + var schedules = {}; + cats.forEach(function (id) { + var windows = (f.schedules[id] || []).map(function (w) { + return {days: DAY_IDS.filter(function (day) { return w.days[day]; }), start: w.start, end: w.end}; + }); + if (windows.length) { + schedules[id] = windows; + } + }); + return {categories: cats, schedules: schedules, safesearch: angular.copy(f.safesearch)}; + } + $scope.filterBody = filterBody; + + $scope.filterChanged = function () { + $scope.detail.filter.dirty = true; + }; + + $scope.applyProfile = function (id) { + var f = $scope.detail.filter; + var profile = ((f.catalog && f.catalog.profiles) || {})[id]; + if (!profile) { + return; + } + f.checked = {}; + (profile.categories || []).forEach(function (c) { f.checked[c] = true; }); + f.schedules = {}; + f.safesearch = angular.copy(profile.safesearch || {google: false, youtube: 'off', bing: false, duckduckgo: false}); + f.dirty = true; + }; + + function safesearchOn(s) { + return !!(s && (s.google || (s.youtube && s.youtube !== 'off') || s.bing || s.duckduckgo)); + } + $scope.safesearchOn = safesearchOn; + + // SafeSearch on: "search engines without SafeSearch" is pre-selected (decision 6). + $scope.safesearchChanged = function () { + var f = $scope.detail.filter; + f.dirty = true; + if (safesearchOn(f.safesearch) && !f.checked.nosafesearch) { + f.checked.nosafesearch = true; + notify.warning(gettext('Search engines without SafeSearch are now blocked too (recommended). Uncheck the category if you do not want that.')); + } + }; + + $scope.addWindow = function (catId) { + var f = $scope.detail.filter; + f.schedules[catId] = (f.schedules[catId] || []).concat([{days: {mo: true, tu: true, we: true, th: true, fr: true}, start: '07:45', end: '13:15'}]); + f.dirty = true; + }; + $scope.removeWindow = function (catId, index) { + var f = $scope.detail.filter; + f.schedules[catId].splice(index, 1); + f.dirty = true; + }; + + function applyResult(data) { + if (data.applied) { + notify.success(gettext('Filter saved and active on the proxy.')); + } else if (data.reason === 'not_running') { + notify.warning(gettext('Filter saved. The instance is not running: it takes effect when it starts.')); + } else if (data.reason === 'image') { + notify.warning(gettext('Filter saved, but this instance runs an image without the category filter: it takes effect after "Update image".')); + } + } + + $scope.saveFilter = function () { + var d = $scope.detail; + var f = d.filter; + d.error = null; + f.busy = true; + var url = API + '/' + enc(d.conn.name) + '/instances/' + enc(d.inst.name) + '/filter'; + $http.put(url, filterBody(f)).then(function (resp) { + f.busy = false; + applyResult(resp.data || {}); + d.filter = filterForm(resp.data, f.catalog); + $scope.loadServer(d.conn.name); + }, function (resp) { + f.busy = false; + d.error = $scope.errorText(resp); + }); + }; + + $scope.catalogUpdate = function (connName) { + post(API + '/' + enc(connName) + '/catalog/update').then(function () { + notify.success(gettext('Catalog update started; it takes about a minute. Reload the catalog state afterwards.')); + var info = $scope.catalogs[connName]; + if (info) { + info.building = true; + } + }, fail); + }; + + // ------------------------------------------------------- exam mode + $scope.examServerTemplate = function () { + var d = $scope.detail; + var domain = String(d.inst.realm || '').toLowerCase(); + var lines = String(d.filter.exam.allowedText || '').split(/[\s,]+/).filter(function (x) { return x; }); + if (domain && lines.indexOf(domain) < 0) { + lines.unshift(domain); + } + d.filter.exam.allowedText = lines.join('\n'); + }; + + $scope.examStart = function () { + var d = $scope.detail; + var f = d.filter; + d.error = null; + var allowed = String(f.exam.allowedText || '').split(/[\s,]+/).filter(function (x) { return x; }); + var text = gettext('Start the exam mode now? Until it ends only the listed domains are reachable through this instance, for every user, also for domains without proxy login.'); + messagebox.show({text: text, positive: gettext('Start exam mode'), negative: gettext('Cancel')}).then(function () { + f.busy = true; + var url = API + '/' + enc(d.conn.name) + '/instances/' + enc(d.inst.name) + '/exam'; + post(url, {minutes: parseInt(f.exam.minutes, 10), allowed: allowed}).then(function (resp) { + f.busy = false; + notify.success(gettext('Exam mode is active.')); + f.view = resp.data; + $scope.loadServer(d.conn.name); + }, function (resp) { + f.busy = false; + d.error = $scope.errorText(resp); + }); + }); + }; + + $scope.examStop = function () { + var d = $scope.detail; + var f = d.filter; + var url = API + '/' + enc(d.conn.name) + '/instances/' + enc(d.inst.name) + '/exam'; + f.busy = true; + del(url).then(function (resp) { + f.busy = false; + notify.success(gettext('Exam mode ended.')); + f.view = resp.data; + $scope.loadServer(d.conn.name); + }, function (resp) { + f.busy = false; + d.error = $scope.errorText(resp); + }); + }; + + $scope.timeText = function (ts) { + if (!ts) { + return '–'; + } + var t = new Date(ts * 1000); + var pad = function (n) { return (n < 10 ? '0' : '') + n; }; + return pad(t.getDate()) + '.' + pad(t.getMonth() + 1) + '.' + t.getFullYear() + ' ' + pad(t.getHours()) + ':' + pad(t.getMinutes()); + }; + + // ---------------------------------------------- "why is X blocked?" and statistics + $scope.lookupDomain = function () { + var d = $scope.detail; + var f = d.filter; + f.lookup.result = null; + f.lookup.error = null; + if (!String(f.lookup.domain || '').trim()) { + return; + } + var url = API + '/' + enc(d.conn.name) + '/instances/' + enc(d.inst.name) + '/filter/lookup'; + $http.get(url, {params: {domain: String(f.lookup.domain).trim()}}).then(function (resp) { + f.lookup.result = resp.data; + }, function (resp) { + f.lookup.error = $scope.errorText(resp); + }); + }; + + $scope.ruleText = function (rule) { + var texts = { + exam: gettext('blocked: exam mode (only the exam domains are reachable)'), + exam_allowed: gettext('allowed: on the list of the running exam'), + exception: gettext('allowed: exception of this instance'), + protected: gettext('allowed: on the protected list (never blocked by a category)'), + category: gettext('blocked: filter category'), + catalog_unavailable: gettext('blocked: the catalog is missing or broken and a youth protection category is active (fail-closed)'), + blocklist: gettext('blocked: own blocklist of this instance'), + none: gettext('not blocked by the filter') + }; + return texts[rule] || rule; + }; + + $scope.loadStats = function (days) { + var d = $scope.detail; + var f = d.filter; + var url = API + '/' + enc(d.conn.name) + '/instances/' + enc(d.inst.name) + '/filter/stats'; + $http.get(url, {params: {days: days || 30}}).then(function (resp) { + var data = resp.data || {}; + var total = data.total || {}; + var labels = {}; + ((f.catalog && f.catalog.categories) || []).forEach(function (c) { labels[c.id] = c.label; }); + var max = 0; + Object.keys(total).forEach(function (k) { max = Math.max(max, total[k]); }); + f.stats = { + days: data.days || [], + bars: Object.keys(total).sort(function (a, b) { return total[b] - total[a]; }).map(function (k) { + return {id: k, label: labels[k] || $scope.ruleText(k), count: total[k], width: max ? Math.round(100 * total[k] / max) : 0}; + }) + }; + }, function (resp) { + d.error = $scope.errorText(resp); + }); + }; + + // ------------------------------------------------- the same settings on several instances + $scope.openBulk = function () { + var d = $scope.detail; + var rows = []; + $scope.connections.forEach(function (conn) { + ((($scope.servers[conn.name] || {}).instances) || []).forEach(function (inst) { + rows.push({conn: conn, inst: inst, selected: conn.name === d.conn.name && inst.name === d.inst.name}); + }); + }); + $scope.bulk = {settings: filterBody(d.filter), rows: rows, role: d.inst.role, results: null}; + }; + $scope.closeBulk = function () { $scope.bulk = null; }; + $scope.bulkSelectRole = function () { + var b = $scope.bulk; + b.rows.forEach(function (r) { r.selected = r.inst.role === b.role; }); + }; + $scope.bulkSelected = function () { + return (($scope.bulk && $scope.bulk.rows) || []).filter(function (r) { return r.selected; }).length; + }; + $scope.runBulk = function () { + var b = $scope.bulk; + var targets = b.rows.filter(function (r) { return r.selected; }).map(function (r) { + return {conn: r.conn.name, name: r.inst.name}; + }); + if (!targets.length) { + return; + } + b.busy = true; + b.error = null; + post(API + '/filter/bulk', {targets: targets, settings: b.settings}).then(function (resp) { + b.busy = false; + b.results = (resp.data && resp.data.results) || []; + var failed = b.results.filter(function (r) { return !r.ok; }).length; + if (failed) { + notify.warning(gettext('Not applied everywhere, see the list.')); + } else { + notify.success(gettext('Applied to every chosen instance.')); + } + $scope.connections.forEach(function (c) { $scope.loadServer(c.name); }); + }, function (resp) { + b.busy = false; + b.error = $scope.errorText(resp); + }); + }; + $scope.bulkResultText = function (r) { + if (!r.ok) { + return (r.message || r.error || '') + (r.detail ? ' ' + (typeof r.detail === 'string' ? r.detail : angular.toJson(r.detail)) : ''); + } + if (r.applied) { + return gettext('active'); + } + return r.reason === 'image' ? gettext('saved, image without the filter') : gettext('saved, instance not running'); + }; + + // ------------------------------------------------- overview "filter per school / group" + $scope.openFilterOverview = function () { + var rows = []; + $scope.connections.forEach(function (conn) { + ((($scope.servers[conn.name] || {}).instances) || []).forEach(function (inst) { + rows.push({conn: conn, inst: inst, filter: (inst.state && inst.state.filter) || null}); + }); + }); + rows.sort(function (a, b) { + var s = schoolOrder(a.inst.school, b.inst.school); + return s || (a.inst.role < b.inst.role ? -1 : (a.inst.role > b.inst.role ? 1 : 0)); + }); + $scope.filterOverview = {rows: rows}; + $scope.connections.forEach(function (conn) { + loadCatalog(conn.name).then(null, function () { return null; }); + }); + }; + $scope.closeFilterOverview = function () { $scope.filterOverview = null; }; + $scope.openFilterFromOverview = function (row) { + $scope.filterOverview = null; + $scope.openDetail(row.conn, row.inst, 'filter'); + }; + + $scope.filterText = function (inst) { + var flt = inst && inst.state && inst.state.filter; + if (!flt) { + return '–'; + } + if (!flt.configured) { + return gettext('not set up'); + } + return flt.categories + ' ' + gettext('categories'); + }; + $scope.filterProblemText = function (problem) { + var texts = { + catalog_missing_fail_closed: gettext('No catalog: requests are refused (youth protection fails closed). Update the catalog.'), + catalog_missing: gettext('No catalog: the categories do not work yet. Update the catalog.'), + catalog_old: gettext('The catalog is older than 7 days: check the nightly update.'), + broken: gettext('filter.json on the proxy host is damaged: requests are refused. Save the filter again.') + }; + return texts[problem] || problem; + }; + // ------------------------------------- set up a new proxy host (D0-D2, ADR-021) $scope.site = null; $http.get(API + '/site', {ignoreLoadingBar: true}).then(function (resp) { diff --git a/webui/lmn_squid/resources/partial/index.html b/webui/lmn_squid/resources/partial/index.html index 08e1d9b..adbf96d 100644 --- a/webui/lmn_squid/resources/partial/index.html +++ b/webui/lmn_squid/resources/partial/index.html @@ -35,6 +35,7 @@
+
-
+ + +
+ +
+ Exam mode active until {{timeText(detail.filter.view.exam.until)}}. + Reachable: {{(detail.filter.view.exam.allowed || []).join(', ') || '–'}} + +
+
+
Exam mode
+
+

Only the listed domains (and their subdomains) are reachable through this instance until the time is up; it ends by itself. Domains without proxy login are blocked too.

+
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ Filter not set up yet. This instance blocks only its own blocklist. Apply a profile, check it and save. +
+
{{filterProblemText(detail.filter.view.summary.problem)}}
+ + +

+ + Catalog: + {{timeText(detail.filter.catalog.built)}}, {{detail.filter.catalog.domains | number}} domains + not available + + update running + Last update failed: {{detail.filter.catalog.last_run.error}} + + + + +

+ +
+ Apply a profile: + +
+ +
+
+
{{g.group.label}}
+
+ + {{c.count | number}} · {{src.name}} ({{src.license}}){{$last ? '' : ', '}} + time window +
+ + – + + +
+
+
+
+ +
SafeSearch
+
+ + + + + +
+

The proxy connects to the SafeSearch address of the service; the certificate stays valid, nothing is decrypted. Search engines that cannot be forced are in the category "Search engines without SafeSearch".

+ +
+ Changed: save to apply + + + Exceptions: tab "Exceptions". Block page for HTTP only; HTTPS shows a certificate warning. +
+ +
Why is a site blocked?
+
+
+ + +
+
+
{{detail.filter.lookup.error}}
+ + + + + +
Result{{ruleText(detail.filter.lookup.result.rule)}} {{detail.filter.lookup.result.category_label}}
Matching entry{{detail.filter.lookup.result.entry}}
Listed in categories{{l.label}} (not active){{$last ? '' : ', '}}
Sources{{src.name}} ({{src.license}}){{$last ? '' : ', '}}
+ +
Statistics filtered requests per category, without users or addresses
+ +
No filtered requests in this period.
+ + + + + +
{{b.label}}
{{b.count | number}}
+
+ +
Read before adding anything:
    @@ -619,6 +745,7 @@

    {{detail.conn.display_name}} / {{detail.inst.name}}

A domain blocks itself and all subdomains. HTTPS shows a certificate warning, not a block page.

+

A domain listed here and its subdomains are reachable although the blocklist or a filter category names them. Not during the exam mode.

@@ -648,3 +775,60 @@

{{detail.conn.display_name}} / {{detail.inst.name}}

+ + + + + + + + + + + + + + diff --git a/webui/lmn_squid/views.py b/webui/lmn_squid/views.py index eb8fd15..df24a15 100644 --- a/webui/lmn_squid/views.py +++ b/webui/lmn_squid/views.py @@ -60,7 +60,9 @@ PREFIX = r"/api/lmn/squid" CONN = r"(?P[^/]+)" NAME = r"(?P[^/]+)" -LIST_KINDS = ("blocklist", "noauth") +LIST_KINDS = ("blocklist", "noauth", "allowlist") +FILTER_KEYS = ("categories", "schedules", "safesearch") +BULK_MAX = 200 HOSTKEY_TTL = 900.0 # Host keys fetched in step 1 of the setup, per target IP, kept in this worker only: the @@ -631,7 +633,7 @@ def handle_instance_logs( return client.request("GET", path, query=query, timeouts=(SHORT[0], 60.0)) # ----------------------------------------------- blocklist and noauth list - @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Pblocklist|noauth)") + @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Pblocklist|noauth|allowlist)") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only @@ -641,7 +643,7 @@ def handle_list_get( client = self._client(conn) return client.request("GET", instance_path(name, kind)) - @post(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Pblocklist|noauth)") + @post(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Pblocklist|noauth|allowlist)") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only @@ -660,7 +662,7 @@ def handle_list_add( + CONN + r"/instances/" + NAME - + r"/(?Pblocklist|noauth)/(?P[^/]+)" + + r"/(?Pblocklist|noauth|allowlist)/(?P[^/]+)" ) @authorize(PERM_CHANGE) @endpoint(api=True) @@ -673,7 +675,14 @@ def handle_list_remove( self._audit(f"{kind} remove", conn=conn, name=name, domain=domain) return client.request("DELETE", path) - @post(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Pblocklist|noauth)/reload") + @post( + PREFIX + + "/" + + CONN + + r"/instances/" + + NAME + + r"/(?Pblocklist|noauth|allowlist)/reload" + ) @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only @@ -684,3 +693,159 @@ def handle_list_reload( path = instance_path(name, kind, "reload") self._audit(f"{kind} reload", conn=conn, name=name) return client.request("POST", path, timeouts=(SHORT[0], 60.0)) + + # ------------------------------------------------ category filter (ADR-022) + @get(PREFIX + "/" + CONN + r"/catalog") + @authorize(PERM_LIST) + @endpoint(api=True) + @global_admin_only + def handle_catalog(self, http_context: Any, conn: str = "") -> Any: + """Catalog of one proxy host: age, categories with groups, sources, licences, profiles.""" + return self._client(conn).request("GET", "/v1/catalog") + + @post(PREFIX + "/" + CONN + r"/catalog/update") + @authorize(PERM_CHANGE) + @endpoint(api=True) + @global_admin_only + def handle_catalog_update(self, http_context: Any, conn: str = "") -> Any: + self._audit("catalog update", conn=conn) + return self._client(conn).request("POST", "/v1/catalog/update") + + @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter") + @authorize(PERM_LIST) + @endpoint(api=True) + @global_admin_only + def handle_filter_get(self, http_context: Any, conn: str = "", name: str = "") -> Any: + return self._client(conn).request("GET", instance_path(name, "filter")) + + @put(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter") + @authorize(PERM_CHANGE) + @endpoint(api=True) + @global_admin_only + def handle_filter_put(self, http_context: Any, conn: str = "", name: str = "") -> Any: + """Categories, schedules and SafeSearch of one instance (validated by the API).""" + body = _filter_body(_body(http_context)) + self._audit( + "filter set", conn=conn, name=name, categories=",".join(body.get("categories") or []) + ) + return self._client(conn).request( + "PUT", instance_path(name, "filter"), body=body, timeouts=(SHORT[0], 60.0) + ) + + @post(PREFIX + r"/filter/bulk") + @authorize(PERM_CHANGE) + @endpoint(api=True) + @global_admin_only + def handle_filter_bulk(self, http_context: Any) -> Any: + """The same filter settings on several instances, on one or more proxy servers. + + One request per instance, one after the other; the answer lists every instance with + its own result, so one server that is down does not hide the others. + """ + body = _body(http_context) + targets = body.get("targets") + if not isinstance(targets, list) or not targets or len(targets) > BULK_MAX: + raise EndpointReturn( + 422, + { + "error": "invalid", + "field": "targets", + "message": f"1 to {BULK_MAX} instances expected", + }, + ) + settings = _filter_body(body.get("settings")) + results: list[dict[str, Any]] = [] + for target in targets: + target = target if isinstance(target, dict) else {} + conn, name = str(target.get("conn") or ""), str(target.get("name") or "") + row: dict[str, Any] = {"conn": conn, "name": name} + try: + found = self.store.get(conn) + if found is None: + raise ControlPlaneError("invalid", f"unknown connection {conn!r}") + answer = ControlPlaneClient(found).request( + "PUT", instance_path(name, "filter"), body=settings, timeouts=(SHORT[0], 60.0) + ) + answer = answer if isinstance(answer, dict) else {} + row.update( + ok=True, + applied=answer.get("applied"), + reason=answer.get("reason"), + detail=answer.get("detail"), + ) + except ControlPlaneError as exc: + row.update(ok=False, **exc.as_dict()) + results.append(row) + self._audit( + "filter bulk", + targets=",".join(f"{r['conn']}/{r['name']}" for r in results), + categories=",".join(settings.get("categories") or []), + failed=sum(1 for r in results if not r["ok"]), + ) + return {"results": results} + + @post(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/exam") + @authorize(PERM_CHANGE) + @endpoint(api=True) + @global_admin_only + def handle_exam_start(self, http_context: Any, conn: str = "", name: str = "") -> Any: + data = _body(http_context) + allowed = data.get("allowed") or [] + if not isinstance(allowed, list): + raise EndpointReturn( + 422, {"error": "invalid", "field": "allowed", "message": "a list of domains"} + ) + body = {"minutes": data.get("minutes"), "allowed": allowed} + self._audit( + "exam start", + conn=conn, + name=name, + minutes=body["minutes"], + allowed=",".join(str(d) for d in allowed), + ) + return self._client(conn).request( + "POST", instance_path(name, "exam"), body=body, timeouts=(SHORT[0], 60.0) + ) + + @delete(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/exam") + @authorize(PERM_CHANGE) + @endpoint(api=True) + @global_admin_only + def handle_exam_stop(self, http_context: Any, conn: str = "", name: str = "") -> Any: + self._audit("exam stop", conn=conn, name=name) + return self._client(conn).request( + "DELETE", instance_path(name, "exam"), timeouts=(SHORT[0], 60.0) + ) + + @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter/lookup") + @authorize(PERM_LIST) + @endpoint(api=True) + @global_admin_only + def handle_filter_lookup(self, http_context: Any, conn: str = "", name: str = "") -> Any: + domain = str((http_context.query or {}).get("domain") or "").strip() + domain_segment(domain) # no domain: refused here, nothing is sent + return self._client(conn).request( + "GET", instance_path(name, "filter", "lookup"), query={"domain": domain} + ) + + @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter/stats") + @authorize(PERM_LIST) + @endpoint(api=True) + @global_admin_only + def handle_filter_stats(self, http_context: Any, conn: str = "", name: str = "") -> Any: + days = _int_param(http_context, "days", 30) + return self._client(conn).request( + "GET", + instance_path(name, "filter", "stats"), + query={"days": days}, + timeouts=(SHORT[0], 60.0), + ) + + +def _filter_body(data: Any) -> dict[str, Any]: + """Only the keys of the API's FilterSettings go through; the API validates the values.""" + if not isinstance(data, dict): + raise EndpointReturn( + 422, {"error": "invalid", "field": "settings", "message": "settings expected"} + ) + return {k: data[k] for k in FILTER_KEYS if k in data} diff --git a/webui/tests/js/controller_check.js b/webui/tests/js/controller_check.js index 99994d6..d8b3fb3 100644 --- a/webui/tests/js/controller_check.js +++ b/webui/tests/js/controller_check.js @@ -274,4 +274,79 @@ hzs.startKeytab(); assert.strictEqual(hzs.keytabForm.jobId, undefined); assert.strictEqual(hzs.keytabForm.precheck.checks[0].message, 'nicht der Proxy dieser Verbindung'); +// --- category filter (ADR-022): profile, SafeSearch pre-select, schedules, body, bulk --------- +const CATALOG = {available: true, built: 1795000000, domains: 5, building: false, last_run: {state: 'ok'}, + groups: [{id: 'youth', label: 'Jugendschutz'}, {id: 'bypass', label: 'Umgehung'}, {id: 'distraction', label: 'Ablenkung'}], + categories: [{id: 'porn', group: 'youth', label: 'Pornografie', count: 3, sources: []}, + {id: 'nosafesearch', group: 'bypass', label: 'Suchmaschinen ohne SafeSearch', count: 1, sources: []}, + {id: 'social', group: 'distraction', label: 'Soziale Netzwerke', count: 1, sources: []}], + profiles: {students: {label: 'Schüler', categories: ['porn', 'nosafesearch'], safesearch: {google: true, youtube: 'strict', bing: false, duckduckgo: false}}, + teachers: {label: 'Lehrkräfte', categories: [], safesearch: {google: false, youtube: 'off', bing: false, duckduckgo: false}}}}; +const FV = {name: 'one-students', configured: false, settings: {categories: [], schedules: {}, safesearch: {google: false, youtube: 'off', bing: false, duckduckgo: false}}, exam: null, summary: {}}; +const RF = Object.assign({}, ROUTES, { + 'GET /api/lmn/squid/b/catalog': {status: 200, data: CATALOG}, + 'GET /api/lmn/squid/b/instances/one-students/filter': {status: 200, data: FV}, + 'PUT /api/lmn/squid/b/instances/one-students/filter': {status: 200, data: Object.assign({}, FV, {configured: true, applied: false, reason: 'image'})}, + 'POST /api/lmn/squid/b/instances/one-students/exam': {status: 200, data: Object.assign({}, FV, {exam: {active: true, until: 1795003600, allowed: ['dev.lmschule.de']}})}, + 'POST /api/lmn/squid/filter/bulk': {status: 200, data: {results: [{conn: 'b', name: 'one-students', ok: true, applied: true}, {conn: 'a', name: 'one-teachers', ok: false, error: 'unreachable', message: 'down'}]}}, +}); +const hf = harness(RF, {}); +const fs_ = hf.scope; +const studentsRow = fs_.servers.b.instances.find((i) => i.name === 'one-students'); +studentsRow.realm = 'DEV.LMSCHULE.DE'; +assert.strictEqual(fs_.suggestedProfile(studentsRow), 'students'); +assert.strictEqual(fs_.suggestedProfile({role: 'teachers'}), 'teachers'); +assert.strictEqual(fs_.suggestedProfile({role: 'guests'}), null); +fs_.openDetail(fs_.connections[1], studentsRow, 'filter'); +const f = fs_.detail.filter; +assert.ok(f && f.catalog.grouped.length === 3, 'catalog grouped'); +assert.strictEqual(f.view.configured, false); +fs_.applyProfile('students'); +assert.deepStrictEqual(fs_.filterBody(f).categories, ['porn', 'nosafesearch']); +assert.strictEqual(fs_.filterBody(f).safesearch.youtube, 'strict'); +// SafeSearch switched on without the category: the category is pre-selected and said so +f.checked.nosafesearch = false; +f.safesearch.bing = true; +fs_.safesearchChanged(); +assert.strictEqual(f.checked.nosafesearch, true); +assert.ok(hf.notes.some((n) => n[0] === 'warn' && /SafeSearch/.test(n[1]))); +// a schedule window only for a checked category, days in week order +f.checked.social = true; +fs_.addWindow('social'); +f.schedules.social[0].days = {fr: true, mo: true}; +const body = fs_.filterBody(f); +assert.deepStrictEqual(body.categories, ['porn', 'nosafesearch', 'social']); +assert.deepStrictEqual(body.schedules, {social: [{days: ['mo', 'fr'], start: '07:45', end: '13:15'}]}); +f.checked.social = false; +assert.deepStrictEqual(fs_.filterBody(f).schedules, {}); +// save: stored but the image has no filter -> a warning, not a success +fs_.saveFilter(); +assert.ok(hf.notes.some((n) => n[0] === 'warn' && /Update image/.test(n[1]))); +// exam: the school server template uses the realm, the exam body carries minutes + domains +fs_.examServerTemplate(); +assert.strictEqual(fs_.detail.filter.exam.allowedText, 'dev.lmschule.de'); +fs_.detail.filter.exam.minutes = '30'; +fs_.examStart(); +const examIdx = hf.calls.indexOf('POST /api/lmn/squid/b/instances/one-students/exam'); +assert.deepStrictEqual(hf.bodies[examIdx], {minutes: 30, allowed: ['dev.lmschule.de']}); +assert.strictEqual(fs_.detail.filter.view.exam.active, true); +// bulk: every instance with the role, one result per instance +fs_.openBulk(); +assert.strictEqual(fs_.bulkSelected(), 1); +fs_.bulk.role = 'teachers'; +fs_.bulkSelectRole(); +assert.deepStrictEqual(fs_.bulk.rows.filter((r) => r.selected).map((r) => r.inst.name).sort(), ['beta-teachers', 'default-school-teachers', 'one-teachers']); +fs_.runBulk(); +const bulkIdx = hf.calls.indexOf('POST /api/lmn/squid/filter/bulk'); +assert.strictEqual(hf.bodies[bulkIdx].targets.length, 3); +assert.ok(hf.notes.some((n) => n[0] === 'warn' && /Not applied everywhere/.test(n[1]))); +assert.strictEqual(fs_.bulkResultText({ok: true, applied: true}), 'active'); +fs_.closeBulk(); assert.strictEqual(fs_.bulk, null); +// overview: rows sorted by school, closes through its function +fs_.openFilterOverview(); +assert.strictEqual(fs_.filterOverview.rows[0].inst.school, 'default-school'); +fs_.closeFilterOverview(); assert.strictEqual(fs_.filterOverview, null); +assert.strictEqual(fs_.filterText({state: {filter: {configured: false}}}), 'not set up'); +assert.strictEqual(fs_.filterText({state: {filter: {configured: true, categories: 4}}}), '4 categories'); + console.log('controller checks: ok'); diff --git a/webui/tests/test_control_plane.py b/webui/tests/test_control_plane.py index 4d6efd3..874fb0a 100644 --- a/webui/tests/test_control_plane.py +++ b/webui/tests/test_control_plane.py @@ -172,3 +172,65 @@ def test_unknown_instance_is_404(webui: WebUI, cp: dict[str, Any]) -> None: add(webui, "a", cp["url"], cp["fingerprint"]) status, body = webui.call("GET", "/api/lmn/squid/a/instances/nope-teachers") assert (status, body["error"], body["status"]) == (404, "http", 404) + + +def test_filter_through_the_plugin(webui: WebUI, cp: dict[str, Any]) -> None: + """Category filter (ADR-022): catalog, settings, exam mode, lookup, stats, bulk.""" + add(webui, "a", cp["url"], cp["fingerprint"]) + base = "/api/lmn/squid/a/instances" + for role in ("students", "teachers"): + assert webui.call("POST", base, {**INSTANCE, "role": role})[0] == 200 + status, catalog = webui.call("GET", "/api/lmn/squid/a/catalog") + assert status == 200 and catalog["profiles"]["students"]["categories"] + assert catalog["available"] is False + flt = f"{base}/default-school-students/filter" + status, view = webui.call("GET", flt) + assert (status, view["configured"]) == (200, False) + status, body = webui.call( + "PUT", flt, {"categories": ["porn"], "safesearch": {"google": True}, "junk": 1} + ) + assert status == 200 and body["applied"] is True, body + assert body["settings"]["categories"] == ["porn"] + status, body = webui.call("PUT", flt, {"categories": ["nope"]}) + assert status == 422 + # exam mode + exam = f"{base}/default-school-students/exam" + status, body = webui.call("POST", exam, {"minutes": 30, "allowed": ["moodle.example"]}) + assert status == 200 and body["exam"]["active"], body + assert webui.call("POST", exam, {"minutes": 30, "allowed": "x"})[0] == 422 + status, body = webui.call("DELETE", exam) + assert status == 200 and body["exam"] is None + # lookup and statistics + status, body = webui.call("GET", f"{flt}/lookup", query={"domain": "example.org"}) + # porn is active and there is no catalog yet: fail-closed, and the lookup says so + assert status == 200 and body["rule"] == "catalog_unavailable" and body["blocked"] + seen = len(cp["recorder"].seen) + assert webui.call("GET", f"{flt}/lookup", query={"domain": "a b"})[0] == 422 + assert len(cp["recorder"].seen) == seen + status, body = webui.call("GET", f"{flt}/stats", query={"days": "7"}) + assert status == 200 and body["total"] == {} + # exceptions use the list endpoints + lst = f"{base}/default-school-students/allowlist" + assert webui.call("POST", lst, {"domain": "wiki.example"})[1]["domains"] == [".wiki.example"] + assert webui.call("POST", f"{lst}/reload")[0] == 200 + # bulk: both instances plus one on an unknown connection, each with its own result + targets = [ + {"conn": "a", "name": "default-school-students"}, + {"conn": "a", "name": "default-school-teachers"}, + {"conn": "zz", "name": "default-school-teachers"}, + {"conn": "a", "name": ".."}, + ] + status, body = webui.call( + "POST", + "/api/lmn/squid/filter/bulk", + {"targets": targets, "settings": {"categories": ["security", "doh"]}}, + ) + assert status == 200 + assert [r["ok"] for r in body["results"]] == [True, True, False, False] + status, view = webui.call("GET", f"{base}/default-school-teachers/filter") + assert view["settings"]["categories"] == ["security", "doh"] + assert webui.call("POST", "/api/lmn/squid/filter/bulk", {"targets": []})[0] == 422 + assert ( + webui.call("POST", "/api/lmn/squid/filter/bulk", {"targets": targets, "settings": "x"})[0] + == 422 + ) diff --git a/webui/tests/test_permissions.py b/webui/tests/test_permissions.py index 619f81e..c1fd3ad 100644 --- a/webui/tests/test_permissions.py +++ b/webui/tests/test_permissions.py @@ -74,6 +74,16 @@ def test_every_endpoint_is_authorized_and_global_admin_only() -> None: ("POST", "/api/lmn/squid/setup/start", {"password": "x"}), ("GET", "/api/lmn/squid/jobs/0123456789abcdef", None), ("POST", "/api/lmn/squid/a/keytab", {}), + ("GET", "/api/lmn/squid/a/catalog", None), + ("POST", "/api/lmn/squid/a/catalog/update", None), + ("GET", "/api/lmn/squid/a/instances/s-teachers/filter", None), + ("PUT", "/api/lmn/squid/a/instances/s-teachers/filter", {"categories": []}), + ("POST", "/api/lmn/squid/a/instances/s-teachers/exam", {"minutes": 5}), + ("DELETE", "/api/lmn/squid/a/instances/s-teachers/exam", None), + ("GET", "/api/lmn/squid/a/instances/s-teachers/filter/lookup", None), + ("GET", "/api/lmn/squid/a/instances/s-teachers/filter/stats", None), + ("GET", "/api/lmn/squid/a/instances/s-teachers/allowlist", None), + ("POST", "/api/lmn/squid/filter/bulk", {"targets": []}), ] From 9fb5b998ece8759a593a9cf914b0c6989d152177 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 14:21:26 +0100 Subject: [PATCH 06/19] style(image): the helper's Python files follow the control plane's ruff rules lmn_filterdecision.py is byte-identical to controlplane/lmnsquid/ filterdecision.py; with ruff's default line length the copy would be formatted differently. image/ruff.toml applies the project's settings. --- controlplane/lmnsquid/catalog.py | 2 ++ controlplane/lmnsquid/filterdecision.py | 6 +++--- image/lmn-filter-acl | 4 +++- image/lmn_filterdecision.py | 6 +++--- image/ruff.toml | 9 +++++++++ 5 files changed, 20 insertions(+), 7 deletions(-) create mode 100644 image/ruff.toml diff --git a/controlplane/lmnsquid/catalog.py b/controlplane/lmnsquid/catalog.py index a0d54f9..65fd705 100644 --- a/controlplane/lmnsquid/catalog.py +++ b/controlplane/lmnsquid/catalog.py @@ -507,6 +507,8 @@ def build_lock(cache_dir: Path) -> Iterator[None]: def is_building(cache_dir: Path) -> bool: + if not cache_dir.is_dir(): + return False try: with build_lock(cache_dir): return False diff --git a/controlplane/lmnsquid/filterdecision.py b/controlplane/lmnsquid/filterdecision.py index 0b0b5f3..ec2cc17 100644 --- a/controlplane/lmnsquid/filterdecision.py +++ b/controlplane/lmnsquid/filterdecision.py @@ -98,7 +98,7 @@ class Policy: broken: str | None = None # why filter.json could not be used (then: fail closed) @classmethod - def load(cls, filter_path: str, allowed_path: str) -> "Policy": + def load(cls, filter_path: str, allowed_path: str) -> Policy: """Read both files. A missing ``filter.json`` = no filter; an unreadable one = broken.""" allowed = read_domains(allowed_path) try: @@ -114,7 +114,7 @@ def load(cls, filter_path: str, allowed_path: str) -> "Policy": return cls(allowed=allowed, broken=f"filter.json invalid: {exc}") @classmethod - def from_dict(cls, data: dict[str, Any], allowed: frozenset[str]) -> "Policy": + def from_dict(cls, data: dict[str, Any], allowed: frozenset[str]) -> Policy: if data.get("format") != FORMAT: raise ValueError(f"format {data.get('format')!r}, expected {FORMAT}") exam = data.get("exam") or None @@ -139,7 +139,7 @@ def _local(self, now: float) -> datetime.datetime: return datetime.datetime.fromtimestamp(now, ZoneInfo(self.timezone)) except Exception: # noqa: BLE001 - unknown zone or no tzdata: UTC, never an error - return datetime.datetime.fromtimestamp(now, datetime.timezone.utc) + return datetime.datetime.fromtimestamp(now, datetime.UTC) def active_categories(self, now: float) -> list[str]: """The categories in force at ``now``: those without a schedule always, the others diff --git a/image/lmn-filter-acl b/image/lmn-filter-acl index 346c599..4d62ca3 100755 --- a/image/lmn-filter-acl +++ b/image/lmn-filter-acl @@ -90,7 +90,9 @@ class State: # squid writes %o of the block page byte by byte as HTML entities: UTF-8 becomes mojibake. -_ASCII = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss"}) +_ASCII = str.maketrans( + {"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss"} +) def quote(text: str) -> str: diff --git a/image/lmn_filterdecision.py b/image/lmn_filterdecision.py index 0b0b5f3..ec2cc17 100644 --- a/image/lmn_filterdecision.py +++ b/image/lmn_filterdecision.py @@ -98,7 +98,7 @@ class Policy: broken: str | None = None # why filter.json could not be used (then: fail closed) @classmethod - def load(cls, filter_path: str, allowed_path: str) -> "Policy": + def load(cls, filter_path: str, allowed_path: str) -> Policy: """Read both files. A missing ``filter.json`` = no filter; an unreadable one = broken.""" allowed = read_domains(allowed_path) try: @@ -114,7 +114,7 @@ def load(cls, filter_path: str, allowed_path: str) -> "Policy": return cls(allowed=allowed, broken=f"filter.json invalid: {exc}") @classmethod - def from_dict(cls, data: dict[str, Any], allowed: frozenset[str]) -> "Policy": + def from_dict(cls, data: dict[str, Any], allowed: frozenset[str]) -> Policy: if data.get("format") != FORMAT: raise ValueError(f"format {data.get('format')!r}, expected {FORMAT}") exam = data.get("exam") or None @@ -139,7 +139,7 @@ def _local(self, now: float) -> datetime.datetime: return datetime.datetime.fromtimestamp(now, ZoneInfo(self.timezone)) except Exception: # noqa: BLE001 - unknown zone or no tzdata: UTC, never an error - return datetime.datetime.fromtimestamp(now, datetime.timezone.utc) + return datetime.datetime.fromtimestamp(now, datetime.UTC) def active_categories(self, now: float) -> list[str]: """The categories in force at ``now``: those without a schedule always, the others diff --git a/image/ruff.toml b/image/ruff.toml new file mode 100644 index 0000000..50c51e1 --- /dev/null +++ b/image/ruff.toml @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The helper's Python files (ADR-022): the rules of controlplane/pyproject.toml, so the +# byte-identical lmn_filterdecision.py is formatted the same in both places. +line-length = 100 + +[lint] +select = ["E4", "E7", "E9", "F"] From a2bedca1d28d4e3ec38ff7d636e68dab59e6305c Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 14:32:17 +0100 Subject: [PATCH 07/19] perf(filter): one suffix list per lookup, protected list checked every 5 s The helper did a stat() of protected.domains on every lookup and split the host name three times. Measured in the image against the full catalog (5.6 million domains, half of the names listed): 7 700 -> 13 000-14 000 lookups/s per helper process, protocol included. --- controlplane/lmnsquid/filterdecision.py | 52 ++++++++++++++++--------- image/lmn_filterdecision.py | 52 ++++++++++++++++--------- 2 files changed, 66 insertions(+), 38 deletions(-) diff --git a/controlplane/lmnsquid/filterdecision.py b/controlplane/lmnsquid/filterdecision.py index ec2cc17..6ff83e3 100644 --- a/controlplane/lmnsquid/filterdecision.py +++ b/controlplane/lmnsquid/filterdecision.py @@ -71,9 +71,16 @@ def read_domains(path: str) -> frozenset[str]: return frozenset(names) -def listed(host: str, names: frozenset[str] | set[str]) -> str | None: - """The entry of ``names`` that covers ``host`` (itself or a parent domain), if any.""" - for suffix in suffixes(host): +def listed( + host: str, names: frozenset[str] | set[str], parts: list[str] | None = None +) -> str | None: + """The entry of ``names`` that covers ``host`` (itself or a parent domain), if any. + + ``parts`` = ``suffixes(host)`` when the caller has them already. + """ + if not names: + return None + for suffix in parts or suffixes(host): if suffix in names: return suffix return None @@ -185,9 +192,9 @@ def __init__(self, path: str) -> None: for sid, bit, name, lic in self.db.execute("SELECT id, bit, name, license FROM srcs") } - def lookup(self, host: str) -> tuple[int, int, dict[str, int]]: + def lookup(self, host: str, parts: list[str] | None = None) -> tuple[int, int, dict[str, int]]: """(category mask, source mask, {listed name: its category mask}) of ``host``.""" - names = suffixes(host) + names = parts or suffixes(host) marks = ",".join("?" * len(names)) cmask = smask = 0 hits: dict[str, int] = {} @@ -228,19 +235,20 @@ def decide( if policy.broken: # The control plane writes filter.json atomically; a broken one was edited by hand. return Decision(CATALOG_UNAVAILABLE, detail=policy.broken) + parts = suffixes(host) if policy.exam_active(now): - entry = listed(host, policy.exam_allowed) + entry = listed(host, policy.exam_allowed, parts) if entry: return Decision(EXAM_ALLOWED, entry=entry) return Decision(EXAM) - entry = listed(host, policy.allowed) + entry = listed(host, policy.allowed, parts) if entry: return Decision(EXCEPTION, entry=entry) active = policy.active_categories(now) if not active: return Decision(NONE) - protected = _protected(catalog) - entry = listed(host, protected) + protected = _protected(catalog, now) + entry = listed(host, protected, parts) if entry: return Decision(PROTECTED, entry=entry) if catalog is None: @@ -248,7 +256,7 @@ def decide( if closed: return Decision(CATALOG_UNAVAILABLE, category=closed[0], detail=catalog_error) return Decision(NONE, detail=f"catalog unavailable, not failing closed: {catalog_error}") - cmask, _smask, hits = catalog.lookup(host) + cmask, _smask, hits = catalog.lookup(host, parts) for category in active: bit = catalog.bits.get(category) if bit is not None and cmask & (1 << bit): @@ -257,8 +265,10 @@ def decide( return Decision(NONE) -# The protected list lives next to the catalog (written with it); read once per file change. -_PROTECTED: dict[str, tuple[float, frozenset[str]]] = {} +# The protected list lives next to the catalog (written with it); read once per file change, +# its mtime looked at no more than every few seconds (a stat per lookup costs a tenth of it). +_PROTECTED: dict[str, tuple[float, float, frozenset[str]]] = {} +PROTECTED_CHECK_SECONDS = 5.0 def protected_path(catalog: Catalog | None, catalog_dir: str | None = None) -> str: @@ -266,17 +276,21 @@ def protected_path(catalog: Catalog | None, catalog_dir: str | None = None) -> s return os.path.join(base, "protected.domains") -def _protected(catalog: Catalog | None) -> frozenset[str]: +def _protected(catalog: Catalog | None, now: float) -> frozenset[str]: path = PROTECTED_FILE or protected_path(catalog) + cached = _PROTECTED.get(path) + if cached is not None and 0 <= now - cached[0] < PROTECTED_CHECK_SECONDS: + return cached[2] try: mtime = os.stat(path).st_mtime except OSError: - return frozenset() - cached = _PROTECTED.get(path) - if cached is None or cached[0] != mtime: - cached = (mtime, read_domains(path)) - _PROTECTED[path] = cached - return cached[1] + mtime = -1.0 + if cached is None or cached[1] != mtime: + cached = (now, mtime, read_domains(path) if mtime >= 0 else frozenset()) + else: + cached = (now, cached[1], cached[2]) + _PROTECTED[path] = cached + return cached[2] # Set by callers that keep the protected list somewhere else than next to the catalog. diff --git a/image/lmn_filterdecision.py b/image/lmn_filterdecision.py index ec2cc17..6ff83e3 100644 --- a/image/lmn_filterdecision.py +++ b/image/lmn_filterdecision.py @@ -71,9 +71,16 @@ def read_domains(path: str) -> frozenset[str]: return frozenset(names) -def listed(host: str, names: frozenset[str] | set[str]) -> str | None: - """The entry of ``names`` that covers ``host`` (itself or a parent domain), if any.""" - for suffix in suffixes(host): +def listed( + host: str, names: frozenset[str] | set[str], parts: list[str] | None = None +) -> str | None: + """The entry of ``names`` that covers ``host`` (itself or a parent domain), if any. + + ``parts`` = ``suffixes(host)`` when the caller has them already. + """ + if not names: + return None + for suffix in parts or suffixes(host): if suffix in names: return suffix return None @@ -185,9 +192,9 @@ def __init__(self, path: str) -> None: for sid, bit, name, lic in self.db.execute("SELECT id, bit, name, license FROM srcs") } - def lookup(self, host: str) -> tuple[int, int, dict[str, int]]: + def lookup(self, host: str, parts: list[str] | None = None) -> tuple[int, int, dict[str, int]]: """(category mask, source mask, {listed name: its category mask}) of ``host``.""" - names = suffixes(host) + names = parts or suffixes(host) marks = ",".join("?" * len(names)) cmask = smask = 0 hits: dict[str, int] = {} @@ -228,19 +235,20 @@ def decide( if policy.broken: # The control plane writes filter.json atomically; a broken one was edited by hand. return Decision(CATALOG_UNAVAILABLE, detail=policy.broken) + parts = suffixes(host) if policy.exam_active(now): - entry = listed(host, policy.exam_allowed) + entry = listed(host, policy.exam_allowed, parts) if entry: return Decision(EXAM_ALLOWED, entry=entry) return Decision(EXAM) - entry = listed(host, policy.allowed) + entry = listed(host, policy.allowed, parts) if entry: return Decision(EXCEPTION, entry=entry) active = policy.active_categories(now) if not active: return Decision(NONE) - protected = _protected(catalog) - entry = listed(host, protected) + protected = _protected(catalog, now) + entry = listed(host, protected, parts) if entry: return Decision(PROTECTED, entry=entry) if catalog is None: @@ -248,7 +256,7 @@ def decide( if closed: return Decision(CATALOG_UNAVAILABLE, category=closed[0], detail=catalog_error) return Decision(NONE, detail=f"catalog unavailable, not failing closed: {catalog_error}") - cmask, _smask, hits = catalog.lookup(host) + cmask, _smask, hits = catalog.lookup(host, parts) for category in active: bit = catalog.bits.get(category) if bit is not None and cmask & (1 << bit): @@ -257,8 +265,10 @@ def decide( return Decision(NONE) -# The protected list lives next to the catalog (written with it); read once per file change. -_PROTECTED: dict[str, tuple[float, frozenset[str]]] = {} +# The protected list lives next to the catalog (written with it); read once per file change, +# its mtime looked at no more than every few seconds (a stat per lookup costs a tenth of it). +_PROTECTED: dict[str, tuple[float, float, frozenset[str]]] = {} +PROTECTED_CHECK_SECONDS = 5.0 def protected_path(catalog: Catalog | None, catalog_dir: str | None = None) -> str: @@ -266,17 +276,21 @@ def protected_path(catalog: Catalog | None, catalog_dir: str | None = None) -> s return os.path.join(base, "protected.domains") -def _protected(catalog: Catalog | None) -> frozenset[str]: +def _protected(catalog: Catalog | None, now: float) -> frozenset[str]: path = PROTECTED_FILE or protected_path(catalog) + cached = _PROTECTED.get(path) + if cached is not None and 0 <= now - cached[0] < PROTECTED_CHECK_SECONDS: + return cached[2] try: mtime = os.stat(path).st_mtime except OSError: - return frozenset() - cached = _PROTECTED.get(path) - if cached is None or cached[0] != mtime: - cached = (mtime, read_domains(path)) - _PROTECTED[path] = cached - return cached[1] + mtime = -1.0 + if cached is None or cached[1] != mtime: + cached = (now, mtime, read_domains(path) if mtime >= 0 else frozenset()) + else: + cached = (now, cached[1], cached[2]) + _PROTECTED[path] = cached + return cached[2] # Set by callers that keep the protected list somewhere else than next to the catalog. From c163eeb660a1765d31b88d09a65bf834601bccf8 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 14:36:16 +0100 Subject: [PATCH 08/19] docs: ADR-022 category filter, operations, threat model T21-T23, install, changelog ADR-022 records the design and where it deviates from the task (the protected list does not override the own blocklist, the exam end is checked by the helper, statistics in their own file instead of %et in access.log, the offered categories, English CLI help, nightly rebuild), with the measurements. ADR-016 amended: categories and the exam mode apply to noauth domains. --- README.md | 5 ++ RELEASE.md | 5 +- debian/changelog | 33 ++++++++++++ docs/architecture.md | 13 +++++ docs/decisions.md | 85 ++++++++++++++++++++++++++++- docs/install.md | 13 +++++ docs/operations.md | 122 +++++++++++++++++++++++++++++++++++++++++- docs/test-strategy.md | 14 +++++ docs/threat-model.md | 3 ++ 9 files changed, 290 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9c78ea1..d8b3ebb 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,11 @@ the same AD/Kerberos infrastructure the school already operates. is never decrypted). Optional per-instance list of domains reachable without proxy login from the school subnets (e.g. Microsoft 365; the blocklist still wins). + **Category filter** per instance (ADR-022): youth protection, security, VPN/proxy/DoH bypass, + ads, telemetry, distraction, AI services… from UT1 (CC BY-SA 4.0) and HaGeZi (GPL-3.0) lists + in one host-wide SQLite catalog (millions of entries without slowing squid down), schedules, + SafeSearch (Google, YouTube, Bing, DuckDuckGo) without decryption, exceptions, an exam mode, + "why is X blocked?" and anonymous statistics. - **Control Plane:** hardened systemd service with **REST API** (FastAPI) and **CLI** (Typer, thin client) — creates instances, configures policies, and **updates digest-pinned with health-check auto-rollback**. Shipped as a diff --git a/RELEASE.md b/RELEASE.md index d444a72..feaa11d 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -71,7 +71,10 @@ 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). -**7.3.8** is such a release: the noauth list (ADR-016) and `lists-sync.sh` live in the image; +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 +pinned image. **7.3.8** is such a release: the noauth list (ADR-016) and `lists-sync.sh` live in the image; until the digest is pinned, `lmnsquid noauth reload` answers 409 and the lists still reach squid unfiltered. The E2E service `squid-old` and the integration test `test_real_old_image_ignores_the_noauth_list` deliberately keep testing the image 7.3.7 pins diff --git a/debian/changelog b/debian/changelog index d91644d..c722e95 100644 --- a/debian/changelog +++ b/debian/changelog @@ -96,6 +96,39 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium taken) no longer stops the service; the loopback API keeps running and "lmnsquid health" shows "tls": "failed: ". PUT /v1/secrets enforces its 64 KiB limit while reading the body. + * Category filter per instance (ADR-022, docs/operations.md): youth + protection, malware/phishing, VPN/proxy/DoH bypass, search engines + without SafeSearch, ads, telemetry per vendor, social networks, games, + chat, streaming, warez, AI services, cheating; from UT1 (CC BY-SA 4.0) + and HaGeZi (GPL-3.0) lists that the proxy host downloads into one + catalog (5.6 million domains, ~200 MB, built in about 80 s with under + 120 MB of memory; nightly timer linuxmuster-squid-catalog.timer, only + while an instance uses categories; "lmnsquid catalog update"). squid + no longer parses large lists: a helper looks names up, lists and + categories change without a restart. Profiles "students"/"teachers", + schedules per category, a protected list (Windows Update, Microsoft + 365, Google Workspace, ... never blocked by a category), exceptions + ("lmnsquid allowlist"), "why is X blocked?" and anonymous statistics + (day and category only, filter.log). Youth protection fails closed: + without a usable catalog such instances refuse requests; build the + catalog first. HTTP gets a German block page naming the reason; HTTPS + still shows a certificate warning. Nothing changes for an instance + until you set its filter ("lmnsquid filter ...", API + /v1/instances//filter). + * SafeSearch per instance without decrypting: Google search (all country + domains), YouTube restricted mode (strict/moderate), Bing, DuckDuckGo. + * Exam mode per instance ("lmnsquid filter exam-start --minutes + N --allow "): only the listed domains, also for domains without + proxy login, ends by itself. + * Containers get the catalog directory as a read-only mount: the + update-all of the package upgrade that brings the data-plane image with + the filter replaces every container once (health-gated, as always). + Until that image is pinned, filter settings are stored without effect + and exam mode is refused. + * WebUI plugin: tab "Filter" per instance (categories, schedules, + profiles, SafeSearch, exam mode, catalog state with "update now", "why + is X blocked?", statistics), tab "Exceptions", "apply to other + instances" across proxy servers and an overview "Filter per school". -- 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 9b9cd5f..4ea5c0d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -102,6 +102,14 @@ Status document. Keep it up to date with every substantive change (see manager ACL localhost only; logs → stdout/stderr; healthcheck = an unauthenticated request that must return **407** (proves Squid is up *and* enforcing Kerberos). +- **Category filter (ADR-022):** an `external_acl_type` helper (`lmn-filter-acl`, Python, + `concurrency`, ttl 60 s) per instance decides from the instance's `filter.json` / + `allowed.domains` (list directory) and the host-wide catalog mounted read-only at + `/etc/squid/catalog` (one SQLite file, page cache shared by all instances): exam mode → + exceptions → protected list → categories with 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). + ## 4. Control Plane - **REST-API (FastAPI/uvicorn):** CRUD over instance definitions + @@ -118,6 +126,11 @@ Status document. Keep it up to date with every substantive change (see plugin; secret in `config.yml` `chmod 600`; **audit log** of every mutation. For clients: `GET /v1/status` (container state of all instances in one call) and `GET /v1/schema` (JSON schema of the instance model with its defaults). +- **Category catalog and filter (ADR-022):** `lmnsquid-catalog update` (nightly timer as + `lmnsquid`, or `POST /v1/catalog/update`) downloads UT1/HaGeZi lists and builds the catalog + streaming (sort on disk), checked and switched atomically; `GET|PUT …/filter`, `…/exam`, + `…/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. - **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 0a9b465..0cc9fb8 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -261,7 +261,10 @@ connections and asks to exempt its required endpoints; a client-side bypass (pro + firewall rules) was not wanted, the traffic should still pass the proxy's domain filter. **Price (threat model T16):** a listed domain is reachable by everyone in the school subnets without identity: exam accounts reach it in exam mode, the Internetsperre does not apply to it, -and the access log shows `-` instead of a user for it. **Rollout:** the template is in the +and the access log shows `-` instead of a user for it. **Amendment (2026-11-24, ADR-022):** the category filter and the exam mode apply to listed +domains too (`deny noauth_domains filter_blocked` before the allow line): in exam mode a noauth +domain is reachable only when it is on the exam's list. +**Rollout:** the template is in the data-plane image; `DEFAULT_IMAGE` must point at an image built with it before the release that ships the control plane is tagged (RELEASE.md). Until then the list is ignored and `lmnsquid noauth reload` answers 409 instead of reporting a reload that @@ -482,6 +485,86 @@ the passwords of `setup/start` do not reach a log. **Why paramiko:** already in memory; Ansible would need ansible-core and sshpass on the DC and the password in a file or the environment. **Price:** threat model T19 (password over the network, TOFU) and T20. +### ADR-022 — Category filter: host-wide SQLite catalog, external ACL helper, settings per instance +**Status:** Proposed (2026-11-24, Kevin: "bau das ein"; task `work/tasks/squid-filterkategorien.md`, +research `work/linuxmuster-squid/recherche-filterlisten.md`). **Decision:** category lists are not +squid lists any more. `lmnsquid-catalog update` (nightly systemd timer as `lmnsquid`, or `POST +/v1/catalog/update`) downloads the sources of the packaged `sources.yml` (UT1 CC BY-SA 4.0 as the +backbone, HaGeZi GPL-3.0 for ads, security, bypass, telemetry and "no SafeSearch"; extendable in +`/etc/linuxmuster-squid/catalog.yml`; the package ships no list content) with conditional GETs and +builds **one SQLite file** per proxy host, `/var/lib/linuxmuster-squid/catalog/current.sqlite` +(symlink, switched atomically; one previous version kept): domain → bit mask of school categories +and of sources. The build streams (parse to a file, GNU `sort` on disk, merge, insert in order): +measured 5.6 million domains, 195 MiB, 70–80 s, 44 MiB RSS plus 64 MiB for `sort`, and it completes +under a 160 MiB memory limit. The directory is mounted read-only into every container at +`/etc/squid/catalog`; per instance an `external_acl_type` helper (`lmn-filter-acl`, Python stdlib, +`concurrency=100`, `ttl=60`, children 1–4 for `%DST` and 1–2 for `%ssl::>sni`) decides with +`filterdecision.py` (byte-identical in the control plane and the image, a test enforces it) from +the instance's `filter.json`, `allowed.domains` and the catalog. Order: **exam mode** (only its +own list) → **exceptions** (`allowed.domains`) → **protected list** → **categories** (with +schedules). Settings per instance in the instance's list directory (ADR-014, so no mount of its +own): `filter.json` (categories, schedules, SafeSearch, exam; written by the control plane only), +`allowed.domains`, `safesearch.hosts`. Changes are applied at once with `squid -k reconfigure`, +which (measured with squid 6.14) also empties squid's cache of helper answers; a new catalog +needs no reconfigure (the helper notices the new file within 5 s, squid's cache ttl is 60 s). +Without `filter.json` the helper blocks nothing: **an upgrade changes no behaviour**; instances +get no categories automatically, the WebUI says "Filter noch nicht eingerichtet" and proposes +the profile of the role (students / teachers, §2.1 of the research). +**squid.conf (image):** `deny filter_blocked` after `deny !authenticated` and the own blocklist +(→ 403 with a German block page via `deny_info ERR_LMN_BLOCKED`, `%o` = the helper's message, +ASCII because squid escapes `%o` byte by byte); `deny noauth_domains filter_blocked` before the +noauth allow line, so categories and the exam mode apply to noauth domains too (ADR-016 amended); +`ssl_bump terminate filter_blocked_sni`; `hosts_file /run/lmnsquid/hosts` (= the container's +`/etc/hosts` plus `safesearch.hosts`, built by `lists-sync.sh`); the own blocklist now reads +`deny blocked_domains !allowed_domains` (an empty exception list = the old rule). +**Fail-closed:** while the catalog is missing or unusable and a category marked `fail_closed` +(the five youth protection categories) is active, every request except exceptions and the +protected list is refused (block page "Filterkatalog nicht verfügbar"); with only other +categories the filter opens. A hand-broken `filter.json` also refuses. The helper never answers +`BH` (squid would skip the deny line). A failed update keeps the active catalog: a download error +falls back to the previous download, a source below its `min_entries` or a category shrinking by +more than half stops the build; `status` reports the age, older than 7 days is a warning. +**SafeSearch** through squid's `hosts_file`, no decryption: Google (187 country domains of +`google.com/supported_domains`, pinned in the package, `www.`, bare and `images.`), YouTube +restricted strict/moderate, Bing, DuckDuckGo. The control plane resolves the services' addresses +at every change and every container creation; a failed lookup keeps the last known address +(Google/YouTube: Google's documented address as the last resort). Measured: CONNECT +`www.google.de` goes to `216.239.38.120` with a valid certificate; the certificates of +`strict.bing.com` (for `www.bing.com`, `bing.com`) and `safe.duckduckgo.com` (for +`duckduckgo.com`, `www.duckduckgo.com`) verify too, whether their content is then filtered is not +verified. Switching SafeSearch on pre-selects "search engines without SafeSearch". +**Exam mode** per instance (`POST/DELETE /v1/instances/{name}/exam`): only the listed domains +(template "school server only" = the realm's DNS domain) until `until`; refused (409, nothing +stored) unless the running image has the filter. **Statistics:** `filter.log` in the log volume +with only the day and the category of a filtered request (`logformat lmnfilter %{%Y-%m-%d}tl +%{category}note`), rotated with the access log's retention; summed by `GET …/filter/stats`. +**Deviations from the task, and why:** (1) the protected list protects against *categories* +only, not against the instance's own blocklist: an explicit block by the admin is intent, and +otherwise an upgrade could unblock entries of existing lists (the task asked for no behaviour +change). (2) The end of an exam is evaluated by the helper itself (`until` in `filter.json`), no +systemd timer: it ends even when the control plane is down; squid's answer cache delays it by at +most 60 s; an expired exam is cleared on the next write. (3) Statistics in a separate file instead +of `%et` in `access.log`: the access log's format stays as it was (log parsers, `access-logs`), +and the statistics file carries no person at all, also with the access log switched off. +(4) Category ids follow §2.1; `mixed_adult` (platforms with mixed content, false positives) and +the expert categories (`jobsearch`, `webmail`, `remote-control`, `shortener`, …) are not offered; +ads come from HaGeZi Multi Light only. (5) The CLI help is English like every other command (the +task assumed German help). (6) The catalog is rebuilt every night even when every source answered +304 (76 s at low priority; skipping would make the age check meaningless). +**Why:** squid's `dstdomain` builds a splay tree per list and instance at every start and +reconfigure (2 million entries: 25 s + 2 × 55 s; UT1 `adult` alone has 4.6 million), the helper +keeps one file in the page cache per host and lets lists and categories change without a restart; +squidGuard/ufdbGuard/e2guardian are unmaintained, unpackaged or break the Kerberos chain (research +§4.1). **Price:** a Python helper per instance (measured 14–17 MiB RSS each, 13 000–14 000 +lookups/s per process against the full catalog, +1.7 ms for the first lookup of a name), the +catalog directory as a fifth mount (one replacement of every container, done by the `update-all` +of the release that pins the image), ~0.4 GB on disk (two catalog versions plus downloads), +python3 and tzdata in the image. HTTPS still shows no block page (ADR-002 unchanged). +**Rollout:** the helper, template and block page are in the data-plane image: until +`DEFAULT_IMAGE` points at an image built with them, filter settings are stored but have no effect +(`PUT …/filter` answers `"applied": false, "reason": "image"`, the exam mode and the exception +reload answer 409), as for ADR-016. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/install.md b/docs/install.md index 1349409..8f0c39d 100644 --- a/docs/install.md +++ b/docs/install.md @@ -221,6 +221,19 @@ traffic to allowed sites is never decrypted (it is spliced). Details, the file p UT-Capitole category lists: [`operations.md`](operations.md#blocklist-per-instance). +## 7a. Category filter, SafeSearch, exam mode (optional) + +```bash +lmnsquid catalog update --wait # first catalog (UT1 + HaGeZi, ~1-2 min, ~0.4 GB disk) +lmnsquid filter all-students profile students # youth protection, security, bypass, SafeSearch +lmnsquid filter all-teachers profile teachers # security, VPN/proxies, DoH +lmnsquid filter all-students lookup example.org +``` + +A nightly timer (`linuxmuster-squid-catalog.timer`) keeps the catalog current. Build the catalog +**before** enabling youth protection categories: without a catalog those instances refuse every +request (fail-closed). Details: [`operations.md`](operations.md#category-filter-safesearch-exceptions-exam-mode-per-instance). + ## 8. Domains without proxy authentication (optional) Some services break behind proxy authentication; Microsoft names it among the techniques that diff --git a/docs/operations.md b/docs/operations.md index 9eed7ab..40d147f 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -181,7 +181,8 @@ lmnsquid blocklist default-school-students reload # squid re-reads file** — entries added with `lmnsquid blocklist add` are lost, so keep manually curated instances out of the refresh or re-add them afterwards. The directory must stay owned by `lmnsquid` so the API can keep writing (it replaces the file atomically). -- **Large category lists (known limit):** `lists-sync.sh` reads the whole list at every start +- **Large category lists:** use the category filter instead (next sections, ADR-022): it reads + millions of entries from one file without squid parsing them. Known limit of this list: `lists-sync.sh` reads the whole list at every start and reload (measured in the cold verification of 2026-10-30: 2 million entries ≈ 25 s and ≈ 290 MiB), and squid then parses it (≈ 55 s for the same list, twice at a start). With lists that size a start can exceed the 90 s health gate of `update`/`reconcile` and roll back. Keep category selections moderate @@ -301,6 +302,122 @@ lmnsquid noauth all-students list && lmnsquid noauth all-students reload of Microsoft names in `lmnsquid logs ` before adding anything: every entry widens what is reachable without identity. +## Category filter, SafeSearch, exceptions, exam mode (per instance) + +Per instance (= per school and role) the proxy can block whole categories (youth protection, +malware, VPN/proxies, ads, social networks, AI services, …), force SafeSearch, let exceptions +through, switch to an exam mode and explain why a site is blocked (ADR-022). Nothing is active +after an upgrade: an instance without filter settings behaves as before. + +**The catalog** (one per proxy host): `/var/lib/linuxmuster-squid/catalog/current.sqlite`, built +from the lists of UT1 (Université Toulouse Capitole, **CC BY-SA 4.0**) and HaGeZi DNS Blocklists +(**GPL-3.0**); the package ships no list, it downloads them on this host. + +``` +lmnsquid catalog update --wait # first build (about 1-2 minutes, ~50 MB download) +lmnsquid catalog status # age, domains, categories with size and sources, last run +lmnsquid catalog lookup example.org # which categories/sources list a name +systemctl list-timers linuxmuster-squid-catalog.timer # nightly 01:30 + up to 2 h random delay +journalctl -u linuxmuster-squid-catalog.service # the nightly runs +``` + +- The timer runs `lmnsquid-catalog update --if-needed` as `lmnsquid` (MemoryMax 400 MiB, idle + I/O): it does nothing while no instance uses categories and no catalog exists. Downloads are + conditional (ETag / If-Modified-Since), UT1 rate-limits, so do not run it more often. +- **Safety:** a source that cannot be downloaded falls back to its last download; a source with + fewer entries than its `min_entries` or a category that shrinks by more than half stops the + build and the **active catalog stays** (`status` shows `last_run.state: failed` and the + error). The previous version stays on disk (`catalog-
- + @@ -195,7 +194,6 @@ {{row.inst.role}} {{row.inst.http_port}} {{stateText(row.inst)}} - exam until {{timeText(row.inst.state.filter.exam_until)}} filter problem @@ -214,7 +212,7 @@
- + @@ -620,31 +618,6 @@

{{detail.conn.display_name}} / {{detail.inst.name}}

- -
- Exam mode active until {{timeText(detail.filter.view.exam.until)}}. - Reachable: {{(detail.filter.view.exam.allowed || []).join(', ') || '–'}} - -
-
-
Exam mode
-
-

Only the listed domains (and their subdomains) are reachable through this instance until the time is up; it ends by itself. Domains without proxy login are blocked too.

-
-
- - -
-
- - -
-
- - -
-
-
Filter not set up yet. This instance blocks only its own blocklist. Apply a profile, check it and save.
@@ -654,7 +627,7 @@

{{detail.conn.display_name}} / {{detail.inst.name}}

Catalog: - {{timeText(detail.filter.catalog.built)}}, {{detail.filter.catalog.domains | number}} domains + {{timeText(detail.filter.catalog.checked || detail.filter.catalog.built, detail.filter.catalog.timezone)}}, {{detail.filter.catalog.domains | number}} domains not available update running @@ -662,25 +635,80 @@

{{detail.conn.display_name}} / {{detail.inst.name}}

+

+
- Apply a profile: - + Template: + +
+
+
Preview of the template „{{detail.filter.preview.profile.label}}“ – {{detail.filter.preview.profile.description}}
+
+

switched on {{detail.filter.preview.diff.on.join(', ')}}

+

switched off {{detail.filter.preview.diff.off.join(', ')}}

+

back to the recommended lists {{detail.filter.preview.diff.variants.join(', ')}}

+

time windows removed {{detail.filter.preview.diff.schedules.join(', ')}}

+

SafeSearch {{x.key}}: {{x.from}} → {{x.to}}{{$last ? '' : ', '}}

+

No changes: the settings already match the template.

+ + +
-
-
-
{{g.group.label}}
-
- - {{c.count | number}} · {{src.name}} ({{src.license}}){{$last ? '' : ', '}} - time window -
+
+ + + + + + +
+

Time windows in {{scheduleZone()}}. Details of a category (description, examples, sources and licences):

+ + +
+
+ + {{g.group.label}} + {{groupActive(g)}} / {{g.categories.length}} + + + + +
+
+

{{g.group.description}}

+ +
+
+ + {{catStateText(catState(c))}} + + + + {{variantOf(c).count | number}}{{c.own_entries | number}} + + + + +
+
+
{{c.description}}
+
Examples: {{x}}
+
{{c.warning}}
+
{{variantOf(c).warning}}
+
{{src.name}} – {{src.license}}, {{src.count | number}} entries, as of {{src.last_modified || timeText(src.fetched, detail.filter.catalog.timezone)}}, not downloaded yet
+
+
- – - + – + + ({{scheduleZone()}})
@@ -719,7 +747,7 @@
Why is a site blocked?
- +
Result{{ruleText(detail.filter.lookup.result.rule)}} {{detail.filter.lookup.result.category_label}}
Matching entry{{detail.filter.lookup.result.entry}}
Listed in categories{{l.label}} (not active){{$last ? '' : ', '}}
Listed in categories{{l.label}} (not active) (not in the chosen lists){{$last ? '' : ', '}}
Sources{{src.name}} ({{src.license}}){{$last ? '' : ', '}}
@@ -745,7 +773,7 @@
Statistics fi

A domain blocks itself and all subdomains. HTTPS shows a certificate warning, not a block page.

-

A domain listed here and its subdomains are reachable although the blocklist or a filter category names them. Not during the exam mode.

+

A domain listed here and its subdomains are reachable although the blocklist or a filter category names them.

@@ -783,18 +811,25 @@

Apply the filter to other instances

+ + + + + + + diff --git a/webui/lmn_squid/sitefacts.py b/webui/lmn_squid/sitefacts.py index b67264b..f44bff7 100644 --- a/webui/lmn_squid/sitefacts.py +++ b/webui/lmn_squid/sitefacts.py @@ -10,6 +10,7 @@ from __future__ import annotations import configparser +import os import re from dataclasses import dataclass from pathlib import Path @@ -100,3 +101,18 @@ def computer_account_roles(path: str = SOPHOMORIX_INI) -> dict[str, bool]: if key.upper() == "COMPUTER_ACCOUNT": roles[section] = value.upper() == "TRUE" return roles + + +def local_timezone() -> str: + """The zone of this server (the DC), e.g. ``Europe/Berlin``; '' when unknown.""" + try: + name = open("/etc/timezone", encoding="utf-8").read().strip() + if name: + return name + except OSError: + pass + try: + target = os.readlink("/etc/localtime") + except OSError: + return "" + return target.split("zoneinfo/", 1)[1] if "zoneinfo/" in target else "" diff --git a/webui/lmn_squid/sshsetup.py b/webui/lmn_squid/sshsetup.py index d604048..b5a6ec3 100644 --- a/webui/lmn_squid/sshsetup.py +++ b/webui/lmn_squid/sshsetup.py @@ -296,6 +296,7 @@ class Setup: display_name: str schools: list[str] keytab: bool + timezone: str = "" # the school server's zone, set on the VM too (filter schedules) @property def short(self) -> str: @@ -333,6 +334,9 @@ def from_payload(cls, p: dict[str, Any]) -> "Setup": display_name=str(p.get("display_name") or ""), schools=[str(s) for s in p.get("schools") or []], keytab=bool(p.get("keytab", True)), + timezone=str(p.get("timezone") or "") + if TZ_RE.match(str(p.get("timezone") or "")) + else "", ) @@ -400,10 +404,22 @@ def preflight_findings(facts: dict[str, str], now: float) -> tuple[list[str], li return errors, warnings -def time_script(serverip: str) -> str: +TZ_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_+-]*(/[A-Za-z0-9_+-]+){0,2}$") + + +def time_script(serverip: str, timezone: str = "") -> str: + """NTP from the school server, and its time zone (idempotent; only a valid zone name).""" ip = shlex.quote(serverip) + tz = "" + if TZ_RE.match(timezone): + zone = shlex.quote(timezone) + tz = ( + f"if [ -e /usr/share/zoneinfo/{zone} ] && " + f'[ "$(timedatectl show -p Timezone --value)" != {zone} ]; then ' + f"timedatectl set-timezone {zone}; fi; " + ) return ( - "set -e; if systemctl is-active -q chrony; then " + "set -e; " + tz + "if systemctl is-active -q chrony; then " "mkdir -p /etc/chrony/sources.d; " f"printf 'server %s iburst\\n' {ip} > /etc/chrony/sources.d/linuxmuster-squid.sources; " "chronyc reload sources >/dev/null; " @@ -414,6 +430,7 @@ def time_script(serverip: str) -> str: "for i in $(seq 1 20); do " '[ "$(timedatectl show -p NTPSynchronized --value)" = yes ] && break; sleep 1; done; ' f"echo server={ip}; " + 'echo "timezone=$(timedatectl show -p Timezone --value)"; ' 'echo "synced=$(timedatectl show -p NTPSynchronized --value)"; ' "if systemctl is-active -q chrony; then " "echo \"offset=$(chronyc tracking | awk -F': ' '/^System time/ {print $2}')\"; " @@ -429,6 +446,8 @@ def time_summary(out: str) -> tuple[str, str]: text = f"NTP-Server {facts.get('server', '?')}, synchronisiert: {'ja' if synced else 'nein'}" if facts.get("offset", "").strip(): text += f", Abweichung {facts['offset'].strip()}" + if facts.get("timezone", "").strip(): + text += f", Zeitzone {facts['timezone'].strip()}" if not synced: text += " (noch nicht; Kerberos verträgt höchstens 5 Minuten Abweichung)" return ("ok" if synced else "warning"), text @@ -641,7 +660,10 @@ def run_setup( current = "time" rep.set(current, "running") - rep.set(current, *time_summary(remote.must(current, time_script(s.serverip), timeout=90.0))) + rep.set( + current, + *time_summary(remote.must(current, time_script(s.serverip, s.timezone), timeout=90.0)), + ) for current, script in ( ("dns", dns_script(s.serverip, s.domain, s.server_fqdn)), @@ -809,7 +831,7 @@ def preflight_control_plane(cp: ControlPlaneClient) -> list[dict[str, Any]]: names = keytab_mod.secret_names(instances) cp.request("GET", f"/v1/secrets/{names[0]}") except ControlPlaneError as exc: - if exc.kind == "http" and exc.status == 404: + if exc.status == 404: raise StepFailed( "keytab", "Control Plane zu alt: der Proxy kennt den Keytab-Empfang (PUT /v1/secrets) " diff --git a/webui/lmn_squid/views.py b/webui/lmn_squid/views.py index df24a15..7f41d6b 100644 --- a/webui/lmn_squid/views.py +++ b/webui/lmn_squid/views.py @@ -20,6 +20,7 @@ from __future__ import annotations import ipaddress +import re import logging import time from functools import wraps @@ -61,7 +62,9 @@ CONN = r"(?P[^/]+)" NAME = r"(?P[^/]+)" LIST_KINDS = ("blocklist", "noauth", "allowlist") -FILTER_KEYS = ("categories", "schedules", "safesearch") +# own category (own_x) or own source (own-x) id as the control plane accepts it +CUSTOM_ID_RE = re.compile(r"^own[_-][a-z0-9_-]{1,30}$") +FILTER_KEYS = ("categories", "variants", "schedules", "safesearch") BULK_MAX = 200 HOSTKEY_TTL = 900.0 @@ -343,6 +346,7 @@ def handle_setup_start(self, http_context: Any) -> Any: "display_name": str(body.get("display_name") or ""), "schools": [str(body.get("school"))], "keytab": bool(body.get("keytab", True)), + "timezone": site_mod.local_timezone(), } if not sshsetup.USER_RE.match(str(payload["user"])) or not payload["password"]: raise EndpointReturn( @@ -784,37 +788,69 @@ def handle_filter_bulk(self, http_context: Any) -> Any: ) return {"results": results} - @post(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/exam") + # ------------------------------------------- own sources and categories (per server) + @get(PREFIX + "/" + CONN + r"/catalog/custom") + @authorize(PERM_LIST) + @endpoint(api=True) + @global_admin_only + def handle_custom_get(self, http_context: Any, conn: str = "") -> Any: + return self._client(conn).request("GET", "/v1/catalog/custom") + + @post(PREFIX + "/" + CONN + r"/catalog/custom/(?Pcategories|sources)") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only - def handle_exam_start(self, http_context: Any, conn: str = "", name: str = "") -> Any: - data = _body(http_context) - allowed = data.get("allowed") or [] - if not isinstance(allowed, list): - raise EndpointReturn( - 422, {"error": "invalid", "field": "allowed", "message": "a list of domains"} - ) - body = {"minutes": data.get("minutes"), "allowed": allowed} - self._audit( - "exam start", - conn=conn, - name=name, - minutes=body["minutes"], - allowed=",".join(str(d) for d in allowed), - ) - return self._client(conn).request( - "POST", instance_path(name, "exam"), body=body, timeouts=(SHORT[0], 60.0) + def handle_custom_add(self, http_context: Any, conn: str = "", kind: str = "") -> Any: + """An own category or source; the control plane validates every field.""" + body = _body(http_context) + keys = ( + ("id", "label", "description") + if kind == "categories" + else ("id", "name", "url", "format", "category", "license", "min_entries", "max_mb") ) + body = {k: body[k] for k in keys if k in body} + self._audit(f"own {kind} add", conn=conn, id=body.get("id"), url=body.get("url")) + return self._client(conn).request("POST", f"/v1/catalog/custom/{kind}", body=body) - @delete(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/exam") + @delete(PREFIX + "/" + CONN + r"/catalog/custom/(?Pcategories|sources)/(?P[^/]+)") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only - def handle_exam_stop(self, http_context: Any, conn: str = "", name: str = "") -> Any: - self._audit("exam stop", conn=conn, name=name) + def handle_custom_remove( + self, http_context: Any, conn: str = "", kind: str = "", item: str = "" + ) -> Any: + if not CUSTOM_ID_RE.match(item): + raise EndpointReturn(422, {"error": "invalid", "field": "id", "message": "id"}) + self._audit(f"own {kind} remove", conn=conn, id=item) + self._client(conn).request("DELETE", f"/v1/catalog/custom/{kind}/{item}") + return {"removed": item} + + @get(PREFIX + "/" + CONN + r"/catalog/custom/categories/(?P[^/]+)/domains") + @authorize(PERM_LIST) + @endpoint(api=True) + @global_admin_only + def handle_custom_domains_get(self, http_context: Any, conn: str = "", item: str = "") -> Any: + if not CUSTOM_ID_RE.match(item): + raise EndpointReturn(422, {"error": "invalid", "field": "id", "message": "id"}) + return self._client(conn).request("GET", f"/v1/catalog/custom/categories/{item}/domains") + + @put(PREFIX + "/" + CONN + r"/catalog/custom/categories/(?P[^/]+)/domains") + @authorize(PERM_CHANGE) + @endpoint(api=True) + @global_admin_only + def handle_custom_domains_put(self, http_context: Any, conn: str = "", item: str = "") -> Any: + if not CUSTOM_ID_RE.match(item): + raise EndpointReturn(422, {"error": "invalid", "field": "id", "message": "id"}) + domains = _body(http_context).get("domains") or [] + if not isinstance(domains, list): + raise EndpointReturn( + 422, {"error": "invalid", "field": "domains", "message": "a list of domains"} + ) + self._audit("own category domains", conn=conn, id=item, count=len(domains)) return self._client(conn).request( - "DELETE", instance_path(name, "exam"), timeouts=(SHORT[0], 60.0) + "PUT", + f"/v1/catalog/custom/categories/{item}/domains", + body={"domains": [str(d) for d in domains]}, ) @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter/lookup") diff --git a/webui/tests/conftest.py b/webui/tests/conftest.py index 2a768e7..f5db4a1 100644 --- a/webui/tests/conftest.py +++ b/webui/tests/conftest.py @@ -318,6 +318,7 @@ def control_plane(tmp_path: Path, token: str) -> Iterator[dict[str, Any]]: catalog_dir=str(tmp_path / "catalog"), catalog_cache_dir=str(tmp_path / "catalog-cache"), catalog_config=str(tmp_path / "catalog.yml"), + catalog_custom=str(tmp_path / "catalog-custom.yml"), protected_file=str(tmp_path / "protected.domains"), filter_timezone="Europe/Berlin", ) diff --git a/webui/tests/js/controller_check.js b/webui/tests/js/controller_check.js index d8b3fb3..5407474 100644 --- a/webui/tests/js/controller_check.js +++ b/webui/tests/js/controller_check.js @@ -274,36 +274,90 @@ hzs.startKeytab(); assert.strictEqual(hzs.keytabForm.jobId, undefined); assert.strictEqual(hzs.keytabForm.precheck.checks[0].message, 'nicht der Proxy dieser Verbindung'); -// --- category filter (ADR-022): profile, SafeSearch pre-select, schedules, body, bulk --------- +// --- category filter (ADR-022): groups, search, variants, profile preview, bulk, own lists --- +const V = (id, label, def, warning, sources) => ({id, label, default: def, warning: warning || '', sources: sources || [], count: 5, missing: []}); const CATALOG = {available: true, built: 1795000000, domains: 5, building: false, last_run: {state: 'ok'}, - groups: [{id: 'youth', label: 'Jugendschutz'}, {id: 'bypass', label: 'Umgehung'}, {id: 'distraction', label: 'Ablenkung'}], - categories: [{id: 'porn', group: 'youth', label: 'Pornografie', count: 3, sources: []}, - {id: 'nosafesearch', group: 'bypass', label: 'Suchmaschinen ohne SafeSearch', count: 1, sources: []}, - {id: 'social', group: 'distraction', label: 'Soziale Netzwerke', count: 1, sources: []}], - profiles: {students: {label: 'Schüler', categories: ['porn', 'nosafesearch'], safesearch: {google: true, youtube: 'strict', bing: false, duckduckgo: false}}, - teachers: {label: 'Lehrkräfte', categories: [], safesearch: {google: false, youtube: 'off', bing: false, duckduckgo: false}}}}; -const FV = {name: 'one-students', configured: false, settings: {categories: [], schedules: {}, safesearch: {google: false, youtube: 'off', bing: false, duckduckgo: false}}, exam: null, summary: {}}; + groups: [{id: 'youth', label: 'Jugendschutz'}, {id: 'bypass', label: 'Umgehung'}, {id: 'ads', label: 'Werbung'}, {id: 'distraction', label: 'Ablenkung'}, {id: 'expert', label: 'Experten'}], + categories: [ + {id: 'porn', group: 'youth', label: 'Pornografie', description: 'explizit', examples: ['pornhub.com'], fail_closed: true, count: 3, + variants: [V('both', 'UT1 und HaGeZi', true, '', [{name: 'UT1', license: 'CC BY-SA 4.0'}]), V('ut1', 'nur UT1', false)]}, + {id: 'nosafesearch', group: 'bypass', label: 'Suchmaschinen ohne SafeSearch', description: '', examples: [], count: 1, variants: [V('', '', true)]}, + {id: 'ads', group: 'ads', label: 'Werbung und Tracking', description: '', examples: ['doubleclick.net'], count: 1, + variants: [V('light', 'Light', true), V('pro', 'Pro', false, 'bricht Seiten', [{name: 'HaGeZi Multi Pro', license: 'GPL-3.0'}])]}, + {id: 'social', group: 'distraction', label: 'Soziale Netzwerke', description: '', examples: ['instagram.com'], count: 1, variants: [V('', '', true)]}, + {id: 'shopping', group: 'expert', label: 'Online-Shopping', description: '', examples: [], warning: 'Schulmaterial', count: 1, variants: [V('', '', true)]}], + profiles: {students: {label: 'Schüler', description: 'x', categories: ['porn', 'nosafesearch'], safesearch: {google: true, youtube: 'strict', bing: false, duckduckgo: false}}, + teachers: {label: 'Lehrkräfte', description: 'y', categories: [], safesearch: {google: false, youtube: 'off', bing: false, duckduckgo: false}}}}; +const FV = {name: 'one-students', configured: false, settings: {categories: ['social'], variants: {}, schedules: {social: [{days: ['mo'], start: '08:00', end: '09:00'}]}, safesearch: {google: false, youtube: 'off', bing: false, duckduckgo: false}}, summary: {}}; const RF = Object.assign({}, ROUTES, { 'GET /api/lmn/squid/b/catalog': {status: 200, data: CATALOG}, + 'GET /api/lmn/squid/a/catalog': {status: 200, data: CATALOG}, 'GET /api/lmn/squid/b/instances/one-students/filter': {status: 200, data: FV}, - 'PUT /api/lmn/squid/b/instances/one-students/filter': {status: 200, data: Object.assign({}, FV, {configured: true, applied: false, reason: 'image'})}, - 'POST /api/lmn/squid/b/instances/one-students/exam': {status: 200, data: Object.assign({}, FV, {exam: {active: true, until: 1795003600, allowed: ['dev.lmschule.de']}})}, + 'PUT /api/lmn/squid/b/instances/one-students/filter': {status: 200, data: Object.assign({}, FV, {configured: true, applied: false, reason: 'image', missing_sources: ['hagezi-pro']})}, 'POST /api/lmn/squid/filter/bulk': {status: 200, data: {results: [{conn: 'b', name: 'one-students', ok: true, applied: true}, {conn: 'a', name: 'one-teachers', ok: false, error: 'unreachable', message: 'down'}]}}, + 'GET /api/lmn/squid/b/catalog/custom': {status: 200, data: {sources: [], categories: [{id: 'own_x', label: 'Eigene', domains: 1}]}}, + 'POST /api/lmn/squid/b/catalog/custom/categories': {status: 200, data: {id: 'own_y'}}, + 'POST /api/lmn/squid/b/catalog/custom/sources': {status: 422, data: {error: 'http', status: 422, detail: [{loc: ['body', 'url'], msg: 'Value error, an https:// URL'}]}}, + 'GET /api/lmn/squid/b/catalog/custom/categories/own_x/domains': {status: 200, data: {domains: ['a.example']}}, + 'PUT /api/lmn/squid/b/catalog/custom/categories/own_x/domains': {status: 200, data: {domains: ['a.example', 'b.example']}}, }); const hf = harness(RF, {}); const fs_ = hf.scope; const studentsRow = fs_.servers.b.instances.find((i) => i.name === 'one-students'); -studentsRow.realm = 'DEV.LMSCHULE.DE'; assert.strictEqual(fs_.suggestedProfile(studentsRow), 'students'); assert.strictEqual(fs_.suggestedProfile({role: 'teachers'}), 'teachers'); -assert.strictEqual(fs_.suggestedProfile({role: 'guests'}), null); +assert.strictEqual(fs_.suggestedProfile({role: 'gaeste'}), null); +assert.strictEqual(fs_.suggestedProfile({role: 'guests'}), 'guests'); +assert.strictEqual(fs_.suggestedProfile({role: 'grundschule-students'}), 'primary'); +assert.strictEqual(fs_.suggestedProfile({role: 'verwaltung'}), 'staff'); fs_.openDetail(fs_.connections[1], studentsRow, 'filter'); const f = fs_.detail.filter; -assert.ok(f && f.catalog.grouped.length === 3, 'catalog grouped'); -assert.strictEqual(f.view.configured, false); -fs_.applyProfile('students'); +assert.ok(f && f.catalog.grouped.length === 5, 'catalog grouped'); +// groups: youth/bypass open by default, distraction open because social is on, expert closed +assert.deepStrictEqual(Object.keys(f.ui.open).filter((k) => f.ui.open[k]).sort(), ['bypass', 'distraction', 'youth']); +const groups = {}; +f.catalog.grouped.forEach((g) => { groups[g.group.id] = g; }); +assert.strictEqual(fs_.groupActive(groups.distraction), 1); +assert.strictEqual(fs_.catState(f.catalog.byId.social), 'scheduled'); +assert.strictEqual(fs_.catState(f.catalog.byId.porn), 'off'); +// search: label, example domains and source names match; a search opens every group +f.ui.query = 'doubleclick'; +assert.ok(fs_.catMatches(f.catalog.byId.ads) && !fs_.catMatches(f.catalog.byId.porn)); +assert.ok(fs_.groupVisible(groups.ads) && !fs_.groupVisible(groups.youth)); +assert.ok(fs_.groupOpen(groups.expert)); +f.ui.query = 'hagezi multi pro'; +assert.ok(fs_.catMatches(f.catalog.byId.ads)); +f.ui.query = ''; +// all on / all off of a group +fs_.setGroup(groups.youth, true); +assert.strictEqual(f.checked.porn, true); +fs_.setGroup(groups.youth, false); +assert.strictEqual(f.checked.porn, false); +// variants: only non-default ones are sent; the warning of the chosen one is shown +f.checked.ads = true; +f.variants.ads = 'light'; +assert.deepStrictEqual(fs_.filterBody(f).variants, {}); +f.variants.ads = 'pro'; +assert.deepStrictEqual(fs_.filterBody(f).variants, {ads: 'pro'}); +assert.strictEqual(fs_.variantOf(f.catalog.byId.ads).warning, 'bricht Seiten'); +f.variants.ads = 'nope'; +assert.deepStrictEqual(fs_.filterBody(f).variants, {}); +f.variants.ads = 'pro'; +// profile preview: nothing changes until it is applied +fs_.previewProfile('students'); +const diff = f.preview.diff; +assert.deepStrictEqual(diff.on, ['Pornografie', 'Suchmaschinen ohne SafeSearch']); +assert.deepStrictEqual(diff.off.sort(), ['Soziale Netzwerke', 'Werbung und Tracking']); +assert.deepStrictEqual(diff.schedules, ['Soziale Netzwerke']); +assert.ok(diff.safesearch.some((x) => x.key === 'youtube' && x.to === 'strict')); +assert.strictEqual(f.checked.social, true); +fs_.cancelPreview(); +assert.strictEqual(f.preview, null); +fs_.previewProfile('students'); +fs_.applyPreview(); assert.deepStrictEqual(fs_.filterBody(f).categories, ['porn', 'nosafesearch']); -assert.strictEqual(fs_.filterBody(f).safesearch.youtube, 'strict'); +assert.deepStrictEqual(fs_.filterBody(f).schedules, {}); +assert.strictEqual(f.dirty, true); // SafeSearch switched on without the category: the category is pre-selected and said so f.checked.nosafesearch = false; f.safesearch.bing = true; @@ -314,25 +368,24 @@ assert.ok(hf.notes.some((n) => n[0] === 'warn' && /SafeSearch/.test(n[1]))); f.checked.social = true; fs_.addWindow('social'); f.schedules.social[0].days = {fr: true, mo: true}; -const body = fs_.filterBody(f); -assert.deepStrictEqual(body.categories, ['porn', 'nosafesearch', 'social']); -assert.deepStrictEqual(body.schedules, {social: [{days: ['mo', 'fr'], start: '07:45', end: '13:15'}]}); -f.checked.social = false; -assert.deepStrictEqual(fs_.filterBody(f).schedules, {}); -// save: stored but the image has no filter -> a warning, not a success +assert.deepStrictEqual(fs_.filterBody(f).schedules, {social: [{days: ['mo', 'fr'], start: '07:45', end: '13:15'}]}); +// save: stored but the image has no filter, and lists still to download: warnings fs_.saveFilter(); assert.ok(hf.notes.some((n) => n[0] === 'warn' && /Update image/.test(n[1]))); -// exam: the school server template uses the realm, the exam body carries minutes + domains -fs_.examServerTemplate(); -assert.strictEqual(fs_.detail.filter.exam.allowedText, 'dev.lmschule.de'); -fs_.detail.filter.exam.minutes = '30'; -fs_.examStart(); -const examIdx = hf.calls.indexOf('POST /api/lmn/squid/b/instances/one-students/exam'); -assert.deepStrictEqual(hf.bodies[examIdx], {minutes: 30, allowed: ['dev.lmschule.de']}); -assert.strictEqual(fs_.detail.filter.view.exam.active, true); -// bulk: every instance with the role, one result per instance +assert.ok(hf.notes.some((n) => n[0] === 'warn' && /hagezi-pro/.test(n[1]))); +// bulk: summary by group, changes per instance, filter and role selection +fs_.servers.a.instances[1].state.filter = {configured: true, active: ['porn', 'social'], variants: {}, scheduled: []}; fs_.openBulk(); assert.strictEqual(fs_.bulkSelected(), 1); +assert.ok(fs_.bulk.summary.length >= 1); +const teachersRow = fs_.bulk.rows.find((r) => r.inst.name === 'one-teachers'); +// after the save the form shows the stored answer (social only): porn would go +assert.deepStrictEqual(teachersRow.diff, {on: 0, off: 1, now: 2}); +fs_.bulk.query = 'server b'; +assert.ok(fs_.bulk.rows.every((r) => fs_.bulkRowVisible(r) === (r.conn.name === 'b'))); +fs_.bulkSelectVisible(true); +assert.strictEqual(fs_.bulkSelected(), 2); +fs_.bulk.query = ''; fs_.bulk.role = 'teachers'; fs_.bulkSelectRole(); assert.deepStrictEqual(fs_.bulk.rows.filter((r) => r.selected).map((r) => r.inst.name).sort(), ['beta-teachers', 'default-school-teachers', 'one-teachers']); @@ -342,11 +395,42 @@ assert.strictEqual(hf.bodies[bulkIdx].targets.length, 3); assert.ok(hf.notes.some((n) => n[0] === 'warn' && /Not applied everywhere/.test(n[1]))); assert.strictEqual(fs_.bulkResultText({ok: true, applied: true}), 'active'); fs_.closeBulk(); assert.strictEqual(fs_.bulk, null); -// overview: rows sorted by school, closes through its function +// overview: rows sorted by school; active categories by group with variant/schedule marks fs_.openFilterOverview(); assert.strictEqual(fs_.filterOverview.rows[0].inst.school, 'default-school'); +const og = fs_.overviewGroups(fs_.connections[0], {active: ['porn', 'ads'], variants: {ads: 'pro'}, scheduled: ['ads']}); +assert.deepStrictEqual(og.map((g) => [g.group.id, g.items.length, g.total]), [['youth', 1, 1], ['ads', 1, 1]]); +assert.deepStrictEqual(og[1].items[0], {label: 'Werbung und Tracking', variant: 'Pro', scheduled: true}); fs_.closeFilterOverview(); assert.strictEqual(fs_.filterOverview, null); assert.strictEqual(fs_.filterText({state: {filter: {configured: false}}}), 'not set up'); assert.strictEqual(fs_.filterText({state: {filter: {configured: true, categories: 4}}}), '4 categories'); +// own lists of a server +fs_.openOwn(fs_.connections[1]); +assert.strictEqual(fs_.own.data.categories[0].id, 'own_x'); +fs_.own.newCat = {id: 'own_y', label: 'Y', description: ''}; +fs_.addOwn('categories'); +assert.deepStrictEqual(hf.bodies[hf.calls.indexOf('POST /api/lmn/squid/b/catalog/custom/categories')], {id: 'own_y', label: 'Y', description: ''}); +fs_.own.newSrc.url = 'http://x'; +fs_.addOwn('sources'); +assert.ok(fs_.own.errors.url && fs_.own.error); +fs_.editOwnDomains({id: 'own_x', label: 'Eigene'}); +assert.strictEqual(fs_.own.edit.text, 'a.example'); +fs_.own.edit.text = 'a.example\nb.example, '; +fs_.saveOwnDomains(); +assert.deepStrictEqual(hf.bodies[hf.calls.indexOf('PUT /api/lmn/squid/b/catalog/custom/categories/own_x/domains')], {domains: ['a.example', 'b.example']}); +assert.strictEqual(fs_.own.edit, null); +fs_.closeOwn(); assert.strictEqual(fs_.own, null); +// server times in the server's zone, named; schedules show their zone +assert.strictEqual(fs_.timeText(1795525200, 'Europe/Berlin'), '24.11.2026, 14:00 (Europe/Berlin)'); +assert.strictEqual(fs_.timeText(1795525200, 'UTC'), '24.11.2026, 13:00 (UTC)'); +fs_.openDetail(fs_.connections[1], studentsRow, 'filter'); +assert.strictEqual(fs_.scheduleZone(), 'Europe/Berlin'); +fs_.detail.filter.view.timezone = 'Etc/UTC'; +assert.strictEqual(fs_.scheduleZone(), 'Etc/UTC'); +// details on demand, all groups folded at once +fs_.toggleInfo(fs_.detail.filter.catalog.byId.ads); +assert.strictEqual(fs_.detail.filter.ui.info.ads, true); +fs_.setAllOpen(false); +assert.ok(Object.keys(fs_.detail.filter.ui.open).every((k) => !fs_.detail.filter.ui.open[k])); console.log('controller checks: ok'); diff --git a/webui/tests/test_control_plane.py b/webui/tests/test_control_plane.py index 874fb0a..f7f9c72 100644 --- a/webui/tests/test_control_plane.py +++ b/webui/tests/test_control_plane.py @@ -175,7 +175,7 @@ def test_unknown_instance_is_404(webui: WebUI, cp: dict[str, Any]) -> None: def test_filter_through_the_plugin(webui: WebUI, cp: dict[str, Any]) -> None: - """Category filter (ADR-022): catalog, settings, exam mode, lookup, stats, bulk.""" + """Category filter (ADR-022): catalog, settings, variants, own lists, lookup, stats, bulk.""" add(webui, "a", cp["url"], cp["fingerprint"]) base = "/api/lmn/squid/a/instances" for role in ("students", "teachers"): @@ -193,13 +193,37 @@ def test_filter_through_the_plugin(webui: WebUI, cp: dict[str, Any]) -> None: assert body["settings"]["categories"] == ["porn"] status, body = webui.call("PUT", flt, {"categories": ["nope"]}) assert status == 422 - # exam mode - exam = f"{base}/default-school-students/exam" - status, body = webui.call("POST", exam, {"minutes": 30, "allowed": ["moodle.example"]}) - assert status == 200 and body["exam"]["active"], body - assert webui.call("POST", exam, {"minutes": 30, "allowed": "x"})[0] == 422 - status, body = webui.call("DELETE", exam) - assert status == 200 and body["exam"] is None + # variants pass through; an unknown one is the API's 422 + status, body = webui.call( + "PUT", flt, {"categories": ["porn", "ads"], "variants": {"ads": "pro"}} + ) + assert status == 200 and body["settings"]["variants"] == {"ads": "pro"}, body + assert webui.call("PUT", flt, {"categories": ["ads"], "variants": {"ads": "x"}})[0] == 422 + # own categories and sources through the plugin + own = "/api/lmn/squid/a/catalog/custom" + status, body = webui.call("POST", f"{own}/categories", {"id": "own_x", "label": "Eigene"}) + assert status == 200, body + status, body = webui.call("PUT", f"{own}/categories/own_x/domains", {"domains": ["a.example"]}) + assert (status, body["domains"]) == (200, ["a.example"]) + assert webui.call("GET", f"{own}/categories/own_x/domains")[1]["domains"] == ["a.example"] + status, body = webui.call( + "POST", + f"{own}/sources", + { + "id": "own-l", + "name": "L", + "url": "http://plain.example/l", + "category": "own_x", + "license": "CC0", + "junk": 1, + }, + ) + assert status == 422 + seen = len(cp["recorder"].seen) + assert webui.call("DELETE", f"{own}/categories/../x")[0] in (404, 422) + assert webui.call("DELETE", f"{own}/categories/evil")[0] == 422 + assert len(cp["recorder"].seen) == seen + assert webui.call("DELETE", f"{own}/categories/own_x")[0] == 200 # lookup and statistics status, body = webui.call("GET", f"{flt}/lookup", query={"domain": "example.org"}) # porn is active and there is no catalog yet: fail-closed, and the lookup says so @@ -234,3 +258,24 @@ def test_filter_through_the_plugin(webui: WebUI, cp: dict[str, Any]) -> None: webui.call("POST", "/api/lmn/squid/filter/bulk", {"targets": targets, "settings": "x"})[0] == 422 ) + + +def test_an_old_control_plane_is_named_too_old(webui: WebUI, cp: dict[str, Any]) -> None: + """An endpoint the control plane lacks (FastAPI's bare 404) is "zu alt", not "Not Found"; + an unknown instance on a current one stays a 404 with its own sentence.""" + from lmn_squid.client import ControlPlaneClient, ControlPlaneError + + add(webui, "a", cp["url"], cp["fingerprint"]) + conn = webui.handler.store.get("a") + try: + ControlPlaneClient(conn).request("GET", "/v1/no-such-endpoint") + except ControlPlaneError as exc: + assert exc.kind == "too_old" and "zu alt" in exc.message and exc.http_status() == 409 + else: + raise AssertionError("no error") + status, body = webui.call( + "POST", + "/api/lmn/squid/filter/bulk", + {"targets": [{"conn": "a", "name": "nope-students"}], "settings": {"categories": []}}, + ) + assert body["results"][0]["error"] == "http" and body["results"][0]["status"] == 404 diff --git a/webui/tests/test_permissions.py b/webui/tests/test_permissions.py index c1fd3ad..cfc4ff9 100644 --- a/webui/tests/test_permissions.py +++ b/webui/tests/test_permissions.py @@ -78,8 +78,11 @@ def test_every_endpoint_is_authorized_and_global_admin_only() -> None: ("POST", "/api/lmn/squid/a/catalog/update", None), ("GET", "/api/lmn/squid/a/instances/s-teachers/filter", None), ("PUT", "/api/lmn/squid/a/instances/s-teachers/filter", {"categories": []}), - ("POST", "/api/lmn/squid/a/instances/s-teachers/exam", {"minutes": 5}), - ("DELETE", "/api/lmn/squid/a/instances/s-teachers/exam", None), + ("GET", "/api/lmn/squid/a/catalog/custom", None), + ("POST", "/api/lmn/squid/a/catalog/custom/categories", {"id": "own_x"}), + ("DELETE", "/api/lmn/squid/a/catalog/custom/sources/own-x", None), + ("GET", "/api/lmn/squid/a/catalog/custom/categories/own_x/domains", None), + ("PUT", "/api/lmn/squid/a/catalog/custom/categories/own_x/domains", {"domains": []}), ("GET", "/api/lmn/squid/a/instances/s-teachers/filter/lookup", None), ("GET", "/api/lmn/squid/a/instances/s-teachers/filter/stats", None), ("GET", "/api/lmn/squid/a/instances/s-teachers/allowlist", None), diff --git a/webui/tests/test_setup.py b/webui/tests/test_setup.py index 15d9972..bfe5969 100644 --- a/webui/tests/test_setup.py +++ b/webui/tests/test_setup.py @@ -610,6 +610,13 @@ def test_time_summary_is_readable() -> None: assert "server=" in sshsetup.time_script( "10.250.0.10" ) and "date +%s" not in sshsetup.time_script("x") + # the school server's zone is set on the VM (filter schedules are local time), idempotent + script = sshsetup.time_script("10.250.0.10", "Europe/Berlin") + assert "timedatectl set-timezone Europe/Berlin" in script and "!= Europe/Berlin" in script + assert "set-timezone" not in sshsetup.time_script("10.250.0.10", "Europe/Berlin; reboot") + assert "set-timezone" not in sshsetup.time_script("10.250.0.10", "") + status, text = sshsetup.time_summary("server=x\nsynced=yes\ntimezone=Europe/Berlin\n") + assert text.endswith("Zeitzone Europe/Berlin") def test_preflight_findings() -> None: From 5574e042f5dbb81d01825234ba0b7dc8fc1f4fca Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 17:06:00 +0100 Subject: [PATCH 12/19] test(e2e): list variants and own categories instead of the exam mode squid-filter's catalog now holds two ads variants under the real source ids and an own category: light -> pro switched by reconfigure, an own list changed without one. 81 passed, 0 failed locally. --- scripts/tests/e2e_kerberos.sh | 32 ++++++++++++++++++----------- scripts/tests/make_test_catalog.py | 33 +++++++++++++++++++++--------- 2 files changed, 43 insertions(+), 22 deletions(-) diff --git a/scripts/tests/e2e_kerberos.sh b/scripts/tests/e2e_kerberos.sh index cf8dd31..3265593 100755 --- a/scripts/tests/e2e_kerberos.sh +++ b/scripts/tests/e2e_kerberos.sh @@ -40,7 +40,7 @@ printf '.www.secure.example.internal\n' > "$FILTER_DIR/lists/allowed.domains" printf '.secure2.example.internal\n.a.secure.example.internal\n' > "$FILTER_DIR/lists/noauth.domains" : > "$FILTER_DIR/lists/blocked.domains" chmod 644 "$FILTER_DIR/lists/"*.domains -filter_json '"categories": ["porn", "ai"], "fail_closed": ["porn"]' +filter_json '"categories": ["porn", "ai", "ads", "own_e2e"], "fail_closed": ["porn"]' # 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 @@ -113,6 +113,9 @@ dcx samba-tool dns add 127.0.0.1 "$DLC" secure2 A 10.228.0.21 -U "Administrato dcx samba-tool spn add "HTTP/squid7.$DLC" squidsvc >/dev/null 2>&1 || true dcx samba-tool dns add 127.0.0.1 "$DLC" squid7 A 10.228.0.16 -U "Administrator%$PW" >/dev/null 2>&1 || true dcx samba-tool dns add 127.0.0.1 "$DLC" chat A 10.228.0.20 -U "Administrator%$PW" >/dev/null 2>&1 || true +for n in light pro fresh; do + dcx samba-tool dns add 127.0.0.1 "$DLC" "$n" A 10.228.0.20 -U "Administrator%$PW" >/dev/null 2>&1 || true +done # Kerberos clock skew (ADR-017): squid6 = squid-skew (KRB5_CLOCKSKEW_SECONDS=5400). dcx samba-tool spn add "HTTP/squid6.$DLC" squidsvc >/dev/null 2>&1 || true @@ -234,7 +237,8 @@ for bad in 299 7201 abc; do fi done -# Category filter (ADR-022), the parts the test client cannot do: exam mode with its end, the +# Category filter (ADR-022), the parts the test client cannot do: switching the variant, a change +# of an own category's list without a reconfigure, the # block page text, fail-closed without catalog, the anonymous statistics. fcode(){ # [curl options...]: status code through squid-filter local user="$1" url="$2"; shift 2 @@ -257,17 +261,21 @@ if printf '%s' "$page" | grep -q 'Grund: Pornografie'; then else echo " [FAIL] block page without the reason: $(printf '%s' "$page" | head -c 300)"; rc=$((rc + 1)) fi -log "filter: exam mode (only secure2), applied by reconfigure, ends by itself" -filter_json "\"categories\": [\"porn\"], \"fail_closed\": [\"porn\"], \"exam\": {\"until\": $(( $(date +%s) + 20 )), \"allowed\": [\"secure2.example.internal\"]}" +log "filter: variant of a category (ads light -> pro), applied by reconfigure" +expect "ads light (default variant): light -> 403" 403 "$(fcode teacher1 http://light.example.internal/)" +expect "ads light (default variant): pro -> 200" 200 "$(fcode teacher1 http://pro.example.internal/)" +filter_json '"categories": ["porn", "ai", "ads", "own_e2e"], "variants": {"ads": "pro"}, "fail_closed": ["porn"]' fsquid squid -k reconfigure -f /run/lmnsquid/squid.conf >/dev/null 2>&1 sleep 3 -expect "exam: exception www.secure (teacher) -> 403" 403 "$(fcode teacher1 http://www.secure.example.internal/)" -expect "exam: listed secure2 (teacher) -> 200" 200 "$(fcode teacher1 http://secure2.example.internal/)" -expect "exam: listed + noauth secure2, no ticket -> 200" 200 "$(fcode "" http://secure2.example.internal/)" -expect "exam: not listed, no ticket -> 407" 407 "$(fcode "" http://chat.example.internal/)" -echo " (waiting 90 s: exam end 20 s + squid's answer cache 60 s, no reconfigure)" -sleep 90 -expect "exam over by itself: exception www.secure (teacher) -> 200" 200 "$(fcode teacher1 http://www.secure.example.internal/)" +expect "ads pro: pro -> 403" 403 "$(fcode teacher1 http://pro.example.internal/)" +expect "ads pro: light -> 200" 200 "$(fcode teacher1 http://light.example.internal/)" +log "filter: own category list changed without reconfigure" +expect "own category: own -> 403" 403 "$(fcode teacher1 http://own.example.internal/)" +printf 'own.example.internal\nfresh.example.internal\n' > "$FILTER_DIR/catalog/custom/.n.tmp" +chmod 644 "$FILTER_DIR/catalog/custom/.n.tmp" +mv -f "$FILTER_DIR/catalog/custom/.n.tmp" "$FILTER_DIR/catalog/custom/own_e2e.domains" +sleep 7 +expect "own category, new entry, no reconfigure: fresh -> 403" 403 "$(fcode teacher1 http://fresh.example.internal/)" log "filter: fail-closed while the catalog is missing" mv "$FILTER_DIR/catalog/current.sqlite" "$FILTER_DIR/catalog/current.off" sleep 7 @@ -282,7 +290,7 @@ sleep 3 expect "catalog back: secure2 (teacher) -> 200" 200 "$(fcode teacher1 http://secure2.example.internal/)" log "filter: statistics hold day and category only" stats=$(fsquid sh -c 'cat /var/log/squid/filter.log' 2>/dev/null) -if printf '%s\n' "$stats" | grep -Eq '^[0-9]{4}-[0-9]{2}-[0-9]{2} (porn|ai|exam|catalog_unavailable)$' \ +if printf '%s\n' "$stats" | grep -Eq '^[0-9]{4}-[0-9]{2}-[0-9]{2} (porn|ai|ads|own_e2e|catalog_unavailable)$' \ && ! printf '%s' "$stats" | grep -Eq 'teacher1|10\.228\.'; then echo " [PASS] filter.log: $(printf '%s\n' "$stats" | awk '{print $2}' | sort | uniq -c | tr -s ' \n' ' ')" else diff --git a/scripts/tests/make_test_catalog.py b/scripts/tests/make_test_catalog.py index 1d0b78a..5a06b94 100644 --- a/scripts/tests/make_test_catalog.py +++ b/scripts/tests/make_test_catalog.py @@ -2,8 +2,10 @@ # SPDX-License-Identifier: GPL-3.0-or-later """Build a small real category catalog for the E2E (ADR-022): usage make_test_catalog.py . -The same builder as production (lmnsquid.catalog), local sources only: -porn = origin, secure (and their subdomains); ai = chat.example.internal. +The same builder as production (lmnsquid.catalog), local files only. porn = origin, secure (and +their subdomains); ai = chat; ads in two variants under the real source ids: light (default, +`light.example.internal`) and pro (`pro.example.internal`); an own category `own_e2e` with +`own.example.internal` as the admin would make it. """ from __future__ import annotations @@ -14,10 +16,13 @@ from lmnsquid import catalog -ENTRIES = { - "porn": ["origin.example.internal", "secure.example.internal"], - "ai": ["chat.example.internal"], -} +# (source id, category, names) +ENTRIES = [ + ("e2e-porn", "porn", ["origin.example.internal", "secure.example.internal"]), + ("e2e-ai", "ai", ["chat.example.internal"]), + ("hagezi-light", "ads", ["light.example.internal"]), + ("hagezi-pro", "ads", ["pro.example.internal"]), +] def main() -> None: @@ -26,12 +31,12 @@ def main() -> None: config = catalog.load_config() with tempfile.TemporaryDirectory() as work: inputs = [] - for cat_id, names in ENTRIES.items(): - path = Path(work) / f"{cat_id}.domains" + for src_id, cat_id, names in ENTRIES: + path = Path(work) / f"{src_id}.domains" path.write_text("".join(f"{n}\n" for n in names), encoding="utf-8") src = { - "id": f"e2e-{cat_id}", - "name": f"E2E {cat_id}", + "id": src_id, + "name": f"E2E {src_id}", "license": "CC0", "path": str(path), "format": "domains", @@ -42,6 +47,14 @@ def main() -> None: catalog.build_file(config, inputs, built, Path(work)) catalog.publish(target_dir, built) catalog.write_protected(target_dir, None) + custom = target_dir / catalog.CUSTOM_DIR + custom.mkdir(exist_ok=True) + (custom / "own_e2e.domains").write_text("own.example.internal\n", encoding="utf-8") + (custom / "categories.json").write_text( + '{"own_e2e": "Eigene Liste"}', encoding="utf-8" + ) + for path in [custom, *custom.iterdir()]: + path.chmod(0o755 if path.is_dir() else 0o644) target_dir.chmod(0o755) From 8d5d067253f7d0d42c5e83f569521c4d50d0a79e Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Tue, 24 Nov 2026 17:06:00 +0100 Subject: [PATCH 13/19] docs: ADR-022 revised (exam mode removed, variants, sources, own lists, time zone), operations, changelog Lab findings of 2026-11-24 addressed: schedule time zone, raw 404 of old control planes, umlauts on the block page, nightly rebuild of unchanged lists, raw CLI errors, noisy category selection. --- README.md | 9 ++- debian/changelog | 66 ++++++++++------- docs/architecture.md | 6 +- docs/decisions.md | 165 ++++++++++++++++++++++++++---------------- docs/install.md | 7 +- docs/operations.md | 131 +++++++++++++++++++-------------- docs/test-strategy.md | 51 +++++++------ docs/threat-model.md | 4 +- 8 files changed, 260 insertions(+), 179 deletions(-) diff --git a/README.md b/README.md index d8b3ebb..46e4134 100644 --- a/README.md +++ b/README.md @@ -44,10 +44,11 @@ the same AD/Kerberos infrastructure the school already operates. Optional per-instance list of domains reachable without proxy login from the school subnets (e.g. Microsoft 365; the blocklist still wins). **Category filter** per instance (ADR-022): youth protection, security, VPN/proxy/DoH bypass, - ads, telemetry, distraction, AI services… from UT1 (CC BY-SA 4.0) and HaGeZi (GPL-3.0) lists - in one host-wide SQLite catalog (millions of entries without slowing squid down), schedules, - SafeSearch (Google, YouTube, Bing, DuckDuckGo) without decryption, exceptions, an exam mode, - "why is X blocked?" and anonymous statistics. + ads, telemetry, distraction, AI services, expert categories… from free lists (UT1 CC BY-SA 4.0, + HaGeZi GPL-3.0, ShadowWhisperer, StevenBlack, Sinfonietta and others) in one host-wide SQLite + catalog (millions of entries without slowing squid down), lists and strictness per category, + own lists, templates, schedules, SafeSearch (Google, YouTube, Bing, DuckDuckGo) without + decryption, exceptions, "why is X blocked?" and anonymous statistics. - **Control Plane:** hardened systemd service with **REST API** (FastAPI) and **CLI** (Typer, thin client) — creates instances, configures policies, and **updates digest-pinned with health-check auto-rollback**. Shipped as a diff --git a/debian/changelog b/debian/changelog index c722e95..1706dee 100644 --- a/debian/changelog +++ b/debian/changelog @@ -96,39 +96,49 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium taken) no longer stops the service; the loopback API keeps running and "lmnsquid health" shows "tls": "failed: ". PUT /v1/secrets enforces its 64 KiB limit while reading the body. - * Category filter per instance (ADR-022, docs/operations.md): youth - protection, malware/phishing, VPN/proxy/DoH bypass, search engines - without SafeSearch, ads, telemetry per vendor, social networks, games, - chat, streaming, warez, AI services, cheating; from UT1 (CC BY-SA 4.0) - and HaGeZi (GPL-3.0) lists that the proxy host downloads into one - catalog (5.6 million domains, ~200 MB, built in about 80 s with under - 120 MB of memory; nightly timer linuxmuster-squid-catalog.timer, only - while an instance uses categories; "lmnsquid catalog update"). squid - no longer parses large lists: a helper looks names up, lists and - categories change without a restart. Profiles "students"/"teachers", - schedules per category, a protected list (Windows Update, Microsoft - 365, Google Workspace, ... never blocked by a category), exceptions - ("lmnsquid allowlist"), "why is X blocked?" and anonymous statistics - (day and category only, filter.log). Youth protection fails closed: - without a usable catalog such instances refuse requests; build the - catalog first. HTTP gets a German block page naming the reason; HTTPS - still shows a certificate warning. Nothing changes for an instance - until you set its filter ("lmnsquid filter ...", API - /v1/instances//filter). + * Category filter per instance (ADR-022, docs/operations.md): 48 + categories in groups (youth protection, security and scam, bypass, + ads, telemetry per vendor, distraction, downloads/AI/cheating, expert + categories, own categories), each with a description, examples and a + choice of lists and strictness where several exist (e.g. ads: HaGeZi + Light (recommended), Normal, Pro, Pro++), the recommended one marked + and strict ones with a warning. Lists from UT1 (CC BY-SA 4.0), HaGeZi + (GPL-3.0), ShadowWhisperer (Unlicense), StevenBlack extensions, + Sinfonietta, durablenapkin, NoCoin (MIT), dibdot (GPL-3.0) and + PeterDaveHello (CC BY-SA 4.0), downloaded by the proxy host into one + catalog: the recommended lists always, others once an instance uses + them (5.6 to 7.8 million domains, 240 to 330 MB, built in 1.5 to 2.5 + minutes with under 120 MB of memory; nightly timer + linuxmuster-squid-catalog.timer, only while an instance uses + categories; "lmnsquid catalog update"). squid no longer parses large + lists: a helper looks names up, lists and categories change without a + restart. Templates (students, primary school, teachers, staff, guest + WLAN) with a preview of the changes, schedules per category, a + protected list (Windows Update, Microsoft 365, Google Workspace, ... + never blocked by a category), exceptions ("lmnsquid allowlist"), + "why is X blocked?" and anonymous statistics (day and category only, + filter.log). Youth protection fails closed: without a usable catalog + such instances refuse requests; build the catalog first. HTTP gets a + German block page naming the reason; HTTPS still shows a certificate + warning. Nothing changes for an instance until you set its filter + ("lmnsquid filter ...", API /v1/instances//filter). + * Own lists: own sources (https URL, checked like the packaged ones) and + own categories with a hand-entered domain list that applies within + seconds ("lmnsquid catalog own ...", API /v1/catalog/custom). * SafeSearch per instance without decrypting: Google search (all country domains), YouTube restricted mode (strict/moderate), Bing, DuckDuckGo. - * Exam mode per instance ("lmnsquid filter exam-start --minutes - N --allow "): only the listed domains, also for domains without - proxy login, ends by itself. * Containers get the catalog directory as a read-only mount: the update-all of the package upgrade that brings the data-plane image with the filter replaces every container once (health-gated, as always). - Until that image is pinned, filter settings are stored without effect - and exam mode is refused. - * WebUI plugin: tab "Filter" per instance (categories, schedules, - profiles, SafeSearch, exam mode, catalog state with "update now", "why - is X blocked?", statistics), tab "Exceptions", "apply to other - instances" across proxy servers and an overview "Filter per school". + Until that image is pinned, filter settings are stored without effect. + * WebUI plugin: tab "Filter" per instance (groups to fold with "all + on/off" and counters, search, state on/off/time-controlled, lists per + category with licence, entries and date, templates with preview, + schedules, SafeSearch, catalog state with "update now", "why is X + blocked?", statistics), tab "Exceptions", "Own lists" per proxy + server, "apply to other instances" across proxy servers with the + changes per instance, and an overview "Filter per school" showing the + active categories of every instance. -- 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 4ea5c0d..1f10a21 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -105,8 +105,8 @@ Status document. Keep it up to date with every substantive change (see - **Category filter (ADR-022):** an `external_acl_type` helper (`lmn-filter-acl`, Python, `concurrency`, ttl 60 s) per instance decides from the instance's `filter.json` / `allowed.domains` (list directory) and the host-wide catalog mounted read-only at - `/etc/squid/catalog` (one SQLite file, page cache shared by all instances): exam mode → - exceptions → protected list → categories with schedules; fail-closed for youth protection. + `/etc/squid/catalog` (one SQLite file, page cache shared by all instances) and the admin's own lists next to it: + 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). @@ -128,7 +128,7 @@ Status document. Keep it up to date with every substantive change (see `GET /v1/schema` (JSON schema of the instance model with its defaults). - **Category catalog and filter (ADR-022):** `lmnsquid-catalog update` (nightly timer as `lmnsquid`, or `POST /v1/catalog/update`) downloads UT1/HaGeZi lists and builds the catalog - streaming (sort on disk), checked and switched atomically; `GET|PUT …/filter`, `…/exam`, + 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. - **Reconciler:** declarative, git-versioned state (`instances/*.yaml`) → diff --git a/docs/decisions.md b/docs/decisions.md index 0cc9fb8..1e6b5d0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -261,9 +261,9 @@ connections and asks to exempt its required endpoints; a client-side bypass (pro + firewall rules) was not wanted, the traffic should still pass the proxy's domain filter. **Price (threat model T16):** a listed domain is reachable by everyone in the school subnets without identity: exam accounts reach it in exam mode, the Internetsperre does not apply to it, -and the access log shows `-` instead of a user for it. **Amendment (2026-11-24, ADR-022):** the category filter and the exam mode apply to listed -domains too (`deny noauth_domains filter_blocked` before the allow line): in exam mode a noauth -domain is reachable only when it is on the exam's list. +and the access log shows `-` instead of a user for it. **Amendment (2026-11-24, ADR-022):** the category filter applies to listed domains too +(`deny noauth_domains filter_blocked` before the allow line): a noauth domain in an active +category is refused like any other request. **Rollout:** the template is in the data-plane image; `DEFAULT_IMAGE` must point at an image built with it before the release that ships the control plane is tagged (RELEASE.md). Until then the list is @@ -486,84 +486,127 @@ memory; Ansible would need ansible-core and sshpass on the DC and the password i the environment. **Price:** threat model T19 (password over the network, TOFU) and T20. ### ADR-022 — Category filter: host-wide SQLite catalog, external ACL helper, settings per instance -**Status:** Proposed (2026-11-24, Kevin: "bau das ein"; task `work/tasks/squid-filterkategorien.md`, -research `work/linuxmuster-squid/recherche-filterlisten.md`). **Decision:** category lists are not -squid lists any more. `lmnsquid-catalog update` (nightly systemd timer as `lmnsquid`, or `POST -/v1/catalog/update`) downloads the sources of the packaged `sources.yml` (UT1 CC BY-SA 4.0 as the -backbone, HaGeZi GPL-3.0 for ads, security, bypass, telemetry and "no SafeSearch"; extendable in -`/etc/linuxmuster-squid/catalog.yml`; the package ships no list content) with conditional GETs and -builds **one SQLite file** per proxy host, `/var/lib/linuxmuster-squid/catalog/current.sqlite` -(symlink, switched atomically; one previous version kept): domain → bit mask of school categories -and of sources. The build streams (parse to a file, GNU `sort` on disk, merge, insert in order): -measured 5.6 million domains, 195 MiB, 70–80 s, 44 MiB RSS plus 64 MiB for `sort`, and it completes -under a 160 MiB memory limit. The directory is mounted read-only into every container at -`/etc/squid/catalog`; per instance an `external_acl_type` helper (`lmn-filter-acl`, Python stdlib, -`concurrency=100`, `ttl=60`, children 1–4 for `%DST` and 1–2 for `%ssl::>sni`) decides with -`filterdecision.py` (byte-identical in the control plane and the image, a test enforces it) from -the instance's `filter.json`, `allowed.domains` and the catalog. Order: **exam mode** (only its -own list) → **exceptions** (`allowed.domains`) → **protected list** → **categories** (with -schedules). Settings per instance in the instance's list directory (ADR-014, so no mount of its -own): `filter.json` (categories, schedules, SafeSearch, exam; written by the control plane only), +**Status:** Proposed (2026-11-24, Kevin: "bau das ein"; revised the same day: "remove the exam mode +again, but extend and improve the selection of the lists and add more lists"; task +`work/tasks/squid-filterkategorien.md`, research `work/linuxmuster-squid/recherche-filterlisten.md` +incl. section 7). **Decision:** category lists are not squid lists any more. +`lmnsquid-catalog update` (nightly systemd timer as `lmnsquid`, or `POST /v1/catalog/update`) +downloads the sources of the packaged `sources.yml` with conditional GETs and builds **one SQLite +file** per proxy host, `/var/lib/linuxmuster-squid/catalog/current.sqlite` (symlink, switched +atomically; one previous version kept): domain → bit mask of **feeds**, one feed = one source for +one category (catalog format 2). Each category has **variants** (which sources, how strict), one +of them the recommended default; the catalog carries them (`vars`), so the helper needs nothing +else. A source no variant names (an admin's own) counts in every variant. +**Sources** (licences read at the primary source, research §1 and §7): UT1 (CC BY-SA 4.0, one +archive for all its categories), HaGeZi (GPL-3.0: NSFW, Gambling medium/full, TIF mini/medium/full, +Fake, Bypass, DoH, Safesearch-not-supported, Multi Light/Normal/Pro/Pro++, native trackers of ten +vendors, Social, Anti-Piracy, Pop-up Ads, DynDNS, Most Abused TLDs, URL Shortener), ShadowWhisperer +(Unlicense), StevenBlack's extension-only files gambling/social/fakenews (MIT, all their +sources MIT), Sinfonietta (MIT), durablenapkin scam list (MIT), dibdot DoH (GPL-3.0), +PeterDaveHello url-shorteners (CC BY-SA 4.0), NoCoin (MIT), and a small package list of AI host +names. Not used, with the reasons in the research: OISD, URLhaus, Phishing Army, Block List +Project, StevenBlack porn and base, 1Hosts, AdGuard DNS filter, AdAway, Phishing.Database, +WindowsSpyBlocker, KADhosts, GoodbyeAds, Clefspeare13. +**What is downloaded:** the default variant of every category outside the expert group, every +source an instance on the host uses (its variant, an expert category), every own source of the +admin, and UT1's archive (its 42 offered categories in one download). Other sources are not +downloaded; a setting that needs one starts a catalog update in the background (`PUT …/filter` +answers `missing_sources`, `catalog_update_started`). Measured (2026-11-24, image Python 3.12): +defaults 28 sources, 5.65 million domains, 58 feeds, 237 MiB, 96 s; defaults plus a broad expert +selection (every strict variant incl. TIF full and Pro++, abused TLDs, DynDNS, URL shorteners, +pop-ups, fake news, crypto, mixed adult) 48 sources, 7.84 million domains, 78 feeds, 327 MiB, +140 s; RSS 47–49 MiB plus 64–69 MiB for `sort` in both, and both complete under a 400 MiB memory +limit (the unit's `MemoryMax`). The build streams (parse to a file, GNU `sort` on disk, merge, +insert in order). +**Categories:** 48 in groups youth protection, security (malware/phishing, scam), bypass, ads, +telemetry per vendor, distraction, downloads/AI/cheating, **experts** (the remaining usable UT1 +categories and the stricter HaGeZi lists, each with a warning where false positives are likely) +and **own**. Not offered (named in the UI with the reason): UT1's "DO NOT USE" lists, its allow +lists, and categories whose block harms school use (bank, jobsearch, press, radio, translation, +webmail, remote-control, shortener, sexual_education, cleaning and webhosting — the last two list +apple.com, avast.com, airtable.com). Every category has a German description and example domains; +`GET /v1/catalog` reports per variant the sources with licence, entries and last download. +**Own lists:** an admin adds own sources (https URL, format domains/hosts/wildcard/adblock/rpz, +target category, licence note, `min_entries`, size limit up to 200 MB; validated, then built and +checked like the packaged ones) and own categories (`own_`) with a hand-entered domain list +(`/v1/catalog/custom…`, CLI `lmnsquid catalog own …`, WebUI "Eigene Listen"). The sources live in +`/etc/linuxmuster-squid/catalog-custom.yml`; the hand-entered lists in `custom/` next to the +catalog, where the helper reads them directly: effective within seconds, no build, no reload. +**Profiles:** students, primary school, teachers, staff, guest WLAN; never applied automatically; +the WebUI and `lmnsquid filter profile --dry-run` show the changes before applying. +**The helper** per instance (`lmn-filter-acl`, Python stdlib, `concurrency=100`, `ttl=60`, +children 1–4 for `%DST` and 1–2 for `%ssl::>sni`) decides with `filterdecision.py` +(byte-identical in the control plane and the image, a test enforces it) from the instance's +`filter.json`, `allowed.domains`, the catalog and the own lists. Order: **exceptions** +(`allowed.domains`) → **protected list** → **categories** (in the instance's order, with their +variant, schedules). Settings per instance in the instance's list directory (ADR-014, no mount of +its own): `filter.json` (categories, variants, schedules, SafeSearch; written by the control plane +only; keys of older builds such as `exam` are ignored and dropped at the next write), `allowed.domains`, `safesearch.hosts`. Changes are applied at once with `squid -k reconfigure`, -which (measured with squid 6.14) also empties squid's cache of helper answers; a new catalog -needs no reconfigure (the helper notices the new file within 5 s, squid's cache ttl is 60 s). -Without `filter.json` the helper blocks nothing: **an upgrade changes no behaviour**; instances -get no categories automatically, the WebUI says "Filter noch nicht eingerichtet" and proposes -the profile of the role (students / teachers, §2.1 of the research). +which (measured with squid 6.14) also empties squid's cache of helper answers; a new catalog or an +own list needs no reconfigure (the helper notices the file within 5 s, squid's cache ttl is 60 s). +Without `filter.json` the helper blocks nothing: **an upgrade changes no behaviour**. **squid.conf (image):** `deny filter_blocked` after `deny !authenticated` and the own blocklist (→ 403 with a German block page via `deny_info ERR_LMN_BLOCKED`, `%o` = the helper's message, -ASCII because squid escapes `%o` byte by byte); `deny noauth_domains filter_blocked` before the -noauth allow line, so categories and the exam mode apply to noauth domains too (ADR-016 amended); +written in ISO-8859-1 because squid writes every byte of `%o` as `&#NNN;`, so umlauts arrive +correctly, measured with squid 6.14; the first build sent ASCII and showed "verfuegbar"); `deny noauth_domains filter_blocked` before the +noauth allow line, so categories apply to noauth domains too (ADR-016 amended); `ssl_bump terminate filter_blocked_sni`; `hosts_file /run/lmnsquid/hosts` (= the container's `/etc/hosts` plus `safesearch.hosts`, built by `lists-sync.sh`); the own blocklist now reads `deny blocked_domains !allowed_domains` (an empty exception list = the old rule). -**Fail-closed:** while the catalog is missing or unusable and a category marked `fail_closed` -(the five youth protection categories) is active, every request except exceptions and the -protected list is refused (block page "Filterkatalog nicht verfügbar"); with only other -categories the filter opens. A hand-broken `filter.json` also refuses. The helper never answers -`BH` (squid would skip the deny line). A failed update keeps the active catalog: a download error -falls back to the previous download, a source below its `min_entries` or a category shrinking by -more than half stops the build; `status` reports the age, older than 7 days is a warning. +**Fail-closed:** while the catalog is missing or unusable (also an older format) and a category +marked `fail_closed` (the five youth protection categories) is active, every request except +exceptions and the protected list is refused (block page "Filterkatalog nicht +verfügbar"); with only other categories the filter opens. A hand-broken `filter.json` also +refuses. The helper never answers `BH` (squid would skip the deny line). A failed update keeps the +active catalog: a download error falls back to the previous download, a source below its +`min_entries` or a feed shrinking by more than half stops the build; `status` reports the age, +older than 7 days is a warning. **SafeSearch** through squid's `hosts_file`, no decryption: Google (187 country domains of `google.com/supported_domains`, pinned in the package, `www.`, bare and `images.`), YouTube restricted strict/moderate, Bing, DuckDuckGo. The control plane resolves the services' addresses at every change and every container creation; a failed lookup keeps the last known address (Google/YouTube: Google's documented address as the last resort). Measured: CONNECT `www.google.de` goes to `216.239.38.120` with a valid certificate; the certificates of -`strict.bing.com` (for `www.bing.com`, `bing.com`) and `safe.duckduckgo.com` (for -`duckduckgo.com`, `www.duckduckgo.com`) verify too, whether their content is then filtered is not -verified. Switching SafeSearch on pre-selects "search engines without SafeSearch". -**Exam mode** per instance (`POST/DELETE /v1/instances/{name}/exam`): only the listed domains -(template "school server only" = the realm's DNS domain) until `until`; refused (409, nothing -stored) unless the running image has the filter. **Statistics:** `filter.log` in the log volume -with only the day and the category of a filtered request (`logformat lmnfilter %{%Y-%m-%d}tl -%{category}note`), rotated with the access log's retention; summed by `GET …/filter/stats`. +`strict.bing.com` and `safe.duckduckgo.com` verify too, whether their content is then filtered is +not verified. Switching SafeSearch on pre-selects "search engines without SafeSearch". +**Time zone of the schedules** (lab 2026-11-24: a VM set up from a cloud image runs in UTC, the +windows were one or two hours off): `filter_timezone` in `config.yml`, default `Europe/Berlin`, +written into `filter.json` and evaluated by the helper with zoneinfo (daylight saving time +included, tested across the change of 2027-03-28); the WebUI shows it next to every time window +and the server's times in it; the WebUI setup also sets the VM's zone to the school server's +(`timedatectl set-timezone`, idempotent, in the time step). +**Statistics:** `filter.log` in the log volume with only the day and the category of a filtered +request (`logformat lmnfilter %{%Y-%m-%d}tl %{category}note`), rotated with the access log's +retention; summed by `GET …/filter/stats`. +**Removed again (Kevin, 2026-11-24):** the exam mode of the first version (only listed domains +until a time). Its endpoints, CLI commands and WebUI are gone; linuxmuster's own exam mode (exam +accounts in no role group, T12) is unaffected. **Deviations from the task, and why:** (1) the protected list protects against *categories* only, not against the instance's own blocklist: an explicit block by the admin is intent, and -otherwise an upgrade could unblock entries of existing lists (the task asked for no behaviour -change). (2) The end of an exam is evaluated by the helper itself (`until` in `filter.json`), no -systemd timer: it ends even when the control plane is down; squid's answer cache delays it by at -most 60 s; an expired exam is cleared on the next write. (3) Statistics in a separate file instead -of `%et` in `access.log`: the access log's format stays as it was (log parsers, `access-logs`), -and the statistics file carries no person at all, also with the access log switched off. -(4) Category ids follow §2.1; `mixed_adult` (platforms with mixed content, false positives) and -the expert categories (`jobsearch`, `webmail`, `remote-control`, `shortener`, …) are not offered; -ads come from HaGeZi Multi Light only. (5) The CLI help is English like every other command (the -task assumed German help). (6) The catalog is rebuilt every night even when every source answered -304 (76 s at low priority; skipping would make the age check meaningless). +otherwise an upgrade could unblock entries of existing lists. (2) Statistics in a separate file +instead of `%et` in `access.log`: the access log's format stays as it was, and the statistics +file carries no person at all, also with the access log switched off. (3) The CLI help is English +like every other command. (4) A nightly run in which every source answered 304 and the configuration and selection did not +change builds nothing (the catalog carries a fingerprint of its inputs; measured in the lab before +this: 80 s of work for an identical file); such a run counts as a confirmation for the age check. +(5) Expert +categories and strict variants are downloaded only when used (Kevin's suggestion), the defaults +always, so a newly enabled recommended category works at once. **Why:** squid's `dstdomain` builds a splay tree per list and instance at every start and reconfigure (2 million entries: 25 s + 2 × 55 s; UT1 `adult` alone has 4.6 million), the helper keeps one file in the page cache per host and lets lists and categories change without a restart; squidGuard/ufdbGuard/e2guardian are unmaintained, unpackaged or break the Kerberos chain (research -§4.1). **Price:** a Python helper per instance (measured 14–17 MiB RSS each, 13 000–14 000 -lookups/s per process against the full catalog, +1.7 ms for the first lookup of a name), the -catalog directory as a fifth mount (one replacement of every container, done by the `update-all` -of the release that pins the image), ~0.4 GB on disk (two catalog versions plus downloads), -python3 and tzdata in the image. HTTPS still shows no block page (ADR-002 unchanged). +§4.1). **Price:** a Python helper per instance (14–17 MiB RSS each, 11 000–14 000 lookups/s per +process against the full catalog, +1.7 ms for the first lookup of a name), the catalog directory +as a fifth mount (one replacement of every container, done by the `update-all` of the release that +pins the image), 0.5–0.7 GB on disk (two catalog versions plus downloads), python3 and tzdata in +the image. HTTPS still shows no block page (ADR-002 unchanged). **Rollout:** the helper, template and block page are in the data-plane image: until `DEFAULT_IMAGE` points at an image built with them, filter settings are stored but have no effect -(`PUT …/filter` answers `"applied": false, "reason": "image"`, the exam mode and the exception -reload answer 409), as for ADR-016. +(`PUT …/filter` answers `"applied": false, "reason": "image"`, the exception reload answers 409), +as for ADR-016. A catalog of the first test build (format 1) is reported as unusable until the +next `lmnsquid catalog update`. --- diff --git a/docs/install.md b/docs/install.md index 8f0c39d..bb326d1 100644 --- a/docs/install.md +++ b/docs/install.md @@ -221,10 +221,11 @@ traffic to allowed sites is never decrypted (it is spliced). Details, the file p UT-Capitole category lists: [`operations.md`](operations.md#blocklist-per-instance). -## 7a. Category filter, SafeSearch, exam mode (optional) +## 7a. Category filter and SafeSearch (optional) ```bash -lmnsquid catalog update --wait # first catalog (UT1 + HaGeZi, ~1-2 min, ~0.4 GB disk) +lmnsquid catalog update --wait # first catalog (UT1, HaGeZi, …; ~2 min, ~0.5 GB disk) +lmnsquid catalog categories # what can be chosen, with variants and sources lmnsquid filter all-students profile students # youth protection, security, bypass, SafeSearch lmnsquid filter all-teachers profile teachers # security, VPN/proxies, DoH lmnsquid filter all-students lookup example.org @@ -232,7 +233,7 @@ lmnsquid filter all-students lookup example.org A nightly timer (`linuxmuster-squid-catalog.timer`) keeps the catalog current. Build the catalog **before** enabling youth protection categories: without a catalog those instances refuse every -request (fail-closed). Details: [`operations.md`](operations.md#category-filter-safesearch-exceptions-exam-mode-per-instance). +request (fail-closed). Details: [`operations.md`](operations.md#category-filter-safesearch-exceptions-per-instance). ## 8. Domains without proxy authentication (optional) diff --git a/docs/operations.md b/docs/operations.md index 40d147f..555f485 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -302,52 +302,77 @@ lmnsquid noauth all-students list && lmnsquid noauth all-students reload of Microsoft names in `lmnsquid logs ` before adding anything: every entry widens what is reachable without identity. -## Category filter, SafeSearch, exceptions, exam mode (per instance) +## Category filter, SafeSearch, exceptions (per instance) Per instance (= per school and role) the proxy can block whole categories (youth protection, -malware, VPN/proxies, ads, social networks, AI services, …), force SafeSearch, let exceptions -through, switch to an exam mode and explain why a site is blocked (ADR-022). Nothing is active -after an upgrade: an instance without filter settings behaves as before. +malware, scam, VPN/proxies, ads, social networks, AI services, …), choose per category which lists +and how strict, force SafeSearch, let exceptions through and explain why a site is blocked +(ADR-022). Nothing is active after an upgrade: an instance without filter settings behaves as +before. **The catalog** (one per proxy host): `/var/lib/linuxmuster-squid/catalog/current.sqlite`, built -from the lists of UT1 (Université Toulouse Capitole, **CC BY-SA 4.0**) and HaGeZi DNS Blocklists -(**GPL-3.0**); the package ships no list, it downloads them on this host. +from free lists whose licences allow automated use: UT1 (Université Toulouse Capitole, **CC BY-SA +4.0**), HaGeZi DNS Blocklists (**GPL-3.0**), ShadowWhisperer (**Unlicense**), StevenBlack +extensions, Sinfonietta, durablenapkin, NoCoin (**MIT**), dibdot (**GPL-3.0**), PeterDaveHello +(**CC BY-SA 4.0**); the package ships no list, the host downloads them. ``` -lmnsquid catalog update --wait # first build (about 1-2 minutes, ~50 MB download) -lmnsquid catalog status # age, domains, categories with size and sources, last run +lmnsquid catalog update --wait # first build (about 2 minutes, ~60 MB download) +lmnsquid catalog categories # groups, categories, variants (* = recommended), sources +lmnsquid catalog status # everything as JSON: age, entries, sources, last run lmnsquid catalog lookup example.org # which categories/sources list a name systemctl list-timers linuxmuster-squid-catalog.timer # nightly 01:30 + up to 2 h random delay journalctl -u linuxmuster-squid-catalog.service # the nightly runs ``` +- **What is downloaded:** the recommended lists of every category outside the expert group, the + lists any instance on this host uses (a stricter variant, an expert category), the own sources, + and UT1's archive. Choosing a list the catalog does not hold yet starts an update in the + background (`missing_sources` in the answer); until it is done that variant blocks with the lists + that are there. - The timer runs `lmnsquid-catalog update --if-needed` as `lmnsquid` (MemoryMax 400 MiB, idle - I/O): it does nothing while no instance uses categories and no catalog exists. Downloads are + I/O): it does nothing while no instance uses categories and no catalog exists, and it builds + nothing when every source answered "unchanged" and neither the selection nor the configuration + changed (`"unchanged": true` in the result; it still counts for the age check). Downloads are conditional (ETag / If-Modified-Since), UT1 rate-limits, so do not run it more often. - **Safety:** a source that cannot be downloaded falls back to its last download; a source with - fewer entries than its `min_entries` or a category that shrinks by more than half stops the - build and the **active catalog stays** (`status` shows `last_run.state: failed` and the - error). The previous version stays on disk (`catalog-
diff --git a/webui/tests/test_build.py b/webui/tests/test_build.py index 1be0021..d062fb0 100644 --- a/webui/tests/test_build.py +++ b/webui/tests/test_build.py @@ -218,7 +218,12 @@ def test_long_lists_in_dialogs_scroll_on_their_own() -> None: own scroll area, so SafeSearch, save and apply stay within reach.""" html = (PLUGIN / "resources/partial/index.html").read_text() css = (PLUGIN / "resources/css/dialogs.css").read_text() - assert "dialog.lmn-squid-dialog .lmn-squid-scroll" in css and "max-height: 55vh" in css + assert "dialog.lmn-squid-dialog .lmn-squid-scroll {" in css + # sized by the window, never a fixed height that can exceed the visible dialog body + assert "max-height: max(140px, calc(100vh - 400px))" in css + assert "max-height: max(140px, calc(100vh - 330px))" in css + assert 'class="lmn-squid-scroll-log"' in html + assert not re.search(r'style="[^"]*max-height: *[3-9][0-9]{2}px', html), "fixed tall area" scroll = '
' first = html.index(scroll) assert 'ng:repeat="g in detail.filter.catalog.grouped"' in html[first : first + 400]