diff --git a/CHANGELOG.md b/CHANGELOG.md index 281f940..894c14a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,46 @@ Changelog ist die Upgrade-Anleitung für die Tools. steigen. Die CI testet jeden Dependabot-PR. Für die Tools ändert sich nichts. +### basicbar-integrations (→ wird `integrations/v0.6.0`) + +**Neue Module `gitlab` und `encryption`** (Regel der Zwei: orientierBAR und +ansehbar trugen je eine eigene Kopie). + +- `gitlab` (Extra `[gitlab]`, httpx): `parse_project_url`, `same_origin`, + `check_project`, `upload_file`, `create_issue` mit einfachen Werten + (`project_url`, `token`). `http` nur mit `allow_http=True`, `.git` am Ende + fällt weg, `create_issue(confidential=True)` verlangt die Bestätigung in der + Antwort (sonst `GitLabError`), `Issue.iid` ist `None`, wenn GitLab keine + Nummer liefert, `Issue.web_url` nur bei gleichem Schema, Host und Port wie + die Projekt-URL. Keine Weiterleitung (3xx) wird verfolgt, das Token geht nur + im Header `PRIVATE-TOKEN` an den konfigurierten Host; Fehlertexte nennen nur + Status oder Exception-Klasse, das Modul loggt nicht. Test-Naht: + `basicbar_integrations.gitlab._transport` (httpx-Transport). +- `encryption` (Extra `[encryption]`, cryptography): `encrypt`, `decrypt`, + `EncryptionKeyError` (zugleich `ImproperlyConfigured` und `ValueError`), + `reset_warnings`. Schlüssel aus dem neuen Setting `TOKEN_ENCRYPTION_KEY` + (Default `""`), sonst aus `SECRET_KEY` abgeleitet, Byte für Byte wie vorher: + **gespeicherte Tokens bleiben lesbar, keine Datenmigration.** Die Warnung + beim Entschlüsseln kommt einmal pro Prozess und Art. +- System-Check `basicbar_integrations.E001`: prüft `TOKEN_ENCRYPTION_KEY`, + nur wenn das Setting gesetzt ist. +- Neue Extras `gitlab`, `encryption` und `test` (beide). Ohne Extras starten + App-Setup und `manage.py check` wie bisher; kein Pflicht-Upgrade für Tools, + die weder GitLab noch Verschlüsselung brauchen. + +Migration (orientierBAR, ansehbar): Tarball auf `integrations/v0.6.0` heben +und in `requirements.txt` `basicbar-integrations[gitlab,encryption] @ …` +eintragen. `common/encryption.py` und einen eigenen System-Check für den +Schlüssel (ansehbar: `common/checks.py`) löschen, Imports auf +`basicbar_integrations.encryption` und `basicbar_integrations.gitlab` +umstellen; der Logger heißt jetzt `basicbar_integrations.encryption`, also +`assertLogs` anpassen. Die eigene GitLab-Kopie ersetzen: Texte (Titel, +Beschreibung) bleiben im Tool; orientierBAR macht `iid is None` selbst zum +Fehler und übergibt `confidential=True`, ansehbar übergibt +`allow_http=settings.DEBUG`. Tests auf die eine Naht +`gitlab._transport` umstellen (`mock.patch.object`). Tools ohne GitLab oder +Verschlüsselung: nur Version heben. + ### basicbar-auth (→ wird `auth/v0.3.0`) **Toleranz für Token-Zeitangaben mit mozilla-django-oidc 5.** Ab 5.x prüft diff --git a/packages/django/basicbar-integrations/README.md b/packages/django/basicbar-integrations/README.md index b4438ae..1bd0d94 100644 --- a/packages/django/basicbar-integrations/README.md +++ b/packages/django/basicbar-integrations/README.md @@ -1,8 +1,9 @@ # basicbar-integrations Optionale externe Dienste für die „-bar“-Tools, alle **aus per Default** und -rein per Umgebungs-Settings aktivierbar. Stdlib-`urllib`-Clients — keine -Provider-SDKs. +rein per Umgebungs-Settings aktivierbar. LibreTranslate und LiteLLM laufen +über Stdlib-`urllib`, keine Provider-SDKs; `gitlab` und `encryption` brauchen +je ein Extra (siehe unten). - `translation_service` — LibreTranslate-Client (`CONTENT_TRANSLATION_PROVIDER=libretranslate` + `LIBRETRANSLATE_URL`, optional `LIBRETRANSLATE_API_KEY`) @@ -22,6 +23,10 @@ Provider-SDKs. - `html_sanitize` — die eine HTML-Allowlist für Rich-Content (nh3-basiert). - `metrics` — token-geschützter Prometheus-Endpunkt (`MetricsView` + `Gauges`); ohne `METRICS_TOKEN` antwortet er mit `404`. +- `gitlab` — GitLab-Client (Extra `[gitlab]`): Projekt prüfen, Datei + hochladen, Issue anlegen (siehe „GitLab-Client“) +- `encryption` — Fernet-Verschlüsselung für gespeicherte Geheimnisse (Extra + `[encryption]`, siehe „Token-Verschlüsselung“) ## Einbinden @@ -86,5 +91,63 @@ path("metrics", ToolMetricsView.as_view()), - Prometheus: `authorization: { type: Bearer, credentials_file: … }` im Scrape-Job, `metrics_path: /metrics`. +## GitLab-Client und Token-Verschlüsselung + +Beide Module sind optional: ohne die Extras importiert das Paket weiter, und +`django.setup()` sowie `manage.py check` laufen. Einbinden mit + +``` +basicbar-integrations[gitlab,encryption] @ https://github.com/virtUOS/basicbar/archive/refs/tags/integrations/v0.6.0.tar.gz#subdirectory=packages/django/basicbar-integrations +``` + +(`gitlab` = `httpx>=0.27`, `encryption` = `cryptography>=42`, `test` = beide.) + +```python +from basicbar_integrations import gitlab +from basicbar_integrations.encryption import decrypt, encrypt + +stored = encrypt("glpat-…") # in der Datenbank ablegen +issue = gitlab.create_issue( + "https://git.example.org/group/project", decrypt(stored), + title="…", description="…", confidential=True, labels=["tool"], +) # Issue(iid=17, web_url="https://…/-/issues/17") +``` + +- **`gitlab`**: `parse_project_url(url, allow_http=False)`, + `same_origin(a, b)`, `check_project(url, token)` (wirft nie), + `upload_file(url, token, filename=, data=, content_type=)` (liefert das + Markdown), `create_issue(url, token, title=, description=, + confidential=False, labels=())` (`labels` ist eine Sequenz von Strings; + ein einzelner `str` löst einen `TypeError` aus). Fehler sind `GitLabError`. + `create_issue(confidential=True)` verlangt, dass die Antwort + `confidential: true` zeigt. `Issue.iid` ist `None`, wenn GitLab keine + Nummer liefert (das Tool entscheidet, ob das ein Fehler ist); + `Issue.web_url` ist nur gesetzt, wenn es zur Projekt-URL passt. +- **`encryption`**: `encrypt`/`decrypt` (leer bleibt leer; `decrypt` liefert bei + falschem Schlüssel `""` und warnt einmal pro Prozess und Art), + `EncryptionKeyError`, `reset_warnings()` für Tests. +- **Settings**: `TOKEN_ENCRYPTION_KEY` (Default `""` = aus `SECRET_KEY` + abgeleitet). Einen Schlüssel erzeugen: `python -c "from cryptography.fernet + import Fernet; print(Fernet.generate_key().decode())"`. Der System-Check + `basicbar_integrations.E001` prüft ihn, nur wenn er gesetzt ist. Wer den + Schlüssel wechselt, macht gespeicherte Token unlesbar. +- **Datenschutz**: Das Paket selbst loggt nichts, und weder Token, Klartext, + Chiffrat, Schlüssel, Antwort-Body noch Issue-Inhalt landen in + Exception-Texten (nur HTTP-Status oder Exception-Klasse). Das Token geht nur + im Header `PRIVATE-TOKEN` an den konfigurierten Host; Weiterleitungen + werden nie verfolgt. `http://` wird ohne `allow_http=True` abgewiesen, bevor + eine Anfrage rausgeht, ebenso URLs mit Benutzerinfo oder ohne Projektpfad. + Achtung: httpx loggt auf dem eigenen Logger `httpx` bei INFO eine Zeile + `HTTP Request: POST ` mit dem Projektpfad (nie mit dem Token). Tools, + die Projektpfade nicht im Log haben wollen, setzen den Logger `httpx` auf + `WARNING`. +- **Test-Naht**: `basicbar_integrations.gitlab._transport` nimmt einen + httpx-Transport; `None` ist das echte Netz. + + ```python + with mock.patch.object(gitlab, "_transport", httpx.MockTransport(handler)): + ... + ``` + Alle Settings haben Defaults („aus“) — ein Tool ohne Konfiguration startet unverändert. Tests: `python runtests.py` (oder über die Repo-CI). diff --git a/packages/django/basicbar-integrations/basicbar_integrations/apps.py b/packages/django/basicbar-integrations/basicbar_integrations/apps.py index fc77aec..3b62f67 100644 --- a/packages/django/basicbar-integrations/basicbar_integrations/apps.py +++ b/packages/django/basicbar-integrations/basicbar_integrations/apps.py @@ -7,3 +7,10 @@ class BasicbarIntegrationsConfig(AppConfig): name = "basicbar_integrations" verbose_name = "Basicbar Integrations" + + def ready(self): + from django.core.checks import register + + from .checks import token_encryption_key_check + + register(token_encryption_key_check) diff --git a/packages/django/basicbar-integrations/basicbar_integrations/checks.py b/packages/django/basicbar-integrations/basicbar_integrations/checks.py new file mode 100644 index 0000000..6f384a0 --- /dev/null +++ b/packages/django/basicbar-integrations/basicbar_integrations/checks.py @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""System checks of the app. ``cryptography`` is imported only when the setting is used.""" + +from django.core.checks import Error + +from . import conf + + +def token_encryption_key_check(app_configs, **kwargs): + if not conf.get("TOKEN_ENCRYPTION_KEY"): + return [] + try: + from .encryption import EncryptionKeyError, _fernet + except ImportError: + return [ + Error( + "TOKEN_ENCRYPTION_KEY is set but the 'cryptography' package is not installed.", + hint="Install the extra: pip install 'basicbar-integrations[encryption]'", + id="basicbar_integrations.E001", + ) + ] + try: + _fernet() + except EncryptionKeyError: + return [ + Error( + "TOKEN_ENCRYPTION_KEY is set but not a valid Fernet key.", + hint=( + "Generate one with: python -c \"from cryptography.fernet " + "import Fernet; print(Fernet.generate_key().decode())\"" + ), + id="basicbar_integrations.E001", + ) + ] + return [] diff --git a/packages/django/basicbar-integrations/basicbar_integrations/conf.py b/packages/django/basicbar-integrations/basicbar_integrations/conf.py index f46d4f9..c559f0e 100644 --- a/packages/django/basicbar-integrations/basicbar_integrations/conf.py +++ b/packages/django/basicbar-integrations/basicbar_integrations/conf.py @@ -25,6 +25,8 @@ "LIBRETRANSLATE_API_KEY": "", # Prometheus endpoint (metrics.MetricsView); empty = off (404) "METRICS_TOKEN": "", + # Fernet key for encryption.encrypt/decrypt; empty = derived from SECRET_KEY + "TOKEN_ENCRYPTION_KEY": "", } diff --git a/packages/django/basicbar-integrations/basicbar_integrations/encryption.py b/packages/django/basicbar-integrations/basicbar_integrations/encryption.py new file mode 100644 index 0000000..e2dbc42 --- /dev/null +++ b/packages/django/basicbar-integrations/basicbar_integrations/encryption.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""Symmetric encryption for secrets stored at rest (e.g. a GitLab project token). + +Needs the extra ``basicbar-integrations[encryption]`` (``cryptography``). Fernet +(AES-128-CBC + HMAC). The key is ``settings.TOKEN_ENCRYPTION_KEY`` when set, otherwise +derived from ``SECRET_KEY``; the derivation is byte-for-byte the one the tools used before, +so tokens stored earlier stay readable. A failed decryption (the key changed) yields an empty +string instead of an error, so a key mismatch switches the feature off rather than breaking +pages. Privacy: neither the plaintext, the ciphertext nor the key is ever logged or put into +an exception message. +""" + +import base64 +import hashlib +import logging + +from cryptography.fernet import Fernet, InvalidToken +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured + +from . import conf + +logger = logging.getLogger(__name__) + +# A key problem is hit on every request that reads a token: warn once per process and kind. +_warned: set[str] = set() + + +def _warn_once(kind: str, message: str) -> None: + if kind not in _warned: + _warned.add(kind) + logger.warning(message) + + +def reset_warnings() -> None: + """Forget what was already warned about (tests).""" + _warned.clear() + + +class EncryptionKeyError(ImproperlyConfigured, ValueError): + """``TOKEN_ENCRYPTION_KEY`` is set but not a valid Fernet key.""" + + +def _fernet() -> Fernet: + key = conf.get("TOKEN_ENCRYPTION_KEY") + if key: + try: + return Fernet(key.encode() if isinstance(key, str) else key) + except ValueError: + raise EncryptionKeyError("TOKEN_ENCRYPTION_KEY is not a valid Fernet key") from None + digest = hashlib.sha256(settings.SECRET_KEY.encode()).digest() + return Fernet(base64.urlsafe_b64encode(digest)) + + +def encrypt(text: str) -> str: + """Encrypt to a storable token; empty stays empty.""" + if not text: + return "" + return _fernet().encrypt(text.encode()).decode() + + +def decrypt(token: str) -> str: + """Decrypt a stored token; empty or undecryptable yields an empty string.""" + if not token: + return "" + try: + return _fernet().decrypt(token.encode()).decode() + except EncryptionKeyError: + _warn_once("key", "TOKEN_ENCRYPTION_KEY is not a valid Fernet key; stored secrets are unreadable.") + return "" + except (InvalidToken, ValueError): + _warn_once("decrypt", "A stored secret could not be decrypted; did TOKEN_ENCRYPTION_KEY change?") + return "" diff --git a/packages/django/basicbar-integrations/basicbar_integrations/gitlab.py b/packages/django/basicbar-integrations/basicbar_integrations/gitlab.py new file mode 100644 index 0000000..087bb0d --- /dev/null +++ b/packages/django/basicbar-integrations/basicbar_integrations/gitlab.py @@ -0,0 +1,183 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""Minimal GitLab client: check a project, upload a file, create an issue. + +Needs the extra ``basicbar-integrations[gitlab]`` (``httpx``). Only +``GET .../projects/:id``, ``POST .../uploads`` and ``POST .../issues`` are sent, to exactly +the configured host, without following redirects. Privacy: the token travels only in the +``PRIVATE-TOKEN`` header; ``GitLabError`` messages carry a status code or an exception class +name, never the token, a response body or any issue content. The module does not log. +""" + +from collections.abc import Sequence +from dataclasses import dataclass +from urllib.parse import quote, urlsplit + +import httpx + +TIMEOUT_SECONDS = 15 + + +class GitLabError(Exception): + """A GitLab problem; the message never contains the token or any content.""" + + +@dataclass(frozen=True) +class Issue: + iid: int | None + web_url: str | None + + +# Test seam: an httpx transport (e.g. httpx.MockTransport); None means the real network. +_transport: httpx.BaseTransport | None = None + + +def parse_project_url(url: str, *, allow_http: bool = False) -> tuple[str, str] | None: + """``https://host[:port]/g/sub/p[.git][/-/...]`` -> ``("https://host[:port]", "g/sub/p")``. + + Query, fragment, a ``.git`` suffix and a ``/-/`` tail are dropped. Anything but https + (http only with ``allow_http``), URLs with userinfo and URLs without a project path give None. + """ + try: + parts = urlsplit((url or "").strip()) + host = parts.hostname + port = parts.port + except ValueError: + return None + scheme = parts.scheme.lower() + if scheme not in (("https", "http") if allow_http else ("https",)) or not host: + return None + if parts.username is not None or parts.password is not None or "@" in parts.netloc: + return None + project = ("/" + parts.path.strip("/")).split("/-/", 1)[0].strip("/") + project = project.removesuffix(".git").strip("/") + if not project: + return None + netloc = f"[{host}]" if ":" in host else host + if port: + netloc = f"{netloc}:{port}" + return f"{scheme}://{netloc}", project + + +def _origin(url: str) -> tuple[str, str, int | None]: + parts = urlsplit(url.strip()) + if "@" in parts.netloc or "\\" in parts.netloc: # userinfo, or a backslash browsers read as "/" + raise ValueError("unusable origin") + scheme = parts.scheme.lower() + host = (parts.hostname or "").lower() + port = parts.port + if port == {"https": 443, "http": 80}.get(scheme): + port = None + return scheme, host, port + + +def same_origin(url_a: str, url_b: str) -> bool: + """True if both URLs share scheme, host and port (default ports count as no port).""" + try: + a, b = _origin(url_a), _origin(url_b) + except (ValueError, AttributeError): + return False + return bool(a[1]) and a == b + + +def _target(project_url: str, token: str, allow_http: bool) -> tuple[str, str]: + parsed = parse_project_url(project_url, allow_http=allow_http) + if parsed is None or not token: + raise GitLabError("GitLab is not configured correctly") + base, project = parsed + return f"{base}/api/v4/projects/{quote(project, safe='')}", token + + +def _send(method: str, url: str, token: str, **kwargs) -> httpx.Response: + try: + with httpx.Client(transport=_transport, timeout=TIMEOUT_SECONDS, follow_redirects=False) as client: + response = client.request(method, url, headers={"PRIVATE-TOKEN": token}, **kwargs) + except httpx.HTTPError as exc: + # Class name only: the message could echo request details. + raise GitLabError(f"GitLab unreachable ({type(exc).__name__})") from None + except Exception as exc: # noqa: BLE001 - httpx/idna/codec errors while building the request + # Local input problem (e.g. a non-ASCII token); class name only, it could name a character. + raise GitLabError(f"GitLab request could not be sent ({type(exc).__name__})") from None + if not 200 <= response.status_code < 300: # a redirect lands here, too + raise GitLabError(f"GitLab answered HTTP {response.status_code}") + return response + + +def _json_object(response: httpx.Response) -> dict | None: + try: + body = response.json() + except ValueError: + return None + return body if isinstance(body, dict) else None + + +def check_project(project_url: str, token: str, *, allow_http: bool = False) -> bool: + """True if the project can be read with the token. Never raises.""" + try: + api, token = _target(project_url, token, allow_http) + _send("GET", api, token) + except GitLabError: + return False + return True + + +def upload_file( + project_url: str, + token: str, + *, + filename: str, + data: bytes, + content_type: str, + allow_http: bool = False, +) -> str: + """Upload a file to the project; returns the Markdown snippet GitLab answers with.""" + api, token = _target(project_url, token, allow_http) + response = _send("POST", f"{api}/uploads", token, files={"file": (filename, data, content_type)}) + body = _json_object(response) + markdown = body.get("markdown") if body else None + if not isinstance(markdown, str) or not markdown: + raise GitLabError("GitLab upload returned no markdown") + return markdown + + +def create_issue( + project_url: str, + token: str, + *, + title: str, + description: str, + confidential: bool = False, + labels: Sequence[str] = (), + allow_http: bool = False, +) -> Issue: + """Create an issue. With ``confidential=True`` the answer must confirm it, else GitLabError. + + ``labels`` must be a sequence of strings; a plain ``str`` raises ``TypeError`` (it would + otherwise be split into single characters). + """ + if isinstance(labels, str): + raise TypeError("labels must be a sequence of strings, not a single string") + api, token = _target(project_url, token, allow_http) + fields = {"title": title, "description": description} + if confidential: + fields["confidential"] = "true" + if labels: + fields["labels"] = ",".join(labels) + response = _send("POST", f"{api}/issues", token, data=fields) + body = _json_object(response) + if confidential and (body is None or body.get("confidential") is not True): + raise GitLabError("GitLab did not create a confidential issue") + body = body or {} + iid = body.get("iid") + web_url = body.get("web_url") + if isinstance(web_url, str): + web_url = web_url.strip() + try: + ok = urlsplit(web_url).scheme.lower() in ("http", "https") and same_origin(web_url, project_url) + except ValueError: + ok = False + web_url = web_url if ok else None + else: + web_url = None + return Issue(iid=iid if type(iid) is int and iid >= 1 else None, web_url=web_url) diff --git a/packages/django/basicbar-integrations/basicbar_integrations/tests/test_encryption.py b/packages/django/basicbar-integrations/basicbar_integrations/tests/test_encryption.py new file mode 100644 index 0000000..1883010 --- /dev/null +++ b/packages/django/basicbar-integrations/basicbar_integrations/tests/test_encryption.py @@ -0,0 +1,102 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +from cryptography.fernet import Fernet +from django.core.exceptions import ImproperlyConfigured +from django.test import SimpleTestCase, override_settings + +from basicbar_integrations.checks import token_encryption_key_check +from basicbar_integrations.encryption import ( + EncryptionKeyError, + decrypt, + encrypt, + reset_warnings, +) + +LOGGER = "basicbar_integrations.encryption" + +# Golden ciphertexts: produced by orientierBAR's unchanged ``common.encryption.encrypt`` +# (identical to ansehBAR's apart from a comment in ``_fernet``) for the plaintext +# ``glpat-golden``. They pin that tokens stored before the switch to the package stay readable. +# A: TOKEN_ENCRYPTION_KEY="", SECRET_KEY="test-only-not-a-secret" (key derived from SECRET_KEY) +# B: TOKEN_ENCRYPTION_KEY=GOLDEN_KEY (explicit Fernet key) +GOLDEN_PLAINTEXT = "glpat-golden" +GOLDEN_A = "gAAAAABrAgrWkQwqVzMt2kIoNdUMpD7RF2cpoZEtWePED2tJ03S2XEGYRWyPNlkOqttaZSHC9SnK1D6fgqErlm_D1Oxc72dH7w==" +GOLDEN_KEY = "fKi0xjFbqRz2kGx6mPpq3oQ8fXr0m3ZtYw5uJc1Vd9A=" # test value only +GOLDEN_B = "gAAAAABrAgrWjZUKQoOkVE9y_V8vaNnnaFFT9VnayiVw42Q9K5l53zmZwIMm13zbUjGqWJFpNcxg2RDWzNMi9imF3RIQGmDIdA==" + + +class EncryptionTests(SimpleTestCase): + def setUp(self): + reset_warnings() + + def test_golden_ciphertext_from_secret_key(self): + with override_settings(TOKEN_ENCRYPTION_KEY="", SECRET_KEY="test-only-not-a-secret"): + self.assertEqual(decrypt(GOLDEN_A), GOLDEN_PLAINTEXT) + + def test_golden_ciphertext_from_token_key(self): + with override_settings(TOKEN_ENCRYPTION_KEY=GOLDEN_KEY, SECRET_KEY="irrelevant"): + self.assertEqual(decrypt(GOLDEN_B), GOLDEN_PLAINTEXT) + + def test_warns_once_per_process(self): + with self.assertLogs(LOGGER, "WARNING") as logs: + for _ in range(3): + self.assertEqual(decrypt("gAAAAnot-a-token"), "") + self.assertEqual(len(logs.output), 1) + + def test_each_kind_warns_once_and_independently(self): + with self.assertLogs(LOGGER, "WARNING") as logs: + decrypt("gAAAAnot-a-token") + with override_settings(TOKEN_ENCRYPTION_KEY="nope-secret-key-value"): + decrypt("gAAAA") + decrypt("gAAAA") + decrypt("gAAAAnot-a-token") + self.assertEqual(len(logs.output), 2) + self.assertNotEqual(logs.output[0], logs.output[1]) + + def test_roundtrip_and_empty(self): + token = encrypt("glpat-abc") + self.assertNotIn("glpat-abc", token) + self.assertEqual(decrypt(token), "glpat-abc") + self.assertEqual((encrypt(""), decrypt("")), ("", "")) + + def test_other_key_gives_empty_and_a_content_free_log(self): + with override_settings(TOKEN_ENCRYPTION_KEY=Fernet.generate_key().decode()): + token = encrypt("glpat-abc") + with override_settings(TOKEN_ENCRYPTION_KEY=Fernet.generate_key().decode()): + with self.assertLogs(LOGGER, "WARNING") as logs: + self.assertEqual(decrypt(token), "") + self.assertNotIn("glpat-abc", "\n".join(logs.output)) + self.assertNotIn(token, "\n".join(logs.output)) + + def test_key_derived_from_secret_key_when_unset(self): + with override_settings(TOKEN_ENCRYPTION_KEY="", SECRET_KEY="one"): + token = encrypt("x") + self.assertEqual(decrypt(token), "x") + with override_settings(TOKEN_ENCRYPTION_KEY="", SECRET_KEY="two"): + with self.assertLogs(LOGGER, "WARNING"): + self.assertEqual(decrypt(token), "") + + def test_invalid_key_raises_on_encrypt_and_degrades_on_decrypt(self): + self.assertTrue(issubclass(EncryptionKeyError, ImproperlyConfigured)) + self.assertTrue(issubclass(EncryptionKeyError, ValueError)) + with override_settings(TOKEN_ENCRYPTION_KEY="nope-secret-key-value"): + with self.assertRaises(EncryptionKeyError) as ctx: + encrypt("x") + self.assertNotIn("nope-secret-key-value", str(ctx.exception)) + with self.assertLogs(LOGGER, "WARNING") as logs: + self.assertEqual(decrypt("gAAAA"), "") + self.assertNotIn("nope-secret-key-value", "\n".join(logs.output)) + + def test_check_silent_without_key(self): + with override_settings(TOKEN_ENCRYPTION_KEY=""): + self.assertEqual(token_encryption_key_check(None), []) + with override_settings(TOKEN_ENCRYPTION_KEY=Fernet.generate_key().decode()): + self.assertEqual(token_encryption_key_check(None), []) + + def test_check_reports_invalid_key_without_value(self): + with override_settings(TOKEN_ENCRYPTION_KEY="nope-secret-key-value"): + (error,) = token_encryption_key_check(None) + self.assertEqual(error.id, "basicbar_integrations.E001") + self.assertIn("Fernet.generate_key", error.hint) + self.assertNotIn("nope-secret-key-value", f"{error.msg} {error.hint}") diff --git a/packages/django/basicbar-integrations/basicbar_integrations/tests/test_gitlab.py b/packages/django/basicbar-integrations/basicbar_integrations/tests/test_gitlab.py new file mode 100644 index 0000000..2a24e9c --- /dev/null +++ b/packages/django/basicbar-integrations/basicbar_integrations/tests/test_gitlab.py @@ -0,0 +1,402 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +from unittest import mock +from urllib.parse import parse_qs + +import httpx +from django.test import SimpleTestCase + +from basicbar_integrations import gitlab +from basicbar_integrations.gitlab import GitLabError, Issue + +TOKEN = "glpat-secret-token-123" +BODY_MARK = "BODY-MARKER-do-not-leak" +URL = "https://git.example.org/group/sub/project" + + +def transport(handler): + return mock.patch.object(gitlab, "_transport", httpx.MockTransport(handler)) + + +def form(request): + return {k: v[0] for k, v in parse_qs(request.content.decode()).items()} + + +class ParseProjectUrlTests(SimpleTestCase): + def test_parse_project_url(self): + host = "https://git.example.org" + for url, expected in [ + (URL, (host, "group/sub/project")), + ("https://git.example.org/g/p.git", (host, "g/p")), + ("https://git.example.org/g/p/-/issues?x=1#y", (host, "g/p")), + ("https://git.example.org/g/p?x=1#y", (host, "g/p")), + ("https://git.example.org:8443/g/p/", (host + ":8443", "g/p")), + (" https://git.example.org/g/p ", (host, "g/p")), + ]: + with self.subTest(url=url): + self.assertEqual(gitlab.parse_project_url(url), expected) + + def test_parse_rejects(self): + for url in ( + "", + "http://git.example.org/g/p", + "ftp://git.example.org/g/p", + "https://u:p@git.example.org/g/p", + "https://u@git.example.org/g/p", + "https://git.example.org", + "https://git.example.org/", + "https://git.example.org/-/issues", + "https://git.example.org:99999999/g/p", + "https://git.example.org/.git", + "not a url", + ): + with self.subTest(url=url): + self.assertIsNone(gitlab.parse_project_url(url)) + + def test_parse_strips_slash_left_by_git_suffix(self): + self.assertEqual( + gitlab.parse_project_url("https://git.example.org/g/.git"), ("https://git.example.org", "g") + ) + + def test_parse_allows_http_when_asked(self): + self.assertEqual( + gitlab.parse_project_url("http://localhost:8929/g/p", allow_http=True), + ("http://localhost:8929", "g/p"), + ) + self.assertIsNone(gitlab.parse_project_url("ftp://localhost/g/p", allow_http=True)) + self.assertIsNone(gitlab.parse_project_url("http://u:p@localhost/g/p", allow_http=True)) + + +class SameOriginTests(SimpleTestCase): + def test_same_origin(self): + same = [ + ("https://a.example/x", "https://a.example/y"), + ("https://a.example:443/x", "https://a.example/y"), + ("http://a.example:80/x", "http://a.example/y"), + ("HTTPS://A.Example/x", "https://a.example/y"), + ] + different = [ + ("https://a.example:8443/x", "https://a.example/y"), + ("http://a.example/x", "https://a.example/y"), + ("https://a.example/x", "https://b.example/y"), + ("https://a.example:80/x", "https://a.example/y"), + ("https://evil.example\\@a.example/x", "https://a.example/y"), + ("https://u@a.example/x", "https://a.example/y"), + ] + for a, b in same: + with self.subTest(a=a, b=b): + self.assertTrue(gitlab.same_origin(a, b)) + for a, b in different: + with self.subTest(a=a, b=b): + self.assertFalse(gitlab.same_origin(a, b)) + for a, b in [("", ""), ("not a url", "not a url"), ("https://a.example:abc/x", "https://a.example/")]: + with self.subTest(a=a, b=b): + self.assertFalse(gitlab.same_origin(a, b)) + + +class CreateIssueTests(SimpleTestCase): + def test_create_issue_sends_token_header_and_fields(self): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(201, json={"iid": 17, "web_url": f"{URL}/-/issues/17"}) + + with transport(handler): + issue = gitlab.create_issue(URL, TOKEN, title="Titel", description="Beschreibung") + self.assertEqual(issue, Issue(iid=17, web_url=f"{URL}/-/issues/17")) + (request,) = seen + self.assertEqual(request.method, "POST") + self.assertEqual(request.url.host, "git.example.org") + self.assertEqual(request.url.raw_path, b"/api/v4/projects/group%2Fsub%2Fproject/issues") + self.assertEqual(request.headers["PRIVATE-TOKEN"], TOKEN) + self.assertNotIn(TOKEN, str(request.url)) + self.assertNotIn(TOKEN.encode(), request.content) + self.assertEqual(form(request), {"title": "Titel", "description": "Beschreibung"}) + + def test_create_issue_confidential_and_labels(self): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(201, json={"iid": 3, "confidential": True}) + + with transport(handler): + issue = gitlab.create_issue( + URL, TOKEN, title="T", description="D", confidential=True, labels=["a", "b"] + ) + self.assertEqual(issue.iid, 3) + self.assertEqual( + form(seen[0]), + {"title": "T", "description": "D", "confidential": "true", "labels": "a,b"}, + ) + + def test_confidential_not_confirmed_raises(self): + for body in ({"iid": 3}, {"iid": 3, "confidential": False}, {"iid": 3, "confidential": "true"}): + with self.subTest(body=body): + with transport(lambda request, body=body: httpx.Response(201, json=body)): + with self.assertRaises(GitLabError): + gitlab.create_issue(URL, TOKEN, title="T", description="D", confidential=True) + + def test_confidential_with_non_json_raises(self): + for response in ( + httpx.Response(201, text="ok"), + httpx.Response(201, json=["not", "a", "dict"]), + ): + with self.subTest(response=response.text): + with transport(lambda request, response=response: response): + with self.assertRaises(GitLabError): + gitlab.create_issue(URL, TOKEN, title="T", description="D", confidential=True) + + def test_issue_without_iid_is_returned_as_none(self): + for response in ( + httpx.Response(201, json={}), + httpx.Response(201, json={"iid": 0}), + httpx.Response(201, json={"iid": "7"}), + httpx.Response(201, json={"iid": True}), + httpx.Response(201, json=[1]), + httpx.Response(201, text="not json"), + ): + with self.subTest(response=response.text): + with transport(lambda request, response=response: response): + issue = gitlab.create_issue(URL, TOKEN, title="T", description="D") + self.assertEqual(issue, Issue(iid=None, web_url=None)) + + def test_web_url_only_on_same_origin(self): + def issue_for(web_url): + with transport(lambda request: httpx.Response(201, json={"iid": 1, "web_url": web_url})): + return gitlab.create_issue(URL, TOKEN, title="T", description="D") + + ok = "https://git.example.org/group/sub/project/-/issues/1" + self.assertEqual(issue_for(ok).web_url, ok) + self.assertEqual(issue_for(f" {ok} ").web_url, ok) + explicit_port = "https://git.example.org:443/group/sub/project/-/issues/1" + self.assertEqual(issue_for(explicit_port).web_url, explicit_port) + for bad in ( + "https://evil.example/group/sub/project/-/issues/1", + "javascript:alert(1)", + "http://git.example.org/group/sub/project/-/issues/1", + "https://git.example.org:8443/x", + "https://evil.example\\@git.example.org/x", + "https://u@git.example.org/x", + "https://[evil/x", + "https://[notipv6]/x", + 42, + None, + "", + ): + with self.subTest(web_url=bad): + issue = issue_for(bad) + self.assertEqual(issue.iid, 1) + self.assertIsNone(issue.web_url) + + def test_allow_http_reaches_http_projects(self): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(201, json={"iid": 2, "web_url": "http://localhost:8929/g/p/-/issues/2"}) + + with transport(handler): + issue = gitlab.create_issue( + "http://localhost:8929/g/p", TOKEN, title="T", description="D", allow_http=True + ) + self.assertEqual(seen[0].url.scheme, "http") + self.assertEqual(issue.web_url, "http://localhost:8929/g/p/-/issues/2") + + +class ErrorTests(SimpleTestCase): + def test_redirect_is_not_followed(self): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(302, headers={"Location": "https://evil.example/steal"}) + + with transport(handler): + with self.assertRaises(GitLabError) as ctx: + gitlab.create_issue(URL, TOKEN, title="T", description="D") + self.assertIn("302", str(ctx.exception)) + self.assertEqual(len(seen), 1) + self.assertEqual(seen[0].url.host, "git.example.org") + + def test_non_2xx_raises_with_status_only(self): + with transport(lambda request: httpx.Response(500, text=BODY_MARK)): + with self.assertRaises(GitLabError) as ctx: + gitlab.create_issue(URL, TOKEN, title="T", description="D") + self.assertEqual(str(ctx.exception), "GitLab answered HTTP 500") + + def test_unreachable_raises_with_class_name_only(self): + def handler(request): + raise httpx.ConnectError(f"boom {TOKEN} {BODY_MARK}") + + with transport(handler): + with self.assertRaises(GitLabError) as ctx: + gitlab.create_issue(URL, TOKEN, title="T", description="D") + self.assertEqual(str(ctx.exception), "GitLab unreachable (ConnectError)") + + def _error_paths(self): + """Callables that each end in a GitLabError, with a token and body-carrying server.""" + def call(handler, fn): + def run(): + with transport(handler): + fn() + return run + + create = lambda **kw: gitlab.create_issue(URL, TOKEN, title="T", description="D", **kw) + upload = lambda: gitlab.upload_file( + URL, TOKEN, filename="a.png", data=b"x", content_type="image/png" + ) + + def boom(request): + raise httpx.ReadTimeout(f"{TOKEN} {BODY_MARK}") + + return [ + call(lambda r: httpx.Response(500, text=f"{TOKEN} {BODY_MARK}"), create), + call(lambda r: httpx.Response(302, headers={"Location": f"https://x/{BODY_MARK}"}), create), + call(boom, create), + call(lambda r: httpx.Response(201, text=f"{TOKEN} {BODY_MARK}"), + lambda: create(confidential=True)), + call(lambda r: httpx.Response(201, json={"confidential": False, "note": BODY_MARK}), + lambda: create(confidential=True)), + call(lambda r: httpx.Response(201, json={"note": BODY_MARK}), upload), + call(lambda r: httpx.Response(404, text=BODY_MARK), upload), + call(boom, upload), + ] + + def test_errors_never_contain_token_or_body(self): + for run in self._error_paths(): + with self.assertRaises(GitLabError) as ctx: + run() + self.assertNotIn(TOKEN, str(ctx.exception)) + self.assertNotIn(BODY_MARK, str(ctx.exception)) + # No chained original exception (it could carry the token or body). + self.assertTrue(ctx.exception.__suppress_context__ or ctx.exception.__context__ is None) + self.assertIsNone(ctx.exception.__cause__) + + def test_unsendable_request_raises_gitlab_error_without_token_char(self): + calls = [] + + def handler(request): + calls.append(request) + return httpx.Response(200, json={}) + + with transport(handler): + for url, token in [(URL, "glpat-\u00e4"), ("https://xn--a.org/g/p", "glpat-x")]: + with self.subTest(url=url): + for fn in ( + lambda: gitlab.create_issue(url, token, title="T", description="D"), + lambda: gitlab.upload_file(url, token, filename="a", data=b"", content_type="x/y"), + ): + with self.assertRaises(GitLabError) as ctx: + fn() + self.assertNotIn("\u00e4", str(ctx.exception)) + self.assertNotIn("position", str(ctx.exception)) + self.assertRegex(str(ctx.exception), r"^GitLab request could not be sent \(\w+\)$") + self.assertNotIn("unreachable", str(ctx.exception)) + self.assertFalse(gitlab.check_project(url, token)) + + def test_labels_must_not_be_a_plain_string(self): + with self.assertRaises(TypeError): + gitlab.create_issue(URL, TOKEN, title="T", description="D", labels="bug") + + def test_not_configured_sends_nothing(self): + calls = [] + + def handler(request): + calls.append(request) + return httpx.Response(200, json={}) + + cases = [ + (URL, ""), + ("", TOKEN), + ("http://git.example.org/g/p", TOKEN), + ("https://user:pw@git.example.org/g/p", TOKEN), + ("https://git.example.org", TOKEN), + ] + with transport(handler): + for url, token in cases: + with self.subTest(url=url, token=bool(token)): + with self.assertRaisesMessage(GitLabError, "GitLab is not configured correctly"): + gitlab.create_issue(url, token, title="T", description="D") + with self.assertRaisesMessage(GitLabError, "GitLab is not configured correctly"): + gitlab.upload_file(url, token, filename="a", data=b"", content_type="x/y") + self.assertFalse(gitlab.check_project(url, token)) + self.assertEqual(calls, []) + + def test_module_does_not_log(self): + # httpx itself logs requests at INFO on its own logger; the package must add nothing. + with self.assertNoLogs("basicbar_integrations", level="DEBUG"): + for run in self._error_paths(): + with self.assertRaises(GitLabError): + run() + with transport(lambda r: httpx.Response(200, json={})): + gitlab.check_project(URL, TOKEN) + gitlab.check_project("", "") + + +class UploadTests(SimpleTestCase): + def test_upload_file_returns_markdown(self): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(201, json={"markdown": "![a](/uploads/x/a.png)"}) + + with transport(handler): + markdown = gitlab.upload_file( + URL, TOKEN, filename="shot.png", data=b"PNGDATA", content_type="image/png" + ) + self.assertEqual(markdown, "![a](/uploads/x/a.png)") + (request,) = seen + self.assertEqual(request.method, "POST") + self.assertEqual(request.url.raw_path, b"/api/v4/projects/group%2Fsub%2Fproject/uploads") + self.assertEqual(request.headers["PRIVATE-TOKEN"], TOKEN) + self.assertTrue(request.headers["Content-Type"].startswith("multipart/form-data")) + self.assertIn(b'filename="shot.png"', request.content) + self.assertIn(b"Content-Type: image/png", request.content) + self.assertIn(b"PNGDATA", request.content) + self.assertNotIn(TOKEN.encode(), request.content) + + def test_upload_without_markdown_raises(self): + for response in ( + httpx.Response(201, json={}), + httpx.Response(201, json={"markdown": ""}), + httpx.Response(201, json={"markdown": 5}), + httpx.Response(201, text="nope"), + ): + with self.subTest(response=response.text): + with transport(lambda request, response=response: response): + with self.assertRaises(GitLabError): + gitlab.upload_file( + URL, TOKEN, filename="a.png", data=b"x", content_type="image/png" + ) + + +class CheckProjectTests(SimpleTestCase): + def test_check_project_true_on_200_false_otherwise(self): + seen = [] + + def ok(request): + seen.append(request) + return httpx.Response(200, json={"id": 1}) + + with transport(ok): + self.assertTrue(gitlab.check_project(URL, TOKEN)) + (request,) = seen + self.assertEqual(request.method, "GET") + self.assertEqual(request.url.raw_path, b"/api/v4/projects/group%2Fsub%2Fproject") + self.assertEqual(request.headers["PRIVATE-TOKEN"], TOKEN) + + def unreachable(request): + raise httpx.ConnectError("down") + + for handler in ( + lambda r: httpx.Response(401), + lambda r: httpx.Response(404), + lambda r: httpx.Response(302, headers={"Location": "https://evil.example/"}), + unreachable, + ): + with transport(handler): + self.assertFalse(gitlab.check_project(URL, TOKEN)) diff --git a/packages/django/basicbar-integrations/basicbar_integrations/tests/test_without_extras.py b/packages/django/basicbar-integrations/basicbar_integrations/tests/test_without_extras.py new file mode 100644 index 0000000..3b7adf6 --- /dev/null +++ b/packages/django/basicbar-integrations/basicbar_integrations/tests/test_without_extras.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""A tool that installs the package without the extras must still start and pass ``check``.""" + +import os +import subprocess +import sys +import textwrap + +from django.test import SimpleTestCase + +SCRIPT = textwrap.dedent( + """ + import os, sys + sys.modules["httpx"] = None + sys.modules["cryptography"] = None + os.environ["DJANGO_SETTINGS_MODULE"] = "basicbar_integrations.tests.settings" + if os.environ.get("KEY"): + from django.conf import settings + settings.TOKEN_ENCRYPTION_KEY = os.environ["KEY"] + import django + django.setup() + from django.core.management import call_command + from django.core.management.base import SystemCheckError + try: + call_command("check") + except SystemCheckError as exc: + sys.stderr.write(str(exc)) + sys.exit(1) + """ +) + + +def run_check(key: str = "") -> subprocess.CompletedProcess: + env = {**os.environ, "KEY": key} + return subprocess.run( + [sys.executable, "-I", "-c", SCRIPT], + capture_output=True, text=True, env=env, timeout=120, + ) + + +class WithoutExtrasTests(SimpleTestCase): + def test_app_and_checks_run_without_extras(self): + result = run_check() + self.assertEqual(result.returncode, 0, result.stderr) + + result = run_check("secret-key-value") + self.assertNotEqual(result.returncode, 0) + self.assertIn("basicbar_integrations.E001", result.stderr) + self.assertIn("basicbar-integrations[encryption]", result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertNotIn("ImportError", result.stderr) + self.assertNotIn("secret-key-value", result.stderr + result.stdout) diff --git a/packages/django/basicbar-integrations/pyproject.toml b/packages/django/basicbar-integrations/pyproject.toml index 830254d..49af69a 100644 --- a/packages/django/basicbar-integrations/pyproject.toml +++ b/packages/django/basicbar-integrations/pyproject.toml @@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta" [project] name = "basicbar-integrations" -version = "0.5.0" -description = "Optionale Integrationen der virtUOS -bar-Tools: LibreTranslate, LiteLLM, HTML-Allowlist, Übersetzungs-Sync" +version = "0.6.0" +description = "Optionale Integrationen der virtUOS -bar-Tools: LibreTranslate, LiteLLM, GitLab-Client, Token-Verschlüsselung, HTML-Allowlist, Übersetzungs-Sync" readme = "README.md" requires-python = ">=3.12" license = { text = "Apache-2.0" } @@ -16,5 +16,10 @@ dependencies = [ "nh3>=0.2", ] +[project.optional-dependencies] +gitlab = ["httpx>=0.27"] +encryption = ["cryptography>=42"] +test = ["httpx>=0.27", "cryptography>=42"] + [tool.setuptools.packages.find] include = ["basicbar_integrations*"]