diff --git a/README.md b/README.md index 9c78ea1..7b655ae 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,12 @@ 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, 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, Ecosia, Brave Search) 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/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/controlplane/lmnsquid/api.py b/controlplane/lmnsquid/api.py index 99bb28d..fe43d1b 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,14 @@ 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 .customlists import CustomError, CustomStore, OwnCategory, OwnSource +from .filters import 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 +47,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 +71,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 +120,104 @@ 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_paths.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), + "problems_old": info.get("problems_old", False), + "error": info.get("error"), + } + + 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() + ) + flt = result["filter"] + if flt["configured"] and flt["categories"] and result.get("filter_capable") is False: + # e.g. after a rollback or the update-all to an older pinned image: nothing filters + flt["problem"] = "image_without_filter" + flt["problem_detail"] = result.get("image") 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 _warnings(config: catalog_mod.Config, body: FilterSettings) -> list[dict[str, str]]: + """The warnings the WebUI shows for what is switched on: expert categories and strict + variants (one per category, both texts when both apply).""" + out: list[dict[str, str]] = [] + for cat_id in body.categories: + cat = config.category(cat_id) or {} + texts = [" ".join(str(cat.get("warning") or "").split())] + chosen = body.variants.get(cat_id) or config.default_variant(cat_id) + variant: dict[str, Any] = next( + (v for v in cat.get("variants") or [] if v["id"] == chosen), {} + ) + texts.append(" ".join(str(variant.get("warning") or "").split())) + text = " ".join(t for t in texts if t) + if text: + label = cat.get("label", cat_id) + if variant.get("label") and not variant.get("default"): + label = f"{label} ({variant['label']})" + out.append({"category": cat_id, "label": label, "warning": text}) + return out + + def _filter_view(name: str) -> dict[str, Any]: + data = filters.read(name) + now = time.time() + zone = (data or {}).get("timezone") or filters.timezone + return { + "name": name, + "configured": data is not None, + "broken": bool(data and data.get("broken")), + # the zone the schedules are evaluated in (read-only; config.yml filter_timezone) + "settings": {**filters.settings(name).model_dump(), "timezone": zone}, + "timezone": zone, + "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 +279,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 +291,123 @@ async def schema() -> dict[str, Any]: return { "instance": Instance.model_json_schema(), "instance_patch": InstancePatch.model_json_schema(), + "filter_settings": FilterSettings.model_json_schema(), + "own_category": OwnCategory.model_json_schema(), + "own_source": OwnSource.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.""" + # the zone of the schedules, in which clients show the server's times too + return { + **catalog_mod.status(catalog_paths, _catalog_config()), + "timezone": filters.timezone, } + @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")} + + # ------------------------------------------- the admin's own sources and categories + custom = CustomStore(settings.catalog_custom, settings.catalog_dir, settings.catalog_config) + + def _custom(call: Any, *args: Any) -> Any: + try: + return call(*args) + except CustomError as exc: + raise HTTPException(status_code=exc.status, detail=str(exc)) from exc + + @app.get("/v1/catalog/custom", dependencies=auth) + def get_custom() -> dict[str, Any]: + """Own sources and own categories (with the number of hand-entered domains).""" + data = _custom(custom.read) + for cat in data["categories"]: + cat["domains"] = len(_custom(custom.domains, cat["id"])) + return data + + @app.post("/v1/catalog/custom/categories", dependencies=auth) + def add_own_category(body: OwnCategory) -> dict[str, Any]: + entry = _custom(custom.add_category, body) + audit.info("own category add id=%s", body.id) + return entry + + @app.delete( + "/v1/catalog/custom/categories/{cat_id}", + dependencies=auth, + status_code=status.HTTP_204_NO_CONTENT, + ) + def remove_own_category(cat_id: str) -> None: + """Remove it with its list and its own sources; instances that use it ignore it.""" + _custom(custom.remove_category, cat_id) + audit.info("own category remove id=%s", cat_id) + + @app.get("/v1/catalog/custom/categories/{cat_id}/domains", dependencies=auth) + def get_own_domains(cat_id: str) -> dict[str, Any]: + return {"id": cat_id, "domains": _custom(custom.domains, cat_id)} + + @app.put("/v1/catalog/custom/categories/{cat_id}/domains", dependencies=auth) + def put_own_domains(cat_id: str, body: dict[str, list[str]]) -> dict[str, Any]: + """Replace the hand-entered list; effective after up to ~60 s (squid's answer cache) on + every instance that uses the category (no catalog build, no reload).""" + domains = _custom(custom.set_domains, cat_id, body.get("domains") or []) + audit.info("own category domains id=%s count=%d", cat_id, len(domains)) + return {"id": cat_id, "domains": domains} + + @app.post("/v1/catalog/custom/sources", dependencies=auth) + def add_own_source(body: OwnSource) -> dict[str, Any]: + """A list on the internet for a category; downloaded and checked at the next catalog + update, which this starts when a catalog exists.""" + if not _catalog_config().category(body.category): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=f"unknown category {body.category!r}", + ) + entry = _custom(custom.add_source, body) + audit.info("own source add id=%s url=%s category=%s", body.id, body.url, body.category) + started = False + if (catalog_paths.catalog_dir / catalog_mod.CURRENT).exists() and not ( + catalog_mod.is_building(catalog_paths.cache_dir) + ): + app.state.spawn_catalog_update() + started = True + return {**entry, "catalog_update_started": started} + + @app.delete( + "/v1/catalog/custom/sources/{src_id}", + dependencies=auth, + status_code=status.HTTP_204_NO_CONTENT, + ) + def remove_own_source(src_id: str) -> None: + _custom(custom.remove_source, src_id) + catalog_mod.forget_source(catalog_paths, src_id) + audit.info("own source remove id=%s", src_id) + # ---------------------------------------------------- write-only secrets (ADR-020) @app.put( "/v1/secrets/{name}", @@ -386,6 +614,157 @@ 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)}", + ) + for cat_id, variant in body.variants.items(): + known = [v["id"] for v in (config.category(cat_id) or {}).get("variants") or []] + if variant not in known: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=f"unknown variant {variant!r} of category {cat_id!r}", + ) + before = filters.read(name) or {} + same = ( + before + and not before.get("broken") + and all( + before.get(k, {} if k in ("variants", "schedules", "safesearch") else []) + == (body.model_dump(mode="json")[k]) + for k in ("categories", "variants", "schedules", "safesearch") + ) + ) + if same: + # nothing changed: no write, no reconfigure, no catalog update + return { + **_filter_view(name), + "applied": True, + "unchanged": True, + "missing_sources": [], + "catalog_update_started": False, + "warnings": _warnings(config, body), + } + written = 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(), + ) + # Sources this selection uses that the catalog does not hold yet (a stricter variant, + # an expert category): the catalog is updated in the background right away. + missing = catalog_mod.missing_for(catalog_paths, config, written) + started = False + if missing and (catalog_paths.catalog_dir / catalog_mod.CURRENT).exists(): + if not catalog_mod.is_building(catalog_paths.cache_dir): + app.state.spawn_catalog_update() + started = True + return { + **_filter_view(name), + **_apply_filter(name), + "missing_sources": missing, + "catalog_update_started": started, + "warnings": _warnings(config, body), + } + + @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``).""" + _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/catalog.py b/controlplane/lmnsquid/catalog.py new file mode 100644 index 0000000..f205e3d --- /dev/null +++ b/controlplane/lmnsquid/catalog.py @@ -0,0 +1,1284 @@ +# 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 *feeds*: one feed is one source for one category (UT1's archive feeds +many categories). The table ``vars`` holds each category's variants (which sources), so the +helper in the container decides from this file and the instance's ``filter.json`` alone. The +directory is mounted read-only into every container at ``/etc/squid/catalog``; the helper there +opens the file read-only and notices a new version by itself. + +What is built: the default variant of every category outside the expert group, every source +that an instance on this host uses (its chosen variant, an expert category), the admin's own +sources, and UT1's archive (one download for all its categories). Other sources are not +downloaded. A setting that needs a source the catalog lacks starts an update (``api.py``). + +The build streams: each source is parsed line by line into ``namefeed 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 feed 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``, opened like the helper does) 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 hashlib +import json +import logging +import os +import re +import resource +import shutil +import sqlite3 +import subprocess +import sys +import tarfile +import tempfile +import time +import urllib.error +import urllib.request +from collections.abc import Callable, 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" +CUSTOM_DIR = "custom" +EXPERT = "expert" +OWN = "own" +MAX_DOWNLOAD = 512 * 1024 * 1024 +MAX_AGE_DAYS = 7 +MAX_FEEDS = 1024 +SHRINK_LIMIT = 0.5 # a feed 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})+$") +_SINGLE_RE = re.compile(rf"^{_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}$") +FORMATS = ("ut1-tar", "domains", "adblock", "rpz") + + +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) + + def source(self, src_id: str) -> dict[str, Any] | None: + return next((s for s in self.sources if s["id"] == src_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 feeding(self, cat_id: str) -> list[str]: + """Ids of the sources that feed ``cat_id``.""" + return [s["id"] for s in self.sources if cat_id in source_targets(s)] + + def default_variant(self, cat_id: str) -> str: + cat = self.category(cat_id) or {} + variants = cat.get("variants") or [] + return next((v["id"] for v in variants if v.get("default")), "") + + def sources_for(self, cat_id: str, variant: str | None = None) -> list[str]: + """The sources ``cat_id`` uses in ``variant`` (unknown/None: the default): the + variant's sources plus every feeding source no variant names.""" + cat = self.category(cat_id) or {} + variants = {v["id"]: v for v in cat.get("variants") or []} + feeding = self.feeding(cat_id) + if not variants: + return feeding + chosen = variants.get(variant or "") or variants[self.default_variant(cat_id)] + named = {s for v in variants.values() for s in v["sources"]} + return [s for s in feeding if s in chosen["sources"] or s not in named] + + +def source_targets(src: dict[str, Any]) -> list[str]: + """The school categories a source feeds.""" + return list(dict.fromkeys((src.get("map") or {}).values())) or [src.get("category")] + + +def _read_yaml(path: str | None) -> dict[str, Any]: + if not path or not os.path.isfile(path): + return {} + loaded = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {} + if not isinstance(loaded, dict): + raise CatalogError(f"{path}: not a mapping") + return loaded + + +def load_config(admin_file: str | None = None, custom_file: str | None = None) -> Config: + """The packaged ``sources.yml``, the admin's hand-written ``catalog.yml`` and the own + sources and categories made through the API (``catalog-custom.yml``), in this order. + + Keys of both files: ``sources`` (same id = replace, new id = add), ``disable_sources``, + ``categories`` (new ones, or changed labels), ``profiles``. + """ + data = yaml.safe_load((DATA_DIR / "sources.yml").read_text(encoding="utf-8")) + categories = {c["id"]: dict(c) for c in data["categories"]} + sources = {s["id"]: dict(s) for s in data["sources"]} + profiles = dict(data.get("profiles", {})) + for extra, origin in ((_read_yaml(admin_file), "admin"), (_read_yaml(custom_file), "custom")): + for cat in extra.get("categories") or []: + merged = {**categories.get(str(cat["id"]), {"group": OWN}), **cat} + merged.setdefault("origin", origin) + categories[str(cat["id"])] = merged + for src in extra.get("sources") or []: + sources[str(src["id"])] = {**dict(src), "origin": origin} + for sid in extra.get("disable_sources") or []: + sources.pop(str(sid), None) + profiles.update(extra.get("profiles") or {}) + config = Config( + list(data["groups"]), list(categories.values()), list(sources.values()), profiles + ) + _validate(config) + return config + + +def _validate(config: Config) -> None: + ids = config.category_ids + 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 not cat.get("label"): + raise CatalogError(f"category {cat['id']}: label missing") + 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 FORMATS: + 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") + for cat in config.categories: + variants = cat.get("variants") or [] + if not variants: + continue + if sum(1 for v in variants if v.get("default")) != 1: + raise CatalogError(f"category {cat['id']}: exactly one default variant") + # a variant may name a source an admin disabled: it then simply has fewer sources + for pid, profile in config.profiles.items(): + for cat_id in profile.get("categories") or []: + if cat_id not in ids: + raise CatalogError(f"profile {pid}: unknown category {cat_id!r}") + + +def needed_sources(config: Config, selections: Iterable[dict[str, Any]]) -> list[str]: + """Sources to download: the defaults of every category outside the expert and own groups, + what ``selections`` (the instances' filter.json) use, every own source of the admin.""" + needed: set[str] = set() + for cat in config.categories: + if cat["group"] not in (EXPERT, OWN): + needed.update(config.sources_for(cat["id"])) + for selection in selections: + variants = selection.get("variants") or {} + for cat_id in selection.get("categories") or []: + if config.category(cat_id): + needed.update(config.sources_for(cat_id, variants.get(cat_id))) + needed.update(s["id"] for s in config.sources if s.get("origin") in ("admin", "custom")) + return [s["id"] for s in config.sources if s["id"] in needed] + + +def selections_of(blocklists_dir: Path | None) -> list[dict[str, Any]]: + if blocklists_dir is None: + return [] + return [read_json(p) for p in sorted(blocklists_dir.glob("*/filter.json"))] + + +# ----------------------------------------------------------------------------- parsing +def normalize_name(raw: str, allow_single_label: bool = False) -> str | None: + """One list entry as a lower-case ASCII domain with at least two labels, or ``None``. + + IP addresses are dropped, single labels too (``com`` would put a whole top-level domain + into a category) unless the source is a list of top-level domains on purpose. + """ + 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): + return None + if _NAME_RE.match(name) or (allow_single_label and _SINGLE_RE.match(name)): + return name + return None + + +def parse_line(line: str, fmt: str, allow_single_label: bool = False) -> 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("*."), allow_single_label) + + +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 + single = bool(src.get("allow_single_label")) + with open(path, "rb") as fh: + for line in iter_lines(fh): + name = parse_line(line, src["format"], single) + 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" + limit = int(src.get("max_bytes") or MAX_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 > limit: + raise CatalogError(f"{src['id']}: larger than {limit} 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]: + """Entries per feed (``source/category``) of the active catalog.""" + current = catalog_dir / CURRENT + if not current.exists(): + return {} + try: + db = sqlite3.connect(f"file:{current}?mode=ro", uri=True) + try: + return { + f"{s}/{c}": int(n) + for s, c, n in db.execute("SELECT source, category, count FROM feeds") + } + finally: + db.close() + except sqlite3.Error: + return {} + + +def _merge(sorted_file: str, bits: dict[tuple[str, str], int]) -> Iterator[tuple[str, int]]: + name: str | None = None + feeds = 0 + with open(sorted_file, encoding="ascii") as fh: + for line in fh: + n, src, cat = line.rstrip("\n").split("\t") + if n != name: + if name is not None: + yield name, feeds + name, feeds = n, 0 + feeds |= 1 << bits[(src, cat)] + if name is not None: + yield name, feeds + + +def _bits(value: int) -> Iterator[int]: + while value: + low = value & -value + yield low.bit_length() - 1 + value ^= low + + +Fallback = Callable[[dict[str, Any], str], "str | None"] + + +def _parse_source(src: dict[str, Any], path: str, index: int, out_file: Path) -> dict[str, int]: + """Parse one source into ``nameindexcategory`` lines; entries per category.""" + counts: dict[str, int] = {} + with open(out_file, "w", encoding="ascii") as out: + for name, category in iter_source(src, path): + out.write(f"{name}\t{index}\t{category}\n") + counts[category] = counts.get(category, 0) + 1 + return counts + + +def check_source(src: dict[str, Any], counts: dict[str, int], previous: dict[str, int]) -> None: + """Refuse a parse with fewer than ``min_entries`` or a feed shrinking by more than half + against the active catalog (``previous``: entries per ``source/category``).""" + total = sum(counts.values()) + if total < int(src.get("min_entries", 1)): + raise CatalogError(f"{total} entries, fewer than min_entries {src.get('min_entries')}") + prefix = f"{src['id']}/" + for key, before in previous.items(): + if not key.startswith(prefix): + continue + after = counts.get(key[len(prefix) :], 0) + if before >= 100 and after < before * SHRINK_LIMIT: + raise CatalogError( + f"{key} would shrink from {before} to {after} entries " + f"(more than {int((1 - SHRINK_LIMIT) * 100)} %): download suspicious" + ) + + +def build_file( + config: Config, + inputs: Iterable[tuple[dict[str, Any], str]], + target: Path, + work: Path, + fetched: dict[str, dict[str, Any]] | None = None, + previous: dict[str, int] | None = None, + fallback: Fallback | None = None, +) -> dict[str, Any]: + """Write the catalog of ``inputs`` (source, downloaded path) to ``target``; return counts. + + Every source is parsed and checked on its own (:func:`check_source`). One that fails -- + unreadable, too few entries, shrinking by more than half -- does not stop the build: + ``fallback(src, reason)`` may name its last good data, which is parsed and checked the same + way; without one the source is left out. ``problems`` in the result names each such source. + """ + fetched = fetched or {} + previous = previous or {} + inputs = list(inputs) + fingerprint = inputs_fingerprint(config, inputs) + feed_bits: dict[tuple[str, str], int] = {} + feed_rows: list[tuple[int, str, str]] = [] + source_rows: list[tuple[Any, ...]] = [] + problems: dict[str, dict[str, Any]] = {} + parsed: list[Path] = [] + for index, (src, path) in enumerate(inputs): + out_file = work / f"source-{index}.tsv" + candidates: list[str] = [path] + error = "" + used: str | None = None + counts: dict[str, int] = {} + while candidates: + candidate = candidates.pop(0) + try: + counts = _parse_source(src, candidate, index, out_file) + check_source(src, counts, previous) + used = candidate + break + except Exception as exc: # noqa: BLE001 - any broken source: isolate it + out_file.unlink(missing_ok=True) + if not error: + error = str(exc) + log.warning("source %s refused: %s", src["id"], error) + alternative = fallback(src, error) if fallback else None + if alternative and alternative != candidate: + candidates.append(alternative) + if error: + problems[src["id"]] = {"error": error, "stale": used is not None} + if used is None: + continue + parsed.append(out_file) + for category in counts: + key = (str(index), category) + if len(feed_bits) >= MAX_FEEDS: + raise CatalogError(f"more than {MAX_FEEDS} feeds") + feed_bits[key] = len(feed_bits) + feed_rows.append((feed_bits[key], src["id"], category)) + info = fetched.get(src["id"]) or {} + source_rows.append( + ( + src["id"], + src["name"], + src["license"], + src.get("url") or "", + src.get("homepage") or "", + sum(counts.values()), + info.get("fetched"), + info.get("last_modified"), + ) + ) + if not parsed: + raise CatalogError( + "no source could be used: " + + "; ".join(f"{k}: {v['error']}" for k, v in problems.items()) + ) + sorted_file = work / "entries.sorted" + subprocess.run( + [ + "sort", + "-S", + "64M", + "-T", + str(work), + "-t", + "\t", + "-k1,1", + "-o", + str(sorted_file), + *[str(f) for f in parsed], + ], + check=True, + env={"LC_ALL": "C", "PATH": "/usr/bin:/bin"}, + ) + for f in parsed: + f.unlink() + nbytes = max(1, (len(feed_bits) + 7) // 8) + feed_cat = {bit: cat for (_idx, cat), bit in feed_bits.items()} + feed_src = {bit: src for bit, src, _cat in feed_rows} + # every (category, variant) as a feed mask, for the counts + var_masks: dict[str, list[tuple[str, int]]] = {} + var_rows: list[tuple[str, str, str]] = [] + for cat in config.categories: + variants = cat.get("variants") or [{"id": "", "sources": config.feeding(cat["id"])}] + for variant in variants: + srcs = set(config.sources_for(cat["id"], variant["id"] or None)) + mask = 0 + for (_idx, category), bit in feed_bits.items(): + if category == cat["id"] and feed_src[bit] in srcs: + mask |= 1 << bit + var_masks.setdefault(cat["id"], []).append((variant["id"], mask)) + if variant["id"]: + var_rows += [(cat["id"], variant["id"], s) for s in variant["sources"]] + feed_counts = dict.fromkeys(feed_bits.values(), 0) + var_counts: dict[tuple[str, str], int] = { + (c, v): 0 for c, vs in var_masks.items() for v, _m in vs + } + 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, label TEXT, grp TEXT, fail_closed INTEGER," + " defvar TEXT);" + "CREATE TABLE feeds(bit INTEGER PRIMARY KEY, source TEXT, category TEXT," + " count INTEGER);" + "CREATE TABLE vars(category TEXT, variant TEXT, source TEXT);" + "CREATE TABLE varcounts(category TEXT, variant TEXT, count INTEGER);" + "CREATE TABLE srcs(id TEXT PRIMARY KEY, name TEXT, license TEXT, url TEXT," + " homepage TEXT, count INTEGER, fetched REAL, last_modified TEXT);" + "CREATE TABLE d(n TEXT PRIMARY KEY, f BLOB) WITHOUT ROWID;" + ) + + def rows() -> Iterator[tuple[str, bytes]]: + for name, feeds in _merge(str(sorted_file), feed_bits): + cats = set() + for bit in _bits(feeds): + feed_counts[bit] += 1 + cats.add(feed_cat[bit]) + for cat_id in cats: + for variant, mask in var_masks.get(cat_id, ()): + if feeds & mask: + var_counts[(cat_id, variant)] += 1 + yield name, feeds.to_bytes(nbytes, "little") + + db.executemany("INSERT INTO d VALUES (?, ?)", rows()) + total = db.execute("SELECT count(*) FROM d").fetchone()[0] + db.executemany( + "INSERT INTO cats VALUES (?, ?, ?, ?, ?)", + [ + ( + c["id"], + c["label"], + c["group"], + int(bool(c.get("fail_closed"))), + config.default_variant(c["id"]), + ) + for c in config.categories + ], + ) + db.executemany( + "INSERT INTO feeds VALUES (?, ?, ?, ?)", + [(bit, s, c, feed_counts[bit]) for bit, s, c in feed_rows], + ) + db.executemany("INSERT INTO vars VALUES (?, ?, ?)", var_rows) + db.executemany( + "INSERT INTO varcounts VALUES (?, ?, ?)", + [(c, v, n) for (c, v), n in var_counts.items()], + ) + 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()), + ("inputs", fingerprint), + ], + ) + 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) + default_counts = {c: var_counts.get((c, config.default_variant(c)), 0) for c in var_masks} + return { + "domains": total, + "feeds": len(feed_bits), + "categories": default_counts, + "feed_counts": {f"{s}/{c}": feed_counts[b] for b, s, c in feed_rows}, + "problems": problems, + } + + +def inputs_fingerprint(config: Config, inputs: Iterable[tuple[dict[str, Any], str]]) -> str: + """What a catalog is built from: the configuration (categories, variants, sources) and, + per used source, the hash of its file's content (a download that brings the same bytes + again, e.g. a broken source refused every night, changes nothing).""" + digest = hashlib.sha256() + digest.update(str(filterdecision.FORMAT).encode()) + digest.update( + json.dumps( + [config.groups, config.categories, config.sources], sort_keys=True, default=str + ).encode() + ) + for src, path in inputs: + file_hash = hashlib.sha256() + try: + with open(path, "rb") as fh: + while chunk := fh.read(1 << 20): + file_hash.update(chunk) + ident = file_hash.hexdigest() + except OSError: + ident = "missing" + digest.update(f"\n{src['id']}={ident}".encode()) + return digest.hexdigest() + + +def _current_inputs(catalog_dir: Path) -> str | None: + current = catalog_dir / CURRENT + if not current.exists(): + return None + try: + db = sqlite3.connect(f"file:{current}?mode=ro", uri=True) + try: + row = db.execute("SELECT v FROM meta WHERE k='inputs'").fetchone() + fmt = db.execute("SELECT v FROM meta WHERE k='format'").fetchone() + finally: + db.close() + except sqlite3.Error: + return None + if not row or not fmt or str(fmt[0]) != str(filterdecision.FORMAT): + return None + return str(row[0]) + + +def check_shrink(new: dict[str, int], old: dict[str, int]) -> None: + """Feeds present before and now: none may lose more than half of its entries.""" + for key, before in old.items(): + if key not in new: + continue # no longer built (nobody uses it): not a shrink + after = new[key] + if before >= 100 and after < before * SHRINK_LIMIT: + raise CatalogError( + f"{key} 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 + custom_file: str | None = None + blocklists_dir: Path | None = None + + def config(self) -> Config: + return load_config(self.admin_config, self.custom_file) + + +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: + if not cache_dir.is_dir(): + return False + 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 _good(cache_dir: Path, src_id: str) -> Path: + """The last download of ``src_id`` that passed its checks (kept beside the current one).""" + return cache_dir / f"{src_id}.good" + + +def _same_file(path: str, other: Path) -> bool: + try: + if os.path.realpath(path) == os.path.realpath(other): + return False # the fallback itself, not a fresh download + with open(path, "rb") as a, open(other, "rb") as b: + while True: + x, y = a.read(1 << 20), b.read(1 << 20) + if x != y: + return False + if not x: + return True + except OSError: + return False + + +def _keep_good(path: str, good: Path) -> None: + if os.path.realpath(path) == os.path.realpath(good): + return + # a copy, not a hard link: whatever writes the next download must not reach the good one + tmp = good.with_name(f".{good.name}.tmp") + shutil.copyfile(path, tmp) + os.replace(tmp, good) + + +def _prune_cache(cache_dir: Path, wanted: set[str], state: dict[str, Any]) -> None: + """Downloads of sources no instance uses any more go (the cache stays bounded).""" + for path in cache_dir.iterdir(): + stem, dot, ext = path.name.partition(".") + if dot and ext in ("download", "good") and stem not in wanted: + path.unlink(missing_ok=True) + for src_id in [k for k in state if k not in wanted]: + del state[src_id] + + +def _update_from_sources(paths: Paths) -> dict[str, Any]: + config = paths.config() + cache = paths.cache_dir + state_file = cache / "sources-state.json" + state = read_json(state_file) + health = read_json(cache / "feeds-state.json") # per source: failing since, last error + wanted = set(needed_sources(config, selections_of(paths.blocklists_dir))) + inputs: list[tuple[dict[str, Any], str]] = [] + fetched: dict[str, str] = {} + failed_download: dict[str, str] = {} + for src in config.sources: + if src["id"] not in wanted: + continue + try: + path, how = fetch(src, cache, state) + except CatalogError as exc: + # nothing downloaded now: the last good data, if any, is all there is + good = _good(cache, src["id"]) + failed_download[src["id"]] = str(exc) + fetched[src["id"]] = "failed" + if good.is_file(): + inputs.append((src, str(good))) + continue + inputs.append((src, path)) + fetched[src["id"]] = how + if how.startswith("cached:"): + failed_download[src["id"]] = how[len("cached: ") :] + _prune_cache(cache, wanted, state) + _write_json(state_file, state) + + def fallback(src: dict[str, Any], reason: str) -> str | None: + # A refused download must not be served again by a 304: forget it, the next run + # downloads in full; the last good data stands in meanwhile. + if not src.get("path"): + (cache / f"{src['id']}.download").unlink(missing_ok=True) + state.pop(src["id"], None) + _write_json(state_file, state) + good = _good(cache, src["id"]) + return str(good) if good.is_file() else None + + # Every source unchanged (304, same local file), the same set of sources and the same + # configuration: the active catalog is exactly what a build would produce. + if inputs_fingerprint(config, inputs) == _current_inputs(paths.catalog_dir): + # the same inputs as the active catalog: its sources' problems stand as they were, + # unless the source now delivered exactly its last good data again (fixed) + current = dict((src["id"], path) for src, path in inputs) + problems = { + k: {"error": v.get("error", ""), "stale": bool(v.get("stale"))} + for k, v in health.items() + if k in wanted + and isinstance(v, dict) + and not (k in current and _same_file(current[k], _good(cache, k))) + } + for k, v in failed_download.items(): + problems.setdefault(k, {"error": v, "stale": True}) + return { + "unchanged": True, + "sources": fetched, + "problems": _record_health(cache, health, problems, wanted, config), + } + with tempfile.TemporaryDirectory(dir=cache, prefix="build.") as work: + target = Path(work) / "catalog.sqlite" + built = build_file( + config, + inputs, + target, + Path(work), + state, + previous=_previous_counts(paths.catalog_dir), + fallback=fallback, + ) + filterdecision.Catalog(str(target)).close() # opens like the helper does + final = publish(paths.catalog_dir, target) + # what passed becomes the last good data of its source + for src, path in inputs: + if src["id"] not in built["problems"] and not src.get("path"): + _keep_good(path, _good(cache, src["id"])) + problems = dict(built["problems"]) + for src_id, reason in failed_download.items(): + problems.setdefault( + src_id, + {"error": f"download failed: {reason}", "stale": (_good(cache, src_id)).is_file()}, + ) + return { + **{k: v for k, v in built.items() if k != "problems"}, + "file": final.name, + "size": final.stat().st_size, + "sources": fetched, + "problems": _record_health(cache, health, problems, wanted, config), + } + + +def _record_health( + cache: Path, + health: dict[str, Any], + problems: dict[str, dict[str, Any]], + wanted: set[str], + config: Config, +) -> list[dict[str, Any]]: + """Keep "failing since" per source across runs; return the current problems with ages.""" + now = time.time() + current: dict[str, Any] = {} + for src_id, problem in problems.items(): + since = float((health.get(src_id) or {}).get("since") or now) + current[src_id] = {"since": since, "error": problem["error"], "stale": problem["stale"]} + _write_json(cache / "feeds-state.json", current) + out = [] + for src_id, item in sorted(current.items()): + src = config.source(src_id) or {"name": src_id} + age = (now - item["since"]) / 86400 + out.append( + { + "source": src_id, + "name": src.get("name", src_id), + "state": "stale" if item["stale"] else "missing", + "error": item["error"], + "since": item["since"], + "age_days": round(age, 2), + "old": age > MAX_AGE_DAYS, + "categories": source_targets(src) if src.get("id") else [], + } + ) + return out + + +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: + filterdecision.Catalog(str(target)).close() + db = sqlite3.connect(f"file:{target}?mode=ro", uri=True) + counts = { + f"{s}/{c}": int(n) + for s, c, n in db.execute("SELECT source, category, count FROM feeds") + } + 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 { + "feed_counts": 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 _catalog_facts(current: Path) -> dict[str, Any]: + """What the active catalog holds, for status(); raises when it is unusable.""" + cat = filterdecision.Catalog(str(current)) + try: + db = cat.db + feeds = [ + (s, c, int(n)) for s, c, n in db.execute("SELECT source, category, count FROM feeds") + ] + varcounts = { + (str(c), str(v)): int(n) + for c, v, n in db.execute("SELECT category, variant, count FROM varcounts") + } + srcs = { + str(r[0]): { + "id": r[0], + "name": r[1], + "license": r[2], + "url": r[3], + "homepage": r[4], + "count": r[5], + "fetched": r[6], + "last_modified": r[7], + } + for r in db.execute( + "SELECT id, name, license, url, homepage, count, fetched, last_modified FROM srcs" + ) + } + domains = db.execute("SELECT v FROM meta WHERE k='domains'").fetchone() + return { + "built": cat.built, + "feeds": feeds, + "varcounts": varcounts, + "srcs": srcs, + "domains": int(domains[0]) if domains else None, + } + finally: + cat.close() + + +def status(paths: Paths, config: Config | None = None) -> dict[str, Any]: + """Everything a client shows about the catalog: age, size, every category with its + description, examples, variants (sources, licences, entries, last download) and the + profiles; and the last update 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": {}, + } + facts: dict[str, Any] = {"feeds": [], "varcounts": {}, "srcs": {}} + current = paths.catalog_dir / CURRENT + try: + facts = _catalog_facts(current) + # a run that found every source unchanged confirms the catalog as current + checked = max(facts["built"], float(run.get("last_success") or 0)) + age = (time.time() - checked) / 86400 + info.update( + available=True, + built=facts["built"], + checked=checked, + age_days=round(age, 2), + old=age > MAX_AGE_DAYS, + domains=facts["domains"], + file=os.path.basename(os.path.realpath(current)), + size=current.stat().st_size, + ) + except (OSError, sqlite3.Error, ValueError) as exc: + info["error"] = "no catalog yet" if not current.exists() else f"catalog unusable: {exc}" + problems = [] + for item in run.get("problems") or []: + age = (time.time() - float(item.get("since") or time.time())) / 86400 + problems.append({**item, "age_days": round(age, 2), "old": age > MAX_AGE_DAYS}) + info["problems"] = problems + info["problems_old"] = any(p["old"] for p in problems) + if config is None: + info["sources"] = list(facts["srcs"].values()) + return info + custom_lists, _labels = filterdecision.read_custom(str(paths.catalog_dir / CUSTOM_DIR)) + feed_count = {(s, c): n for s, c, n in facts["feeds"]} + info["groups"] = config.groups + info["profiles"] = config.profiles + + def source_view(src_id: str, cat_id: str) -> dict[str, Any]: + src = config.source(src_id) or {"id": src_id, "name": src_id, "license": "?"} + built = facts["srcs"].get(src_id) or {} + return { + "id": src_id, + "name": src["name"], + "license": src["license"], + "homepage": src.get("homepage") or "", + "own": src.get("origin") == "custom", + "in_catalog": (src_id, cat_id) in feed_count, + "count": feed_count.get((src_id, cat_id)), + "fetched": built.get("fetched"), + "last_modified": built.get("last_modified"), + } + + for cat in config.categories: + cat_id = cat["id"] + variants = cat.get("variants") or [{"id": "", "label": "", "default": True}] + variant_views = [] + for variant in variants: + srcs = config.sources_for(cat_id, variant["id"] or None) + views = [source_view(s, cat_id) for s in srcs] + variant_views.append( + { + "id": variant["id"], + "label": variant.get("label") or "", + "default": bool(variant.get("default")), + "warning": variant.get("warning") or "", + "sources": views, + "count": facts["varcounts"].get((cat_id, variant["id"])), + "missing": [v["id"] for v in views if not v["in_catalog"]], + } + ) + default = next(v for v in variant_views if v["default"]) + info["categories"].append( + { + "id": cat_id, + "group": cat["group"], + "label": cat["label"], + "description": " ".join(str(cat.get("description") or "").split()), + "examples": cat.get("examples") or [], + "warning": " ".join(str(cat.get("warning") or "").split()), + "fail_closed": bool(cat.get("fail_closed")), + "expert": cat["group"] == EXPERT, + "own": cat["group"] == OWN, + "variants": variant_views, + "count": default["count"], + "own_entries": len(custom_lists.get(cat_id, ())) + if cat_id in custom_lists + else None, + } + ) + info["sources"] = [ + { + **source_view(s["id"], (source_targets(s) or [""])[0]), + "url": s.get("url") or "", + "categories": source_targets(s), + "count": (facts["srcs"].get(s["id"]) or {}).get("count"), + } + for s in config.sources + ] + return info + + +def missing_for(paths: Paths, config: Config, selection: dict[str, Any]) -> list[str]: + """Downloaded sources ``selection`` (a filter.json) uses that the active catalog lacks.""" + try: + have = {s for s, _c, _n in _catalog_facts(paths.catalog_dir / CURRENT)["feeds"]} + except (OSError, sqlite3.Error, ValueError): + have = set() + variants = selection.get("variants") or {} + # a source the last run refused is known: it is fetched again by the next run anyway, + # a rebuild now would refuse it again (lab: 80-100 s per filter change) + failing = { + str(p.get("source")) for p in read_json(paths.cache_dir / STATUS).get("problems") or [] + } + used = { + src + for cat_id in selection.get("categories") or [] + if config.category(cat_id) + for src in config.sources_for(cat_id, variants.get(cat_id)) + } + return sorted(s for s in used if s not in have and s not in failing) + + +def forget_source(paths: Paths, src_id: str) -> None: + """A source the admin removed: out of the reported problems and the cache at once.""" + for name in (STATUS, "feeds-state.json"): + path = paths.cache_dir / name + data = read_json(path) + if not data: + continue + if name == STATUS: + problems = [p for p in data.get("problems") or [] if p.get("source") != src_id] + sources = data.get("sources") + listed = isinstance(sources, dict) and src_id in sources + if problems == (data.get("problems") or []) and not listed: + continue + data["problems"] = problems + if isinstance(sources, dict) and listed: + del sources[src_id] + elif src_id in data: + del data[src_id] + else: + continue + _write_json(path, data) + for suffix in ("download", "good"): + (paths.cache_dir / f"{src_id}.{suffix}").unlink(missing_ok=True) + + +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, + custom_file=settings.catalog_custom, + blocklists_dir=Path(settings.blocklists_dir), + ) + + +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 + result.pop("feed_counts", None) + 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/cli.py b/controlplane/lmnsquid/cli.py index 9b93a34..1cf46ea 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 @@ -42,10 +43,32 @@ def _get_client() -> httpx.Client: ) +def error_lines(status: int, text: str) -> list[str]: + """An error answer as readable lines: one per invalid field of a 422, else the sentence.""" + try: + detail = json.loads(text).get("detail") + except (ValueError, AttributeError): + detail = None + if isinstance(detail, list): + lines = [] + for item in detail: + if not isinstance(item, dict): + continue + loc = [str(x) for x in item.get("loc") or [] if x not in ("body", "query", "path")] + msg = str(item.get("msg") or "invalid").removeprefix("Value error, ") + lines.append(f"error {status}: {'.'.join(loc) or 'input'}: {msg}") + if lines: + return lines + if isinstance(detail, str) and detail: + return [f"error {status}: {detail}"] + return [f"error {status}: {text.strip() or 'no details'}"] + + def _emit(resp: httpx.Response) -> None: - """Print the response as pretty JSON; exit non-zero on HTTP error.""" + """Print the response as pretty JSON; exit non-zero on HTTP error (readable lines).""" if resp.status_code >= 400: - typer.secho(f"error {resp.status_code}: {resp.text}", fg=typer.colors.RED, err=True) + for line in error_lines(resp.status_code, resp.text): + typer.secho(line, fg=typer.colors.RED, err=True) raise typer.Exit(1) if resp.status_code == 204 or not resp.content: typer.echo("ok") @@ -231,6 +254,420 @@ 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. " + "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; + sources whose current download was refused are listed at the end.""" + with _get_client() as c: + resp = c.get("/v1/catalog") + _emit(resp) + _print_problems(resp.json()) + + +def _print_problems(info: dict[str, Any]) -> None: + for item in info.get("problems") or []: + what = "last good list used" if item.get("state") == "stale" else "not in the catalog" + typer.secho( + f"warning: source {item['source']} ({what} for {item.get('age_days', 0):.1f} days): " + f"{item.get('error')}", + fg=typer.colors.RED if item.get("old") else typer.colors.YELLOW, + err=True, + ) + + +@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)) + _print_problems(info.json()) + if last.get("state") != "ok": + raise typer.Exit(1) + + +@catalog_app.command("categories") +def catalog_categories() -> None: + """Categories by group: id, label, entries, variants (* = default), sources and licences.""" + with _get_client() as c: + resp = c.get("/v1/catalog") + if resp.status_code >= 400: + _emit(resp) + info = resp.json() + labels = {g["id"]: g["label"] for g in info.get("groups", [])} + for group in info.get("groups", []): + cats = [x for x in info.get("categories", []) if x["group"] == group["id"]] + if not cats: + continue + typer.echo(f"\n{labels[group['id']]}") + for cat in cats: + count = cat.get("count") + typer.echo(f" {cat['id']:<22} {cat['label']} ({'-' if count is None else count})") + for var in cat.get("variants", []): + srcs = ", ".join(f"{s['name']} [{s['license']}]" for s in var["sources"]) + mark = "*" if var["default"] else " " + vid = var["id"] or "-" + typer.echo(f" {mark} {vid:<10} {srcs}") + + +custom_app = typer.Typer( + help="Own list sources (URL, https only, checked like the packaged ones) and own categories " + "with a hand-entered domain list (effective at once). Use them like any category.", + no_args_is_help=True, +) +catalog_app.add_typer(custom_app, name="own") + + +@custom_app.command("show") +def own_show() -> None: + """Own sources and categories.""" + with _get_client() as c: + _emit(c.get("/v1/catalog/custom")) + + +@custom_app.command("add-category") +def own_add_category( + cat_id: str = typer.Argument(..., help="own_"), + label: str = typer.Option(..., help="name shown in the WebUI and on the block page"), + description: str = typer.Option(""), +) -> None: + """Create an own category.""" + with _get_client() as c: + _emit( + c.post( + "/v1/catalog/custom/categories", + json={"id": cat_id, "label": label, "description": description}, + ) + ) + + +@custom_app.command("remove-category") +def own_remove_category(cat_id: str) -> None: + """Remove an own category with its list and its own sources.""" + with _get_client() as c: + _emit(c.delete(f"/v1/catalog/custom/categories/{quote(cat_id, safe='')}")) + + +@custom_app.command("domains") +def own_domains( + cat_id: str, + add: list[str] = typer.Option([], "--add", help="domain (repeat)"), + remove: list[str] = typer.Option([], "--remove", help="domain (repeat)"), +) -> None: + """Show or change the domain list of an own category (effective after up to ~60 s).""" + url = f"/v1/catalog/custom/categories/{quote(cat_id, safe='')}/domains" + with _get_client() as c: + resp = c.get(url) + if resp.status_code >= 400 or not (add or remove): + _emit(resp) + return + domains = [d for d in resp.json()["domains"] if d not in remove] + list(add) + _emit(c.put(url, json={"domains": domains})) + + +@custom_app.command("add-source") +def own_add_source( + src_id: str = typer.Argument(..., help="own-"), + url: str = typer.Option(..., help="https URL of the list"), + category: str = typer.Option(..., help="category id (packaged or own_...)"), + license_: str = typer.Option(..., "--license", help="licence of the list (shown to users)"), + name: Optional[str] = typer.Option(None), + fmt: str = typer.Option( + "domains", "--format", help="domains | hosts | wildcard | adblock | rpz" + ), + min_entries: int = typer.Option(10, help="fewer entries = download refused"), + max_mb: int = typer.Option(50, help="size limit of the download"), +) -> None: + """Add a list source; the catalog is updated in the background.""" + body = { + "id": src_id, + "name": name or src_id, + "url": url, + "category": category, + "license": license_, + "format": fmt, + "min_entries": min_entries, + "max_mb": max_mb, + } + with _get_client() as c: + _emit(c.post("/v1/catalog/custom/sources", json=body)) + + +@custom_app.command("remove-source") +def own_remove_source(src_id: str) -> None: + """Remove an own source (gone from the catalog at the next update).""" + with _get_client() as c: + _emit(c.delete(f"/v1/catalog/custom/sources/{quote(src_id, safe='')}")) + + +@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 and their variants, schedules, SafeSearch, " + '"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, variants, schedules and SafeSearch.""" + 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: + settings = {k: v for k, v in settings.items() if k != "timezone"} # read-only + resp = c.put(f"/v1/instances/{name}/filter", json=settings) + _emit(resp) + body = resp.json() + for item in body.get("warnings") or []: + typer.secho( + f"warning: {item['label']}: {item['warning']}", fg=typer.colors.YELLOW, err=True + ) + if body.get("missing_sources"): + started = "started" if body.get("catalog_update_started") else "needed" + typer.secho( + f"note: lists not in the catalog yet ({', '.join(body['missing_sources'])}): " + f"catalog update {started}", + fg=typer.colors.YELLOW, + err=True, + ) + + +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"), + variant: list[str] = typer.Option( + [], + "--variant", + help="= (repeat), e.g. ads=normal; ids: `catalog categories`", + ), + 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"), + ecosia: Optional[bool] = typer.Option(None, help="SafeSearch for Ecosia"), + brave: Optional[bool] = typer.Option(None, help="SafeSearch for Brave Search"), +) -> 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 + for item in variant: + cat_id, sep, var_id = item.partition("=") + if not sep or not cat_id or not var_id: + typer.secho(f"--variant {item!r}: expected =", err=True) + raise typer.Exit(2) + settings.setdefault("variants", {})[cat_id] = var_id + 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), + ("ecosia", ecosia), + ("brave", brave), + ): + if value is not None: + safe[key] = value + _put_settings(c, ctx.obj, settings) + + +def profile_diff(current: dict[str, Any], profile: dict[str, Any]) -> dict[str, Any]: + """What applying ``profile`` changes in ``current`` (the preview before applying).""" + now, new = set(current.get("categories") or []), set(profile.get("categories") or []) + safe_now = current.get("safesearch") or {} + safe_new = profile.get("safesearch") or {} + return { + "categories_on": sorted(new - now), + "categories_off": sorted(now - new), + "variants_reset": sorted((current.get("variants") or {}).keys() & new), + "schedules_dropped": sorted(current.get("schedules") or {}), + "safesearch": { + k: [safe_now.get(k), v] for k, v in safe_new.items() if safe_now.get(k) != v + }, + } + + +@filter_app.command("profile") +def filter_profile( + ctx: typer.Context, + profile: str = typer.Argument(..., help="students | primary | teachers | staff | guests"), + dry_run: bool = typer.Option(False, "--dry-run", help="only show what would change"), +) -> None: + """Apply a profile: its categories (default variants) and SafeSearch replace the current + ones, schedules are dropped. --dry-run shows the changes first.""" + 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] + current = _current(c, ctx.obj) + if dry_run: + typer.echo(json.dumps(profile_diff(current, chosen), indent=2, ensure_ascii=False)) + return + _put_settings( + c, + ctx.obj, + { + "categories": chosen["categories"], + "variants": chosen.get("variants", {}), + "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, in the zone filter_timezone of + config.yml (default Europe/Berlin; `filter show` names it), not the host's clock zone.""" + 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("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/config.py b/controlplane/lmnsquid/config.py index 7f0859f..3062ddd 100644 --- a/controlplane/lmnsquid/config.py +++ b/controlplane/lmnsquid/config.py @@ -26,6 +26,17 @@ 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" + catalog_custom: str = "/etc/linuxmuster-squid/catalog-custom.yml" # API-managed own sources + protected_file: str = "/etc/linuxmuster-squid/protected.domains" + catalog_url: str | None = None # a finished catalog from an internal mirror instead + # Time zone of the filter's schedules: school time, not the proxy host's clock zone (a VM + # from a cloud image runs in UTC). Also the zone the WebUI shows server times in. + filter_timezone: str = "Europe/Berlin" docker_host: str | None = None bind_host: str = "127.0.0.1" bind_port: int = 8080 diff --git a/controlplane/lmnsquid/customlists.py b/controlplane/lmnsquid/customlists.py new file mode 100644 index 0000000..038acc0 --- /dev/null +++ b/controlplane/lmnsquid/customlists.py @@ -0,0 +1,274 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The admin's own list sources and own categories (ADR-022), managed through the API. + +* Own **sources** (a URL list for an existing or an own category) and own **categories** + (id ``own_``, label, description) live in ``catalog-custom.yml`` (``Settings. + catalog_custom``), merged into the catalog configuration by ``catalog.load_config``. A source + is downloaded and checked like every other one at the next catalog update. +* The **domain list** of an own category (entered by hand) lives next to the catalog in + ``custom/.domains`` with the labels in ``custom/categories.json``: the helper in every + container reads them directly, so a change applies after up to ~60 s (squid's answer cache), without a build. + +Every write is atomic (temporary file + rename) and serialised by a lock file. +""" + +from __future__ import annotations + +import contextlib +import fcntl +import json +import os +import re +import tempfile +from collections.abc import Iterator +from pathlib import Path +from typing import Any, Literal + +import yaml +from pydantic import BaseModel, field_validator + +from . import catalog as catalog_mod +from .filterdecision import OWN_PREFIX, read_domains + +OWN_ID_RE = re.compile(r"^own_[a-z0-9_]{1,30}$") +OWN_SOURCE_RE = re.compile(r"^own-[a-z0-9-]{1,30}$") +MAX_DOMAINS = 50_000 +MAX_SOURCE_MB = 200 + + +class CustomError(Exception): + """A request the store refuses (``status``: the HTTP status the API answers).""" + + def __init__(self, message: str, status: int = 422) -> None: + super().__init__(message) + self.status = status + + +class OwnCategory(BaseModel): + """Body of ``POST /v1/catalog/custom/categories``.""" + + id: str + label: str + description: str = "" + + @field_validator("id") + @classmethod + def _v_id(cls, v: str) -> str: + if not OWN_ID_RE.match(v): + raise ValueError("id must look like own_ (at most 34 characters)") + return v + + @field_validator("label") + @classmethod + def _v_label(cls, v: str) -> str: + v = " ".join(v.split()) + if not 1 <= len(v) <= 60: + raise ValueError("label: 1 to 60 characters") + return v + + @field_validator("description") + @classmethod + def _v_description(cls, v: str) -> str: + v = " ".join(v.split()) + if len(v) > 300: + raise ValueError("description: at most 300 characters") + return v + + +class OwnSource(BaseModel): + """Body of ``POST /v1/catalog/custom/sources``: a list on the internet for one category.""" + + id: str + name: str + url: str + format: Literal["domains", "hosts", "wildcard", "adblock", "rpz"] = "domains" + category: str + license: str + min_entries: int = 10 + max_mb: int = 50 + + @field_validator("id") + @classmethod + def _v_id(cls, v: str) -> str: + if not OWN_SOURCE_RE.match(v): + raise ValueError("id must look like own-") + return v + + @field_validator("name", "license") + @classmethod + def _v_text(cls, v: str) -> str: + v = " ".join(v.split()) + if not 1 <= len(v) <= 120: + raise ValueError("1 to 120 characters") + return v + + @field_validator("url") + @classmethod + def _v_url(cls, v: str) -> str: + v = v.strip() + if not re.match(r"^https://[A-Za-z0-9.-]+(:\d{1,5})?(/[^\s]*)?$", v) or len(v) > 500: + raise ValueError("an https:// URL (plain http is refused)") + return v + + @field_validator("min_entries") + @classmethod + def _v_min(cls, v: int) -> int: + if not 1 <= v <= 10_000_000: + raise ValueError("min_entries: 1 to 10 000 000") + return v + + @field_validator("max_mb") + @classmethod + def _v_max(cls, v: int) -> int: + if not 1 <= v <= MAX_SOURCE_MB: + raise ValueError(f"max_mb: 1 to {MAX_SOURCE_MB}") + return v + + def as_source(self) -> dict[str, Any]: + """The entry of catalog-custom.yml (hosts and wildcard are read as domains).""" + return { + "id": self.id, + "name": self.name, + "license": self.license, + "url": self.url, + "format": "domains" if self.format in ("hosts", "wildcard") else self.format, + "category": self.category, + "min_entries": self.min_entries, + "max_bytes": self.max_mb * 1024 * 1024, + } + + +def _atomic(path: Path, text: str, mode: int) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + 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, mode) + os.replace(tmp, path) + except BaseException: + if os.path.exists(tmp): + os.unlink(tmp) + raise + + +class CustomStore: + """Own sources and categories (``custom_file``) and the own domain lists (``catalog_dir``).""" + + def __init__(self, custom_file: str, catalog_dir: str, admin_file: str | None = None) -> None: + self.file = Path(custom_file) + self.dir = Path(catalog_dir) / catalog_mod.CUSTOM_DIR + self.admin_file = admin_file + + @contextlib.contextmanager + def _locked(self) -> Iterator[None]: + self.file.parent.mkdir(parents=True, exist_ok=True) + with open(self.file.parent / ".catalog-custom.lock", "w") as fh: + fcntl.flock(fh, fcntl.LOCK_EX) + yield + + def read(self) -> dict[str, Any]: + try: + data = yaml.safe_load(self.file.read_text(encoding="utf-8")) or {} + except FileNotFoundError: + data = {} + if not isinstance(data, dict): + raise CustomError(f"{self.file}: not a mapping", 409) + return { + "sources": list(data.get("sources") or []), + "categories": list(data.get("categories") or []), + } + + def _write(self, data: dict[str, Any]) -> None: + # Check before writing: the merged configuration must still load. + fd, tmp = tempfile.mkstemp(dir=self.file.parent, prefix=".check.", suffix=".yml") + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + yaml.safe_dump(data, fh, allow_unicode=True, sort_keys=False) + try: + catalog_mod.load_config(self.admin_file, tmp) + except catalog_mod.CatalogError as exc: + raise CustomError(str(exc)) from None + finally: + os.unlink(tmp) + header = "# Managed by linuxmuster-squid (API, CLI, WebUI): own sources and categories.\n" + _atomic( + self.file, header + yaml.safe_dump(data, allow_unicode=True, sort_keys=False), 0o644 + ) + self._write_labels(data) + + def _write_labels(self, data: dict[str, Any]) -> None: + labels = {c["id"]: c["label"] for c in data["categories"]} + self.dir.mkdir(parents=True, exist_ok=True) + os.chmod(self.dir, 0o755) + _atomic(self.dir / "categories.json", json.dumps(labels, ensure_ascii=False), 0o644) + + # ------------------------------------------------------------------ categories + def add_category(self, cat: OwnCategory) -> dict[str, Any]: + with self._locked(): + data = self.read() + entry = { + "id": cat.id, + "group": catalog_mod.OWN, + "label": cat.label, + "description": cat.description, + } + data["categories"] = [c for c in data["categories"] if c["id"] != cat.id] + [entry] + self._write(data) + if not (self.dir / f"{cat.id}.domains").exists(): + _atomic(self.dir / f"{cat.id}.domains", "", 0o644) + return entry + + def remove_category(self, cat_id: str) -> None: + with self._locked(): + data = self.read() + if not any(c["id"] == cat_id for c in data["categories"]): + raise CustomError(f"no own category {cat_id!r}", 404) + data["categories"] = [c for c in data["categories"] if c["id"] != cat_id] + data["sources"] = [s for s in data["sources"] if s.get("category") != cat_id] + self._write(data) + (self.dir / f"{cat_id}.domains").unlink(missing_ok=True) + + def domains(self, cat_id: str) -> list[str]: + self._require_own(cat_id) + return sorted(read_domains(str(self.dir / f"{cat_id}.domains"))) + + def set_domains(self, cat_id: str, domains: list[str]) -> list[str]: + """Replace the hand-entered list of ``cat_id`` (normalised; bad names refused).""" + self._require_own(cat_id) + if len(domains) > MAX_DOMAINS: + raise CustomError(f"at most {MAX_DOMAINS} domains") + names: set[str] = set() + for raw in domains: + name = catalog_mod.normalize_name(str(raw)) + if name is None: + raise CustomError(f"not a domain: {raw!r}") + names.add(name) + with self._locked(): + text = "".join(f"{n}\n" for n in sorted(names)) + _atomic(self.dir / f"{cat_id}.domains", text, 0o644) + return sorted(names) + + def _require_own(self, cat_id: str) -> None: + if not cat_id.startswith(OWN_PREFIX) or not any( + c["id"] == cat_id for c in self.read()["categories"] + ): + raise CustomError(f"no own category {cat_id!r}", 404) + + # ------------------------------------------------------------------ sources + def add_source(self, src: OwnSource) -> dict[str, Any]: + with self._locked(): + data = self.read() + entry = src.as_source() + data["sources"] = [s for s in data["sources"] if s["id"] != src.id] + [entry] + self._write(data) + return entry + + def remove_source(self, src_id: str) -> None: + with self._locked(): + data = self.read() + if not any(s["id"] == src_id for s in data["sources"]): + raise CustomError(f"no own source {src_id!r}", 404) + data["sources"] = [s for s in data["sources"] if s["id"] != src_id] + self._write(data) 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/nosafesearch-extra.domains b/controlplane/lmnsquid/data/nosafesearch-extra.domains new file mode 100644 index 0000000..d3d6d57 --- /dev/null +++ b/controlplane/lmnsquid/data/nosafesearch-extra.domains @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Search engines without a SafeSearch that a network can force (checked 2026-11-24), which the +# HaGeZi list "Safesearch not supported" does not name. Not here, because the proxy forces their +# SafeSearch instead (filters.py): Google, YouTube, Bing, DuckDuckGo, Ecosia, Brave Search. +# Startpage documents safe.startpage.com, but it depends on the Host header (404 for +# www.startpage.com via that address), so squid's hosts_file cannot force it: blocked. +startpage.com +startpage.de +qwant.com +mojeek.com +mojeek.co.uk +metager.de +metager.org +search.yahoo.com +search.aol.com +ask.com +dogpile.com +yandex.com +yandex.ru +kagi.com diff --git a/controlplane/lmnsquid/data/protected.domains b/controlplane/lmnsquid/data/protected.domains new file mode 100644 index 0000000..67b13e3 --- /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 still applies. +# 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..833aa8e --- /dev/null +++ b/controlplane/lmnsquid/data/sources.yml @@ -0,0 +1,543 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Category catalog of the filter (ADR-022): the school categories offered, their variants +# (which sources, how strict), the list sources and the profiles. The package ships no list +# content, only this description; `lmnsquid catalog update` downloads the sources on the proxy +# host. Additions: /etc/linuxmuster-squid/catalog.yml by hand (same keys; a source with the same +# id replaces this one, `disable_sources: [id, ...]` drops some) and the admin's own sources and +# categories made with the API/CLI/WebUI (catalog-custom.yml). Basis: +# work/linuxmuster-squid/recherche-filterlisten.md (2026-11-24), sections 2.1 and 7. +# +# Category ids are stable (stored per instance in filter.json). A variant names the sources it +# uses; a source feeding a category that no variant names (an admin's own source) always counts. +# The default variant of every category outside the expert group is always in the catalog; other +# variants and expert categories are downloaded once an instance on the host uses them. +# fail_closed: requests are refused while the catalog is missing or broken and such a category is +# active (youth protection). + +groups: + - {id: youth, label: "Jugendschutz", + description: "Inhalte, die für Kinder und Jugendliche ungeeignet sind (§ 184 StGB, JMStV)."} + - {id: security, label: "Sicherheit", + description: "Schadsoftware, Phishing, Betrug. Auch für Lehrkräfte und Verwaltung sinnvoll."} + - {id: bypass, label: "Umgehung", + description: "Dienste, mit denen sich der Filter umgehen lässt."} + - {id: ads, label: "Werbung und Tracking", + description: "Werbung, Tracker, Analyse; strengere Stufen sperren mehr, aber auch Nützliches."} + - {id: telemetry, label: "Telemetrie (je Hersteller)", + description: "Datensammlung der Geräte und Betriebssysteme. Nie als Standard: kann Updates, + Office oder Defender stören; Windows Update u. Ä. stehen auf der Schutzliste."} + - {id: distraction, label: "Ablenkung", + description: "Pädagogische Entscheidung der Schule, z. B. nur in der Unterrichtszeit sperren."} + - {id: misc, label: "Downloads, KI, Prüfungen", description: ""} + - {id: expert, label: "Weitere Kategorien (Experten)", + description: "Nur bewusst einschalten: mehr Fehlsperrungen möglich. Nicht angeboten werden + UT1-Kategorien, die laut Hersteller nicht zu verwenden sind (examen_pix, tricheur_pix), + Freigabelisten (liste_blanche, liste_bu, child, educational_games, update) und solche, deren + Sperre Schule und Unterricht schadet: bank, jobsearch (Berufsorientierung), press, radio, + translation, webmail (Eltern-/Schulmail), remote-control (Schul-Support), shortener (bricht + Links in Arbeitsblättern), sexual_education (Aufklärung), cleaning und webhosting (enthalten + apple.com, avast.com, airtable.com u. a.)."} + - {id: own, label: "Eigene Kategorien", description: "Von der Schul-IT angelegte Listen."} + +categories: + # --- youth protection + - id: porn + group: youth + label: "Pornografie" + description: "Pornografische und sexuell explizite Seiten (UT1 adult und lingerie, HaGeZi NSFW)." + examples: [pornhub.com, xvideos.com, xhamster.com] + fail_closed: true + variants: + - {id: both, label: "UT1 und HaGeZi NSFW", sources: [ut1, hagezi-nsfw], default: true} + - {id: ut1, label: "nur UT1", sources: [ut1]} + - {id: hagezi, label: "nur HaGeZi NSFW (kleiner, weniger Fehlsperrungen)", + sources: [hagezi-nsfw]} + - {id: all, label: "alle Quellen (UT1, HaGeZi, ShadowWhisperer, Sinfonietta)", + sources: [ut1, hagezi-nsfw, sw-adult, sinfonietta-porn], + warning: "Mehr Quellen sperren mehr, aber auch mehr Plattformen mit gemischtem Inhalt."} + - id: gambling + group: youth + label: "Glücksspiel" + description: "Online-Casinos, Sportwetten, Lotterie-Anbieter." + examples: [bet365.com, pokerstars.com, tipico.de] + fail_closed: true + variants: + - {id: standard, label: "UT1 und HaGeZi Gambling (mittel)", + sources: [ut1, hagezi-gambling-medium], default: true} + - {id: strict, label: "UT1, HaGeZi Gambling (voll, ~700 000), ShadowWhisperer, StevenBlack", + sources: [ut1, hagezi-gambling-full, sw-gambling, stevenblack-gambling], + warning: "Die volle Liste enthält auch Werbe- und Affiliate-Seiten rund um Glücksspiel; + gelegentlich Fehlsperrungen."} + - id: violence + group: youth + label: "Gewalt, Hass und Extremismus" + description: "Gewaltverherrlichung, Hass, Rassismus, Sekten, Anleitungen zu gefährlichen + Stoffen (UT1 agressif, sect, dangerous_material)." + examples: [whatisscientology.org] + fail_closed: true + variants: + - {id: standard, label: "UT1 und Sinfonietta (Gewaltvideos)", sources: [ut1, sinfonietta-snuff], + default: true} + - id: drugs + group: youth + label: "Drogen" + description: "Verkauf und Verherrlichung von Drogen (UT1 drogue)." + examples: [zamnesia.fr] + fail_closed: true + - id: dating + group: youth + label: "Dating" + description: "Partnerbörsen und Dating-Apps (UT1 dating)." + examples: [tinder.com, badoo.com] + fail_closed: true + # --- security + - id: security + group: security + label: "Malware und Phishing" + description: "Schadsoftware, Phishing, Kryptomining, Stalkerware, DDoS-Dienste (UT1 und + HaGeZi Threat Intelligence Feeds)." + examples: [0000usdtvip.com] + variants: + - {id: medium, label: "UT1 und HaGeZi TIF (mittel)", + sources: [ut1, hagezi-tif-medium, nocoin], default: true} + - {id: mini, label: "UT1 und HaGeZi TIF (klein)", sources: [ut1, hagezi-tif-mini, nocoin]} + - {id: full, label: "UT1, HaGeZi TIF (voll, ~1,9 Mio. Einträge), ShadowWhisperer Malware", + sources: [ut1, hagezi-tif-full, nocoin, sw-malware], + warning: "Die volle Liste ist sehr groß (mehr Speicher und Bauzeit) und sperrt auch + ältere, inzwischen harmlose Domains."} + - id: scam + group: security + label: "Betrug und Fake-Shops" + description: "Fake-Shops, Abofallen, betrügerische Investment- und Support-Seiten (HaGeZi Fake, + durablenapkin Scam Blocklist)." + examples: [] + variants: + - {id: standard, label: "HaGeZi Fake und Scam Blocklist", sources: [hagezi-fake, scamblocklist], + default: true} + - {id: strict, label: "dazu ShadowWhisperer Scam", sources: [hagezi-fake, scamblocklist, sw-scam], + warning: "Etwas breitere Liste; vereinzelt Fehlsperrungen bei kleinen Shops."} + # --- bypass + - id: vpn_proxy + group: bypass + label: "VPN, Proxys und Anonymisierer" + description: "Web-Proxys, VPN-Anbieter, Residential Proxies (UT1 vpn, redirector, + residential-proxies; HaGeZi DoH/VPN/Tor/Proxy-Bypass)." + examples: [4proxy.com, 1clickvpn.net] + variants: + - {id: standard, label: "UT1 und HaGeZi Bypass", sources: [ut1, hagezi-bypass], default: true} + - {id: strict, label: "dazu ShadowWhisperer Tunnels", sources: [ut1, hagezi-bypass, sw-tunnels], + warning: "Sperrt auch Tunnel-Dienste, die Entwickler oder Schul-IT nutzen (z. B. ngrok)."} + - id: doh + group: bypass + label: "DNS-over-HTTPS-Resolver" + description: "Verschlüsselte DNS-Server, mit denen Apps an Filtern vorbei auflösen (UT1, HaGeZi, + dibdot DoH-Liste, ShadowWhisperer DNS)." + examples: [dns.google, cloudflare-dns.com] + - id: nosafesearch + group: bypass + label: "Suchmaschinen ohne SafeSearch" + description: "Suchmaschinen, bei denen sich SafeSearch nicht erzwingen lässt (HaGeZi und + Ergänzung des Pakets: Startpage, Qwant, Mojeek, MetaGer, Yahoo-, AOL-Suche, Ask, Dogpile, + Yandex, Kagi). Google, YouTube, Bing, DuckDuckGo, Ecosia und Brave Search werden stattdessen + über SafeSearch erzwungen. Empfohlen, sobald SafeSearch an ist." + examples: [startpage.com, qwant.com] + # --- ads and tracking + - id: ads + group: ads + label: "Werbung und Tracking" + description: "Werbenetze, Tracker, Analyse- und Telemetriedienste von Webseiten (HaGeZi Multi)." + examples: [doubleclick.net] + variants: + - {id: light, label: "Light (empfohlen)", sources: [hagezi-light], default: true} + - {id: normal, label: "Normal", sources: [hagezi-multi]} + - {id: pro, label: "Pro", sources: [hagezi-pro], + warning: "Pro sperrt mehr Tracker; einzelne Seiten oder Funktionen (Links in + Newslettern, eingebettete Inhalte) können ausfallen."} + - {id: proplus, label: "Pro++", sources: [hagezi-proplus], + warning: "Pro++ ist aggressiv und bricht laut HaGeZi auch Funktionen bekannter Dienste. + Nur mit Ausnahmeliste und Rückmeldungen der Nutzer."} + # --- telemetry per vendor + - {id: telemetry_microsoft, group: telemetry, label: "Telemetrie Microsoft (Windows, Office)", + description: "Diagnosedaten von Windows und Office (HaGeZi Native). Kann Cloud-Funktionen in + Office stören.", examples: []} + - {id: telemetry_apple, group: telemetry, label: "Telemetrie Apple", description: "", examples: []} + - {id: telemetry_amazon, group: telemetry, label: "Telemetrie Amazon", description: "", + examples: []} + - {id: telemetry_samsung, group: telemetry, label: "Telemetrie Samsung", description: "", + examples: []} + - {id: telemetry_huawei, group: telemetry, label: "Telemetrie Huawei", description: "", + examples: []} + - {id: telemetry_xiaomi, group: telemetry, label: "Telemetrie Xiaomi", description: "", + examples: []} + - id: telemetry_tiktok + group: telemetry + label: "Telemetrie TikTok" + description: "Tracking der TikTok-App (die App selbst sperrt „Soziale Netzwerke“)." + examples: [] + variants: + - {id: standard, label: "Standard", sources: [hagezi-native-tiktok], default: true} + - {id: extended, label: "Erweitert", sources: [hagezi-native-tiktok-extended], + warning: "Die erweiterte Liste kann TikTok-Inhalte auf anderen Seiten brechen."} + - {id: telemetry_lg, group: telemetry, label: "Telemetrie LG webOS (Smart-TV)", description: "", + examples: []} + - {id: telemetry_roku, group: telemetry, label: "Telemetrie Roku", description: "", + examples: []} + - {id: telemetry_vivo, group: telemetry, label: "Telemetrie Vivo", description: "", + examples: []} + - {id: telemetry_oppo, group: telemetry, label: "Telemetrie OPPO/Realme", description: "", + examples: []} + # --- distraction + - id: social + group: distraction + label: "Soziale Netzwerke" + description: "Instagram, TikTok, Facebook, Snapchat u. a. (UT1 social_networks, HaGeZi Social)." + examples: [instagram.com, tiktok.com, snapchat.com] + variants: + - {id: standard, label: "UT1 und HaGeZi Social", sources: [ut1, hagezi-social], default: true} + - {id: extended, label: "dazu StevenBlack/Sinfonietta Social", + sources: [ut1, hagezi-social, stevenblack-social]} + - id: games + group: distraction + label: "Spiele" + description: "Online- und Browserspiele, Spieleportale (UT1 games)." + examples: [miniclip.com, 7sudoku.com] + - id: chat + group: distraction + label: "Chat und Messenger" + description: "Webchats und Messenger-Weboberflächen (UT1 chat)." + examples: [321chat.com] + - id: streaming + group: distraction + label: "Streaming und Video" + description: "Film-, Musik- und Videoportale (UT1 audio-video). YouTube steht auf der + Schutzliste und bleibt erreichbar (Eingeschränkter Modus per SafeSearch)." + examples: [1000films.com] + # --- downloads, AI, exams + - id: warez + group: misc + label: "Downloads, Warez und Filehoster" + description: "Raubkopien, Torrent-Seiten, Filehoster, Download-Portale (UT1 warez, + filehosting, download; HaGeZi Anti-Piracy)." + examples: [1337x.org, 1fichier.com] + - id: ai + group: misc + label: "KI-Dienste" + description: "Chatbots und KI-Werkzeuge (UT1 ai und Ergänzung des Pakets). KI in erlaubten + Diensten (Copilot in Microsoft 365, Gemini in Workspace) lässt sich nicht trennen." + examples: [chatgpt.com, claude.ai, gemini.google.com] + - id: cheating + group: misc + label: "Prüfungsbetrug" + description: "Seiten, die Schummeln bei Prüfungen erklären oder anbieten (UT1 tricheur)." + examples: [] + # --- expert categories (UT1 and HaGeZi) + - {id: mixed_adult, group: expert, label: "Gemischte Inhalte mit Erotik", + description: "Plattformen mit teils expliziten Inhalten (UT1 mixed_adult), z. B. Imageboards.", + examples: [4chan.org], warning: "Enthält auch Plattformen mit überwiegend harmlosem Inhalt."} + - {id: astrology, group: expert, label: "Astrologie und Wahrsagerei", description: "UT1 astrology.", + examples: []} + - {id: bitcoin, group: expert, label: "Kryptowährungen und Mining", + description: "UT1 bitcoin, ShadowWhisperer Cryptocurrency.", + examples: []} + - {id: blogs, group: expert, label: "Blog-Plattformen", description: "UT1 blog.", examples: [], + warning: "Sperrt ganze Blog-Hoster, auch Unterrichtsmaterial auf Blogs."} + - {id: celebrity, group: expert, label: "Promi-Klatsch", description: "UT1 celebrity.", + examples: []} + - {id: cooking, group: expert, label: "Kochen", description: "UT1 cooking.", examples: []} + - {id: fakenews, group: expert, label: "Fake News", + description: "UT1 fakenews, StevenBlack Fake News (marktron).", examples: [], + warning: "Einordnung als Fake News ist eine redaktionelle Entscheidung der Listenpflege."} + - {id: financial, group: expert, label: "Börse und Finanzinformationen", + description: "UT1 financial.", examples: []} + - {id: forums, group: expert, label: "Foren", description: "UT1 forums.", examples: [], + warning: "Sperrt auch Hilfe- und Fachforen."} + - {id: hacking, group: expert, label: "Hacking", description: "UT1 hacking.", examples: []} + - {id: manga, group: expert, label: "Manga und Comics", description: "UT1 manga.", examples: []} + - {id: marketing, group: expert, label: "Marketing-Seiten", description: "UT1 marketingware.", + examples: []} + - {id: mobile, group: expert, label: "Handy-Zubehör, Klingeltöne", description: "UT1 mobile-phone.", + examples: []} + - {id: shopping, group: expert, label: "Online-Shopping", description: "UT1 shopping.", + examples: [], warning: "Sperrt auch Shops, die für Schulmaterial gebraucht werden."} + - {id: sports, group: expert, label: "Sport", description: "UT1 sports.", examples: []} + - {id: popupads, group: expert, label: "Pop-up-Werbung", + description: "Pop-up- und Pop-under-Werbenetze (HaGeZi Pop-Up Ads).", examples: []} + - {id: dyndns, group: expert, label: "Dynamische DNS-Dienste", + description: "Kostenlose Subdomains dynamischer DNS-Anbieter (UT1 dynamic-dns, HaGeZi DynDNS).", + examples: [], warning: "Sperrt auch selbst gehostete Dienste von Vereinen, Lehrkräften oder + Projekten unter solchen Namen."} + - {id: abused_tlds, group: expert, label: "Missbrauchte Top-Level-Domains", + description: "Ganze Endungen, die überwiegend für Spam und Betrug genutzt werden (HaGeZi + Most Abused TLDs).", examples: [], + warning: "Sperrt jede Adresse mit diesen Endungen (z. B. .zip, .xyz-Varianten), auch + seriöse; HaGeZi rät zu einer eigenen Ausnahmeliste."} + - {id: urlshortener, group: expert, label: "Link-Verkürzer", + description: "bit.ly, tinyurl u. a. (HaGeZi URL Shortener, PeterDaveHello, ShadowWhisperer).", + examples: [bit.ly], + warning: "Bricht verkürzte Links in Arbeitsblättern, Mails und QR-Codes."} + +# 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). allow_single_label: entries may be whole +# top-level domains (only for the abused-TLD list). +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 + mixed_adult: mixed_adult + astrology: astrology + bitcoin: bitcoin + blog: blogs + celebrity: celebrity + cooking: cooking + fakenews: fakenews + financial: financial + forums: forums + hacking: hacking + manga: manga + marketingware: marketing + mobile-phone: mobile + shopping: shopping + sports: sports + dynamic-dns: dyndns + - {<<: *hagezi, id: hagezi-nsfw, name: "HaGeZi NSFW", category: porn, min_entries: 10000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/nsfw-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-gambling-medium, name: "HaGeZi Gambling (mittel)", category: gambling, + min_entries: 10000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/gambling.medium-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-gambling-full, name: "HaGeZi Gambling", category: gambling, + min_entries: 100000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/gambling-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-tif-mini, name: "HaGeZi TIF (klein)", category: security, + min_entries: 20000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/tif.mini-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-tif-medium, name: "HaGeZi TIF (mittel)", category: security, + min_entries: 50000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/tif.medium-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-tif-full, name: "HaGeZi TIF", category: security, min_entries: 300000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/tif-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-fake, name: "HaGeZi Fake", category: scam, min_entries: 1000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/fake-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-bypass, name: "HaGeZi DoH/VPN/Tor/Proxy 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, name: "HaGeZi DoH", category: doh, min_entries: 500, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/doh-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-nosafesearch, name: "HaGeZi Safesearch not supported", + category: nosafesearch, min_entries: 20, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/nosafesearch-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-light, name: "HaGeZi Multi Light", category: ads, min_entries: 10000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/light-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-multi, name: "HaGeZi Multi Normal", category: ads, min_entries: 50000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/multi-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-pro, name: "HaGeZi Multi Pro", category: ads, min_entries: 50000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/pro-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-proplus, name: "HaGeZi Multi Pro++", category: ads, min_entries: 50000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/pro.plus-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-microsoft, name: "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, name: "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, name: "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, name: "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, name: "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, name: "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, name: "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-native-tiktok-extended, name: "HaGeZi Native TikTok (erweitert)", + category: telemetry_tiktok, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.tiktok.extended-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-lgwebos, name: "HaGeZi Native LG webOS", category: telemetry_lg, + min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.lgwebos-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-roku, name: "HaGeZi Native Roku", category: telemetry_roku, + min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.roku-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-vivo, name: "HaGeZi Native Vivo", category: telemetry_vivo, + min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.vivo-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-native-oppo, name: "HaGeZi Native OPPO/Realme", + category: telemetry_oppo, min_entries: 10, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/native.oppo-realme-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-social, name: "HaGeZi Social", category: social, min_entries: 500, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/social-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-antipiracy, name: "HaGeZi Anti-Piracy", category: warez, + min_entries: 1000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/anti.piracy-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-popupads, name: "HaGeZi Pop-Up Ads", category: popupads, + min_entries: 1000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/popupads-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-dyndns, name: "HaGeZi DynDNS", category: dyndns, min_entries: 100, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/dyndns-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-spam-tlds, name: "HaGeZi Most Abused TLDs", category: abused_tlds, + min_entries: 10, allow_single_label: true, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/spam-tlds-onlydomains.txt"} + - {<<: *hagezi, id: hagezi-urlshortener, name: "HaGeZi URL Shortener", category: urlshortener, + min_entries: 1000, + url: "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/urlshortener-onlydomains.txt"} + # Further free sources, licences read at the primary source on 2026-11-24 + # (work/linuxmuster-squid/recherche-filterlisten.md, section 7). + - {id: sw-adult, name: "ShadowWhisperer Adult", license: "Unlicense", category: porn, + homepage: "https://github.com/ShadowWhisperer/BlockLists", format: domains, min_entries: 10000, + url: "https://raw.githubusercontent.com/ShadowWhisperer/BlockLists/master/RAW/Adult"} + - {id: sw-gambling, name: "ShadowWhisperer Gambling", license: "Unlicense", category: gambling, + homepage: "https://github.com/ShadowWhisperer/BlockLists", format: domains, min_entries: 1000, + url: "https://raw.githubusercontent.com/ShadowWhisperer/BlockLists/master/RAW/Gambling"} + - {id: sw-malware, name: "ShadowWhisperer Malware", license: "Unlicense", category: security, + homepage: "https://github.com/ShadowWhisperer/BlockLists", format: domains, min_entries: 1000, + url: "https://raw.githubusercontent.com/ShadowWhisperer/BlockLists/master/RAW/Malware"} + - {id: sw-scam, name: "ShadowWhisperer Scam", license: "Unlicense", category: scam, + homepage: "https://github.com/ShadowWhisperer/BlockLists", format: domains, min_entries: 500, + url: "https://raw.githubusercontent.com/ShadowWhisperer/BlockLists/master/RAW/Scam"} + - {id: sw-tunnels, name: "ShadowWhisperer Tunnels", license: "Unlicense", category: vpn_proxy, + homepage: "https://github.com/ShadowWhisperer/BlockLists", format: domains, min_entries: 100, + url: "https://raw.githubusercontent.com/ShadowWhisperer/BlockLists/master/RAW/Tunnels"} + - {id: sw-dns, name: "ShadowWhisperer DNS", license: "Unlicense", category: doh, + homepage: "https://github.com/ShadowWhisperer/BlockLists", format: domains, min_entries: 20, + url: "https://raw.githubusercontent.com/ShadowWhisperer/BlockLists/master/RAW/DNS"} + - {id: sw-urlshortener, name: "ShadowWhisperer URL Shortener", license: "Unlicense", + category: urlshortener, homepage: "https://github.com/ShadowWhisperer/BlockLists", + format: domains, min_entries: 500, + url: "https://raw.githubusercontent.com/ShadowWhisperer/BlockLists/master/RAW/UrlShortener"} + - {id: sw-crypto, name: "ShadowWhisperer Cryptocurrency", license: "Unlicense", category: bitcoin, + homepage: "https://github.com/ShadowWhisperer/BlockLists", format: domains, min_entries: 100, + url: "https://raw.githubusercontent.com/ShadowWhisperer/BlockLists/master/RAW/Cryptocurrency"} + - {id: stevenblack-gambling, name: "StevenBlack Gambling (hostsVN, Sinfonietta)", license: "MIT", + category: gambling, homepage: "https://github.com/StevenBlack/hosts", format: domains, + min_entries: 1000, + url: "https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/gambling-only/hosts"} + - {id: stevenblack-social, name: "StevenBlack Social (Sinfonietta)", license: "MIT", + category: social, homepage: "https://github.com/StevenBlack/hosts", format: domains, + min_entries: 500, + url: "https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/social-only/hosts"} + - {id: stevenblack-fakenews, name: "StevenBlack Fake News (marktron)", license: "MIT", + category: fakenews, homepage: "https://github.com/StevenBlack/hosts", format: domains, + min_entries: 500, + url: "https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-only/hosts"} + - {id: sinfonietta-porn, name: "Sinfonietta Pornography Hosts", license: "MIT", category: porn, + homepage: "https://github.com/Sinfonietta/hostfiles", format: domains, min_entries: 10000, + url: "https://raw.githubusercontent.com/Sinfonietta/hostfiles/master/pornography-hosts"} + - {id: sinfonietta-snuff, name: "Sinfonietta Snuff Hosts", license: "MIT", category: violence, + homepage: "https://github.com/Sinfonietta/hostfiles", format: domains, min_entries: 5, + url: "https://raw.githubusercontent.com/Sinfonietta/hostfiles/master/snuff-hosts"} + - {id: scamblocklist, name: "durablenapkin Scam Blocklist", license: "MIT", category: scam, + homepage: "https://github.com/durablenapkin/scamblocklist", format: domains, min_entries: 200, + url: "https://raw.githubusercontent.com/durablenapkin/scamblocklist/master/hosts.txt"} + - {id: dibdot-doh, name: "dibdot DoH-IP-blocklists (Domains)", license: "GPL-3.0", category: doh, + homepage: "https://github.com/dibdot/DoH-IP-blocklists", format: domains, min_entries: 200, + url: "https://raw.githubusercontent.com/dibdot/DoH-IP-blocklists/master/doh-domains.txt"} + - {id: url-shorteners, name: "PeterDaveHello url-shorteners", license: "CC BY-SA 4.0", + category: urlshortener, homepage: "https://github.com/PeterDaveHello/url-shorteners", + format: domains, min_entries: 200, + url: "https://raw.githubusercontent.com/PeterDaveHello/url-shorteners/master/list"} + - {id: nocoin, name: "NoCoin (Browser-Mining)", license: "MIT", category: security, + homepage: "https://github.com/hoshsadiq/adblock-nocoin-list", format: domains, min_entries: 50, + url: "https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt"} + - id: lmn-nosafesearch + name: "linuxmuster-squid (Ergänzung Suchmaschinen ohne SafeSearch)" + license: "GPL-3.0-or-later" + homepage: "https://github.com/faircomp/linuxmuster-squid" + path: "nosafesearch-extra.domains" + format: domains + category: nosafesearch + min_entries: 1 + # 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", with a preview of the changes); never +# applied automatically (an upgrade changes nothing). Categories not named are switched off; +# variants not named are the defaults. +profiles: + students: + label: "Schüler (Sekundarstufe)" + description: "Jugendschutz, Sicherheit, Umgehungsschutz, SafeSearch streng." + categories: [porn, gambling, violence, drugs, dating, security, scam, vpn_proxy, doh, + nosafesearch] + safesearch: {google: true, youtube: strict, bing: true, duckduckgo: true, ecosia: true, + brave: true} + primary: + label: "Grundschule" + description: "Wie Schüler, dazu Ablenkung, KI-Dienste, Downloads und Werbung gesperrt." + categories: [porn, gambling, violence, drugs, dating, security, scam, vpn_proxy, doh, + nosafesearch, social, games, chat, ai, warez, ads, mixed_adult] + safesearch: {google: true, youtube: strict, bing: true, duckduckgo: true, ecosia: true, + brave: true} + teachers: + label: "Lehrkräfte" + description: "Sicherheit und Umgehungsschutz; kein Jugendschutz (Recherche z. B. zu + Extremismus oder Drogenprävention)." + categories: [security, scam, vpn_proxy, doh] + safesearch: {google: false, youtube: "off", bing: false, duckduckgo: false, ecosia: false, + brave: false} + staff: + label: "Verwaltung und Mitarbeitende" + description: "Sicherheit, Betrug, Werbung (Light) gegen Malvertising, DoH." + categories: [security, scam, doh, ads] + safesearch: {google: false, youtube: "off", bing: false, duckduckgo: false, ecosia: false, + brave: false} + guests: + label: "Gäste-WLAN" + description: "Für eine Instanz der Gastgruppe: Jugendschutz, Sicherheit, Filesharing gesperrt + (Störerhaftung), SafeSearch an; VPN bleibt erlaubt (Firmen-VPN von Gästen)." + categories: [porn, gambling, violence, drugs, security, scam, warez] + safesearch: {google: true, youtube: moderate, bing: true, duckduckgo: true, ecosia: true, + brave: true} diff --git a/controlplane/lmnsquid/docker_service.py b/controlplane/lmnsquid/docker_service.py index 8e72a7d..3ae72c6 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,15 @@ 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" +FILTER_LABEL = "org.faircomp.linuxmuster-squid.filter" +# 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 +115,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 +125,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 +228,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 +272,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 +458,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). @@ -493,6 +535,7 @@ def status(self, name: str) -> dict[str, Any]: image_obj = container.image if image_obj is not None and image_obj.tags: image = image_obj.tags[0] + labels = (getattr(image_obj, "labels", None) or {}) if image_obj is not None else {} return { "name": name, @@ -500,6 +543,8 @@ def status(self, name: str) -> dict[str, Any]: "running": running, "health": health, "image": image, + # the data-plane image has the category filter (label set by image/Dockerfile) + "filter_capable": bool(labels.get(FILTER_LABEL)), } def logs( diff --git a/controlplane/lmnsquid/filterdecision.py b/controlplane/lmnsquid/filterdecision.py new file mode 100644 index 0000000..509cfb9 --- /dev/null +++ b/controlplane/lmnsquid/filterdecision.py @@ -0,0 +1,365 @@ +# 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, the + chosen variant (sources / strictness) per category, schedules, the categories that fail + closed and the time zone; +* 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 -> bit mask of *feeds* (one feed = one source + for one category), with the variants of every category; +* the admin's own categories: ``custom/.domains`` next to the catalog, with their labels in + ``custom/categories.json``. + +Order: exceptions -> search engines whose SafeSearch has no address -> protected list -> +categories (in the instance's order). 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 = 2 +FILTER_FORMAT = 1 +DAYS = ("mo", "tu", "we", "th", "fr", "sa", "su") +OWN_PREFIX = "own_" +# Decisions. BLOCKING ones block the request; the others let it pass to the rest of squid's chain. +EXCEPTION = "exception" +PROTECTED = "protected" +CATEGORY = "category" +CATALOG_UNAVAILABLE = "catalog_unavailable" +SAFESEARCH_UNAVAILABLE = "safesearch_unavailable" +NONE = "none" +BLOCKING = (CATEGORY, CATALOG_UNAVAILABLE, SAFESEARCH_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], 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 + + +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) + variants: dict[str, str] = field(default_factory=dict) + schedules: dict[str, list[dict[str, Any]]] = field(default_factory=dict) + fail_closed: frozenset[str] = frozenset() + timezone: str = "UTC" + allowed: frozenset[str] = frozenset() + # host names of search engines with SafeSearch switched on but no address to send them to: + # blocked rather than reachable unfiltered + safesearch_block: 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: + """Unknown keys are ignored (a test build wrote ``exam``; it has no meaning now).""" + if data.get("format") != FILTER_FORMAT: + raise ValueError(f"format {data.get('format')!r}, expected {FILTER_FORMAT}") + return cls( + categories=[str(c) for c in data.get("categories") or []], + variants={str(k): str(v) for k, v in (data.get("variants") or {}).items()}, + 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"), + allowed=allowed, + safesearch_block=frozenset(str(h).lower() for h in data.get("safesearch_block") or []), + ) + + 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.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}: lmnsquid catalog update" + ) + self.built = float(meta.get("built") or 0) + self.labels: dict[str, str] = {} + self.default_variant: dict[str, str] = {} + for cat_id, label, default in self.db.execute("SELECT id, label, defvar FROM cats"): + self.labels[str(cat_id)] = str(label) + self.default_variant[str(cat_id)] = str(default or "") + # feed bit -> (source, category) + self.feeds: dict[int, tuple[str, str]] = { + int(bit): (str(src), str(cat)) + for bit, src, cat in self.db.execute("SELECT bit, source, category FROM feeds") + } + self.variants: dict[str, dict[str, set[str]]] = {} + for cat, variant, src in self.db.execute("SELECT category, variant, source FROM vars"): + self.variants.setdefault(str(cat), {}).setdefault(str(variant), set()).add(str(src)) + self.sources: dict[str, tuple[str, str]] = { + str(sid): (str(name), str(lic)) + for sid, name, lic in self.db.execute("SELECT id, name, license FROM srcs") + } + self._masks: dict[tuple[str, str], int] = {} + + def mask(self, category: str, variant: str | None = None) -> int: + """Feed bits of ``category`` in ``variant`` (unknown/None: the default variant). + + A variant names sources; a source feeding the category that no variant names (an + admin's own source for it) counts in every variant. + """ + variants = self.variants.get(category) or {} + if variant not in variants: + variant = self.default_variant.get(category, "") + key = (category, variant or "") + found = self._masks.get(key) + if found is not None: + return found + chosen = variants.get(variant or "", set()) + named = set().union(*variants.values()) if variants else set() + mask = 0 + for bit, (src, cat) in self.feeds.items(): + if cat == category and (not variants or src in chosen or src not in named): + mask |= 1 << bit + self._masks[key] = mask + return mask + + def lookup(self, host: str, parts: list[str] | None = None) -> tuple[int, dict[str, int]]: + """(feed mask, {listed name: its feed mask}) of ``host``.""" + names = parts or suffixes(host) + marks = ",".join("?" * len(names)) + fmask = 0 + hits: dict[str, int] = {} + for name, blob in self.db.execute(f"SELECT n, f FROM d WHERE n IN ({marks})", names): + value = int.from_bytes(blob, "little") + fmask |= value + hits[str(name)] = value + return fmask, hits + + def close(self) -> None: + self.db.close() + + +def read_custom(directory: str) -> tuple[dict[str, frozenset[str]], dict[str, str]]: + """The admin's own categories next to the catalog: ({id: names}, {id: label}).""" + lists: dict[str, frozenset[str]] = {} + labels: dict[str, str] = {} + try: + with open(os.path.join(directory, "categories.json"), encoding="utf-8") as fh: + data = json.load(fh) + labels = {str(k): str(v) for k, v in (data or {}).items()} + except (OSError, ValueError, AttributeError): + labels = {} + try: + entries = os.listdir(directory) + except OSError: + return lists, labels + for entry in entries: + if entry.startswith(OWN_PREFIX) and entry.endswith(".domains"): + lists[entry[: -len(".domains")]] = read_domains(os.path.join(directory, entry)) + return lists, labels + + +@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 = "", + custom: dict[str, frozenset[str]] | None = None, +) -> 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) + parts = suffixes(host) + entry = listed(host, policy.allowed, parts) + if entry: + return Decision(EXCEPTION, entry=entry) + if host in policy.safesearch_block: + return Decision(SAFESEARCH_UNAVAILABLE, category="safesearch", entry=host) + active = policy.active_categories(now) + if not active: + return Decision(NONE) + protected = _protected(catalog, now) + entry = listed(host, protected, parts) + if entry: + return Decision(PROTECTED, entry=entry) + custom = custom or {} + fmask, hits = catalog.lookup(host, parts) if catalog is not None else (0, {}) + for category in active: + own = custom.get(category) + if own is not None: + entry = listed(host, own, parts) + if entry: + return Decision(CATEGORY, category=category, entry=entry) + if catalog is None: + continue + mask = catalog.mask(category, policy.variants.get(category)) + if fmask & mask: + entry = next((n for n, f in hits.items() if f & mask), None) + return Decision(CATEGORY, category=category, entry=entry) + if not mask and own is None and category in policy.fail_closed: + # youth protection whose lists never reached the catalog (refused or not yet + # downloaded): closed, as without a catalog + return Decision( + CATALOG_UNAVAILABLE, + category=category, + detail=f"no list of {category} in the catalog yet", + ) + 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}") + return Decision(NONE) + + +# 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: + base = catalog_dir or (os.path.dirname(catalog.path) if catalog else "") + return os.path.join(base, "protected.domains") + + +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: + 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. +PROTECTED_FILE: str | None = None diff --git a/controlplane/lmnsquid/filters.py b/controlplane/lmnsquid/filters.py new file mode 100644 index 0000000..d2a4b18 --- /dev/null +++ b/controlplane/lmnsquid/filters.py @@ -0,0 +1,530 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Filter settings of one instance: categories with variants, schedules, SafeSearch, exceptions. + +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" +_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") +# Ecosia: "www.ecosia.org is a CNAME to strict-safe-search.ecosia.org" (support article 562, +# 2026-02-11); Brave: "search.brave.com IN CNAME forcesafe.search.brave.com", the main name only +# (safe.search.brave.com/help/safesearch). Certificates via both addresses verified 2026-11-24. +ECOSIA_VIP = "strict-safe-search.ecosia.org" +ECOSIA_HOSTS = ("www.ecosia.org", "ecosia.org") +BRAVE_VIP = "forcesafe.search.brave.com" +BRAVE_HOSTS = ("search.brave.com",) +# Last resort when neither a lookup nor an earlier one gave an address: the addresses the +# services document (Google's example; Ecosia's A record). Bing, DuckDuckGo and Brave document +# none: without an address their search is blocked instead (see safesearch_hosts). +FALLBACK = { + GOOGLE_VIP: "216.239.38.120", + "restrict.youtube.com": "216.239.38.120", + "restrictmoderate.youtube.com": "216.239.38.119", + ECOSIA_VIP: "77.73.113.2", +} +ADDRESSES_FILE = ".safesearch-addresses.json" # host-wide last known addresses + + +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] != "#"] + + +DEFAULT_TIMEZONE = "Europe/Berlin" + + +def valid_timezone(name: str | None) -> str: + """``name`` if the system knows the zone, else the default (with schedules in mind).""" + try: + from zoneinfo import ZoneInfo + + ZoneInfo(str(name)) + return str(name) + except Exception: # noqa: BLE001 - unknown zone, no tzdata, None + return DEFAULT_TIMEZONE + + +# ------------------------------------------------------------------------------- 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 + ecosia: bool = False + brave: bool = False + + @property + def on(self) -> bool: + return ( + self.google + or self.youtube != "off" + or self.bing + or self.duckduckgo + or self.ecosia + or self.brave + ) + + +class FilterSettings(BaseModel): + """Body of ``PUT /v1/instances/{name}/filter``. + + ``variants``: the chosen variant (sources / strictness) per category; a category without an + entry uses its default. The API checks ids against the catalog configuration. + """ + + categories: list[str] = [] + variants: dict[str, 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} + # a variant of a category that is off is kept: switching it on again restores it + return self + + +# ------------------------------------------------------------------------------- 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 = valid_timezone(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", "variants", "schedules", "safesearch") + if k in data + } + ) + + def write(self, name: str, settings: FilterSettings, fail_closed: set[str]) -> dict[str, Any]: + """Write ``filter.json`` and ``safesearch.hosts``; return what was written. + + Keys of an older test build (``exam``) are not carried over. + """ + self.lists.ensure(name) + previous = self.read(name) or {} + resolved, hosts, unresolved = self.safesearch_hosts( + settings.safesearch, previous.get("resolved") + ) + data = { + "format": fd.FILTER_FORMAT, + "categories": settings.categories, + "variants": dict(settings.variants), + "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, + "resolved": resolved, + # enabled SafeSearch targets without any address: blocked, not left unfiltered + "safesearch_unresolved": sorted(unresolved), + "safesearch_block": sorted({h for hs in unresolved.values() for h in hs}), + "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, unresolved = 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 and sorted(unresolved) == (data.get("safesearch_unresolved") or []): + return False + data["resolved"] = resolved + data["safesearch_unresolved"] = sorted(unresolved) + data["safesearch_block"] = sorted({h for hs in unresolved.values() for h in hs}) + _atomic_write(target, hosts) + _atomic_write(self.path(name), json.dumps(data, indent=1) + "\n") + return True + + def _host_addresses(self) -> dict[str, str]: + try: + data = json.loads((self.lists.root / ADDRESSES_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return {str(k): str(v) for k, v in data.items()} if isinstance(data, dict) else {} + + def safesearch_hosts( + self, safesearch: SafeSearch, known: dict[str, str] | None + ) -> tuple[dict[str, str], str, dict[str, tuple[str, ...]]]: + """(resolved VIP addresses, content of safesearch.hosts, {engine: its host names} of the + enabled engines without any address) for ``safesearch``. + + An address comes from a lookup now, else from the last one that worked on this host or + for this instance (both kept), else from the address the service documents. + """ + known = {**self._host_addresses(), **dict(known or {})} + resolved: dict[str, str] = {} + looked_up: dict[str, str] = {} + + def address(vip: str) -> str | None: + now = self.resolver(vip) + if now: + looked_up[vip] = now + found = now or known.get(vip) or FALLBACK.get(vip) + if found: + resolved[vip] = found + return found + + lines: list[str] = [] + unresolved: dict[str, tuple[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 engine, on, vip, hosts in ( + ("bing", safesearch.bing, BING_VIP, BING_HOSTS), + ("duckduckgo", safesearch.duckduckgo, DDG_VIP, DDG_HOSTS), + ("ecosia", safesearch.ecosia, ECOSIA_VIP, ECOSIA_HOSTS), + ("brave", safesearch.brave, BRAVE_VIP, BRAVE_HOSTS), + ): + if on: + ip = address(vip) + if ip: + lines += [f"{ip} {host}" for host in hosts] + else: + unresolved[engine] = hosts + if looked_up: + merged = {**self._host_addresses(), **looked_up} + try: + _atomic_write(self.lists.root / ADDRESSES_FILE, json.dumps(merged, indent=1)) + except OSError: + pass # only the memory of the last addresses is lost + # 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), unresolved + + +# ------------------------------------------------------------------------------- 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): + active category ids, their variants, which of them run on a schedule, the problem.""" + empty = { + "configured": False, + "categories": 0, + "active": [], + "variants": {}, + "scheduled": [], + "safesearch": {}, + "problem": None, + } + if data is None: + return empty + if data.get("broken"): + return {**empty, "configured": True, "problem": "broken"} + cats = [str(c) for c in data.get("categories") or []] + problem = None + unresolved = [str(e) for e in data.get("safesearch_unresolved") or []] + if cats: + 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" + elif catalog_info.get("problems_old"): + problem = "catalog_lists_old" + if problem is None and unresolved: + problem = "safesearch_unresolved" + return { + "configured": True, + "categories": len(cats), + "active": cats, + "variants": {k: v for k, v in (data.get("variants") or {}).items() if k in cats}, + "scheduled": [c for c in cats if (data.get("schedules") or {}).get(c)], + "safesearch": data.get("safesearch") or {}, + "problem": problem, + # why the catalog is unusable (e.g. an older format), for the WebUI's message + "problem_detail": ( + catalog_info.get("error") + if problem and "missing" in problem + else ", ".join(unresolved) + if problem == "safesearch_unresolved" + else None + ), + } + + +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) + custom, custom_labels = fd.read_custom(str(catalog_dir / catalog_mod.CUSTOM_DIR)) + labels = {**labels, **custom_labels} + 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") + listed_in: dict[str, dict[str, Any]] = {} + sources: dict[str, dict[str, str]] = {} + try: + verdict = fd.decide(name, policy, cat, now, error, custom) + if cat is not None: + _fmask, hits = cat.lookup(name) + for entry, fmask in hits.items(): + for bit, (src, cid) in cat.feeds.items(): + if not fmask & (1 << bit): + continue + row = listed_in.setdefault( + cid, + { + "category": cid, + "label": labels.get(cid, cid), + "active": cid in policy.categories, + "entries": set(), + "sources": set(), + "in_variant": False, + "variants": set(), + }, + ) + row["entries"].add(entry) + row["sources"].add(src) + if fmask & cat.mask(cid, policy.variants.get(cid)): + row["in_variant"] = True + for variant in cat.variants.get(cid) or {}: + if fmask & (1 << bit) & cat.mask(cid, variant): + row["variants"].add(variant) + sname, lic = cat.sources.get(src, (src, "?")) + sources[src] = {"id": src, "name": sname, "license": lic} + for cid, names in custom.items(): + own_entry = fd.listed(name, names) + if own_entry: + listed_in[cid] = { + "category": cid, + "label": labels.get(cid, cid), + "active": cid in policy.categories, + "entries": {own_entry}, + "sources": {"own"}, + "in_variant": True, + "variants": set(), + } + 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": [ + { + **row, + "entries": sorted(row["entries"]), + "sources": sorted(row["sources"]), + "variants": sorted(row["variants"]), + } + for row in listed_in.values() + ], + "sources": list(sources.values()), + "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/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..8cfe4f2 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"]: @@ -143,6 +156,8 @@ def status(self, name: str) -> dict[str, Any]: "running": bool(container["running"]), "health": container["health"], "image": container["image"], + # an image tagged "old" stands for one without the category filter (ADR-022) + "filter_capable": "old" not in container["image"], } def logs( @@ -190,6 +205,12 @@ 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"), + catalog_custom=str(tmp_path / "catalog-custom.yml"), + protected_file=str(tmp_path / "protected.domains"), + filter_timezone="Europe/Berlin", ) @@ -256,3 +277,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..6bfb155 --- /dev/null +++ b/controlplane/tests/test_catalog.py @@ -0,0 +1,749 @@ +# 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", allow lists and those whose block harms (research 2.1, 7) + ut1 = next(s for s in config.sources if s["id"] == "ut1") + for never in ( + "examen_pix", + "tricheur_pix", + "update", + "liste_blanche", + "liste_bu", + "child", + "educational_games", + "jobsearch", + "webmail", + "remote-control", + "shortener", + "bank", + "press", + "radio", + "translation", + "sexual_education", + "cleaning", + "webhosting", + ): + assert never not in ut1["map"] + # the remaining UT1 categories are offered as experts, with a warning where the research + # sees false positives + assert config.category("mixed_adult")["group"] == "expert" + assert config.category("mixed_adult")["warning"] + for profile in ("students", "primary", "teachers", "staff", "guests"): + assert set(config.profiles[profile]["categories"]) <= set(ids) + assert config.profiles[profile]["label"] + licences = {s["license"] for s in config.sources} + assert licences >= {"CC BY-SA 4.0", "GPL-3.0", "MIT", "Unlicense"} + for cat in config.categories: + assert cat.get("description") is not None, cat["id"] + variants = cat.get("variants") or [] + if variants: + assert sum(1 for v in variants if v.get("default")) == 1, cat["id"] + for v in variants: + assert set(v["sources"]) <= {s["id"] for s in config.sources}, (cat["id"], v) + # strict levels carry a warning + ads = {v["id"]: v for v in config.category("ads")["variants"]} + assert ads["light"]["default"] and ads["pro"]["warning"] and ads["proplus"]["warning"] + assert config.sources_for("ads") == ["hagezi-light"] + assert config.sources_for("ads", "pro") == ["hagezi-pro"] + + +def test_only_needed_sources_are_downloaded() -> None: + config = cm.load_config() + base = set(cm.needed_sources(config, [])) + assert {"ut1", "hagezi-light", "hagezi-tif-medium", "hagezi-nsfw"} <= base + # stricter variants and expert categories only once an instance uses them + assert not {"hagezi-pro", "hagezi-tif-full", "hagezi-spam-tlds", "sw-adult"} & base + used = set( + cm.needed_sources( + config, + [ + {"categories": ["ads", "abused_tlds"], "variants": {"ads": "pro"}}, + ], + ) + ) + assert {"hagezi-pro", "hagezi-spam-tlds"} <= used + # an admin's own source is always fetched + config.sources.append({"id": "own-x", "origin": "custom", "category": "ads"}) + assert "own-x" in cm.needed_sources(config, []) + + +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: + fmask, hits = cat.lookup("www.a.example") + assert fmask & cat.mask("porn") and fmask & cat.mask("ads") + assert set(hits) == {"a.example"} + feeds = {c: n for _s, c, n in cat.db.execute("SELECT source, category, count FROM feeds")} + assert feeds == {"porn": 2, "ads": 2} + assert cat.mask("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({"ut1/porn": 600}, {"ut1/porn": 1000}) + cm.check_shrink({"ut1/ai": 10}, {"ut1/ai": 90}) # small feeds may move freely + with pytest.raises(cm.CatalogError, match="shrink"): + cm.check_shrink({"ut1/porn": 499}, {"ut1/porn": 1000}) + # a feed nobody uses any more is not built: that is no shrink + cm.check_shrink({}, {"hagezi-pro/ads": 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 + variant = porn["variants"][0] + assert variant["default"] and variant["sources"][-1]["license"] == "CC0" + assert variant["sources"][-1]["in_catalog"] and variant["sources"][-1]["count"] == 300 + assert porn["description"] and porn["examples"] and porn["fail_closed"] + expert = next(c for c in info["categories"] if c["id"] == "abused_tlds") + assert expert["expert"] and expert["warning"] + 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/") + + +def test_single_labels_only_for_a_tld_list(tmp_path: Path) -> None: + assert cm.parse_line("zip", "domains") is None + assert cm.parse_line("zip", "domains", allow_single_label=True) == "zip" + path = tmp_path / "tlds.txt" + path.write_text("# TLDs\nzip\nmov\n") + src = {"id": "t", "format": "domains", "category": "abused_tlds", "allow_single_label": True} + assert sorted(cm.iter_source(src, str(path))) == [ + ("mov", "abused_tlds"), + ("zip", "abused_tlds"), + ] + + +def test_unchanged_inputs_skip_the_rebuild(tmp_path: Path) -> None: + paths = _paths(tmp_path, _local_sources(tmp_path, 300)) + first = cm.update(paths) + assert first["state"] == "ok" and not first.get("unchanged") + built = os.readlink(paths.catalog_dir / cm.CURRENT) + second = cm.update(paths) + assert second["state"] == "ok" and second["unchanged"] is True + assert os.readlink(paths.catalog_dir / cm.CURRENT) == built + info = cm.status(paths) + assert info["checked"] >= info["built"] and not info["old"] + # a changed source, a changed configuration: built again + time.sleep(1.05) + (tmp_path / "lists" / "p.domains").write_text("".join(f"p{i}.example\n" for i in range(301))) + assert not cm.update(paths).get("unchanged") + time.sleep(1.05) + admin = yaml.safe_load(Path(paths.admin_config).read_text()) + admin["categories"] = [{"id": "porn", "label": "Porno (geändert)"}] + Path(paths.admin_config).write_text(yaml.safe_dump(admin)) + assert not cm.update(paths).get("unchanged") + + +def test_a_confirmed_old_catalog_is_not_old(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() + paths = _paths(tmp_path) + paths.cache_dir.mkdir() + (paths.cache_dir / cm.STATUS).write_text( + json.dumps({"state": "ok", "last_success": time.time()}) + ) + assert not cm.status(paths)["old"] + + +# ---------------------------------------------------------------- one bad source, not all +def _url_world(tmp_path: Path, monkeypatch: Any, files: dict[str, list[str] | None]) -> cm.Paths: + """Two URL sources (ads, porn) and a fake fetch: a list = a download of these names, + None = the download fails. ``files`` is read at every update.""" + from lmnsquid.catalog import load_config + + admin = { + "disable_sources": [s["id"] for s in load_config().sources], + "sources": [ + { + "id": "u-ads", + "name": "U ads", + "license": "CC0", + "format": "domains", + "category": "ads", + "url": "https://l.example/ads", + "min_entries": 3, + }, + { + "id": "u-porn", + "name": "U porn", + "license": "CC0", + "format": "domains", + "category": "porn", + "url": "https://l.example/porn", + "min_entries": 3, + }, + ], + } + paths = _paths(tmp_path, admin) + + def fake_fetch(src: dict[str, Any], cache_dir: Path, state: dict[str, Any]) -> tuple[str, str]: + names = files.get(src["id"]) + target = cache_dir / f"{src['id']}.download" + if names is None: + raise cm.CatalogError( + f"{src['id']}: download failed (HTTP 503) and no earlier download" + ) + target.write_text("".join(f"{n}\n" for n in names)) + state[src["id"]] = {"url": src["url"]} + return str(target), "downloaded" + + monkeypatch.setattr(cm, "fetch", fake_fetch) + return paths + + +def _names(paths: cm.Paths, host: str) -> set[str]: + cat = fd.Catalog(str(paths.catalog_dir / cm.CURRENT)) + try: + fmask, _hits = cat.lookup(host) + return {c for b, (_s, c) in cat.feeds.items() if fmask & (1 << b)} + finally: + cat.close() + + +def test_a_bad_source_keeps_its_last_good_data_and_the_rest_is_built( + tmp_path: Path, monkeypatch: Any +) -> None: + files: dict[str, list[str] | None] = { + "u-ads": [f"ad{i}.example" for i in range(200)], + "u-porn": [f"p{i}.example" for i in range(200)], + } + paths = _url_world(tmp_path, monkeypatch, files) + assert cm.update(paths)["state"] == "ok" + # porn's list collapses (shrink), ads gets a new entry: ads is rebuilt, porn stays as it was + files["u-porn"] = ["p0.example"] + files["u-ads"] = [*files["u-ads"], "new-ad.example"] # type: ignore[misc] + result = cm.update(paths) + assert result["state"] == "ok", result + assert [p["source"] for p in result["problems"]] == ["u-porn"] + assert ( + result["problems"][0]["state"] == "stale" + and "fewer than min_entries" in (result["problems"][0]["error"]) + ) + assert _names(paths, "new-ad.example") == {"ads"} + assert _names(paths, "p150.example") == {"porn"} # the last good porn list + # the refused download is forgotten (no 304 for it), the good copy stays + assert not (paths.cache_dir / "u-porn.download").exists() + assert (paths.cache_dir / "u-porn.good").exists() + # status names it with its age; the next failing run keeps "since" + info = cm.status(paths) + assert info["problems"][0]["source"] == "u-porn" and not info["problems_old"] + since = info["problems"][0]["since"] + files["u-porn"] = None # now the download fails as well + result = cm.update(paths) + assert result["problems"][0]["since"] == since + assert result["problems"][0]["state"] == "stale" + assert _names(paths, "p150.example") == {"porn"} + # a week later it is an old problem + health = json.loads((paths.cache_dir / "feeds-state.json").read_text()) + health["u-porn"]["since"] -= 8 * 86400 + (paths.cache_dir / "feeds-state.json").write_text(json.dumps(health)) + cm.update(paths) + assert cm.status(paths)["problems_old"] + # fixed: the problem disappears + files["u-porn"] = [f"p{i}.example" for i in range(200)] + assert cm.update(paths)["problems"] == [] + assert cm.status(paths)["problems"] == [] + + +def test_a_source_that_never_had_data_is_left_out(tmp_path: Path, monkeypatch: Any) -> None: + files: dict[str, list[str] | None] = { + "u-ads": [f"ad{i}.example" for i in range(10)], + "u-porn": ["only-one.example"], + } + paths = _url_world(tmp_path, monkeypatch, files) + result = cm.update(paths) + assert result["state"] == "ok" + assert result["problems"][0]["source"] == "u-porn" + assert result["problems"][0]["state"] == "missing" + cat = fd.Catalog(str(paths.catalog_dir / cm.CURRENT)) + try: + assert cat.mask("porn") == 0 and cat.mask("ads") + # youth protection without any list: closed, like without a catalog + policy = fd.Policy.from_dict( + {"format": 1, "categories": ["porn"], "fail_closed": ["porn"]}, frozenset() + ) + verdict = fd.decide("anything.example", policy, cat, time.time()) + assert verdict.decision == "catalog_unavailable" and "no list" in verdict.detail + ads_only = fd.Policy.from_dict({"format": 1, "categories": ["ads"]}, frozenset()) + assert not fd.decide("anything.example", ads_only, cat, time.time()).blocked + finally: + cat.close() + + +def test_every_source_failing_keeps_the_active_catalog(tmp_path: Path, monkeypatch: Any) -> None: + files: dict[str, list[str] | None] = {"u-ads": None, "u-porn": None} + paths = _url_world(tmp_path, monkeypatch, files) + result = cm.update(paths) + assert result["state"] == "failed" and not (paths.catalog_dir / cm.CURRENT).exists() + + +def test_unused_sources_leave_catalog_and_cache(tmp_path: Path, monkeypatch: Any) -> None: + """Point 5 of the lab retest: no instance uses an expert list any more -> the next run + builds without it and drops its downloads.""" + config = cm.load_config() + lists = tmp_path / "lists" + (lists / "s-students").mkdir(parents=True) + selection = lists / "s-students" / "filter.json" + selection.write_text(json.dumps({"categories": ["ads"], "variants": {"ads": "pro"}})) + assert "hagezi-pro" in cm.needed_sources(config, cm.selections_of(lists)) + sizes = {"hagezi-light": 10_000, "hagezi-pro": 50_000} # their min_entries + files = {s: [f"{s}-{i}.example" for i in range(n)] for s, n in sizes.items()} + + def fake_fetch(src: dict[str, Any], cache_dir: Path, state: dict[str, Any]) -> tuple[str, str]: + target = cache_dir / f"{src['id']}.download" + target.write_text("".join(f"{n}\n" for n in files.get(src["id"], []))) + state[src["id"]] = {"url": src.get("url")} + return str(target), "downloaded" + + monkeypatch.setattr(cm, "fetch", fake_fetch) + monkeypatch.setattr( + cm, + "needed_sources", + lambda c, sel: [ + s + for s in ("hagezi-light", "hagezi-pro") + if s == "hagezi-light" + or any((x.get("variants") or {}).get("ads") == "pro" for x in sel) + ], + ) + paths = cm.Paths(tmp_path / "catalog", tmp_path / "cache", blocklists_dir=lists) + assert cm.update(paths)["state"] == "ok" + assert _names(paths, "hagezi-pro-1.example") == {"ads"} + assert (paths.cache_dir / "hagezi-pro.good").exists() + selection.write_text(json.dumps({"categories": ["ads"]})) + result = cm.update(paths) + assert result["state"] == "ok" and not result.get("unchanged") + assert _names(paths, "hagezi-pro-1.example") == set() + assert not any(p.name.startswith("hagezi-pro.") for p in paths.cache_dir.iterdir()) + state = json.loads((paths.cache_dir / "sources-state.json").read_text()) + assert "hagezi-pro" not in state + + +def test_a_source_refused_again_with_the_same_bytes_builds_nothing( + tmp_path: Path, monkeypatch: Any +) -> None: + files: dict[str, list[str] | None] = { + "u-ads": [f"ad{i}.example" for i in range(10)], + "u-porn": ["only-one.example"], + } + paths = _url_world(tmp_path, monkeypatch, files) + assert cm.update(paths)["problems"][0]["source"] == "u-porn" + built = os.readlink(paths.catalog_dir / cm.CURRENT) + time.sleep(1.05) # a new download gets a new mtime; only the content counts + again = cm.update(paths) + assert again["unchanged"] is True and again["problems"][0]["source"] == "u-porn" + assert os.readlink(paths.catalog_dir / cm.CURRENT) == built + + +def test_search_engines_without_safesearch_are_completed() -> None: + config = cm.load_config() + assert "lmn-nosafesearch" in config.sources_for("nosafesearch") + path = cm.DATA_DIR / "nosafesearch-extra.domains" + names = set(fd.read_domains(str(path))) + assert {"startpage.com", "qwant.com", "mojeek.com"} <= names + # forced through SafeSearch instead of blocked + assert not names & {"ecosia.org", "search.brave.com", "bing.com", "duckduckgo.com"} + assert config.profiles["students"]["safesearch"]["ecosia"] is True diff --git a/controlplane/tests/test_cli.py b/controlplane/tests/test_cli.py index 37ce07e..ed1419b 100644 --- a/controlplane/tests/test_cli.py +++ b/controlplane/tests/test_cli.py @@ -191,3 +191,141 @@ 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, "set", "--variant", "ads=pro", "--add", "ads"]) + assert r.exit_code == 0, r.output + data = _json.loads((Path(settings.blocklists_dir) / name / "filter.json").read_text()) + assert data["variants"] == {"ads": "pro"} + assert runner.invoke(cli.app, ["filter", name, "set", "--variant", "ads"]).exit_code == 2 + # profile preview: what changes, nothing written + before = (Path(settings.blocklists_dir) / name / "filter.json").read_text() + r = runner.invoke(cli.app, ["filter", name, "profile", "teachers", "--dry-run"]) + assert r.exit_code == 0, r.output + diff = _json.loads(r.output) + assert "porn" in diff["categories_off"] and "scam" not in diff["categories_off"] + assert diff["safesearch"]["youtube"] == ["moderate", "off"] + assert (Path(settings.blocklists_dir) / name / "filter.json").read_text() == before + # own categories and sources + own = ["catalog", "own"] + assert ( + runner.invoke(cli.app, [*own, "add-category", "own_x", "--label", "Eigene"]).exit_code == 0 + ) + r = runner.invoke( + cli.app, [*own, "domains", "own_x", "--add", "a.example", "--add", "b.example"] + ) + assert r.exit_code == 0 and "a.example" in r.output + r = runner.invoke(cli.app, [*own, "domains", "own_x", "--remove", "a.example"]) + assert '"a.example"' not in r.output + r = runner.invoke( + cli.app, + [ + *own, + "add-source", + "own-l", + "--url", + "https://l.example/x", + "--category", + "own_x", + "--license", + "CC0", + ], + ) + assert r.exit_code == 0, r.output + assert "own-l" in runner.invoke(cli.app, [*own, "show"]).output + assert runner.invoke(cli.app, [*own, "remove-source", "own-l"]).exit_code == 0 + assert runner.invoke(cli.app, [*own, "remove-category", "own_x"]).exit_code == 0 + r = runner.invoke(cli.app, ["catalog", "categories"]) + assert r.exit_code == 0 and "Werbung und Tracking" in r.output and "* light" in r.output + 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 + + +def test_errors_are_readable_lines() -> None: + pydantic = ( + '{"detail": [{"type": "value_error", "loc": ["body", "schedules", "social", 0], ' + '"msg": "Value error, start must be before end", "input": {}}]}' + ) + assert cli.error_lines(422, pydantic) == [ + "error 422: schedules.social.0: start must be before end" + ] + assert cli.error_lines(422, '{"detail": "unknown categories: nope"}') == [ + "error 422: unknown categories: nope" + ] + assert cli.error_lines(502, "Bad Gateway") == ["error 502: Bad Gateway"] + + +def test_cli_shows_422_without_raw_json( + patch_client: None, client: Any, auth_headers: dict[str, str], instance_data: dict[str, Any] +) -> None: + client.post("/v1/instances", json=instance_data, headers=auth_headers) + r = runner.invoke(cli.app, ["filter", "default-school-teachers", "set", "--add", "nope"]) + assert r.exit_code == 1 and "error 422: unknown categories: nope" in r.output + assert '{"detail"' not in r.output + + +def test_cli_prints_the_warnings( + patch_client: None, client: Any, auth_headers: dict[str, str], instance_data: dict[str, Any] +) -> None: + client.post("/v1/instances", json=instance_data, headers=auth_headers) + r = runner.invoke( + cli.app, + ["filter", "default-school-teachers", "set", "--add", "ads", "--variant", "ads=pro"], + ) + assert r.exit_code == 0, r.output + assert "warning: Werbung und Tracking (Pro):" in r.output diff --git a/controlplane/tests/test_docker_integration.py b/controlplane/tests/test_docker_integration.py index f438fe0..d8b675d 100644 --- a/controlplane/tests/test_docker_integration.py +++ b/controlplane/tests/test_docker_integration.py @@ -41,7 +41,9 @@ def test_real_container_lifecycle(tmp_path: Path) -> None: (secrets / "it.keytab").write_bytes(b"dummy-keytab-not-valid") lists = tmp_path / "lists" - svc = DockerService(secrets_dir=str(secrets), blocklists_dir=str(lists)) + svc = DockerService( + secrets_dir=str(secrets), blocklists_dir=str(lists), catalog_dir=str(tmp_path / "catalog") + ) inst = Instance( school="it", role="teachers", @@ -104,6 +106,75 @@ def test_real_container_lifecycle(tmp_path: Path) -> None: assert svc.status(inst.name)["exists"] is False +def test_real_filter_mount_reload_and_stats(tmp_path: Path) -> None: + """ADR-022 with the real DockerService and the image under test: the catalog directory is + mounted, the filter is recognised, applied by reload, and the statistics read by exec.""" + from conftest import make_catalog + + from lmnsquid.docker_service import DockerService + from lmnsquid.filters import FilterSettings, SafeSearch + from lmnsquid.models import Instance + + secrets = tmp_path / "secrets" + secrets.mkdir() + (secrets / "it.keytab").write_bytes(b"dummy-keytab-not-valid") + lists, catalog = tmp_path / "lists", tmp_path / "catalog" + make_catalog(catalog, {"porn": ["adult.example"]}, work=tmp_path / "work") + for directory in (catalog, tmp_path): + directory.chmod(0o755) # squid's helper reads them as user proxy + svc = DockerService( + secrets_dir=str(secrets), blocklists_dir=str(lists), catalog_dir=str(catalog) + ) + svc.filters.resolver = lambda _name: "216.239.38.120" + inst = Instance( + school="itf", + role="students", + ad_group="students", + realm="EXAMPLE.INTERNAL", + visible_hostname="squid-itf.example.internal", + http_port=3195, + keytab_secret="it.keytab", + cache_size_mb=100, + image=IMAGE, + ) + svc.remove(inst.name) + try: + svc.ensure_running(inst) + container = svc.client.containers.get(inst.container_name) + mounts = {m["Destination"]: m for m in container.attrs["Mounts"]} + assert mounts["/etc/squid/catalog"]["RW"] is False + assert svc.filter_active(inst.name) is True + # the status tells a filtering image from an older one (cold check 2026-11-24) + assert svc.status(inst.name)["filter_capable"] is True + svc.filters.write( + inst.name, + FilterSettings(categories=["porn"], safesearch=SafeSearch(google=True)), + {"porn"}, + ) + assert svc.reload(inst.name)["reloaded"] is True + code, out = container.exec_run( + ["grep", "-c", "216.239.38.120 www.google.de", "/run/lmnsquid/hosts"] + ) + assert code == 0 and out.strip() == b"1" + # the helper as squid runs it, inside the container, against the mounted files + code, out = container.exec_run( + [ + "sh", + "-c", + "printf '0 www.adult.example\\n1 example.org\\n' | /usr/local/bin/lmn-filter-acl" + " 2>/dev/null", + ], + user="proxy", + ) + assert out.decode().splitlines()[:2] == [ + '0 OK tag=lmnfilter category=porn message="Pornografie"', + "1 ERR", + ], out + assert svc.filter_stats(inst.name) == "" + finally: + svc.remove(inst.name) + + def test_real_update_auto_rollback(tmp_path: Path) -> None: """Updating to a broken image (which crashes) must auto-roll-back to the good one.""" from lmnsquid.docker_service import DockerService @@ -118,7 +189,11 @@ def test_real_update_auto_rollback(tmp_path: Path) -> None: (secrets / "it.keytab").write_bytes(b"dummy-keytab-not-valid") store = Store(str(tmp_path / "instances")) - docker = DockerService(secrets_dir=str(secrets), blocklists_dir=str(tmp_path / "lists")) + docker = DockerService( + secrets_dir=str(secrets), + blocklists_dir=str(tmp_path / "lists"), + catalog_dir=str(tmp_path / "catalog"), + ) reconciler = Reconciler(store, docker) updater = Updater(store, docker, reconciler, health_timeout=45.0, poll_interval=2.0) @@ -160,7 +235,9 @@ def test_real_old_image_ignores_the_noauth_list(tmp_path: Path) -> None: secrets.mkdir() (secrets / "it.keytab").write_bytes(b"dummy-keytab-not-valid") lists = tmp_path / "lists" - svc = DockerService(secrets_dir=str(secrets), blocklists_dir=str(lists)) + svc = DockerService( + secrets_dir=str(secrets), blocklists_dir=str(lists), catalog_dir=str(tmp_path / "catalog") + ) inst = Instance( school="ito", role="teachers", @@ -177,6 +254,7 @@ def test_real_old_image_ignores_the_noauth_list(tmp_path: Path) -> None: svc.noauth.add(inst.name, "office.com") # a list that is there before the container try: status = svc.ensure_running(inst) # health-gated: raises if it does not come up + assert svc.status(inst.name)["filter_capable"] is False assert status["running"] is True and status["health"] == "healthy" assert svc.noauth_active(inst.name) is False assert svc.reload(inst.name)["reloaded"] is True # the blocklist reload still works @@ -199,7 +277,11 @@ def _hardened(tmp_path: Path, school: str, port: int, retention: int = 2) -> tup secrets = tmp_path / "secrets" secrets.mkdir() (secrets / "it.keytab").write_bytes(b"dummy-keytab-not-valid") - svc = DockerService(secrets_dir=str(secrets), blocklists_dir=str(tmp_path / "lists")) + svc = DockerService( + secrets_dir=str(secrets), + blocklists_dir=str(tmp_path / "lists"), + catalog_dir=str(tmp_path / "catalog"), + ) inst = Instance( school=school, role="teachers", @@ -334,6 +416,8 @@ def test_log_rotation_hardened(tmp_path: Path) -> None: "cache.log.2.gz", "cache.log.3.gz", "cache.log.4.gz", + # the anonymous filter statistics (ADR-022): empty, so notifempty leaves it alone + "filter.log", ], files for name, stat in files.items(): if name != ".logrotate.state": 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..2dea617 --- /dev/null +++ b/controlplane/tests/test_filter_api.py @@ -0,0 +1,639 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Category filter through the API (ADR-022): settings, variants, own lists, apply/reload, 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 filterdecision as fd +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"), + ("get", "/v1/catalog/custom"), + ("post", "/v1/catalog/custom/categories"), + ("delete", "/v1/catalog/custom/categories/own_x"), + ("put", "/v1/catalog/custom/categories/own_x/domains"), + ("post", "/v1/catalog/custom/sources"), + ("delete", "/v1/catalog/custom/sources/own-x"), + ("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"] is False and state["filter"]["active"] == [] + + +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 "exam" not in data + # 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" + + +# ---------------------------------------------------------------- variants, missing sources +def test_variants_are_validated_stored_and_summarised( + client: Any, auth_headers: Any, created: str, settings: Any +) -> None: + resp = _put(client, auth_headers, categories=["ads"], variants={"ads": "pro"}) + assert resp.status_code == 200, resp.text + assert _filter_file(settings)["variants"] == {"ads": "pro"} + assert resp.json()["settings"]["variants"] == {"ads": "pro"} + assert _put(client, auth_headers, categories=["ads"], variants={"ads": "x"}).status_code == 422 + assert _put(client, auth_headers, categories=["ads"], variants={"zz": "x"}).status_code == 422 + sched = {"ads": [{"days": ["mo"], "start": "08:00", "end": "09:00"}]} + _put(client, auth_headers, categories=["ads", "porn"], variants={"ads": "pro"}, schedules=sched) + flt = client.get("/v1/status", headers=auth_headers).json()[0]["filter"] + assert flt["active"] == ["ads", "porn"] and flt["variants"] == {"ads": "pro"} + assert flt["scheduled"] == ["ads"] + + +def test_a_source_the_catalog_lacks_starts_an_update( + client: Any, auth_headers: Any, created: str, settings: Any, app: Any +) -> None: + make_catalog(settings.catalog_dir, {"ads": ["a.example"]}) + started: list[int] = [] + app.state.spawn_catalog_update = lambda: started.append(1) + body = _put(client, auth_headers, categories=["ads"], variants={"ads": "pro"}).json() + assert "hagezi-pro" in body["missing_sources"] and body["catalog_update_started"] + assert started == [1] + + +def test_exam_data_of_an_older_build_is_dropped(tmp_path: Path) -> None: + store = fm.FilterStore(str(tmp_path), "UTC", resolver=lambda _n: None) + store.lists.ensure("s-students") + (tmp_path / "s-students" / "filter.json").write_text( + json.dumps({"format": 1, "categories": ["porn"], "exam": {"until": 9e9, "allowed": []}}) + ) + assert store.settings("s-students").categories == ["porn"] + assert "exam" not in store.write("s-students", store.settings("s-students"), set()) + + +# ---------------------------------------------------------------- own sources and categories +def test_own_categories_and_sources( + client: Any, auth_headers: Any, created: str, settings: Any, app: Any +) -> None: + app.state.spawn_catalog_update = lambda: None + base = "/v1/catalog/custom" + resp = client.post( + f"{base}/categories", + json={"id": "own_lessons", "label": "Unterrichtsstörer", "description": "von der IT"}, + headers=auth_headers, + ) + assert resp.status_code == 200, resp.text + assert ( + client.post( + f"{base}/categories", json={"id": "lessons", "label": "x"}, headers=auth_headers + ).status_code + == 422 + ) + resp = client.put( + f"{base}/categories/own_lessons/domains", + json={"domains": ["Game.Example", "b.example"]}, + headers=auth_headers, + ) + assert resp.json()["domains"] == ["b.example", "game.example"] + assert ( + client.put( + f"{base}/categories/own_lessons/domains", + json={"domains": ["a b"]}, + headers=auth_headers, + ).status_code + == 422 + ) + assert ( + client.put( + f"{base}/categories/own_nope/domains", json={"domains": []}, headers=auth_headers + ).status_code + == 404 + ) + custom_dir = Path(settings.catalog_dir) / "custom" + assert (custom_dir / "own_lessons.domains").read_text() == "b.example\ngame.example\n" + assert json.loads((custom_dir / "categories.json").read_text()) == { + "own_lessons": "Unterrichtsstörer" + } + # usable like a catalog category, and explained + assert _put(client, auth_headers, categories=["own_lessons"]).status_code == 200 + hit = client.get( + f"/v1/instances/{NAME}/filter/lookup", + params={"domain": "www.game.example"}, + headers=auth_headers, + ).json() + assert hit["blocked"] and hit["category_label"] == "Unterrichtsstörer" + info = client.get("/v1/catalog", headers=auth_headers).json() + own = next(c for c in info["categories"] if c["id"] == "own_lessons") + assert own["own"] and own["own_entries"] == 2 + # own sources: https only, known category, size limits + src = { + "id": "own-list", + "name": "Liste", + "url": "https://lists.example/x.txt", + "category": "own_lessons", + "license": "CC0", + "format": "hosts", + "min_entries": 5, + } + resp = client.post(f"{base}/sources", json=src, headers=auth_headers) + assert resp.status_code == 200, resp.text + assert resp.json()["format"] == "domains" + for bad in ( + {"url": "http://lists.example/x"}, + {"category": "nope"}, + {"max_mb": 500}, + {"id": "list"}, + {"format": "csv"}, + ): + assert ( + client.post(f"{base}/sources", json={**src, **bad}, headers=auth_headers).status_code + == 422 + ), bad + data = client.get(base, headers=auth_headers).json() + assert [s["id"] for s in data["sources"]] == ["own-list"] + assert data["categories"][0]["domains"] == 2 + assert client.delete(f"{base}/sources/own-list", headers=auth_headers).status_code == 204 + assert client.delete(f"{base}/sources/own-list", headers=auth_headers).status_code == 404 + assert client.delete(f"{base}/categories/own_lessons", headers=auth_headers).status_code == 204 + assert not (custom_dir / "own_lessons.domains").exists() + + +# ---------------------------------------------------------------- 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 + assert set(info["profiles"]) == {"students", "primary", "teachers", "staff", "guests"} + 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 "own_source" 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) + + +def test_schedule_time_zone_is_configured_not_the_hosts(tmp_path: Path) -> None: + assert fm.FilterStore(str(tmp_path)).timezone == "Europe/Berlin" + assert fm.FilterStore(str(tmp_path), "America/New_York").timezone == "America/New_York" + assert fm.FilterStore(str(tmp_path), "Mars/Olympus").timezone == "Europe/Berlin" + store = fm.FilterStore(str(tmp_path), None, resolver=lambda _n: None) + assert store.write("s-students", fm.FilterSettings(), set())["timezone"] == "Europe/Berlin" + + +def test_catalog_answer_names_the_time_zone(client: Any, auth_headers: Any) -> None: + assert client.get("/v1/catalog", headers=auth_headers).json()["timezone"] == "Europe/Berlin" + + +def test_warnings_for_expert_categories_and_strict_variants( + client: Any, auth_headers: Any, created: str +) -> None: + body = _put( + client, auth_headers, categories=["ads", "abused_tlds", "porn"], variants={"ads": "proplus"} + ).json() + found = {w["category"]: w for w in body["warnings"]} + assert set(found) == {"ads", "abused_tlds"} # porn in its recommended variant: none + assert "Pro++" in found["ads"]["label"] and "aggressiv" in found["ads"]["warning"] + assert "Ausnahmeliste" in found["abused_tlds"]["warning"] + assert _put(client, auth_headers, categories=["ads"]).json()["warnings"] == [] + + +def test_settings_carry_the_effective_time_zone( + client: Any, auth_headers: Any, created: str +) -> None: + sched = {"social": [{"days": ["mo"], "start": "08:00", "end": "09:00"}]} + body = _put(client, auth_headers, categories=["social"], schedules=sched).json() + assert body["settings"]["timezone"] == "Europe/Berlin" == body["timezone"] + # sent back as is (the WebUI and the CLI do): ignored, not an error + settings = {**body["settings"], "timezone": "UTC"} + assert _put(client, auth_headers, **settings).status_code == 200 + + +def test_lookup_names_the_variant_a_domain_is_in( + client: Any, auth_headers: Any, created: str, settings: Any +) -> None: + from lmnsquid import catalog as cm + + work = Path(settings.catalog_dir).parent / "w" + work.mkdir() + inputs = [] + for src_id, names in {"hagezi-light": ["l.example"], "hagezi-pro": ["p.example"]}.items(): + path = work / f"{src_id}.txt" + path.write_text("".join(f"{n}\n" for n in names)) + inputs.append( + ( + { + "id": src_id, + "name": src_id, + "license": "GPL-3.0", + "format": "domains", + "category": "ads", + "path": str(path), + }, + str(path), + ) + ) + Path(settings.catalog_dir).mkdir(parents=True, exist_ok=True) + cm.build_file(cm.load_config(), inputs, work / "c.sqlite", work) + cm.publish(Path(settings.catalog_dir), work / "c.sqlite") + _put(client, auth_headers, categories=["ads"]) + hit = client.get( + f"/v1/instances/{NAME}/filter/lookup", params={"domain": "p.example"}, headers=auth_headers + ).json() + assert hit["rule"] == "none" + row = hit["listed_in"][0] + assert row["active"] and not row["in_variant"] + assert "pro" in row["variants"] and "light" not in row["variants"] + + +def test_summary_names_why_the_catalog_is_unusable( + client: Any, auth_headers: Any, created: str, settings: Any +) -> None: + _put(client, auth_headers, categories=["porn"]) + Path(settings.catalog_dir).mkdir(parents=True, exist_ok=True) + (Path(settings.catalog_dir) / "current.sqlite").write_text("garbage") + flt = client.get("/v1/status", headers=auth_headers).json()[0]["filter"] + assert flt["problem"] == "catalog_missing_fail_closed" + assert "unusable" in flt["problem_detail"] + + +def test_summary_warns_about_lists_stale_for_a_week( + client: Any, auth_headers: Any, created: str, settings: Any +) -> None: + make_catalog(settings.catalog_dir, {"porn": ["a.example"]}) + _put(client, auth_headers, categories=["porn"]) + cache = Path(settings.catalog_cache_dir) + cache.mkdir(parents=True, exist_ok=True) + (cache / "status.json").write_text( + json.dumps( + { + "state": "ok", + "problems": [ + { + "source": "ut1", + "state": "stale", + "error": "HTTP 503", + "since": time.time() - 9 * 86400, + } + ], + } + ) + ) + flt = client.get("/v1/status", headers=auth_headers).json()[0]["filter"] + assert flt["problem"] == "catalog_lists_old" + info = client.get("/v1/catalog", headers=auth_headers).json() + assert info["problems"][0]["age_days"] > 8 and info["problems_old"] + + +# ---------------------------------------------------------------- cold check 2026-11-24 +def test_safesearch_without_address_blocks_the_engine_and_says_so(tmp_path: Path) -> None: + answers: dict[str, str | None] = {"forcesafesearch.google.com": "216.239.38.120"} + store = fm.FilterStore(str(tmp_path), "UTC", resolver=lambda n: answers.get(n)) + settings = fm.FilterSettings( + safesearch=fm.SafeSearch(google=True, bing=True, ecosia=True, brave=True) + ) + data = store.write("s-students", settings, set()) + # Ecosia has a documented address, Bing and Brave none: blocked, not unfiltered + assert data["safesearch_unresolved"] == ["bing", "brave"] + assert ( + "www.bing.com" in data["safesearch_block"] + and "search.brave.com" in data["safesearch_block"] + ) + hosts = (tmp_path / "s-students" / "safesearch.hosts").read_text() + assert "77.73.113.2 www.ecosia.org" in hosts + policy = fd.Policy.from_dict(data, frozenset()) + verdict = fd.decide("www.bing.com", policy, None, time.time()) + assert verdict.blocked and verdict.decision == "safesearch_unavailable" + assert not fd.decide("www.google.de", policy, None, time.time()).blocked + summary = fm.summary(data, {"available": True}, time.time()) + assert ( + summary["problem"] == "safesearch_unresolved" and summary["problem_detail"] == "bing, brave" + ) + # Bing resolves once: its address is kept host-wide and used when DNS fails again, + # also for another instance + answers["strict.bing.com"] = "150.171.28.16" + store.write("s-students", settings, set()) + answers["strict.bing.com"] = None + other = store.write("t-students", settings, set()) + assert other["safesearch_unresolved"] == ["brave"] + assert ( + "150.171.28.16 www.bing.com" in (tmp_path / "t-students" / "safesearch.hosts").read_text() + ) + + +def test_noop_filter_change_triggers_nothing( + client: Any, auth_headers: Any, created: str, docker: Any, app: Any, settings: Any +) -> None: + make_catalog(settings.catalog_dir, {"ads": ["a.example"]}) + started: list[int] = [] + app.state.spawn_catalog_update = lambda: started.append(1) + _put(client, auth_headers, categories=["ads"], safesearch={"youtube": "strict"}) + reloads, spawned = len(docker.reloaded), len(started) + body = _put(client, auth_headers, categories=["ads"], safesearch={"youtube": "strict"}).json() + assert body["unchanged"] is True and body["applied"] is True + assert len(docker.reloaded) == reloads and len(started) == spawned + + +def test_a_failing_source_does_not_start_an_update_per_change( + client: Any, auth_headers: Any, created: str, app: Any, settings: Any +) -> None: + make_catalog(settings.catalog_dir, {"ads": ["a.example"]}) + cache = Path(settings.catalog_cache_dir) + cache.mkdir(parents=True, exist_ok=True) + (cache / "status.json").write_text( + json.dumps( + { + "state": "ok", + "problems": [ + { + "source": "hagezi-pro", + "state": "missing", + "error": "0 entries", + "since": time.time(), + } + ], + } + ) + ) + started: list[int] = [] + app.state.spawn_catalog_update = lambda: started.append(1) + body = _put(client, auth_headers, categories=["ads"], variants={"ads": "pro"}).json() + assert body["missing_sources"] == [] and not body["catalog_update_started"] and started == [] + + +def test_removed_own_source_leaves_the_problems_at_once( + client: Any, auth_headers: Any, app: Any, settings: Any +) -> None: + app.state.spawn_catalog_update = lambda: None + src = { + "id": "own-l", + "name": "L", + "url": "https://l.example/x", + "category": "ads", + "license": "CC0", + } + assert ( + client.post("/v1/catalog/custom/sources", json=src, headers=auth_headers).status_code == 200 + ) + cache = Path(settings.catalog_cache_dir) + cache.mkdir(parents=True, exist_ok=True) + (cache / "status.json").write_text( + json.dumps( + { + "state": "ok", + "problems": [ + { + "source": "own-l", + "state": "missing", + "error": "0 entries", + "since": time.time(), + }, + {"source": "ut1", "state": "stale", "error": "HTTP 503", "since": time.time()}, + ], + "sources": {"own-l": "unchanged", "ut1": "stale"}, + } + ) + ) + (cache / "own-l.download").write_text("x") + assert ( + client.delete("/v1/catalog/custom/sources/own-l", headers=auth_headers).status_code == 204 + ) + problems = client.get("/v1/catalog", headers=auth_headers).json()["problems"] + assert [p["source"] for p in problems] == ["ut1"] + assert json.loads((cache / "status.json").read_text())["sources"] == {"ut1": "stale"} + assert not (cache / "own-l.download").exists() + + +def test_status_names_an_image_that_cannot_filter( + 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 + ) + _put(client, auth_headers, categories=["porn", "ads"]) + flt = client.get("/v1/status", headers=auth_headers).json()[0]["filter"] + assert flt["problem"] == "image_without_filter" and flt["problem_detail"] == "ghcr.io/x/old:1" + single = client.get(f"/v1/instances/{NAME}/status", headers=auth_headers).json() + assert single["filter"]["problem"] == "image_without_filter" diff --git a/controlplane/tests/test_filter_helper.py b/controlplane/tests/test_filter_helper.py new file mode 100644 index 0000000..483b376 --- /dev/null +++ b/controlplane/tests/test_filter_helper.py @@ -0,0 +1,156 @@ +# 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, + encoding="latin-1", # what squid reads (see quote() in the helper) + 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_reach_squid_as_latin1(env: Any) -> None: + """squid writes each byte of %o as &#NNN;: Latin-1 bytes give the right umlauts.""" + lists, catalog, helper = env + (catalog / "custom").mkdir() + (catalog / "custom" / "own_x.domains").write_text("stoer.example\n") + (catalog / "custom" / "categories.json").write_text('{"own_x": "Störer für Prüfungen"}') + _filter(lists, categories=["own_x"]) + (answer,) = helper.ask("0 www.stoer.example") + assert answer == '0 OK tag=lmnfilter category=own_x message="Störer für Prüfungen"' + + +def test_own_category_list_changes_apply_at_once(env: Any) -> None: + lists, catalog, helper = env + custom = catalog / "custom" + custom.mkdir() + (custom / "own_x.domains").write_text("") + _filter(lists, categories=["own_x"]) + assert helper.ask("0 new.example") == ["0 ERR"] + tmp = custom / ".tmp" + tmp.write_text("new.example\n") + os.replace(tmp, custom / "own_x.domains") + assert helper.ask("1 new.example")[0].startswith("1 OK tag=lmnfilter category=own_x") + + +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 verfügbar" 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_filterdecision.py b/controlplane/tests/test_filterdecision.py new file mode 100644 index 0000000..80a5565 --- /dev/null +++ b/controlplane/tests/test_filterdecision.py @@ -0,0 +1,238 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The filter decision (ADR-022): order exceptions -> protected -> categories (variants, own), 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(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" + + +def test_exam_data_of_an_older_build_is_ignored(catalog: fd.Catalog) -> None: + policy = _policy(exam={"until": NOW + 600, "allowed": ["school.lan"]}) + assert not fd.decide("wiki.example", policy, catalog, NOW).blocked + assert fd.decide("adult.example", policy, catalog, NOW).blocked + + +def test_variants_choose_the_sources(tmp_path: Path) -> None: + """A category with variants: the default uses its sources, another variant others; a + source no variant names (the admin's own) counts in every variant.""" + from lmnsquid import catalog as cm + + config = cm.load_config() + work = tmp_path / "w" + work.mkdir() + inputs = [] + for src_id, names in { + "hagezi-light": ["light.example"], + "hagezi-pro": ["pro.example"], + "own-extra": ["own.example"], + }.items(): + path = work / f"{src_id}.txt" + path.write_text("".join(f"{n}\n" for n in names)) + src = { + "id": src_id, + "name": src_id, + "license": "x", + "format": "domains", + "category": "ads", + "path": str(path), + } + inputs.append((src, str(path))) + target = work / "c.sqlite" + cm.build_file(config, inputs, target, work) + cat = fd.Catalog(str(target)) + try: + light = fd.Policy.from_dict({"format": 1, "categories": ["ads"]}, frozenset()) + pro = fd.Policy.from_dict( + {"format": 1, "categories": ["ads"], "variants": {"ads": "pro"}}, frozenset() + ) + assert fd.decide("light.example", light, cat, NOW).blocked + assert not fd.decide("pro.example", light, cat, NOW).blocked + assert fd.decide("pro.example", pro, cat, NOW).blocked + assert not fd.decide("light.example", pro, cat, NOW).blocked + for policy in (light, pro): + assert fd.decide("own.example", policy, cat, NOW).blocked + unknown = fd.Policy.from_dict( + {"format": 1, "categories": ["ads"], "variants": {"ads": "nope"}}, frozenset() + ) + assert fd.decide("light.example", unknown, cat, NOW).blocked # falls back to default + finally: + cat.close() + + +def test_own_categories_from_the_custom_lists(tmp_path: Path) -> None: + custom = tmp_path / "custom" + custom.mkdir() + (custom / "own_lessons.domains").write_text("game.example\n") + (custom / "categories.json").write_text('{"own_lessons": "Unterrichtsstörer"}') + lists, labels = fd.read_custom(str(custom)) + assert lists == {"own_lessons": frozenset({"game.example"})} + assert labels["own_lessons"] == "Unterrichtsstörer" + policy = _policy(categories=["own_lessons"], fail_closed=[]) + hit = fd.decide("www.game.example", policy, None, NOW, "no catalog", lists) + assert (hit.decision, hit.category, hit.entry) == ("category", "own_lessons", "game.example") + assert not fd.decide("other.example", policy, None, NOW, "no catalog", lists).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='1' WHERE k='format'") + db.commit() + db.close() + with pytest.raises(ValueError): + fd.Catalog(str(current)) + + +def test_schedules_follow_daylight_saving_time(catalog: fd.Catalog) -> None: + """07:45-13:15 Berlin is 06:45 UTC in winter and 05:45 UTC in summer (2027-03-28).""" + policy = _policy( + categories=["social"], + fail_closed=[], + timezone="Europe/Berlin", + schedules={"social": [{"days": list(fd.DAYS), "start": "07:45", "end": "13:15"}]}, + ) + utc = datetime.timezone.utc + friday_winter = datetime.datetime(2027, 3, 26, 6, 50, tzinfo=utc).timestamp() # 07:50 CET + friday_early = datetime.datetime(2027, 3, 26, 5, 50, tzinfo=utc).timestamp() # 06:50 CET + monday_summer = datetime.datetime(2027, 3, 29, 5, 50, tzinfo=utc).timestamp() # 07:50 CEST + monday_late = datetime.datetime(2027, 3, 29, 11, 20, tzinfo=utc).timestamp() # 13:20 CEST + assert fd.decide("social.example", policy, catalog, friday_winter).blocked + assert not fd.decide("social.example", policy, catalog, friday_early).blocked + assert fd.decide("social.example", policy, catalog, monday_summer).blocked + assert not fd.decide("social.example", policy, catalog, monday_late).blocked 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/debian/changelog b/debian/changelog index d91644d..f91d1ee 100644 --- a/debian/changelog +++ b/debian/changelog @@ -96,6 +96,68 @@ 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): 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). + * A list that cannot be downloaded or fails its checks (too few entries, + shrinking by half) no longer stops the catalog update: it keeps its + last good version (or stays out) and is listed with the reason in + "lmnsquid catalog status" and the WebUI; after 7 days it is a warning. + Lists no instance uses any more leave the catalog and the download + cache. + * Own lists: own sources (https URL, checked like the packaged ones) and + own categories with a hand-entered domain list that applies after up + to about a minute ("lmnsquid catalog own ...", API /v1/catalog/custom). + * SafeSearch per instance without decrypting: Google search (all country + domains), YouTube restricted mode (strict/moderate), Bing, DuckDuckGo, + Ecosia, Brave Search. An engine switched on whose SafeSearch address + cannot be resolved (and was never resolved before) is blocked and + reported, not left unfiltered. "Search engines without SafeSearch" + also blocks Startpage, Qwant, Mojeek, MetaGer, Yahoo/AOL search, Ask, + Dogpile, Yandex and Kagi (packaged supplement list). + * 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 status, API and WebUI say so (image_without_filter). + * A package upgrade starts one catalog update in the background (where + the filter is in use and the nightly timer is enabled), so lists the + new package brings apply at once. + * 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. Its dialogs scroll inside the + window like the others; the category list, the instance list of + "apply to other instances" and the container log scroll on their own, + sized to the window so they fit into the dialog (no scroll area inside + a scrolling one at 125 % zoom). -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium 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..14ccb64 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 @@ -221,6 +238,15 @@ if [ -d /run/systemd/system ]; then lmn_step reconcile fi fi + # On upgrade, build the category catalog once in the background, so lists this package + # brings or changes apply now, not only after the next filter change or the nightly run. + # The unit builds only where a catalog exists or an instance uses categories (--if-needed) + # and skips unchanged input; started only while the nightly timer is enabled (an admin who + # turned it off wants no downloads). Never fails the install. + if [ -n "${2:-}" ] && [ "$(systemctl is-enabled "$TIMER" 2>/dev/null)" = enabled ]; then + systemctl start --no-block linuxmuster-squid-catalog.service >/dev/null 2>&1 || + echo "linuxmuster-squid: catalog update not started; the nightly timer runs it" + fi fi #DEBHELPER# 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/deploy/e2e/client/assert.sh b/deploy/e2e/client/assert.sh index fa44471..222b5ec 100755 --- a/deploy/e2e/client/assert.sh +++ b/deploy/e2e/client/assert.sh @@ -147,6 +147,26 @@ check_via "old image + noauth.domains: no ticket -> 407" "" "$PROXY5" " check_via "old image + noauth.domains: teacher -> 200" teacher1 "$PROXY5" "http://secure.example.internal/" 200 check_via "old image + noauth.domains: student -> 403" student1 "$PROXY5" "$ALLOWED" 403 +echo "-- Category filter (ADR-022, squid7: porn + ai active; exception www.secure; noauth secure2, a.secure) --" +P7="http://squid7.example.internal:3128" +P7_HOST="squid7.example.internal:3128" +check_via "filter: category (teacher) -> 403" teacher1 "$P7" "$ALLOWED" 403 +check_via "filter: category, subdomain (teacher) -> 403" teacher1 "$P7" "http://b.secure.example.internal/" 403 +check_via "filter: second category ai (teacher) -> 403" teacher1 "$P7" "http://chat.example.internal/" 403 +check_via "filter: not listed (teacher) -> 200" teacher1 "$P7" "http://secure2.example.internal/" 200 +check_via "filter: exception beats the category (teacher) -> 200" teacher1 "$P7" "http://www.secure.example.internal/" 200 +check_via "filter: still no ticket -> 407" "" "$P7" "http://www.secure.example.internal/" 407 +check_via "filter: still student -> 403" student1 "$P7" "http://www.secure.example.internal/" 403 +check_via "filter: noauth listed but in a category, no ticket -> 403" "" "$P7" "http://a.secure.example.internal/" 403 +check_via "filter: noauth listed, no category, no ticket -> 200" "" "$P7" "http://secure2.example.internal/" 200 +check_tunnel "filter: HTTPS CONNECT to a category name (teacher)" teacher1 "$P7" "https://secure.example.internal/" "200 403" +check_tunnel "filter: HTTPS not listed (teacher) -> tunnel" teacher1 "$P7" "https://secure2.example.internal/" "200 200" +check_tls_sni "filter: SNI not listed -> ok" "$P7_HOST" "secure2.example.internal:443" "secure2.example.internal" ok +# a.secure is on the noauth list too, so only the category can cut it +check_tls_sni "filter: SNI in a category behind an allowed CONNECT -> cut" "$P7_HOST" "secure2.example.internal:443" "a.secure.example.internal" cut +echo "-- the same name through the instance without filter --" +check_via "no filter (squid): teacher -> 200" teacher1 "$PROXY" "$ALLOWED" 200 + # Kerberos clock skew (ADR-017): the tickets are fetched with the true time (as a Windows # client holds them when its clock jumps), then curl runs with the client clock # ahead, so every authenticator it builds carries that time. The proxy's own clock is true. diff --git a/deploy/e2e/docker-compose.yml b/deploy/e2e/docker-compose.yml index 965cd2d..f87f8d7 100644 --- a/deploy/e2e/docker-compose.yml +++ b/deploy/e2e/docker-compose.yml @@ -122,6 +122,35 @@ services: cap_add: ["SETUID", "SETGID", "DAC_OVERRIDE", "CHOWN"] security_opt: ["no-new-privileges:true"] + # Category filter (ADR-022): the instance's list directory and a small real catalog, both made + # by e2e_kerberos.sh in a temporary directory (LMNSQUID_E2E_FILTER_DIR), mounted like the + # control plane does it. + squid-filter: + image: linuxmuster-squid:dev + hostname: squid7.example.internal + depends_on: [samba-dc, squid] + environment: + INSTANCE: "e2e-filter" + VISIBLE_HOSTNAME: "squid7.example.internal" + REALM: "EXAMPLE.INTERNAL" + AD_GROUP: "teachers" + SCHOOL_SUBNETS: "10.228.0.30/32" + KEYTAB: "/shared/squid.keytab" + CACHE_SIZE_MB: "200" + dns: ["10.228.0.2"] + networks: + e2e: + ipv4_address: 10.228.0.16 + volumes: + - shared:/shared:ro + - ${LMNSQUID_E2E_FILTER_DIR:-./filter-not-prepared}/lists:/etc/squid/lists:ro + - ${LMNSQUID_E2E_FILTER_DIR:-./filter-not-prepared}/catalog:/etc/squid/catalog:ro + read_only: true + tmpfs: ["/run", "/tmp", "/var/log/squid", "/var/spool/squid"] + cap_drop: ["ALL"] + cap_add: ["SETUID", "SETGID", "DAC_OVERRIDE", "CHOWN"] + security_opt: ["no-new-privileges:true"] + # Domains without proxy auth (ADR-016): the list directory mounted like the control plane # does it; school_net is the test client alone, so a request from any other container is # "outside the school subnets". diff --git a/docs/architecture.md b/docs/architecture.md index 9b9cd5f..1f10a21 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) 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). + ## 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`, `…/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`) → 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..a5566b0 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 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 ignored and `lmnsquid noauth reload` answers 409 instead of reporting a reload that @@ -482,6 +485,147 @@ 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"; 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 after up to ~60 s (squid's answer cache, ttl=60), 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 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, +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 (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). **One bad source does not stop the others** (lab retest 2026-11-24: an own source with 0 entries +failed every run): each source is parsed and checked on its own; one that cannot be downloaded, +cannot be read, has fewer than `min_entries` or would shrink a feed by more than half is built +from its **last good download** (kept per source in the cache), or left out if it never had one, +and the rest of the catalog is rebuilt and activated. A refused download is forgotten, so the +next run downloads it in full instead of getting a 304. `GET /v1/catalog`, `lmnsquid catalog +status` and the WebUI list such sources with the reason and since when; after 7 days it is a +warning (`problems_old`, instance problem `catalog_lists_old`). A youth protection category of +which no list ever reached the catalog fails closed like a missing catalog. Only when no source +at all can be used does the run fail and the active catalog stay; `status` reports its 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, Ecosia, Brave Search (both by their documented DNS +override). The control plane resolves the services' addresses at every change and every container +creation; a failed lookup keeps the last known address, per instance and host-wide +(Google/YouTube/Ecosia: the documented address as the last resort). Amendment after the cold +check (2026-11-24): an engine switched on without any known address is blocked by the helper +(fail closed, decision `safesearch_unavailable`) and reported as `safesearch_unresolved`; +before, its lines were silently left out and the engine stayed reachable unfiltered. Engines +with no forceable SafeSearch (Startpage, Qwant, …) are a packaged supplement feed of +`nosafesearch`, since HaGeZi's list does not name them. An instance whose image lacks the +filter (label `org.faircomp.linuxmuster-squid.filter`, e.g. after a rollback or the +`update-all` to an older pinned image) reports `image_without_filter` instead of a healthy +filter. A source refused by the last run neither counts as missing for `PUT …/filter` nor +causes a rebuild when it brings the same bytes again (the fingerprint hashes content); a +`PUT …/filter` without a change writes, reloads and starts nothing. Measured: CONNECT +`www.google.de` goes to `216.239.38.120` with a valid certificate; the certificates of +`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. (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 (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 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`. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/install.md b/docs/install.md index 1349409..bb326d1 100644 --- a/docs/install.md +++ b/docs/install.md @@ -221,6 +221,20 @@ 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 and SafeSearch (optional) + +```bash +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 +``` + +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-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..1b30808 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,178 @@ 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 (per instance) + +Per instance (= per school and role) the proxy can block whole categories (youth protection, +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 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 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, 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. +- A **package upgrade** starts the same unit once in the background (`systemctl start --no-block + linuxmuster-squid-catalog.service`), so lists or list changes the new package brings apply + right away instead of after the next filter change or nightly run. Same `--if-needed` rule; + only while the timer is enabled (an admin who disabled it gets no download from an upgrade); + a failed start does not fail the upgrade. Follow it with `journalctl -u + linuxmuster-squid-catalog.service`. +- **Safety, per source:** a source that cannot be downloaded or read, has fewer entries than its + `min_entries` or would shrink by more than half is built from its **last good download** (or + left out if it never had one); every other list is updated as usual. `lmnsquid catalog status` + (warnings at the end), `GET /v1/catalog` (`problems`) and the WebUI name such sources with the + reason and since when; after 7 days it is a warning. A youth protection category without any + list in the catalog refuses requests (fail-closed). Only if no source can be used at all does + the run fail and the **active catalog stays** (`last_run.state: failed`). +- Sources no instance uses any more leave the catalog at the next run, and their downloads leave + the cache. The + previous version stays on disk (`catalog-