From 3ebf00c2fe6b76b6393944f16629f391cd6dca93 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Thu, 26 Nov 2026 10:58:56 +0100 Subject: [PATCH 01/30] refactor(webui): move the management routes into a framework-free manage_core The proxy and connection routes of the management page become methods of manage_core.ManageService with one route table (ROUTES); views.py keeps one thin aj endpoint per route. The edulution plugin will serve the same routes from that module instead of a copy. A test keeps the aj endpoints and the table in step. --- webui/build_plugin.py | 1 + webui/lmn_squid/manage_core.py | 725 ++++++++++++++++++++++++++++++++ webui/lmn_squid/views.py | 390 +++-------------- webui/tests/test_build.py | 1 + webui/tests/test_manage_core.py | 38 ++ 5 files changed, 828 insertions(+), 327 deletions(-) create mode 100644 webui/lmn_squid/manage_core.py create mode 100644 webui/tests/test_manage_core.py diff --git a/webui/build_plugin.py b/webui/build_plugin.py index d58c457..f749494 100644 --- a/webui/build_plugin.py +++ b/webui/build_plugin.py @@ -31,6 +31,7 @@ "__init__.py", "main.py", "views.py", + "manage_core.py", "client.py", "connections.py", "sitefacts.py", diff --git a/webui/lmn_squid/manage_core.py b/webui/lmn_squid/manage_core.py new file mode 100644 index 0000000..e3741fa --- /dev/null +++ b/webui/lmn_squid/manage_core.py @@ -0,0 +1,725 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The management logic of the plugin (page "Squid-Proxy"), free of the WebUI core. + +Shared by the WebUI plugin (``views.py``: aj endpoints, one thin method per route) and the +edulution plugin (``edulution/``: its own HTTP server). Everything here talks to the control +planes over the pinned connections of :class:`ConnectionStore`; nothing here touches the AD or +the school server. Those parts differ between the two hosts (the WebUI runs as root on the DC, +the edulution plugin reaches the DC over SSH) and stay with each front end. + +Who may call: global administrators only. Each front end checks the role and the origin of a +state-changing request *before* it calls in here (``views.global_admin_only``, the edulution +server's guard); ``identity`` is that checked person and only goes into the audit lines and the +activity log settings (who confirmed the privacy notice). + +Errors: :class:`ServiceError` (status + JSON body) for the plugin's own refusals; the errors of +the client, the connection file and the jobs are turned into answers by :func:`error_answer`. +""" + +from __future__ import annotations + +import logging +import re +import time +from typing import Any, Callable + +from .activity_core import ServiceError, forget_instances +from .client import LONG, SHORT, ControlPlaneClient, ControlPlaneError, domain_segment +from .client import instance_path +from .connections import ( + BrokenEntry, + Connection, + ConnectionConfigError, + ConnectionFileError, + ConnectionStore, +) +from . import jobs + +audit = logging.getLogger("lmn_squid.audit") + +LIST_KINDS = ("blocklist", "noauth", "allowlist") +# own category (own_x) or own source (own-x) id as the control plane accepts it +CUSTOM_ID_RE = re.compile(r"^own[_-][a-z0-9_-]{1,30}$") +FILTER_KEYS = ("categories", "variants", "schedules", "safesearch") +BULK_MAX = 200 + +CONN = r"(?P[^/]+)" +NAME = r"(?P[^/]+)" +INST = "/" + CONN + r"/instances/" + NAME + +# (method, path below the plugin's API prefix, method of ManageService, needs PERM_CHANGE) +ROUTES: list[tuple[str, str, str, bool]] = [ + ("GET", r"/connections", "connections", False), + ("POST", r"/connections", "connection_add", True), + ("PUT", r"/connections/" + CONN, "connection_update", True), + ("GET", "/" + CONN + r"/test", "test", False), + ("GET", "/" + CONN + r"/overview", "overview", False), + ("GET", "/" + CONN + r"/schema", "schema", False), + ("POST", "/" + CONN + r"/(?Pupdate-all|reconcile)", "server_op", True), + ("GET", "/" + CONN + r"/instances", "instances", False), + ("POST", "/" + CONN + r"/instances", "instance_create", True), + ("GET", INST, "instance_get", False), + ("PATCH", INST, "instance_patch", True), + ("DELETE", INST, "instance_delete", True), + ("POST", INST + r"/(?Pstart|stop|restart|rollback)", "instance_action", True), + ("POST", INST + r"/update", "instance_update", True), + ("GET", INST + r"/status", "instance_status", False), + ("GET", INST + r"/(?Plogs|logs/access)", "instance_logs", False), + ("GET", INST + r"/(?Pblocklist|noauth|allowlist)", "list_get", False), + ("POST", INST + r"/(?Pblocklist|noauth|allowlist)", "list_add", True), + ( + "DELETE", + INST + r"/(?Pblocklist|noauth|allowlist)/(?P[^/]+)", + "list_remove", + True, + ), + ("POST", INST + r"/(?Pblocklist|noauth|allowlist)/reload", "list_reload", True), + ("GET", "/" + CONN + r"/catalog", "catalog", False), + ("POST", "/" + CONN + r"/catalog/update", "catalog_update", True), + ("GET", INST + r"/filter", "filter_get", False), + ("PUT", INST + r"/filter", "filter_put", True), + ("POST", r"/filter/bulk", "filter_bulk", True), + ("GET", "/" + CONN + r"/catalog/custom", "custom_get", False), + ("POST", "/" + CONN + r"/catalog/custom/(?Pcategories|sources)", "custom_add", True), + ( + "DELETE", + "/" + CONN + r"/catalog/custom/(?Pcategories|sources)/(?P[^/]+)", + "custom_remove", + True, + ), + ( + "GET", + "/" + CONN + r"/catalog/custom/categories/(?P[^/]+)/domains", + "custom_domains_get", + False, + ), + ( + "PUT", + "/" + CONN + r"/catalog/custom/categories/(?P[^/]+)/domains", + "custom_domains_put", + True, + ), + ("GET", INST + r"/filter/lookup", "filter_lookup", False), + ("GET", INST + r"/filter/stats", "filter_stats", False), + ("GET", "/" + CONN + r"/activity", "activity", False), + ("PUT", INST + r"/activity", "activity_settings", True), + ("GET", "/" + CONN + r"/activity/audit", "activity_audit", False), +] + + +def error_answer(exc: BaseException) -> tuple[int, dict[str, Any]] | None: + """The HTTP answer for an error of this module or the modules it uses; None if unknown.""" + if isinstance(exc, ServiceError): + return exc.status, exc.data + if isinstance(exc, ControlPlaneError): + return exc.http_status(), exc.as_dict() + if isinstance(exc, ConnectionFileError): + # 409, not 500: the WebUI answers every 500 with its own "this is likely a bug" dialog + return 409, {"error": "config", "message": exc.message} + if isinstance(exc, ConnectionConfigError): + return 422, { + "error": "invalid", + "field": exc.field, + "code": exc.code, + "message": exc.message, + } + if isinstance(exc, jobs.JobBusy): + return 409, {"error": "busy", "message": str(exc), "job": exc.job} + if isinstance(exc, jobs.JobError): + return 500, {"error": "job", "message": str(exc)} + return None + + +def int_param(query: dict[str, Any], key: str, default: int | None = None) -> int | None: + value = (query or {}).get(key) + if value in (None, ""): + return default + try: + return int(value) + except (TypeError, ValueError): + raise ServiceError( + 422, {"error": "invalid", "field": key, "message": f"{key} must be a number"} + ) from None + + +def int_body(body: dict[str, Any], key: str) -> int | None: + value = body.get(key) + if value in (None, ""): + return None + if isinstance(value, bool): + raise ServiceError(422, {"error": "invalid", "field": key, "message": f"{key}"}) + try: + return int(value) + except (TypeError, ValueError): + raise ServiceError( + 422, {"error": "invalid", "field": key, "message": f"{key} must be a number"} + ) from None + + +def filter_body(data: Any) -> dict[str, Any]: + """Only the keys of the API's FilterSettings go through; the API validates the values.""" + if not isinstance(data, dict): + raise ServiceError( + 422, {"error": "invalid", "field": "settings", "message": "settings expected"} + ) + return {k: data[k] for k in FILTER_KEYS if k in data} + + +def _flag(query: dict[str, Any], key: str) -> bool: + return str((query or {}).get(key, "")).lower() in ("1", "true") + + +def _custom_id(item: str) -> str: + if not CUSTOM_ID_RE.match(item): + raise ServiceError(422, {"error": "invalid", "field": "id", "message": "id"}) + return item + + +class ManageService: + """One method per route of :data:`ROUTES`: ``(identity, query, body, **path params)``. + + ``forget`` drops the activity view's cached instance lists after a settings change (the + WebUI asks its bridge, the edulution plugin its own cache). + """ + + def __init__( + self, + store: ConnectionStore, + forget: Callable[[str], None] = forget_instances, + ) -> None: + self.store = store + self.forget = forget + self._routes = [(m, re.compile(f"^{p}$"), n, c) for m, p, n, c in ROUTES] + + # ------------------------------------------------------------------ helpers + def route(self, method: str, path: str) -> tuple[str, bool, dict[str, str]] | None: + """(method name, needs the change permission, path parameters) of a request.""" + for m, pattern, name, change in self._routes: + match = pattern.match(path) + if match and m == method: + return name, change, match.groupdict() + return None + + def connection(self, conn: str) -> Connection: + found = self.store.get(conn) + if found is None: + raise ServiceError( + 404, {"error": "unknown_connection", "message": f"no connection {conn!r}"} + ) + return found + + def client(self, conn: str) -> ControlPlaneClient: + return ControlPlaneClient(self.connection(conn)) + + @staticmethod + def audit(identity: str | None, what: str, **fields: Any) -> None: + # Never the token: fields are connection/instance names, domains and flags only. + details = " ".join(f"{k}={v}" for k, v in fields.items()) + audit.info("user=%s %s %s", identity, what, details) + + # -------------------------------------------------------------- connections + def connections(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """Every entry of the file; a broken one with ``broken`` and ``problem``.""" + return [item.public() for item in self.store.items()] + + def connection_add(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + conn = self.store.add(body) + self.audit(identity, "connection add", conn=conn.name, url=conn.url) + return conn.public() + + def connection_update( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + updated = self.store.update(conn, body) + if updated is None: + raise ServiceError(404, {"error": "unknown_connection", "message": conn}) + self.audit(identity, "connection update", conn=conn, url=updated.url) + return updated.public() + + def connection_remove(self, identity: str, conn: str) -> Connection | BrokenEntry: + """Forget the connection (the proxy host is not changed); the removed entry.""" + removed = self.store.remove(conn) + if removed is None: + raise ServiceError(404, {"error": "unknown_connection", "message": conn}) + return removed + + # ------------------------------------------------------------ per server + def test( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + """Test a connection: reachability (health, no token) and the token (version).""" + client = self.client(conn) + health = client.request("GET", "/v1/health", auth=False) + version = client.request("GET", "/v1/version") + return {"health": health, "version": (version or {}).get("version")} + + def overview( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + """Version, instances and their container state of one server (one card of the page).""" + client = self.client(conn) + version = (client.request("GET", "/v1/version") or {}).get("version") + instances = client.request("GET", "/v1/instances") or [] + try: + states = client.request("GET", "/v1/status") or [] + except ControlPlaneError as exc: + if exc.status != 404: # a control plane before 7.3.11 has no bulk status + raise + states = [client.request("GET", instance_path(i["name"], "status")) for i in instances] + by_name = {s.get("name"): s for s in states if isinstance(s, dict)} + for inst in instances: + inst["state"] = by_name.get(inst.get("name")) + return {"version": version, "instances": instances} + + def schema( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + try: + return self.client(conn).request("GET", "/v1/schema") + except ControlPlaneError as exc: + if exc.status == 404: # older control plane: the form works without defaults + return {"instance": None, "instance_patch": None} + raise + + def server_op( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + op: str = "", + ) -> Any: + client = self.client(conn) + self.audit(identity, op, conn=conn) + return client.request("POST", f"/v1/{op}", timeouts=LONG) + + # ------------------------------------------------------------- instances + def instances( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + return self.client(conn).request("GET", "/v1/instances") + + def instance_create( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + client = self.client(conn) + self.audit( + identity, "instance create", conn=conn, school=body.get("school"), role=body.get("role") + ) + return client.request("POST", "/v1/instances", body=body, timeouts=LONG) + + def instance_get( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + client = self.client(conn) + return client.request("GET", instance_path(name)) + + def instance_patch( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + client = self.client(conn) + path = instance_path(name) + self.audit(identity, "instance patch", conn=conn, name=name, fields=",".join(sorted(body))) + return client.request("PATCH", path, body=body, timeouts=LONG) + + def instance_delete( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + client = self.client(conn) + path = instance_path(name) + keep = _flag(query, "keep_logs") + self.audit(identity, "instance delete", conn=conn, name=name, keep_logs=keep) + client.request( + "DELETE", path, query={"keep_logs": "true" if keep else "false"}, timeouts=LONG + ) + return {"deleted": name} + + def instance_action( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + action: str = "", + ) -> Any: + client = self.client(conn) + path = instance_path(name, action) + self.audit(identity, f"instance {action}", conn=conn, name=name) + return client.request("POST", path, timeouts=LONG) + + def instance_update( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + client = self.client(conn) + path = instance_path(name, "update") + data = {k: v for k, v in body.items() if k == "image" and v} + self.audit( + identity, "instance update", conn=conn, name=name, image=data.get("image", "default") + ) + return client.request("POST", path, body=data, timeouts=LONG) + + def instance_status( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + client = self.client(conn) + return client.request("GET", instance_path(name, "status")) + + def instance_logs( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + kind: str = "", + ) -> Any: + client = self.client(conn) + path = instance_path(name, *kind.split("/")) + params = { + "tail": int_param(query, "tail"), + "since": int_param(query, "since"), + "until": int_param(query, "until"), + "grep": (query or {}).get("grep") or None, + } + return client.request("GET", path, query=params, timeouts=(SHORT[0], 60.0)) + + # ----------------------------------------------- blocklist and noauth list + def list_get( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + kind: str = "", + ) -> Any: + client = self.client(conn) + return client.request("GET", instance_path(name, kind)) + + def list_add( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + kind: str = "", + ) -> Any: + client = self.client(conn) + path = instance_path(name, kind) + domain = str(body.get("domain") or "") + self.audit(identity, f"{kind} add", conn=conn, name=name, domain=domain) + return client.request("POST", path, body={"domain": domain}) + + def list_remove( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + kind: str = "", + domain: str = "", + ) -> Any: + client = self.client(conn) + path = instance_path(name, kind, domain_segment(domain)) + self.audit(identity, f"{kind} remove", conn=conn, name=name, domain=domain) + return client.request("DELETE", path) + + def list_reload( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + kind: str = "", + ) -> Any: + client = self.client(conn) + path = instance_path(name, kind, "reload") + self.audit(identity, f"{kind} reload", conn=conn, name=name) + return client.request("POST", path, timeouts=(SHORT[0], 60.0)) + + # ------------------------------------------------ category filter (ADR-022) + def catalog( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + """Catalog of one proxy host: age, categories with groups, sources, licences, profiles.""" + return self.client(conn).request("GET", "/v1/catalog") + + def catalog_update( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + self.audit(identity, "catalog update", conn=conn) + return self.client(conn).request("POST", "/v1/catalog/update") + + def filter_get( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + return self.client(conn).request("GET", instance_path(name, "filter")) + + def filter_put( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + """Categories, schedules and SafeSearch of one instance (validated by the API).""" + data = filter_body(body) + self.audit( + identity, + "filter set", + conn=conn, + name=name, + categories=",".join(data.get("categories") or []), + ) + return self.client(conn).request( + "PUT", instance_path(name, "filter"), body=data, timeouts=(SHORT[0], 60.0) + ) + + def filter_bulk(self, identity: str, query: dict[str, Any], body: dict[str, Any]) -> Any: + """The same filter settings on several instances, on one or more proxy servers. + + One request per instance, one after the other; the answer lists every instance with + its own result, so one server that is down does not hide the others. + """ + targets = body.get("targets") + if not isinstance(targets, list) or not targets or len(targets) > BULK_MAX: + raise ServiceError( + 422, + { + "error": "invalid", + "field": "targets", + "message": f"1 to {BULK_MAX} instances expected", + }, + ) + settings = filter_body(body.get("settings")) + results: list[dict[str, Any]] = [] + for target in targets: + target = target if isinstance(target, dict) else {} + conn, name = str(target.get("conn") or ""), str(target.get("name") or "") + row: dict[str, Any] = {"conn": conn, "name": name} + try: + found = self.store.get(conn) + if found is None: + raise ControlPlaneError("invalid", f"unknown connection {conn!r}") + answer = ControlPlaneClient(found).request( + "PUT", instance_path(name, "filter"), body=settings, timeouts=(SHORT[0], 60.0) + ) + answer = answer if isinstance(answer, dict) else {} + row.update( + ok=True, + applied=answer.get("applied"), + reason=answer.get("reason"), + detail=answer.get("detail"), + ) + except ControlPlaneError as exc: + row.update(ok=False, **exc.as_dict()) + results.append(row) + self.audit( + identity, + "filter bulk", + targets=",".join(f"{r['conn']}/{r['name']}" for r in results), + categories=",".join(settings.get("categories") or []), + failed=sum(1 for r in results if not r["ok"]), + ) + return {"results": results} + + # ------------------------------------------- own sources and categories (per server) + def custom_get( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + return self.client(conn).request("GET", "/v1/catalog/custom") + + def custom_add( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + kind: str = "", + ) -> Any: + """An own category or source; the control plane validates every field.""" + keys = ( + ("id", "label", "description") + if kind == "categories" + else ("id", "name", "url", "format", "category", "license", "min_entries", "max_mb") + ) + data = {k: body[k] for k in keys if k in body} + self.audit(identity, f"own {kind} add", conn=conn, id=data.get("id"), url=data.get("url")) + return self.client(conn).request("POST", f"/v1/catalog/custom/{kind}", body=data) + + def custom_remove( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + kind: str = "", + item: str = "", + ) -> Any: + _custom_id(item) + self.audit(identity, f"own {kind} remove", conn=conn, id=item) + self.client(conn).request("DELETE", f"/v1/catalog/custom/{kind}/{item}") + return {"removed": item} + + def custom_domains_get( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + item: str = "", + ) -> Any: + _custom_id(item) + return self.client(conn).request("GET", f"/v1/catalog/custom/categories/{item}/domains") + + def custom_domains_put( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + item: str = "", + ) -> Any: + _custom_id(item) + domains = body.get("domains") or [] + if not isinstance(domains, list): + raise ServiceError( + 422, {"error": "invalid", "field": "domains", "message": "a list of domains"} + ) + self.audit(identity, "own category domains", conn=conn, id=item, count=len(domains)) + return self.client(conn).request( + "PUT", + f"/v1/catalog/custom/categories/{item}/domains", + body={"domains": [str(d) for d in domains]}, + ) + + def filter_lookup( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + domain = str((query or {}).get("domain") or "").strip() + domain_segment(domain) # no domain: refused here, nothing is sent + return self.client(conn).request( + "GET", instance_path(name, "filter", "lookup"), query={"domain": domain} + ) + + def filter_stats( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + days = int_param(query, "days", 30) + return self.client(conn).request( + "GET", + instance_path(name, "filter", "stats"), + query={"days": days}, + timeouts=(SHORT[0], 60.0), + ) + + # ------------------------------------------- activity log settings and audit (E1, ADR-023) + def activity( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + """Activity log settings of every instance of one server, with what is stored.""" + return self.client(conn).request("GET", "/v1/activity") + + def activity_settings( + self, + identity: str, + query: dict[str, Any], + body: dict[str, Any], + conn: str = "", + name: str = "", + ) -> Any: + """Switch the log of one instance on/off, set its retention. Switching on needs the + confirmed privacy notice; who confirmed it is the logged-in global administrator.""" + enabled = body.get("enabled") + if not isinstance(enabled, bool): + raise ServiceError(422, {"error": "invalid", "field": "enabled", "message": "bool"}) + payload: dict[str, Any] = {"enabled": enabled, "actor": identity} + retention = int_body(body, "retention_days") + if retention is not None: + payload["retention_days"] = retention + if enabled and body.get("privacy_confirmed") is True: + payload["ack_by"] = identity + if not enabled: + payload["delete_data"] = body.get("delete_data") is True + self.audit( + identity, + "activity settings", + connection=conn, + instance=name, + enabled=enabled, + retention=payload.get("retention_days"), + delete_data=payload.get("delete_data"), + ) + try: + # switching on or off replaces the container (health-gated): the long timeout + return self.client(conn).request( + "PUT", instance_path(name, "activity"), payload, timeouts=LONG + ) + finally: + self.forget(conn) + + def activity_audit( + self, identity: str, query: dict[str, Any], body: dict[str, Any], conn: str = "" + ) -> Any: + """Who read activity data on this server (newest first, 100 per page).""" + days = max(1, min(int_param(query, "days", 7) or 7, 3650)) + offset = max(0, int_param(query, "offset", 0) or 0) + actor = str((query or {}).get("actor") or "").strip() or None + now = int(time.time()) + return self.client(conn).request( + "GET", + "/v1/activity/audit", + query={ + "since": now - days * 86400, + "until": now + 1, + "actor": actor, + "limit": 100, + "offset": offset, + }, + ) diff --git a/webui/lmn_squid/views.py b/webui/lmn_squid/views.py index f462f85..18f0611 100644 --- a/webui/lmn_squid/views.py +++ b/webui/lmn_squid/views.py @@ -20,7 +20,6 @@ from __future__ import annotations import ipaddress -import re import logging import time from functools import wraps @@ -32,15 +31,7 @@ from aj.auth import SecurityError, authorize from jadi import component -from .client import ( - LONG, - SHORT, - ControlPlaneClient, - ControlPlaneError, - domain_segment, - instance_path, -) -from . import jobs, precheck, sshsetup +from . import jobs, manage_core, precheck, sshsetup from . import keytab as keytab_mod from . import sitefacts as site_mod from .connections import ( @@ -49,8 +40,6 @@ RESERVED_NAMES, BrokenEntry, Connection, - ConnectionConfigError, - ConnectionFileError, ConnectionStore, ) @@ -61,11 +50,6 @@ PREFIX = r"/api/lmn/squid" CONN = r"(?P[^/]+)" NAME = r"(?P[^/]+)" -LIST_KINDS = ("blocklist", "noauth", "allowlist") -# own category (own_x) or own source (own-x) id as the control plane accepts it -CUSTOM_ID_RE = re.compile(r"^own[_-][a-z0-9_-]{1,30}$") -FILTER_KEYS = ("categories", "variants", "schedules", "safesearch") -BULK_MAX = 200 HOSTKEY_TTL = 900.0 # Host keys fetched in step 1 of the setup, per target IP, kept in this worker only: the @@ -163,23 +147,13 @@ def wrapper(self: Any, http_context: Any, **kwargs: Any) -> Any: check_same_origin(http_context) try: return fx(self, http_context, **kwargs) - except ControlPlaneError as exc: - raise EndpointReturn(exc.http_status(), exc.as_dict()) from None - except ConnectionFileError as exc: - # 409, not 500: the WebUI answers every 500 with its own "this is likely a bug" - # dialog on top of the plugin's message. - raise EndpointReturn(409, {"error": "config", "message": exc.message}) from None - except ConnectionConfigError as exc: - raise EndpointReturn( - 422, - {"error": "invalid", "field": exc.field, "code": exc.code, "message": exc.message}, - ) from None - except jobs.JobBusy as exc: - raise EndpointReturn( - 409, {"error": "busy", "message": str(exc), "job": exc.job} - ) from None - except jobs.JobError as exc: - raise EndpointReturn(500, {"error": "job", "message": str(exc)}) from None + except EndpointReturn: + raise + except Exception as exc: + answer = manage_core.error_answer(exc) + if answer is None: + raise + raise EndpointReturn(*answer) from None wrapper.global_admin_only = True # type: ignore[attr-defined] return wrapper @@ -195,18 +169,6 @@ def _body(http_context: Any) -> dict[str, Any]: return data -def _int_param(http_context: Any, key: str, default: int | None = None) -> int | None: - value = (http_context.query or {}).get(key) - if value in (None, ""): - return default - try: - return int(value) - except (TypeError, ValueError): - raise EndpointReturn( - 422, {"error": "invalid", "field": key, "message": f"{key} must be a number"} - ) from None - - @component(HttpPlugin) class Handler(HttpPlugin): def __init__(self, context: Any) -> None: @@ -214,8 +176,20 @@ def __init__(self, context: Any) -> None: self.store = ConnectionStore(CONFIG_PATH) # ------------------------------------------------------------------ helpers - def _client(self, conn: str) -> ControlPlaneClient: - return ControlPlaneClient(self._connection(conn)) + @property + def svc(self) -> manage_core.ManageService: + # built per use: tests replace ``store`` after construction + from . import activity_views + + return manage_core.ManageService(self.store, forget=activity_views.forget_instances) + + def _identity(self) -> str: + return str(getattr(self.context, "identity", None) or "") + + def _svc(self, route: str, http_context: Any, /, **params: str) -> Any: + """One route of manage_core with the checked identity, the query and the JSON body.""" + body = _body(http_context) if http_context.method.upper() in STATE_CHANGING else {} + return getattr(self.svc, route)(self._identity(), http_context.query or {}, body, **params) def _connection(self, conn: str) -> Connection: found = self.store.get(conn) @@ -425,33 +399,28 @@ def handle_keytab(self, http_context: Any, conn: str = "") -> Any: return {"job": job} # -------------------------------------------------------------- connections + # The routes below are thin: the logic is shared with the edulution plugin in + # manage_core.ManageService (one method per route, same name without "handle_"). @get(PREFIX + r"/connections") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_connections(self, http_context: Any) -> Any: - """Every entry of the file; a broken one with ``broken`` and ``problem``.""" - return [item.public() for item in self.store.items()] + return self._svc("connections", http_context) @post(PREFIX + r"/connections") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_connection_add(self, http_context: Any) -> Any: - conn = self.store.add(_body(http_context)) - self._audit("connection add", conn=conn.name, url=conn.url) - return conn.public() + return self._svc("connection_add", http_context) @put(PREFIX + r"/connections/" + CONN) @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_connection_update(self, http_context: Any, conn: str = "") -> Any: - updated = self.store.update(conn, _body(http_context)) - if updated is None: - raise EndpointReturn(404, {"error": "unknown_connection", "message": conn}) - self._audit("connection update", conn=conn, url=updated.url) - return updated.public() + return self._svc("connection_update", http_context, conn=conn) @delete(PREFIX + r"/connections/" + CONN) @authorize(PERM_CHANGE) @@ -464,9 +433,7 @@ def handle_connection_remove(self, http_context: Any, conn: str = "") -> Any: "1", "true", ) - removed = self.store.remove(conn) - if removed is None: - raise EndpointReturn(404, {"error": "unknown_connection", "message": conn}) + removed = self.svc.connection_remove(self._identity(), conn) self._audit("connection remove", conn=conn, disable_account=disable) answer: dict[str, Any] = {"removed": conn} if disable: @@ -488,109 +455,68 @@ def _disable_account(self, removed: Connection | BrokenEntry) -> dict[str, Any]: self._audit("service account disabled", account=account, fqdn=removed.fqdn) return {"ok": True, "account": account, "message": text} - # ------------------------------------------------------------ per server @get(PREFIX + "/" + CONN + r"/test") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_test(self, http_context: Any, conn: str = "") -> Any: - """Test a connection: reachability (health, no token) and the token (version).""" - client = self._client(conn) - health = client.request("GET", "/v1/health", auth=False) - version = client.request("GET", "/v1/version") - return {"health": health, "version": (version or {}).get("version")} + return self._svc("test", http_context, conn=conn) @get(PREFIX + "/" + CONN + r"/overview") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_overview(self, http_context: Any, conn: str = "") -> Any: - """Version, instances and their container state of one server (one card of the page).""" - client = self._client(conn) - version = (client.request("GET", "/v1/version") or {}).get("version") - instances = client.request("GET", "/v1/instances") or [] - try: - states = client.request("GET", "/v1/status") or [] - except ControlPlaneError as exc: - if exc.status != 404: # a control plane before 7.3.10 has no bulk status - raise - states = [client.request("GET", instance_path(i["name"], "status")) for i in instances] - by_name = {s.get("name"): s for s in states if isinstance(s, dict)} - for inst in instances: - inst["state"] = by_name.get(inst.get("name")) - return {"version": version, "instances": instances} + return self._svc("overview", http_context, conn=conn) @get(PREFIX + "/" + CONN + r"/schema") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_schema(self, http_context: Any, conn: str = "") -> Any: - try: - return self._client(conn).request("GET", "/v1/schema") - except ControlPlaneError as exc: - if exc.status == 404: # older control plane: the form works without defaults - return {"instance": None, "instance_patch": None} - raise + return self._svc("schema", http_context, conn=conn) @post(PREFIX + "/" + CONN + r"/(?Pupdate-all|reconcile)") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_server_op(self, http_context: Any, conn: str = "", op: str = "") -> Any: - client = self._client(conn) - self._audit(op, conn=conn) - return client.request("POST", f"/v1/{op}", timeouts=LONG) + return self._svc("server_op", http_context, conn=conn, op=op) - # ------------------------------------------------------------- instances @get(PREFIX + "/" + CONN + r"/instances") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_instances(self, http_context: Any, conn: str = "") -> Any: - return self._client(conn).request("GET", "/v1/instances") + return self._svc("instances", http_context, conn=conn) @post(PREFIX + "/" + CONN + r"/instances") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_instance_create(self, http_context: Any, conn: str = "") -> Any: - client = self._client(conn) - body = _body(http_context) - self._audit("instance create", conn=conn, school=body.get("school"), role=body.get("role")) - return client.request("POST", "/v1/instances", body=body, timeouts=LONG) + return self._svc("instance_create", http_context, conn=conn) @get(PREFIX + "/" + CONN + r"/instances/" + NAME) @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_instance_get(self, http_context: Any, conn: str = "", name: str = "") -> Any: - client = self._client(conn) - return client.request("GET", instance_path(name)) + return self._svc("instance_get", http_context, conn=conn, name=name) @patch(PREFIX + "/" + CONN + r"/instances/" + NAME) @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_instance_patch(self, http_context: Any, conn: str = "", name: str = "") -> Any: - client = self._client(conn) - path = instance_path(name) - body = _body(http_context) - self._audit("instance patch", conn=conn, name=name, fields=",".join(sorted(body))) - return client.request("PATCH", path, body=body, timeouts=LONG) + return self._svc("instance_patch", http_context, conn=conn, name=name) @delete(PREFIX + "/" + CONN + r"/instances/" + NAME) @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_instance_delete(self, http_context: Any, conn: str = "", name: str = "") -> Any: - client = self._client(conn) - path = instance_path(name) - keep = str((http_context.query or {}).get("keep_logs", "")).lower() in ("1", "true") - self._audit("instance delete", conn=conn, name=name, keep_logs=keep) - client.request( - "DELETE", path, query={"keep_logs": "true" if keep else "false"}, timeouts=LONG - ) - return {"deleted": name} + return self._svc("instance_delete", http_context, conn=conn, name=name) @post(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Pstart|stop|restart|rollback)") @authorize(PERM_CHANGE) @@ -599,29 +525,21 @@ def handle_instance_delete(self, http_context: Any, conn: str = "", name: str = def handle_instance_action( self, http_context: Any, conn: str = "", name: str = "", action: str = "" ) -> Any: - client = self._client(conn) - path = instance_path(name, action) - self._audit(f"instance {action}", conn=conn, name=name) - return client.request("POST", path, timeouts=LONG) + return self._svc("instance_action", http_context, conn=conn, name=name, action=action) @post(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/update") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_instance_update(self, http_context: Any, conn: str = "", name: str = "") -> Any: - client = self._client(conn) - path = instance_path(name, "update") - body = {k: v for k, v in _body(http_context).items() if k == "image" and v} - self._audit("instance update", conn=conn, name=name, image=body.get("image", "default")) - return client.request("POST", path, body=body, timeouts=LONG) + return self._svc("instance_update", http_context, conn=conn, name=name) @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/status") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_instance_status(self, http_context: Any, conn: str = "", name: str = "") -> Any: - client = self._client(conn) - return client.request("GET", instance_path(name, "status")) + return self._svc("instance_status", http_context, conn=conn, name=name) @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Plogs|logs/access)") @authorize(PERM_LIST) @@ -630,17 +548,8 @@ def handle_instance_status(self, http_context: Any, conn: str = "", name: str = def handle_instance_logs( self, http_context: Any, conn: str = "", name: str = "", kind: str = "" ) -> Any: - client = self._client(conn) - path = instance_path(name, *kind.split("/")) - query = { - "tail": _int_param(http_context, "tail"), - "since": _int_param(http_context, "since"), - "until": _int_param(http_context, "until"), - "grep": (http_context.query or {}).get("grep") or None, - } - return client.request("GET", path, query=query, timeouts=(SHORT[0], 60.0)) + return self._svc("instance_logs", http_context, conn=conn, name=name, kind=kind) - # ----------------------------------------------- blocklist and noauth list @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Pblocklist|noauth|allowlist)") @authorize(PERM_LIST) @endpoint(api=True) @@ -648,8 +557,7 @@ def handle_instance_logs( def handle_list_get( self, http_context: Any, conn: str = "", name: str = "", kind: str = "" ) -> Any: - client = self._client(conn) - return client.request("GET", instance_path(name, kind)) + return self._svc("list_get", http_context, conn=conn, name=name, kind=kind) @post(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/(?Pblocklist|noauth|allowlist)") @authorize(PERM_CHANGE) @@ -658,11 +566,7 @@ def handle_list_get( def handle_list_add( self, http_context: Any, conn: str = "", name: str = "", kind: str = "" ) -> Any: - client = self._client(conn) - path = instance_path(name, kind) - domain = str(_body(http_context).get("domain") or "") - self._audit(f"{kind} add", conn=conn, name=name, domain=domain) - return client.request("POST", path, body={"domain": domain}) + return self._svc("list_add", http_context, conn=conn, name=name, kind=kind) @delete( PREFIX @@ -678,10 +582,9 @@ def handle_list_add( def handle_list_remove( self, http_context: Any, conn: str = "", name: str = "", kind: str = "", domain: str = "" ) -> Any: - client = self._client(conn) - path = instance_path(name, kind, domain_segment(domain)) - self._audit(f"{kind} remove", conn=conn, name=name, domain=domain) - return client.request("DELETE", path) + return self._svc( + "list_remove", http_context, conn=conn, name=name, kind=kind, domain=domain + ) @post( PREFIX @@ -697,124 +600,56 @@ def handle_list_remove( def handle_list_reload( self, http_context: Any, conn: str = "", name: str = "", kind: str = "" ) -> Any: - client = self._client(conn) - path = instance_path(name, kind, "reload") - self._audit(f"{kind} reload", conn=conn, name=name) - return client.request("POST", path, timeouts=(SHORT[0], 60.0)) + return self._svc("list_reload", http_context, conn=conn, name=name, kind=kind) - # ------------------------------------------------ category filter (ADR-022) @get(PREFIX + "/" + CONN + r"/catalog") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_catalog(self, http_context: Any, conn: str = "") -> Any: - """Catalog of one proxy host: age, categories with groups, sources, licences, profiles.""" - return self._client(conn).request("GET", "/v1/catalog") + return self._svc("catalog", http_context, conn=conn) @post(PREFIX + "/" + CONN + r"/catalog/update") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_catalog_update(self, http_context: Any, conn: str = "") -> Any: - self._audit("catalog update", conn=conn) - return self._client(conn).request("POST", "/v1/catalog/update") + return self._svc("catalog_update", http_context, conn=conn) @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_filter_get(self, http_context: Any, conn: str = "", name: str = "") -> Any: - return self._client(conn).request("GET", instance_path(name, "filter")) + return self._svc("filter_get", http_context, conn=conn, name=name) @put(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_filter_put(self, http_context: Any, conn: str = "", name: str = "") -> Any: - """Categories, schedules and SafeSearch of one instance (validated by the API).""" - body = _filter_body(_body(http_context)) - self._audit( - "filter set", conn=conn, name=name, categories=",".join(body.get("categories") or []) - ) - return self._client(conn).request( - "PUT", instance_path(name, "filter"), body=body, timeouts=(SHORT[0], 60.0) - ) + return self._svc("filter_put", http_context, conn=conn, name=name) @post(PREFIX + r"/filter/bulk") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_filter_bulk(self, http_context: Any) -> Any: - """The same filter settings on several instances, on one or more proxy servers. - - One request per instance, one after the other; the answer lists every instance with - its own result, so one server that is down does not hide the others. - """ - body = _body(http_context) - targets = body.get("targets") - if not isinstance(targets, list) or not targets or len(targets) > BULK_MAX: - raise EndpointReturn( - 422, - { - "error": "invalid", - "field": "targets", - "message": f"1 to {BULK_MAX} instances expected", - }, - ) - settings = _filter_body(body.get("settings")) - results: list[dict[str, Any]] = [] - for target in targets: - target = target if isinstance(target, dict) else {} - conn, name = str(target.get("conn") or ""), str(target.get("name") or "") - row: dict[str, Any] = {"conn": conn, "name": name} - try: - found = self.store.get(conn) - if found is None: - raise ControlPlaneError("invalid", f"unknown connection {conn!r}") - answer = ControlPlaneClient(found).request( - "PUT", instance_path(name, "filter"), body=settings, timeouts=(SHORT[0], 60.0) - ) - answer = answer if isinstance(answer, dict) else {} - row.update( - ok=True, - applied=answer.get("applied"), - reason=answer.get("reason"), - detail=answer.get("detail"), - ) - except ControlPlaneError as exc: - row.update(ok=False, **exc.as_dict()) - results.append(row) - self._audit( - "filter bulk", - targets=",".join(f"{r['conn']}/{r['name']}" for r in results), - categories=",".join(settings.get("categories") or []), - failed=sum(1 for r in results if not r["ok"]), - ) - return {"results": results} + return self._svc("filter_bulk", http_context) - # ------------------------------------------- own sources and categories (per server) @get(PREFIX + "/" + CONN + r"/catalog/custom") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_custom_get(self, http_context: Any, conn: str = "") -> Any: - return self._client(conn).request("GET", "/v1/catalog/custom") + return self._svc("custom_get", http_context, conn=conn) @post(PREFIX + "/" + CONN + r"/catalog/custom/(?Pcategories|sources)") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_custom_add(self, http_context: Any, conn: str = "", kind: str = "") -> Any: - """An own category or source; the control plane validates every field.""" - body = _body(http_context) - keys = ( - ("id", "label", "description") - if kind == "categories" - else ("id", "name", "url", "format", "category", "license", "min_entries", "max_mb") - ) - body = {k: body[k] for k in keys if k in body} - self._audit(f"own {kind} add", conn=conn, id=body.get("id"), url=body.get("url")) - return self._client(conn).request("POST", f"/v1/catalog/custom/{kind}", body=body) + return self._svc("custom_add", http_context, conn=conn, kind=kind) @delete(PREFIX + "/" + CONN + r"/catalog/custom/(?Pcategories|sources)/(?P[^/]+)") @authorize(PERM_CHANGE) @@ -823,152 +658,53 @@ def handle_custom_add(self, http_context: Any, conn: str = "", kind: str = "") - def handle_custom_remove( self, http_context: Any, conn: str = "", kind: str = "", item: str = "" ) -> Any: - if not CUSTOM_ID_RE.match(item): - raise EndpointReturn(422, {"error": "invalid", "field": "id", "message": "id"}) - self._audit(f"own {kind} remove", conn=conn, id=item) - self._client(conn).request("DELETE", f"/v1/catalog/custom/{kind}/{item}") - return {"removed": item} + return self._svc("custom_remove", http_context, conn=conn, kind=kind, item=item) @get(PREFIX + "/" + CONN + r"/catalog/custom/categories/(?P[^/]+)/domains") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_custom_domains_get(self, http_context: Any, conn: str = "", item: str = "") -> Any: - if not CUSTOM_ID_RE.match(item): - raise EndpointReturn(422, {"error": "invalid", "field": "id", "message": "id"}) - return self._client(conn).request("GET", f"/v1/catalog/custom/categories/{item}/domains") + return self._svc("custom_domains_get", http_context, conn=conn, item=item) @put(PREFIX + "/" + CONN + r"/catalog/custom/categories/(?P[^/]+)/domains") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_custom_domains_put(self, http_context: Any, conn: str = "", item: str = "") -> Any: - if not CUSTOM_ID_RE.match(item): - raise EndpointReturn(422, {"error": "invalid", "field": "id", "message": "id"}) - domains = _body(http_context).get("domains") or [] - if not isinstance(domains, list): - raise EndpointReturn( - 422, {"error": "invalid", "field": "domains", "message": "a list of domains"} - ) - self._audit("own category domains", conn=conn, id=item, count=len(domains)) - return self._client(conn).request( - "PUT", - f"/v1/catalog/custom/categories/{item}/domains", - body={"domains": [str(d) for d in domains]}, - ) + return self._svc("custom_domains_put", http_context, conn=conn, item=item) @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter/lookup") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_filter_lookup(self, http_context: Any, conn: str = "", name: str = "") -> Any: - domain = str((http_context.query or {}).get("domain") or "").strip() - domain_segment(domain) # no domain: refused here, nothing is sent - return self._client(conn).request( - "GET", instance_path(name, "filter", "lookup"), query={"domain": domain} - ) + return self._svc("filter_lookup", http_context, conn=conn, name=name) @get(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/filter/stats") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_filter_stats(self, http_context: Any, conn: str = "", name: str = "") -> Any: - days = _int_param(http_context, "days", 30) - return self._client(conn).request( - "GET", - instance_path(name, "filter", "stats"), - query={"days": days}, - timeouts=(SHORT[0], 60.0), - ) + return self._svc("filter_stats", http_context, conn=conn, name=name) - # ------------------------------------------- activity log settings and audit (E1, ADR-023) @get(PREFIX + "/" + CONN + r"/activity") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_activity(self, http_context: Any, conn: str = "") -> Any: - """Activity log settings of every instance of one server, with what is stored.""" - return self._client(conn).request("GET", "/v1/activity") + return self._svc("activity", http_context, conn=conn) - @put(PREFIX + "/" + CONN + "/instances/" + NAME + r"/activity") + @put(PREFIX + "/" + CONN + r"/instances/" + NAME + r"/activity") @authorize(PERM_CHANGE) @endpoint(api=True) @global_admin_only def handle_activity_settings(self, http_context: Any, conn: str = "", name: str = "") -> Any: - """Switch the log of one instance on/off, set its retention. Switching on needs the - confirmed privacy notice; who confirmed it is the logged-in global administrator.""" - from . import activity_views - - body = _body(http_context) - enabled = body.get("enabled") - if not isinstance(enabled, bool): - raise EndpointReturn(422, {"error": "invalid", "field": "enabled", "message": "bool"}) - identity = str(getattr(self.context, "identity", None) or "") - payload: dict[str, Any] = {"enabled": enabled, "actor": identity} - retention = _int_param_body(body, "retention_days") - if retention is not None: - payload["retention_days"] = retention - if enabled and body.get("privacy_confirmed") is True: - payload["ack_by"] = identity - if not enabled: - payload["delete_data"] = body.get("delete_data") is True - self._audit( - "activity settings", - connection=conn, - instance=name, - enabled=enabled, - retention=payload.get("retention_days"), - delete_data=payload.get("delete_data"), - ) - try: - # switching on or off replaces the container (health-gated): the long timeout - return self._client(conn).request( - "PUT", instance_path(name, "activity"), payload, timeouts=LONG - ) - finally: - activity_views.forget_instances(conn) + return self._svc("activity_settings", http_context, conn=conn, name=name) @get(PREFIX + "/" + CONN + r"/activity/audit") @authorize(PERM_LIST) @endpoint(api=True) @global_admin_only def handle_activity_audit(self, http_context: Any, conn: str = "") -> Any: - """Who read activity data on this server (newest first, 100 per page).""" - days = max(1, min(_int_param(http_context, "days", 7) or 7, 3650)) - offset = max(0, _int_param(http_context, "offset", 0) or 0) - actor = str((http_context.query or {}).get("actor") or "").strip() or None - now = int(time.time()) - return self._client(conn).request( - "GET", - "/v1/activity/audit", - query={ - "since": now - days * 86400, - "until": now + 1, - "actor": actor, - "limit": 100, - "offset": offset, - }, - ) - - -def _int_param_body(body: dict[str, Any], key: str) -> int | None: - value = body.get(key) - if value in (None, ""): - return None - if isinstance(value, bool): - raise EndpointReturn(422, {"error": "invalid", "field": key, "message": f"{key}"}) - try: - return int(value) - except (TypeError, ValueError): - raise EndpointReturn( - 422, {"error": "invalid", "field": key, "message": f"{key} must be a number"} - ) from None - - -def _filter_body(data: Any) -> dict[str, Any]: - """Only the keys of the API's FilterSettings go through; the API validates the values.""" - if not isinstance(data, dict): - raise EndpointReturn( - 422, {"error": "invalid", "field": "settings", "message": "settings expected"} - ) - return {k: data[k] for k in FILTER_KEYS if k in data} + return self._svc("activity_audit", http_context, conn=conn) diff --git a/webui/tests/test_build.py b/webui/tests/test_build.py index 1662a95..19d1300 100644 --- a/webui/tests/test_build.py +++ b/webui/tests/test_build.py @@ -37,6 +37,7 @@ def test_build_produces_what_the_webui_serves(tmp_path: Path) -> None: "locale/de/LC_MESSAGES/app.js", "locale/de/LC_MESSAGES/app.po", "main.py", + "manage_core.py", "permissions.yml", "plugin.yml", "precheck.py", diff --git a/webui/tests/test_manage_core.py b/webui/tests/test_manage_core.py new file mode 100644 index 0000000..1af33fb --- /dev/null +++ b/webui/tests/test_manage_core.py @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The management routes are shared with the edulution plugin (manage_core.ROUTES): every one +of them must be an aj endpoint of the WebUI with the same method, path and permission, so the +two front ends cannot drift apart.""" + +from __future__ import annotations + +import pytest + +from lmn_squid import manage_core, views + + +@pytest.mark.parametrize("method,path,name,change", manage_core.ROUTES) +def test_every_shared_route_is_a_webui_endpoint( + method: str, path: str, name: str, change: bool +) -> None: + fn = views.Handler.__dict__.get(f"handle_{name}") + assert fn is not None, f"views.Handler.handle_{name} missing" + assert fn.method == method.lower() + assert fn.url_pattern.pattern == f"^{views.PREFIX}{path}$" + assert fn.permission_id == (views.PERM_CHANGE if change else views.PERM_LIST) + assert getattr(fn, "global_admin_only", False) or getattr( + fn.__wrapped__, "global_admin_only", False + ) + + +def test_route_lookup() -> None: + svc = manage_core.ManageService(store=None) # type: ignore[arg-type] + assert svc.route("GET", "/a/instances/x/filter/lookup") == ( + "filter_lookup", + False, + {"conn": "a", "name": "x"}, + ) + assert svc.route("DELETE", "/a/instances/x/noauth/example.org")[0] == "list_remove" + assert svc.route("POST", "/a/instances/x/noauth/reload")[0] == "list_reload" + assert svc.route("GET", "/a/instances/x/logs/access")[2]["kind"] == "logs/access" + assert svc.route("POST", "/connections/a") is None From f2bff364eb917f3299b4bcff63175b974fafd68a Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Thu, 26 Nov 2026 11:01:39 +0100 Subject: [PATCH 02/30] feat(webui): keep allowed TLS clients on setup; keytab maker and TLS clients injectable tls_script keeps the addresses tls_allowed_clients already holds and adds the setup's own, so a setup from one front end does not lock out another. The keytab steps of provision_and_deliver become a KeytabMaker (local_keytab is the old behaviour) and the setup takes its TLS clients from the payload (default: the school server): the edulution plugin runs the same steps with the keytab made on the DC over SSH. --- debian/changelog | 3 ++ webui/lmn_squid/sshsetup.py | 77 +++++++++++++++++++++++++++++-------- webui/tests/test_remote.py | 27 +++++++++++++ 3 files changed, 91 insertions(+), 16 deletions(-) diff --git a/debian/changelog b/debian/changelog index 56bc389..c6754af 100644 --- a/debian/changelog +++ b/debian/changelog @@ -230,6 +230,9 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium log on receives no data. Quarantined spool files are moved beside the spool (also unreadable ones); a file collected completely is never quarantined. + * Setting up a proxy host again from the WebUI keeps the clients its TLS + listener already allows (tls_allowed_clients) and adds the school + server, instead of replacing the list. -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium diff --git a/webui/lmn_squid/sshsetup.py b/webui/lmn_squid/sshsetup.py index b5a6ec3..d9ccd27 100644 --- a/webui/lmn_squid/sshsetup.py +++ b/webui/lmn_squid/sshsetup.py @@ -32,7 +32,7 @@ import shlex import socket import time -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable from urllib.parse import urlsplit @@ -297,6 +297,8 @@ class Setup: schools: list[str] keytab: bool timezone: str = "" # the school server's zone, set on the VM too (filter schedules) + # clients of the TLS listener this setup needs (default: the school server) + tls_allow: list[str] = field(default_factory=list) @property def short(self) -> str: @@ -337,6 +339,8 @@ def from_payload(cls, p: dict[str, Any]) -> "Setup": timezone=str(p.get("timezone") or "") if TZ_RE.match(str(p.get("timezone") or "")) else "", + tls_allow=[str(ipaddress.IPv4Address(str(a))) for a in p.get("tls_allow") or []] + or [serverip], ) @@ -588,13 +592,30 @@ def package_script(remote_deb: str, sha: str) -> str: ) -def tls_script(ip: str, serverip: str) -> str: - """Turn the TLS listener on and check that it really listens; on failure say why.""" +CONFIG_YML = "/etc/linuxmuster-squid/config.yml" + + +def tls_script(ip: str, allow: str | list[str], config: str = CONFIG_YML) -> str: + """Turn the TLS listener on and check that it really listens; on failure say why. + + ``allow``: the clients this setup needs (the school server; for the edulution plugin the + edulution host and the school server). Clients the listener already allows stay allowed, + so a setup run from the WebUI does not lock out the edulution plugin or the other way + round (``tls_allowed_clients`` is the JSON list ``lmnsquid tls enable`` writes). + """ qip, port = shlex.quote(ip), TLS_PORT listen = shlex.quote(f"{ip}:{port}") + wanted = [allow] if isinstance(allow, str) else list(allow) + args = " ".join(f"--allow {shlex.quote(a)}" for a in wanted) + keep = ( + f"set -- {args}; if [ -f {shlex.quote(config)} ]; then " + f"for a in $(sed -n 's/^tls_allowed_clients: *//p' {shlex.quote(config)} " + "| tr -d '[]\",'); do " + 'case "$a" in *[!0-9a-fA-F.:/]*) ;; *) set -- "$@" --allow "$a" ;; esac; done; fi; ' + ) return ( - f"set -e; lmnsquid tls enable --bind-host {qip} --port {port} " - f"--allow {shlex.quote(serverip)}; systemctl restart linuxmuster-squid; " + "set -e; " + keep + f'lmnsquid tls enable --bind-host {qip} --port {port} "$@"; ' + "systemctl restart linuxmuster-squid; " "ok=0; for i in $(seq 1 40); do if lmnsquid health >/dev/null 2>&1; then ok=1; break; fi; " "sleep 1; done; " f"if [ $ok = 1 ]; then for i in $(seq 1 15); do " @@ -622,6 +643,7 @@ def run_setup( keytab_runner: keytab_mod.Runner = keytab_mod.run_cmd, now: Callable[[], float] = time.time, sleep: Callable[[float], None] = time.sleep, + make_keytab: KeytabMaker | None = None, ) -> None: """The fixed step list; stops at the first failed step and says which and why.""" store = store or ConnectionStore(CONFIG_PATH) @@ -727,7 +749,7 @@ def run_setup( current = "tls" rep.set(current, "running") - rep.set(current, "ok", remote.must(current, tls_script(s.ip, s.serverip), timeout=150.0)) + rep.set(current, "ok", remote.must(current, tls_script(s.ip, s.tls_allow), timeout=150.0)) current = "connection" rep.set(current, "running") @@ -759,8 +781,8 @@ def run_setup( if exc.kind == "allowlist": raise StepFailed( current, - f"Der Proxy lässt nur {s.serverip} zu, der Schulserver kommt offenbar mit " - "einer anderen Adresse an (mehrere Netze, NAT). Auf dem Proxy " + f"Der Proxy lässt nur {', '.join(s.tls_allow)} zu, dieser Rechner kommt " + "offenbar mit einer anderen Adresse an (mehrere Netze, NAT). Auf dem Proxy " "'lmnsquid tls enable --bind-host … --allow ' mit der Adresse aus " "'journalctl -u linuxmuster-squid' ausführen, dann erneut starten.", ) from None @@ -773,7 +795,11 @@ def run_setup( current = "keytab" if s.keytab: rep.set(current, "running") - rep.set(current, "ok", provision_and_deliver(cp, s.fqdn, keytab_runner, sleep=sleep)) + rep.set( + current, + "ok", + provision_and_deliver(cp, s.fqdn, keytab_runner, sleep=sleep, make=make_keytab), + ) else: rep.set(current, "skipped", "nicht gewünscht") @@ -817,6 +843,26 @@ def run_setup( client.close() +# fqdn, account, drop_old -> (keytab, "angelegt"/"vorhanden", rotate mode, was disabled) +KeytabMaker = Callable[[str, str, bool], tuple[bytes, str, str, bool]] + + +def local_keytab(run: keytab_mod.Runner = keytab_mod.run_cmd) -> KeytabMaker: + """The keytab made on this host (the WebUI runs as root on the DC): account, rotation, + export by provision-keytab.sh. The edulution plugin runs the same steps on the DC over SSH.""" + + def make(fqdn: str, account: str, drop_old: bool) -> tuple[bytes, str, str, bool]: + # setpassword enables the account as a side effect (Samba's samdb.setpassword calls + # enable_account): the admin started this on purpose, so it is done, but said. + was_disabled = keytab_mod.is_disabled(keytab_mod.account_attrs(account, run)) + state = keytab_mod.ensure_account(account, run) + rotate = "" if state == "angelegt" else ("drop" if drop_old else "keep") + data, _log = keytab_mod.export(fqdn, account, run, rotate=rotate) + return data, state, rotate, was_disabled + + return make + + DELIVER_TRIES = 3 DELIVER_WAIT = 10.0 @@ -853,20 +899,17 @@ def provision_and_deliver( drop_old: bool = False, sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic, + make: KeytabMaker | None = None, ) -> str: """D2: check the proxy first, then account and new key (an existing account is rotated), PUT to every keytab name the host's instances use (retried), then each instance restarted - and waited for until healthy.""" + and waited for until healthy. ``make`` makes the keytab (default: on this host with + ``run``).""" account = keytab_mod.account_name(fqdn) instances = preflight_control_plane(cp) names = keytab_mod.secret_names(instances) try: - # setpassword enables the account as a side effect (Samba's samdb.setpassword calls - # enable_account): the admin started this on purpose, so it is done, but said. - was_disabled = keytab_mod.is_disabled(keytab_mod.account_attrs(account, run)) - state = keytab_mod.ensure_account(account, run) - rotate = "" if state == "angelegt" else ("drop" if drop_old else "keep") - data, _log = keytab_mod.export(fqdn, account, run, rotate=rotate) + data, state, rotate, was_disabled = (make or local_keytab(run))(fqdn, account, drop_old) except keytab_mod.KeytabError as exc: raise StepFailed("keytab", str(exc)) from None for attempt in range(1, DELIVER_TRIES + 1): @@ -925,6 +968,7 @@ def run_keytab( keytab_runner: keytab_mod.Runner = keytab_mod.run_cmd, sleep: Callable[[float], None] = time.sleep, check: Callable[..., precheck.Result] = precheck.keytab_target, + make_keytab: KeytabMaker | None = None, ) -> None: store = store or ConnectionStore(CONFIG_PATH) try: @@ -947,6 +991,7 @@ def run_keytab( keytab_runner, drop_old=bool(payload.get("drop_old_key")), sleep=sleep, + make=make_keytab, ) rep.set("keytab", "ok", text) current = store.get(conn.name) diff --git a/webui/tests/test_remote.py b/webui/tests/test_remote.py index 293b269..caad7ce 100644 --- a/webui/tests/test_remote.py +++ b/webui/tests/test_remote.py @@ -135,6 +135,33 @@ def test_tls_step_says_why_the_listener_is_missing(tmp_path: Path) -> None: assert res.returncode == 0 and "TLS-Listener auf 10.0.0.5:8443" in res.stdout +def test_tls_step_keeps_the_clients_already_allowed(tmp_path: Path) -> None: + """A setup from the WebUI must not lock out the edulution plugin (and the other way + round): the clients in tls_allowed_clients stay, the setup's own are added; a value that + is not an address/CIDR is never passed on.""" + cfg = tmp_path / "config.yml" + cfg.write_text( + 'api_token: "x"\ntls_bind_host: "10.0.0.5"\n' + 'tls_allowed_clients: ["10.0.0.20/32", "10.9.0.0/24", "$(touch /tmp/x)"]\n' + ) + env, calls = stub_env(tmp_path, { + "lmnsquid": "exit 0", "systemctl": "exit 0", + "ss": "echo 'LISTEN 0 2048 10.0.0.5:8443 0.0.0.0:*'", + }) # fmt: skip + res = run_sh(sshsetup.tls_script("10.0.0.5", ["10.0.0.1"], config=str(cfg)), env) + assert res.returncode == 0, res.stdout + enable = next(c for c in calls.read_text().splitlines() if "tls enable" in c) + assert enable == ( + "lmnsquid tls enable --bind-host 10.0.0.5 --port 8443 --allow 10.0.0.1 " + "--allow 10.0.0.20/32 --allow 10.9.0.0/24" + ) + # without a config file (first setup): only the setup's own clients + res = run_sh(sshsetup.tls_script("10.0.0.5", ["10.0.0.1", "10.0.0.20"], config="/nope"), env) + assert res.returncode == 0 + enable = [c for c in calls.read_text().splitlines() if "tls enable" in c][-1] + assert enable.endswith("--port 8443 --allow 10.0.0.1 --allow 10.0.0.20") + + def test_package_is_checked_and_installed_from_a_root_only_copy() -> None: """Security L1: the SSH user cannot swap the file between the check and the install.""" script = sshsetup.package_script("/tmp/lmn-squid-setup.AbCdEf12/x_1_amd64.deb", "ab" * 32) From 602f4391a76e8b03f22a05b6a52e9e02b2b8dcc4 Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Thu, 26 Nov 2026 11:24:05 +0100 Subject: [PATCH 03/30] feat(edulution): container plugin with the WebUI's management and activity view New binary package linuxmuster-squid-edulution (ADR-024) for the edulution host and a container image built from this tree: - a stdlib HTTP server behind edulution's Traefik (forwardAuth edulution-keycloak-auth), identity = X-Auth-User checked against the person's edulution token with edu-api's auth/verify, CSRF by JSON + same Origin/Referer; - the management routes of manage_core and the activity view of activity_core, the scope computed by activity_scope from the AD over LDAPS (pinned certificate, read-only bind); - its own connections to the control planes in the plugin's volume; - precheck, keytab and service-account actions on the DC over SSH with a login per action and a confirmed host key, running the WebUI's own modules there (dc_agent); - setup and keytab jobs with sshsetup's steps (keytab made on the DC, TLS allowlist with the edulution host and the DC); - linuxmuster-squid-edulution up/down/register/unregister/doctor/status on the host, compose project without published ports, Traefik file plugin-lmn-squid.yml; - Python deps only from the hashed edulution/requirements.lock (lock gate extended); - tests: the real server against real control planes, forged headers, roles, scope, CSRF, secrets in answers, LDAPS pinning, the DC agent, the host command; scripts/tests/edulution_it.sh for real Traefik + image + LDAPS + control plane. --- .github/workflows/ci.yml | 8 + debian/changelog | 10 + debian/control | 17 + debian/linuxmuster-squid-edulution.install | 10 + debian/linuxmuster-squid-edulution.postinst | 27 + debian/linuxmuster-squid-edulution.postrm | 25 + debian/linuxmuster-squid-edulution.prerm | 18 + debian/rules | 5 + docs/decisions.md | 96 +++ docs/operations.md | 57 ++ docs/threat-model.md | 3 + edulution/Dockerfile | 50 ++ edulution/Dockerfile.dockerignore | 11 + edulution/build-image.sh | 22 + edulution/build_app.py | 68 ++ edulution/host/docker-compose.yml | 37 + edulution/host/icons/internetnutzung.svg | 3 + edulution/host/icons/squidproxy.svg | 3 + edulution/host/linuxmuster_squid_edulution.py | 518 ++++++++++++++ edulution/host/tested-versions | 4 + edulution/host/traefik/plugin-lmn-squid.yml | 31 + edulution/lmnsquid_edu/__init__.py | 9 + edulution/lmnsquid_edu/auth.py | 173 +++++ edulution/lmnsquid_edu/dc.py | 244 +++++++ edulution/lmnsquid_edu/dc_agent.py | 112 +++ edulution/lmnsquid_edu/ldapdir.py | 248 +++++++ edulution/lmnsquid_edu/runner.py | 79 ++ edulution/lmnsquid_edu/serve.py | 15 + edulution/lmnsquid_edu/server.py | 672 ++++++++++++++++++ edulution/lmnsquid_edu/settings.py | 191 +++++ edulution/pyproject.toml | 26 + edulution/requirements.in | 10 + edulution/requirements.lock | 354 +++++++++ edulution/requirements.lock.license | 3 + edulution/tests/conftest.py | 322 +++++++++ edulution/tests/test_cli.py | 285 ++++++++ edulution/tests/test_ldap_dc.py | 200 ++++++ edulution/tests/test_server.py | 368 ++++++++++ packaging/lock-deps.sh | 5 +- scripts/tests/edulution_it.sh | 127 ++++ scripts/tests/edulution_it/Dockerfile | 9 + scripts/tests/edulution_it/api_checks.py | 231 ++++++ scripts/tests/edulution_it/cp_server.py | 90 +++ scripts/tests/edulution_it/fake_edu_api.py | 63 ++ scripts/tests/edulution_it/slapd.sh | 70 ++ scripts/tests/run.sh | 4 + 46 files changed, 4932 insertions(+), 1 deletion(-) create mode 100644 debian/linuxmuster-squid-edulution.install create mode 100755 debian/linuxmuster-squid-edulution.postinst create mode 100755 debian/linuxmuster-squid-edulution.postrm create mode 100755 debian/linuxmuster-squid-edulution.prerm create mode 100644 edulution/Dockerfile create mode 100644 edulution/Dockerfile.dockerignore create mode 100755 edulution/build-image.sh create mode 100644 edulution/build_app.py create mode 100644 edulution/host/docker-compose.yml create mode 100644 edulution/host/icons/internetnutzung.svg create mode 100644 edulution/host/icons/squidproxy.svg create mode 100755 edulution/host/linuxmuster_squid_edulution.py create mode 100644 edulution/host/tested-versions create mode 100644 edulution/host/traefik/plugin-lmn-squid.yml create mode 100644 edulution/lmnsquid_edu/__init__.py create mode 100644 edulution/lmnsquid_edu/auth.py create mode 100644 edulution/lmnsquid_edu/dc.py create mode 100644 edulution/lmnsquid_edu/dc_agent.py create mode 100644 edulution/lmnsquid_edu/ldapdir.py create mode 100644 edulution/lmnsquid_edu/runner.py create mode 100644 edulution/lmnsquid_edu/serve.py create mode 100644 edulution/lmnsquid_edu/server.py create mode 100644 edulution/lmnsquid_edu/settings.py create mode 100644 edulution/pyproject.toml create mode 100644 edulution/requirements.in create mode 100644 edulution/requirements.lock create mode 100644 edulution/requirements.lock.license create mode 100644 edulution/tests/conftest.py create mode 100644 edulution/tests/test_cli.py create mode 100644 edulution/tests/test_ldap_dc.py create mode 100644 edulution/tests/test_server.py create mode 100755 scripts/tests/edulution_it.sh create mode 100644 scripts/tests/edulution_it/Dockerfile create mode 100644 scripts/tests/edulution_it/api_checks.py create mode 100644 scripts/tests/edulution_it/cp_server.py create mode 100644 scripts/tests/edulution_it/fake_edu_api.py create mode 100755 scripts/tests/edulution_it/slapd.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 85215bc..6dfb631 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -85,6 +85,8 @@ jobs: pytest==9.1.1 \ pytest-asyncio types-PyYAML pip install --require-hashes --no-deps --only-binary :all: -r controlplane/requirements.lock + # the edulution plugin's image dependencies (paramiko, ldap3; PyYAML is the same pin) + pip install --require-hashes --no-deps --only-binary :all: -r edulution/requirements.lock pip install --no-deps ./controlplane pip check - name: ruff check @@ -110,6 +112,12 @@ jobs: # planes (lmnsquid app, fake Docker) on a TLS listener with a self-signed certificate. - name: pytest (WebUI plugin) run: pytest -q webui/tests + - name: mypy (edulution plugin) + run: mypy --config-file edulution/pyproject.toml edulution/lmnsquid_edu edulution/host/linuxmuster_squid_edulution.py edulution/build_app.py + # The edulution plugin's real HTTP server (identity, CSRF, roles, scope) against real + # control planes; apart from webui/tests, both import a package named lmn_squid. + - name: pytest (edulution plugin) + run: pytest -q edulution/tests - name: shellcheck run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck && shellcheck --severity=warning $(git ls-files '*.sh') debian/*.preinst debian/*.postinst debian/*.prerm debian/*.postrm - name: reuse (license compliance) diff --git a/debian/changelog b/debian/changelog index c6754af..2aba620 100644 --- a/debian/changelog +++ b/debian/changelog @@ -233,6 +233,16 @@ linuxmuster-squid (7.3.11) lmn73; urgency=medium * Setting up a proxy host again from the WebUI keeps the clients its TLS listener already allows (tls_allowed_clients) and adds the school server, instead of replacing the list. + * New package linuxmuster-squid-edulution (same version, from this + source) for the edulution host (2.3.117 or newer): the apps + "Squid-Proxy" (global administrators: everything the WebUI plugin's + management page does) and "Internetnutzung" (teachers, school and + global administrators, scope from the AD as in the WebUI) in a + container behind edulution's Traefik, with its own pinned connections + to the proxies and nothing new on the school server. Actions that need + the school server (precheck, keytab) ask for its SSH login each time. + The container image is loaded separately; then + "linuxmuster-squid-edulution up" and "register" (docs/operations.md). -- Kevin Stenzel Sat, 28 Nov 2026 03:59:40 +0100 linuxmuster-squid (7.3.10) lmn73; urgency=medium diff --git a/debian/control b/debian/control index 301e076..29ed3cc 100644 --- a/debian/control +++ b/debian/control @@ -39,3 +39,20 @@ Description: linuxmuster.net WebUI plugin for linuxmuster-squid proxy servers logs, blocklist and noauth list, updates) over their TLS listener with a pinned certificate. Global administrators only. Install linuxmuster-squid on the proxy host itself. + +Package: linuxmuster-squid-edulution +Architecture: all +Depends: ${misc:Depends}, + python3, + iproute2 +Recommends: docker-ce | docker.io, + docker-compose-plugin | docker-compose-v2 +Description: edulution plugin for linuxmuster-squid proxy servers + Two edulution apps on the edulution host: "Squid-Proxy" (global + administrators: proxy servers, instances, filter, lists, updates, logs, + setup of new proxy hosts, keytab) and "Internetnutzung" (teachers and + administrators, scope from the AD like the WebUI's view). A container + behind edulution's Traefik (forwardAuth edulution-keycloak-auth) with its + own pinned connections to the control planes. The container image is not + part of this package; load it with docker load, then run + linuxmuster-squid-edulution up and register. diff --git a/debian/linuxmuster-squid-edulution.install b/debian/linuxmuster-squid-edulution.install new file mode 100644 index 0000000..5a6e826 --- /dev/null +++ b/debian/linuxmuster-squid-edulution.install @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The edulution host's side of the plugin (ADR-024); the command itself is installed by +# debian/rules (execute_after_dh_install-indep) as /usr/sbin/linuxmuster-squid-edulution. +edulution/host/docker-compose.yml usr/share/linuxmuster-squid-edulution/ +edulution/host/tested-versions usr/share/linuxmuster-squid-edulution/ +edulution/host/traefik/plugin-lmn-squid.yml usr/share/linuxmuster-squid-edulution/traefik/ +edulution/host/icons/squidproxy.svg usr/share/linuxmuster-squid-edulution/icons/ +edulution/host/icons/internetnutzung.svg usr/share/linuxmuster-squid-edulution/icons/ diff --git a/debian/linuxmuster-squid-edulution.postinst b/debian/linuxmuster-squid-edulution.postinst new file mode 100755 index 0000000..e38b9a3 --- /dev/null +++ b/debian/linuxmuster-squid-edulution.postinst @@ -0,0 +1,27 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +set -e + +# Start (or move to this version's image) the plugin container and its Traefik route when +# this is an edulution host and the image is loaded. The app tiles need a global +# administrator's login: `linuxmuster-squid-edulution register` (docs/operations.md). +if [ "$1" = configure ]; then + if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then + rc=0 + linuxmuster-squid-edulution up || rc=$? + case "$rc" in + 0) ;; + 2) echo "linuxmuster-squid-edulution: load the image, then run: linuxmuster-squid-edulution up" ;; + *) echo "linuxmuster-squid-edulution: up failed ($rc); see the message above, then run: linuxmuster-squid-edulution up" ;; + esac + if [ ! -e /var/lib/linuxmuster-squid-edulution/registered ]; then + echo "linuxmuster-squid-edulution: create the app tiles with: linuxmuster-squid-edulution register --user " + fi + else + echo "linuxmuster-squid-edulution: Docker is not running; run linuxmuster-squid-edulution up later" + fi +fi + +#DEBHELPER# +exit 0 diff --git a/debian/linuxmuster-squid-edulution.postrm b/debian/linuxmuster-squid-edulution.postrm new file mode 100755 index 0000000..c2e7dcc --- /dev/null +++ b/debian/linuxmuster-squid-edulution.postrm @@ -0,0 +1,25 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +set -e + +# purge: the plugin's data (connections with the proxies' tokens, the directory account) in +# the Docker volume, the compose project and the command's own configuration and state. +if [ "$1" = purge ]; then + project=/srv/docker/edulution-plugin-lmn-squid + conf=/etc/linuxmuster-squid-edulution/plugin.conf + if [ -f "$conf" ]; then + found=$(sed -n 's/^PROJECT_DIR=//p' "$conf" | tail -n 1) + case "$found" in + /srv/*|/opt/*) project=$found ;; + esac + fi + if command -v docker >/dev/null 2>&1; then + docker rm -f edulution-plugin-lmn-squid >/dev/null 2>&1 || true + docker volume rm edulution-plugin-lmn-squid-data >/dev/null 2>&1 || true + fi + rm -rf "$project" /etc/linuxmuster-squid-edulution /var/lib/linuxmuster-squid-edulution +fi + +#DEBHELPER# +exit 0 diff --git a/debian/linuxmuster-squid-edulution.prerm b/debian/linuxmuster-squid-edulution.prerm new file mode 100755 index 0000000..5158896 --- /dev/null +++ b/debian/linuxmuster-squid-edulution.prerm @@ -0,0 +1,18 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +set -e + +# Removing the package removes the container and the Traefik route (the data volume stays +# until purge). An upgrade keeps both: the new postinst moves the container to its image. +if [ "$1" = remove ]; then + linuxmuster-squid-edulution down || true + if [ -e /var/lib/linuxmuster-squid-edulution/registered ]; then + echo "linuxmuster-squid-edulution: the app tiles stay in edulution; remove them with" + echo " linuxmuster-squid-edulution unregister --user (before removing)" + echo " or in edulution: Einstellungen -> Apps" + fi +fi + +#DEBHELPER# +exit 0 diff --git a/debian/rules b/debian/rules index 3c8e742..4cf3447 100755 --- a/debian/rules +++ b/debian/rules @@ -41,6 +41,11 @@ override_dh_auto_install-arch: override_dh_auto_install-indep: /usr/bin/python3 -I webui/build_plugin.py webui/lmn_squid "$(WEBUI_PLUGIN)" +# The edulution plugin's host command (ADR-024): stdlib Python, as a command without suffix. +execute_after_dh_install-indep: + install -D -m 0755 edulution/host/linuxmuster_squid_edulution.py \ + "$(CURDIR)/debian/$(PKG)-edulution/usr/sbin/$(PKG)-edulution" + override_dh_auto_clean: rm -rf controlplane/build controlplane/*.egg-info find webui -name __pycache__ -prune -exec rm -rf {} + diff --git a/docs/decisions.md b/docs/decisions.md index 8852a9c..2678730 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -936,6 +936,102 @@ access stays audited as before; no further allowlist (decision a). Why: a projec school-wide or voluntary and joined by any teacher; its members are not "the teacher's students" the way a class is. Supersedes the project rule of the scope paragraph above. +### ADR-024 — edulution plugin as a third binary package: container behind Traefik, own connections +**Status:** Proposed (2026-11-26, Kevin: task `work/tasks/squid-edulution.md`, decisions 1–3; +hub defaults 4–9). **Decision:** everything the WebUI plugin does is also offered in edulution +(2.3.117), as the binary package `linuxmuster-squid-edulution` (Architecture: all, same source, +same version) for the edulution host, plus a container image built like the squid image. +**Architecture:** one container `edulution-plugin-lmn-squid` (Ubuntu 24.04 by digest, Python +venv only from the hashed `edulution/requirements.lock`: paramiko, ldap3, PyYAML; user 10001, +read-only root, no capabilities, `no-new-privileges`, an init) in its own compose project +`/srv/docker/edulution-plugin-lmn-squid`, attached to `edulution-ui_default` as an external +network, **no `ports:`**. Traefik reaches it through the file +`data/traefik/config/plugin-lmn-squid.yml` (router `PathPrefix(/plugin/lmn-squid/)`, middlewares +`edulution-keycloak-auth@file` and a stripPrefix); the file name is no app name (edulution +deletes `.yml` when an app's proxy setting is empty). Two apps of type `frame` (`/edu-api/ +appconfig`, created and updated by `linuxmuster-squid-edulution register` with a global +administrator's login, removed by `unregister`): **Squid-Proxy** (`/plugin/lmn-squid/manage/`, +access group `role-globaladministrator`) and **Internetnutzung** (`…/activity/`, global and school +administrators, teachers). The tiles only decide who sees a tile; every request is checked on the +server. **Shared code instead of a copy:** the management routes moved from the WebUI's +`views.py` into `webui/lmn_squid/manage_core.py` (one route table, a test keeps the aj endpoints +and the table in step); the activity view is `activity_core.ActivityService` as in the WebUI's +bridge; setup and keytab are `sshsetup`'s steps with an injectable keytab maker and TLS client +list; jobs, connections and the pinned client are the same modules. `edulution/build_app.py` +copies exactly these modules (with an `__init__` of their own, without aj) into the image and +into the tests. **Data path:** the container has its **own** connections (pinned TLS, bearer +token) to the control planes, in its volume (`connections.yml`, `settings.json`, 0600, user +10001); nothing new on the DC. The control plane has one token (ADR-018): the WebUI and the +edulution plugin share it, each in its own file; the proxy's TLS allowlist names both hosts (the +setup from either side now keeps the clients already allowed, `sshsetup.tls_script`). Rotating +the token means updating both connections. +**Identity:** `X-Auth-User` from the forwardAuth middleware (Traefik overwrites a header the +browser sends); because other containers on `edulution-ui_default` could reach the plugin +directly with any header, the request must also carry the person's edulution token (cookie +`authToken` or `Authorization: Bearer`), which the plugin checks itself with the middleware's own +probe `GET http://edu-api:3000/edu-api/auth/verify` (cached 30 s by the token's hash); the user it +names must equal the header, else 401. That probe also gives the session's groups. `root` is +refused (the shared scope code treats `root` as the WebUI's superuser). +**Roles:** management = the session's group `role-globaladministrator` **and**, once the +directory is set up, `sophomorixRole` globaladministrator in the AD (the AD wins; the group alone +only lets a global administrator reach the settings to set the directory up). Activity view = +`sophomorixRole` from the AD in globaladministrator, schooladministrator, teacher (the WebUI's +permission `lm:squid:activity`), else 403 before any proxy is asked; scope refusals are 404 as in +the WebUI (m1). **Scope source: LDAPS to the AD, not `/edu-api/lmn-api`.** The scope is +`activity_scope.scope_for` unchanged, fed by `LdapsDirectory`, which reads the attributes +linuxmusterTools reads (person by `sAMAccountName`; users below `OU=,OU=SCHOOLS`; +classes and projects from `memberOf` by linuxmusterTools' `extract_schoolclasses`/ +`extract_projects` rules; a project's `sophomorixMemberGroups`/`sophomorixAdminGroups`). +Why not lmn-api with the user's token: it works only while edulution holds the person's +linuxmuster password (409 `LmnApiCredentialMissing` otherwise), `school-classes` lists the whole +school, there is no endpoint for "all users of a school with their classes" for a school +administrator, its answers are not versioned (ANLEITUNG §8), and the scope would be a second +implementation that could drift from the WebUI's. LDAPS gives the same code path and the same +answers. **Price:** a read-only directory account stored in the plugin's volume (write-only in the +API, never sent back). edulution already holds one (`edulutionui-binduser`); `global-binduser` +works too; no new kind of trust. The server certificate is pinned (SHA-256, shown and confirmed +by the global administrator in the settings; a new LDAP URL needs a new confirmation); the bind +is sent only after the certificate matched; plain `ldap://` is refused. +**DC access (task decision 7): per action over SSH, nothing stored.** Precheck of a new proxy +host, keytab and disabling a service account need the DC (devices.csv, sam.ldb, samba-tool, +provision-keytab.sh). For each of these actions the global administrator fetches the DC's SSH +host key, compares and confirms its fingerprint (15 minutes; a read-only precheck may be followed +by the setup, a changing action uses the confirmation up) and gives an SSH login (root or a sudo +user) for this action only. The plugin then connects with exactly that key (`RejectPolicy`, +password only, no agent, no key files, as ADR-021), copies `dc_agent.py`, the **unchanged** +WebUI modules `keytab`, `precheck`, `sitefacts`, `runtime`, `client`, `connections` and +`provision-keytab.sh` into a root-only directory, runs one fixed action with `sudo -S python3 -I` +(arguments as base64 JSON; nothing from the browser is executed), reads one JSON line (a keytab +as base64, into memory) and removes the directory, the upload and the sudo credential. So the DC +runs the same checked steps as with the WebUI plugin; the keytab travels DC → plugin over SSH +and plugin → proxy over the pinned TLS connection. Passwords exist only in memory: the request +body is scrubbed after use, jobs get them on stdin (`jobs.spawn`), the job's progress file is +scrubbed (`Reporter.scrub`). Why not linuxmuster-api: it has no keytab, no samba-tool and no +devices.csv precheck; why not a stored key or a service on the DC: a permanent root path from +the edulution host to the DC is exactly what decision 7 rules out. +**CSRF:** edulution's `authToken` cookie is `SameSite=None`; every state-changing request needs +`Content-Type: application/json` and an `Origin` (else `Referer`) equal to the origin the +request came in on (`X-Forwarded-Proto` + host), none at all is refused (m4). +**Frontend:** plain ES2020 modules and own CSS in edulution's look (dark, Lato stack, its CI +colours), no build step, no npm, no framework, no external resources; CSP `script-src 'self'`, +no inline script or style attribute. Deviation from hub default 4 (`@edulution-io/ui-kit` or +React/Tailwind): the ui-kit is AGPL-3.0 (bundling it would put the plugin's pages under AGPL +terms), and React/Tailwind would bring an npm toolchain into the build, which ADR-015 keeps out +(the WebUI plugin made the same choice, ADR-019). +**Stability over edulution updates (ANLEITUNG §8):** the plugin relies on the middleware file +(`# version: v1.0`), the headers, the cookie and the endpoints `auth/verify`, `auth`, +`appconfig`, `groups`, `health/version`; nothing in MongoDB, no edulution container is changed. +`doctor` checks the edulution version (warns outside `tested-versions`), the middleware's +version line, the route file, container, health, network, that no port is published, the route +(401 without login, 200 with), and the tiles. +**Packaging:** the image is not in the .deb (built locally with `edulution/build-image.sh`, +loaded with `docker load` in the lab, later a registry); the package's postinst runs `up` when +the image is there (else it says what to do), prerm `remove` runs `down` (container and route), +postrm `purge` deletes the volume, the project directory and the command's configuration. The +tiles need a login and are removed with `unregister` before removing the package (the prerm +reminds). The setup assistant installs the linuxmuster-squid .deb bundled in the image from the +same build, as the WebUI plugin does. + --- ## Site facts to be verified (P0, enter with source/date) diff --git a/docs/operations.md b/docs/operations.md index 455f63f..364840e 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -563,6 +563,63 @@ messages name the cause: not reachable, timeout, certificate does not match the fingerprint (nothing was sent), token refused, or the control plane's own answer (404, 409, 422 per form field, 5xx). +## From edulution (optional, ADR-024) + +`linuxmuster-squid-edulution` on the **edulution host** (2.3.117 or newer) offers the same as +the WebUI plugin in two edulution apps: **Squid-Proxy** (global administrators) and +**Internetnutzung** (teachers, school and global administrators, scope from the AD). It keeps +its own connections to the proxies and needs nothing new on the school server. + +**Install** (as root on the edulution host): + +```bash +docker load -i linuxmuster-squid-edulution-image.tar.gz # the image of the same build +apt install ./linuxmuster-squid-edulution__all.deb # postinst runs `up` +linuxmuster-squid-edulution register --user global-admin # the two app tiles (asks the password) +linuxmuster-squid-edulution doctor --user global-admin # everything OK? +``` + +`up` writes `/srv/docker/edulution-plugin-lmn-squid/` (compose file, `.env`), starts the +container on `edulution-ui_default` without a published port and then writes the Traefik route +`/data/traefik/config/plugin-lmn-squid.yml`. Options: `--edulution-dir` (default +`/srv/docker/edulution-ui`), `--host-ip` (this host's address as the proxies see it; default the +source address of the default route), `--image` (pins a tag; without it the tag follows the +package version). The settings live in `/etc/linuxmuster-squid-edulution/plugin.conf`. + +**First steps in the app Squid-Proxy** (global administrator): +1. *Schulserver und Verzeichnis*: the DC's address, `ldaps://`, base DN, a read-only bind + account (edulution's own `CN=edulutionui-binduser,OU=Management,OU=GLOBAL,…` or + `global-binduser`; password from `/etc/linuxmuster/.secret/` on the DC), fetch the + LDAPS certificate, compare its fingerprint on the DC (`openssl x509 -noout -fingerprint + -sha256 -in /etc/linuxmuster/ssl/.cert.pem`), confirm, save, *Test*. +2. Connect the proxies: *Connect an existing host* with the same token as the WebUI's connection + (`api_token` in `/etc/linuxmuster-squid/config.yml` on the proxy; one token per control + plane, ADR-018) and the certificate fingerprint; add this host to the proxy's TLS allowlist + first: `lmnsquid tls enable --bind-host --allow --allow `, + `systemctl restart linuxmuster-squid`. Or set up a new VM with the assistant, which allows + both hosts. +3. Actions that need the DC (precheck of a new VM, keytab, disabling a service account) ask for + an SSH login of the DC each time and for the confirmation of the DC's host key + (`ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` on the DC). Nothing is stored. + +**Updates.** A new package version: load its image, then `apt install` (postinst runs `up`, +which moves the container to the new image; without the image loaded nothing changes and the +postinst says so). An **edulution update** (`get.edulution.io/update`) replaces edulution's +compose file and restarts its stack; the plugin's container, compose project, volume and route +file are not touched (tested in the lab, see test-strategy.md). Afterwards run +`linuxmuster-squid-edulution doctor --user `; it warns when the edulution version +is not in `/usr/share/linuxmuster-squid-edulution/tested-versions`. + +**Remove.** `linuxmuster-squid-edulution unregister --user ` (the tiles need a +login), then `apt remove linuxmuster-squid-edulution` (container and route gone, data kept) or +`apt purge` (also the volume with the connections and settings, the compose project and +`/etc/linuxmuster-squid-edulution`). The proxies keep running; remove the edulution host from +their TLS allowlist if it should not come back. + +**Logs:** `docker logs edulution-plugin-lmn-squid` (requests without query strings or bodies, +management actions with user and target, every request of the activity view with user, role +and scope; never a token or password). The proxies keep their own audit of every activity read. + ## Observing ``` diff --git a/docs/threat-model.md b/docs/threat-model.md index 1a64ab2..bbba830 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -48,6 +48,9 @@ Risks + countermeasures. Grows per roadmap phase; the negative tests for it live | T25 | **The users list comes from the WebUI** (ADR-023): the proxy cannot check who asks; a stolen token reads everything | the token is the global administrator's credential already (T5, T18); the list is computed on the server, never taken from the browser; the audit names the person the WebUI reports and, for the CLI, `cli:`; the WebUI logs every request of the view, refused ones and those without a proxy request included, to its system log (`journalctl -t lmn-squid-activity`) | `test_activity_views.py` (out-of-scope requests never reach a proxy) | | T26 | **Spool and day files on the proxy host** (ADR-023): another local user reads them; the spool fills the disk while the collector stops; squid stops because of the log | spool `/var/spool/linuxmuster-squid/activity` (0750 lmnsquid) with per-instance directories 1733 (squid's proxy user can create, not list; no set-group-id, which `RestrictSUIDSGID=yes` refuses), files 0644 unreachable for other host users behind the 0750 parent; day files 0600 in a 0700 directory; the receiver drops lines while 1 GiB waits; UDP: a dead receiver never stops squid (the `daemon:` module ends squid, measured); the collector streams a file in chunks (memory independent of its size) and quarantines a file that fails three times, so one file cannot stop the collection of the other instances (cold check M1) | `test_activity.py` (receiver), local squid 6.14 test | | T27 | **The activity bridge** (ADR-023 addendum 2): a root service on a socket every local process can open; a teacher's worker (or any local user) claims to be someone else, asks for students outside its classes, floods the bridge, or sends a huge or slow request; a bug in the bridge leaks the tokens | the identity of a non-root caller comes from the kernel (`SO_PEERCRED` → `getpwuid`), a claimed identity must match it; only root names a person; the scope is computed in the bridge from the AD, a users list of the caller is ignored; tokens never leave the bridge (answers carry activity data and typed errors only); request ≤ 256 KiB, 10 s, 32 at once, 60 per UID in 10 s; no shell, no path from the caller; systemd hardening (`ProtectSystem=true`: /usr and /boot read-only, /etc writable because linuxmusterTools chmods the files it reads as root, ADR-023 addendum 4; `NoNewPrivileges`, `ProtectHome`, private /tmp, kernel protections, address families AF_UNIX/AF_INET/AF_INET6/AF_NETLINK — netlink for samba's interface list); one log line per request with UID and identity, refusals audited (tag `lmn-squid-activity`). Residual: upstream gives teachers `sudo ALL` (`webui-sudoers`), so a teacher with a shell on the server is root anyway; the bridge does not make that worse | `webui/tests/test_bridge.py`; `scripts/tests/webui_ajenti_it.sh` (bridge asked as teacher, student, `nobody` and root UIDs) | +| T28 | **edulution plugin: forged identity** (ADR-024): a request that bypasses Traefik with a chosen `X-Auth-User` (another container on `edulution-ui_default`, a published port), a student's valid token with an administrator's name in the header, a stale session group after a role change in the AD | no published port (compose, `doctor` checks); every request must carry an edulution token that the plugin itself verifies with edu-api's `auth/verify` (the middleware's own probe), and the user it names must equal the header, else 401; `root` refused; management needs the session group `role-globaladministrator` **and** the AD role once the directory is set up; the activity view takes the role from the AD only; scope from the AD (`scope_for`, unchanged), never from the browser or the group header | +| T29 | **edulution plugin: secrets on the edulution host** (ADR-024): the proxies' root-equivalent tokens and the read-only directory password in the plugin's volume; another app under the same domain reads the `authToken` cookie (SameSite=None, not HttpOnly; edulution's design) and uses the plugin as that person; CSRF with that cookie | volume 0700/files 0600 for user 10001, never in an answer (tests search every answer), the directory password write-only; whoever is root on the edulution host or controls an app under its domain can act as any logged-in person there anyway (edulution's trust model); state-changing requests need JSON and the same `Origin`/`Referer`; the LDAPS certificate is pinned and the bind is sent only after it matched | +| T30 | **edulution plugin: DC actions over SSH** (ADR-024): a man in the middle on first contact, the administrator's DC password in a log, a residue on the DC, a path from the edulution host into the DC that stays | the DC's host key is fetched and its fingerprint confirmed per action (15 min, a changing action uses it up), `RejectPolicy`, password only, no agent or key files; passwords only in memory (request body scrubbed, jobs on stdin, progress file scrubbed); the DC runs one fixed action of the unchanged WebUI modules from a root-only directory removed afterwards, upload and sudo credential dropped; nothing is stored, no key, no service on the DC | ## Non-goals (deliberate) diff --git a/edulution/Dockerfile b/edulution/Dockerfile new file mode 100644 index 0000000..73e4637 --- /dev/null +++ b/edulution/Dockerfile @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# linuxmuster-squid-edulution — the edulution container plugin (ADR-024). +# Build from the repository root (the shared modules live in webui/lmn_squid/), with the +# linuxmuster-squid .deb of the same build in edulution/build/packages/ (edulution/build-image.sh +# puts it there; the setup assistant installs exactly that package on a new proxy VM): +# edulution/build-image.sh _amd64.deb> [tag] +# Python dependencies only from edulution/requirements.lock (hashes, ADR-015); the base by digest. +FROM ubuntu:24.04@sha256:008173c23f95b170204355c12626cb5a965d779a7e1283b09e9cffbb1bf33ca3 + +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update \ + && apt-get install -y --no-install-recommends python3 python3-venv ca-certificates tzdata \ + && rm -rf /var/lib/apt/lists/* + +COPY edulution/requirements.lock /tmp/requirements.lock +RUN python3 -m venv /opt/lmn-squid-edu/venv \ + && /opt/lmn-squid-edu/venv/bin/pip install --no-cache-dir --require-hashes --no-deps \ + --only-binary :all: -r /tmp/requirements.lock \ + && rm /tmp/requirements.lock + +COPY edulution/build_app.py /src/edulution/build_app.py +COPY edulution/lmnsquid_edu /src/edulution/lmnsquid_edu +COPY edulution/static /src/edulution/static +COPY webui/lmn_squid /src/webui/lmn_squid +COPY scripts/provision-keytab.sh /src/scripts/provision-keytab.sh +RUN python3 -I /src/edulution/build_app.py /src /opt/lmn-squid-edu \ + && rm -rf /src \ + && python3 -I -m compileall -q /opt/lmn-squid-edu/app +COPY edulution/build/packages/ /opt/lmn-squid-edu/packages/ + +# One unprivileged user; its data (settings, connections: tokens, bind password) in the volume +# /var/lib/lmn-squid-edu (0700), job state on a tmpfs at /run/lmn_squid (compose file). +RUN useradd --system --uid 10001 --home-dir /var/lib/lmn-squid-edu --shell /usr/sbin/nologin lmnsquid \ + && install -d -m 0700 -o lmnsquid -g lmnsquid /var/lib/lmn-squid-edu /run/lmn_squid +USER 10001 +ENV LMNSQUID_EDU_DATA=/var/lib/lmn-squid-edu \ + LMNSQUID_EDU_STATIC=/opt/lmn-squid-edu/static \ + LMNSQUID_EDU_PACKAGES=/opt/lmn-squid-edu/packages \ + LMNSQUID_EDU_PROVISION=/opt/lmn-squid-edu/share/provision-keytab.sh \ + LMNSQUID_EDU_JOBS=/run/lmn_squid/jobs \ + PYTHONDONTWRITEBYTECODE=1 +EXPOSE 8080 +HEALTHCHECK --interval=30s --timeout=5s --retries=3 \ + CMD ["/opt/lmn-squid-edu/venv/bin/python", "-I", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/healthz', timeout=4).status == 200 else 1)"] +LABEL org.opencontainers.image.title="linuxmuster-squid-edulution" \ + org.opencontainers.image.source="https://github.com/faircomp/linuxmuster-squid" \ + org.opencontainers.image.licenses="GPL-3.0-or-later" +CMD ["/opt/lmn-squid-edu/venv/bin/python", "-I", "/opt/lmn-squid-edu/app/lmnsquid_edu/serve.py"] diff --git a/edulution/Dockerfile.dockerignore b/edulution/Dockerfile.dockerignore new file mode 100644 index 0000000..87bb435 --- /dev/null +++ b/edulution/Dockerfile.dockerignore @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# Build context of edulution/Dockerfile (the repository root): only what the image needs. +* +!edulution/requirements.lock +!edulution/build_app.py +!edulution/lmnsquid_edu/*.py +!edulution/static +!edulution/build/packages +!webui/lmn_squid/*.py +!scripts/provision-keytab.sh diff --git a/edulution/build-image.sh b/edulution/build-image.sh new file mode 100755 index 0000000..7e96d62 --- /dev/null +++ b/edulution/build-image.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Build the edulution plugin image locally (like the squid image: nothing is built on the +# edulution host). holds the linuxmuster-squid__amd64.deb of the same +# `make deb` run (the setup assistant installs it on a new proxy VM, as the WebUI plugin's). +# edulution/build-image.sh [tag] (default tag: linuxmuster-squid-edulution:) +# docker save | gzip > linuxmuster-squid-edulution-image.tar.gz (for the lab) +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." +debdir=${1:?usage: build-image.sh _amd64.deb> [tag]} +version=$(dpkg-parsechangelog -S Version 2>/dev/null || sed -n '1s/.*(\([^)]*\)).*/\1/p' debian/changelog) +tag=${2:-linuxmuster-squid-edulution:$version} +deb="$debdir/linuxmuster-squid_${version}_amd64.deb" +[ -f "$deb" ] || { echo "missing $deb (run make deb first)" >&2; exit 1; } +rm -rf edulution/build/packages +mkdir -p edulution/build/packages +cp "$deb" edulution/build/packages/ +(cd edulution/build/packages && sha256sum "$(basename "$deb")" > "$(basename "$deb").sha256") +docker build -f edulution/Dockerfile -t "$tag" . +echo "built $tag" diff --git a/edulution/build_app.py b/edulution/build_app.py new file mode 100644 index 0000000..2392c08 --- /dev/null +++ b/edulution/build_app.py @@ -0,0 +1,68 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Assemble the edulution plugin's application directory from this repository. + + build_app.py + +/app/lmn_squid/ the shared modules of the WebUI plugin (SHARED), unchanged, with + an __init__.py of its own (the WebUI's imports the aj core) +/app/lmnsquid_edu/ the edulution backend +/share/provision-keytab.sh (copied to the DC for a keytab, dc_agent) +/static/ the pages + +The container image (edulution/Dockerfile) and the tests (edulution/tests/conftest.py) both +use this, so the tests run exactly the module set the image ships. +""" + +from __future__ import annotations + +import shutil +import sys +from pathlib import Path + +SHARED = ( + "activity_core", + "activity_scope", + "client", + "connections", + "jobs", + "keytab", + "manage_core", + "precheck", + "runtime", + "sitefacts", + "sshsetup", +) +# REUSE-IgnoreStart (the header of the generated file, not of this one) +INIT = ( + "# SPDX-FileCopyrightText: Kevin Stenzel\n" + "# SPDX-License-Identifier: GPL-3.0-or-later\n" + '"""The modules of the WebUI plugin lmn_squid the edulution plugin shares (ADR-024)."""\n' +) +# REUSE-IgnoreEnd + + +def build(repo: Path, dest: Path) -> None: + app = dest / "app" + shared = app / "lmn_squid" + shared.mkdir(parents=True, exist_ok=True) + (shared / "__init__.py").write_text(INIT, encoding="utf-8") + for name in SHARED: + shutil.copy2(repo / "webui" / "lmn_squid" / f"{name}.py", shared / f"{name}.py") + edu = app / "lmnsquid_edu" + edu.mkdir(exist_ok=True) + for src in sorted((repo / "edulution" / "lmnsquid_edu").glob("*.py")): + shutil.copy2(src, edu / src.name) + (dest / "share").mkdir(exist_ok=True) + shutil.copy2(repo / "scripts" / "provision-keytab.sh", dest / "share" / "provision-keytab.sh") + static = repo / "edulution" / "static" + if static.is_dir(): + shutil.copytree(static, dest / "static", dirs_exist_ok=True) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + print(__doc__, file=sys.stderr) + sys.exit(2) + build(Path(sys.argv[1]), Path(sys.argv[2])) diff --git a/edulution/host/docker-compose.yml b/edulution/host/docker-compose.yml new file mode 100644 index 0000000..af8a048 --- /dev/null +++ b/edulution/host/docker-compose.yml @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The edulution plugin of linuxmuster-squid (ADR-024). Written by `linuxmuster-squid-edulution +# up` into its own project directory (/srv/docker/edulution-plugin-lmn-squid), never into the +# edulution directory; .env beside it names the image and this host's address. +# No `ports:`: only edulution's Traefik reaches the container, through the forwardAuth +# middleware edulution-keycloak-auth (data/traefik/config/plugin-lmn-squid.yml). +name: edulution-plugin-lmn-squid + +services: + lmn-squid: + image: ${LMNSQUID_EDU_IMAGE:?image} + container_name: edulution-plugin-lmn-squid + restart: unless-stopped + init: true + read_only: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + tmpfs: + - /run/lmn_squid:uid=10001,gid=10001,mode=0700 + - /tmp:mode=1777 + environment: + LMNSQUID_EDU_HOST_IP: ${LMNSQUID_EDU_HOST_IP:-} + volumes: + - data:/var/lib/lmn-squid-edu + networks: + - edulution + +networks: + edulution: + external: true + name: edulution-ui_default + +volumes: + data: + name: edulution-plugin-lmn-squid-data diff --git a/edulution/host/icons/internetnutzung.svg b/edulution/host/icons/internetnutzung.svg new file mode 100644 index 0000000..c7bf07e --- /dev/null +++ b/edulution/host/icons/internetnutzung.svg @@ -0,0 +1,3 @@ + + + diff --git a/edulution/host/icons/squidproxy.svg b/edulution/host/icons/squidproxy.svg new file mode 100644 index 0000000..2a6ee1f --- /dev/null +++ b/edulution/host/icons/squidproxy.svg @@ -0,0 +1,3 @@ + + + diff --git a/edulution/host/linuxmuster_squid_edulution.py b/edulution/host/linuxmuster_squid_edulution.py new file mode 100755 index 0000000..6a0a2d9 --- /dev/null +++ b/edulution/host/linuxmuster_squid_edulution.py @@ -0,0 +1,518 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""linuxmuster-squid-edulution: the edulution plugin of linuxmuster-squid on the edulution host. + + up write the compose project and the Traefik route, start the container + down stop and remove the container and the Traefik route (--purge: also its data) + register create or update the two app tiles in edulution (global admin login) + unregister delete the two app tiles (global admin login) + doctor check edulution version, Traefik files, container, network, route, tiles + status the configuration this command uses + +Relies only on what docs/ANLEITUNG §8 of the edulution plugin work names as stable: the +middleware ``edulution-keycloak-auth`` (``# version: v1.0``), the headers X-Auth-User/-Groups, +the cookie ``authToken`` and single ``/edu-api`` endpoints (auth, appconfig, groups, +health/version). Standard library only (runs as root, before and without the container). +""" + +from __future__ import annotations + +import argparse +import base64 +import getpass +import http.client +import json +import os +import re +import shutil +import ssl +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +SHARE = Path(os.environ.get("LMNSQUID_EDU_SHARE", "/usr/share/linuxmuster-squid-edulution")) +CONF = Path(os.environ.get("LMNSQUID_EDU_CONF", "/etc/linuxmuster-squid-edulution/plugin.conf")) +STATE = Path(os.environ.get("LMNSQUID_EDU_STATE", "/var/lib/linuxmuster-squid-edulution")) +PROJECT = "edulution-plugin-lmn-squid" +CONTAINER = "edulution-plugin-lmn-squid" +VOLUME = "edulution-plugin-lmn-squid-data" +NETWORK = "edulution-ui_default" +ROUTE = "/plugin/lmn-squid" +TRAEFIK_FILE = "plugin-lmn-squid.yml" # differs from every app name (edulution deletes .yml) +MIDDLEWARE_FILE = "edulution-keycloak-auth.yml" +MIDDLEWARE_VERSION = "# version: v1.0" +DEFAULTS = { + "EDULUTION_DIR": "/srv/docker/edulution-ui", + "PROJECT_DIR": f"/srv/docker/{PROJECT}", + "IMAGE": "", + "BASE_DOMAIN": "", + "HOST_IP": "", +} +# (app name, German, English, French, path, role groups that see the tile, icon file, position) +APPS = ( + ( + "squidproxy", + "Squid-Proxy", + "Squid proxy", + "Proxy Squid", + "manage", + ("role-globaladministrator",), + "squidproxy.svg", + 30, + ), + ( + "internetnutzung", + "Internetnutzung", + "Internet use", + "Utilisation d'Internet", + "activity", + ("role-globaladministrator", "role-schooladministrator", "role-teacher"), + "internetnutzung.svg", + 31, + ), +) + + +class Fail(Exception): + pass + + +# ---------------------------------------------------------------------- configuration +def package_version() -> str: + try: + out = subprocess.run( + ["dpkg-query", "-W", "-f=${Version}", "linuxmuster-squid-edulution"], + capture_output=True, + text=True, + check=False, + ) + return out.stdout.strip() + except OSError: + return "" + + +def read_env(path: Path) -> dict[str, str]: + values: dict[str, str] = {} + try: + lines = path.read_text(encoding="utf-8").splitlines() + except OSError: + return values + for line in lines: + m = re.match(r"^\s*([A-Z_][A-Z0-9_]*)=(.*)$", line) + if m: + values[m.group(1)] = m.group(2).strip().strip('"').strip("'") + return values + + +def load_conf() -> dict[str, str]: + conf = dict(DEFAULTS) + conf.update({k: v for k, v in read_env(CONF).items() if k in DEFAULTS and v}) + # IMAGE is stored only when an administrator chose one (--image); otherwise it follows + # the package version, so an upgrade of the package moves the container to its image + conf["IMAGE_PINNED"] = conf["IMAGE"] + if not conf["IMAGE"]: + conf["IMAGE"] = f"linuxmuster-squid-edulution:{package_version() or 'latest'}" + if not conf["BASE_DOMAIN"]: + # convenience only: the installer's file names the domain; --url / plugin.conf win + conf["BASE_DOMAIN"] = read_env(Path(conf["EDULUTION_DIR"]) / "edulution.env").get( + "EDULUTION_BASE_DOMAIN", "" + ) + return conf + + +def save_conf(conf: dict[str, str]) -> None: + CONF.parent.mkdir(parents=True, exist_ok=True) + keep = {k: v for k, v in conf.items() if k in DEFAULTS and v} + if not conf.get("IMAGE_PINNED"): + keep.pop("IMAGE", None) + text = "".join(f"{k}={v}\n" for k, v in keep.items()) + atomic_write(CONF, "# written by linuxmuster-squid-edulution\n" + text, 0o644) + + +def atomic_write(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}.") + 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 + + +def traefik_dir(conf: dict[str, str]) -> Path: + return Path(conf["EDULUTION_DIR"]) / "data" / "traefik" / "config" + + +# ---------------------------------------------------------------------- docker +def docker(*args: str, check: bool = True) -> subprocess.CompletedProcess[str]: + try: + res = subprocess.run(["docker", *args], capture_output=True, text=True, check=False) + except FileNotFoundError: + raise Fail("docker nicht gefunden") from None + if check and res.returncode != 0: + raise Fail(f"docker {' '.join(args[:3])}: {(res.stderr or res.stdout).strip()[-400:]}") + return res + + +def compose(conf: dict[str, str], *args: str) -> subprocess.CompletedProcess[str]: + return docker("compose", "-p", PROJECT, "--project-directory", conf["PROJECT_DIR"], *args) + + +def image_present(image: str) -> bool: + return docker("image", "inspect", image, check=False).returncode == 0 + + +def cmd_up(args: argparse.Namespace) -> int: + conf = load_conf() + for key in ("image", "edulution_dir", "host_ip", "base_domain"): + value = getattr(args, key, None) + if value: + conf[key.upper()] = value + if args.image: + conf["IMAGE_PINNED"] = args.image + edudir = Path(conf["EDULUTION_DIR"]) + if not (edudir / "docker-compose.yml").is_file(): + raise Fail(f"{edudir}: keine edulution-Installation (--edulution-dir)") + if not (traefik_dir(conf) / MIDDLEWARE_FILE).is_file(): + raise Fail(f"{traefik_dir(conf) / MIDDLEWARE_FILE} fehlt: edulution 2.3 oder neuer nötig") + if docker("network", "inspect", NETWORK, check=False).returncode != 0: + raise Fail(f"Docker-Netz {NETWORK} fehlt: läuft edulution?") + if not conf["HOST_IP"]: + conf["HOST_IP"] = guess_host_ip() + save_conf(conf) + if not image_present(conf["IMAGE"]): + # nothing changed: a running container keeps its image until the new one is loaded + print( + f"Image {conf['IMAGE']} ist nicht geladen (docker load -i , dann " + "linuxmuster-squid-edulution up); am laufenden Plugin wurde nichts geändert.", + file=sys.stderr, + ) + return 2 + project = Path(conf["PROJECT_DIR"]) + project.mkdir(mode=0o755, parents=True, exist_ok=True) + shutil.copy2(SHARE / "docker-compose.yml", project / "docker-compose.yml") + atomic_write( + project / ".env", + f"LMNSQUID_EDU_IMAGE={conf['IMAGE']}\nLMNSQUID_EDU_HOST_IP={conf['HOST_IP']}\n", + 0o644, + ) + compose(conf, "up", "-d", "--remove-orphans") + # the route only after the container is there (Traefik reloads the file at once) + src = (SHARE / "traefik" / TRAEFIK_FILE).read_text(encoding="utf-8") + atomic_write(traefik_dir(conf) / TRAEFIK_FILE, src, 0o644) + print(f"Container {CONTAINER} läuft ({conf['IMAGE']}), Route {ROUTE}/ angelegt.") + return 0 + + +def guess_host_ip() -> str: + """The address the proxies see: the source address towards the default route.""" + out = subprocess.run( + ["ip", "-4", "route", "get", "1.1.1.1"], capture_output=True, text=True, check=False + ).stdout + m = re.search(r"\bsrc (\d+\.\d+\.\d+\.\d+)", out) + return m.group(1) if m else "" + + +def cmd_down(args: argparse.Namespace) -> int: + conf = load_conf() + route = traefik_dir(conf) / TRAEFIK_FILE + if route.exists(): + route.unlink() + project = Path(conf["PROJECT_DIR"]) + if (project / "docker-compose.yml").is_file(): + down = ["down", "--remove-orphans"] + (["--volumes"] if args.purge else []) + compose(conf, *down) + else: + docker("rm", "-f", CONTAINER, check=False) + if args.purge: + docker("volume", "rm", VOLUME, check=False) + shutil.rmtree(project, ignore_errors=True) + print("Container und Route entfernt" + (", Daten gelöscht" if args.purge else "")) + return 0 + + +# ---------------------------------------------------------------------- edu-api +class Edu: + """edu-api through Traefik on this host (loopback: the certificate is not checked; the + connection never leaves the machine).""" + + def __init__(self, base_domain: str, url: str = "") -> None: + self.host = base_domain + target = url or "https://127.0.0.1" + m = re.match(r"^https://([^/:]+)(?::(\d+))?/?$", target) + if not m: + raise Fail("--url https:// erwartet") + self.addr, self.port = m.group(1), int(m.group(2) or 443) + self.token = "" + + def request( + self, method: str, path: str, body: Any = None, auth: bool = True + ) -> tuple[int, Any]: + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + conn = http.client.HTTPSConnection(self.addr, self.port, context=ctx, timeout=30) + headers = {"Host": self.host or self.addr, "Accept": "application/json"} + data = None + if body is not None: + data = json.dumps(body).encode("utf-8") + headers["Content-Type"] = "application/json" + if auth and self.token: + headers["Authorization"] = f"Bearer {self.token}" + try: + conn.request(method, path, body=data, headers=headers) + res = conn.getresponse() + raw = res.read() + except OSError as exc: + raise Fail(f"edulution nicht erreichbar ({self.addr}:{self.port}): {exc}") from None + finally: + conn.close() + try: + return res.status, json.loads(raw) if raw else None + except ValueError: + return res.status, raw.decode("utf-8", "replace")[:300] + + def login(self, user: str, password: str) -> None: + status, data = self.request( + "POST", + "/edu-api/auth", + { + "grant_type": "password", + "username": user, + "password": base64.b64encode(password.encode("utf-8")).decode("ascii"), + }, + auth=False, + ) + if status not in (200, 201) or not isinstance(data, dict) or not data.get("access_token"): + msg = data.get("message") if isinstance(data, dict) else data + raise Fail(f"Anmeldung als {user} fehlgeschlagen ({status}): {msg}") + self.token = str(data["access_token"]) + + def group(self, name: str) -> dict[str, Any]: + from urllib.parse import quote + + status, data = self.request("GET", f"/edu-api/groups?groupName={quote(name)}") + if status != 200 or not isinstance(data, list): + raise Fail(f"Gruppe {name}: HTTP {status}") + for g in data: + if isinstance(g, dict) and g.get("name") == name: + return {**g, "value": g.get("id"), "label": name, "groupCategory": "group"} + raise Fail(f"Gruppe {name} gibt es in edulution nicht") + + def apps(self) -> dict[str, dict[str, Any]]: + status, data = self.request("GET", "/edu-api/appconfig") + if status != 200 or not isinstance(data, list): + raise Fail(f"App-Liste: HTTP {status} (Global-Admin?)") + return {str(a.get("name")): a for a in data if isinstance(a, dict)} + + +def credentials(args: argparse.Namespace) -> tuple[str, str]: + user = args.user or input("edulution-Benutzer (Global-Admin): ").strip() + if args.password_stdin: + password = sys.stdin.readline().rstrip("\n") + else: + password = getpass.getpass(f"Passwort für {user}: ") + if not user or not password: + raise Fail("Benutzer und Passwort nötig") + return user, password + + +def edu_for(args: argparse.Namespace, conf: dict[str, str]) -> Edu: + domain = args.base_domain or conf["BASE_DOMAIN"] + if not domain: + raise Fail("edulution-Domain unbekannt: --base-domain angeben") + return Edu(domain, args.url or "") + + +def icon(name: str) -> str: + from urllib.parse import quote + + svg = (SHARE / "icons" / name).read_text(encoding="utf-8") + return "data:image/svg+xml," + quote(svg, safe="") + + +def app_body( + app: tuple[Any, ...], domain: str, groups: dict[str, dict[str, Any]] +) -> dict[str, Any]: + name, de, en, fr, page, roles, icon_file, position = app + return { + "name": name, + "translations": {"de": de, "en": en, "fr": fr}, + "icon": icon(icon_file), + "appType": "frame", + "options": {"url": f"https://{domain}{ROUTE}/{page}/", "proxyConfig": '""'}, + "extendedOptions": {}, + "accessGroups": [groups[r] for r in roles], + "displayLocations": ["sidebar", "launcher"], + "position": position, + "isPinned": True, + "usesPushNotifications": False, + } + + +def cmd_register(args: argparse.Namespace) -> int: + conf = load_conf() + edu = edu_for(args, conf) + edu.login(*credentials(args)) + roles = sorted({r for app in APPS for r in app[5]}) + groups = {r: edu.group(r) for r in roles} + existing = edu.apps() + for app in APPS: + body = app_body(app, edu.host, groups) + name = app[0] + if name in existing: + # keep what an administrator changed in edulution: position, pinning, places + for key in ("position", "isPinned", "displayLocations"): + if key in existing[name]: + body[key] = existing[name][key] + status, data = edu.request("PUT", f"/edu-api/appconfig/{name}", body) + what = "aktualisiert" + else: + status, data = edu.request("POST", "/edu-api/appconfig", body) + what = "angelegt" + if status not in (200, 201): + raise Fail(f"App {name}: HTTP {status} {data}") + print(f"App „{app[1]}“ ({name}) {what}: {', '.join(app[5])}") + STATE.mkdir(parents=True, exist_ok=True) + atomic_write(STATE / "registered", "".join(f"{a[0]}\n" for a in APPS), 0o644) + return 0 + + +def cmd_unregister(args: argparse.Namespace) -> int: + conf = load_conf() + edu = edu_for(args, conf) + edu.login(*credentials(args)) + existing = edu.apps() + for app in APPS: + if app[0] not in existing: + print(f"App {app[0]}: nicht vorhanden") + continue + status, data = edu.request("DELETE", f"/edu-api/appconfig/{app[0]}") + if status not in (200, 204): + raise Fail(f"App {app[0]} löschen: HTTP {status} {data}") + print(f"App {app[0]} gelöscht") + try: + (STATE / "registered").unlink() + except FileNotFoundError: + pass + return 0 + + +# ---------------------------------------------------------------------- doctor +def cmd_doctor(args: argparse.Namespace) -> int: + conf = load_conf() + problems = 0 + + def report(ok: bool | None, text: str) -> None: + nonlocal problems + mark = {True: "OK ", False: "FEHL", None: "INFO"}[ok] + if ok is False: + problems += 1 + print(f"[{mark}] {text}") + + edu = edu_for(args, conf) + status, data = edu.request("GET", "/edu-api/health/version", auth=False) + version = data.get("version") if isinstance(data, dict) else None + report( + status == 200 and bool(version), f"edulution-API Version {version or '?'} (HTTP {status})" + ) + tested = read_env(SHARE / "tested-versions").get("TESTED", "") + if version and tested and version not in tested.split(): + report(None, f"Version {version} nicht mit diesem Plugin getestet (getestet: {tested})") + mw = traefik_dir(conf) / MIDDLEWARE_FILE + try: + head = mw.read_text(encoding="utf-8").splitlines()[0].strip() + except (OSError, IndexError): + head = "" + report(head == MIDDLEWARE_VERSION, f"Middleware {mw.name}: {head or 'fehlt'}") + route = traefik_dir(conf) / TRAEFIK_FILE + report(route.is_file(), f"Traefik-Route {route}") + res = docker("inspect", CONTAINER, check=False) + info = json.loads(res.stdout)[0] if res.returncode == 0 and res.stdout.strip() else {} + state = info.get("State") or {} + health = (state.get("Health") or {}).get("Status") + report( + bool(state.get("Running")) and health in ("healthy", None), + f"Container {CONTAINER}: {state.get('Status', 'fehlt')}, Health {health or '–'}, " + f"Image {(info.get('Config') or {}).get('Image', '–')}", + ) + nets = sorted(((info.get("NetworkSettings") or {}).get("Networks") or {}).keys()) + report(NETWORK in nets, f"Netz {NETWORK}: verbunden" if NETWORK in nets else f"Netze: {nets}") + ports = (info.get("HostConfig") or {}).get("PortBindings") or {} + report( + not ports, "kein veröffentlichter Port" if not ports else f"veröffentlichte Ports: {ports}" + ) + status, _ = edu.request("GET", f"{ROUTE}/manage/", auth=False) + report(status == 401, f"Route ohne Anmeldung: HTTP {status} (erwartet 401)") + if args.user: + edu.login(*credentials(args)) + status, data = edu.request("GET", f"{ROUTE}/api/lmn/squid/whoami") + report(status == 200, f"Route mit Anmeldung ({args.user}): HTTP {status} {data}") + status, _ = edu.request("GET", f"{ROUTE}/manage/") + report(status == 200, f"Seite mit Anmeldung: HTTP {status}") + apps = edu.apps() + for app in APPS: + found = apps.get(app[0]) + url = ((found or {}).get("options") or {}).get("url", "") + report( + bool(found) and url.endswith(f"{ROUTE}/{app[4]}/"), + f"App {app[0]}: {'vorhanden, ' + url if found else 'fehlt (register)'}", + ) + else: + report(None, "Mit --user prüft doctor auch Anmeldung und App-Kacheln") + print(f"{problems} Problem(e)") + return 1 if problems else 0 + + +def cmd_status(args: argparse.Namespace) -> int: + for k, v in load_conf().items(): + if k != "IMAGE_PINNED": + print(f"{k}={v}") + return 0 + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser( + prog="linuxmuster-squid-edulution", description=__doc__.split("\n")[0] + ) + sub = parser.add_subparsers(dest="cmd", required=True) + up = sub.add_parser("up", help="Container und Route einrichten/aktualisieren") + up.add_argument("--image") + up.add_argument("--edulution-dir") + up.add_argument("--host-ip", help="Adresse dieses Hosts, wie die Proxys sie sehen") + up.add_argument("--base-domain") + up.set_defaults(fn=cmd_up) + down = sub.add_parser("down", help="Container und Route entfernen") + down.add_argument( + "--purge", action="store_true", help="auch Daten (Verbindungen, Einstellungen)" + ) + down.set_defaults(fn=cmd_down) + for name, fn in ( + ("register", cmd_register), + ("unregister", cmd_unregister), + ("doctor", cmd_doctor), + ): + p = sub.add_parser(name) + p.add_argument("--user") + p.add_argument("--password-stdin", action="store_true") + p.add_argument("--base-domain", default="") + p.add_argument("--url", default="", help="edulution von hier (Standard https://127.0.0.1)") + p.set_defaults(fn=fn) + sub.add_parser("status").set_defaults(fn=cmd_status) + args = parser.parse_args(argv) + try: + return int(args.fn(args)) + except Fail as exc: + print(f"Fehler: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/edulution/host/tested-versions b/edulution/host/tested-versions new file mode 100644 index 0000000..7affa9b --- /dev/null +++ b/edulution/host/tested-versions @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# edulution versions this plugin was tested against in the lab (doctor warns about others) +TESTED="2.3.117" diff --git a/edulution/host/traefik/plugin-lmn-squid.yml b/edulution/host/traefik/plugin-lmn-squid.yml new file mode 100644 index 0000000..d6bca9a --- /dev/null +++ b/edulution/host/traefik/plugin-lmn-squid.yml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# linuxmuster-squid-edulution: Traefik route of the plugin, written to +# /data/traefik/config/plugin-lmn-squid.yml by `linuxmuster-squid-edulution up`. +# The file name is no app name: edulution deletes .yml when an app's proxy setting is empty. +# edulution-keycloak-auth (written by edulution-api, "# version: v1.0") lets only logged-in +# users through and sets X-Auth-User / X-Auth-Groups (overwriting the browser's). +http: + routers: + plugin-lmn-squid: + rule: "PathPrefix(`/plugin/lmn-squid/`)" + service: plugin-lmn-squid + entryPoints: + - websecure + tls: {} + middlewares: + - edulution-keycloak-auth@file + - plugin-lmn-squid-strip + + middlewares: + plugin-lmn-squid-strip: + stripPrefix: + prefixes: + - "/plugin/lmn-squid" + + services: + plugin-lmn-squid: + loadBalancer: + servers: + - url: "http://edulution-plugin-lmn-squid:8080" diff --git a/edulution/lmnsquid_edu/__init__.py b/edulution/lmnsquid_edu/__init__.py new file mode 100644 index 0000000..18e1e63 --- /dev/null +++ b/edulution/lmnsquid_edu/__init__.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""edulution container plugin of linuxmuster-squid (ADR-024). + +The backend of the two edulution apps "Squid-Proxy" (management, global administrators) and +"Internetnutzung" (activity view). It serves the same routes as the WebUI plugin from the +shared modules of ``lmn_squid`` (``manage_core``, ``activity_core``, ``sshsetup``, ``jobs``), +behind edulution's Traefik with the forwardAuth middleware ``edulution-keycloak-auth``. +""" diff --git a/edulution/lmnsquid_edu/auth.py b/edulution/lmnsquid_edu/auth.py new file mode 100644 index 0000000..d34b1f8 --- /dev/null +++ b/edulution/lmnsquid_edu/auth.py @@ -0,0 +1,173 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Who is calling, and may this request change something (ADR-024). + +Identity: edulution's Traefik runs the forwardAuth middleware ``edulution-keycloak-auth`` +before a request reaches the plugin and sets ``X-Auth-User`` (overwriting any the browser +sent). The plugin's container publishes no port, so only Traefik reaches it. Containers on the +same Docker network could, though; so the plugin does not trust the header alone: the request +must also carry the user's edulution token (cookie ``authToken`` or ``Authorization: Bearer``), +which the plugin checks itself with edulution's own probe ``GET /edu-api/auth/verify`` (the +endpoint behind the middleware), and the user that probe names must be the header's. The +probe's groups are the session's LDAP groups (role groups such as ``role-globaladministrator``). + +CSRF: edulution's ``authToken`` cookie is ``SameSite=None``, so a page of another site can make +the browser send it. Every state-changing request needs ``Content-Type: application/json`` (a +cross-site page cannot send that without a CORS preflight, which the plugin never answers) and +an ``Origin`` (else ``Referer``) equal to the edulution origin the request came in on; one with +neither is refused (as the WebUI plugin, m4). +""" + +from __future__ import annotations + +import hashlib +import http.client +import os +import re +import threading +import time +from dataclasses import dataclass, field +from http.cookies import CookieError, SimpleCookie +from typing import Callable, Mapping +from urllib.parse import unquote, urlsplit + +EDU_API = os.environ.get("LMNSQUID_EDU_API", "http://edu-api:3000/edu-api") +USER_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$") +VERIFY_TTL = 30.0 +VERIFY_TIMEOUT = 5.0 +STATE_CHANGING = ("POST", "PUT", "PATCH", "DELETE") +_DEFAULT_PORTS = {"http": 80, "https": 443} + + +class AuthError(Exception): + def __init__(self, status: int, code: str, message: str) -> None: + super().__init__(message) + self.status = status + self.code = code + self.message = message + + def answer(self) -> tuple[int, dict[str, str]]: + return self.status, {"error": self.code, "message": self.message} + + +@dataclass +class Caller: + user: str + groups: set[str] = field(default_factory=set) + + @property + def global_admin(self) -> bool: + return "role-globaladministrator" in self.groups + + +def _token(headers: Mapping[str, str]) -> str: + auth = headers.get("Authorization") or "" + if auth.lower().startswith("bearer "): + return auth[7:].strip() + try: + jar = SimpleCookie(headers.get("Cookie") or "") + except CookieError: + return "" + morsel = jar.get("authToken") + return morsel.value if morsel else "" + + +def verify_with_edu_api(token: str) -> tuple[str, set[str]] | None: + """(user, groups) for a valid token from ``GET /edu-api/auth/verify``; None if invalid.""" + parts = urlsplit(EDU_API) + cls = http.client.HTTPSConnection if parts.scheme == "https" else http.client.HTTPConnection + conn = cls(parts.hostname or "", parts.port, timeout=VERIFY_TIMEOUT) + try: + conn.request( + "GET", + parts.path.rstrip("/") + "/auth/verify", + headers={"Authorization": f"Bearer {token}"}, + ) + res = conn.getresponse() + res.read() + if res.status not in (200, 204): + return None + user = unquote(res.getheader("x-auth-user") or "").strip().lower() + groups = {unquote(g).strip() for g in (res.getheader("x-auth-groups") or "").split(",")} + return (user, {g for g in groups if g}) if user else None + finally: + conn.close() + + +class Verifier: + """Token checks, cached briefly by the token's hash (never the token itself).""" + + def __init__(self, probe: Callable[[str], tuple[str, set[str]] | None] = verify_with_edu_api): + self.probe = probe + self.lock = threading.Lock() + self.cache: dict[str, tuple[float, tuple[str, set[str]] | None]] = {} + + def __call__(self, token: str) -> tuple[str, set[str]] | None: + key = hashlib.sha256(token.encode("utf-8")).hexdigest() + now = time.monotonic() + with self.lock: + hit = self.cache.get(key) + if hit and now - hit[0] < VERIFY_TTL: + return hit[1] + try: + found = self.probe(token) + except OSError as exc: + raise AuthError( + 503, "edu_api", f"edulution-API nicht erreichbar ({type(exc).__name__})" + ) from None + with self.lock: + if len(self.cache) > 1000: + self.cache.clear() + self.cache[key] = (now, found) + return found + + +def identify( + headers: Mapping[str, str], verify: Callable[[str], tuple[str, set[str]] | None] +) -> Caller: + """The checked caller of a request, or :class:`AuthError` (401).""" + user = unquote(headers.get("X-Auth-User") or "").strip().lower() + if not user: + raise AuthError(401, "auth", "nicht angemeldet (kein X-Auth-User: nicht über Traefik)") + if not USER_RE.match(user) or user == "root": + raise AuthError(401, "auth", "ungültiger Benutzername") + token = _token(headers) + if not token: + raise AuthError(401, "auth", "kein edulution-Token in der Anfrage") + found = verify(token) + if found is None: + raise AuthError(401, "auth", "edulution-Token ungültig oder abgelaufen") + if found[0] != user: + raise AuthError(401, "auth", "Token und Anmeldung gehören nicht zur selben Person") + return Caller(user=user, groups=found[1]) + + +def _origin_of(url: str) -> tuple[str, str, int] | None: + try: + parts = urlsplit(url.strip()) + port = parts.port + except ValueError: + return None + if parts.scheme not in _DEFAULT_PORTS or not parts.hostname: + return None + return parts.scheme, parts.hostname.lower(), port or _DEFAULT_PORTS[parts.scheme] + + +def check_same_origin(method: str, headers: Mapping[str, str]) -> None: + """Refuse a state-changing request that a page of another site could have sent.""" + if method.upper() not in STATE_CHANGING: + return + ctype = str(headers.get("Content-Type") or "").split(";", 1)[0].strip().lower() + if ctype != "application/json": + raise AuthError(415, "content_type", "Content-Type application/json required") + proto = (headers.get("X-Forwarded-Proto") or "https").split(",")[0].strip() + host = (headers.get("X-Forwarded-Host") or headers.get("Host") or "").split(",")[0].strip() + own = _origin_of(f"{proto}://{host}") + for name in ("Origin", "Referer"): + value = headers.get(name) + if not value: + continue + if own is None or _origin_of(str(value)) != own: + raise AuthError(403, "origin", f"request from another site refused ({name})") + return + raise AuthError(403, "origin", "request without Origin and Referer refused") diff --git a/edulution/lmnsquid_edu/dc.py b/edulution/lmnsquid_edu/dc.py new file mode 100644 index 0000000..6d5e903 --- /dev/null +++ b/edulution/lmnsquid_edu/dc.py @@ -0,0 +1,244 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Actions on the school server (DC) over SSH, with the administrator's login for one action. + +The WebUI plugin runs as root on the DC; the edulution plugin does not, and must not get a +permanent way in (task decision 7). So every action that needs the DC (precheck of a new +proxy host, keytab, disabling a service account) asks the global administrator for an SSH +login of the DC and confirms the DC's host key first, exactly like the proxy setup does for a +new VM (ADR-021): ``RejectPolicy`` with the confirmed key as the only known host key, password +authentication only, no agent, no key files, the password only in memory and through ``sudo +-S`` on the channel's stdin. The work on the DC is :mod:`dc_agent` with the WebUI plugin's own +modules (see there); nothing is stored on either side. +""" + +from __future__ import annotations + +import base64 +import json +import os +import re +import shlex +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable + +from lmn_squid import keytab as keytab_mod +from lmn_squid import precheck, sshsetup + +APP_DIR = Path(os.environ.get("LMNSQUID_EDU_APP", str(Path(__file__).resolve().parent.parent))) +PROVISION_SCRIPT = os.environ.get( + "LMNSQUID_EDU_PROVISION", "/opt/lmn-squid-edu/share/provision-keytab.sh" +) +AGENT_MODULES = ("keytab", "precheck", "sitefacts", "runtime", "client", "connections") +REMOTE_DIR = "/run/lmn-squid-dc" +MARK = "LMNSQUID-DC " +HOSTKEY_TTL = 900.0 +AGENT_TIMEOUT = 300.0 + +# Host keys of the DC fetched for a confirmation, per address, in this process only: the +# browser confirms a fingerprint, the key itself never comes back from the browser. +_HOSTKEYS: dict[str, tuple[float, dict[str, str]]] = {} + + +class DcError(Exception): + """An action on the DC failed; ``code`` for the page: hostkey, login, agent.""" + + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + self.message = message + + +@dataclass +class DcLogin: + host: str + user: str + password: str + sudo_password: str + keytype: str + key: str + + def payload(self) -> dict[str, str]: + """For a job's stdin (never a file, an argument or the environment).""" + return dict(self.__dict__) + + @classmethod + def from_payload(cls, data: dict[str, Any]) -> "DcLogin": + return cls(**{k: str(data[k]) for k in cls.__dataclass_fields__}) + + +def scan(host: str) -> dict[str, str]: + scanned = sshsetup.scan_host_key(host) + _HOSTKEYS[host] = (time.monotonic(), scanned) + return { + "host": host, + "keytype": scanned["keytype"], + "fingerprint": scanned["fingerprint"], + } + + +def login_from_body(host: str, data: Any, consume: bool) -> DcLogin: + """The DC login of one action from the request body, against the confirmed host key. + + ``consume``: the confirmation is used up (an action that changes something); a precheck + (read-only) may be followed by the setup within the same 15 minutes. + """ + data = data if isinstance(data, dict) else {} + scanned_at, scanned = _HOSTKEYS.get(host, (0.0, {})) + if ( + not scanned + or time.monotonic() - scanned_at > HOSTKEY_TTL + or str(data.get("fingerprint") or "") != scanned["fingerprint"] + ): + raise DcError( + "dc_hostkey", + "Host-Key des Schulservers nicht (mehr) bestätigt: erneut holen und bestätigen.", + ) + user = str(data.get("user") or "") + password = str(data.get("password") or "") + if not sshsetup.USER_RE.match(user) or not password: + raise DcError("dc_login", "SSH-Benutzer und Passwort des Schulservers nötig") + if consume: + _HOSTKEYS.pop(host, None) + return DcLogin( + host=host, + user=user, + password=password, + sudo_password=str(data.get("sudo_password") or "") or password, + keytype=scanned["keytype"], + key=scanned["key"], + ) + + +def _bundle() -> list[tuple[Path, str]]: + """(local file, name in the remote directory) of everything the agent needs.""" + pkg = APP_DIR / "lmn_squid" + files = [(pkg / f"{m}.py", f"lmn_squid/{m}.py") for m in AGENT_MODULES] + files.append((Path(__file__).resolve().parent / "dc_agent.py", "dc_agent.py")) + files.append((Path(PROVISION_SCRIPT), "provision-keytab.sh")) + return files + + +Connector = Callable[..., Any] + + +def run_agent( + login: DcLogin, + action: str, + args: dict[str, Any], + connect_fn: Connector = sshsetup.connect, +) -> dict[str, Any]: + """Upload the agent, run ``action`` as root, remove everything again; its JSON answer.""" + try: + client = connect_fn(login.host, login.user, login.password, login.keytype, login.key) + except Exception as exc: # noqa: BLE001 - paramiko raises many types; name it + raise DcError("dc_login", f"SSH-Anmeldung am Schulserver: {type(exc).__name__}: {exc}") + remote = sshsetup.Remote(client, login.user, login.sudo_password) + made: list[str] = [] # the upload directory, once it exists + try: + return _agent(remote, action, args, made) + except sshsetup.StepFailed as exc: + raise DcError("dc_agent", f"Schulserver: {exc.detail}") from None + except DcError: + raise + except Exception as exc: # noqa: BLE001 - a dropped session and the like: named + raise DcError("dc_agent", f"Schulserver: {type(exc).__name__}: {exc}") from None + finally: + try: + for tmp in made: + remote.run(f"rm -rf {shlex.quote(tmp)}", root=False, timeout=30.0) + remote.run("sudo -K", root=False, timeout=30.0) + except Exception: # noqa: BLE001 - best effort + pass + client.close() + + +def _agent(remote: Any, action: str, args: dict[str, Any], made: list[str]) -> dict[str, Any]: + tmp = remote.must("dc", "mktemp -d /tmp/lmn-squid-dc.XXXXXXXX", root=False).strip() + if not re.match(r"^/tmp/lmn-squid-dc\.[A-Za-z0-9]{8}$", tmp): + raise DcError("dc_agent", f"unerwartetes Temp-Verzeichnis {tmp!r}") + made.append(tmp) + remote.must("dc", f"mkdir -p {shlex.quote(tmp)}/lmn_squid && : > " + f"{shlex.quote(tmp)}/lmn_squid/__init__.py", root=False) # fmt: skip + for local, name in _bundle(): + remote.put(str(local), f"{tmp}/{name}") + encoded = base64.b64encode(json.dumps(args).encode("utf-8")).decode("ascii") + # a root-only copy: the SSH user cannot swap a file between the copy and the start + script = ( + f"d={REMOTE_DIR}; rm -rf $d; install -d -m 0700 -o root -g root $d; " + f"cp -R {shlex.quote(tmp)}/. $d/; chown -R root:root $d; chmod -R go-rwx $d; " + f"rc=0; cd / && python3 -I $d/dc_agent.py {shlex.quote(action)} " + f"{shlex.quote(encoded)} || rc=$?; rm -rf $d; exit $rc" + ) + try: + status, out = remote.run(script, timeout=AGENT_TIMEOUT) + except sshsetup.StepFailed as exc: + raise DcError("dc_agent", f"Schulserver: {exc.detail}") from None + lines = [line for line in out.splitlines() if line.startswith(MARK)] + if not lines: + tail = out.strip()[-600:] + if status != 0 and ("incorrect password" in tail or "Sorry, try again" in tail): + raise DcError("dc_login", "sudo-Passwort am Schulserver falsch") + raise DcError("dc_agent", f"Schulserver: keine Antwort (Exit {status}) {tail}") + answer: dict[str, Any] = json.loads(lines[-1][len(MARK) :]) + return answer + + +def result_of(data: dict[str, Any]) -> precheck.Result: + """A precheck.Result from the agent's ``as_dict``.""" + res = precheck.Result(facts=dict(data.get("facts") or {})) + for c in data.get("checks") or []: + res.add(str(c.get("id")), str(c.get("status")), str(c.get("message"))) + return res + + +def keytab_maker(login: DcLogin, connect_fn: Connector = sshsetup.connect) -> sshsetup.KeytabMaker: + """The keytab made on the DC (the same steps as ``sshsetup.local_keytab`` there).""" + + def make(fqdn: str, account: str, drop_old: bool) -> tuple[bytes, str, str, bool]: + try: + answer = run_agent( + login, + "keytab", + {"fqdn": fqdn, "account": account, "drop_old": drop_old}, + connect_fn, + ) + except DcError as exc: + raise keytab_mod.KeytabError(exc.message) from None + if answer.get("error"): + raise keytab_mod.KeytabError(str(answer["error"])) + data = base64.b64decode(str(answer["keytab"])) + return ( + data, + str(answer["state"]), + str(answer["rotate"]), + bool(answer["was_disabled"]), + ) + + return make + + +def keytab_check(login: DcLogin, connect_fn: Connector = sshsetup.connect) -> Callable[..., Any]: + """precheck.keytab_target, run on the DC (its DNS, its sam.ldb).""" + + def check(fqdn: str, conn_host: str, conn_fqdn: str, account: str) -> precheck.Result: + try: + answer = run_agent( + login, + "keytab_target", + {"fqdn": fqdn, "conn_host": conn_host, "conn_fqdn": conn_fqdn}, + connect_fn, + ) + except DcError as exc: + res = precheck.Result() + res.add("dc", "error", exc.message) + return res + if answer.get("error"): + res = precheck.Result() + res.add("dc", "error", str(answer["error"])) + return res + return result_of(answer.get("precheck") or {}) + + return check diff --git a/edulution/lmnsquid_edu/dc_agent.py b/edulution/lmnsquid_edu/dc_agent.py new file mode 100644 index 0000000..f89274f --- /dev/null +++ b/edulution/lmnsquid_edu/dc_agent.py @@ -0,0 +1,112 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Runs ON the school server (DC), as root, for one action of the edulution plugin (ADR-024). + +The plugin copies this file, the unchanged modules of the WebUI plugin it needs (``keytab``, +``precheck``, ``sitefacts``, ``runtime``, ``client``, ``connections``) and +``provision-keytab.sh`` over SSH into a root-only directory and starts it once with +``sudo python3 -I``; the directory is removed afterwards. So the DC runs exactly the checked +steps the WebUI runs there (devices.csv and AD checks, account, rotation, export), nothing the +browser sends is executed, and nothing stays on the DC. + +Usage: ``dc_agent.py ``; the answer is one line +``LMNSQUID-DC `` on stdout (a keytab as base64 in it, never written to a file the +agent does not delete). +""" + +from __future__ import annotations + +import base64 +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +MARK = "LMNSQUID-DC " + + +def site() -> dict: + from lmn_squid import sitefacts + + s = sitefacts.read_site() + return { + "realm": s.realm, + "domain": s.domain, + "serverip": s.serverip, + "server_fqdn": s.server_fqdn, + "schools": sitefacts.schools(), + "timezone": sitefacts.local_timezone(), + } + + +def main(argv: list[str]) -> dict: + sys.path.insert(0, HERE) + from lmn_squid import keytab, precheck + + keytab.PROVISION_SCRIPT = os.path.join(HERE, "provision-keytab.sh") + action = argv[1] + args = json.loads(base64.b64decode(argv[2]).decode("utf-8")) if len(argv) > 2 else {} + if action == "site": + return {"site": site()} + if action == "precheck": + same = args.get("same_name") + result = precheck.run( + str(args.get("school") or ""), + str(args.get("fqdn") or ""), + str(args.get("ip") or ""), + keytab.account_name(str(args.get("fqdn") or "x")), + known_hosts=[str(h) for h in args.get("known_hosts") or []], + same_name=tuple(same) if same else None, + ) + try: + facts = site() + except Exception: # noqa: BLE001 - the precheck names the missing site facts itself + facts = {} + return {"precheck": result.as_dict(), "site": facts} + if action == "keytab_target": + fqdn = str(args["fqdn"]) + result = precheck.keytab_target( + fqdn, + str(args["conn_host"]), + str(args.get("conn_fqdn") or ""), + keytab.account_name(fqdn), + ) + return {"precheck": result.as_dict()} + if action == "keytab": + fqdn, account = str(args["fqdn"]), str(args["account"]) + if account != keytab.account_name(fqdn): + return {"error": "Kontoname passt nicht zum FQDN"} + try: + was_disabled = keytab.is_disabled(keytab.account_attrs(account)) + state = keytab.ensure_account(account) + rotate = "" if state == "angelegt" else ("drop" if args.get("drop_old") else "keep") + data, _log = keytab.export(fqdn, account, rotate=rotate) + except keytab.KeytabError as exc: + return {"error": str(exc)} + return { + "keytab": base64.b64encode(data).decode("ascii"), + "state": state, + "rotate": rotate, + "was_disabled": was_disabled, + } + if action == "disable": + account = str(args["account"]) + if not account.startswith("squid-"): + return {"ok": False, "message": "kein Dienstkonto dieses Plugins"} + try: + return {"ok": True, "message": keytab.disable_account(account)} + except keytab.KeytabError as exc: + return {"ok": False, "message": str(exc)} + return {"error": f"unknown action {action!r}"} + + +if __name__ == "__main__": + if os.geteuid() != 0: + print(MARK + json.dumps({"error": "nicht als root gestartet"})) + sys.exit(1) + try: + answer = main(sys.argv) + except Exception as exc: # noqa: BLE001 - one line for the plugin, never a traceback + answer = {"error": f"{type(exc).__name__}: {exc}"} + print(MARK + json.dumps(answer)) diff --git a/edulution/lmnsquid_edu/ldapdir.py b/edulution/lmnsquid_edu/ldapdir.py new file mode 100644 index 0000000..067c373 --- /dev/null +++ b/edulution/lmnsquid_edu/ldapdir.py @@ -0,0 +1,248 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The AD as the scope of the activity view needs it, read over LDAPS (ADR-024). + +The edulution plugin does not run on the DC, so it cannot use linuxmusterTools as the WebUI's +bridge does. It reads the same attributes with a read-only bind account over LDAPS, and hands +:func:`lmn_squid.activity_scope.scope_for` the same shapes linuxmusterTools' models produce: +``schoolclasses`` and ``projects`` are taken from ``memberOf`` by the rules of +``LMNUserMixin.extract_schoolclasses``/``extract_projects`` (a group below ``OU=Students`` that +is no ``-teachers``/``-parents``/``-students`` group is a class; one below ``OU=Projects`` a +project), the users of a school are those below ``OU=,OU=SCHOOLS`` (``/rawusers`` with +``school``), a project's groups its ``sophomorixMemberGroups`` and ``sophomorixAdminGroups``. + +The server certificate is pinned (SHA-256 of the certificate, confirmed by the administrator in +the settings): the TLS handshake trusts no CA, and the bind (with the password) happens only +after the presented certificate matched the pin. +""" + +from __future__ import annotations + +import logging +import socket +import ssl +from typing import Any +from urllib.parse import urlsplit + +from lmn_squid.activity_scope import DirectoryError + +from .settings import Settings, cert_fingerprint + +logger = logging.getLogger("lmnsquid_edu.ldap") + +TIMEOUT = 10 +ROLES = ( + "globaladministrator", + "schooladministrator", + "teacher", + "student", + "parent", + "staff", +) +ATTRS = [ + "sAMAccountName", + "sophomorixRole", + "sophomorixSchoolname", + "displayName", + "givenName", + "sn", + "memberOf", +] +MESSAGE = ( + "Das Benutzerverzeichnis (AD) konnte nicht gelesen werden; Einzelheiten im Log des " + "Plugin-Containers (docker logs edulution-plugin-lmn-squid)." +) + + +def _common_name(dn: str) -> str: + first = dn.split(",", 1)[0] + return first.split("=", 1)[1] if first.upper().startswith("CN=") else "" + + +def schoolclasses(member_of: list[str]) -> list[str]: + """linuxmusterTools' LMNUserMixin.extract_schoolclasses (lmn73).""" + found = [] + for dn in member_of: + if ( + "OU=Students" in dn + and "-teachers," not in dn + and "-parents," not in dn + and "-students," not in dn + ): + name = _common_name(dn) + if name: + found.append(name) + return sorted(found) + + +def projects(member_of: list[str]) -> list[str]: + """linuxmusterTools' LMNUserMixin.extract_projects (lmn73).""" + return sorted(n for n in (_common_name(dn) for dn in member_of if "OU=Projects" in dn) if n) + + +def host_port(url: str) -> tuple[str, int]: + parts = urlsplit(url) + return parts.hostname or "", parts.port or 636 + + +def fetch_certificate(url: str, timeout: float = TIMEOUT) -> dict[str, str]: + """The certificate the LDAPS server presents (nothing is sent but the TLS handshake).""" + from cryptography import x509 + + host, port = host_port(url) + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + with socket.create_connection((host, port), timeout=timeout) as raw: + with ctx.wrap_socket(raw, server_hostname=host) as tls: + der = tls.getpeercert(binary_form=True) or b"" + cert = x509.load_der_x509_certificate(der) + from .settings import colon + + return { + "fingerprint": colon(cert_fingerprint(der)), + "subject": cert.subject.rfc4514_string(), + "not_after": cert.not_valid_after_utc.strftime("%Y-%m-%d"), + } + + +class LdapsDirectory: + """:class:`lmn_squid.activity_scope.Directory` over LDAPS with a pinned certificate.""" + + def __init__(self, settings: Settings) -> None: + if not settings.configured: + raise DirectoryError( + "Schulserver und Verzeichnis sind im Plugin noch nicht eingerichtet " + "(Squid-Proxy → Schulserver und Verzeichnis)." + ) + self.settings = settings + + # ------------------------------------------------------------------ plumbing + def _connection(self) -> Any: + import ldap3 + + host, port = host_port(self.settings.ldap_url) + tls = ldap3.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLS_CLIENT) + server = ldap3.Server( + host, + port=port, + use_ssl=True, + tls=tls, + connect_timeout=TIMEOUT, + get_info=ldap3.NONE, + ) + conn = ldap3.Connection( + server, + user=self.settings.bind_dn, + password=self.settings.bind_password, + auto_bind=ldap3.AUTO_BIND_NONE, + receive_timeout=TIMEOUT, + raise_exceptions=True, + read_only=True, + ) + conn.open() + der = conn.socket.getpeercert(binary_form=True) or b"" + if cert_fingerprint(der) != self.settings.ldap_fingerprint: + conn.unbind() + logger.error("LDAPS certificate of %s does not match the pin: not bound", host) + raise DirectoryError( + "Das Zertifikat des LDAP-Servers passt nicht zum bestätigten Fingerabdruck; " + "nichts gesendet. In den Einstellungen neu holen und vergleichen." + ) + conn.bind() + return conn + + def _search( + self, base: str, flt: str, attrs: list[str], scope: str = "SUBTREE" + ) -> list[dict[str, list[Any]]]: + import ldap3 + + try: + conn = self._connection() + try: + entries = conn.extend.standard.paged_search( + base, + flt, + search_scope=getattr(ldap3, scope), + attributes=attrs, + paged_size=500, + generator=False, + ) + return [ + {k: list(v) if isinstance(v, list) else [v] for k, v in e["attributes"].items()} + | {"dn": [e.get("dn", "")]} + for e in entries + if e.get("type") == "searchResEntry" + ] + finally: + conn.unbind() + except DirectoryError: + raise + except Exception as exc: # noqa: BLE001 - socket, TLS and LDAP errors: one message + logger.error("LDAP %s (%s): %s: %s", base, flt[:80], type(exc).__name__, exc) + raise DirectoryError(MESSAGE) from None + + def _school_base(self, school: str) -> str: + from ldap3.utils.dn import escape_rdn + + return f"OU={escape_rdn(school)},OU=SCHOOLS,{self.settings.base_dn}" + + @staticmethod + def _user(entry: dict[str, list[Any]]) -> dict[str, Any]: + member_of = [str(v) for v in entry.get("memberOf", [])] + user = {k: entry.get(k, []) for k in ATTRS if k != "memberOf"} + user["schoolclasses"] = schoolclasses(member_of) + user["projects"] = projects(member_of) + return user + + # ------------------------------------------------------------------ Directory + def person(self, name: str) -> dict[str, Any] | None: + from ldap3.utils.conv import escape_filter_chars + + found = self._search( + self.settings.base_dn, + f"(&(objectClass=user)(sAMAccountName={escape_filter_chars(name)}))", + ATTRS, + ) + if len(found) != 1: + return None + return self._user(found[0]) + + def school_users(self, school: str) -> list[dict[str, Any]]: + roles = "".join(f"(sophomorixRole={r})" for r in ROLES) + found = self._search(self._school_base(school), f"(&(objectClass=user)(|{roles}))", ATTRS) + return [self._user(e) for e in found] + + def project_groups(self, school: str, project: str) -> list[str]: + from ldap3.utils.conv import escape_filter_chars + + found = self._search( + self._school_base(school), + f"(&(cn={escape_filter_chars(project)})(sophomorixType=project))", + ["sophomorixMemberGroups", "sophomorixAdminGroups"], + ) + if not found: + return [] + return [str(v) for v in found[0].get("sophomorixMemberGroups", [])] + [ + str(v) for v in found[0].get("sophomorixAdminGroups", []) + ] + + # ------------------------------------------------------------------ site facts + def schools(self) -> list[str]: + found = self._search( + f"OU=SCHOOLS,{self.settings.base_dn}", + "(objectClass=organizationalUnit)", + ["ou"], + scope="LEVEL", + ) + names = sorted(str((e.get("ou") or [""])[0]) for e in found) + return sorted((n for n in names if n), key=lambda s: (s != "default-school", s)) + + def server_fqdn(self) -> str: + """The DC's own name (rootDSE dnsHostName), '' if the server does not say.""" + found = self._search("", "(objectClass=*)", ["dnsHostName"], scope="BASE") + value = (found[0].get("dnsHostName") or [""])[0] if found else "" + return str(value).lower() + + def count_users(self, school: str) -> int: + return len(self.school_users(school)) diff --git a/edulution/lmnsquid_edu/runner.py b/edulution/lmnsquid_edu/runner.py new file mode 100644 index 0000000..d9f369a --- /dev/null +++ b/edulution/lmnsquid_edu/runner.py @@ -0,0 +1,79 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Entry point of a background job of the edulution plugin: ``python3 -I runner.py ``. + +The counterpart of the WebUI's ``setup_runner.py`` (same jobs module, same steps of +``sshsetup``), with what differs on this host: the connections live in the plugin's volume, +the keytab is made on the DC over SSH with the administrator's login of this job (``dc`` +in the payload, from stdin only), and the bundled linuxmuster-squid package is the image's. +""" + +from __future__ import annotations + +import json +import os +import signal +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lmn_squid import jobs, sshsetup # noqa: E402 +from lmn_squid.connections import ConnectionStore # noqa: E402 + +from lmnsquid_edu import dc # noqa: E402 +from lmnsquid_edu.settings import DATA_DIR # noqa: E402 + +PACKAGE_DIR = os.environ.get("LMNSQUID_EDU_PACKAGES", "/opt/lmn-squid-edu/packages") + + +def main(argv: list[str]) -> int: + if len(argv) != 3: + print("usage: runner.py ", file=sys.stderr) + return 2 + job_dir, job_id = argv[1], argv[2] + payload = json.loads(sys.stdin.read()) + sys.stdin.close() + rep = jobs.Reporter(job_id, job_dir) + login = dc.DcLogin.from_payload(payload.pop("dc")) + rep.scrub += [login.password, login.sudo_password] + store = ConnectionStore(os.path.join(DATA_DIR, "connections.yml")) + + def stop(signum: int, _frame: object) -> None: + if signum == signal.SIGALRM: + minutes = jobs.JOB_TIMEOUT // 60 + raise jobs.JobAborted(f"Zeitlimit von {minutes} Minuten überschritten, abgebrochen") + raise jobs.JobAborted("Auftrag beendet (SIGTERM), abgebrochen") + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGALRM, stop) + signal.alarm(jobs.JOB_TIMEOUT) + try: + locks = payload.get("locks") or [str(payload.get("target"))] + with jobs.hold_targets(locks, job_dir, job_id): + rep.attach() + maker = dc.keytab_maker(login) + if payload.get("kind") == "setup": + sshsetup.run_setup( + payload, rep, store=store, package_dir=PACKAGE_DIR, make_keytab=maker + ) + elif payload.get("kind") == "keytab": + sshsetup.run_keytab( + payload, rep, store=store, check=dc.keytab_check(login), make_keytab=maker + ) + else: + rep.finish("unbekannter Auftrag") + except jobs.JobError as exc: + rep.finish(str(exc)) + except jobs.JobAborted as exc: + signal.signal(signal.SIGTERM, signal.SIG_IGN) + rep.abort(str(exc)) + return 1 + finally: + signal.alarm(0) + payload.clear() + login.password = login.sudo_password = "" + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/edulution/lmnsquid_edu/serve.py b/edulution/lmnsquid_edu/serve.py new file mode 100644 index 0000000..beca55f --- /dev/null +++ b/edulution/lmnsquid_edu/serve.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Container entry point: ``python3 -I serve.py`` (isolated mode puts no script dir on the path).""" + +from __future__ import annotations + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lmnsquid_edu.server import main # noqa: E402 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/edulution/lmnsquid_edu/server.py b/edulution/lmnsquid_edu/server.py new file mode 100644 index 0000000..84bbb0e --- /dev/null +++ b/edulution/lmnsquid_edu/server.py @@ -0,0 +1,672 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""HTTP server of the edulution plugin (behind Traefik, ``/plugin/lmn-squid`` stripped). + +- ``/manage/`` and ``/activity/``: the two pages (one app tile each), ``/static/...`` their + files, ``/healthz`` for Docker's health check (no data). +- ``/api/lmn/squid/...``: the management routes of the WebUI plugin (``manage_core``), plus + the routes that differ on this host (settings, DC actions, setup, jobs, keytab) — global + administrators only. +- ``/api/lmn/squid-activity/...``: the activity view (``activity_core``), scope from the AD. + +Every API request is identified first (:mod:`auth`); state-changing ones are checked for +their origin. Answers are JSON; tokens, pins of the proxies' tokens and passwords never are in +one. Standard library HTTP server with one thread per request: the users are a school's +administrators and teachers, and the slow parts (proxies, SSH) wait on the network. +""" + +from __future__ import annotations + +import ipaddress +import json +import logging +import mimetypes +import os +import re +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Callable +from urllib.parse import parse_qsl, unquote, urlsplit + +from lmn_squid import activity_core, jobs, manage_core, sshsetup +from lmn_squid import keytab as keytab_mod +from lmn_squid.activity_core import ActivityService, ServiceError +from lmn_squid.activity_scope import CACHE, PERSON_CACHE_SECONDS, ROLES, DirectoryError +from lmn_squid.connections import NAME_RE, RESERVED_NAMES, ConnectionStore + +from . import auth, dc, settings as settings_mod +from .ldapdir import LdapsDirectory, fetch_certificate + +logger = logging.getLogger("lmnsquid_edu") + +DATA_DIR = settings_mod.DATA_DIR +STATIC_DIR = Path(os.environ.get("LMNSQUID_EDU_STATIC", "/opt/lmn-squid-edu/static")) +PACKAGE_DIR = os.environ.get("LMNSQUID_EDU_PACKAGES", "/opt/lmn-squid-edu/packages") +JOB_DIR = os.environ.get("LMNSQUID_EDU_JOBS", "/run/lmn_squid/jobs") +RUNNER = str(Path(__file__).resolve().parent / "runner.py") +# the edulution host's own address as the proxies see it (their TLS allowlist) +EDU_HOST_IP = os.environ.get("LMNSQUID_EDU_HOST_IP", "") +MANAGE = "/api/lmn/squid" +ACTIVITY = "/api/lmn/squid-activity" +MAX_BODY = 1024 * 1024 +CSP = ( + "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; " + "connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'" +) +PAGES = {"manage": "manage.html", "activity": "activity.html"} +EDU_ROUTES = [ + ("GET", r"/whoami", "whoami"), + ("GET", r"/settings", "settings_get"), + ("PUT", r"/settings", "settings_put"), + ("POST", r"/settings/ldap-cert", "settings_cert"), + ("POST", r"/settings/test", "settings_test"), + ("POST", r"/dc/hostkey", "dc_hostkey"), + ("GET", r"/site", "site"), + ("POST", r"/setup/precheck", "setup_precheck"), + ("POST", r"/setup/hostkey", "setup_hostkey"), + ("POST", r"/setup/start", "setup_start"), + ("GET", r"/jobs", "jobs_list"), + ("GET", r"/jobs/(?P[0-9a-f]{16})", "job"), + ("POST", r"/(?P[^/]+)/keytab", "keytab"), + ("DELETE", r"/connections/(?P[^/]+)", "connection_remove"), +] + + +def _deny(status: int, code: str, message: str) -> ServiceError: + return ServiceError(status, {"error": code, "message": message}) + + +class App: + """The routes; one instance per server, shared by the request threads.""" + + def __init__( + self, + store: ConnectionStore | None = None, + settings_store: settings_mod.SettingsStore | None = None, + verify: Callable[[str], tuple[str, set[str]] | None] | None = None, + directory_factory: Callable[[], Any] | None = None, + job_dir: str = JOB_DIR, + spawn: Callable[..., str] = jobs.spawn, + ) -> None: + self.store = store or ConnectionStore(os.path.join(DATA_DIR, "connections.yml")) + self.settings = settings_store or settings_mod.SettingsStore() + self.verify = verify or auth.Verifier() + self.directory_factory = directory_factory or (lambda: LdapsDirectory(self.settings.load())) + self.job_dir = job_dir + self.spawn = spawn + self.manage = manage_core.ManageService(self.store, forget=activity_core.forget_instances) + self.activity = ActivityService( + self.store, + directory_factory=self.directory_factory, + audit=self._activity_line, + ) + self.edu_routes = [(m, re.compile(f"^{p}$"), n) for m, p, n in EDU_ROUTES] + + @staticmethod + def _activity_line(text: str) -> None: + logging.getLogger("lmnsquid_edu.activity").info("%s", text) + + # ------------------------------------------------------------------ entry + def handle( + self, method: str, path: str, query: dict[str, str], headers: Any, raw: bytes + ) -> tuple[int, Any]: + """One API request: (status, JSON data).""" + try: + caller = auth.identify(headers, self.verify) + auth.check_same_origin(method, headers) + body = self._body(method, raw) + if path.startswith(ACTIVITY + "/"): + return self._activity(caller, method, path[len(ACTIVITY) + 1 :], query, body) + if path.startswith(MANAGE + "/"): + return 200, self._manage(caller, method, path[len(MANAGE) :], query, body) + return 404, {"error": "not_found", "message": path[:100]} + except auth.AuthError as exc: + return exc.answer() + except dc.DcError as exc: + status = 409 if exc.code == "dc_hostkey" else 502 + return status, {"error": exc.code, "message": exc.message} + except settings_mod.SettingsError as exc: + return 422, {"error": "invalid", "field": exc.field, "message": exc.message} + except DirectoryError as exc: + return 503, {"error": "directory", "message": str(exc)} + except Exception as exc: # noqa: BLE001 + answer = manage_core.error_answer(exc) + if answer is not None: + return answer + logger.exception("request failed: %s %s", method, path[:100]) + return 502, { + "error": "plugin", + "message": "Interner Fehler des Plugins (docker logs)", + } + + @staticmethod + def _body(method: str, raw: bytes) -> dict[str, Any]: + if method not in auth.STATE_CHANGING or not raw: + return {} + try: + data = json.loads(raw.decode("utf-8")) + except ValueError: + raise _deny(400, "invalid", "body is not JSON") from None + if not isinstance(data, dict): + raise _deny(400, "invalid", "body must be an object") + return data + + def _activity( + self, + caller: auth.Caller, + method: str, + path: str, + query: dict[str, str], + body: Any, + ) -> tuple[int, Any]: + # the role gate the WebUI's permission lm:squid:activity is (students, parents, staff: + # 403); the role comes from the AD, never from the session's groups + if self._ldap_role(caller.user) not in ROLES: + raise _deny(403, "role", "Kein Zugriff auf die Internetnutzung") + status, data = self.activity.dispatch(caller.user, method, path, query, body) + if status == 403 and isinstance(data, dict) and data.get("error") == "scope": + # outside the caller's classes: 404, the same answer as for a person that does + # not exist for them (as the WebUI plugin, cold check m1) + status = 404 + if status >= 500 and status not in (502, 503, 504): + status = 502 + return status, data + + def _manage( + self, + caller: auth.Caller, + method: str, + path: str, + query: dict[str, str], + body: Any, + ) -> Any: + if method == "GET" and path == "/whoami": + return self.whoami(caller) + self._require_global_admin(caller) + for m, pattern, name in self.edu_routes: + match = pattern.match(path) + if match and m == method: + return getattr(self, name)(caller, query, body, **match.groupdict()) + found = self.manage.route(method, path) + if found is None: + raise _deny(404, "not_found", path[:100]) + name, _change, params = found + return getattr(self.manage, name)(caller.user, query, body, **params) + + # ------------------------------------------------------------------ roles + def _person(self, user: str) -> dict[str, Any]: + """The person from the AD, from the scope's own cache (10 s).""" + found = CACHE.get( + ("person", user), + PERSON_CACHE_SECONDS, + lambda: self.directory_factory().person(user), + ) + return found or {} + + def _ldap_role(self, user: str) -> str | None: + """The role from the AD (None while the directory is not set up).""" + if not self.settings.load().configured: + return None + return _first(self._person(user).get("sophomorixRole")) + + def _require_global_admin(self, caller: auth.Caller) -> None: + """Global administrators only: the session's role group, and the AD's role as well + once the directory is set up (a role changed in the AD applies at once).""" + if not caller.global_admin: + raise _deny(403, "role", "Nur für Global-Administratoren") + role = self._ldap_role(caller.user) + if role is not None and role != "globaladministrator": + raise _deny(403, "role", "Nur für Global-Administratoren (laut AD)") + + def whoami(self, caller: auth.Caller) -> dict[str, Any]: + manage = caller.global_admin + role, school, activity = None, None, False + try: + if self.settings.load().configured: + person = self._person(caller.user) + role = _first(person.get("sophomorixRole")) + school = _first(person.get("sophomorixSchoolname")) or None + manage = manage and role == "globaladministrator" + activity = role in ( + "globaladministrator", + "schooladministrator", + "teacher", + ) + except DirectoryError: + pass + return { + "user": caller.user, + "role": role or ("globaladministrator" if caller.global_admin else ""), + "school": school, + "manage": manage, + "activity": activity, + } + + # ------------------------------------------------------------------ settings + def settings_get(self, caller: auth.Caller, query: Any, body: Any) -> Any: + return self.settings.load().public() + + def settings_put(self, caller: auth.Caller, query: Any, body: dict[str, Any]) -> Any: + new = self.settings.update(body) + CACHE.clear() # another directory: no stale scope or person + logger.info( + "user=%s settings changed dc=%s ldap=%s", + caller.user, + new.dc_host, + new.ldap_url, + ) + return new.public() + + def settings_cert(self, caller: auth.Caller, query: Any, body: dict[str, Any]) -> Any: + url = settings_mod.ldap_url(body.get("ldap_url") or self.settings.load().ldap_url) + try: + return fetch_certificate(url) + except OSError as exc: + raise _deny(502, "unreachable", f"{url}: {type(exc).__name__}: {exc}") from None + + def settings_test(self, caller: auth.Caller, query: Any, body: Any) -> Any: + directory = self.directory_factory() + schools = directory.schools() + users = sum(directory.count_users(s) for s in schools) + me = directory.person(caller.user) + role = _first((me or {}).get("sophomorixRole")) + return { + "ok": bool(schools) and role == "globaladministrator", + "message": ( + f"{len(schools)} Schule(n), {users} Benutzer; Ihre Rolle laut AD: {role or '–'}" + ), + "schools": schools, + "users": users, + } + + def _settings(self) -> settings_mod.Settings: + found = self.settings.load() + if not found.configured: + raise _deny( + 409, + "settings", + "Erst Schulserver und Verzeichnis einrichten (Einstellungen)", + ) + return found + + # ------------------------------------------------------------------ DC and setup + def dc_hostkey(self, caller: auth.Caller, query: Any, body: Any) -> Any: + host = self._settings().dc_host + try: + scanned = dc.scan(host) + except Exception as exc: # noqa: BLE001 - socket and paramiko errors alike + raise _deny(502, "unreachable", f"{host}:22 – {type(exc).__name__}: {exc}") from None + logger.info( + "user=%s dc hostkey host=%s fp=%s", + caller.user, + host, + scanned["fingerprint"], + ) + return scanned + + def site(self, caller: auth.Caller, query: Any, body: Any) -> Any: + cfg = self._settings() + directory = self.directory_factory() + try: + version: str | None = sshsetup.packaged_deb(PACKAGE_DIR)[1] + except Exception: # noqa: BLE001 - only reported as "not available" + version = None + return { + "realm": cfg.domain.upper(), + "domain": cfg.domain, + "serverip": cfg.dc_host, + "server_fqdn": directory.server_fqdn(), + "schools": directory.schools(), + "package_version": version, + "timezone": cfg.timezone, + } + + def _precheck_args(self, body: dict[str, Any]) -> dict[str, Any]: + name = str(body.get("name") or "") + all_conns = self.store.load() + conns = [c for c in all_conns.values() if c.name != name] + hosts = [urlsplit(c.url).hostname or "" for c in conns] + [c.fqdn for c in conns if c.fqdn] + same = all_conns.get(name) + return { + "school": str(body.get("school") or ""), + "fqdn": str(body.get("fqdn") or "").strip().lower(), + "ip": str(body.get("ip") or ""), + "known_hosts": hosts, + "same_name": [name, urlsplit(same.url).hostname or "", same.fqdn] if same else None, + } + + def _dc_precheck(self, login: dc.DcLogin, body: dict[str, Any]) -> dict[str, Any]: + answer = dc.run_agent(login, "precheck", self._precheck_args(body)) + if answer.get("error"): + raise dc.DcError("dc_agent", f"Schulserver: {answer['error']}") + return answer + + def setup_precheck(self, caller: auth.Caller, query: Any, body: dict[str, Any]) -> Any: + """D0 on the DC (devices.csv, role, DNS, computer account, SPNs), read-only.""" + login = dc.login_from_body(self._settings().dc_host, body.get("dc"), consume=False) + try: + answer = self._dc_precheck(login, body) + finally: + login.password = login.sudo_password = "" + _scrub(body) + return answer["precheck"] + + def setup_hostkey(self, caller: auth.Caller, query: Any, body: dict[str, Any]) -> Any: + ip = _ipv4(body.get("ip")) + try: + scanned = sshsetup.scan_host_key(ip) + except Exception as exc: # noqa: BLE001 + raise _deny(502, "unreachable", f"{ip}:22 – {type(exc).__name__}: {exc}") from None + _VM_HOSTKEYS[ip] = (_now(), scanned) + logger.info("user=%s setup hostkey ip=%s fp=%s", caller.user, ip, scanned["fingerprint"]) + return { + "ip": ip, + "keytype": scanned["keytype"], + "fingerprint": scanned["fingerprint"], + } + + def setup_start(self, caller: auth.Caller, query: Any, body: dict[str, Any]) -> Any: + """The setup job against the confirmed VM key, with the DC login for precheck and + keytab; every password goes to the job on stdin only.""" + cfg = self._settings() + try: + ip = _ipv4(body.get("ip")) + name = str(body.get("name") or "") + if not NAME_RE.match(name) or name in RESERVED_NAMES: + raise ServiceError(422, {"error": "invalid", "field": "name", "message": "name"}) + login = dc.login_from_body(cfg.dc_host, body.get("dc"), consume=True) + answer = self._dc_precheck(login, body) + result = answer["precheck"] + if not result.get("ok"): + raise ServiceError(409, {"error": "precheck", "precheck": result}) + site = answer.get("site") or {} + scanned_at, scanned = _VM_HOSTKEYS.get(ip, (0.0, {})) + if ( + not scanned + or _now() - scanned_at > sshsetup_hostkey_ttl() + or str(body.get("fingerprint") or "") != scanned["fingerprint"] + ): + raise ServiceError( + 409, + { + "error": "hostkey", + "message": "Host-Key nicht (mehr) bestätigt: erneut holen und bestätigen.", + }, + ) + allow = [cfg.dc_host] + ([EDU_HOST_IP] if EDU_HOST_IP else []) + payload: dict[str, Any] = { + "ip": ip, + "fqdn": str(body.get("fqdn") or "").strip().lower(), + "user": str(body.get("user") or ""), + "password": str(body.get("password") or ""), + "sudo_password": str(body.get("sudo_password") or ""), + "keytype": scanned["keytype"], + "key": scanned["key"], + "serverip": str(site.get("serverip") or cfg.dc_host), + "domain": str(site.get("domain") or cfg.domain), + "server_fqdn": str(site.get("server_fqdn") or ""), + "name": name, + "display_name": str(body.get("display_name") or ""), + "schools": [str(body.get("school"))], + "keytab": bool(body.get("keytab", True)), + "timezone": str(site.get("timezone") or cfg.timezone), + "tls_allow": sorted(set(allow)), + "dc": login.payload(), + } + if not sshsetup.USER_RE.match(str(payload["user"])) or not payload["password"]: + raise ServiceError( + 422, + { + "error": "invalid", + "field": "user", + "message": "SSH user and password needed", + }, + ) + try: + job = self.spawn( + "setup", + ip, + sshsetup.STEPS, + payload, + job_dir=self.job_dir, + runner=RUNNER, + systemd_run=None, + locks=[ip, str(payload["fqdn"])], + ) + finally: + payload.clear() + login.password = login.sudo_password = "" + _VM_HOSTKEYS.pop(ip, None) + logger.info( + "user=%s setup start ip=%s fqdn=%s ssh_user=%s dc_user=%s job=%s", + caller.user, ip, body.get("fqdn"), body.get("user"), login.user, job, + ) # fmt: skip + return {"job": job} + finally: + _scrub(body) + + def jobs_list(self, caller: auth.Caller, query: Any, body: Any) -> Any: + return jobs.list_jobs(self.job_dir) + + def job(self, caller: auth.Caller, query: Any, body: Any, job: str = "") -> Any: + state = jobs.status(job, self.job_dir) + if state is None: + raise _deny(404, "unknown_job", job) + return state + + def keytab(self, caller: auth.Caller, query: Any, body: dict[str, Any], conn: str = "") -> Any: + """D2 with the keytab made on the DC over SSH; the job checks the target there first.""" + cfg = self._settings() + try: + found = self.manage.connection(conn) + fqdn = str(body.get("fqdn") or found.fqdn).strip().lower() + if not sshsetup.FQDN_RE.match(fqdn): + raise ServiceError(422, {"error": "invalid", "field": "fqdn", "message": "FQDN"}) + drop_old = bool(body.get("drop_old_key", False)) + host = urlsplit(found.url).hostname or conn + login = dc.login_from_body(cfg.dc_host, body.get("dc"), consume=True) + checked = dc.keytab_check(login)(fqdn, host, found.fqdn, keytab_mod.account_name(fqdn)) + if not checked.ok: + raise ServiceError(409, {"error": "precheck", "precheck": checked.as_dict()}) + payload = { + "connection": conn, + "fqdn": fqdn, + "drop_old_key": drop_old, + "dc": login.payload(), + } + try: + job = self.spawn( + "keytab", + conn, + sshsetup.KEYTAB_STEPS, + payload, + job_dir=self.job_dir, + runner=RUNNER, + systemd_run=None, + locks=[host, fqdn], + ) + finally: + payload.clear() + login.password = login.sudo_password = "" + logger.info( + "user=%s keytab conn=%s fqdn=%s drop_old_key=%s dc_user=%s job=%s", + caller.user, conn, fqdn, drop_old, login.user, job, + ) # fmt: skip + return {"job": job} + finally: + _scrub(body) + + def connection_remove( + self, caller: auth.Caller, query: Any, body: dict[str, Any], conn: str = "" + ) -> Any: + """Forget the connection; with ``disable_account`` also disable the host's service + account on the DC (only one this plugin created), with the DC login of this action.""" + try: + disable = body.get("disable_account") is True + login = None + if disable: + login = dc.login_from_body(self._settings().dc_host, body.get("dc"), consume=True) + removed = self.manage.connection_remove(caller.user, conn) + logger.info( + "user=%s connection remove conn=%s disable_account=%s", + caller.user, + conn, + disable, + ) + answer: dict[str, Any] = {"removed": conn} + if login is not None: + fqdn = getattr(removed, "fqdn", "") + if not fqdn: + answer["account"] = { + "ok": False, + "message": "FQDN des Proxys unbekannt: Dienstkonto nicht deaktiviert " + "(von Hand: samba-tool user disable squid-)", + } + else: + account = keytab_mod.account_name(fqdn) + try: + result = dc.run_agent(login, "disable", {"account": account}) + except dc.DcError as exc: + result = {"ok": False, "message": exc.message} + finally: + login.password = login.sudo_password = "" + answer["account"] = {"account": account, **result} + return answer + finally: + _scrub(body) + + +_VM_HOSTKEYS: dict[str, tuple[float, dict[str, str]]] = {} + + +def sshsetup_hostkey_ttl() -> float: + return dc.HOSTKEY_TTL + + +def _now() -> float: + import time + + return time.monotonic() + + +def _first(value: Any) -> str: + if isinstance(value, list): + value = value[0] if value else "" + return str(value or "") + + +def _ipv4(value: Any) -> str: + try: + return str(ipaddress.IPv4Address(str(value).strip())) + except ValueError: + raise _deny(422, "invalid", "IPv4 address expected") from None + + +def _scrub(body: Any) -> None: + """Passwords out of the request body as soon as they are used.""" + if isinstance(body, dict): + body.pop("password", None) + body.pop("sudo_password", None) + if isinstance(body.get("dc"), dict): + body["dc"].pop("password", None) + body["dc"].pop("sudo_password", None) + + +# ---------------------------------------------------------------------- HTTP plumbing +class Handler(BaseHTTPRequestHandler): + server_version = "lmn-squid-edu" + sys_version = "" + app: App + protocol_version = "HTTP/1.1" + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 - stdlib's name + # method, path, status only: never a query string or a body + logger.info("%s %s", self.command, self.path.split("?", 1)[0][:120]) + + def _send( + self, status: int, body: bytes, ctype: str, extra: dict[str, str] | None = None + ) -> None: + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "same-origin") + self.send_header("Content-Security-Policy", CSP) + self.send_header("Cache-Control", "no-store") + for k, v in (extra or {}).items(): + self.send_header(k, v) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def _json(self, status: int, data: Any) -> None: + self._send(status, json.dumps(data).encode("utf-8"), "application/json; charset=utf-8") + + def _dispatch(self) -> None: + parts = urlsplit(self.path) + path = unquote(parts.path) + if path == "/healthz": + self._send(200, b"ok", "text/plain") + return + if path.startswith("/api/"): + length = int(self.headers.get("Content-Length") or 0) + if length > MAX_BODY: + self._json(413, {"error": "invalid", "message": "body too large"}) + return + raw = self.rfile.read(length) if length else b"" + query = dict(parse_qsl(parts.query, keep_blank_values=True)) + status, data = self.app.handle(self.command, path, query, self.headers, raw) + self._json(status, data) + return + if self.command not in ("GET", "HEAD"): + self._json(405, {"error": "method", "message": "method not allowed"}) + return + page = re.match(r"^/(manage|activity)/?(index\.html)?$", path) + if page: + if not path.endswith("/") and not path.endswith(".html"): + self._send(302, b"", "text/plain", {"Location": f"{path}/"}) + return + self._file(STATIC_DIR / PAGES[page.group(1)]) + return + if path.startswith("/static/"): + target = (STATIC_DIR / path[len("/static/") :]).resolve() + if STATIC_DIR.resolve() not in target.parents or not target.is_file(): + self._json(404, {"error": "not_found", "message": "no such file"}) + return + self._file(target) + return + self._json(404, {"error": "not_found", "message": "no such page"}) + + def _file(self, target: Path) -> None: + try: + data = target.read_bytes() + except OSError: + self._json(404, {"error": "not_found", "message": "no such file"}) + return + ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream" + if ctype.startswith("text/") or ctype.endswith("javascript"): + ctype += "; charset=utf-8" + self._send(200, data, ctype) + + do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = _dispatch + + +def main(argv: list[str] | None = None) -> int: + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(name)s %(levelname)s %(message)s", + stream=sys.stdout, + ) + mimetypes.add_type("text/javascript", ".js") + port = int(os.environ.get("LMNSQUID_EDU_PORT", "8080")) + Handler.app = App() + server = ThreadingHTTPServer(("0.0.0.0", port), Handler) # noqa: S104 - the container's net only + server.daemon_threads = True + logger.info("listening on :%d (behind edulution's Traefik)", port) + server.serve_forever() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/edulution/lmnsquid_edu/settings.py b/edulution/lmnsquid_edu/settings.py new file mode 100644 index 0000000..704f145 --- /dev/null +++ b/edulution/lmnsquid_edu/settings.py @@ -0,0 +1,191 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The plugin's own settings: the school server (DC) and the read-only directory account. + +Stored in one JSON file in the plugin's volume (``0600``, the container's user), written +atomically under a lock, like the connection file. The bind password is write-only: it never +leaves this module towards the browser (:meth:`Settings.public` says only whether one is set). +""" + +from __future__ import annotations + +import contextlib +import fcntl +import hashlib +import ipaddress +import json +import os +import re +import tempfile +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Iterator +from urllib.parse import urlsplit + +DATA_DIR = os.environ.get("LMNSQUID_EDU_DATA", "/var/lib/lmn-squid-edu") +DN_RE = re.compile( + r"^(?:[A-Za-z][A-Za-z0-9-]*=[^,=\x00-\x1f]+,)*[A-Za-z][A-Za-z0-9-]*=[^,=\x00-\x1f]+$" +) +FINGERPRINT_RE = re.compile(r"^[0-9a-f]{64}$") +TZ_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_+-]*(/[A-Za-z0-9_+-]+){0,2}$") +PASSWORD_MAX = 256 + + +class SettingsError(ValueError): + """Invalid settings; ``field`` names the form field.""" + + def __init__(self, field_name: str, message: str) -> None: + super().__init__(message) + self.field = field_name + self.message = message + + +def normalize_fingerprint(value: str) -> str: + """SHA-256 of a certificate: 64 hex digits, with or without colons, any case.""" + text = re.sub(r"[\s:]", "", str(value or "")).lower() + if text.startswith("sha256="): + text = text[7:] + if not FINGERPRINT_RE.match(text): + raise SettingsError("ldap_fingerprint", "SHA-256-Fingerabdruck (64 Hexziffern) erwartet") + return text + + +def cert_fingerprint(der: bytes) -> str: + return hashlib.sha256(der).hexdigest() + + +def colon(fp: str) -> str: + return ":".join(fp[i : i + 2] for i in range(0, len(fp), 2)).upper() + + +@dataclass +class Settings: + dc_host: str = "" + ldap_url: str = "" + base_dn: str = "" + bind_dn: str = "" + bind_password: str = "" + ldap_fingerprint: str = "" + timezone: str = "Europe/Berlin" + + @property + def configured(self) -> bool: + return bool( + self.dc_host + and self.ldap_url + and self.base_dn + and self.bind_dn + and self.bind_password + and self.ldap_fingerprint + ) + + @property + def domain(self) -> str: + """dc=dev,dc=lmschule,dc=de -> dev.lmschule.de""" + parts = [p.split("=", 1)[1] for p in self.base_dn.split(",") if p.lower().startswith("dc=")] + return ".".join(parts).lower() + + def public(self) -> dict[str, Any]: + return { + "configured": self.configured, + "dc_host": self.dc_host, + "ldap_url": self.ldap_url, + "base_dn": self.base_dn, + "bind_dn": self.bind_dn, + "password_set": bool(self.bind_password), + "ldap_fingerprint": colon(self.ldap_fingerprint) if self.ldap_fingerprint else "", + "timezone": self.timezone, + } + + +def ldap_url(value: str) -> str: + """ldaps://host[:port] only: the bind password never travels in clear.""" + text = str(value or "").strip() + parts = urlsplit(text) + try: + port = parts.port + except ValueError: + port = -1 + if parts.scheme != "ldaps" or not parts.hostname or port == -1 or parts.path not in ("", "/"): + raise SettingsError("ldap_url", "ldaps://[:636] erwartet") + return f"ldaps://{parts.hostname}" + (f":{port}" if port else "") + + +def validate(data: dict[str, Any], old: Settings) -> Settings: + new = Settings(**asdict(old)) + if "dc_host" in data: + try: + new.dc_host = str(ipaddress.IPv4Address(str(data["dc_host"]).strip())) + except ValueError: + raise SettingsError("dc_host", "IPv4-Adresse des Schulservers erwartet") from None + if "ldap_url" in data: + new.ldap_url = ldap_url(data["ldap_url"]) + for key in ("base_dn", "bind_dn"): + if key in data: + value = str(data[key] or "").strip() + if not DN_RE.match(value) or len(value) > 512: + raise SettingsError(key, "DN der Form CN=…,OU=…,DC=… erwartet") + setattr(new, key, value) + if data.get("password"): + password = str(data["password"]) + if len(password) > PASSWORD_MAX or any(c in password for c in "\x00\r\n"): + raise SettingsError("password", "ungültiges Passwort") + new.bind_password = password + if "ldap_fingerprint" in data: + new.ldap_fingerprint = ( + normalize_fingerprint(data["ldap_fingerprint"]) if data["ldap_fingerprint"] else "" + ) + if "timezone" in data: + zone = str(data["timezone"] or "").strip() + if not TZ_RE.match(zone): + raise SettingsError("timezone", "Zeitzone wie Europe/Berlin erwartet") + new.timezone = zone + if new.base_dn and new.bind_dn and not new.bind_dn.lower().endswith(new.base_dn.lower()): + raise SettingsError("bind_dn", "Das Konto liegt nicht unter der Basis-DN") + if new.ldap_url != old.ldap_url and "ldap_fingerprint" not in data: + new.ldap_fingerprint = "" # another server: its certificate must be confirmed again + return new + + +class SettingsStore: + def __init__(self, path: str | None = None) -> None: + self.path = Path(path or os.path.join(DATA_DIR, "settings.json")) + + def load(self) -> Settings: + try: + raw = json.loads(self.path.read_text(encoding="utf-8")) + except FileNotFoundError: + return Settings() + except (OSError, ValueError) as exc: + raise SettingsError("file", f"{self.path} nicht lesbar: {exc}") from None + known = {k: str(v) for k, v in raw.items() if k in Settings.__dataclass_fields__} + return Settings(**known) + + @contextlib.contextmanager + def _locked(self) -> Iterator[None]: + self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open( + self.path.parent / ".settings.lock", + os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + ) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) + + def update(self, data: dict[str, Any]) -> Settings: + with self._locked(): + new = validate(data, self.load()) + fd, tmp = tempfile.mkstemp(dir=self.path.parent, prefix=".settings-", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + os.fchmod(fh.fileno(), 0o600) + json.dump(asdict(new), fh) + os.replace(tmp, self.path) + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp) + raise + return new diff --git a/edulution/pyproject.toml b/edulution/pyproject.toml new file mode 100644 index 0000000..53cb137 --- /dev/null +++ b/edulution/pyproject.toml @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Tool settings for the edulution plugin (package linuxmuster-squid-edulution and its container +# image). Not a Python distribution: the image installs edulution/requirements.lock and copies +# lmnsquid_edu/ beside the shared modules of webui/lmn_squid/ (ADR-024). + +[tool.ruff] +line-length = 100 + +[tool.ruff.lint] +# Same rule set as controlplane/pyproject.toml and webui/pyproject.toml. +select = ["E4", "E7", "E9", "F"] + +[tool.mypy] +python_version = "3.12" +warn_unused_ignores = true +warn_redundant_casts = true +mypy_path = "$MYPY_CONFIG_FILE_DIR/../webui" + +[[tool.mypy.overrides]] +module = ["ldap3", "ldap3.*", "paramiko", "aj", "aj.*", "jadi", "linuxmusterTools", "linuxmusterTools.*"] +ignore_missing_imports = true + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/edulution/requirements.in b/edulution/requirements.in new file mode 100644 index 0000000..3f9b612 --- /dev/null +++ b/edulution/requirements.in @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# What the edulution plugin's container needs besides Python's standard library (ADR-024): +# paramiko (SSH to a new proxy VM and to the DC, as the WebUI plugin), ldap3 (the scope from +# the AD over LDAPS), PyYAML (the shared connection file). Compiled with hashes into +# edulution/requirements.lock by packaging/lock-deps.sh; the image installs only that lock. +paramiko>=3.2 +ldap3 +pyyaml diff --git a/edulution/requirements.lock b/edulution/requirements.lock new file mode 100644 index 0000000..3c3050e --- /dev/null +++ b/edulution/requirements.lock @@ -0,0 +1,354 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile edulution/requirements.in --python-version=3.12 --exclude-newer=P7D --generate-hashes --output-file=edulution/requirements.lock +bcrypt==5.0.0 \ + --hash=sha256:046ad6db88edb3c5ece4369af997938fb1c19d6a699b9c1b27b0db432faae4c4 \ + --hash=sha256:0c418ca99fd47e9c59a301744d63328f17798b5947b0f791e9af3c1c499c2d0a \ + --hash=sha256:0c8e093ea2532601a6f686edbc2c6b2ec24131ff5c52f7610dd64fa4553b5464 \ + --hash=sha256:0cae4cb350934dfd74c020525eeae0a5f79257e8a201c0c176f4b84fdbf2a4b4 \ + --hash=sha256:137c5156524328a24b9fac1cb5db0ba618bc97d11970b39184c1d87dc4bf1746 \ + --hash=sha256:200af71bc25f22006f4069060c88ed36f8aa4ff7f53e67ff04d2ab3f1e79a5b2 \ + --hash=sha256:212139484ab3207b1f0c00633d3be92fef3c5f0af17cad155679d03ff2ee1e41 \ + --hash=sha256:2b732e7d388fa22d48920baa267ba5d97cca38070b69c0e2d37087b381c681fd \ + --hash=sha256:35a77ec55b541e5e583eb3436ffbbf53b0ffa1fa16ca6782279daf95d146dcd9 \ + --hash=sha256:38cac74101777a6a7d3b3e3cfefa57089b5ada650dce2baf0cbdd9d65db22a9e \ + --hash=sha256:3abeb543874b2c0524ff40c57a4e14e5d3a66ff33fb423529c88f180fd756538 \ + --hash=sha256:3ca8a166b1140436e058298a34d88032ab62f15aae1c598580333dc21d27ef10 \ + --hash=sha256:3cf67a804fc66fc217e6914a5635000259fbbbb12e78a99488e4d5ba445a71eb \ + --hash=sha256:4870a52610537037adb382444fefd3706d96d663ac44cbb2f37e3919dca3d7ef \ + --hash=sha256:48f753100931605686f74e27a7b49238122aa761a9aefe9373265b8b7aa43ea4 \ + --hash=sha256:4bfd2a34de661f34d0bda43c3e4e79df586e4716ef401fe31ea39d69d581ef23 \ + --hash=sha256:560ddb6ec730386e7b3b26b8b4c88197aaed924430e7b74666a586ac997249ef \ + --hash=sha256:5b1589f4839a0899c146e8892efe320c0fa096568abd9b95593efac50a87cb75 \ + --hash=sha256:5feebf85a9cefda32966d8171f5db7e3ba964b77fdfe31919622256f80f9cf42 \ + --hash=sha256:611f0a17aa4a25a69362dcc299fda5c8a3d4f160e2abb3831041feb77393a14a \ + --hash=sha256:61afc381250c3182d9078551e3ac3a41da14154fbff647ddf52a769f588c4172 \ + --hash=sha256:64d7ce196203e468c457c37ec22390f1a61c85c6f0b8160fd752940ccfb3a683 \ + --hash=sha256:64ee8434b0da054d830fa8e89e1c8bf30061d539044a39524ff7dec90481e5c2 \ + --hash=sha256:6b8f520b61e8781efee73cba14e3e8c9556ccfb375623f4f97429544734545b4 \ + --hash=sha256:741449132f64b3524e95cd30e5cd3343006ce146088f074f31ab26b94e6c75ba \ + --hash=sha256:744d3c6b164caa658adcb72cb8cc9ad9b4b75c7db507ab4bc2480474a51989da \ + --hash=sha256:79cfa161eda8d2ddf29acad370356b47f02387153b11d46042e93a0a95127493 \ + --hash=sha256:7aeef54b60ceddb6f30ee3db090351ecf0d40ec6e2abf41430997407a46d2254 \ + --hash=sha256:7edda91d5ab52b15636d9c30da87d2cc84f426c72b9dba7a9b4fe142ba11f534 \ + --hash=sha256:7f277a4b3390ab4bebe597800a90da0edae882c6196d3038a73adf446c4f969f \ + --hash=sha256:7f4c94dec1b5ab5d522750cb059bb9409ea8872d4494fd152b53cca99f1ddd8c \ + --hash=sha256:801cad5ccb6b87d1b430f183269b94c24f248dddbbc5c1f78b6ed231743e001c \ + --hash=sha256:83e787d7a84dbbfba6f250dd7a5efd689e935f03dd83b0f919d39349e1f23f83 \ + --hash=sha256:89042e61b5e808b67daf24a434d89bab164d4de1746b37a8d173b6b14f3db9ff \ + --hash=sha256:92864f54fb48b4c718fc92a32825d0e42265a627f956bc0361fe869f1adc3e7d \ + --hash=sha256:9d52ed507c2488eddd6a95bccee4e808d3234fa78dd370e24bac65a21212b861 \ + --hash=sha256:9fffdb387abe6aa775af36ef16f55e318dcda4194ddbf82007a6f21da29de8f5 \ + --hash=sha256:a28bc05039bdf3289d757f49d616ab3efe8cf40d8e8001ccdd621cd4f98f4fc9 \ + --hash=sha256:a5393eae5722bcef046a990b84dff02b954904c36a194f6cfc817d7dca6c6f0b \ + --hash=sha256:a71f70ee269671460b37a449f5ff26982a6f2ba493b3eabdd687b4bf35f875ac \ + --hash=sha256:b17366316c654e1ad0306a6858e189fc835eca39f7eb2cafd6aaca8ce0c40a2e \ + --hash=sha256:baade0a5657654c2984468efb7d6c110db87ea63ef5a4b54732e7e337253e44f \ + --hash=sha256:c2388ca94ffee269b6038d48747f4ce8df0ffbea43f31abfa18ac72f0218effb \ + --hash=sha256:c58b56cdfb03202b3bcc9fd8daee8e8e9b6d7e3163aa97c631dfcfcc24d36c86 \ + --hash=sha256:cde08734f12c6a4e28dc6755cd11d3bdfea608d93d958fffbe95a7026ebe4980 \ + --hash=sha256:d79e5c65dcc9af213594d6f7f1fa2c98ad3fc10431e7aa53c176b441943efbdd \ + --hash=sha256:d8d65b564ec849643d9f7ea05c6d9f0cd7ca23bdd4ac0c2dbef1104ab504543d \ + --hash=sha256:db99dca3b1fdc3db87d7c57eac0c82281242d1eabf19dcb8a6b10eb29a2e72d1 \ + --hash=sha256:dcd58e2b3a908b5ecc9b9df2f0085592506ac2d5110786018ee5e160f28e0911 \ + --hash=sha256:dd19cf5184a90c873009244586396a6a884d591a5323f0e8a5922560718d4993 \ + --hash=sha256:ddb4e1500f6efdd402218ffe34d040a1196c072e07929b9820f363a1fd1f4191 \ + --hash=sha256:e3cf5b2560c7b5a142286f69bde914494b6d8f901aaa71e453078388a50881c4 \ + --hash=sha256:ed2e1365e31fc73f1825fa830f1c8f8917ca1b3ca6185773b349c20fd606cec2 \ + --hash=sha256:edfcdcedd0d0f05850c52ba3127b1fce70b9f89e0fe5ff16517df7e81fa3cbb8 \ + --hash=sha256:f0ce778135f60799d89c9693b9b398819d15f1921ba15fe719acb3178215a7db \ + --hash=sha256:f2347d3534e76bf50bca5500989d6c1d05ed64b440408057a37673282c654927 \ + --hash=sha256:f3c08197f3039bec79cee59a606d62b96b16669cff3949f21e74796b6e3cd2be \ + --hash=sha256:f632fd56fc4e61564f78b46a2269153122db34988e78b6be8b32d28507b7eaeb \ + --hash=sha256:f6984a24db30548fd39a44360532898c33528b74aedf81c26cf29c51ee47057e \ + --hash=sha256:f70aadb7a809305226daedf75d90379c397b094755a710d7014b8b117df1ebbf \ + --hash=sha256:f748f7c2d6fd375cc93d3fba7ef4a9e3a092421b8dbf34d8d4dc06be9492dfdd \ + --hash=sha256:f8429e1c410b4073944f03bd778a9e066e7fad723564a52ff91841d278dfc822 \ + --hash=sha256:fc746432b951e92b58317af8e0ca746efe93e66555f1b40888865ef5bf56446b + # via paramiko +cffi==2.1.1 \ + --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \ + --hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \ + --hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \ + --hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \ + --hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \ + --hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \ + --hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \ + --hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \ + --hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \ + --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \ + --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \ + --hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \ + --hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \ + --hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \ + --hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \ + --hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \ + --hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \ + --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \ + --hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \ + --hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \ + --hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \ + --hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \ + --hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \ + --hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \ + --hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \ + --hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \ + --hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \ + --hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \ + --hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \ + --hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \ + --hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \ + --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \ + --hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \ + --hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \ + --hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \ + --hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \ + --hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \ + --hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \ + --hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \ + --hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \ + --hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \ + --hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \ + --hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \ + --hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \ + --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \ + --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \ + --hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \ + --hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \ + --hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \ + --hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \ + --hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \ + --hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \ + --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \ + --hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \ + --hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \ + --hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \ + --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \ + --hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \ + --hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \ + --hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \ + --hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \ + --hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \ + --hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \ + --hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \ + --hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \ + --hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \ + --hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \ + --hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \ + --hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \ + --hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \ + --hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \ + --hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \ + --hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \ + --hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \ + --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \ + --hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \ + --hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \ + --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \ + --hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \ + --hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \ + --hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \ + --hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \ + --hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \ + --hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \ + --hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \ + --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \ + --hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \ + --hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \ + --hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \ + --hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \ + --hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \ + --hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \ + --hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \ + --hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \ + --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \ + --hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \ + --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \ + --hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \ + --hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \ + --hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264 + # via + # cryptography + # pynacl +cryptography==50.0.2 \ + --hash=sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602 \ + --hash=sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2 \ + --hash=sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047 \ + --hash=sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c \ + --hash=sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42 \ + --hash=sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18 \ + --hash=sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51 \ + --hash=sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81 \ + --hash=sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856 \ + --hash=sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2 \ + --hash=sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de \ + --hash=sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7 \ + --hash=sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd \ + --hash=sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2 \ + --hash=sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be \ + --hash=sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45 \ + --hash=sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0 \ + --hash=sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e \ + --hash=sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c \ + --hash=sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5 \ + --hash=sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452 \ + --hash=sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48 \ + --hash=sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05 \ + --hash=sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1 \ + --hash=sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93 \ + --hash=sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04 \ + --hash=sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e \ + --hash=sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67 \ + --hash=sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7 \ + --hash=sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107 \ + --hash=sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079 \ + --hash=sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134 \ + --hash=sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227 \ + --hash=sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1 \ + --hash=sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539 \ + --hash=sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e \ + --hash=sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d \ + --hash=sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c \ + --hash=sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd \ + --hash=sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020 \ + --hash=sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd \ + --hash=sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94 \ + --hash=sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a \ + --hash=sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408 \ + --hash=sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37 \ + --hash=sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e \ + --hash=sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454 \ + --hash=sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c \ + --hash=sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc \ + --hash=sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37 \ + --hash=sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767 \ + --hash=sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a \ + --hash=sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5 \ + --hash=sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc \ + --hash=sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67 \ + --hash=sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8 \ + --hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \ + --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb \ + --hash=sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b + # via paramiko +invoke==3.0.3 \ + --hash=sha256:437b6a622223824380bfb4e64f612711a6b648c795f565efc8625af66fb57f0c \ + --hash=sha256:f11327165e5cbb89b2ad1d88d3292b5113332c43b8553b494da435d6ec6f5053 + # via paramiko +ldap3==2.9.1 \ + --hash=sha256:5869596fc4948797020d3f03b7939da938778a0f9e2009f7a072ccf92b8e8d70 \ + --hash=sha256:f3e7fc4718e3f09dda568b57100095e0ce58633bcabbed8667ce3f8fbaa4229f + # via -r edulution/requirements.in +paramiko==5.1.0 \ + --hash=sha256:239b5f9b2a53006cd54f83cf8495ee742083708ead947882c8dd2786de79f39b \ + --hash=sha256:d9fe6d67a9d0bbf3eb85b051d26ab850b678c02d060f32915b944e5ca6d0d9e1 + # via -r edulution/requirements.in +pyasn1==0.6.5 \ + --hash=sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587 \ + --hash=sha256:6b11616a6bcf3a40e635f082bb232fa57b5e0dd7f517bd7ddd69ec3794508a47 + # via ldap3 +pycparser==3.12 \ + --hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e \ + --hash=sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6 + # via cffi +pynacl==1.6.2 \ + --hash=sha256:018494d6d696ae03c7e656e5e74cdfd8ea1326962cc401bcf018f1ed8436811c \ + --hash=sha256:04316d1fc625d860b6c162fff704eb8426b1a8bcd3abacea11142cbd99a6b574 \ + --hash=sha256:22de65bb9010a725b0dac248f353bb072969c94fa8d6b1f34b87d7953cf7bbe4 \ + --hash=sha256:26bfcd00dcf2cf160f122186af731ae30ab120c18e8375684ec2670dccd28130 \ + --hash=sha256:2fef529ef3ee487ad8113d287a593fa26f48ee3620d92ecc6f1d09ea38e0709b \ + --hash=sha256:320ef68a41c87547c91a8b58903c9caa641ab01e8512ce291085b5fe2fcb7590 \ + --hash=sha256:3bffb6d0f6becacb6526f8f42adfb5efb26337056ee0831fb9a7044d1a964444 \ + --hash=sha256:44081faff368d6c5553ccf55322ef2819abb40e25afaec7e740f159f74813634 \ + --hash=sha256:46065496ab748469cdd999246d17e301b2c24ae2fdf739132e580a0e94c94a87 \ + --hash=sha256:5811c72b473b2f38f7e2a3dc4f8642e3a3e9b5e7317266e4ced1fba85cae41aa \ + --hash=sha256:622d7b07cc5c02c666795792931b50c91f3ce3c2649762efb1ef0d5684c81594 \ + --hash=sha256:62985f233210dee6548c223301b6c25440852e13d59a8b81490203c3227c5ba0 \ + --hash=sha256:68be3a09455743ff9505491220b64440ced8973fe930f270c8e07ccfa25b1f9e \ + --hash=sha256:834a43af110f743a754448463e8fd61259cd4ab5bbedcf70f9dabad1d28a394c \ + --hash=sha256:8845c0631c0be43abdd865511c41eab235e0be69c81dc66a50911594198679b0 \ + --hash=sha256:8a66d6fb6ae7661c58995f9c6435bda2b1e68b54b598a6a10247bfcdadac996c \ + --hash=sha256:8b097553b380236d51ed11356c953bf8ce36a29a3e596e934ecabe76c985a577 \ + --hash=sha256:a84bf1c20339d06dc0c85d9aea9637a24f718f375d861b2668b2f9f96fa51145 \ + --hash=sha256:a9f9932d8d2811ce1a8ffa79dcbdf3970e7355b5c8eb0c1a881a57e7f7d96e88 \ + --hash=sha256:bc4a36b28dd72fb4845e5d8f9760610588a96d5a51f01d84d8c6ff9849968c14 \ + --hash=sha256:c8a231e36ec2cab018c4ad4358c386e36eede0319a0c41fed24f840b1dac59f6 \ + --hash=sha256:c949ea47e4206af7c8f604b8278093b674f7c79ed0d4719cc836902bf4517465 \ + --hash=sha256:d071c6a9a4c94d79eb665db4ce5cedc537faf74f2355e4d502591d850d3913c0 \ + --hash=sha256:d29bfe37e20e015a7d8b23cfc8bd6aa7909c92a1b8f41ee416bbb3e79ef182b2 \ + --hash=sha256:fe9847ca47d287af41e82be1dd5e23023d3c31a951da134121ab02e42ac218c9 + # via paramiko +pyyaml==6.0.3 \ + --hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \ + --hash=sha256:0150219816b6a1fa26fb4699fb7daa9caf09eb1999f3b70fb6e786805e80375a \ + --hash=sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3 \ + --hash=sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956 \ + --hash=sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6 \ + --hash=sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c \ + --hash=sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65 \ + --hash=sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a \ + --hash=sha256:1ebe39cb5fc479422b83de611d14e2c0d3bb2a18bbcb01f229ab3cfbd8fee7a0 \ + --hash=sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b \ + --hash=sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1 \ + --hash=sha256:22ba7cfcad58ef3ecddc7ed1db3409af68d023b7f940da23c6c2a1890976eda6 \ + --hash=sha256:27c0abcb4a5dac13684a37f76e701e054692a9b2d3064b70f5e4eb54810553d7 \ + --hash=sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e \ + --hash=sha256:2e71d11abed7344e42a8849600193d15b6def118602c4c176f748e4583246007 \ + --hash=sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310 \ + --hash=sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4 \ + --hash=sha256:3c5677e12444c15717b902a5798264fa7909e41153cdf9ef7ad571b704a63dd9 \ + --hash=sha256:3ff07ec89bae51176c0549bc4c63aa6202991da2d9a6129d7aef7f1407d3f295 \ + --hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \ + --hash=sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0 \ + --hash=sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e \ + --hash=sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac \ + --hash=sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9 \ + --hash=sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7 \ + --hash=sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35 \ + --hash=sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb \ + --hash=sha256:5cf4e27da7e3fbed4d6c3d8e797387aaad68102272f8f9752883bc32d61cb87b \ + --hash=sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69 \ + --hash=sha256:5ed875a24292240029e4483f9d4a4b8a1ae08843b9c54f43fcc11e404532a8a5 \ + --hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \ + --hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \ + --hash=sha256:6344df0d5755a2c9a276d4473ae6b90647e216ab4757f8426893b5dd2ac3f369 \ + --hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \ + --hash=sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824 \ + --hash=sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198 \ + --hash=sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065 \ + --hash=sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c \ + --hash=sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c \ + --hash=sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764 \ + --hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \ + --hash=sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b \ + --hash=sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00 \ + --hash=sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac \ + --hash=sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8 \ + --hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \ + --hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \ + --hash=sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3 \ + --hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \ + --hash=sha256:9c57bb8c96f6d1808c030b1687b9b5fb476abaa47f0db9c0101f5e9f394e97f4 \ + --hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b \ + --hash=sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf \ + --hash=sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5 \ + --hash=sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702 \ + --hash=sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8 \ + --hash=sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788 \ + --hash=sha256:b865addae83924361678b652338317d1bd7e79b1f4596f96b96c77a5a34b34da \ + --hash=sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d \ + --hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \ + --hash=sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c \ + --hash=sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba \ + --hash=sha256:c2514fceb77bc5e7a2f7adfaa1feb2fb311607c9cb518dbc378688ec73d8292f \ + --hash=sha256:c3355370a2c156cffb25e876646f149d5d68f5e0a3ce86a5084dd0b64a994917 \ + --hash=sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5 \ + --hash=sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26 \ + --hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \ + --hash=sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b \ + --hash=sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be \ + --hash=sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c \ + --hash=sha256:efd7b85f94a6f21e4932043973a7ba2613b059c4a000551892ac9f1d11f5baf3 \ + --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \ + --hash=sha256:fa160448684b4e94d80416c0fa4aac48967a969efe22931448d853ada8baf926 \ + --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0 + # via -r edulution/requirements.in diff --git a/edulution/requirements.lock.license b/edulution/requirements.lock.license new file mode 100644 index 0000000..38fc113 --- /dev/null +++ b/edulution/requirements.lock.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: Kevin Stenzel + +SPDX-License-Identifier: GPL-3.0-or-later diff --git a/edulution/tests/conftest.py b/edulution/tests/conftest.py new file mode 100644 index 0000000..c690ff1 --- /dev/null +++ b/edulution/tests/conftest.py @@ -0,0 +1,322 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""Fixtures of the edulution plugin's tests. + +The application is assembled by ``edulution/build_app.py`` into a temporary directory, exactly +as the image gets it (the shared ``lmn_squid`` modules with an ``__init__`` of their own, not the +WebUI's), and the real HTTP server runs on a free port. A real control plane (the project's own +FastAPI app with a fake Docker, on its TLS listener) answers the proxies' side. Run apart from +``webui/tests``: both import a package named ``lmn_squid``. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import shutil +import socket +import ssl +import subprocess +import sys +import tempfile +import threading +import time +from contextlib import contextmanager +from http.client import HTTPConnection +from pathlib import Path +from typing import Any, Iterator + +import pytest + +EDU = Path(__file__).resolve().parent.parent +REPO = EDU.parent +APP_ROOT = Path(tempfile.mkdtemp(prefix="lmnsquid-edu-app-")) + +spec = importlib.util.spec_from_file_location("build_app", EDU / "build_app.py") +assert spec and spec.loader +build_app = importlib.util.module_from_spec(spec) +spec.loader.exec_module(build_app) +build_app.build(REPO, APP_ROOT) +sys.path.insert(0, str(APP_ROOT / "app")) + +from lmnsquid_edu import auth, server, settings as settings_mod # noqa: E402 +from lmn_squid.activity_scope import CACHE # noqa: E402 +from lmn_squid.connections import ConnectionStore # noqa: E402 + +TOKENS = { + # token -> (user, the session's LDAP groups as edulution's auth/verify names them) + "tok-global": ("global-admin", {"role-globaladministrator", "SCHOOLS"}), + "tok-pgm": ("pgmadmin", {"role-schooladministrator", "default-school"}), + "tok-lehr01": ("dslehr01", {"role-teacher", "teachers", "5a"}), + "tok-lehr02": ("dslehr02", {"role-teacher", "teachers"}), + "tok-student": ("dstest01", {"role-student", "students", "5a"}), + "tok-extra": ("dsextra01", {"role-student", "students", "6b"}), +} +USERS = { + "global-admin": {"sophomorixRole": "globaladministrator", "sophomorixSchoolname": "global"}, + "pgmadmin": {"sophomorixRole": "schooladministrator", "sophomorixSchoolname": "default-school"}, + "dslehr01": {"sophomorixRole": "teacher", "schoolclasses": ["5a"], "projects": ["p_robotik"]}, + "dslehr02": {"sophomorixRole": "teacher", "schoolclasses": []}, + "dstest01": {"sophomorixRole": "student", "schoolclasses": ["5a"]}, + "s5a2": {"sophomorixRole": "student", "schoolclasses": ["5a"]}, + "dsextra01": {"sophomorixRole": "student", "schoolclasses": ["6b"]}, + "s7c1": {"sophomorixRole": "student", "schoolclasses": ["7c"]}, + "otherlehr": {"sophomorixRole": "teacher", "schoolclasses": ["5a"]}, + "fremd1": { + "sophomorixRole": "student", + "sophomorixSchoolname": "other", + "schoolclasses": ["5a"], + }, +} + + +class FakeDirectory: + """The AD with the shapes LdapsDirectory hands over (lists like ldap3 returns them).""" + + def __init__(self) -> None: + self.calls: list[str] = [] + + def _entry(self, name: str) -> dict[str, Any]: + u = USERS[name] + return { + "sAMAccountName": [name], + "sophomorixRole": [u["sophomorixRole"]], + "sophomorixSchoolname": [u.get("sophomorixSchoolname", "default-school")], + "displayName": [f"Person {name}"], + "schoolclasses": list(u.get("schoolclasses", [])), + "projects": list(u.get("projects", [])), + } + + def person(self, name: str) -> dict[str, Any] | None: + self.calls.append(f"person {name}") + return self._entry(name) if name in USERS else None + + def school_users(self, school: str) -> list[dict[str, Any]]: + self.calls.append(f"school {school}") + return [ + self._entry(n) + for n, u in USERS.items() + if u.get("sophomorixSchoolname", "default-school") == school + ] + + def project_groups(self, school: str, project: str) -> list[str]: + return ["7c"] if project == "p_robotik" else [] + + def schools(self) -> list[str]: + return ["default-school", "other"] + + def server_fqdn(self) -> str: + return "server.dev.lmschule.de" + + def count_users(self, school: str) -> int: + return len(self.school_users(school)) + + +class Probe: + """edulution's auth/verify as the plugin sees it; counts calls.""" + + def __init__(self) -> None: + self.calls = 0 + + def __call__(self, token: str) -> tuple[str, set[str]] | None: + self.calls += 1 + return TOKENS.get(token) + + +class Client: + """A browser-like client of the plugin, as Traefik would forward its requests.""" + + ORIGIN = "https://edu.example" + + def __init__(self, port: int) -> None: + self.port = port + self.seen: list[str] = [] # every answer body, to search for secrets + + def call( + self, + method: str, + path: str, + body: Any = None, + token: str | None = "tok-global", + user: str | None = None, + headers: dict[str, str] | None = None, + cookie: bool = True, + ) -> tuple[int, Any]: + h = {"Host": "edu.example", "X-Forwarded-Proto": "https"} + if token is not None: + if user is None: + user = TOKENS.get(token, ("nobody", set()))[0] + if cookie: + h["Cookie"] = f"other=1; authToken={token}" + else: + h["Authorization"] = f"Bearer {token}" + if user is not None: + h["X-Auth-User"] = user + data = None + if method in ("POST", "PUT", "PATCH", "DELETE"): + h["Content-Type"] = "application/json" + h["Origin"] = self.ORIGIN + data = json.dumps(body if body is not None else {}).encode() + h.update(headers or {}) + conn = HTTPConnection("127.0.0.1", self.port, timeout=120) + try: + conn.request( + method, path, body=data, headers={k: v for k, v in h.items() if v is not None} + ) + res = conn.getresponse() + raw = res.read().decode("utf-8") + finally: + conn.close() + self.seen.append(raw) + try: + return res.status, json.loads(raw) if raw else None + except ValueError: + return res.status, raw + + +@pytest.fixture +def app(tmp_path: Path) -> Iterator[dict[str, Any]]: + CACHE.clear() + directory = FakeDirectory() + store = ConnectionStore(str(tmp_path / "data" / "connections.yml")) + sstore = settings_mod.SettingsStore(str(tmp_path / "data" / "settings.json")) + probe = Probe() + spawned: list[dict[str, Any]] = [] + + def spawn(kind: str, target: str, steps: Any, payload: dict[str, Any], **kw: Any) -> str: + spawned.append({"kind": kind, "target": target, "payload": dict(payload), **kw}) + return "0123456789abcdef" + + application = server.App( + store=store, + settings_store=sstore, + verify=auth.Verifier(probe), + directory_factory=lambda: directory, + job_dir=str(tmp_path / "jobs"), + spawn=spawn, + ) + handler = type("H", (server.Handler,), {"app": application}) + httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + thread = threading.Thread(target=httpd.serve_forever, daemon=True) + thread.start() + try: + yield { + "client": Client(httpd.server_address[1]), + "app": application, + "dir": directory, + "probe": probe, + "store": store, + "settings": sstore, + "spawned": spawned, + } + finally: + httpd.shutdown() + httpd.server_close() + + +def configure(sstore: settings_mod.SettingsStore, password: str = "bind-secret-0815") -> None: + sstore.update( + { + "dc_host": "10.0.0.1", + "ldap_url": "ldaps://10.0.0.1", + "base_dn": "DC=dev,DC=lmschule,DC=de", + "bind_dn": "CN=edulutionui-binduser,OU=Management,OU=GLOBAL,DC=dev,DC=lmschule,DC=de", + "password": password, + "ldap_fingerprint": "ab" * 32, + } + ) + + +# ------------------------------------------------------------- a real control plane +def make_cert(directory: Path, cn: str = "proxy.example") -> tuple[Path, Path]: + directory.mkdir(parents=True, exist_ok=True) + key, crt = directory / "api.key", directory / "api.crt" + subprocess.run( + ["openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", + "-nodes", "-days", "30", "-subj", f"/CN={cn}", "-keyout", str(key), "-out", str(crt)], + check=True, capture_output=True, + ) # fmt: skip + key.chmod(0o600) + return crt, key + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return int(s.getsockname()[1]) + + +@contextmanager +def control_plane(tmp_path: Path, token: str) -> Iterator[dict[str, Any]]: + """The lmnsquid control plane (fake Docker) on its TLS listener, 127.0.0.1.""" + import uvicorn + + from lmnsquid.api import create_app + from lmnsquid.config import Settings + from lmnsquid.reconciler import Reconciler + from lmnsquid.store import Store + from lmnsquid.updater import Updater + + cspec = importlib.util.spec_from_file_location( + "cp_conftest_edu", REPO / "controlplane" / "tests" / "conftest.py" + ) + assert cspec and cspec.loader + cp = importlib.util.module_from_spec(cspec) + cspec.loader.exec_module(cp) + crt, key = make_cert(tmp_path / "tls") + settings = Settings( + api_token=token, + 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", + activity_dir=str(tmp_path / "activity"), + activity_spool_dir=str(tmp_path / "spool"), + ) + store = Store(settings.instances_dir) + docker = cp.FakeDockerService( + secrets_dir=settings.secrets_dir, blocklists_dir=settings.blocklists_dir + ) + reconciler = Reconciler(store, docker) + app = create_app(settings, store, reconciler, docker, Updater(store, docker, reconciler)) + port = free_port() + + class Server(uvicorn.Server): + @contextmanager + def capture_signals(self) -> Iterator[None]: + yield + + srv = Server( + uvicorn.Config( + app, host="127.0.0.1", port=port, ssl_certfile=str(crt), ssl_keyfile=str(key), + lifespan="off", log_level="warning", + ) + ) # fmt: skip + thread = threading.Thread(target=srv.run, daemon=True) + thread.start() + for _ in range(200): + if srv.started: + break + time.sleep(0.02) + assert srv.started + der = ssl.PEM_cert_to_DER_cert(crt.read_text()) + try: + yield { + "url": f"https://127.0.0.1:{port}", + "fingerprint": hashlib.sha256(der).hexdigest(), + "docker": docker, + "store": store, + "settings": settings, + } + finally: + srv.should_exit = True + thread.join(10) + + +needs_openssl = pytest.mark.skipif(shutil.which("openssl") is None, reason="openssl missing") diff --git a/edulution/tests/test_cli.py b/edulution/tests/test_cli.py new file mode 100644 index 0000000..7469d1a --- /dev/null +++ b/edulution/tests/test_cli.py @@ -0,0 +1,285 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The host command linuxmuster-squid-edulution: register/unregister against an edu-api stand-in +(HTTPS, the endpoints and bodies of edulution 2.3.117), up/down/doctor with a docker stub.""" + +from __future__ import annotations + +import base64 +import importlib.util +import json +import os +import ssl +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Iterator + +import pytest +from conftest import EDU, make_cert, needs_openssl + +HOST = EDU / "host" + + +def load_cli(tmp_path: Path) -> Any: + os.environ["LMNSQUID_EDU_SHARE"] = str(HOST) + os.environ["LMNSQUID_EDU_CONF"] = str(tmp_path / "etc" / "plugin.conf") + os.environ["LMNSQUID_EDU_STATE"] = str(tmp_path / "state") + spec = importlib.util.spec_from_file_location("cli", HOST / "linuxmuster_squid_edulution.py") + assert spec and spec.loader + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +GROUPS = { + name: {"id": f"id-{name}", "name": name, "path": f"/{name}", "subGroupCount": 0, + "subGroups": [], "attributes": {}, "realmRoles": [], "clientRoles": {}, "access": {}} + for name in ("role-globaladministrator", "role-schooladministrator", "role-teacher", + "role-student") +} # fmt: skip + + +class FakeEdu: + def __init__(self, tmp: Path) -> None: + self.apps: dict[str, dict[str, Any]] = { + "dashboard": {"name": "dashboard", "appType": "native", "accessGroups": []} + } + self.calls: list[tuple[str, str]] = [] + crt, key = make_cert(tmp / "edu", cn="edu.example") + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(str(crt), str(key)) + fake = self + + class H(BaseHTTPRequestHandler): + def log_message(self, *a: Any) -> None: + pass + + def _send( + self, status: int, data: Any = None, headers: dict[str, str] | None = None + ) -> None: + raw = json.dumps(data).encode() if data is not None else b"" + self.send_response(status) + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + def _body(self) -> Any: + n = int(self.headers.get("Content-Length") or 0) + return json.loads(self.rfile.read(n)) if n else None + + def handle_one(self) -> None: + path = self.path + fake.calls.append((self.command, path.split("?")[0])) + authed = self.headers.get("Authorization") == "Bearer admin-token" + if path == "/edu-api/health/version": + return self._send(200, {"version": "2.3.117"}) + if self.command == "POST" and path == "/edu-api/auth": + b = self._body() + ok = ( + b["username"] == "global-admin" + and base64.b64decode(b["password"]) == b"Muster!" + ) + return ( + self._send(201, {"access_token": "admin-token"}) + if ok + else self._send(401, {"message": "Unauthorized"}) + ) + if path.startswith("/plugin/lmn-squid/"): + return self._send(200 if authed else 401, {"user": "global-admin"}) + if not authed: + return self._send(401, {"message": "no"}) + if path.startswith("/edu-api/groups?groupName="): + name = path.split("=", 1)[1] + return self._send(200, [g for g in GROUPS.values() if name in g["name"]]) + if path == "/edu-api/appconfig": + if self.command == "GET": + return self._send(200, list(fake.apps.values())) + b = self._body() + fake.apps[b["name"]] = b + return self._send(201, b) + name = path.rsplit("/", 1)[1] + if self.command == "PUT": + fake.apps[name] = self._body() + return self._send(200, fake.apps[name]) + if self.command == "DELETE": + fake.apps.pop(name, None) + return self._send(200, {}) + return self._send(404) + + do_GET = do_POST = do_PUT = do_DELETE = handle_one + + self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), H) + self.httpd.socket = ctx.wrap_socket(self.httpd.socket, server_side=True) + self.url = f"https://127.0.0.1:{self.httpd.server_address[1]}" + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + + +@pytest.fixture +def edu(tmp_path: Path) -> Iterator[FakeEdu]: + fake = FakeEdu(tmp_path) + yield fake + fake.httpd.shutdown() + + +def run(cli: Any, monkeypatch: pytest.MonkeyPatch, *argv: str, password: str = "Muster!\n") -> int: + import io + + monkeypatch.setattr("sys.stdin", io.StringIO(password)) + return int(cli.main(list(argv))) + + +@needs_openssl +def test_register_is_idempotent_and_keeps_admin_changes( + tmp_path: Path, edu: FakeEdu, monkeypatch: pytest.MonkeyPatch +) -> None: + cli = load_cli(tmp_path) + args = [ + "--user", + "global-admin", + "--password-stdin", + "--base-domain", + "edu.example", + "--url", + edu.url, + ] + assert run(cli, monkeypatch, "register", *args) == 0 + assert [c for c in edu.calls if c[1] == "/edu-api/appconfig" and c[0] == "POST"] == [ + ("POST", "/edu-api/appconfig") + ] * 2 + app = edu.apps["squidproxy"] + assert app["appType"] == "frame" + assert app["options"]["url"] == "https://edu.example/plugin/lmn-squid/manage/" + assert [g["name"] for g in app["accessGroups"]] == ["role-globaladministrator"] + assert app["accessGroups"][0]["value"] == "id-role-globaladministrator" + use = edu.apps["internetnutzung"] + assert sorted(g["name"] for g in use["accessGroups"]) == [ + "role-globaladministrator", "role-schooladministrator", "role-teacher", + ] # fmt: skip + assert use["icon"].startswith("data:image/svg+xml,") + edu.apps["squidproxy"]["position"] = 3 # an admin moved the tile + edu.calls.clear() + assert run(cli, monkeypatch, "register", *args) == 0 + assert ("POST", "/edu-api/appconfig") not in edu.calls + assert edu.calls.count(("PUT", "/edu-api/appconfig/squidproxy")) == 1 + assert edu.apps["squidproxy"]["position"] == 3 + assert (tmp_path / "state" / "registered").read_text().split() == [ + "squidproxy", + "internetnutzung", + ] + # a wrong password changes nothing + assert run(cli, monkeypatch, "register", *args, password="falsch\n") == 1 + assert run(cli, monkeypatch, "unregister", *args) == 0 + assert set(edu.apps) == {"dashboard"} + assert run(cli, monkeypatch, "unregister", *args) == 0 # again: nothing to do + + +def docker_stub(tmp: Path, image_present: bool, inspect: dict[str, Any] | None = None) -> Path: + bindir = tmp / "bin" + bindir.mkdir(exist_ok=True) + log = tmp / "docker.log" + info = json.dumps([inspect]) if inspect else "" + (tmp / "inspect.json").write_text(info) + (bindir / "docker").write_text( + f'#!/bin/sh\necho "$*" >> {log}\n' + 'case "$1" in\n' + f" image) {'exit 0' if image_present else 'exit 1'} ;;\n" + " network) exit 0 ;;\n" + f" inspect) [ -s {tmp / 'inspect.json'} ] && cat {tmp / 'inspect.json'} && exit 0; exit 1 ;;\n" + "esac\nexit 0\n" + ) + (bindir / "docker").chmod(0o755) + (bindir / "ip").write_text( + "#!/bin/sh\necho '1.1.1.1 via 10.0.0.254 dev eth0 src 10.0.0.20 uid 0'\n" + ) + (bindir / "ip").chmod(0o755) + return log + + +def edulution_dir(tmp: Path) -> Path: + edudir = tmp / "edulution-ui" + cfg = edudir / "data" / "traefik" / "config" + cfg.mkdir(parents=True) + (edudir / "docker-compose.yml").write_text("services: {}\n") + (edudir / "edulution.env").write_text("EDULUTION_BASE_DOMAIN=edu.example\n") + (cfg / "edulution-keycloak-auth.yml").write_text("# version: v1.0\nhttp: {}\n") + return edudir + + +def test_up_and_down(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + cli = load_cli(tmp_path) + edudir = edulution_dir(tmp_path) + project = tmp_path / "project" + (tmp_path / "etc").mkdir() + (tmp_path / "etc" / "plugin.conf").write_text( + f"EDULUTION_DIR={edudir}\nPROJECT_DIR={project}\n" + ) + route = edudir / "data" / "traefik" / "config" / "plugin-lmn-squid.yml" + log = docker_stub(tmp_path, image_present=False) + monkeypatch.setenv("PATH", f"{tmp_path / 'bin'}:/usr/bin:/bin") + # no image loaded: nothing started, no route (Traefik would route to nothing) + assert run(cli, monkeypatch, "up", "--image", "lmn-squid-edu:test") == 2 + assert not route.exists() and "compose" not in log.read_text() + log = docker_stub(tmp_path, image_present=True) + assert run(cli, monkeypatch, "up") == 0 + assert route.read_text() == (HOST / "traefik" / "plugin-lmn-squid.yml").read_text() + env = (project / ".env").read_text() + assert ( + "LMNSQUID_EDU_IMAGE=lmn-squid-edu:test" in env and "LMNSQUID_EDU_HOST_IP=10.0.0.20" in env + ) + assert "compose -p edulution-plugin-lmn-squid" in log.read_text() + compose = (project / "docker-compose.yml").read_text() + assert "\n ports:" not in compose and "edulution-ui_default" in compose + assert run(cli, monkeypatch, "down") == 0 + assert not route.exists() and project.exists() + assert "volume rm" not in log.read_text() + assert run(cli, monkeypatch, "down", "--purge") == 0 + assert "volume rm edulution-plugin-lmn-squid-data" in log.read_text() and not project.exists() + + +@needs_openssl +def test_doctor_names_every_problem( + tmp_path: Path, + edu: FakeEdu, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + cli = load_cli(tmp_path) + edudir = edulution_dir(tmp_path) + (tmp_path / "etc").mkdir() + (tmp_path / "etc" / "plugin.conf").write_text(f"EDULUTION_DIR={edudir}\n") + base = ["--base-domain", "edu.example", "--url", edu.url] + healthy = { + "State": {"Running": True, "Status": "running", "Health": {"Status": "healthy"}}, + "Config": {"Image": "lmn-squid-edu:test"}, + "NetworkSettings": {"Networks": {"edulution-ui_default": {}}}, + "HostConfig": {"PortBindings": {}}, + } + docker_stub(tmp_path, True, healthy) + monkeypatch.setenv("PATH", f"{tmp_path / 'bin'}:/usr/bin:/bin") + # no route file yet: the route answers 401 (the stand-in), but the file is missing + assert run(cli, monkeypatch, "doctor", *base) == 1 + out = capsys.readouterr().out + assert "[FEHL] Traefik-Route" in out and "[OK ] edulution-API Version 2.3.117" in out + (edudir / "data" / "traefik" / "config" / "plugin-lmn-squid.yml").write_text("x") + assert run(cli, monkeypatch, "doctor", *base) == 0 + # a published port, a missing network, a missing middleware version line: all named + bad = dict(healthy, HostConfig={"PortBindings": {"8080/tcp": [{"HostPort": "8080"}]}}, + NetworkSettings={"Networks": {"bridge": {}}}) # fmt: skip + docker_stub(tmp_path, True, bad) + (edudir / "data" / "traefik" / "config" / "edulution-keycloak-auth.yml").write_text( + "http: {}\n" + ) + assert run(cli, monkeypatch, "doctor", *base) == 1 + out = capsys.readouterr().out + assert "veröffentlichte Ports" in out and "Netze: ['bridge']" in out and "Middleware" in out + # with a login: route 200 and the tiles (none registered: named) + docker_stub(tmp_path, True, healthy) + (edudir / "data" / "traefik" / "config" / "edulution-keycloak-auth.yml").write_text( + "# version: v1.0\n" + ) + assert run(cli, monkeypatch, "doctor", *base, "--user", "global-admin", "--password-stdin") == 1 + out = capsys.readouterr().out + assert "Route mit Anmeldung (global-admin): HTTP 200" in out and "fehlt (register)" in out diff --git a/edulution/tests/test_ldap_dc.py b/edulution/tests/test_ldap_dc.py new file mode 100644 index 0000000..ab63429 --- /dev/null +++ b/edulution/tests/test_ldap_dc.py @@ -0,0 +1,200 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""LDAPS pinning, the memberOf rules of linuxmusterTools, the DC login and the DC agent.""" + +from __future__ import annotations + +import base64 +import json +import socket +import ssl +import subprocess +import sys +import threading +import time +from pathlib import Path +from typing import Any + +import pytest +from conftest import APP_ROOT, configure, make_cert, needs_openssl + +from lmn_squid.activity_scope import DirectoryError +from lmnsquid_edu import dc, ldapdir, settings as settings_mod + +S = "OU=default-school,OU=SCHOOLS,DC=dev,DC=lmschule,DC=de" + + +def test_classes_and_projects_from_member_of_like_linuxmustertools() -> None: + member_of = [ + f"CN=5a,OU=5a,OU=Students,{S}", + f"CN=10b,OU=10b,OU=Students,{S}", + f"CN=students,OU=Students,{S}", # no '-students,' marker in default-school + f"CN=one-students,OU=Students,{S}", + f"CN=5a-parents,OU=5a,OU=Students,{S}", + f"CN=p_robotik,OU=Projects,{S}", + f"CN=teachers,OU=Teachers,{S}", + ] + assert ldapdir.projects(member_of) == ["p_robotik"] + # role groups that slip through the DN rule are dropped later by activity_scope + assert "5a" in ldapdir.schoolclasses(member_of) + assert "one-students" not in ldapdir.schoolclasses(member_of) + assert "5a-parents" not in ldapdir.schoolclasses(member_of) + + +class TlsRecorder: + """A TLS server that records what a client sends after the handshake.""" + + def __init__(self, tmp: Path) -> None: + crt, key = make_cert(tmp / "ldaps", cn="dc.example") + self.ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + self.ctx.load_cert_chain(str(crt), str(key)) + der = ssl.PEM_cert_to_DER_cert(crt.read_text()) + self.fingerprint = settings_mod.cert_fingerprint(der) + self.sock = socket.socket() + self.sock.bind(("127.0.0.1", 0)) + self.sock.listen(5) + self.port = self.sock.getsockname()[1] + self.received = b"" + threading.Thread(target=self.serve, daemon=True).start() + + def serve(self) -> None: + while True: + try: + raw, _ = self.sock.accept() + except OSError: + return + try: + with self.ctx.wrap_socket(raw, server_side=True) as tls: + tls.settimeout(2) + try: + while chunk := tls.recv(4096): + self.received += chunk + except (OSError, ssl.SSLError): + pass + except (OSError, ssl.SSLError): + pass + + +@needs_openssl +def test_ldaps_pin_mismatch_sends_no_bind(tmp_path: Path) -> None: + srv = TlsRecorder(tmp_path) + store = settings_mod.SettingsStore(str(tmp_path / "s.json")) + configure(store, password="the-bind-password") + store.update({"ldap_url": f"ldaps://127.0.0.1:{srv.port}", "ldap_fingerprint": "cd" * 32}) + directory = ldapdir.LdapsDirectory(store.load()) + with pytest.raises(DirectoryError, match="passt nicht"): + directory.person("dslehr01") + time.sleep(0.3) + # nothing but an unbind (LDAP tag 0x42): neither the bind DN nor the password + assert b"the-bind-password" not in srv.received and b"binduser" not in srv.received + assert srv.received in (b"", b"0\x05\x02\x01\x01B\x00") + # with the right pin the bind (with the password) is sent; the stub never answers it + store.update({"ldap_fingerprint": srv.fingerprint}) + with pytest.raises(DirectoryError): + ldapdir.LdapsDirectory(store.load()).person("dslehr01") + time.sleep(0.3) + assert b"the-bind-password" in srv.received + cert = ldapdir.fetch_certificate(f"ldaps://127.0.0.1:{srv.port}") + assert cert["fingerprint"] == settings_mod.colon(srv.fingerprint) + assert "dc.example" in cert["subject"] + + +def test_unconfigured_directory_says_so(tmp_path: Path) -> None: + with pytest.raises(DirectoryError, match="noch nicht eingerichtet"): + ldapdir.LdapsDirectory(settings_mod.Settings()) + + +# ------------------------------------------------------------------ DC login +def test_dc_login_needs_the_confirmed_key_and_is_used_once() -> None: + dc._HOSTKEYS["10.0.0.1"] = (time.monotonic(), {"keytype": "ssh-ed25519", "key": "AAAA", + "fingerprint": "SHA256:abc"}) # fmt: skip + body = {"user": "root", "password": "pw", "fingerprint": "SHA256:abc"} + with pytest.raises(dc.DcError) as err: + dc.login_from_body("10.0.0.1", {**body, "fingerprint": "SHA256:other"}, consume=False) + assert err.value.code == "dc_hostkey" + with pytest.raises(dc.DcError) as err: + dc.login_from_body("10.0.0.1", {**body, "user": "bad user"}, consume=False) + assert err.value.code == "dc_login" + login = dc.login_from_body("10.0.0.1", body, consume=False) # a precheck keeps it + assert login.sudo_password == "pw" and login.key == "AAAA" + dc.login_from_body("10.0.0.1", body, consume=True) + with pytest.raises(dc.DcError): + dc.login_from_body("10.0.0.1", body, consume=True) + dc._HOSTKEYS["10.0.0.1"] = (time.monotonic() - dc.HOSTKEY_TTL - 1, {"fingerprint": "x"}) + with pytest.raises(dc.DcError): + dc.login_from_body("10.0.0.1", {**body, "fingerprint": "x"}, consume=False) + + +# ------------------------------------------------------------------ DC agent +def agent( + action: str, args: dict[str, Any], tmp_path: Path, stubs: dict[str, str] +) -> dict[str, Any]: + """dc_agent.py with stubbed samba-tool/ldbsearch and site files, as a subprocess (main() + without the root check, which the stubs make unnecessary).""" + bindir = tmp_path / "bin" + bindir.mkdir(exist_ok=True) + for name, body in stubs.items(): + (bindir / name).write_text(f"#!/bin/sh\n{body}\n") + (bindir / name).chmod(0o755) + code = ( + "import sys, json; sys.path.insert(0, sys.argv[1]);" + "from lmn_squid import sitefacts, precheck, keytab;" + f"sitefacts.read_site.__defaults__=({str(tmp_path / 'setup.ini')!r},);" + f"sitefacts.schools.__defaults__=({str(tmp_path / 'conf')!r},);" + "import dc_agent; print(dc_agent.MARK + json.dumps(dc_agent.main(sys.argv[1:])))" + ) + (tmp_path / "setup.ini").write_text( + "[setup]\nserverip = 10.0.0.1\ndomainname = dev.lmschule.de\nrealm = DEV.LMSCHULE.DE\n" + "servername = server\n" + ) + (tmp_path / "conf" / "default-school").mkdir(parents=True, exist_ok=True) + encoded = base64.b64encode(json.dumps(args).encode()).decode() + res = subprocess.run( + [sys.executable, "-c", code, str(APP_ROOT / "app" / "lmnsquid_edu"), action, encoded], + capture_output=True, + text=True, + env={"PATH": f"{bindir}:/usr/bin:/bin", "PYTHONPATH": str(APP_ROOT / "app")}, + timeout=60, + ) + line = [x for x in res.stdout.splitlines() if x.startswith(dc.MARK)] + assert line, res.stdout + res.stderr + return json.loads(line[-1][len(dc.MARK) :]) + + +def test_agent_site_and_refusals(tmp_path: Path) -> None: + out = agent("site", {}, tmp_path, {}) + assert out["site"]["serverip"] == "10.0.0.1" and out["site"]["schools"] == ["default-school"] + out = agent("keytab", {"fqdn": "p.dev.lmschule.de", "account": "squid-other"}, tmp_path, {}) + assert "passt nicht" in out["error"] + out = agent("disable", {"account": "Administrator"}, tmp_path, {}) + assert out["ok"] is False + assert "unknown action" in agent("rm", {}, tmp_path, {})["error"] + + +def test_agent_refuses_a_foreign_account(tmp_path: Path) -> None: + """The same KeytabError text as on the WebUI: a foreign account is never reused.""" + show = "echo 'dn: CN=squid-p,CN=Users,DC=x'; echo 'description: something else'" + out = agent( + "keytab", + {"fqdn": "p.dev.lmschule.de", "account": "squid-p", "drop_old": False}, + tmp_path, + {"samba-tool": f'case "$2" in show) {show};; *) exit 9;; esac'}, + ) + assert "wird nicht verwendet" in out["error"] + + +def test_agent_is_root_only(tmp_path: Path) -> None: + res = subprocess.run( + [sys.executable, str(APP_ROOT / "app" / "lmnsquid_edu" / "dc_agent.py"), "site"], + capture_output=True, + text=True, + timeout=30, + ) + assert res.returncode == 1 and "nicht als root" in res.stdout + + +def test_bundle_holds_what_the_agent_imports() -> None: + names = {name for _, name in dc._bundle()} + for module in ("keytab", "precheck", "sitefacts", "runtime", "client", "connections"): + assert f"lmn_squid/{module}.py" in names + assert {"dc_agent.py", "provision-keytab.sh"} <= names diff --git a/edulution/tests/test_server.py b/edulution/tests/test_server.py new file mode 100644 index 0000000..125a912 --- /dev/null +++ b/edulution/tests/test_server.py @@ -0,0 +1,368 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The plugin's HTTP server end to end: identity, roles, CSRF, scope, secrets, and the +management routes against a real control plane.""" + +from __future__ import annotations + +import time +from pathlib import Path +from typing import Any +from zoneinfo import ZoneInfo + +import pytest +from conftest import configure, control_plane, needs_openssl + +API = "/api/lmn/squid" +ACT = "/api/lmn/squid-activity" +CP_TOKEN = "cp-token-0123456789abcdef0123456789" + + +# ------------------------------------------------------------------ identity (auth.py) +def test_without_x_auth_user_nothing_is_answered(app: dict[str, Any]) -> None: + """Reached past Traefik (no header): 401, the token alone is not enough.""" + c = app["client"] + status, data = c.call("GET", API + "/connections", token="tok-global", user="") + assert status == 401 and data["error"] == "auth" + + +def test_forged_header_without_a_matching_token_is_refused(app: dict[str, Any]) -> None: + """A container on edulution's network can send any X-Auth-User; it has no token of that + person: the plugin's own check with edu-api refuses it.""" + c = app["client"] + assert c.call("GET", API + "/connections", token=None, user="global-admin")[0] == 401 + assert c.call("GET", API + "/connections", token="forged", user="global-admin")[0] == 401 + # a student's own valid token with the global admin's name in the header + status, data = c.call("GET", API + "/connections", token="tok-student", user="global-admin") + assert status == 401 and "selben Person" in data["message"] + + +def test_root_and_odd_names_are_refused(app: dict[str, Any]) -> None: + c = app["client"] + assert c.call("GET", API + "/whoami", token="tok-global", user="root")[0] == 401 + assert c.call("GET", API + "/whoami", token="tok-global", user="a b")[0] == 401 + + +def test_token_from_bearer_header_and_cookie_and_cache(app: dict[str, Any]) -> None: + c = app["client"] + assert c.call("GET", API + "/whoami", cookie=False)[0] == 200 + assert c.call("GET", API + "/whoami")[0] == 200 + assert c.call("GET", API + "/whoami")[0] == 200 + assert app["probe"].calls == 1 # cached by the token's hash for 30 s + + +def test_url_encoded_user_header(app: dict[str, Any]) -> None: + status, data = app["client"].call("GET", API + "/whoami", user="global%2Dadmin") + assert status == 200 and data["user"] == "global-admin" + + +# ------------------------------------------------------------------ roles +@pytest.mark.parametrize("token", ["tok-pgm", "tok-lehr01", "tok-student"]) +def test_management_is_global_admins_only(app: dict[str, Any], token: str) -> None: + c = app["client"] + for method, path in ( + ("GET", "/connections"), + ("GET", "/settings"), + ("POST", "/connections"), + ("GET", "/jobs"), + ("POST", "/dc/hostkey"), + ("PUT", "/settings"), + ("GET", "/x/overview"), + ): + status, data = c.call(method, API + path, token=token) + assert status == 403 and data["error"] == "role", (method, path) + + +def test_ad_role_overrides_a_stale_session_group(app: dict[str, Any]) -> None: + """The session says global admin, the AD (configured) says teacher: refused.""" + configure(app["settings"]) + app["dir"]._entry # noqa: B018 - the fake reads USERS + import conftest + + conftest.TOKENS["tok-stale"] = ("dslehr01", {"role-globaladministrator"}) + try: + status, data = app["client"].call("GET", API + "/connections", token="tok-stale") + assert status == 403 and "laut AD" in data["message"] + finally: + del conftest.TOKENS["tok-stale"] + + +def test_whoami(app: dict[str, Any]) -> None: + c = app["client"] + status, data = c.call("GET", API + "/whoami") + assert status == 200 and data["manage"] is True and data["activity"] is False # no AD yet + configure(app["settings"]) + assert c.call("GET", API + "/whoami")[1]["activity"] is True + me = c.call("GET", API + "/whoami", token="tok-student")[1] + assert me["manage"] is False and me["activity"] is False and me["role"] == "student" + + +# ------------------------------------------------------------------ CSRF +def test_state_changing_requests_need_json_and_same_origin(app: dict[str, Any]) -> None: + c = app["client"] + body = {"name": "a", "url": "https://10.0.0.2:8443", "token": "x" * 32} + status, data = c.call( + "POST", API + "/connections", body, headers={"Content-Type": "text/plain"} + ) + assert status == 415 + status, data = c.call( + "POST", API + "/connections", body, headers={"Origin": "https://evil.example"} + ) + assert status == 403 and data["error"] == "origin" + status, data = c.call("POST", API + "/connections", body, headers={"Origin": None}) + assert status == 403 and "without Origin" in data["message"] + status, _ = c.call( + "POST", + API + "/connections", + body, + headers={"Origin": None, "Referer": "https://evil.example/x"}, + ) + assert status == 403 + # the activity view's queries are POSTs too + status, _ = c.call("POST", ACT + "/query/users", {}, headers={"Origin": "https://evil.example"}) + assert status == 403 + # same origin, the Referer alone is enough + status, _ = c.call( + "POST", API + "/connections", body, headers={"Origin": None, "Referer": c.ORIGIN + "/x"} + ) + assert status != 403 + + +def test_get_is_never_state_changing(app: dict[str, Any]) -> None: + """No route changes anything on GET (a cross-site could send one).""" + from lmn_squid import manage_core + from lmnsquid_edu import server + + assert all(name.endswith(("_get", "s", "test", "overview", "schema", "status", "logs", + "catalog", "lookup", "stats", "activity", "audit")) + for m, _, name, change in manage_core.ROUTES if m == "GET") # fmt: skip + assert all(not change for m, _, _, change in manage_core.ROUTES if m == "GET") + assert {n for m, _, n in server.EDU_ROUTES if m == "GET"} == { + "whoami", "settings_get", "site", "jobs_list", "job", + } # fmt: skip + + +# ------------------------------------------------------------------ settings and secrets +def test_settings_password_is_write_only(app: dict[str, Any]) -> None: + c = app["client"] + status, data = c.call( + "PUT", + API + "/settings", + { + "dc_host": "10.0.0.1", + "ldap_url": "ldaps://10.0.0.1", + "base_dn": "DC=dev,DC=lmschule,DC=de", + "bind_dn": "CN=x,OU=Management,OU=GLOBAL,DC=dev,DC=lmschule,DC=de", + "password": "very-secret-bind-pw", + "ldap_fingerprint": "AB:" * 31 + "AB", + }, + ) + assert status == 200 and data["password_set"] and data["configured"] + status, data = c.call("PUT", API + "/settings", {"timezone": "Europe/Berlin", "password": ""}) + assert status == 200 and data["password_set"] # empty keeps it + assert app["settings"].load().bind_password == "very-secret-bind-pw" + status, data = c.call("PUT", API + "/settings", {"ldap_url": "ldap://10.0.0.1"}) + assert status == 422 and data["field"] == "ldap_url" # never in clear + assert all("very-secret-bind-pw" not in seen for seen in c.seen) + mode = Path(app["settings"].path).stat().st_mode & 0o777 + assert mode == 0o600 + + +def test_another_ldap_server_needs_its_certificate_confirmed_again(app: dict[str, Any]) -> None: + configure(app["settings"]) + c = app["client"] + status, data = c.call("PUT", API + "/settings", {"ldap_url": "ldaps://10.0.0.9"}) + assert status == 200 and data["ldap_fingerprint"] == "" and not data["configured"] + + +def test_dc_actions_need_a_confirmed_host_key(app: dict[str, Any]) -> None: + configure(app["settings"]) + c = app["client"] + status, data = c.call( + "POST", + API + "/setup/precheck", + {"school": "default-school", "fqdn": "p.dev.lmschule.de", "ip": "10.0.0.5", + "dc": {"user": "root", "password": "pw", "fingerprint": "SHA256:x"}}, + ) # fmt: skip + assert status == 409 and data["error"] == "dc_hostkey" + status, data = c.call("POST", API + "/a/keytab", {"dc": {"user": "root", "password": "pw"}}) + assert status == 404 # no such connection, before anything else + + +def test_dc_hostkey_needs_settings(app: dict[str, Any]) -> None: + status, data = app["client"].call("POST", API + "/dc/hostkey", {}) + assert status == 409 and data["error"] == "settings" + + +# ------------------------------------------------------------------ against a real control plane +@needs_openssl +def test_management_through_the_plugin(app: dict[str, Any], tmp_path: Path) -> None: + c = app["client"] + with control_plane(tmp_path / "cp", CP_TOKEN) as cp: + status, conn = c.call( + "POST", + API + "/connections", + {"name": "lab", "url": cp["url"], "token": CP_TOKEN, "fingerprint": cp["fingerprint"], + "schools": ["default-school"], "display_name": "Lab-Proxy"}, + ) # fmt: skip + assert status == 200 and conn["token_set"] is True and "token" not in conn + status, data = c.call("GET", API + "/lab/test") + assert status == 200 and data["version"] + status, inst = c.call( + "POST", + API + "/lab/instances", + {"school": "default-school", "role": "students", "ad_group": "students", + "realm": "DEV.LMSCHULE.DE", "visible_hostname": "proxy.dev.lmschule.de", + "keytab_secret": "proxy.keytab", "image": "x/y:1"}, + ) # fmt: skip + assert status == 200, inst + name = "default-school-students" + status, data = c.call("GET", API + "/lab/overview") + assert status == 200 and [i["name"] for i in data["instances"]] == [name] + for kind in ("blocklist", "noauth", "allowlist"): + assert ( + c.call("POST", API + f"/lab/instances/{name}/{kind}", {"domain": "ex.org"})[0] + == 200 + ) + status, data = c.call("GET", API + f"/lab/instances/{name}/{kind}") + assert status == 200 and "ex.org" in str(data) + assert c.call("DELETE", API + f"/lab/instances/{name}/{kind}/ex.org")[0] == 200 + status, data = c.call( + "PUT", API + f"/lab/instances/{name}/filter", {"categories": [], "x": 1} + ) + assert status == 200, data + status, data = c.call( + "POST", + API + "/filter/bulk", + {"targets": [{"conn": "lab", "name": name}, {"conn": "nope", "name": name}], + "settings": {"categories": []}}, + ) # fmt: skip + assert status == 200 and [r["ok"] for r in data["results"]] == [True, False] + for action in ("restart", "stop", "start"): + assert c.call("POST", API + f"/lab/instances/{name}/{action}")[0] == 200 + status, data = c.call("GET", API + f"/lab/instances/{name}/logs?tail=10") + assert status == 200 and "logs" in data + assert c.call("GET", API + f"/lab/instances/{name}/logs?tail=abc")[1]["field"] == "tail" + assert c.call("POST", API + "/lab/reconcile")[0] == 200 + status, data = c.call("PUT", API + f"/lab/instances/{name}/activity", + {"enabled": True, "privacy_confirmed": True, "retention_days": 7}) # fmt: skip + assert status == 200, data + inst_def = cp["store"].get(name) + assert inst_def.activity_ack_by == "global-admin" # the checked identity, not the browser's + status, data = c.call("GET", API + "/lab/activity/audit") + assert status == 200 + # an unknown connection is 404, never another server + assert c.call("GET", API + "/other/overview")[0] == 404 + # a bad instance name never reaches the API + assert c.call("GET", API + "/lab/instances/..%2F..%2Fetc/status")[0] in (404, 422) + assert c.call("DELETE", API + f"/lab/instances/{name}", {})[0] == 200 + status, data = c.call("DELETE", API + "/connections/lab", {}) + assert status == 200 and data == {"removed": "lab"} + assert all(CP_TOKEN not in seen for seen in c.seen), "the proxy token reached the browser" + + +@needs_openssl +def test_activity_scope_for_every_role(app: dict[str, Any], tmp_path: Path) -> None: + """Scope from the AD (fake directory with linuxmusterTools' shapes) for every role; only + the users of the scope go to the proxy, which audits the read with the checked identity.""" + from lmnsquid import activity + from lmnsquid.models import Instance + + configure(app["settings"]) + c = app["client"] + with control_plane(tmp_path / "cp", CP_TOKEN) as cp: + inst = Instance( + school="default-school", role="students", ad_group="students", + realm="DEV.LMSCHULE.DE", visible_hostname="proxy.dev.lmschule.de", + keytab_secret="proxy.keytab", image="x/y:1", activity_log_enabled=True, + activity_ack_by="it", activity_ack_at="now", + ) # fmt: skip + cp["store"].put(inst) + cp["docker"].ensure_running(inst) + settings = cp["settings"] + now = int(time.time()) + spool = activity.ensure_spool(settings.activity_spool_dir, inst.name) + lines = "".join( + f"{now - 120} {u}@DEV.LMSCHULE.DE site-{u}.example 200 TCP_TUNNEL 100 -\n" + for u in ("dstest01", "s5a2", "dsextra01", "s7c1", "otherlehr") + ) + (spool / f"act-{now:010d}-it000000-000001.log").write_text(lines) + activity.collect_instance( + inst, settings.activity_dir, settings.activity_spool_dir, ZoneInfo("Europe/Berlin") + ) + assert c.call( + "POST", API + "/connections", + {"name": "lab", "url": cp["url"], "token": CP_TOKEN, "fingerprint": cp["fingerprint"], + "schools": ["default-school"]}, + )[0] == 200 # fmt: skip + span = {"since": now - 3600, "until": now + 60} + + def users(token: str, **extra: Any) -> tuple[int, Any]: + return c.call("POST", ACT + "/query/users", {**span, **extra}, token=token) + + # teacher: only students of their own classes, no projects (Kevin 2026-11-26), also + # when they are in one (dslehr01 is in p_robotik, whose member group 7c holds s7c1) + status, scope = c.call("GET", ACT + "/scope", token="tok-lehr01") + assert status == 200, scope + assert [(g["kind"], g["name"]) for g in scope["groups"]] == [("class", "5a")] + status, data = users("tok-lehr01") + assert status == 200, data + seen = {row["user"] for row in data["users"]} + assert seen == {"dstest01", "s5a2"}, seen + status, data = c.call("GET", ACT + "/group/project/p_robotik/members", token="tok-lehr01") + assert status == 404 and data["error"] == "scope" + day = time.strftime("%Y-%m-%d") + status, data = c.call( + "POST", ACT + "/query/day", {"user": "s7c1", "day": day}, token="tok-lehr01" + ) + assert status == 404 and data["error"] == "scope" + # the school administrator keeps the projects + status, scope = c.call("GET", ACT + "/scope", token="tok-pgm") + assert ("project", "p_robotik") in [(g["kind"], g["name"]) for g in scope["groups"]] + # a class the teacher is not in: 404 like a person that does not exist for them + status, data = c.call("GET", ACT + "/group/class/6b/members", token="tok-lehr01") + assert status == 404 and data["error"] == "scope" + # a teacher without classes sees nobody + status, data = users("tok-lehr02") + assert status == 200 and data["users"] == [] + # school administrator: the school (other schools never) + status, data = users("tok-pgm", show_teachers=True) + assert status == 200 + seen = {row["user"] for row in data["users"]} + assert {"dstest01", "dsextra01", "s7c1", "otherlehr"} <= seen and "fremd1" not in seen + # students: 403 before anything is asked + for token in ("tok-student", "tok-extra"): + status, data = c.call("GET", ACT + "/scope", token=token) + assert status == 403 and data["error"] == "role", data + assert users(token)[0] == 403 + # the proxy audited the reads with the identity the plugin checked + audit = c.call("GET", API + "/lab/activity/audit")[1] + actors = {e.get("actor") for e in audit.get("entries", [])} + assert {"dslehr01", "pgmadmin"} <= actors and "dstest01" not in actors + assert all(CP_TOKEN not in seen for seen in c.seen) + + +def test_pages_and_static_files(app: dict[str, Any]) -> None: + """Pages are served with the CSP; nothing outside the static directory.""" + from http.client import HTTPConnection + + port = app["client"].port + + def get(path: str) -> tuple[int, dict[str, str], bytes]: + conn = HTTPConnection("127.0.0.1", port, timeout=10) + conn.request("GET", path) + res = conn.getresponse() + return res.status, dict(res.getheaders()), res.read() + + status, headers, _ = get("/healthz") + assert status == 200 + status, headers, _ = get("/static/../lmnsquid_edu/server.py") + assert status == 404 + status, headers, _ = get("/static/%2e%2e/app/lmnsquid_edu/server.py") + assert status == 404 + status, headers, _ = get("/manage") + assert status == 302 and headers["Location"] == "/manage/" + status, headers, body = get("/manage/") + if status == 200: # the pages exist once edulution/static is there + assert "script-src 'self'" in headers["Content-Security-Policy"] + assert headers["X-Content-Type-Options"] == "nosniff" diff --git a/packaging/lock-deps.sh b/packaging/lock-deps.sh index 015a8a4..8d44756 100755 --- a/packaging/lock-deps.sh +++ b/packaging/lock-deps.sh @@ -7,6 +7,7 @@ # (the shipped venv, packaging/build-venv.sh) # packaging/requirements-build.lock <- packaging/requirements-build.in (the throwaway build venv) # packaging/requirements-uv.lock <- packaging/requirements-uv.in (uv alone, the gate's resolver) +# edulution/requirements.lock <- edulution/requirements.in (the edulution plugin's image) # # bash packaging/lock-deps.sh re-resolve after an input changed; every pin that # still fits is kept (what Renovate does for a bump) @@ -50,11 +51,13 @@ export UV_DEFAULT_INDEX="$PYPI_SIMPLE" UV_PYTHON="$PYTHON" TMP="$(mktemp -d)" trap 'rm -rf "$TMP"' EXIT -LOCKS=(controlplane/requirements.lock packaging/requirements-build.lock packaging/requirements-uv.lock) +LOCKS=(controlplane/requirements.lock packaging/requirements-build.lock packaging/requirements-uv.lock + edulution/requirements.lock) TOOL_LOCK=packaging/requirements-uv.lock inputs() { case "$1" in controlplane/requirements.lock) echo controlplane/pyproject.toml packaging/requirements-venv.in ;; + edulution/requirements.lock) echo edulution/requirements.in ;; packaging/requirements-build.lock) echo packaging/requirements-build.in ;; packaging/requirements-uv.lock) echo packaging/requirements-uv.in ;; esac diff --git a/scripts/tests/edulution_it.sh b/scripts/tests/edulution_it.sh new file mode 100755 index 0000000..6744477 --- /dev/null +++ b/scripts/tests/edulution_it.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The edulution plugin as it runs on an edulution host, in throw-away containers (ADR-024): +# - Traefik (v3, file provider) with the package's route file plugin-lmn-squid.yml verbatim and +# the forwardAuth middleware edulution-keycloak-auth as edulution 2.3.117 writes it; +# - edu-api's auth/verify as a stand-in (fixed tokens per test user, the real header contract); +# - the plugin image built from this tree, started with the package's docker-compose.yml on a +# network named edulution-ui_default, no published port; +# - an OpenLDAP stand-in of the AD over LDAPS and a real control plane (fake Docker, TLS); +# - checks of the header contract (api_checks.py) and headless Chromium over every page and +# dialog for global admin, school admin, teacher and student (browser.py). +# Needs Docker and the images traefik:v3.7.19 and lmnsquid-ajenti-it:aj2.2.16 (webui_ajenti_it.sh +# builds the latter). Argument "broken": serve a page script with an error on purpose; the run +# must then fail (the counter-check that the browser test finds real errors). +# Exit code = failed checks. LMNSQUID_IT_OUT=: screenshots of failed browser steps. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +IT="$ROOT/scripts/tests/edulution_it" +VER=$(sed -n '1s/.*(\(.*\)).*/\1/p' "$ROOT/debian/changelog") +IMG="linuxmuster-squid-edulution:it-$VER" +SUPPORT_IMG=lmnsquid-edu-it-support:1 +TRAEFIK=traefik:v3.7.19 +NET=edulution-ui_default +PROJ=edulution-plugin-lmn-squid-it +MODE="${1:-}" +WORK="$(mktemp -d)" +cleanup() { + docker rm -f lmnsquid-edu-it-traefik lmnsquid-edu-it-support >/dev/null 2>&1 || true + docker compose -p "$PROJ" -f "$ROOT/edulution/host/docker-compose.yml" --env-file "$WORK/.env" \ + down --volumes >/dev/null 2>&1 || true + docker network rm "$NET" >/dev/null 2>&1 || true + rm -rf "$WORK" +} +trap cleanup EXIT +if docker network inspect "$NET" >/dev/null 2>&1; then + echo "network $NET exists (a real edulution on this host?): refusing to run" >&2 + exit 2 +fi +docker image inspect "$TRAEFIK" >/dev/null +docker image inspect lmnsquid-ajenti-it:aj2.2.16 >/dev/null 2>&1 \ + || docker build -q -t lmnsquid-ajenti-it:aj2.2.16 "$ROOT/scripts/tests/webui_ajenti_it" >/dev/null +docker image inspect "$SUPPORT_IMG" >/dev/null 2>&1 || docker build -q -t "$SUPPORT_IMG" "$IT" >/dev/null + +# the plugin image from this tree; a placeholder package (the setup assistant is not run here) +mkdir -p "$WORK/deb" +: > "$WORK/deb/linuxmuster-squid_${VER}_amd64.deb" +if [ "$MODE" = broken ]; then + # counter-check: a page script that throws at start; browser.py must report it + mkdir "$WORK/tree" + tar -C "$ROOT" --exclude=./.venv --exclude=./.git -c . | tar -C "$WORK/tree" -x + printf '\nthrow new Error("broken on purpose (edulution_it.sh broken)");\n' >> "$WORK/tree/edulution/static/js/manage.js" + BUILD="$WORK/tree" + IMG="$IMG-broken" +else + BUILD="$ROOT" +fi +"$BUILD/edulution/build-image.sh" "$WORK/deb" "$IMG" >/dev/null + +docker network create "$NET" >/dev/null +mkdir -p "$WORK/dyn" "$WORK/shared" +cp "$ROOT/edulution/host/traefik/plugin-lmn-squid.yml" "$WORK/dyn/" +cat > "$WORK/dyn/edulution-keycloak-auth.yml" <<'YML' +# version: v1.0 +# Written by edulution-api on startup. Edits are overwritten on the next restart; +# set EDUI_INTERNAL_API_URL to change the address. + +http: + middlewares: + edulution-keycloak-auth: + forwardAuth: + address: http://edu-api:3000/edu-api/auth/verify + authResponseHeaders: + - X-Auth-User + - X-Auth-Groups +YML +docker run -d --name lmnsquid-edu-it-support --network "$NET" \ + --network-alias edu-api --network-alias ldap --network-alias cp \ + -v "$ROOT:/src:ro" -v "$IT:/it:ro" -v "$ROOT/scripts/tests/webui_bridge_systemd:/stub:ro" \ + -v "$WORK/shared:/shared" -e TZ=Europe/Berlin "$SUPPORT_IMG" sleep infinity >/dev/null +PY=/opt/linuxmuster/bin/python3 +docker exec lmnsquid-edu-it-support bash -c " + set -e + SITE=\$($PY -c 'import site; print(site.getsitepackages()[0])') + mkdir -p \"\$SITE/lmnsquid-$VER.dist-info\" + printf 'Metadata-Version: 2.1\nName: lmnsquid\nVersion: %s\n' '$VER' > \"\$SITE/lmnsquid-$VER.dist-info/METADATA\" + bash /it/slapd.sh + nohup $PY /it/fake_edu_api.py > /var/tmp/edu.log 2>&1 & + nohup $PY /it/cp_server.py > /var/tmp/cp.log 2>&1 & + for i in \$(seq 1 100); do [ -s /shared/cp.fp ] && $PY -c 'import socket; socket.create_connection((\"127.0.0.1\", 18443))' 2>/dev/null && exit 0; sleep 0.2; done + cat /var/tmp/cp.log; exit 1" +docker run -d --name lmnsquid-edu-it-traefik --network "$NET" --network-alias edu.example \ + -v "$WORK/dyn:/dyn:ro" "$TRAEFIK" \ + --entrypoints.websecure.address=:443 --providers.file.directory=/dyn \ + --providers.file.watch=true --log.level=ERROR >/dev/null +printf 'LMNSQUID_EDU_IMAGE=%s\nLMNSQUID_EDU_HOST_IP=10.0.0.20\n' "$IMG" > "$WORK/.env" +docker compose -p "$PROJ" -f "$ROOT/edulution/host/docker-compose.yml" --env-file "$WORK/.env" \ + up -d --quiet-pull >/dev/null 2>&1 +for _ in $(seq 1 60); do + [ "$(docker inspect -f '{{.State.Health.Status}}' edulution-plugin-lmn-squid 2>/dev/null)" = healthy ] && break + sleep 1 +done +FAILS=0 +# no port of the plugin is published on the host +if [ -n "$(docker port edulution-plugin-lmn-squid)" ]; then + echo "FAIL published ports: $(docker port edulution-plugin-lmn-squid)"; FAILS=$((FAILS + 1)) +else + echo "ok no port of the plugin container is published" +fi +OUT=() +if [ -n "${LMNSQUID_IT_OUT:-}" ]; then mkdir -p "$LMNSQUID_IT_OUT"; OUT=(-e "SHOTS=/shared/shots"); fi +docker exec -e LDAP_FP="$(cat "$WORK/shared/ldap.fp")" -e CP_FP="$(cat "$WORK/shared/cp.fp")" \ + lmnsquid-edu-it-support $PY /it/api_checks.py || FAILS=$((FAILS + $?)) +docker exec "${OUT[@]}" lmnsquid-edu-it-support $PY /it/browser.py \ + || FAILS=$((FAILS + $?)) +if [ -n "${LMNSQUID_IT_OUT:-}" ] && [ -d "$WORK/shared/shots" ]; then + cp -r "$WORK/shared/shots/." "$LMNSQUID_IT_OUT/" +fi +docker logs edulution-plugin-lmn-squid > "$WORK/plugin.log" 2>&1 || true +if grep -E "it-token-0123|bind-pw-0815|tok-[a-z]" "$WORK/plugin.log" >/dev/null; then + echo "FAIL a secret is in the plugin's log"; FAILS=$((FAILS + 1)) +else + echo "ok no token or password in the plugin's log ($(wc -l < "$WORK/plugin.log") lines)" +fi +echo "edulution_it: $FAILS failed check(s)" +exit "$FAILS" diff --git a/scripts/tests/edulution_it/Dockerfile b/scripts/tests/edulution_it/Dockerfile new file mode 100644 index 0000000..3a59175 --- /dev/null +++ b/scripts/tests/edulution_it/Dockerfile @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# Support container of edulution_it.sh: the browser (playwright/chromium), the control plane's +# Python (from the WebUI IT image, built by webui_ajenti_it.sh) and an OpenLDAP stand-in of the AD. +FROM lmnsquid-ajenti-it:aj2.2.16 +RUN apt-get update -qq \ + && echo "slapd slapd/no_configuration boolean true" | debconf-set-selections \ + && apt-get install -y -qq --no-install-recommends slapd ldap-utils openssl curl >/dev/null \ + && rm -rf /var/lib/apt/lists/* diff --git a/scripts/tests/edulution_it/api_checks.py b/scripts/tests/edulution_it/api_checks.py new file mode 100644 index 0000000..2bfa9d7 --- /dev/null +++ b/scripts/tests/edulution_it/api_checks.py @@ -0,0 +1,231 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""The header contract through a real Traefik and past it, then the plugin's setup over its +own API (directory settings with the pinned LDAPS certificate, a connection to the control +plane) as the browser test needs it. Exit code = failed checks.""" + +import json +import os +import ssl +import sys +import urllib.error +import urllib.request + +EDU = "https://edu.example" # Traefik +DIRECT = "http://edulution-plugin-lmn-squid:8080" # past Traefik (another container) +CTX = ssl.create_default_context() +CTX.check_hostname = False +CTX.verify_mode = ssl.CERT_NONE +FAILS: list[str] = [] + + +def call(base, method, path, token=None, body=None, headers=None): + h = {"Origin": base} if method != "GET" else {} + if token: + h["Cookie"] = f"authToken={token}" + data = None + if body is not None or method != "GET": + data = json.dumps(body or {}).encode() + h["Content-Type"] = "application/json" + h.update(headers or {}) + req = urllib.request.Request(base + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, context=CTX, timeout=60) as res: + raw = res.read() + return res.status, json.loads(raw) if raw[:1] in (b"{", b"[") else raw + except urllib.error.HTTPError as exc: + raw = exc.read() + try: + return exc.code, json.loads(raw) + except ValueError: + return exc.code, raw + + +def check(label, ok, detail=""): + print(("ok " if ok else "FAIL ") + label + ("" if ok else f": {detail}")) + if not ok: + FAILS.append(label) + + +API = "/plugin/lmn-squid/api/lmn/squid" +ACT = "/plugin/lmn-squid/api/lmn/squid-activity" + +# 1. Traefik's forwardAuth: no session, no way in (not even to the pages) +status, _ = call(EDU, "GET", "/plugin/lmn-squid/manage/") +check("Traefik: page without login is 401", status == 401, status) +status, _ = call(EDU, "GET", API + "/whoami", headers={"X-Auth-User": "global-admin"}) +check("Traefik: forged X-Auth-User without session is 401", status == 401, status) +status, data = call( + EDU, + "GET", + API + "/whoami", + token="tok-dstest01", + headers={"X-Auth-User": "global-admin"}, +) +check( + "Traefik overwrites a forged X-Auth-User with the session's user", + status == 200 and data.get("user") == "dstest01", + (status, data), +) +status, data = call( + EDU, + "GET", + API + "/connections", + token="tok-dstest01", + headers={"X-Auth-User": "global-admin"}, +) +check("student with forged header: management 403", status == 403, (status, data)) +status, _ = call(EDU, "GET", "/plugin/lmn-squid/manage/", token="tok-dslehr01") +check("Traefik: page with login is 200", status == 200, status) +status, _ = call(EDU, "GET", "/plugin/lmn-squidx/manage/", token="tok-global-admin") +check("route matches /plugin/lmn-squid/ only", status == 404, status) + +# 2. past Traefik (a container on the same network): the header alone gets nothing +status, data = call( + DIRECT, + "GET", + API[len("/plugin/lmn-squid") :] + "/whoami", + headers={"X-Auth-User": "global-admin"}, +) +check("direct: X-Auth-User without token is 401", status == 401, (status, data)) +status, data = call( + DIRECT, + "GET", + API[len("/plugin/lmn-squid") :] + "/connections", + token="tok-dstest01", + headers={"X-Auth-User": "global-admin"}, +) +check( + "direct: a student's token with the admin's name is 401", + status == 401, + (status, data), +) + +# 3. CSRF through Traefik +status, data = call( + EDU, + "PUT", + API + "/settings", + token="tok-global-admin", + body={"timezone": "Europe/Berlin"}, + headers={"Origin": "https://evil.example"}, +) +check( + "foreign Origin refused", + status == 403 and data.get("error") == "origin", + (status, data), +) +status, data = call( + EDU, + "PUT", + API + "/settings", + token="tok-global-admin", + body={"timezone": "Europe/Berlin"}, + headers={"Content-Type": "text/plain"}, +) +check("text/plain refused", status == 415, (status, data)) + +# 4. set the plugin up through its own API, like the global admin in the settings page +status, cert = call( + EDU, + "POST", + API + "/settings/ldap-cert", + token="tok-global-admin", + body={"ldap_url": "ldaps://ldap:636"}, +) +check( + "LDAPS certificate fetched", + status == 200 and cert.get("fingerprint") == os.environ["LDAP_FP"], + (status, cert), +) +status, data = call( + EDU, + "PUT", + API + "/settings", + token="tok-global-admin", + body={ + "dc_host": "10.0.0.1", + "ldap_url": "ldaps://ldap:636", + "base_dn": "DC=dev,DC=lmschule,DC=de", + "bind_dn": "CN=edulutionui-binduser,OU=Management,OU=GLOBAL,DC=dev,DC=lmschule,DC=de", + "password": "bind-pw-0815", + "ldap_fingerprint": os.environ["LDAP_FP"], + "timezone": "Europe/Berlin", + }, +) +check( + "settings saved", + status == 200 and data.get("configured") and "bind-pw" not in json.dumps(data), + (status, data), +) +status, data = call( + EDU, "POST", API + "/settings/test", token="tok-global-admin", body={} +) +check( + "directory test against LDAPS", + status == 200 and data.get("ok") and data.get("users", 0) >= 6, + (status, data), +) +status, data = call( + EDU, + "POST", + API + "/connections", + token="tok-global-admin", + body={ + "name": "lab", + "display_name": "proxygesamtschulemusterstadt.gebaeudenord.schulnetz.example", + "url": "https://cp:18443", + "token": "it-token-0123456789abcdef0123456789", + "fingerprint": os.environ["CP_FP"], + "schools": ["default-school"], + }, +) +check( + "connection to the control plane", + status == 200 and "token" not in data, + (status, data), +) +status, data = call(EDU, "GET", API + "/lab/overview", token="tok-global-admin") +check( + "overview through the pinned connection", + status == 200 and data.get("instances"), + (status, data), +) + +# 5. roles and scope through Traefik with the AD stand-in +status, data = call(EDU, "GET", API + "/connections", token="tok-pgmadmin") +check("school admin: management 403", status == 403, status) +for tok in ("tok-dstest01", "tok-dsextra01"): + status, data = call(EDU, "GET", ACT + "/scope", token=tok) + check(f"{tok}: activity 403", status == 403, (status, data)) +status, data = call(EDU, "GET", ACT + "/scope", token="tok-dslehr01") +groups = sorted(g["name"] for g in data.get("groups", [])) if status == 200 else data +check("teacher's scope: 5a and p_robotik", groups == ["5a", "p_robotik"], groups) +status, data = call(EDU, "GET", ACT + "/group/class/6b/members", token="tok-dslehr01") +check("teacher: other class is 404", status == 404, (status, data)) +import time + +now = int(time.time()) +status, data = call( + EDU, + "POST", + ACT + "/query/users", + token="tok-dslehr01", + body={"since": now - 3600, "until": now + 60}, +) +users = sorted(r["user"] for r in data.get("users", [])) if status == 200 else data +check( + "teacher sees only own students' activity", + users == ["dstest01", "s5a2", "s7c1"], + users, +) +status, data = call(EDU, "GET", API + "/lab/activity/audit", token="tok-global-admin") +actors = {e.get("actor") for e in data.get("entries", [])} if status == 200 else data +check( + "proxy audit names the checked identity", + isinstance(actors, set) and "dslehr01" in actors, + actors, +) + +print(f"api_checks: {len(FAILS)} failed") +sys.exit(len(FAILS)) diff --git a/scripts/tests/edulution_it/cp_server.py b/scripts/tests/edulution_it/cp_server.py new file mode 100644 index 0000000..04c1ff3 --- /dev/null +++ b/scripts/tests/edulution_it/cp_server.py @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""A real control plane (fake Docker) with activity data on its TLS listener 0.0.0.0:18443; +writes its certificate's SHA-256 to /shared/cp.fp.""" + +import hashlib +import importlib.util +import os +import ssl +import subprocess +import sys +import time +from pathlib import Path +from zoneinfo import ZoneInfo + +import uvicorn + +sys.path.insert(0, "/src/controlplane") +from lmnsquid import activity +from lmnsquid.api import create_app +from lmnsquid.config import Settings +from lmnsquid.models import Instance +from lmnsquid.reconciler import Reconciler +from lmnsquid.store import Store +from lmnsquid.updater import Updater + +spec = importlib.util.spec_from_file_location( + "cpt", "/src/controlplane/tests/conftest.py" +) +cpt = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cpt) + +base = "/var/tmp/cp" +os.makedirs(base, exist_ok=True) +subprocess.run( + ["openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", + "-nodes", "-days", "2", "-subj", "/CN=cp", "-keyout", f"{base}/api.key", + "-out", f"{base}/api.crt"], + check=True, capture_output=True, +) # fmt: skip +der = ssl.PEM_cert_to_DER_cert(Path(f"{base}/api.crt").read_text()) +Path("/shared/cp.fp").write_text(hashlib.sha256(der).hexdigest()) +settings = Settings( + api_token="it-token-0123456789abcdef0123456789", + instances_dir=f"{base}/instances", + secrets_dir=f"{base}/secrets", + blocklists_dir=f"{base}/blocklists", + catalog_dir=f"{base}/catalog", + activity_dir=f"{base}/activity", + activity_spool_dir=f"{base}/spool", +) +store = Store(settings.instances_dir) +docker = cpt.FakeDockerService( + secrets_dir=settings.secrets_dir, blocklists_dir=settings.blocklists_dir +) +inst = Instance( + school="default-school", role="students", ad_group="students", realm="DEV.LMSCHULE.DE", + visible_hostname="proxy.dev.lmschule.de", keytab_secret="proxy.keytab", image="x/y:1", + activity_log_enabled=True, activity_ack_by="it", activity_ack_at="now", +) # fmt: skip +store.put(inst) +docker.ensure_running(inst) +now = int(time.time()) +spool = activity.ensure_spool(settings.activity_spool_dir, inst.name) +lines = "".join( + f"{now - 120} {u}@DEV.LMSCHULE.DE site-{u}.example 200 TCP_TUNNEL 100 -\n" + for u in ("dstest01", "s5a2", "dsextra01", "s7c1", "dslehr01") +) +lines += ( + f"{now - 60} dstest01@DEV.LMSCHULE.DE lotto.example 403 TCP_DENIED 10 gambling\n" +) +(spool / f"act-{now:010d}-it000000-000001.log").write_text(lines) +activity.collect_instance( + inst, settings.activity_dir, settings.activity_spool_dir, ZoneInfo("Europe/Berlin") +) +app = create_app( + settings, + store, + Reconciler(store, docker), + docker, + Updater(store, docker, Reconciler(store, docker)), +) +uvicorn.run( + app, + host="0.0.0.0", + port=18443, + log_level="warning", + ssl_certfile=f"{base}/api.crt", + ssl_keyfile=f"{base}/api.key", +) diff --git a/scripts/tests/edulution_it/fake_edu_api.py b/scripts/tests/edulution_it/fake_edu_api.py new file mode 100644 index 0000000..75e5aa8 --- /dev/null +++ b/scripts/tests/edulution_it/fake_edu_api.py @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +"""edu-api as the plugin and Traefik's forwardAuth use it (edulution 2.3.117, lab-verified): +GET /edu-api/auth/verify with the token in `Authorization: Bearer`, the cookie `authToken` or +`?token=` answers 204 with X-Auth-User / X-Auth-Groups, else 401; GET /edu-api/health/version. +Tokens are fixed per test user (no Keycloak in the test).""" + +import json +from http.cookies import SimpleCookie +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, quote, urlsplit + +USERS = { + "tok-global-admin": ("global-admin", ["role-globaladministrator", "SCHOOLS"]), + "tok-pgmadmin": ("pgmadmin", ["role-schooladministrator", "default-school"]), + "tok-dslehr01": ("dslehr01", ["role-teacher", "teachers", "5a"]), + "tok-dslehr02": ("dslehr02", ["role-teacher", "teachers"]), + "tok-dstest01": ("dstest01", ["role-student", "students", "5a"]), + "tok-dsextra01": ("dsextra01", ["role-student", "students", "6b"]), +} + + +class H(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_GET(self): + parts = urlsplit(self.path) + if parts.path == "/edu-api/health/version": + body = json.dumps({"version": "2.3.117"}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if parts.path != "/edu-api/auth/verify": + self.send_response(404) + self.send_header("Content-Length", "0") + self.end_headers() + return + token = "" + auth = self.headers.get("Authorization") or "" + if auth.startswith("Bearer "): + token = auth[7:] + if not token: + jar = SimpleCookie(self.headers.get("Cookie") or "") + token = jar["authToken"].value if "authToken" in jar else "" + if not token: + token = (parse_qs(parts.query).get("token") or [""])[0] + found = USERS.get(token) + if not found: + self.send_response(401) + self.send_header("Content-Length", "0") + self.end_headers() + return + self.send_response(204) + self.send_header("X-Auth-User", quote(found[0])) + self.send_header("X-Auth-Groups", ",".join(quote(g) for g in found[1])) + self.end_headers() + + +ThreadingHTTPServer(("0.0.0.0", 3000), H).serve_forever() diff --git a/scripts/tests/edulution_it/slapd.sh b/scripts/tests/edulution_it/slapd.sh new file mode 100755 index 0000000..fbcb57d --- /dev/null +++ b/scripts/tests/edulution_it/slapd.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# SPDX-FileCopyrightText: Kevin Stenzel +# SPDX-License-Identifier: GPL-3.0-or-later +# +# OpenLDAP stand-in of the AD for edulution_it.sh: the sophomorix attributes the plugin's scope +# reads (schema of webui_bridge_systemd), LDAPS on 636 with a self-signed certificate (its +# SHA-256 in /shared/ldap.fp), a read-only bind account like edulution's own. +set -euo pipefail +D=/var/tmp/slapd +B="DC=dev,DC=lmschule,DC=de" +S="OU=default-school,OU=SCHOOLS,$B" +mkdir -p "$D/db" +openssl req -x509 -newkey rsa:2048 -nodes -days 2 -subj "/CN=ldap" -keyout "$D/key.pem" -out "$D/cert.pem" 2>/dev/null +openssl x509 -in "$D/cert.pem" -noout -fingerprint -sha256 | sed 's/.*=//' > /shared/ldap.fp +chown -R openldap:openldap "$D" +cat > "$D/slapd.conf" < [memberOf groups..] + local cn=$1 ou=$2 role=$3 school=$4; shift 4 + printf 'dn: CN=%s,%s\nobjectClass: user\ncn: %s\nsAMAccountName: %s\nsophomorixRole: %s\nsophomorixSchoolname: %s\ndisplayName: Person %s\n' \ + "$cn" "$ou" "$cn" "$cn" "$role" "$school" "$cn" + for g in "$@"; do + case "$g" in p_*) echo "memberOf: CN=$g,OU=Projects,$S" ;; *) cls "$g" ;; esac + done + echo +} +ou() { printf 'dn: %s\nobjectClass: organizationalUnit\nou: %s\n\n' "$1" "$2"; } +{ + printf 'dn: %s\nobjectClass: organization\nobjectClass: dcObject\no: dev\ndc: dev\n\n' "$B" + ou "OU=GLOBAL,$B" GLOBAL; ou "OU=Management,OU=GLOBAL,$B" Management + ou "OU=SCHOOLS,$B" SCHOOLS; ou "$S" default-school + ou "OU=Management,$S" Management; ou "OU=Teachers,$S" Teachers; ou "OU=Students,$S" Students + ou "OU=Projects,$S" Projects + for c in 5a 6b 7c; do ou "OU=$c,OU=Students,$S" "$c"; done + printf 'dn: CN=edulutionui-binduser,OU=Management,OU=GLOBAL,%s\nobjectClass: user\nobjectClass: simpleSecurityObject\ncn: edulutionui-binduser\nuserPassword: bind-pw-0815\n\n' "$B" + person global-admin "OU=Management,OU=GLOBAL,$B" globaladministrator global + person pgmadmin "OU=Management,$S" schooladministrator default-school + person dslehr01 "OU=Teachers,$S" teacher default-school 5a p_robotik + person dslehr02 "OU=Teachers,$S" teacher default-school + person dstest01 "OU=5a,OU=Students,$S" student default-school 5a + person s5a2 "OU=5a,OU=Students,$S" student default-school 5a + person dsextra01 "OU=6b,OU=Students,$S" student default-school 6b + person s7c1 "OU=7c,OU=Students,$S" student default-school 7c + printf 'dn: CN=p_robotik,OU=Projects,%s\nobjectClass: group\ncn: p_robotik\nsophomorixType: project\nsophomorixSchoolname: default-school\nsophomorixMemberGroups: 7c\n\n' "$S" +} > "$D/tree.ldif" +runuser -u openldap -- slapadd -f "$D/slapd.conf" -l "$D/tree.ldif" >/dev/null +/usr/sbin/slapd -u openldap -g openldap -f "$D/slapd.conf" -h "ldaps:///" +for _ in $(seq 1 50); do + LDAPTLS_REQCERT=never ldapsearch -LLL -H ldaps://localhost:636 -x \ + -D "CN=edulutionui-binduser,OU=Management,OU=GLOBAL,$B" -w bind-pw-0815 -b "$B" -s base dn \ + >/dev/null 2>&1 && exit 0 + sleep 0.2 +done +echo "slapd stand-in did not start" >&2 +exit 1 diff --git a/scripts/tests/run.sh b/scripts/tests/run.sh index d069a66..485bae9 100755 --- a/scripts/tests/run.sh +++ b/scripts/tests/run.sh @@ -109,6 +109,10 @@ unit(){ run_step "pytest" pytest pytest -q controlplane/tests run_step "mypy (webui)" mypy mypy --config-file webui/pyproject.toml webui/lmn_squid webui/build_plugin.py run_step "pytest (webui)" pytest pytest -q webui/tests + # the edulution plugin: apart from webui/tests (both import a package named lmn_squid) + run_step "mypy (edulution)" mypy mypy --config-file edulution/pyproject.toml \ + edulution/lmnsquid_edu edulution/host/linuxmuster_squid_edulution.py edulution/build_app.py + run_step "pytest (edulution)" pytest pytest -q edulution/tests else skip "unit" "no control-plane code yet" fi From 436d8f3bfbf2e48ffea0258e9dfca6a9fe30c4da Mon Sep 17 00:00:00 2001 From: Kevin Stenzel Date: Thu, 26 Nov 2026 11:26:47 +0100 Subject: [PATCH 04/30] feat(edulution): pages Squid-Proxy and Internetnutzung in edulution's look A plain ES2020 port of the WebUI plugin's two pages (no build step, no npm, no external resources; CSP script-src 'self', DOM built with textContent only), German, usable at 1366x768 with scrollable dialogs: connections, setup assistant and keytab with a DC login per action, instances with every tab, filter, lists, logs, bulk and per-school filter, own lists, internet use settings and access log, the directory settings; the student-centred activity view. Error codes of the DC actions renamed to the ones the pages show (dc, dc_auth, dc_unreachable, ldap). --- edulution/lmnsquid_edu/dc.py | 16 +- edulution/lmnsquid_edu/server.py | 6 +- edulution/static/activity.html | 19 + edulution/static/css/app.css | 856 +++++++++++++++++++ edulution/static/js/activity.js | 1082 ++++++++++++++++++++++++ edulution/static/js/api.js | 95 +++ edulution/static/js/detail.js | 1102 +++++++++++++++++++++++++ edulution/static/js/dom.js | 275 +++++++ edulution/static/js/fmt.js | 118 +++ edulution/static/js/manage-core.js | 275 +++++++ edulution/static/js/manage.js | 1218 ++++++++++++++++++++++++++++ edulution/static/js/setup.js | 649 +++++++++++++++ edulution/static/manage.html | 19 + edulution/tests/test_ldap_dc.py | 2 +- 14 files changed, 5720 insertions(+), 12 deletions(-) create mode 100644 edulution/static/activity.html create mode 100644 edulution/static/css/app.css create mode 100644 edulution/static/js/activity.js create mode 100644 edulution/static/js/api.js create mode 100644 edulution/static/js/detail.js create mode 100644 edulution/static/js/dom.js create mode 100644 edulution/static/js/fmt.js create mode 100644 edulution/static/js/manage-core.js create mode 100644 edulution/static/js/manage.js create mode 100644 edulution/static/js/setup.js create mode 100644 edulution/static/manage.html diff --git a/edulution/lmnsquid_edu/dc.py b/edulution/lmnsquid_edu/dc.py index 6d5e903..38597c1 100644 --- a/edulution/lmnsquid_edu/dc.py +++ b/edulution/lmnsquid_edu/dc.py @@ -99,7 +99,7 @@ def login_from_body(host: str, data: Any, consume: bool) -> DcLogin: user = str(data.get("user") or "") password = str(data.get("password") or "") if not sshsetup.USER_RE.match(user) or not password: - raise DcError("dc_login", "SSH-Benutzer und Passwort des Schulservers nötig") + raise DcError("dc_auth", "SSH-Benutzer und Passwort des Schulservers nötig") if consume: _HOSTKEYS.pop(host, None) return DcLogin( @@ -134,17 +134,17 @@ def run_agent( try: client = connect_fn(login.host, login.user, login.password, login.keytype, login.key) except Exception as exc: # noqa: BLE001 - paramiko raises many types; name it - raise DcError("dc_login", f"SSH-Anmeldung am Schulserver: {type(exc).__name__}: {exc}") + raise DcError("dc_auth", f"SSH-Anmeldung am Schulserver: {type(exc).__name__}: {exc}") remote = sshsetup.Remote(client, login.user, login.sudo_password) made: list[str] = [] # the upload directory, once it exists try: return _agent(remote, action, args, made) except sshsetup.StepFailed as exc: - raise DcError("dc_agent", f"Schulserver: {exc.detail}") from None + raise DcError("dc", f"Schulserver: {exc.detail}") from None except DcError: raise except Exception as exc: # noqa: BLE001 - a dropped session and the like: named - raise DcError("dc_agent", f"Schulserver: {type(exc).__name__}: {exc}") from None + raise DcError("dc", f"Schulserver: {type(exc).__name__}: {exc}") from None finally: try: for tmp in made: @@ -158,7 +158,7 @@ def run_agent( def _agent(remote: Any, action: str, args: dict[str, Any], made: list[str]) -> dict[str, Any]: tmp = remote.must("dc", "mktemp -d /tmp/lmn-squid-dc.XXXXXXXX", root=False).strip() if not re.match(r"^/tmp/lmn-squid-dc\.[A-Za-z0-9]{8}$", tmp): - raise DcError("dc_agent", f"unerwartetes Temp-Verzeichnis {tmp!r}") + raise DcError("dc", f"unerwartetes Temp-Verzeichnis {tmp!r}") made.append(tmp) remote.must("dc", f"mkdir -p {shlex.quote(tmp)}/lmn_squid && : > " f"{shlex.quote(tmp)}/lmn_squid/__init__.py", root=False) # fmt: skip @@ -175,13 +175,13 @@ def _agent(remote: Any, action: str, args: dict[str, Any], made: list[str]) -> d try: status, out = remote.run(script, timeout=AGENT_TIMEOUT) except sshsetup.StepFailed as exc: - raise DcError("dc_agent", f"Schulserver: {exc.detail}") from None + raise DcError("dc", f"Schulserver: {exc.detail}") from None lines = [line for line in out.splitlines() if line.startswith(MARK)] if not lines: tail = out.strip()[-600:] if status != 0 and ("incorrect password" in tail or "Sorry, try again" in tail): - raise DcError("dc_login", "sudo-Passwort am Schulserver falsch") - raise DcError("dc_agent", f"Schulserver: keine Antwort (Exit {status}) {tail}") + raise DcError("dc_auth", "sudo-Passwort am Schulserver falsch") + raise DcError("dc", f"Schulserver: keine Antwort (Exit {status}) {tail}") answer: dict[str, Any] = json.loads(lines[-1][len(MARK) :]) return answer diff --git a/edulution/lmnsquid_edu/server.py b/edulution/lmnsquid_edu/server.py index 84bbb0e..5b24178 100644 --- a/edulution/lmnsquid_edu/server.py +++ b/edulution/lmnsquid_edu/server.py @@ -263,7 +263,7 @@ def settings_cert(self, caller: auth.Caller, query: Any, body: dict[str, Any]) - try: return fetch_certificate(url) except OSError as exc: - raise _deny(502, "unreachable", f"{url}: {type(exc).__name__}: {exc}") from None + raise _deny(502, "ldap", f"{url}: {type(exc).__name__}: {exc}") from None def settings_test(self, caller: auth.Caller, query: Any, body: Any) -> Any: directory = self.directory_factory() @@ -296,7 +296,7 @@ def dc_hostkey(self, caller: auth.Caller, query: Any, body: Any) -> Any: try: scanned = dc.scan(host) except Exception as exc: # noqa: BLE001 - socket and paramiko errors alike - raise _deny(502, "unreachable", f"{host}:22 – {type(exc).__name__}: {exc}") from None + raise _deny(502, "dc_unreachable", f"{host}:22 – {type(exc).__name__}: {exc}") from None logger.info( "user=%s dc hostkey host=%s fp=%s", caller.user, @@ -339,7 +339,7 @@ def _precheck_args(self, body: dict[str, Any]) -> dict[str, Any]: def _dc_precheck(self, login: dc.DcLogin, body: dict[str, Any]) -> dict[str, Any]: answer = dc.run_agent(login, "precheck", self._precheck_args(body)) if answer.get("error"): - raise dc.DcError("dc_agent", f"Schulserver: {answer['error']}") + raise dc.DcError("dc", f"Schulserver: {answer['error']}") return answer def setup_precheck(self, caller: auth.Caller, query: Any, body: dict[str, Any]) -> Any: diff --git a/edulution/static/activity.html b/edulution/static/activity.html new file mode 100644 index 0000000..34069dc --- /dev/null +++ b/edulution/static/activity.html @@ -0,0 +1,19 @@ + + + + + + + + Internetnutzung + + + + + +
+ + diff --git a/edulution/static/css/app.css b/edulution/static/css/app.css new file mode 100644 index 0000000..6a8f400 --- /dev/null +++ b/edulution/static/css/app.css @@ -0,0 +1,856 @@ +/* SPDX-FileCopyrightText: Kevin Stenzel */ +/* SPDX-License-Identifier: GPL-3.0-or-later */ + +/* + * Both pages of the edulution plugin, in the look of edulution's dark theme (own rules, no + * framework, no web fonts: the page runs under a strict CSP without external resources). + * Usable at 1366x768: dialogs are as high as the window at most, only their body scrolls; wide + * tables scroll sideways inside their box. + */ +:root { + --bg: rgb(0 0 0); + --panel: rgb(45 45 48); + --panel-2: rgb(26 26 26); + --panel-3: rgb(60 63 69); + --fg: rgb(255 255 255); + --muted: rgb(187 187 187); + --primary: rgb(0 129 198); + --primary-hover: rgb(0 108 166); + --green: rgb(143 192 70); + --danger: rgb(220 38 38); + --danger-light: rgb(248 113 113); + --warning: rgb(255 215 0); + --success: rgb(55 238 5); + --border: rgb(80 84 92); + --radius: 0.25rem; + color-scheme: dark; +} + +* { + box-sizing: border-box; +} + +html, body { + margin: 0; + background: var(--bg); + color: var(--fg); + font-family: Lato, "Segoe UI", system-ui, sans-serif; + font-size: 0.938rem; + line-height: 1.45; +} + +a { + color: rgb(96 186 240); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} + +code, pre { + font-family: ui-monospace, "Cascadia Mono", "DejaVu Sans Mono", monospace; + font-size: 0.85em; +} +code { + background: var(--panel-2); + padding: 0 0.25em; + border-radius: var(--radius); +} +.break { + word-break: break-all; +} + +h1 { + font-size: 1.4rem; + margin: 0; + font-weight: 700; +} +h2 { + font-size: 1.1rem; + margin: 0.5rem 0; +} +h3 { + font-size: 1rem; + margin: 1rem 0 0.5rem; +} +small, .small { + font-size: 0.85em; +} +hr { + border: 0; + border-top: 1px solid var(--border); + margin: 1rem 0; +} + +.page { + padding: 0.75rem 1rem 3rem; + max-width: 1500px; +} +.page-head { + display: flex; + align-items: baseline; + gap: 1rem; + margin-bottom: 0.75rem; +} + +.muted { color: var(--muted); } +.text-danger { color: var(--danger-light); } +.text-warning { color: var(--warning); } +.text-success { color: var(--success); } +.text-info { color: rgb(96 186 240); } +.right { text-align: right; } +.center { text-align: center; } +.nowrap { white-space: nowrap; } +.bold { font-weight: 700; } +.tight { margin: 0.1rem 0; } +.w1 { width: 1%; } +.w18 { width: 18%; } +.w30 { width: 30%; } +.w32 { width: 32%; } +.w35 { width: 35%; } + +.icon { + width: 1em; + height: 1em; + vertical-align: -0.125em; + fill: none; + stroke: currentColor; + stroke-width: 2; + stroke-linecap: round; + stroke-linejoin: round; +} + +/* ---------------------------------------------------------------- buttons */ +.btn { + display: inline-flex; + align-items: center; + gap: 0.3em; + border: 1px solid var(--border); + background: var(--panel); + color: var(--fg); + border-radius: var(--radius); + padding: 0.35rem 0.75rem; + font: inherit; + cursor: pointer; + line-height: 1.3; + white-space: nowrap; + text-decoration: none; +} +.btn:hover:not(:disabled) { + background: var(--panel-3); + text-decoration: none; +} +.btn:focus-visible, .input:focus-visible, .dropdown-item:focus-visible, .tabs button:focus-visible { + outline: 2px solid var(--primary); + outline-offset: 1px; +} +.btn:disabled { + opacity: 0.45; + cursor: not-allowed; +} +.btn-sm { + padding: 0.2rem 0.5rem; + font-size: 0.85rem; +} +.btn-primary { + background: var(--primary); + border-color: var(--primary); +} +.btn-primary:hover:not(:disabled) { + background: var(--primary-hover); +} +.btn-success { + background: var(--green); + border-color: var(--green); + color: rgb(0 0 0); +} +.btn-success:hover:not(:disabled) { + background: rgb(123 170 56); +} +.btn-danger { + background: var(--danger); + border-color: var(--danger); +} +.btn-danger:hover:not(:disabled) { + background: rgb(185 28 28); +} +.btn-flat { + background: transparent; +} +.btn.active { + background: var(--primary); + border-color: var(--primary); +} +.btn-group { + display: inline-flex; +} +.btn-group > .btn:not(:first-child) { + border-top-left-radius: 0; + border-bottom-left-radius: 0; + margin-left: -1px; +} +.btn-group > .btn:not(:last-child) { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} +.icon-btn { + border: 0; + background: transparent; + color: rgb(96 186 240); + cursor: pointer; + padding: 0 0.2rem; + font: inherit; +} +.th-sort { + border: 0; + background: transparent; + color: inherit; + font: inherit; + font-weight: 700; + cursor: pointer; + padding: 0; +} +.day-label { + min-width: 11rem; + justify-content: center; + cursor: default; +} + +/* ---------------------------------------------------------------- labels, alerts */ +.label { + display: inline-block; + padding: 0.05rem 0.45rem; + border-radius: var(--radius); + font-size: 0.8rem; + font-weight: 700; + background: var(--panel-3); + color: var(--fg); + margin: 0.05rem 0.15rem 0.05rem 0; + vertical-align: baseline; +} +.label.wrap { + white-space: normal; +} +.label.inline { + display: inline-block; +} +.label-success { background: rgb(52 120 30); } +.label-info { background: var(--primary); } +.label-warning { background: rgb(180 140 0); color: rgb(0 0 0); } +.label-danger { background: var(--danger); } +.label-default { background: var(--panel-3); } +.label-button { + border: 0; + cursor: pointer; + font: inherit; + font-size: 0.8rem; + font-weight: 700; + color: var(--fg); +} +.badge { + display: inline-block; + padding: 0 0.45rem; + border-radius: 1rem; + background: var(--panel-3); + font-size: 0.8rem; +} + +.alert { + border-radius: var(--radius); + padding: 0.6rem 0.85rem; + margin: 0.5rem 0; + border-left: 4px solid var(--border); + background: var(--panel-2); +} +.alert p { + margin: 0.25rem 0; +} +.alert ul { + margin: 0.3rem 0 0 1rem; + padding: 0; +} +.alert.compact { + padding: 0.35rem 0.75rem; +} +.alert-info { border-left-color: var(--primary); } +.alert-success { border-left-color: var(--green); } +.alert-warning { border-left-color: var(--warning); } +.alert-danger { border-left-color: var(--danger); background: rgb(48 12 12); } + +/* ---------------------------------------------------------------- forms */ +.input { + background: var(--panel-2); + color: var(--fg); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 0.35rem 0.5rem; + font: inherit; + min-width: 0; + max-width: 100%; +} +.input:disabled, .input[readonly] { + opacity: 0.6; +} +select.input { + padding-right: 1.5rem; +} +textarea.input { + width: 100%; + font-family: ui-monospace, "DejaVu Sans Mono", monospace; +} +.field .input { + width: 100%; +} +.input-narrow { width: 5.5rem !important; } +.input-narrow2 { width: 9rem; } +.input-wide { width: 22rem; } +.input-time { width: 4.5rem; } +.input-date { width: 10rem; } +.input-xs { + padding: 0 0.25rem; + font-size: 0.8rem; + max-width: 16rem; +} +.input-icon { + display: inline-flex; + align-items: center; + gap: 0.35rem; +} +.field { + margin-bottom: 0.6rem; +} +.field-label { + display: block; + font-weight: 700; + margin-bottom: 0.2rem; +} +.field.has-error .input { + border-color: var(--danger); +} +.field-check { + padding-top: 1.6rem; +} +.help { + color: var(--muted); + font-size: 0.82rem; + margin-top: 0.15rem; +} +.help.error { + color: var(--danger-light); +} +.static { + margin: 0.3rem 0; +} +.check { + display: inline-flex; + align-items: center; + gap: 0.3rem; + cursor: pointer; + margin-right: 0.6rem; +} +.check input { + accent-color: var(--primary); +} +.grid { + display: grid; + gap: 0 1rem; +} +.grid-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.grid-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } +.grid-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); } + +.toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.4rem 0.6rem; + margin: 0.5rem 0; +} +.toolbar > label { + font-weight: 700; +} +.toolbar-right { + margin-left: auto; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.4rem; +} +.detail-title { + font-size: 1.05rem; +} + +/* ---------------------------------------------------------------- tabs */ +.tabs, .pills { + display: flex; + flex-wrap: wrap; + list-style: none; + margin: 0 0 0.75rem; + padding: 0; + border-bottom: 1px solid var(--border); + gap: 0.25rem; +} +.pills { + border-bottom: 0; + margin: 0.5rem 0; +} +.tabs button, .pills button { + border: 0; + background: transparent; + color: var(--muted); + font: inherit; + padding: 0.45rem 0.85rem; + cursor: pointer; + border-bottom: 3px solid transparent; +} +.pills button { + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 0.2rem 0.7rem; +} +.tabs li.active button { + color: var(--fg); + border-bottom-color: var(--primary); +} +.pills li.active button { + color: var(--fg); + background: var(--primary); + border-color: var(--primary); +} + +/* ---------------------------------------------------------------- panels, tables */ +.panel { + background: var(--panel-2); + border: 1px solid var(--border); + border-radius: var(--radius); + margin-bottom: 0.75rem; +} +.panel-compact { + margin-bottom: 0.35rem; +} +.panel-info { + border-color: var(--primary); +} +.panel-heading { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.45rem 0.75rem; + background: var(--panel); + border-bottom: 1px solid var(--border); + border-radius: var(--radius) var(--radius) 0 0; +} +.panel-heading.clickable { + cursor: pointer; +} +.heading-main { + flex: 1 1 auto; + min-width: 0; +} +.panel-body { + padding: 0.5rem 0.75rem; +} +.table-wrap { + overflow-x: auto; +} +.table { + width: 100%; + border-collapse: collapse; +} +.table th, .table td { + padding: 0.35rem 0.6rem; + border-top: 1px solid rgb(55 58 64); + text-align: left; + vertical-align: top; +} +.table th { + font-weight: 700; + border-top: 0; +} +.table th.right, .table td.right { + text-align: right; +} +.table-hover tr:hover td { + background: rgb(36 38 42); +} +.table tr.selected td { + background: rgb(0 60 95); +} +.sticky-action { + position: sticky; + right: 0; + background: var(--panel-2); + box-shadow: -6px 0 6px -6px rgba(0, 0, 0, 0.8); +} +.scroll-area { + max-height: max(140px, calc(100vh - 400px)); + overflow-y: auto; + margin-bottom: 0.5rem; +} +.dialog .scroll-area { + max-height: max(140px, calc(100vh - 420px)); +} +pre.log { + max-height: max(160px, calc(100vh - 330px)); + overflow: auto; + white-space: pre; + background: var(--panel-2); + border: 1px solid var(--border); + padding: 0.5rem; + border-radius: var(--radius); +} +pre.step-detail { + max-height: 160px; + overflow: auto; + white-space: pre-wrap; + font-size: 0.75rem; + margin: 0; +} + +/* ---------------------------------------------------------------- filter categories */ +.cat-row { + border-bottom: 1px solid rgb(55 58 64); + padding: 0.15rem 0; +} +.cat-line { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.25rem; +} +.cat-right { + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 0.35rem; +} +.cat-info, .window-row { + margin: 0.15rem 0 0.3rem 1.4rem; +} +.window-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.25rem; +} +.sticky-save { + position: sticky; + bottom: 0; + background: var(--bg); + padding: 0.4rem 0; + z-index: 5; +} +.bar { + display: inline-block; + height: 0.8rem; + background: var(--primary); + min-width: 2px; + vertical-align: middle; +} + +/* ---------------------------------------------------------------- drop-downs */ +.dropdown { + position: relative; + display: inline-block; +} +.dropdown-menu { + position: absolute; + top: 100%; + left: 0; + z-index: 50; + min-width: 14rem; + margin: 0.2rem 0 0; + padding: 0.25rem 0; + list-style: none; + background: var(--panel); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: 0 6px 20px rgba(0, 0, 0, 0.6); +} +.dropdown-right .dropdown-menu { + left: auto; + right: 0; +} +.dropdown-menu .divider { + border-top: 1px solid var(--border); + margin: 0.25rem 0; +} +.dropdown-item { + display: block; + width: 100%; + text-align: left; + border: 0; + background: transparent; + color: var(--fg); + font: inherit; + padding: 0.35rem 0.85rem; + cursor: pointer; + white-space: nowrap; +} +.dropdown-item:hover { + background: var(--primary); +} +.dropdown-item.text-danger { + color: var(--danger-light); +} +.dropdown-item.text-danger:hover { + color: var(--fg); + background: var(--danger); +} + +/* ---------------------------------------------------------------- dialogs */ +.overlay { + position: fixed; + inset: 0; + z-index: 100; + background: rgba(0, 0, 0, 0.72); + display: flex; + align-items: flex-start; + justify-content: center; + padding: 20px; +} +.dialog { + display: flex; + flex-direction: column; + width: min(640px, 100%); + max-height: calc(100vh - 40px); + background: var(--panel-2); + border: 1px solid var(--border); + border-radius: 0.5rem; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.8); +} +.dialog-lg { + width: min(1000px, 100%); +} +.dialog-header, .dialog-footer { + flex: 0 0 auto; + padding: 0.6rem 1rem; +} +.dialog-header { + border-bottom: 1px solid var(--border); +} +.dialog-header h2 { + margin: 0; +} +.dialog-body { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + padding: 0.75rem 1rem; +} +.dialog-footer { + border-top: 1px solid var(--border); + display: flex; + justify-content: flex-end; + align-items: center; + gap: 0.5rem; +} +.dc-block { + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 0.25rem 0.75rem 0.5rem; + margin: 0.5rem 0; + background: rgb(20 20 22); +} + +/* ---------------------------------------------------------------- toasts, spinner */ +.toasts { + position: fixed; + top: 0.75rem; + right: 0.75rem; + z-index: 200; + display: flex; + flex-direction: column; + gap: 0.4rem; + max-width: min(28rem, calc(100vw - 1.5rem)); +} +.toast { + display: flex; + align-items: flex-start; + gap: 0.5rem; + padding: 0.55rem 0.75rem; + border-radius: var(--radius); + background: var(--panel); + border-left: 4px solid var(--primary); + box-shadow: 0 6px 20px rgba(0, 0, 0, 0.6); +} +.toast-success { border-left-color: var(--green); } +.toast-warning { border-left-color: var(--warning); } +.toast-error { border-left-color: var(--danger); } +.toast span { + flex: 1 1 auto; +} +.toast-close { + border: 0; + background: transparent; + color: var(--muted); + font-size: 1.1rem; + cursor: pointer; + line-height: 1; +} +.spinner { + display: inline-block; + width: 1em; + height: 1em; + border: 2px solid var(--panel-3); + border-top-color: var(--primary); + border-radius: 50%; + animation: spin 0.8s linear infinite; + vertical-align: -0.15em; +} +@keyframes spin { + to { transform: rotate(360deg); } +} +@media (prefers-reduced-motion: reduce) { + .spinner { animation-duration: 3s; } +} + +/* ---------------------------------------------------------------- activity view */ +.typeahead { + position: relative; + max-width: 36rem; + margin: 0.5rem 0 1rem; +} +.typeahead-list { + position: absolute; + z-index: 40; + left: 0; + right: 0; + list-style: none; + margin: 0.2rem 0 0; + padding: 0.25rem 0; + background: var(--panel); + border: 1px solid var(--border); + border-radius: var(--radius); +} +.typeahead-list button { + display: block; + width: 100%; + text-align: left; + border: 0; + background: transparent; + color: var(--fg); + font: inherit; + padding: 0.35rem 0.75rem; + cursor: pointer; +} +.typeahead-list button:hover, .typeahead-list button:focus-visible { + background: var(--primary); +} +.typeahead-empty { + padding: 0.3rem 0; +} +.tiles { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(9.5rem, 1fr)); + gap: 0.6rem; + margin-bottom: 1rem; +} +.tile { + display: block; + padding: 0.65rem 0.75rem; + background: var(--panel); + border: 1px solid var(--border); + border-radius: var(--radius); + color: var(--fg); +} +.tile:hover { + border-color: var(--primary); + text-decoration: none; +} +.dot { + display: inline-block; + width: 0.65rem; + height: 0.65rem; + border-radius: 50%; + background: rgb(80 80 84); +} +.dot-on { + background: var(--success); +} +.stats { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 0.5rem; + text-align: center; + margin: 0.5rem 0 1rem; +} +.stat strong { + font-size: 1.15rem; +} +.daybar-wrap { + margin-bottom: 1rem; +} +.daybar-axis { + position: relative; + height: 1rem; + font-size: 0.72rem; + color: var(--muted); +} +.daybar-axis span { + position: absolute; +} +.daybar { + position: relative; + height: 1.6rem; + background: rgb(38 38 42); + border-radius: var(--radius); +} +.session { + position: absolute; + top: 0.2rem; + height: 1.2rem; + min-width: 3px; + background: var(--primary); + border: 0; + border-radius: 2px; + cursor: pointer; + padding: 0; +} +.session.chosen { + background: var(--green); +} +.blocked-tick { + /* drawn over the sessions, but a click goes to the session below (its title names the + blocked requests too) */ + pointer-events: none; + position: absolute; + top: 0; + height: 1.6rem; + width: 2px; + background: var(--danger); +} +.columns { + display: grid; + grid-template-columns: minmax(0, 7fr) minmax(0, 5fr); + gap: 1.5rem; +} +.heat-title { + margin-top: 1.5rem; +} +.heat { + border-collapse: separate; + border-spacing: 2px; + font-size: 0.72rem; +} +.heat-cell { + width: 1.6rem; + height: 1.1rem; + padding: 0; + border: 2px solid transparent; + border-radius: 2px; + cursor: pointer; +} +.heat-cell:disabled { + cursor: default; +} +.heat-cell.heat-blocked { + border-color: var(--danger); +} + +@media (max-width: 900px) { + .grid-3, .grid-4 { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .columns { grid-template-columns: minmax(0, 1fr); } + .stats { grid-template-columns: repeat(3, minmax(0, 1fr)); } + .input-wide { width: 100%; } +} diff --git a/edulution/static/js/activity.js b/edulution/static/js/activity.js new file mode 100644 index 0000000..58f34d9 --- /dev/null +++ b/edulution/static/js/activity.js @@ -0,0 +1,1082 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// +// "Internetnutzung" (ADR-023) in edulution: start page, class list and the student page, all on +// one page; the view comes from the query string (?group=class:5a, ?user=x&day=YYYY-MM-DD), so +// links open in a new tab and the browser's Back works. The server decides what the person may +// see; every request for activity data is audited on the proxy, so this page asks only for what +// it shows: nothing on the start page, one cheap list for a class, one day and one heat map for +// a student, details only when opened. Port of the WebUI's activity.controller.es. + +import {h, icon, spinner, mount, toast, textInput, checkbox, button, label, alert} from './dom.js'; +import {request, commonErrorText} from './api.js'; +import * as T from './fmt.js'; + +const API = '/api/lmn/squid-activity'; +const SESSION_GAP = 4 * 60; // minutes without activity that still belong to one session +const GROUP_LIVE = 60; // seconds +const USER_LIVE = 30; // the collector runs every 30 s; faster brings nothing +const LIVE_MAX = 15 * 60; // live updates end after 15 minutes +const HEAT_DAYS = 7; +const GROUP_RANGES = [['today', 'Heute'], ['hour', 'Diese Stunde'], ['lesson', 'Unterrichtszeit']]; +const DAY_PARTS = [['day', 'Ganzer Tag'], ['lesson', 'Unterrichtszeit'], ['hour', 'Diese Stunde']]; + +const S = { + loaded: false, + loadError: '', + denied: false, + busy: false, + info: {groups: [], schools: []}, + tz: 'Europe/Berlin', + page: 'start', + sel: {school: '', range: 'today', part: 'day', live: false, teachers: false, background: false, day: ''}, + failures: [], + showFailures: false, + people: {query: '', results: [], open: false}, + tiles: {filter: ''}, + group: null, + groupKey: '', + members: [], + teachersHidden: 0, + rows: [], + loadedRows: false, + anyActivity: false, + tableFilter: {text: '', activeOnly: false, blockedOnly: false}, + sort: {key: null, reverse: false}, + agg: {blocked: {open: false, rows: []}, domains: {open: false, rows: [], background: false}, search: {open: false, rows: [], domain: ''}}, + person: {}, + dayData: null, + sessions: [], + chosenSession: null, + blockedTicks: [], + axis: {ticks: []}, + domainsShown: {rows: [], other: {count: 0}}, + domainDetail: {}, + heat: [], + dateInput: {value: ''}, +}; + +const root = document.getElementById('app'); +function render() { + mount(root, page); +} + +function now() { + return Math.floor(Date.now() / 1000); +} + +function api(method, path, opts) { + return request(method, API + path, opts); +} + +// ------------------------------------------------------------------ errors +function failureKindText(kind) { + switch (kind) { + case 'unreachable': return 'nicht erreichbar'; + case 'timeout': return 'antwortet nicht rechtzeitig (5 s)'; + case 'too_old': return 'Version zu alt für diese Funktion (linuxmuster-squid aktualisieren)'; + case 'auth': return 'Token abgelehnt'; + case 'allowlist': return 'lehnt den edulution-Host ab (tls_allowed_clients)'; + case 'tls': + case 'fingerprint': return 'Zertifikat passt nicht zum gespeicherten Fingerabdruck'; + case 'too_large': return 'Antwort zu groß: einen kürzeren Zeitraum oder eine Klasse wählen'; + default: return 'Fehler'; + } +} +function limitText(code) { + return { + range_too_long: 'Zeitraum zu lang', + too_many_users: 'zu viele Personen auf einmal', + too_many_hits: 'zu viele Treffer: einen kürzeren Zeitraum oder einen längeren Domainnamen wählen', + query_too_large: 'Abfrage zu groß: einen kürzeren Zeitraum oder weniger Personen wählen', + }[code] || ''; +} +function failureText(f) { + if (f.kind === 'limit') { + return limitText(f.code) || f.message; + } + return failureKindText(f.kind) + (f.kind === 'error' && f.message ? ': ' + f.message : ''); +} +function noteFailures(list) { + S.failures = list || []; +} + +function errorText(err) { + const common = commonErrorText(err); + if (common) { + return common; + } + const data = (err && err.data) || {}; + switch (data.error) { + case 'export_incomplete': + return 'Export abgelehnt: ein Proxy-Server kann seinen Teil nicht liefern. ' + + (data.unreachable || []).map((f) => f.connection + ': ' + failureText(f)).join('; '); + case 'export_too_large': return 'Export zu groß: einen kürzeren Zeitraum oder eine Klasse wählen.'; + case 'scope': return 'Nicht in Ihren Klassen und Projekten.'; + case 'bridge': + case 'internal': return 'Interner Fehler des Plugin-Dienstes der Internetnutzung; Einzelheiten im Log des Plugin-Containers.'; + case 'rate': return 'Zu viele Anfragen in kurzer Zeit; bitte einen Moment warten.'; + case 'directory': return 'Das Benutzerverzeichnis (AD) konnte nicht gelesen werden; Einzelheiten im Log des Plugin-Containers.'; + case 'settings': return 'Die Internetnutzung ist noch nicht eingerichtet (Verzeichnis fehlt in den Einstellungen des Squid-Proxy-Plugins).'; + default: + if (data.message) { + return data.message; + } + return 'Anfrage fehlgeschlagen (' + (err && err.status) + ')'; + } +} + +function toastError(err) { + toast(errorText(err), 'error'); +} + +// A person outside the caller's classes: 404 (or 403) with error "scope" (m1); said inline. +function outOfScope(err) { + return !!err && (err.status === 403 || err.status === 404) && !!err.data && err.data.error === 'scope'; +} + +// ------------------------------------------------------------------ routing +function params() { + const out = {}; + new URLSearchParams(location.search).forEach((v, k) => { out[k] = v; }); + return out; +} + +function href(p) { + const all = Object.assign({}, p || {}); + if (S.sel.school && !all.school) { + all.school = S.sel.school; + } + const q = new URLSearchParams(); + ['school', 'group', 'user', 'day'].forEach((k) => { + if (all[k]) { + q.set(k, all[k]); + } + }); + const s = q.toString(); + return location.pathname + (s ? '?' + s : ''); +} + +function go(p) { + history.pushState(null, '', href(p)); + onRoute(); +} + +// an internal link: a real href (new tab works), a plain click stays on the page +function link(test, p, text, opts) { + const o = opts || {}; + return h('a', {href: href(p), test, class: o.class, title: o.title || '', on: {click: (e) => { + if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) { + return; + } + e.preventDefault(); + go(p); + }}}, text); +} + +function act(test, text, onClick, opts) { + const o = opts || {}; + return h('a', {href: '#', test, class: o.class, title: o.title || '', on: {click: (e) => { e.preventDefault(); onClick(); }}}, text); +} + +window.addEventListener('popstate', onRoute); + +function onRoute() { + const school = params().school || ''; + if (school !== S.sel.school) { + S.sel.school = school; + loadScope().then(applyRoute); + } else { + applyRoute(); + } +} + +// ------------------------------------------------------------------ helpers +function categoryLabel(id) { + return (S.info.category_labels || {})[id] || id; +} + +function durationText(minutes) { + if (!minutes) { + return '0 min'; + } + const hh = Math.floor(minutes / 60); + return (hh ? hh + ' h ' : '') + (minutes % 60) + ' min'; +} + +function lesson(day) { + const lh = S.info.lesson_hours || ['07:45', '16:00']; + return [T.at(day, lh[0], S.tz), T.at(day, lh[1], S.tz)]; +} + +function currentHour(day) { + const p = T.parts(now(), S.tz); + const start = T.at(day, T.two(p.h) + ':00', S.tz); + return [start, start + 3600]; +} + +// since/until of the class list's range (today in the proxies' zone) +function groupRange(id, t) { + const day = T.dayOf(t, S.tz); + if (id === 'hour') { + return [currentHour(day)[0], t + 60]; + } + if (id === 'lesson') { + const l = lesson(day); + return [l[0], Math.min(l[1], t + 60)]; + } + return [T.dayStart(day, S.tz), t + 60]; +} + +// ------------------------------------------------------------------ sessions and day bar +// minutes [[t, n, x, d], ...] (t = start of the minute, seconds) -> sessions +function buildSessions(minutes) { + const out = []; + let cur = null; + (minutes || []).forEach((m) => { + if (cur && m[0] - (cur.end - 60) <= SESSION_GAP + 60) { + cur.end = m[0] + 60; + cur.minutes += 1; + cur.requests += m[1]; + cur.blocked += m[2]; + } else { + cur = {start: m[0], end: m[0] + 60, minutes: 1, requests: m[1], blocked: m[2]}; + out.push(cur); + } + }); + return out; +} + +function layoutDay(data) { + const sessions = buildSessions(data.minutes || []); + const start = T.dayStart(S.sel.day, S.tz); + const first = sessions.length ? sessions[0].start : start + 7 * 3600; + const last = sessions.length ? sessions[sessions.length - 1].end : start + 17 * 3600; + const from = Math.min(start + 7 * 3600, first - (first - start) % 3600); + const to = Math.max(start + 17 * 3600, last + (3600 - (last - start) % 3600) % 3600); + const span = Math.max(to - from, 3600); + const pct = (t) => Math.max(0, Math.min(100, (t - from) * 100 / span)); + sessions.forEach((s) => { + s.left = pct(s.start); + s.width = Math.max(0.3, pct(s.end) - pct(s.start)); + s.title = T.time(s.start, S.tz, 'time') + '–' + T.time(s.end, S.tz, 'time') + ' · ' + s.minutes + ' min' + + (s.blocked ? ' · ' + s.blocked + ' davon gesperrt' : ''); + }); + const ticks = []; + for (let t = from; t <= to; t += 3600) { + ticks.push({left: pct(t), label: T.time(t, S.tz, 'time').substring(0, 2)}); + } + S.sessions = sessions; + S.axis = {ticks}; + S.blockedTicks = (data.minutes || []).filter((m) => m[2]).map((m) => ({left: pct(m[0]), title: T.time(m[0], S.tz, 'time') + ' · ' + m[2] + ' gesperrt'})); +} + +function refreshDomains() { + const src = S.chosenSession && S.chosenSession.data ? S.chosenSession.data : S.dayData; + const rows = ((src && src.domains) || []).filter((d) => S.sel.background || !d.background); + S.domainsShown = {rows, other: (src && src.other) || {count: 0}}; +} + +// ------------------------------------------------------------------ heat map +function heatColor(n, max) { + if (!n) { + return 'rgb(38 38 42)'; + } + const level = Math.min(1, Math.log(1 + n) / Math.log(1 + Math.max(max, 1))); + return 'hsl(201, 100%, ' + Math.round(18 + level * 42) + '%)'; +} + +function buildHeat(rows, today) { + const byHour = {}; + let max = 0; + (rows || []).forEach((r) => { + byHour[r.t] = r; + max = Math.max(max, r.requests); + }); + const out = []; + for (let d = HEAT_DAYS - 1; d >= 0; d--) { + const day = T.addDays(today, -d); + const start = T.dayStart(day, S.tz); + const cells = []; + for (let hh = 0; hh < 24; hh++) { + const t = start + hh * 3600; + const r = byHour[t] || {requests: 0, blocked: 0}; + cells.push({ + t, hour: hh, requests: r.requests, blocked: r.blocked, color: heatColor(r.requests, max), + title: hh + ':00 – ' + r.requests + ' Anfragen in dieser Stunde' + (r.blocked ? ', ' + r.blocked + ' davon gesperrt' : ''), + }); + } + out.push({day, label: T.time(start + 43200, S.tz, 'weekday').substring(0, 10), cells}); + } + return out; +} + +// ------------------------------------------------------------------ start page +let peopleTimer = null; +function findPeople() { + clearTimeout(peopleTimer); + const q = S.people.query.trim(); + if (q.length < 2) { + S.people.results = []; + S.people.open = false; + render(); + return; + } + peopleTimer = setTimeout(async () => { + try { + const data = await api('GET', '/people', {query: {q, school: S.sel.school || null}}); + if (S.people.query.trim() === q) { + S.people.results = data.people || []; + S.people.open = true; + } + } catch (err) { + S.people.results = []; + } + render(); + }, 250); +} + +function openPerson(p) { + S.people = {query: '', results: [], open: false}; + go({user: p.user}); +} + +function changeSchool() { + go({school: S.sel.school}); +} + +// ------------------------------------------------------------------ class page +function mergeRows(found, members) { + const byUser = {}; + (found || []).forEach((r) => { byUser[r.user] = r; }); + return (members || []).map((m) => { + const r = byUser[m.user] || {user: m.user, requests: 0, blocked: 0, last: 0, active_now: false}; + r.display = m.display; + r.role = m.role; + return r; + }); +} + +function rowVisible(r) { + const text = (S.tableFilter.text || '').toLowerCase(); + if (text && (r.display || '').toLowerCase().indexOf(text) < 0 && String(r.user || '').indexOf(text) < 0) { + return false; + } + if (S.tableFilter.activeOnly && !r.requests) { + return false; + } + if (S.tableFilter.blockedOnly && !r.blocked) { + return false; + } + return true; +} + +function sortBy(key) { + if (S.sort.key === key) { + S.sort.reverse = !S.sort.reverse; + } else { + S.sort.key = key; + S.sort.reverse = key !== 'display' && key !== 'user'; + } + render(); +} + +function sortedRows() { + const rows = S.rows.filter(rowVisible); + const cmp = (a, b) => (a < b ? -1 : (a > b ? 1 : 0)); + if (!S.sort.key) { + // active now first, then by name + return rows.sort((a, b) => cmp(b.active_now ? 1 : 0, a.active_now ? 1 : 0) || cmp(String(a.display || '').toLowerCase(), String(b.display || '').toLowerCase())); + } + const k = S.sort.key; + const val = (r) => (k === 'display' || k === 'user' ? String(r[k] || '').toLowerCase() : (r[k] || 0)); + rows.sort((a, b) => cmp(val(a), val(b))); + return S.sort.reverse ? rows.reverse() : rows; +} + +function groupBody() { + const r = groupRange(S.sel.range, now()); + return {since: r[0], until: r[1], school: S.sel.school || null, group: S.group, teachers: S.sel.teachers}; +} + +async function loadMembers() { + const data = await api('GET', '/group/' + encodeURIComponent(S.group.kind) + '/' + encodeURIComponent(S.group.name) + '/members', + {query: {school: S.sel.school || null, teachers: S.sel.teachers ? '1' : null}}); + S.members = data.members || []; + S.teachersHidden = data.teachers_hidden || 0; +} + +async function loadGroupRows() { + const body = groupBody(); + S.rangeText = T.time(body.since, S.tz, 'short') + ' – ' + T.time(Math.min(body.until, now()), S.tz, 'time'); + S.busy = true; + render(); + try { + const data = await api('POST', '/query/users', {body}); + S.rows = mergeRows(data.users || [], S.members); + S.anyActivity = (data.users || []).length > 0; + S.loadedRows = true; + noteFailures(data.unreachable); + } catch (err) { + toastError(err); + } + S.busy = false; + render(); +} + +async function loadAgg(kind) { + const a = S.agg[kind]; + const body = groupBody(); + if (kind === 'domains') { + body.hide_background = !a.background; + } + if (kind === 'search') { + body.domain = (a.domain || '').trim(); + if (!body.domain) { + return; + } + } + a.loading = true; + render(); + try { + const data = await api('POST', '/query/' + kind, {body}); + a.rows = (kind === 'search' ? data.users : data.domains) || []; + a.loaded = true; + noteFailures(data.unreachable); + } catch (err) { + toastError(err); + } + a.loading = false; + render(); +} + +function toggleAgg(kind) { + const a = S.agg[kind]; + a.open = !a.open; + if (a.open && !a.loaded && kind !== 'search') { + loadAgg(kind); + } + render(); +} + +function searchFor(domain) { + if (!S.groupKey) { + return; + } + S.agg.search.open = true; + S.agg.search.domain = domain; + if (S.page !== 'group') { + S.pendingSearch = domain; + go({group: S.groupKey}); + return; + } + loadAgg('search'); +} + +function setRange(id) { + S.sel.range = id; + S.agg.blocked.loaded = false; + S.agg.domains.loaded = false; + reload(); + if (S.agg.blocked.open) { + loadAgg('blocked'); + } + if (S.agg.domains.open) { + loadAgg('domains'); + } +} + +async function toggleTeachers() { + try { + await loadMembers(); + await loadGroupRows(); + } catch (err) { + toastError(err); + } +} + +// ------------------------------------------------------------------ student page +function dayBody(extra) { + const body = {user: S.person.user, day: S.sel.day, school: S.sel.school || null}; + if (S.sel.part === 'lesson') { + const l = lesson(S.sel.day); + body.start = l[0]; + body.end = l[1]; + } else if (S.sel.part === 'hour') { + const hr = S.hourStart || currentHour(S.sel.day)[0]; + body.start = hr; + body.end = hr + 3600; + } + return Object.assign(body, extra || {}); +} + +function showDay(data) { + S.dayData = data; + S.person.display = data.display; + S.person.classes = data.classes || []; + S.chosenSession = null; + layoutDay(data); + refreshDomains(); +} + +async function loadDay() { + S.dayLoading = true; + render(); + try { + const data = await api('POST', '/query/day', {body: dayBody()}); + showDay(data); + noteFailures(data.unreachable); + } catch (err) { + if (outOfScope(err)) { + S.person.denied = true; + } else { + toastError(err); + } + } + S.dayLoading = false; + render(); +} + +async function loadHeat() { + const start = T.dayStart(T.addDays(S.today, -(HEAT_DAYS - 1)), S.tz); + const body = {user: S.person.user, since: start, until: now() + 60, resolution: 'hour', school: S.sel.school || null}; + if (S.heatEtags && S.heatUser === S.person.user) { + body.etags = S.heatEtags; + } + try { + const data = await api('POST', '/query/timeline', {body}); + if (!data.not_modified) { + S.heatEtags = data.etags; + S.heatUser = S.person.user; + S.heat = buildHeat(data.rows || [], S.today); + } + } catch (err) { + if (!outOfScope(err)) { + toastError(err); + } + } + render(); +} + +// live: only the minutes from the last one on (domains and totals come whole) +function mergeLive(data) { + const since = data.minutes.length ? data.minutes[0][0] : null; + const kept = S.dayData.minutes.filter((m) => since === null || m[0] < since); + data.minutes = kept.concat(data.minutes); + showDay(data); +} + +async function liveTick() { + if (S.page !== 'user' || !S.dayData || S.dayLoading) { + return; + } + const cursor = S.dayData.cursor; + try { + const data = await api('POST', '/query/day', {body: dayBody(cursor ? {since_minute: cursor} : {})}); + if (!data.not_modified) { + if (cursor) { + mergeLive(data); + } else { + showDay(data); + } + } + } catch (err) { + // the next tick tries again + } + render(); +} + +async function openSession(s) { + if (!s) { + S.chosenSession = null; + refreshDomains(); + render(); + return; + } + S.chosenSession = s; + if (s.data) { + refreshDomains(); + render(); + return; + } + render(); + try { + s.data = await api('POST', '/query/day', {body: dayBody({start: s.start, end: s.end})}); + if (S.chosenSession === s) { + refreshDomains(); + } + } catch (err) { + toastError(err); + } + render(); +} + +async function openDomain(d) { + const start = T.dayStart(S.sel.day, S.tz); + const cat = d.category || (d.categories || [])[0]; + const detail = {domain: d.domain, first: d.first, last: d.last, label: cat ? categoryLabel(cat) : '', rows: [], loading: true}; + S.domainDetail = detail; + render(); + try { + const data = await api('POST', '/query/timeline', {body: {user: S.person.user, since: start, + until: T.dayStart(T.addDays(S.sel.day, 1), S.tz), resolution: 'minute', domain: d.domain, school: S.sel.school || null}}); + detail.rows = data.rows || []; + } catch (err) { + toastError(err); + } + detail.loading = false; + render(); +} + +function goDay(day) { + go({user: S.person.user, group: S.groupKey || null, day}); +} + +function canGoBack() { + return !S.oldest || S.sel.day > S.oldest; +} + +function setPart(id) { + S.sel.part = id; + S.hourStart = null; + S.domainDetail = {}; + loadDay(); +} + +function openHour(row, cell) { + S.hourStart = cell.t; + S.sel.part = 'hour'; + if (row.day !== S.sel.day) { + S.pendingHour = cell.t; + goDay(row.day); + } else { + loadDay(); + } +} + +// ------------------------------------------------------------------ export +async function exportCsv() { + let body; + if (S.page === 'user') { + const r = dayBody(); + // as in the WebUI: the day (or part) of the class the page came from, else the scope + body = {since: r.start || T.dayStart(S.sel.day, S.tz), until: r.end || T.dayStart(T.addDays(S.sel.day, 1), S.tz), + school: S.sel.school || null, group: S.group}; + } else { + body = groupBody(); + } + S.busy = true; + render(); + try { + const data = await api('POST', '/export', {body}); + const blob = new Blob([data.csv || ''], {type: 'text/csv;charset=utf-8'}); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = 'internetnutzung.csv'; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + setTimeout(() => URL.revokeObjectURL(a.href), 1000); + } catch (err) { + toastError(err); + } + S.busy = false; + render(); +} + +// ------------------------------------------------------------------ live updates (E4) +let live = null; +let liveSince = 0; +function stopLive() { + if (live) { + clearInterval(live); + live = null; + } +} +function toggleLive() { + stopLive(); + S.liveEnded = false; + if (S.sel.live) { + liveSince = now(); + const seconds = S.page === 'user' ? USER_LIVE : GROUP_LIVE; + live = setInterval(() => { + if (now() - liveSince > LIVE_MAX) { + stopLive(); + S.sel.live = false; + S.liveEnded = true; + render(); + return; + } + if (document.hidden || S.busy) { + return; // paused while the tab is not visible + } + if (S.page === 'user') { + liveTick(); + } else if (S.page === 'group') { + loadGroupRows(); + } + }, seconds * 1000); + } + render(); +} + +function reload() { + if (S.page === 'group') { + loadGroupRows(); + } else if (S.page === 'user') { + loadDay(); + } +} + +// ------------------------------------------------------------------ route -> page +function findGroup(key) { + const i = key.indexOf(':'); + return i < 0 ? null : {kind: key.substring(0, i), name: key.substring(i + 1)}; +} + +function applyRoute() { + if (S.denied || S.loadError) { + render(); + return; + } + const p = params(); + const previousPage = S.page; + const previousUser = S.person.user; + stopLive(); + S.sel.live = false; + S.groupKey = p.group || ''; + S.group = p.group ? findGroup(p.group) : null; + S.today = T.dayOf(now(), S.tz); + S.yesterday = T.addDays(S.today, -1); + if (p.user) { + S.page = 'user'; + S.person = {user: String(p.user).toLowerCase(), display: p.user, classes: []}; + S.sel.day = /^\d{4}-\d{2}-\d{2}$/.test(p.day || '') ? p.day : S.today; + S.dayStartT = T.dayStart(S.sel.day, S.tz); + S.dateInput.value = S.sel.day; + S.domainDetail = {}; + S.dayData = null; + if (S.pendingHour) { + S.hourStart = S.pendingHour; + S.pendingHour = null; + S.sel.part = 'hour'; + } else if (previousPage !== 'user' || previousUser !== S.person.user) { + S.sel.part = 'day'; + S.hourStart = null; + } + loadDay(); + if (previousUser !== S.person.user || !S.heat.length) { + S.heat = buildHeat([], S.today); + loadHeat(); + } + } else if (S.group) { + S.page = 'group'; + S.rows = []; + S.loadedRows = false; + S.sort = {key: null, reverse: false}; + S.agg.blocked = {open: false, rows: []}; + S.agg.domains = {open: false, rows: [], background: false}; + S.agg.search = {open: S.agg.search.open, rows: [], domain: S.agg.search.domain}; + loadMembers().then(async () => { + await loadGroupRows(); + if (S.pendingSearch) { + S.pendingSearch = null; + loadAgg('search'); + } + }, toastError); + } else { + S.page = 'start'; + noteFailures([]); + } + window.scrollTo(0, 0); + render(); +} + +async function loadScope() { + try { + const data = await api('GET', '/scope', {query: {school: S.sel.school || null}}); + S.info = data; + S.tz = data.timezone || 'Europe/Berlin'; + S.oldest = data.oldest || null; + S.loaded = true; + S.loadError = ''; + noteFailures(data.unreachable); + } catch (err) { + S.loaded = true; + const e = (err && err.data && err.data.error) || ''; + if (err.status === 403 && (e === 'scope' || e === 'role' || !e)) { + S.denied = true; // a student or another role: no further requests + } else { + S.loadError = errorText(err); + } + } + render(); +} + +// ------------------------------------------------------------------ views +function failuresLine() { + if (!S.failures.length) { + return null; + } + return h('div', {class: 'alert alert-warning compact', test: 'alert-failures'}, + icon('warn'), ' ' + S.failures.length + ' Proxy-Server lieferte(n) keine Daten für diese Ansicht. ', + act('btn-failures-toggle', 'Details', () => { S.showFailures = !S.showFailures; render(); }), + S.showFailures ? h('ul', {}, S.failures.map((f) => h('li', {}, f.connection + ': ' + failureText(f)))) : null); +} + +function startPage() { + const info = S.info; + const groups = (info.groups || []).filter((g) => { + const f = (S.tiles.filter || '').toLowerCase(); + return !f || String(g.name || '').toLowerCase().indexOf(f) >= 0; + }); + return h('div', {test: 'page-start'}, + info.is_global ? h('div', {class: 'toolbar'}, + h('label', {}, 'Schule'), + h('select', {class: 'input', test: 'sel-school', value: S.sel.school, on: {change: (e) => { S.sel.school = e.target.value; changeSchool(); }}}, + h('option', {value: ''}, '-- Schule wählen --'), (info.schools || []).map((s) => h('option', {value: s}, s)))) : null, + info.is_global && !S.sel.school ? alert('info', 'Bitte eine Schule wählen, um ihre Klassen und Schülerinnen und Schüler zu sehen.') : null, + !info.is_global || S.sel.school ? [ + h('div', {class: 'typeahead'}, + h('span', {class: 'input-icon'}, icon('search'), + textInput('in-people', S.people, 'query', {placeholder: 'Schülerin oder Schüler suchen (Name oder Anmeldename)', class: 'input-wide', onInput: findPeople, + onEnter: () => { if (S.people.results.length) { openPerson(S.people.results[0]); } }})), + S.people.open && S.people.results.length ? h('ul', {class: 'typeahead-list', test: 'list-people'}, + S.people.results.map((p) => h('li', {}, h('button', {type: 'button', test: 'people-' + p.user, on: {click: () => openPerson(p)}}, + p.display + ' (' + p.user + ')', (p.classes || []).length ? h('span', {class: 'muted'}, ' · ' + p.classes.join(', ')) : null)))) : null, + S.people.open && !S.people.results.length && S.people.query.trim().length >= 2 ? h('div', {class: 'typeahead-empty muted'}, 'Keine Treffer.') : null), + info.role === 'teacher' && !(info.groups || []).length ? alert('info', 'Sie sind in keiner Klasse und keinem Projekt mit Schülerinnen und Schülern. ', + 'Klassen treten Sie in der linuxmuster-Schulkonsole unter „Einschreiben“ bei.') : null, + (info.groups || []).length ? h('div', {}, + h('div', {class: 'toolbar'}, + h('h2', {}, info.role === 'teacher' ? 'Meine Klassen und Projekte' : 'Klassen und Projekte'), + (info.groups || []).length > 12 ? h('div', {class: 'toolbar-right'}, textInput('in-tiles-filter', S.tiles, 'filter', {placeholder: 'Klassen filtern', onInput: render})) : null), + h('div', {class: 'tiles', test: 'tiles'}, groups.map((g) => link('tile-' + g.kind + '-' + g.name, {group: g.kind + ':' + g.name}, + [h('strong', {}, (g.kind === 'project' ? '◆ ' : '') + g.name), h('br'), h('span', {class: 'muted'}, icon('users'), ' ' + g.students)], + {class: 'tile'})))) : null, + h('p', {class: 'muted'}, + info.role === 'teacher' ? 'Angezeigt werden nur Schülerinnen und Schüler Ihrer Klassen und Projekte. ' : '', + 'Jeder Abruf wird protokolliert.'), + ] : null); +} + +function sortHead(key, text, right) { + const arrow = S.sort.key === key ? (S.sort.reverse ? ' ▾' : ' ▴') : ''; + return h('th', {class: right ? 'right' : ''}, h('button', {type: 'button', class: 'th-sort', test: 'sort-' + key, on: {click: () => sortBy(key)}}, text + arrow)); +} + +function aggPanel(kind, title, body) { + const a = S.agg[kind]; + return h('div', {class: 'panel', test: 'agg-' + kind}, + h('div', {class: 'panel-heading clickable', test: 'agg-toggle-' + kind, on: {click: () => toggleAgg(kind)}}, + h('div', {class: 'heading-main'}, icon(a.open ? 'down' : 'right'), ' ' + title)), + a.open ? h('div', {class: 'panel-body'}, body()) : null); +} + +function domainCell(d, test) { + return act(test, d.domain, () => searchFor(d.domain), {title: 'Wer war auf dieser Domain?'}); +} + +function groupPage() { + const g = S.group || {}; + const rows = sortedRows(); + return h('div', {test: 'page-group'}, + h('div', {class: 'toolbar'}, + link('btn-back-overview', {}, [icon('back'), ' Übersicht'], {class: 'btn btn-default btn-sm'}), + h('strong', {class: 'detail-title'}, (g.kind === 'project' ? 'Projekt ' : 'Klasse ') + g.name), + h('span', {class: 'muted'}, '(' + S.members.length + ')'), + h('div', {class: 'toolbar-right'}, + h('div', {class: 'btn-group'}, GROUP_RANGES.map(([id, text]) => button('btn-range-' + id, text, () => setRange(id), + {small: true, class: S.sel.range === id ? 'active' : ''}))), + h('span', {title: 'Alle 60 Sekunden neu laden, solange die Seite sichtbar ist'}, + checkbox('chk-live', S.sel, 'live', 'Live', toggleLive)), + button('btn-reload', '', reload, {small: true, icon: 'sync', title: 'Neu laden'}), + S.busy ? spinner() : null, + S.info.can_export ? button('btn-export', 'CSV exportieren', exportCsv, {small: true, icon: 'csv'}) : null)), + h('p', {class: 'muted'}, S.rangeText || ''), + S.liveEnded ? h('p', {class: 'muted'}, 'Live-Aktualisierung nach 15 Minuten beendet.') : null, + h('div', {class: 'toolbar'}, + textInput('in-table-filter', S.tableFilter, 'text', {placeholder: 'Nach Namen filtern', onInput: render}), + checkbox('chk-active-only', S.tableFilter, 'activeOnly', 'nur mit Aktivität', render), + checkbox('chk-blocked-only', S.tableFilter, 'blockedOnly', 'nur mit gesperrten Versuchen', render), + S.info.role !== 'teacher' ? h('span', {}, checkbox('chk-teachers', S.sel, 'teachers', 'Lehrkräfte anzeigen', toggleTeachers), + S.teachersHidden && !S.sel.teachers ? h('span', {class: 'muted'}, ' (' + S.teachersHidden + ')') : null) : null), + h('div', {class: 'table-wrap'}, h('table', {class: 'table table-hover', test: 'table-members'}, + h('tr', {}, h('th', {class: 'w1'}), sortHead('display', 'Name'), sortHead('user', 'Anmeldename'), sortHead('last', 'Zuletzt aktiv', true), + sortHead('requests', 'Anfragen', true), sortHead('blocked', 'Gesperrt', true)), + rows.map((r) => h('tr', {test: 'member-' + r.user}, + h('td', {}, h('span', {class: ['dot', r.active_now ? 'dot-on' : ''], title: r.active_now ? 'in den letzten 5 Minuten aktiv' : ''})), + h('td', {}, link('link-user-' + r.user, {user: r.user, group: S.groupKey}, r.display), ' ', r.role === 'teacher' ? label('Lehrkraft', 'default') : null), + h('td', {class: 'muted'}, r.user), + h('td', {class: 'right'}, r.last ? T.time(r.last, S.tz, 'time') : '–'), + h('td', {class: 'right'}, T.num(r.requests)), + h('td', {class: 'right'}, r.blocked ? label(T.num(r.blocked), 'danger') : '0'))))), + S.loadedRows && !S.anyActivity ? h('p', {class: 'muted'}, 'In diesem Zeitraum noch keine Internetnutzung in dieser Klasse.') : null, + aggPanel('blocked', 'Gesperrte Versuche der Klasse', () => { + const a = S.agg.blocked; + return [a.loading ? spinner() : null, + a.loaded && !a.rows.length ? h('p', {class: 'muted'}, 'Keine gesperrten Versuche in diesem Zeitraum.') : null, + a.rows.length ? h('table', {class: 'table', test: 'table-agg-blocked'}, + h('tr', {}, h('th', {}, 'Domain'), h('th', {}, 'Kategorie'), h('th', {class: 'right'}, 'Schüler'), h('th', {class: 'right'}, 'Gesperrt')), + a.rows.map((d) => h('tr', {}, + h('td', {}, domainCell(d, 'agg-blocked-' + d.domain)), + h('td', {}, d.category ? label(categoryLabel(d.category), 'default') : null), + h('td', {class: 'right'}, T.num(d.users)), + h('td', {class: 'right'}, T.num(d.blocked))))) : null]; + }), + aggPanel('domains', 'Häufigste Domains der Klasse', () => { + const a = S.agg.domains; + return [checkbox('chk-agg-background', a, 'background', 'Hintergrunddienste zeigen (Werbung, Tracking, Telemetrie)', () => loadAgg('domains')), + a.loading ? spinner() : null, + a.rows.length ? h('table', {class: 'table', test: 'table-agg-domains'}, + h('tr', {}, h('th', {}, 'Domain'), h('th', {}, 'Kategorie'), h('th', {class: 'right'}, 'Schüler'), h('th', {class: 'right'}, 'Anfragen'), h('th', {class: 'right'}, 'Gesperrt')), + a.rows.map((d) => { + const cat = d.category || (d.categories || [])[0]; + return h('tr', {}, + h('td', {}, domainCell(d, 'agg-domains-' + d.domain)), + h('td', {}, cat ? label(categoryLabel(cat), 'default') : null), + h('td', {class: 'right'}, T.num(d.users)), + h('td', {class: 'right'}, T.num(d.requests)), + h('td', {class: 'right'}, d.blocked ? label(T.num(d.blocked), 'danger') : null)); + })) : null]; + }), + aggPanel('search', 'Wer war auf …?', () => { + const a = S.agg.search; + return [h('div', {class: 'toolbar'}, + textInput('in-search-domain', a, 'domain', {placeholder: 'z. B. example.org (mit Subdomains)', class: 'input-wide', onEnter: () => loadAgg('search')}), + button('btn-search-domain', 'Suchen', () => loadAgg('search'), {kind: 'primary', icon: 'search'})), + a.loading ? spinner() : null, + a.loaded && !a.rows.length ? h('p', {class: 'muted'}, 'Niemand aus Ihrem Bereich war in diesem Zeitraum auf dieser Domain.') : null, + a.rows.length ? h('table', {class: 'table', test: 'table-agg-search'}, + h('tr', {}, ['Name', 'Anfragen', 'Gesperrt', 'Erster Aufruf', 'Letzter Aufruf', 'Domains'].map((t, i) => h('th', {class: i === 1 || i === 2 ? 'right' : ''}, t))), + a.rows.map((u) => h('tr', {}, + h('td', {}, link('search-user-' + u.user, {user: u.user, group: S.groupKey}, u.display || u.user)), + h('td', {class: 'right'}, T.num(u.requests)), + h('td', {class: 'right'}, u.blocked ? label(T.num(u.blocked), 'danger') : null), + h('td', {}, T.time(u.first, S.tz, 'short')), + h('td', {}, T.time(u.last, S.tz, 'short')), + h('td', {class: 'muted'}, (u.domains || []).join(', '))))) : null]; + })); +} + +function userPage() { + if (S.person.denied) { + return h('div', {test: 'page-user'}, + h('div', {class: 'toolbar'}, link('btn-back', S.groupKey ? {group: S.groupKey} : {}, [icon('back'), ' Zurück'], {class: 'btn btn-default btn-sm'})), + alert('danger', 'Diese Person gehört nicht zu Ihren Klassen.')); + } + const dd = S.dayData; + const tz = S.tz; + const hasMinutes = dd && (dd.minutes || []).length; + const out = [ + h('div', {class: 'toolbar'}, + link('btn-back', S.groupKey ? {group: S.groupKey} : {}, [icon('back'), ' ' + (S.groupKey && S.group ? S.group.name : 'Übersicht')], {class: 'btn btn-default btn-sm'}), + h('strong', {class: 'detail-title'}, S.person.display || S.person.user), + h('span', {class: 'muted'}, S.person.user + ((S.person.classes || []).length ? ' · ' + S.person.classes.join(', ') : '')), + h('div', {class: 'toolbar-right'}, S.info.can_export ? button('btn-export', 'CSV exportieren', exportCsv, {small: true, icon: 'csv'}) : null)), + h('div', {class: 'toolbar'}, + h('div', {class: 'btn-group'}, + button('btn-day-prev', '', () => goDay(T.addDays(S.sel.day, -1)), {small: true, icon: 'back', disabled: !canGoBack(), + title: canGoBack() ? '' : 'Ältere Daten sind gelöscht (Aufbewahrung).'}), + h('span', {class: 'btn btn-default btn-sm day-label', test: 'text-day'}, h('strong', {}, T.time(S.dayStartT, tz, 'weekday'))), + button('btn-day-next', '', () => goDay(T.addDays(S.sel.day, 1)), {small: true, icon: 'next', disabled: S.sel.day >= S.today})), + button('btn-day-today', 'Heute', () => goDay(S.today), {small: true}), + button('btn-day-yesterday', 'Gestern', () => goDay(S.yesterday), {small: true}), + h('input', {type: 'date', class: 'input input-date', test: 'in-date', value: S.dateInput.value, max: S.today, + on: {change: (e) => { if (/^\d{4}-\d{2}-\d{2}$/.test(e.target.value)) { goDay(e.target.value); } }}}), + h('div', {class: 'btn-group'}, DAY_PARTS.map(([id, text]) => button('btn-part-' + id, text, () => setPart(id), {small: true, class: S.sel.part === id ? 'active' : ''}))), + S.sel.day === S.today ? h('span', {title: 'Alle 30 Sekunden, solange die Seite sichtbar ist, für 15 Minuten'}, checkbox('chk-live', S.sel, 'live', 'Live', toggleLive)) : null, + S.liveEnded ? h('span', {class: 'muted'}, 'Live-Aktualisierung nach 15 Minuten beendet.') : null), + S.dayLoading ? spinner() : null, + ]; + if (dd) { + const t = dd.totals || {}; + out.push(h('div', {class: 'stats', test: 'day-totals'}, + stat('Aktiv', durationText(t.active_minutes)), + stat('Sitzungen', String(S.sessions.length)), + stat('Domains', T.num(t.domains)), + stat('Gesperrt', T.num(t.blocked), t.blocked ? 'text-danger' : ''), + stat('Zuletzt aktiv', T.time(t.last, tz, 'time')))); + if (!hasMinutes) { + out.push(h('p', {class: 'muted'}, 'An diesem Tag keine Internetnutzung.')); + } + } + if (hasMinutes) { + out.push(h('div', {class: 'daybar-wrap', test: 'daybar'}, + h('div', {class: 'daybar-axis'}, S.axis.ticks.map((tick) => h('span', {style: {left: tick.left + '%'}}, tick.label))), + h('div', {class: 'daybar'}, + S.sessions.map((s, i) => h('button', {type: 'button', class: ['session', s === S.chosenSession ? 'chosen' : ''], test: 'session-' + i, title: s.title, + style: {left: s.left + '%', width: s.width + '%'}, attrs: {'aria-label': s.title}, on: {click: () => openSession(s)}})), + S.blockedTicks.map((b) => h('span', {class: 'blocked-tick', title: b.title, style: {left: b.left + '%'}}))), + h('div', {class: 'small muted'}, + S.sessions.map((s, i) => [act('session-link-' + i, T.time(s.start, tz, 'time') + '–' + T.time(s.end, tz, 'time'), () => openSession(s)), ' ']), + '(eine Sitzung anklicken zeigt ihre Domains)'))); + const dd2 = S.domainDetail; + out.push(h('div', {class: 'columns'}, + h('div', {class: 'col-main'}, + h('p', {}, + S.chosenSession ? h('strong', {}, 'Domains der Sitzung ' + T.time(S.chosenSession.start, tz, 'time') + '–' + T.time(S.chosenSession.end, tz, 'time')) : + h('strong', {}, 'Häufigste Domains'), ' ', + S.chosenSession ? act('btn-session-all', 'ganzen Zeitraum zeigen', () => openSession(null)) : null), + checkbox('chk-background', S.sel, 'background', 'Hintergrunddienste zeigen (Werbung, Tracking, Telemetrie)', () => { refreshDomains(); render(); }), + h('table', {class: 'table table-hover', test: 'table-day-domains'}, + h('tr', {}, h('th', {}, 'Domain'), h('th', {class: 'right'}, 'Aktive Minuten'), h('th', {class: 'right'}, 'Anfragen'), h('th', {class: 'right'}, 'Gesperrt')), + S.domainsShown.rows.map((d) => { + const cat = d.category || (d.categories || [])[0]; + return h('tr', {class: d.domain === dd2.domain ? 'selected' : ''}, + h('td', {}, act('domain-' + d.domain, d.domain, () => openDomain(d)), ' ', cat ? label(categoryLabel(cat), d.blocked ? 'danger' : 'default') : null), + h('td', {class: 'right'}, T.num(d.minutes)), + h('td', {class: 'right'}, T.num(d.requests)), + h('td', {class: 'right'}, d.blocked ? label(T.num(d.blocked), 'danger') : null)); + })), + S.domainsShown.other && S.domainsShown.other.count ? h('p', {class: 'muted'}, 'Weitere Domains: ' + T.num(S.domainsShown.other.count)) : null), + h('div', {class: 'col-side', test: 'domain-detail'}, + !dd2.domain ? h('p', {class: 'muted'}, 'Eine Domain anklicken: wann genau sie genutzt wurde.') : [ + h('p', {}, h('strong', {}, dd2.domain), ' ', dd2.label ? label(dd2.label, 'default') : null), + h('p', {class: 'muted'}, T.time(dd2.first, tz, 'time') + '–' + T.time(dd2.last, tz, 'time') + ' · ' + dd2.rows.length + ' aktive Minuten'), + dd2.loading ? spinner() : null, + h('div', {class: 'scroll-area', attrs: {'data-keep-scroll': 'domain-minutes'}}, h('table', {class: 'table'}, + dd2.rows.map((m) => h('tr', {}, h('td', {}, T.time(m.t, tz, 'time')), h('td', {class: 'right'}, T.num(m.requests)), + h('td', {}, m.blocked ? label('gesperrt', 'danger') : null))))), + S.groupKey ? h('p', {}, act('btn-who-else', [icon('users'), ' Wer aus der Klasse war noch auf dieser Domain?'], () => searchFor(dd2.domain))) : null, + ]))); + } + out.push(h('h2', {class: 'heat-title'}, 'Letzte 7 Tage ', h('small', {class: 'muted'}, 'Anfragen je Stunde, roter Rand: gesperrte Versuche; eine Stunde anklicken öffnet sie'))); + out.push(h('div', {class: 'table-wrap'}, h('table', {class: 'heat', test: 'heatmap'}, + h('tr', {}, h('td'), Array.from({length: 24}, (_, hh) => h('td', {class: 'muted center'}, String(hh)))), + S.heat.map((row) => h('tr', {}, + h('td', {class: ['muted', 'nowrap', row.day === S.sel.day ? 'bold' : '']}, row.label), + row.cells.map((c) => h('td', {}, h('button', {type: 'button', class: ['heat-cell', c.blocked ? 'heat-blocked' : ''], test: 'heat-' + row.day + '-' + c.hour, + title: c.title, disabled: !c.requests, style: {backgroundColor: c.color}, attrs: {'aria-label': c.title}, + on: {click: () => openHour(row, c)}})))))))); + return h('div', {test: 'page-user'}, out); +} + +function stat(title, value, cls) { + return h('div', {class: 'stat'}, h('div', {class: 'muted'}, title), h('strong', {class: cls || ''}, value)); +} + +function page() { + const head = h('div', {class: 'page-head'}, h('h1', {}, icon('users'), ' Internetnutzung')); + if (!S.loaded) { + return h('div', {class: 'page'}, head, spinner()); + } + if (S.denied) { + return h('div', {class: 'page'}, head, h('div', {test: 'page-denied'}, + alert('danger', h('strong', {}, 'Kein Zugriff. '), 'Die Internetnutzung steht Lehrkräften (für ihre Klassen und Projekte), Schul-Administratoren und Global-Administratoren zur Verfügung.'))); + } + if (S.loadError) { + return h('div', {class: 'page'}, head, alert('danger', S.loadError)); + } + let body = startPage(); + if (S.page === 'group') { + body = groupPage(); + } else if (S.page === 'user') { + body = userPage(); + } + return h('div', {class: 'page'}, head, failuresLine(), body); +} + +S.sel.school = params().school || ''; +render(); +loadScope().then(applyRoute); diff --git a/edulution/static/js/api.js b/edulution/static/js/api.js new file mode 100644 index 0000000..a18ea98 --- /dev/null +++ b/edulution/static/js/api.js @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Requests of both pages to the plugin container (same origin, behind edulution's Traefik). +// Every state-changing request carries a JSON body and Content-Type application/json: the +// plugin refuses anything else, and checks Origin/Referer, so a page of another site cannot use +// the logged-in browser (the edulution cookie is SameSite=None). + +// /plugin/lmn-squid/manage/... -> /plugin/lmn-squid +export const BASE = (() => { + const path = location.pathname; + const m = /^(.*?)\/(manage|activity|static)(\/|$)/.exec(path); + if (m) { + return m[1]; + } + return path.replace(/\/[^/]*$/, ''); +})(); + +export class ApiError extends Error { + constructor(status, data) { + super((data && data.message) || ('HTTP ' + status)); + this.status = status; + this.data = data || {}; + } +} + +const CHANGING = ['POST', 'PUT', 'PATCH', 'DELETE']; + +function queryString(query) { + if (!query) { + return ''; + } + const parts = []; + Object.keys(query).forEach((k) => { + const v = query[k]; + if (v !== null && v !== undefined && v !== '') { + parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(v)); + } + }); + return parts.length ? '?' + parts.join('&') : ''; +} + +// request('GET', '/api/lmn/squid/connections', {query, body}) -> parsed JSON (or {} for none) +export async function request(method, path, opts) { + const o = opts || {}; + const init = {method, credentials: 'same-origin', headers: {Accept: 'application/json'}, cache: 'no-store'}; + if (CHANGING.indexOf(method) >= 0) { + init.headers['Content-Type'] = 'application/json'; + init.body = JSON.stringify(o.body || {}); + } + let resp; + try { + resp = await fetch(BASE + path + queryString(o.query), init); + } catch (e) { + throw new ApiError(0, {error: 'network', message: ''}); + } + let data = null; + const text = await resp.text(); + if (text) { + try { + data = JSON.parse(text); + } catch (e) { + data = {error: 'not_json', message: ''}; + } + } + if (!resp.ok) { + throw new ApiError(resp.status, data && typeof data === 'object' ? data : {}); + } + return data === null ? {} : data; +} + +export function encodePath(value) { + return encodeURIComponent(value); +} + +// Failures that are the same on both pages: the plugin itself, the session, the network. +export function commonErrorText(err) { + const data = (err && err.data) || {}; + if (!err || err.status === 0) { + return 'Keine Verbindung zum Plugin-Dienst (Netzwerk oder Container).'; + } + if (err.status === 401) { + return 'Die Anmeldung ist abgelaufen: Seite neu laden und erneut anmelden.'; + } + if (data.error === 'content_type' || data.error === 'origin') { + return 'Anfrage abgelehnt: sie kam nicht von dieser Seite.'; + } + if (data.error === 'role') { + return 'Zugriff verweigert: nur für Global-Administratoren.'; + } + if (data.error === 'not_json') { + return 'Unerwartete Antwort des Plugin-Dienstes (HTTP ' + err.status + ').'; + } + return null; +} diff --git a/edulution/static/js/detail.js b/edulution/static/js/detail.js new file mode 100644 index 0000000..c7bb8f2 --- /dev/null +++ b/edulution/static/js/detail.js @@ -0,0 +1,1102 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// +// The page of one instance (overview, category filter, lists, logs, internet use) and the +// dialogs that belong to the filter: apply to other instances, filter per school, own lists. + +import {h, icon, spinner, dialog, toast, textInput, checkbox, select, field, button, label, alert} from './dom.js'; +import {BASE} from './api.js'; +import * as F from './fmt.js'; +import {S, api, enc, render, errorText, fail, fieldErrors, yesNo, schoolOrder, copy, confirmBox, menu} from './manage-core.js'; +import { + setRoute, loadServer, loadActivity, stateClass, stateText, problemText, action, editInstance, saveRetention, + askEnable, askDisable, activityProblem, QUARANTINE_TEXT, +} from './manage.js'; + +export const TABS = ['status', 'filter', 'blocklist', 'allowlist', 'noauth', 'logs', 'access', 'activity']; +const DAY_IDS = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']; +const DAY_NAMES = {mo: 'Mo', tu: 'Di', we: 'Mi', th: 'Do', fr: 'Fr', sa: 'Sa', su: 'So'}; +const NO_SAFESEARCH = {google: false, youtube: 'off', bing: false, duckduckgo: false, ecosia: false, brave: false}; + +function base(d) { + return '/' + enc(d.conn.name) + '/instances/' + enc(d.inst.name); +} + +// ------------------------------------------------------------------ open / close / tabs +export function filterDirty() { + const d = S.detail; + return !!(d && d.tab === 'filter' && d.filter && d.filter.dirty); +} + +async function confirmDiscard() { + if (!filterDirty()) { + return true; + } + if (await confirmBox('Ungespeicherte Filteränderungen verwerfen?', 'Verwerfen')) { + S.detail.filter.dirty = false; + return true; + } + return false; +} + +export function openDetail(conn, inst, tab, fromRoute) { + S.detail = {conn, inst, tab: tab || 'status', logQuery: {tail: 200, grep: ''}, newDomain: ''}; + const server = S.servers[conn.name] || {}; + if (server.activity) { + S.detail.activity = (server.activity.instances || []).find((a) => a.name === inst.name) || null; + S.detail.activityTz = server.activity.timezone; + } + if (!fromRoute) { + setRoute({conn: conn.name, name: inst.name, tab: S.detail.tab}); + } + loadTab(S.detail.tab); + window.scrollTo(0, 0); +} + +async function showTab(tab) { + if (!S.detail || tab === S.detail.tab) { + return; + } + if (await confirmDiscard()) { + setRoute({conn: S.detail.conn.name, name: S.detail.inst.name, tab}, true); + loadTab(tab); + } +} + +async function closeDetail() { + if (await confirmDiscard()) { + S.detail = null; + setRoute({}); + render(); + } +} + +export async function loadTab(tab) { + const d = S.detail; + d.tab = tab; + d.error = null; + d.data = null; + d.loading = true; + render(); + try { + if (tab === 'filter') { + const view = await api('GET', base(d) + '/filter'); + const catalog = await loadCatalog(d.conn.name); + d.filter = filterForm(view, catalog); + } else if (tab === 'activity') { + loadActivity(d.conn.name); + } else if (tab === 'status') { + d.data = await api('GET', base(d) + '/status'); + } else if (tab === 'logs' || tab === 'access') { + d.data = await api('GET', base(d) + (tab === 'logs' ? '/logs' : '/logs/access'), + {query: {tail: d.logQuery.tail, grep: d.logQuery.grep || null}}); + } else { + d.data = await api('GET', base(d) + '/' + tab); + } + } catch (err) { + d.error = errorText(err); + } + if (S.detail === d) { + d.loading = false; + } + render(); +} + +// ------------------------------------------------------------------ lists +async function addDomain() { + const d = S.detail; + d.error = null; + if (!(d.newDomain || '').trim()) { + return; + } + try { + d.data = await api('POST', base(d) + '/' + d.tab, {body: {domain: d.newDomain}}); + d.newDomain = ''; + d.dirty = true; + await reloadList(); // applied at once, no second step + } catch (err) { + d.error = errorText(err) + ' Bitte eine Domain wie example.org eingeben.'; + render(); + } +} + +async function removeDomain(domain) { + const d = S.detail; + try { + d.data = await api('DELETE', base(d) + '/' + d.tab + '/' + enc(domain), {body: {}}); + d.dirty = true; + await reloadList(); + } catch (err) { + d.error = errorText(err); + render(); + } +} + +async function reloadList() { + const d = S.detail; + try { + const data = await api('POST', base(d) + '/' + d.tab + '/reload', {body: {}}); + d.dirty = false; + const notices = (data && data.notices) || []; + toast('Der Proxy hat seine Listen neu eingelesen.' + (notices.length ? ' ' + notices.join(' ') : ''), 'success'); + } catch (err) { + d.error = errorText(err); + } + render(); +} + +// ------------------------------------------------------------------ catalog (ADR-022) +export async function loadCatalog(connName) { + const info = await api('GET', '/' + enc(connName) + '/catalog'); + info.byId = {}; + (info.categories || []).forEach((c) => { + c.variantById = {}; + (c.variants || []).forEach((v) => { c.variantById[v.id] = v; }); + c.defaultVariant = (c.variants || []).find((v) => v.default) || null; + info.byId[c.id] = c; + }); + info.grouped = (info.groups || []).map((g) => ({group: g, categories: (info.categories || []).filter((c) => c.group === g.id)})) + .filter((g) => g.categories.length); + S.catalogs[connName] = info; + return info; +} + +async function refreshCatalog() { + const d = S.detail; + try { + const info = await loadCatalog(d.conn.name); + if (d.filter) { + d.filter.catalog = info; + } + render(); + } catch (err) { + fail(err); + } +} + +async function catalogUpdate(connName) { + try { + await api('POST', '/' + enc(connName) + '/catalog/update', {body: {}}); + toast('Katalog-Aktualisierung gestartet; sie dauert etwa eine Minute. Danach den Katalogstatus neu laden.', 'success'); + const info = S.catalogs[connName]; + if (info) { + info.building = true; + } + render(); + } catch (err) { + fail(err); + } +} + +function suggestedProfile(inst) { + const role = String((inst && inst.role) || '').toLowerCase(); + if (/grundschul|primary/.test(role)) { + return 'primary'; + } + if (/student|schueler|schuler|pupil/.test(role)) { + return 'students'; + } + if (/teacher|lehrer/.test(role)) { + return 'teachers'; + } + if (/staff|verwaltung|admin|mitarbeit/.test(role)) { + return 'staff'; + } + if (/guest|gast/.test(role)) { + return 'guests'; + } + return null; +} + +function scheduleForm(schedules) { + const out = {}; + Object.keys(schedules || {}).forEach((c) => { + out[c] = schedules[c].map((w) => { + const days = {}; + (w.days || []).forEach((day) => { days[day] = true; }); + return {days, start: w.start, end: w.end}; + }); + }); + return out; +} + +function withDefaults(catalog, chosen) { + const out = {}; + ((catalog && catalog.categories) || []).forEach((c) => { + if (c.defaultVariant) { + out[c.id] = c.defaultVariant.id; + } + }); + Object.keys(chosen || {}).forEach((k) => { out[k] = chosen[k]; }); + return out; +} + +function filterForm(view, catalog) { + const settings = view.settings || {categories: [], variants: {}, schedules: {}, safesearch: NO_SAFESEARCH}; + const checked = {}; + (settings.categories || []).forEach((c) => { checked[c] = true; }); + const open = {}; + // only groups with an active category start open (an empty filter: youth protection) + const anyOn = Object.keys(checked).some((k) => checked[k]); + ((catalog && catalog.grouped) || []).forEach((g) => { + open[g.group.id] = anyOn ? g.categories.some((c) => checked[c.id]) : g.group.id === 'youth'; + }); + return { + view, catalog, checked, + variants: withDefaults(catalog, settings.variants), + schedules: scheduleForm(settings.schedules), + safesearch: copy(settings.safesearch || NO_SAFESEARCH), + ui: {query: '', open, info: {}}, + preview: null, + lookup: {domain: '', result: null}, + stats: null, + dirty: false, + }; +} + +// The settings the form describes, in the API's shape (categories in catalog order). +export function filterBody(f) { + const cats = ((f.catalog && f.catalog.categories) || []).map((c) => c.id).filter((id) => f.checked[id]); + const schedules = {}; + const variants = {}; + cats.forEach((id) => { + const windows = (f.schedules[id] || []).map((w) => ({days: DAY_IDS.filter((day) => w.days[day]), start: w.start, end: w.end})); + if (windows.length) { + schedules[id] = windows; + } + }); + Object.keys(f.variants || {}).forEach((id) => { + const cat = f.catalog && f.catalog.byId[id]; + if (cat && cat.variantById[f.variants[id]] && !cat.variantById[f.variants[id]].default) { + variants[id] = f.variants[id]; + } + }); + return {categories: cats, variants, schedules, safesearch: copy(f.safesearch)}; +} + +function catMatches(f, c) { + const q = String((f && f.ui.query) || '').toLowerCase().trim(); + if (!q) { + return true; + } + const text = [c.id, c.label, c.description, (c.examples || []).join(' ')]; + (c.variants || []).forEach((v) => { + text.push(v.label); + (v.sources || []).forEach((s) => text.push(s.name)); + }); + return text.join(' ').toLowerCase().indexOf(q) >= 0; +} + +function scheduleZone(f) { + return (f && ((f.view && f.view.timezone) || (f.catalog && f.catalog.timezone))) || 'Europe/Berlin'; +} + +function catState(f, c) { + if (!c || !f || !f.checked[c.id]) { + return 'off'; + } + return ((f.schedules || {})[c.id] || []).length ? 'scheduled' : 'on'; +} +const CAT_STATE = {on: ['an', 'success'], off: ['aus', 'default'], scheduled: ['zeitgesteuert', 'info']}; + +function variantOf(f, c) { + if (!c) { + return null; + } + return (f && c.variantById[(f.variants || {})[c.id]]) || c.defaultVariant; +} + +function profileDiff(f, profile) { + const now = filterBody(f); + const target = profile.categories || []; + const labels = (f.catalog && f.catalog.byId) || {}; + const lab = (id) => (labels[id] && labels[id].label) || id; + const safeNow = now.safesearch || {}; + const safeNew = profile.safesearch || {}; + return { + on: target.filter((c) => now.categories.indexOf(c) < 0).map(lab), + off: now.categories.filter((c) => target.indexOf(c) < 0).map(lab), + variants: Object.keys(now.variants).filter((c) => target.indexOf(c) >= 0).map(lab), + schedules: Object.keys(now.schedules).map(lab), + safesearch: Object.keys(safeNew).filter((k) => safeNow[k] !== safeNew[k]).map((k) => ({key: k, from: safeNow[k], to: safeNew[k]})), + }; +} + +function previewProfile(id) { + const f = S.detail.filter; + const profile = ((f.catalog && f.catalog.profiles) || {})[id]; + if (profile) { + f.preview = {id, profile, diff: profileDiff(f, profile)}; + } +} + +function applyPreview() { + const f = S.detail.filter; + const profile = f.preview.profile; + f.checked = {}; + (profile.categories || []).forEach((c) => { f.checked[c] = true; }); + f.variants = withDefaults(f.catalog, profile.variants); + f.schedules = {}; + f.safesearch = copy(profile.safesearch || NO_SAFESEARCH); + f.preview = null; + f.dirty = true; + render(); +} + +export function safesearchOn(s) { + return !!(s && (s.google || (s.youtube && s.youtube !== 'off') || s.bing || s.duckduckgo)); +} + +export function safesearchOnInst(inst) { + const ss = (((inst && inst.state) || {}).filter || {}).safesearch || {}; + return Object.keys(ss).some((k) => ss[k] && ss[k] !== 'off'); +} + +// SafeSearch on: "search engines without SafeSearch" is pre-selected (decision 6). +function safesearchChanged() { + const f = S.detail.filter; + f.dirty = true; + if (safesearchOn(f.safesearch) && !f.checked.nosafesearch) { + f.checked.nosafesearch = true; + toast('Suchmaschinen ohne SafeSearch werden jetzt ebenfalls gesperrt (empfohlen). Kategorie abwählen, wenn das nicht gewünscht ist.', 'warning'); + } + render(); +} + +function addWindow(catId) { + const f = S.detail.filter; + f.schedules[catId] = (f.schedules[catId] || []).concat([{days: {mo: true, tu: true, we: true, th: true, fr: true}, start: '07:45', end: '13:15'}]); + f.dirty = true; + render(); +} + +function removeWindow(catId, index) { + const f = S.detail.filter; + f.schedules[catId].splice(index, 1); + f.dirty = true; + render(); +} + +function applyResult(data) { + if (data.applied) { + toast('Filter gespeichert und auf dem Proxy aktiv.', 'success'); + } else if (data.reason === 'not_running') { + toast('Filter gespeichert. Die Instanz läuft nicht: er wirkt, sobald sie startet.', 'warning'); + } else if (data.reason === 'image') { + toast('Filter gespeichert, aber diese Instanz läuft mit einem Image ohne Kategorienfilter: er wirkt erst nach „Image aktualisieren“.', 'warning'); + } + if ((data.missing_sources || []).length) { + toast('Einige gewählte Listen sind noch nicht im Katalog; sie werden geladen (etwa zwei Minuten): ' + data.missing_sources.join(', '), 'warning'); + } +} + +async function saveFilter() { + const d = S.detail; + const f = d.filter; + d.error = null; + f.busy = true; + render(); + try { + const data = await api('PUT', base(d) + '/filter', {body: filterBody(f)}); + f.busy = false; + applyResult(data || {}); + const ui = f.ui; + d.filter = filterForm(data, f.catalog); + d.filter.ui = ui; + loadServer(d.conn.name); + } catch (err) { + f.busy = false; + d.error = errorText(err); + } + render(); +} + +async function lookupDomain() { + const d = S.detail; + const f = d.filter; + f.lookup.result = null; + f.lookup.error = null; + if (!String(f.lookup.domain || '').trim()) { + render(); + return; + } + try { + f.lookup.result = await api('GET', base(d) + '/filter/lookup', {query: {domain: String(f.lookup.domain).trim()}}); + } catch (err) { + f.lookup.error = errorText(err); + } + render(); +} + +function ruleText(rule) { + return { + exception: 'erlaubt: Ausnahme dieser Instanz', + protected: 'erlaubt: auf der Schutzliste (nie durch eine Kategorie gesperrt)', + category: 'gesperrt: Filterkategorie', + catalog_unavailable: 'gesperrt: der Katalog fehlt oder ist defekt und eine Jugendschutz-Kategorie ist aktiv (fail-closed)', + blocklist: 'gesperrt: eigene Sperrliste dieser Instanz', + none: 'nicht durch den Filter gesperrt', + }[rule] || rule; +} + +async function loadStats(days) { + const d = S.detail; + const f = d.filter; + try { + const data = await api('GET', base(d) + '/filter/stats', {query: {days: days || 30}}); + const total = data.total || {}; + const labels = (f.catalog && f.catalog.byId) || {}; + let max = 0; + Object.keys(total).forEach((k) => { max = Math.max(max, total[k]); }); + f.stats = { + days: data.days || [], + bars: Object.keys(total).sort((a, b) => total[b] - total[a]).map((k) => ({ + id: k, label: (labels[k] && labels[k].label) || ruleText(k), count: total[k], width: max ? Math.round(100 * total[k] / max) : 0, + })), + }; + } catch (err) { + d.error = errorText(err); + } + render(); +} + +function variantLabels(f, row) { + const cat = f.catalog && f.catalog.byId[row.category]; + return (row.variants || []).map((v) => (cat && cat.variantById[v] && cat.variantById[v].label) || v).join(', '); +} + +export function filterProblemText(problem) { + return { + catalog_missing_fail_closed: 'Kein Katalog: Anfragen werden abgelehnt (Jugendschutz sperrt im Fehlerfall). Katalog aktualisieren.', + catalog_missing: 'Kein Katalog: die Kategorien wirken noch nicht. Katalog aktualisieren.', + catalog_old: 'Der Katalog ist älter als 7 Tage: nächtliche Aktualisierung prüfen.', + safesearch_unresolved: 'SafeSearch ist an, aber die SafeSearch-Adresse einer Suchmaschine ist unbekannt: diese Suchmaschine ist gesperrt, bis die Adresse aufgelöst werden kann.', + image_without_filter: 'Filter konfiguriert, aber das Image der Instanz kann nicht filtern: nach Kategorien wird nichts gesperrt. Image aktualisieren (Container-Aktionen → Image aktualisieren).', + catalog_lists_old: 'Einige Listen konnten seit mehr als 7 Tagen nicht aktualisiert werden; der letzte gute Stand ist in Gebrauch. Siehe Katalogstatus.', + broken: 'filter.json auf dem Proxy-Host ist beschädigt: Anfragen werden abgelehnt. Filter erneut speichern.', + }[problem] || problem; +} + +function catalogLabel(catalog) { + if (!catalog) { + return null; + } + const kind = catalog.available ? (catalog.old ? 'warning' : 'success') : 'danger'; + const text = catalog.available ? + 'Katalog: ' + F.timeText(catalog.checked || catalog.built, catalog.timezone) + ', ' + F.int(catalog.domains) + ' Domains' : + 'Katalog: nicht verfügbar' + (catalog.error ? ': ' + catalog.error : ''); + return label(text, kind, {test: 'label-catalog'}); +} + +// ------------------------------------------------------------------ filter tab +function filterTab() { + const d = S.detail; + const f = d.filter; + const cat = f.catalog || {}; + const summary = (f.view && f.view.summary) || {}; + const profiles = cat.profiles || {}; + const suggested = suggestedProfile(d.inst); + const zone = scheduleZone(f); + const out = []; + if (!(f.view && f.view.configured)) { + out.push(alert('info', h('strong', {}, 'Filter noch nicht eingerichtet. '), 'Diese Instanz sperrt nur ihre eigene Sperrliste. Vorlage anwenden, prüfen und speichern.')); + } + if (summary.problem) { + out.push(alert('danger', filterProblemText(summary.problem), summary.problem_detail ? h('small', {}, ' (' + summary.problem_detail + ')') : null)); + } + out.push(h('div', {class: 'toolbar'}, + catalogLabel(cat), + cat.building ? label('Aktualisierung läuft', 'info') : null, + cat.last_run && cat.last_run.state === 'failed' ? h('span', {class: 'text-danger'}, 'Letzte Aktualisierung fehlgeschlagen: ' + (cat.last_run.error || '')) : null, + h('div', {class: 'toolbar-right'}, + button('btn-catalog-refresh', 'Katalogstatus neu laden', refreshCatalog, {small: true, icon: 'sync'}), + button('btn-catalog-update', 'Katalog jetzt aktualisieren', () => catalogUpdate(d.conn.name), {small: true, icon: 'download', disabled: !!cat.building}), + button('btn-own-open', 'Eigene Listen', () => openOwn(d.conn), {small: true, icon: 'list'})))); + if ((cat.problems || []).length) { + out.push(h('div', {class: 'small'}, cat.problems.map((p) => h('div', {class: p.old ? 'text-danger' : 'text-warning'}, + icon('warn'), ' ' + p.name + ': ' + (p.state === 'stale' ? 'letzter guter Stand in Gebrauch' : 'nicht im Katalog') + + ' (seit ' + F.timeText(p.since, cat.timezone) + ') – ' + (p.error || ''))))); + } + if (f.preview) { + const df = f.preview.diff; + const none = !df.on.length && !df.off.length && !df.variants.length && !df.schedules.length && !df.safesearch.length; + out.push(h('div', {class: 'panel panel-info', test: 'panel-preview'}, + h('div', {class: 'panel-heading'}, h('strong', {}, 'Vorschau der Vorlage „' + f.preview.profile.label + '“'), ' – ' + (f.preview.profile.description || '')), + h('div', {class: 'panel-body'}, + df.on.length ? h('p', {}, label('wird eingeschaltet', 'success'), ' ' + df.on.join(', ')) : null, + df.off.length ? h('p', {}, label('wird abgeschaltet', 'default'), ' ' + df.off.join(', ')) : null, + df.variants.length ? h('p', {}, label('zurück auf die empfohlenen Listen', 'warning'), ' ' + df.variants.join(', ')) : null, + df.schedules.length ? h('p', {}, label('Zeitfenster entfallen', 'warning'), ' ' + df.schedules.join(', ')) : null, + df.safesearch.length ? h('p', {}, label('SafeSearch', 'info'), ' ' + df.safesearch.map((x) => x.key + ': ' + x.from + ' → ' + x.to).join(', ')) : null, + none ? h('p', {}, 'Keine Änderungen: die Einstellungen entsprechen schon der Vorlage.') : null, + button('btn-preview-apply', 'Vorlage übernehmen (danach speichern)', applyPreview, {kind: 'primary', small: true, icon: 'check'}), ' ', + button('btn-preview-cancel', 'Abbrechen', () => { f.preview = null; render(); }, {kind: 'flat', small: true})))); + } + out.push(h('div', {class: 'toolbar'}, + h('span', {class: 'input-icon'}, icon('search'), + textInput('in-filter-search', f.ui, 'query', {placeholder: 'Kategorien, Quellen, Beispiel-Domains suchen', onInput: render, class: 'input-wide'})), + menu('menu-template', [icon('magic'), ' Vorlage'], Object.keys(profiles).map((id) => + ['menu-template-' + id, profiles[id].label + (suggested === id ? ' (empfohlen)' : ''), () => previewProfile(id), {title: profiles[id].description}])), + button('btn-filter-fold', '', () => { + ((f.catalog && f.catalog.grouped) || []).forEach((g) => { f.ui.open[g.group.id] = false; }); + render(); + }, {icon: 'down', title: 'Alle Gruppen zuklappen'}), + button('btn-filter-save-top', 'Filter speichern', saveFilter, {kind: 'primary', icon: 'save', disabled: !!f.busy}))); + out.push(h('p', {class: 'small muted'}, 'Zeitfenster in ' + zone + '. Details einer Kategorie (Beschreibung, Beispiele, Quellen und Lizenzen): ', icon('info'))); + + // categories by group: collapsible, counters, all on/off; a scroll area of its own + out.push(h('div', {class: 'scroll-area', attrs: {'data-keep-scroll': 'filter-groups'}, test: 'filter-groups'}, + (cat.grouped || []).filter((g) => g.categories.some((c) => catMatches(f, c))).map((g) => { + const open = !!(f.ui.query || f.ui.open[g.group.id]); + const active = g.categories.filter((c) => f.checked[c.id]).length; + return h('div', {class: 'panel panel-compact', test: 'group-' + g.group.id}, + h('div', {class: 'panel-heading clickable', test: 'group-toggle-' + g.group.id, + on: {click: () => { f.ui.open[g.group.id] = !f.ui.open[g.group.id]; render(); }}}, + h('div', {class: 'heading-main'}, icon(open ? 'down' : 'right'), ' ', h('strong', {}, g.group.label), ' ', + h('span', {class: 'badge'}, active + ' / ' + g.categories.length)), + h('span', {on: {click: (e) => e.stopPropagation()}}, + button('btn-group-on-' + g.group.id, 'alle an', () => { + g.categories.filter((c) => catMatches(f, c)).forEach((c) => { f.checked[c.id] = true; }); + f.dirty = true; + render(); + }, {small: true}), ' ', + button('btn-group-off-' + g.group.id, 'alle aus', () => { + g.categories.filter((c) => catMatches(f, c)).forEach((c) => { f.checked[c.id] = false; }); + f.dirty = true; + render(); + }, {small: true}))), + open ? h('div', {class: 'panel-body'}, + g.group.description ? h('p', {class: 'muted small'}, g.group.description) : null, + g.categories.filter((c) => catMatches(f, c)).map((c) => categoryRow(f, c, zone))) : null); + }))); + + const ss = f.safesearch; + out.push(h('h3', {}, 'SafeSearch')); + out.push(h('div', {class: 'toolbar'}, + checkbox('chk-ss-google', ss, 'google', 'Google-Suche', safesearchChanged), + h('label', {}, 'YouTube'), + select('sel-ss-youtube', ss, 'youtube', [['off', 'aus'], ['moderate', 'eingeschränkt (moderat)'], ['strict', 'eingeschränkt (streng)']], safesearchChanged), + checkbox('chk-ss-bing', ss, 'bing', 'Bing', safesearchChanged), + checkbox('chk-ss-duckduckgo', ss, 'duckduckgo', 'DuckDuckGo', safesearchChanged), + checkbox('chk-ss-ecosia', ss, 'ecosia', 'Ecosia', safesearchChanged), + checkbox('chk-ss-brave', ss, 'brave', 'Brave Search', safesearchChanged))); + out.push(h('p', {class: 'muted small'}, 'Der Proxy verbindet zur SafeSearch-Adresse des Dienstes; das Zertifikat bleibt gültig, nichts wird entschlüsselt. Suchmaschinen, bei denen sich SafeSearch nicht erzwingen lässt, stehen in der Kategorie „Suchmaschinen ohne SafeSearch“.')); + out.push(h('div', {class: 'toolbar sticky-save'}, + f.dirty ? label('Geändert: zum Übernehmen speichern', 'warning', {test: 'label-filter-dirty'}) : null, + button('btn-filter-save', 'Filter speichern', saveFilter, {kind: 'primary', icon: 'save', disabled: !!f.busy}), + button('btn-bulk-open', 'Auf weitere Instanzen anwenden', openBulk, {icon: 'copy'}), + spinner(!!f.busy), + h('small', {class: 'muted'}, 'Ausnahmen: Reiter „Ausnahmen“. Sperrseite nur bei HTTP; bei HTTPS erscheint eine Zertifikatswarnung.'))); + + out.push(h('h3', {}, 'Warum ist eine Seite gesperrt?')); + out.push(h('div', {class: 'toolbar'}, + textInput('in-lookup-domain', f.lookup, 'domain', {placeholder: 'z. B. example.org', onEnter: lookupDomain, class: 'input-wide'}), + button('btn-lookup', 'Prüfen', lookupDomain, {icon: 'search'}))); + if (f.lookup.error) { + out.push(alert('danger', f.lookup.error)); + } + const r = f.lookup.result; + if (r) { + out.push(h('table', {class: 'table', test: 'table-lookup'}, + h('tr', {}, h('th', {class: 'w30'}, 'Ergebnis'), h('td', {}, label(ruleText(r.rule), r.blocked ? 'danger' : 'success'), ' ', h('strong', {}, r.category_label || ''))), + r.entry ? h('tr', {}, h('th', {}, 'Passender Eintrag'), h('td', {}, h('code', {}, r.entry))) : null, + (r.listed_in || []).length ? h('tr', {}, h('th', {}, 'Gelistet in Kategorien'), h('td', {}, r.listed_in.map((l) => + l.label + (!l.active ? ' (nicht aktiv)' : '') + (l.active && !l.in_variant ? ' (nur gelistet in ' + variantLabels(f, l) + ', nicht aktiv)' : '')).join(', '))) : null, + (r.sources || []).length ? h('tr', {}, h('th', {}, 'Quellen'), h('td', {}, r.sources.map((s) => s.name + ' (' + s.license + ')').join(', '))) : null)); + } + + out.push(h('h3', {}, 'Statistik ', h('small', {class: 'muted'}, 'gefilterte Anfragen je Kategorie, ohne Benutzer oder Adressen'))); + out.push(button('btn-stats', 'Letzte 30 Tage', () => loadStats(30), {small: true})); + if (f.stats && !f.stats.bars.length) { + out.push(alert('info', 'Keine gefilterten Anfragen in diesem Zeitraum.')); + } + if (f.stats && f.stats.bars.length) { + out.push(h('table', {class: 'table', test: 'table-stats'}, f.stats.bars.map((b) => h('tr', {}, + h('td', {class: 'w35'}, b.label), + h('td', {}, h('span', {class: 'bar', style: {width: Math.max(b.width, 1) + '%'}}), ' ' + F.int(b.count)))))); + } + return h('div', {test: 'tab-content-filter'}, out); +} + +function categoryRow(f, c, zone) { + const st = catState(f, c); + const v = variantOf(f, c) || {}; + return h('div', {class: 'cat-row', test: 'cat-' + c.id}, + h('div', {class: 'cat-line'}, + h('label', {class: 'check'}, h('input', {type: 'checkbox', test: 'chk-cat-' + c.id, checked: !!f.checked[c.id], + on: {change: (e) => { f.checked[c.id] = e.target.checked; f.dirty = true; render(); }}}), ' ' + c.label), ' ', + label(CAT_STATE[st][0], CAT_STATE[st][1]), ' ', + c.fail_closed ? h('span', {class: 'text-danger', title: 'Jugendschutz: Anfragen werden abgelehnt, solange der Katalog fehlt'}, icon('child')) : null, + c.warning || v.warning ? h('span', {class: 'text-warning', title: (c.warning || '') + ' ' + (v.warning || '')}, icon('warn')) : null, + h('span', {class: 'cat-right'}, + h('small', {class: 'muted'}, c.own ? F.int(c.own_entries || 0) : (v.count !== null && v.count !== undefined ? F.int(v.count) : '')), + (c.variants || []).length > 1 ? h('select', {class: 'input input-xs', test: 'sel-variant-' + c.id, title: 'Listen: ' + (v.label || ''), + value: f.variants[c.id] || '', on: {change: (e) => { f.variants[c.id] = e.target.value; f.dirty = true; render(); }}}, + c.variants.map((x) => h('option', {value: x.id}, x.label + (x.default ? ' – empfohlen' : '')))) : null, + f.checked[c.id] ? h('button', {type: 'button', class: 'icon-btn', test: 'btn-window-add-' + c.id, title: 'Nur zu diesen Zeiten sperren', + on: {click: () => addWindow(c.id)}}, icon('clock')) : null, + h('button', {type: 'button', class: 'icon-btn', test: 'btn-cat-info-' + c.id, title: 'Beschreibung, Beispiele, Quellen', + on: {click: () => { f.ui.info[c.id] = !f.ui.info[c.id]; render(); }}}, icon('info')))), + f.ui.info[c.id] ? h('div', {class: 'cat-info small', test: 'cat-info-' + c.id}, + c.description ? h('div', {class: 'muted'}, c.description) : null, + (c.examples || []).length ? h('div', {class: 'muted'}, 'Beispiele: ', c.examples.map((x) => [h('code', {}, x), ' '])) : null, + c.warning ? h('div', {class: 'text-warning'}, icon('warn'), ' ' + c.warning) : null, + v.warning ? h('div', {class: 'text-warning'}, icon('warn'), ' ' + v.warning) : null, + (v.sources || []).map((src) => h('div', {class: 'muted'}, src.name + ' – ' + src.license + + (src.count !== null && src.count !== undefined ? ', ' + F.int(src.count) + ' Einträge' : '') + + (src.last_modified || src.fetched ? ', Stand ' + (src.last_modified || F.timeText(src.fetched, f.catalog.timezone)) : ''), + !src.in_catalog ? h('span', {class: 'text-warning'}, ', noch nicht geladen') : null))) : null, + (f.schedules[c.id] || []).map((w, idx) => h('div', {class: 'window-row small', test: 'window-' + c.id + '-' + idx}, + DAY_IDS.map((day) => h('label', {class: 'check'}, h('input', {type: 'checkbox', test: 'chk-window-' + c.id + '-' + idx + '-' + day, checked: !!w.days[day], + on: {change: (e) => { w.days[day] = e.target.checked; f.dirty = true; render(); }}}), ' ' + DAY_NAMES[day])), + textInput('in-window-start-' + c.id + '-' + idx, w, 'start', {class: 'input-time', onInput: () => { f.dirty = true; }}), ' – ', + textInput('in-window-end-' + c.id + '-' + idx, w, 'end', {class: 'input-time', onInput: () => { f.dirty = true; }}), + h('span', {class: 'muted'}, ' (' + zone + ') '), + button('btn-window-remove-' + c.id + '-' + idx, '', () => removeWindow(c.id, idx), {small: true, icon: 'x', title: 'Zeitfenster entfernen'})))); +} + +// ------------------------------------------------------------------ instance page +function listsTab() { + const d = S.detail; + const domains = (d.data && d.data.domains) || []; + return h('div', {test: 'tab-content-' + d.tab}, + d.tab === 'noauth' ? alert('warning', h('strong', {}, 'Vor dem Hinzufügen lesen:'), h('ul', {}, + h('li', {}, 'Prüfungsmodus: Prüfungskonten (und jedes andere Gerät in den Schulnetzen) erreichen eine gelistete Domain während einer Prüfung ohne Ticket.'), + h('li', {}, 'Die Internetsperre gilt nicht für gelistete Domains: ein Benutzer ohne Internet-Gruppe erreicht sie weiterhin.'), + h('li', {}, 'Diese Anfragen erscheinen im Zugriffslog ohne Benutzer.'), + h('li', {}, 'Nur aus den Client-Netzen der Instanz. Mit dem Standard 0.0.0.0/0 ist das jeder, der den Proxy-Port erreicht: zuerst die echten Client-Netze setzen.'))) : null, + d.tab === 'blocklist' ? h('p', {class: 'muted'}, 'Eine Domain sperrt sich selbst und alle Subdomains. Bei HTTPS erscheint eine Zertifikatswarnung, keine Sperrseite.') : null, + d.tab === 'allowlist' ? h('p', {class: 'muted'}, 'Eine hier eingetragene Domain und ihre Subdomains sind erreichbar, auch wenn die Sperrliste oder eine Filterkategorie sie nennt.') : null, + h('div', {class: 'toolbar'}, + textInput('in-list-domain', d, 'newDomain', {placeholder: 'z. B. example.org', onEnter: addDomain, class: 'input-wide'}), + button('btn-list-add', 'Domain hinzufügen', addDomain, {icon: 'plus'}), + h('div', {class: 'toolbar-right'}, + d.dirty ? label('Geändert: zum Anwenden neu laden', 'warning') : null, + button('btn-list-reload', 'Liste im Proxy neu laden', reloadList, {kind: 'primary', icon: 'sync'}))), + d.data && !domains.length ? alert('info', 'Die Liste ist leer.') : null, + domains.length ? h('table', {class: 'table', test: 'table-list'}, domains.map((domain) => h('tr', {}, + h('td', {}, domain), + h('td', {class: 'right'}, button('btn-list-remove-' + domain, '', () => removeDomain(domain), {small: true, icon: 'trash', title: 'Domain entfernen'}))))) : null); +} + +function logsTab() { + const d = S.detail; + return h('div', {test: 'tab-content-' + d.tab}, + h('div', {class: 'toolbar'}, + h('label', {}, 'Zeilen'), + textInput('in-log-tail', d.logQuery, 'tail', {type: 'number', min: 1, max: 10000, class: 'input-narrow', onEnter: () => loadTab(d.tab)}), + h('label', {}, 'Suchtext'), + textInput('in-log-grep', d.logQuery, 'grep', {placeholder: 'z. B. lehrer1', onEnter: () => loadTab(d.tab), class: 'input-wide'}), + button('btn-log-show', 'Log anzeigen', () => loadTab(d.tab), {kind: 'primary', icon: 'search'})), + d.data && !d.data.logs ? alert('info', 'Keine Einträge.') : null, + d.data && d.data.logs ? h('pre', {class: 'log', test: 'log-output', attrs: {'data-keep-scroll': 'log'}}, d.data.logs) : null); +} + +function activityTab() { + const d = S.detail; + const a = d.activity; + if (!a) { + return h('div', {test: 'tab-content-activity'}, spinner()); + } + const problem = activityProblem(a, d.activityTz); + return h('div', {test: 'tab-content-activity'}, + h('p', {}, label(a.enabled ? 'an' : 'aus', a.enabled ? 'success' : 'default'), ' ', + a.ack_by ? h('span', {class: 'muted'}, 'Bestätigt von ' + a.ack_by + ', ' + F.time(a.ack_at, d.activityTz, 'datetime')) : null), + h('p', {}, 'Gespeichert: ' + F.num((a.usage || {}).days) + ' Tage · ' + F.num(((a.usage || {}).bytes || 0) / 1048576) + ' MB'), + problem ? alert('warning', problem) : null, + (a.usage || {}).quarantined ? alert('danger', F.num(a.usage.quarantined) + ' Spool-Datei(en) in Quarantäne: ' + QUARANTINE_TEXT + + ' Sie liegen auf dem Proxy-Host in /var/spool/linuxmuster-squid/activity/.quarantine/; zum erneuten Versuch zurück in den Spool der Instanz verschieben oder löschen.') : null, + h('div', {class: 'toolbar'}, + h('label', {}, 'Aufbewahrung (Tage)'), + textInput('in-detail-retention', a, 'newRetention', {type: 'number', min: 1, max: 365, class: 'input-narrow', onInput: render}), + a.newRetention !== a.retention_days ? button('btn-detail-retention-save', 'Aufbewahrung speichern', () => saveRetention(d.conn, a), {small: true}) : null, + a.enabled ? button('btn-detail-activity-off', 'Ausschalten', () => askDisable(d.conn, a), {kind: 'danger', small: true}) : + button('btn-detail-activity-on', 'Einschalten', () => askEnable(d.conn, a), {kind: 'primary', small: true})), + h('p', {class: 'muted'}, h('a', {href: BASE + '/activity/', test: 'link-activity-view', target: '_top'}, 'Ansicht „Internetnutzung“ öffnen'))); +} + +function statusTab() { + const d = S.detail; + const s = d.data; + if (!s) { + return null; + } + return h('table', {class: 'table', test: 'tab-content-status'}, + h('tr', {}, h('th', {class: 'w30'}, 'Container vorhanden'), h('td', {}, yesNo(s.exists))), + s.problem ? h('tr', {}, h('th', {}, 'Problem'), h('td', {}, h('span', {class: 'text-danger'}, problemText(s.problem)), h('br'), + h('small', {class: 'muted'}, s.problem_detail || ''))) : null, + h('tr', {}, h('th', {}, 'Container läuft'), h('td', {}, yesNo(s.running))), + h('tr', {}, h('th', {}, 'Health-Check'), h('td', {}, label(s.health || '–', stateClass({state: s})))), + h('tr', {}, h('th', {}, 'Laufendes Image'), h('td', {}, h('code', {class: 'break'}, s.image || '–'))), + h('tr', {}, h('th', {}, 'Konfiguriertes Image'), h('td', {}, h('code', {class: 'break'}, d.inst.image || '–')))); +} + +export function detailPage() { + const d = S.detail; + const isList = ['blocklist', 'allowlist', 'noauth'].indexOf(d.tab) >= 0; + const isLog = d.tab === 'logs' || d.tab === 'access'; + const tab = (id, text, active) => h('li', {class: active ? 'active' : ''}, + h('button', {type: 'button', test: 'dtab-' + id, on: {click: () => showTab(id)}}, text)); + let content = null; + if (!d.loading) { + if (d.tab === 'status') { + content = statusTab(); + } else if (d.tab === 'filter' && d.filter) { + content = filterTab(); + } else if (isList) { + content = listsTab(); + } else if (isLog) { + content = logsTab(); + } else if (d.tab === 'activity') { + content = activityTab(); + } + } + return h('div', {class: 'detail', test: 'page-detail'}, + h('div', {class: 'toolbar'}, + button('btn-detail-back', 'Squid-Proxy', closeDetail, {small: true, icon: 'back'}), + h('strong', {class: 'detail-title'}, d.conn.display_name + ' / ' + d.inst.name), + label(stateText(d.inst), stateClass(d.inst)), + h('div', {class: 'toolbar-right'}, + button('btn-detail-restart', 'Container neu starten', () => action(d.conn, d.inst, 'restart'), {small: true, icon: 'sync'}), + button('btn-detail-edit', 'Instanz bearbeiten', () => editInstance(d.conn, d.inst), {small: true, icon: 'edit'}))), + h('ul', {class: 'tabs'}, + tab('status', 'Übersicht', d.tab === 'status'), + tab('filter', 'Filter', d.tab === 'filter'), + tab('blocklist', 'Listen', isList), + tab('logs', 'Logs', isLog), + tab('activity', 'Internetnutzung', d.tab === 'activity')), + isList ? h('ul', {class: 'pills'}, + tab('blocklist', 'Sperrliste', d.tab === 'blocklist'), + tab('allowlist', 'Ausnahmen', d.tab === 'allowlist'), + tab('noauth', 'Ohne Proxy-Anmeldung', d.tab === 'noauth')) : null, + isLog ? h('ul', {class: 'pills'}, + tab('logs', 'Container-Log', d.tab === 'logs'), + tab('access', 'Zugriffslog', d.tab === 'access')) : null, + h('div', {class: 'tab-body'}, + d.error ? alert('danger', d.error) : null, + d.loading ? spinner() : null, + content)); +} + +// ------------------------------------------------------------------ apply to other instances +function bulkDiff(inst, settings) { + const active = (inst.state && inst.state.filter && inst.state.filter.active) || []; + return { + on: settings.categories.filter((c) => active.indexOf(c) < 0).length, + off: active.filter((c) => settings.categories.indexOf(c) < 0).length, + now: active.length, + }; +} + +function openBulk() { + const d = S.detail; + const settings = filterBody(d.filter); + const rows = []; + S.connections.forEach((conn) => { + ((S.servers[conn.name] || {}).instances || []).forEach((inst) => { + rows.push({conn, inst, diff: bulkDiff(inst, settings), selected: conn.name === d.conn.name && inst.name === d.inst.name}); + }); + }); + const catalog = d.filter.catalog; + S.bulk = { + settings, + summary: (catalog.grouped || []).map((g) => ({group: g.group, items: g.categories.filter((c) => settings.categories.indexOf(c.id) >= 0).map((c) => { + const v = settings.variants[c.id] && c.variantById[settings.variants[c.id]]; + return {label: c.label, variant: v ? v.label : '', scheduled: !!settings.schedules[c.id]}; + })})).filter((g) => g.items.length), + rows, role: d.inst.role, query: '', results: null, + }; + render(); +} + +function bulkRowVisible(r) { + const q = String((S.bulk && S.bulk.query) || '').toLowerCase().trim(); + return !q || [r.inst.name, r.inst.school, r.inst.role, r.conn.display_name].join(' ').toLowerCase().indexOf(q) >= 0; +} + +async function runBulk() { + const b = S.bulk; + const targets = b.rows.filter((r) => r.selected).map((r) => ({conn: r.conn.name, name: r.inst.name})); + if (!targets.length) { + return; + } + b.busy = true; + b.error = null; + render(); + try { + const data = await api('POST', '/filter/bulk', {body: {targets, settings: b.settings}}); + b.results = data.results || []; + if (b.results.some((r) => !r.ok)) { + toast('Nicht überall angewendet, siehe Liste.', 'warning'); + } else { + toast('Auf alle gewählten Instanzen angewendet.', 'success'); + } + S.connections.forEach((c) => loadServer(c.name)); + } catch (err) { + b.error = errorText(err); + } + b.busy = false; + render(); +} + +function bulkResultText(r) { + if (!r.ok) { + return (r.message || r.error || '') + (r.detail ? ' ' + (typeof r.detail === 'string' ? r.detail : JSON.stringify(r.detail)) : ''); + } + if (r.applied) { + return 'aktiv'; + } + return r.reason === 'image' ? 'gespeichert, Image ohne Filter' : 'gespeichert, Instanz läuft nicht'; +} + +function bulkDialog() { + const b = S.bulk; + if (!b) { + return null; + } + const selected = b.rows.filter((r) => r.selected).length; + return dialog('dlg-bulk', 'Filter auf weitere Instanzen anwenden', [ + b.error ? alert('danger', b.error) : null, + h('p', {}, h('strong', {}, 'Zu übernehmende Einstellungen:')), + b.summary.map((g) => h('p', {class: 'tight'}, h('strong', {}, g.group.label + ': '), + g.items.map((i) => i.label + (i.variant ? ' (' + i.variant + ')' : '') + (i.scheduled ? ' ⏱' : '')).join(', '))), + !b.summary.length ? h('p', {class: 'muted'}, 'Keine Kategorie: die gewählten Instanzen sperren dann nur ihre eigene Sperrliste.') : null, + h('p', {}, 'SafeSearch: ' + yesNo(safesearchOn(b.settings.safesearch))), + h('div', {class: 'toolbar'}, + textInput('in-bulk-query', b, 'query', {placeholder: 'Filtern: Schule, Rolle, Server', onInput: render}), + button('btn-bulk-select-shown', 'angezeigte wählen', () => { b.rows.filter(bulkRowVisible).forEach((r) => { r.selected = true; }); render(); }, {small: true}), + button('btn-bulk-clear-shown', 'angezeigte abwählen', () => { b.rows.filter(bulkRowVisible).forEach((r) => { r.selected = false; }); render(); }, {small: true}), + h('label', {}, 'Rolle'), + textInput('in-bulk-role', b, 'role', {class: 'input-narrow'}), + button('btn-bulk-select-role', 'Alle Instanzen mit dieser Rolle wählen', () => { b.rows.forEach((r) => { r.selected = r.inst.role === b.role; }); render(); }, {small: true, icon: 'check'})), + h('div', {class: 'scroll-area', attrs: {'data-keep-scroll': 'bulk-rows'}}, h('table', {class: 'table', test: 'table-bulk'}, + h('tr', {}, ['', 'Instanz', 'Proxy-Server', 'Änderung', 'Ergebnis'].map((t) => h('th', {}, t))), + b.rows.filter(bulkRowVisible).map((r) => { + const key = r.conn.name + '-' + r.inst.name; + const res = (b.results || []).find((x) => x.conn === r.conn.name && x.name === r.inst.name); + return h('tr', {}, + h('td', {}, h('input', {type: 'checkbox', test: 'chk-bulk-' + key, checked: !!r.selected, on: {change: (e) => { r.selected = e.target.checked; render(); }}})), + h('td', {}, r.inst.name), + h('td', {}, r.conn.display_name), + h('td', {}, h('small', {}, h('span', {class: 'text-success'}, '+' + r.diff.on), ' / ', h('span', {class: 'muted'}, '−' + r.diff.off), + h('span', {class: 'muted'}, ' (jetzt ' + r.diff.now + ')'))), + h('td', {}, res ? label(bulkResultText(res), res.ok ? (res.applied ? 'success' : 'warning') : 'danger') : null)); + }))), + ], [ + spinner(!!b.busy), + button('btn-bulk-apply', 'Anwenden (' + selected + ')', runBulk, {kind: 'primary', icon: 'copy', disabled: b.busy || !selected}), + button('btn-bulk-close', 'Schließen', () => { S.bulk = null; render(); }, {kind: 'flat'}), + ], 'lg'); +} + +// ------------------------------------------------------------------ filter per school / group +function overviewGroups(conn, flt) { + const catalog = S.catalogs[conn.name]; + if (!catalog || !flt || !flt.active) { + return []; + } + return (catalog.grouped || []).map((g) => { + const items = g.categories.filter((c) => flt.active.indexOf(c.id) >= 0).map((c) => { + const v = flt.variants && flt.variants[c.id] && c.variantById[flt.variants[c.id]]; + return {label: c.label, variant: v ? v.label : '', scheduled: (flt.scheduled || []).indexOf(c.id) >= 0}; + }); + return {group: g.group, items, total: g.categories.length}; + }).filter((g) => g.items.length); +} + +export function openFilterOverview() { + const rows = []; + S.connections.forEach((conn) => { + ((S.servers[conn.name] || {}).instances || []).forEach((inst) => { + rows.push({conn, inst, filter: (inst.state && inst.state.filter) || null}); + }); + }); + rows.sort((a, b) => schoolOrder(a.inst.school, b.inst.school) || (a.inst.role < b.inst.role ? -1 : (a.inst.role > b.inst.role ? 1 : 0))); + S.filterOverview = {rows}; + render(); + S.connections.forEach((conn) => { + loadCatalog(conn.name).then(render, () => null); + }); +} + +function filterText(inst) { + const flt = inst && inst.state && inst.state.filter; + if (!flt) { + return '–'; + } + return flt.configured ? flt.categories + ' Kategorien' : 'nicht eingerichtet'; +} + +function overviewDialog() { + const o = S.filterOverview; + if (!o) { + return null; + } + return dialog('dlg-filter-overview', 'Filter je Schule und Gruppe', [ + h('div', {class: 'table-wrap', attrs: {'data-keep-scroll': 'overview-x'}}, h('table', {class: 'table', test: 'table-filter-overview'}, + h('tr', {}, ['Schule', 'Rolle', 'Proxy-Server', 'Aktive Kategorien', 'SafeSearch', 'Katalog'].map((t) => h('th', {}, t)), h('th', {class: 'sticky-action'})), + o.rows.map((row) => { + const groups = overviewGroups(row.conn, row.filter); + const catalog = S.catalogs[row.conn.name]; + return h('tr', {}, + h('td', {}, row.inst.school), + h('td', {}, row.inst.role), + h('td', {}, row.conn.display_name), + h('td', {}, + !(row.filter && row.filter.configured) ? h('span', {class: 'muted'}, filterText(row.inst)) : null, + groups.map((g) => h('div', {class: 'small'}, h('strong', {}, g.group.label), ' (' + g.items.length + '/' + g.total + '): ', + g.items.map((i) => label(i.label + (i.variant ? ' *' : '') + (i.scheduled ? ' ⏱' : ''), i.scheduled ? 'info' : 'success', {title: i.variant, class: 'inline'})))), + row.filter && row.filter.problem ? label('Problem', 'warning', {title: filterProblemText(row.filter.problem)}) : null), + h('td', {}, yesNo(safesearchOn(row.filter && row.filter.safesearch))), + h('td', {}, catalog ? label(catalog.available ? F.timeText(catalog.checked || catalog.built, catalog.timezone) : 'fehlt', + catalog.available ? (catalog.old ? 'warning' : 'success') : 'danger', {class: 'wrap'}) : null), + h('td', {class: 'right sticky-action'}, button('btn-overview-filter-' + row.conn.name + '-' + row.inst.name, 'Filter', () => { + S.filterOverview = null; + openDetail(row.conn, row.inst, 'filter'); + }, {small: true, icon: 'filter'}))); + }))), + h('p', {class: 'small muted'}, label('an', 'success'), ' ', label('⏱ zeitgesteuert', 'info'), ' * = andere Listen als empfohlen'), + !o.rows.length ? alert('info', 'Keine Proxy-Instanzen.') : null, + ], [ + button('btn-overview-close', 'Schließen', () => { S.filterOverview = null; render(); }, {kind: 'flat'}), + ], 'lg'); +} + +// ------------------------------------------------------------------ own categories and sources +const NEW_CAT = () => ({id: 'own_', label: '', description: ''}); +const NEW_SRC = () => ({id: 'own-', name: '', url: 'https://', format: 'domains', category: '', license: '', min_entries: 10, max_mb: 50}); + +function openOwn(conn) { + S.own = {conn, data: null, newCat: NEW_CAT(), newSrc: NEW_SRC(), edit: null, errors: {}}; + loadOwn(); + loadCatalog(conn.name).then(render, () => null); + render(); +} + +async function loadOwn() { + const o = S.own; + try { + o.data = await api('GET', '/' + enc(o.conn.name) + '/catalog/custom'); + } catch (err) { + o.error = errorText(err); + } + render(); +} + +async function addOwn(kind) { + const o = S.own; + o.error = null; + o.errors = {}; + const body = kind === 'categories' ? o.newCat : o.newSrc; + try { + await api('POST', '/' + enc(o.conn.name) + '/catalog/custom/' + kind, {body}); + toast(kind === 'categories' ? 'Eigene Kategorie angelegt.' : 'Eigene Quelle hinzugefügt; der Katalog wird im Hintergrund aktualisiert.', 'success'); + if (kind === 'categories') { + o.newCat = NEW_CAT(); + } else { + o.newSrc = NEW_SRC(); + } + loadOwn(); + loadCatalog(o.conn.name).then(render, () => null); + } catch (err) { + o.errors = fieldErrors(err); + o.error = errorText(err); + render(); + } +} + +async function removeOwn(kind, id) { + const o = S.own; + if (!await confirmBox('Wirklich entfernen? Instanzen, die eine eigene Kategorie nutzen, ignorieren sie danach.', 'Entfernen', {danger: true})) { + return; + } + try { + await api('DELETE', '/' + enc(o.conn.name) + '/catalog/custom/' + kind + '/' + enc(id), {body: {}}); + loadOwn(); + loadCatalog(o.conn.name).then(render, () => null); + } catch (err) { + o.error = errorText(err); + render(); + } +} + +async function editOwnDomains(cat) { + const o = S.own; + try { + const data = await api('GET', '/' + enc(o.conn.name) + '/catalog/custom/categories/' + enc(cat.id) + '/domains'); + o.edit = {id: cat.id, label: cat.label, text: (data.domains || []).join('\n')}; + } catch (err) { + o.error = errorText(err); + } + render(); +} + +async function saveOwnDomains() { + const o = S.own; + const domains = String(o.edit.text || '').split(/[\s,]+/).filter((x) => x); + try { + await api('PUT', '/' + enc(o.conn.name) + '/catalog/custom/categories/' + enc(o.edit.id) + '/domains', {body: {domains}}); + toast('Liste gespeichert; wirkt nach spätestens etwa einer Minute in jeder Instanz, die sie nutzt.', 'success'); + o.edit = null; + loadOwn(); + } catch (err) { + o.error = errorText(err); + render(); + } +} + +function ownDialog() { + const o = S.own; + if (!o) { + return null; + } + const catalog = S.catalogs[o.conn.name] || {}; + const e = o.errors || {}; + const cats = (o.data && o.data.categories) || []; + const srcs = (o.data && o.data.sources) || []; + return dialog('dlg-own', 'Eigene Listen – ' + o.conn.display_name, [ + o.error ? alert('danger', o.error) : null, + h('h3', {}, 'Eigene Kategorien ', h('small', {class: 'muted'}, 'eine Domainliste der Schul-IT, wirkt nach spätestens etwa einer Minute, nutzbar wie jede Kategorie')), + cats.length ? h('table', {class: 'table', test: 'table-own-categories'}, cats.map((c) => h('tr', {}, + h('td', {}, h('strong', {}, c.label), ' ', h('code', {}, c.id), h('br'), h('small', {class: 'muted'}, c.description || '')), + h('td', {}, F.int(c.domains) + ' Domains'), + h('td', {class: 'right nowrap'}, + button('btn-own-edit-' + c.id, 'Domains bearbeiten', () => editOwnDomains(c), {small: true, icon: 'edit'}), ' ', + button('btn-own-remove-cat-' + c.id, '', () => removeOwn('categories', c.id), {small: true, kind: 'danger', icon: 'trash', title: 'Entfernen'}))))) : null, + o.edit ? h('div', {class: 'panel', test: 'panel-own-edit'}, + h('div', {class: 'panel-heading'}, o.edit.label + ': eine Domain pro Zeile (mit allen Subdomains)'), + h('div', {class: 'panel-body'}, + h('textarea', {class: 'input', rows: 8, test: 'in-own-domains', value: o.edit.text, on: {input: (ev) => { o.edit.text = ev.target.value; }}}), + button('btn-own-save-domains', 'Liste speichern', saveOwnDomains, {kind: 'primary', small: true, icon: 'save'}))) : null, + h('div', {class: 'toolbar'}, + textInput('in-own-cat-id', o.newCat, 'id', {placeholder: 'own_name', class: 'input-narrow2'}), + textInput('in-own-cat-label', o.newCat, 'label', {placeholder: 'Name'}), + textInput('in-own-cat-description', o.newCat, 'description', {placeholder: 'Beschreibung (optional)', class: 'input-wide'}), + button('btn-own-add-category', 'Kategorie anlegen', () => addOwn('categories'), {small: true, icon: 'plus'})), + h('h3', {}, 'Eigene Quellen ', h('small', {class: 'muted'}, 'eine Liste im Internet (nur https), bei jeder Katalog-Aktualisierung geladen und geprüft wie die mitgelieferten')), + srcs.length ? h('table', {class: 'table', test: 'table-own-sources'}, srcs.map((s) => h('tr', {}, + h('td', {}, h('strong', {}, s.name), ' ', h('code', {}, s.id), h('br'), h('small', {class: 'muted break'}, s.url)), + h('td', {}, ((catalog.byId || {})[s.category] || {}).label || s.category), + h('td', {}, h('small', {}, s.license)), + h('td', {class: 'right'}, button('btn-own-remove-src-' + s.id, '', () => removeOwn('sources', s.id), {small: true, kind: 'danger', icon: 'trash', title: 'Entfernen'}))))) : null, + h('div', {class: 'grid grid-3'}, + field('Kennung', textInput('in-own-src-id', o.newSrc, 'id'), null, e.id), + field('Name', textInput('in-own-src-name', o.newSrc, 'name'), null, e.name), + field('Lizenz der Liste', textInput('in-own-src-license', o.newSrc, 'license', {placeholder: 'z. B. CC BY-SA 4.0'}), null, e.license)), + field('URL (https)', textInput('in-own-src-url', o.newSrc, 'url'), null, e.url), + h('div', {class: 'grid grid-4'}, + field('Format', select('sel-own-src-format', o.newSrc, 'format', [['domains', 'eine Domain pro Zeile'], ['hosts', 'hosts-Datei'], + ['wildcard', 'Wildcard (*.example.org)'], ['adblock', 'Adblock (||example.org^)'], ['rpz', 'RPZ']])), + field('Kategorie', select('sel-own-src-category', o.newSrc, 'category', [['', '–']].concat((catalog.categories || []).map((c) => [c.id, c.label]))), null, e.category), + field('Min. Einträge', textInput('in-own-src-min', o.newSrc, 'min_entries', {type: 'number'}), null, e.min_entries), + field('Max. MB', textInput('in-own-src-max', o.newSrc, 'max_mb', {type: 'number'}), null, e.max_mb)), + button('btn-own-add-source', 'Quelle hinzufügen', () => addOwn('sources'), {small: true, icon: 'plus'}), + h('p', {class: 'small muted'}, 'Nur Listen, deren Lizenz die automatische Nutzung durch die Schule erlaubt; ein Download mit weniger als den Mindesteinträgen oder eine Liste, die um die Hälfte schrumpft, wird abgelehnt und der alte Katalog bleibt.'), + ], [ + button('btn-own-close', 'Schließen', () => { S.own = null; render(); }, {kind: 'flat'}), + ], 'lg'); +} + +export function dialogs() { + return [bulkDialog(), overviewDialog(), ownDialog()]; +} diff --git a/edulution/static/js/dom.js b/edulution/static/js/dom.js new file mode 100644 index 0000000..8710ead --- /dev/null +++ b/edulution/static/js/dom.js @@ -0,0 +1,275 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// +// A tiny DOM builder for the two pages of the edulution plugin. No framework, no innerHTML: +// every text from the server becomes a text node (the page runs under a strict CSP and shows +// names, domains and messages that come from the proxies and the AD). +// +// The pages keep their state in a plain object and rebuild their DOM from it after every change +// (mount). Focus, caret and the scroll position of marked areas survive a rebuild, so an input +// can re-render on every keystroke. + +const SVG_NS = 'http://www.w3.org/2000/svg'; + +function append(el, child) { + if (child === null || child === undefined || child === false || child === true) { + return; + } + if (Array.isArray(child)) { + child.forEach((c) => append(el, c)); + return; + } + if (child instanceof Node) { + el.appendChild(child); + return; + } + el.appendChild(document.createTextNode(String(child))); +} + +// h('button', {class: 'btn', test: 'btn-x', on: {click: fn}, disabled: true}, 'Text', ...) +// class string or array (falsy entries dropped) +// test the data-test attribute (stable hooks for the browser test) +// on {event: handler} +// attrs raw attributes (aria-*, for, ...) +// style object, set through CSSOM (allowed by the CSP, unlike style="") +// value set after the children (a { + const v = String((e.target as { value: unknown }).value); + S.dateInput.value = v; + if (/^\d{4}-\d{2}-\d{2}$/.test(v)) { + goDay(v); + } else { + render(); + } + }} + /> +
+ {DAY_PARTS.map(([id, text]) => ( + setPart(id)}> + {text} + + ))} +
+ {S.sel.day === S.today ? ( + + + + ) : null} + {S.liveEnded ? Live-Aktualisierung nach 15 Minuten beendet. : null} + + {S.dayLoading ? : null} + {dd ? ( +
+ + + + + +
+ ) : null} + {dd && !hasMinutes ?

An diesem Tag keine Internetnutzung.

: null} + {hasMinutes ? ( + <> +
+
+ {S.axis.ticks.map((tick) => ( + + {tick.label} + + ))} +
+
+ {S.sessions.map((s, i) => ( +
+
+ {S.sessions.map((s, i) => ( + openSession(s)} + > + {T.time(s.start, tz, 'time') + '–' + T.time(s.end, tz, 'time')} + + ))} + (eine Sitzung anklicken zeigt ihre Domains) +
+
+
+ + + {S.chosenSession + ? 'Domains der Sitzung ' + + T.time(S.chosenSession.start, tz, 'time') + + '–' + + T.time(S.chosenSession.end, tz, 'time') + : 'Häufigste Domains'} + + {S.chosenSession ? ( + openSession(null)}> + ganzen Zeitraum zeigen + + ) : null} + + } + > +
+ + + + Domain + Aktive Minuten + Anfragen + Gesperrt + + {S.domainsShown.rows.map((d) => { + const cat = d.category || (d.categories || [])[0]; + return ( + + + + openDomain(d)}> + {d.domain} + + {cat ? {categoryLabel(cat)} : null} + + + {T.num(d.minutes)} + {T.num(d.requests)} + {d.blocked ? {T.num(d.blocked)} : null} + + ); + })} + + {S.domainsShown.other && S.domainsShown.other.count ? ( +

{'Weitere Domains: ' + T.num(S.domainsShown.other.count)}

+ ) : null} +
+
+ + {!dd2.domain ? ( +

Eine Domain anklicken: wann genau sie genutzt wurde.

+ ) : ( +
+

+ {dd2.domain} {dd2.label ? {dd2.label} : null} +

+

+ {T.time(dd2.first, tz, 'time') + + '–' + + T.time(dd2.last, tz, 'time') + + ' · ' + + dd2.rows.length + + ' aktive Minuten'} +

+ {dd2.loading ? : null} +
+ + {dd2.rows.map((m: Json) => ( + + {T.time(m.t, tz, 'time')} + {T.num(m.requests)} + {m.blocked ? gesperrt : null} + + ))} + +
+ {S.groupKey ? ( +

+ searchFor(dd2.domain)}> + Wer aus der Klasse war noch auf dieser Domain? + +

+ ) : null} +
+ )} +
+
+ + ) : null} +

+ {'Letzte 7 Tage '} + + Anfragen je Stunde, roter Rand: gesperrte Versuche; eine Stunde anklicken öffnet sie + +

+
+ + + + + ))} + + {S.heat.map((row) => ( + + + {row.cells.map((c) => ( + + ))} + + ))} + +
+ {Array.from({ length: 24 }, (_, hh) => ( + + {String(hh)} +
+ {row.label} + +
+
+ + ); +} + +const HEAD_ICON: IconName = 'users'; + +function Body() { + if (!S.loaded) { + return ; + } + if (S.denied) { + return ( +
+ + Kein Zugriff. + Die Internetnutzung steht Lehrkräften (für ihre Klassen und Projekte), Schul-Administratoren und + Global-Administratoren zur Verfügung. + +
+ ); + } + if (S.loadError) { + return {S.loadError}; + } + return ( + <> + + {S.page === 'group' ? : S.page === 'user' ? : } + + ); +} + +export function App() { + useRendered(); + return ( + + + + + + ); +} + +export function start() { + S.sel.school = params().school || ''; + render(); + loadScope().then(applyRoute); +} diff --git a/edulution/frontend/src/base.ts b/edulution/frontend/src/base.ts new file mode 100644 index 0000000..f3b1dd1 --- /dev/null +++ b/edulution/frontend/src/base.ts @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: Kevin Stenzel +// SPDX-License-Identifier: GPL-3.0-or-later +// +// What every page loads first: the CSP nonce, edulution's fonts (Lato, bundled files) and +// theme, and FontAwesome without its own