Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
67 changes: 65 additions & 2 deletions packages/django/basicbar-integrations/README.md
Original file line number Diff line number Diff line change
@@ -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`)
Expand All @@ -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

Expand Down Expand Up @@ -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 <URL>` 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).
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
@@ -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 []
Original file line number Diff line number Diff line change
Expand Up @@ -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": "",
}


Expand Down
Original file line number Diff line number Diff line change
@@ -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 ""
Loading