From c1fa019e2abecdeec73ddb8094aa2c66e45ab5f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 14:37:26 +0100 Subject: [PATCH 1/9] =?UTF-8?q?feat(lti):=20LtiRegistrationToken=20und=20S?= =?UTF-8?q?ettings=20f=C3=BCr=20Dynamic=20Registration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../django/basicbar-lti/basicbar_lti/admin.py | 15 +++- .../django/basicbar-lti/basicbar_lti/conf.py | 22 ++++++ .../migrations/0002_ltiregistrationtoken.py | 30 ++++++++ .../basicbar-lti/basicbar_lti/models.py | 72 +++++++++++++++++++ .../basicbar_lti/tests/test_dynreg.py | 59 +++++++++++++++ 5 files changed, 197 insertions(+), 1 deletion(-) create mode 100644 packages/django/basicbar-lti/basicbar_lti/migrations/0002_ltiregistrationtoken.py create mode 100644 packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py diff --git a/packages/django/basicbar-lti/basicbar_lti/admin.py b/packages/django/basicbar-lti/basicbar_lti/admin.py index eee74a8..2aa6eca 100644 --- a/packages/django/basicbar-lti/basicbar_lti/admin.py +++ b/packages/django/basicbar-lti/basicbar_lti/admin.py @@ -3,7 +3,7 @@ from django.contrib import admin -from .models import LtiPlatform, LtiToolKey, LtiUserLink +from .models import LtiPlatform, LtiRegistrationToken, LtiToolKey, LtiUserLink @admin.register(LtiPlatform) @@ -23,3 +23,16 @@ class LtiToolKeyAdmin(admin.ModelAdmin): list_display = ("__str__", "created_at") readonly_fields = ("public_key", "created_at") exclude = ("private_key",) + + +@admin.register(LtiRegistrationToken) +class LtiRegistrationTokenAdmin(admin.ModelAdmin): + """Read-only overview; deleting a token revokes it.""" + + list_display = ("note", "created_by", "created_at", "expires_at", "status", "platform") + + def get_readonly_fields(self, request, obj=None): + return [f.name for f in self.model._meta.fields] + + def has_add_permission(self, request): + return False diff --git a/packages/django/basicbar-lti/basicbar_lti/conf.py b/packages/django/basicbar-lti/basicbar_lti/conf.py index 4ad87be..1a3c455 100644 --- a/packages/django/basicbar-lti/basicbar_lti/conf.py +++ b/packages/django/basicbar-lti/basicbar_lti/conf.py @@ -3,6 +3,8 @@ """Settings access with package defaults.""" +from datetime import timedelta + from django.conf import settings DEFAULTS = { @@ -10,9 +12,29 @@ # frame-ancestors middleware acts only under these prefixes). Tools add # their embeddable surfaces, e.g. abstimmbar: ("/lti/", "/p/"). "LTI_FRAME_PATH_PREFIXES": ("/lti/",), + # Dynamic Registration: lifetime of a one-time registration token. + "LTI_REGISTRATION_TOKEN_TTL": timedelta(days=7), + # Allow http:// and loopback/link-local targets (local development only). + "LTI_REGISTRATION_ALLOW_HTTP": False, + # What the tool announces to the platform; the project's setting is + # merged flat (key by key) over this dict. + "LTI_TOOL_REGISTRATION": { + "client_name": "LTI Tool", + "description": "", + "logo_path": "", + "messages": [{"type": "LtiResourceLinkRequest"}], + "claims": ["iss", "sub", "name", "given_name", "family_name", "email"], + "scope": "", + "custom_parameters": {}, + }, } def get(name: str): """Return the project's setting, or the package default when unset.""" return getattr(settings, name, DEFAULTS[name]) + + +def tool_registration() -> dict: + """Default tool registration, overridden key by key by the project.""" + return {**DEFAULTS["LTI_TOOL_REGISTRATION"], **get("LTI_TOOL_REGISTRATION")} diff --git a/packages/django/basicbar-lti/basicbar_lti/migrations/0002_ltiregistrationtoken.py b/packages/django/basicbar-lti/basicbar_lti/migrations/0002_ltiregistrationtoken.py new file mode 100644 index 0000000..fdbdd40 --- /dev/null +++ b/packages/django/basicbar-lti/basicbar_lti/migrations/0002_ltiregistrationtoken.py @@ -0,0 +1,30 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('basicbar_lti', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='LtiRegistrationToken', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('token_hash', models.CharField(max_length=64, unique=True)), + ('note', models.CharField(blank=True, max_length=200)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('expires_at', models.DateTimeField()), + ('used_at', models.DateTimeField(blank=True, null=True)), + ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), + ('platform', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='registration_tokens', to='basicbar_lti.ltiplatform')), + ], + ), + ] diff --git a/packages/django/basicbar-lti/basicbar_lti/models.py b/packages/django/basicbar-lti/basicbar_lti/models.py index 323a6f8..f601e1a 100644 --- a/packages/django/basicbar-lti/basicbar_lti/models.py +++ b/packages/django/basicbar-lti/basicbar_lti/models.py @@ -10,10 +10,16 @@ A tool that carried these models itself adopts the package with a data-move migration (abstimmbar's ``lti/0003`` is the template). """ +import hashlib +import secrets + from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from django.conf import settings from django.db import models +from django.utils import timezone + +from . import conf class TimeStampedModel(models.Model): @@ -123,3 +129,69 @@ class Meta: def __str__(self): return f"{self.platform.name}:{self.sub} → {self.user}" + + +class LtiRegistrationToken(models.Model): + """One-time token authorising a platform's Dynamic Registration. + + Only the SHA-256 hash is stored; the plaintext is shown exactly once + when the token is issued. + """ + + token_hash = models.CharField(max_length=64, unique=True) + note = models.CharField(max_length=200, blank=True) + created_by = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="+", + ) + created_at = models.DateTimeField(auto_now_add=True) + expires_at = models.DateTimeField() + used_at = models.DateTimeField(null=True, blank=True) + platform = models.ForeignKey( + LtiPlatform, + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="registration_tokens", + ) + + @staticmethod + def hash(raw: str) -> str: + return hashlib.sha256(raw.encode()).hexdigest() + + @classmethod + def issue(cls, *, note: str = "", created_by=None): + """Create a token; returns ``(instance, plaintext)``.""" + raw = secrets.token_urlsafe(32) + obj = cls.objects.create( + token_hash=cls.hash(raw), + note=note, + created_by=created_by, + expires_at=timezone.now() + conf.get("LTI_REGISTRATION_TOKEN_TTL"), + ) + return obj, raw + + @classmethod + def find_valid(cls, raw: str): + """The unused, unexpired token for ``raw``, else ``None``.""" + if not raw: + return None + return cls.objects.filter( + token_hash=cls.hash(raw), + used_at__isnull=True, + expires_at__gt=timezone.now(), + ).first() + + @property + def status(self) -> str: + if self.used_at is not None: + return "used" + if self.expires_at <= timezone.now(): + return "expired" + return "open" + + def __str__(self): + return f"Registration token ({self.note or self.pk})" diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py new file mode 100644 index 0000000..65fddb7 --- /dev/null +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -0,0 +1,59 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""Tests for LTI Dynamic Registration (token model, settings, ...).""" +import hashlib +from datetime import timedelta + +from django.test import TestCase, override_settings +from django.utils import timezone + +from basicbar_lti import conf +from basicbar_lti.models import LtiRegistrationToken + + +class RegistrationTokenTests(TestCase): + def test_issue_stores_only_hash(self): + obj, raw = LtiRegistrationToken.issue(note="Moodle") + self.assertEqual(obj.token_hash, hashlib.sha256(raw.encode()).hexdigest()) + values = [ + str(getattr(obj, f.attname)) for f in LtiRegistrationToken._meta.fields + ] + self.assertFalse(any(raw in v for v in values)) + self.assertEqual(obj.status, "open") + + def test_default_ttl_is_seven_days(self): + obj, _ = LtiRegistrationToken.issue() + delta = obj.expires_at - obj.created_at + self.assertGreater(delta, timedelta(days=6, hours=23)) + self.assertLess(delta, timedelta(days=7, minutes=1)) + + @override_settings(LTI_REGISTRATION_TOKEN_TTL=timedelta(hours=1)) + def test_ttl_setting(self): + obj, _ = LtiRegistrationToken.issue() + delta = obj.expires_at - obj.created_at + self.assertGreater(delta, timedelta(minutes=59)) + self.assertLess(delta, timedelta(hours=1, minutes=1)) + + def test_find_valid(self): + obj, raw = LtiRegistrationToken.issue() + self.assertEqual(LtiRegistrationToken.find_valid(raw), obj) + self.assertIsNone(LtiRegistrationToken.find_valid("")) + self.assertIsNone(LtiRegistrationToken.find_valid("nope")) + obj.used_at = timezone.now() + obj.save() + self.assertIsNone(LtiRegistrationToken.find_valid(raw)) + self.assertEqual(obj.status, "used") + obj.used_at = None + obj.expires_at = timezone.now() - timedelta(seconds=1) + obj.save() + self.assertIsNone(LtiRegistrationToken.find_valid(raw)) + self.assertEqual(obj.status, "expired") + + @override_settings(LTI_TOOL_REGISTRATION={"client_name": "abstimmbar"}) + def test_tool_registration_merges_flat(self): + cfg = conf.tool_registration() + self.assertEqual(cfg["client_name"], "abstimmbar") + self.assertEqual( + cfg["claims"], conf.DEFAULTS["LTI_TOOL_REGISTRATION"]["claims"] + ) From f9a067542f5a9433b5d7a7668b5014f1bbea88f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 14:39:15 +0100 Subject: [PATCH 2/9] =?UTF-8?q?feat(lti):=20abgeschotteter=20HTTP-Client?= =?UTF-8?q?=20f=C3=BCr=20Dynamic=20Registration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../basicbar-lti/basicbar_lti/dynreg_http.py | 167 ++++++++++++++++ .../basicbar_lti/tests/test_dynreg.py | 180 +++++++++++++++++- 2 files changed, 345 insertions(+), 2 deletions(-) create mode 100644 packages/django/basicbar-lti/basicbar_lti/dynreg_http.py diff --git a/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py b/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py new file mode 100644 index 0000000..63d2aa8 --- /dev/null +++ b/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py @@ -0,0 +1,167 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""Sealed-off HTTP client for the two outbound requests of Dynamic +Registration (fetch the platform's OpenID configuration, POST the tool +registration). + +The URLs come from an LMS admin's browser, so they are untrusted: only +https (unless ``LTI_REGISTRATION_ALLOW_HTTP``), no loopback / link-local / +unspecified target addresses, same-origin redirects only, bounded time and +size, JSON objects only. Private networks stay allowed (on-prem Moodle). +""" + +import ipaddress +import json +import socket +import urllib.error +import urllib.request +from urllib.parse import urlsplit + +from . import conf + +TIMEOUT = 10 # seconds +MAX_BYTES = 256 * 1024 +_DETAIL_CHARS = 500 + + +class RegistrationError(Exception): + """``str(exc)`` is the (German) message for the platform admin; + ``detail`` is for the log only.""" + + def __init__(self, message: str, detail: str = ""): + super().__init__(message) + self.detail = detail + + +def _origin(url: str) -> tuple[str, str, int | None]: + parts = urlsplit(url) + try: + port = parts.port + except ValueError: + port = None + return (parts.scheme.lower(), (parts.hostname or "").lower(), port) + + +def _default_port(scheme: str) -> int: + return 443 if scheme == "https" else 80 + + +class _SameOriginRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + old, new = _origin(req.full_url), _origin(newurl) + if (old[0], old[1], old[2] or _default_port(old[0])) != ( + new[0], + new[1], + new[2] or _default_port(new[0]), + ): + raise RegistrationError( + "Die Plattform leitet auf eine andere Adresse um; das wird " + "aus Sicherheitsgründen abgelehnt.", + detail=f"redirect {req.full_url} -> {newurl}", + ) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +_opener = urllib.request.build_opener(_SameOriginRedirectHandler) + + +def _open(req: urllib.request.Request): + """The single I/O seam (patched in tests).""" + return _opener.open(req, timeout=TIMEOUT) + + +def _check_address(host: str, port: int) -> None: + try: + infos = socket.getaddrinfo(host, port) + except (socket.gaierror, UnicodeError, OSError) as exc: + raise RegistrationError( + "Die Adresse der Plattform konnte nicht aufgelöst werden.", + detail=f"{host}: {exc}", + ) from exc + if not infos: + raise RegistrationError( + "Die Adresse der Plattform konnte nicht aufgelöst werden.", + detail=host, + ) + for info in infos: + raw = str(info[4][0]).split("%", 1)[0] + try: + ip = ipaddress.ip_address(raw) + except ValueError as exc: + raise RegistrationError( + "Die Adresse der Plattform ist ungültig.", detail=raw + ) from exc + if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped: + ip = ip.ipv4_mapped + if ip.is_loopback or ip.is_link_local or ip.is_unspecified: + raise RegistrationError( + "Die Adresse der Plattform zeigt auf einen nicht erlaubten " + "Bereich (lokal, link-lokal oder unspezifiziert).", + detail=f"{host} -> {raw}", + ) + + +def request_json( + url: str, *, bearer: str | None = None, payload: dict | None = None +) -> dict: + """GET ``url`` (POST JSON when ``payload`` is given); return the JSON + object of the answer or raise :class:`RegistrationError`.""" + allow_http = bool(conf.get("LTI_REGISTRATION_ALLOW_HTTP")) + scheme, host, port = _origin(url) + if scheme != "https" and not (allow_http and scheme == "http"): + raise RegistrationError( + "Die Adresse muss mit https:// beginnen.", detail=url + ) + if not host: + raise RegistrationError("Die Adresse ist ungültig.", detail=url) + if not allow_http: + _check_address(host, port or _default_port(scheme)) + + headers = {"Accept": "application/json"} + data = None + if payload is not None: + data = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + if bearer: + headers["Authorization"] = f"Bearer {bearer}" + req = urllib.request.Request( + url, data=data, headers=headers, method="POST" if data else "GET" + ) + + try: + with _open(req) as resp: + body = resp.read(MAX_BYTES + 1) + except RegistrationError: + raise + except urllib.error.HTTPError as exc: + try: + excerpt = exc.read(_DETAIL_CHARS * 4).decode("utf-8", "replace") + except Exception: # noqa: BLE001 - detail is best effort + excerpt = "" + raise RegistrationError( + f"Die Plattform hat die Anfrage abgelehnt (HTTP {exc.code}).", + detail=f"{exc.code} {url}: {excerpt[:_DETAIL_CHARS]}", + ) from exc + except (urllib.error.URLError, OSError, ValueError) as exc: + raise RegistrationError( + "Die Plattform ist nicht erreichbar.", detail=f"{url}: {exc}" + ) from exc + + if len(body) > MAX_BYTES: + raise RegistrationError( + "Die Antwort der Plattform ist zu groß.", detail=url + ) + try: + result = json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, ValueError) as exc: + raise RegistrationError( + "Die Plattform hat keine gültige JSON-Antwort geliefert.", + detail=body[:_DETAIL_CHARS].decode("utf-8", "replace"), + ) from exc + if not isinstance(result, dict): + raise RegistrationError( + "Die Plattform hat keine gültige JSON-Antwort geliefert.", + detail=body[:_DETAIL_CHARS].decode("utf-8", "replace"), + ) + return result diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py index 65fddb7..e332414 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -3,12 +3,18 @@ """Tests for LTI Dynamic Registration (token model, settings, ...).""" import hashlib +import io +import json +import urllib.error +import urllib.request from datetime import timedelta +from unittest import mock -from django.test import TestCase, override_settings +from django.test import SimpleTestCase, TestCase, override_settings from django.utils import timezone -from basicbar_lti import conf +from basicbar_lti import conf, dynreg_http +from basicbar_lti.dynreg_http import RegistrationError, request_json from basicbar_lti.models import LtiRegistrationToken @@ -57,3 +63,173 @@ def test_tool_registration_merges_flat(self): self.assertEqual( cfg["claims"], conf.DEFAULTS["LTI_TOOL_REGISTRATION"]["claims"] ) + + +def _addrinfo(*ips): + return lambda host, port, *a, **kw: [ + (2, 1, 6, "", (ip, port)) for ip in ips + ] + + +class _Resp: + def __init__(self, body): + self._body = io.BytesIO(body) + + def read(self, n=-1): + return self._body.read(n) + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + +class HttpClientTests(SimpleTestCase): + def _patch(self, ip="93.184.216.34", body=b"{}"): + gai = mock.patch("socket.getaddrinfo", side_effect=_addrinfo(ip)) + op = mock.patch.object( + dynreg_http, "_open", return_value=_Resp(body) + ) + return gai, op + + def test_rejects_http_by_default(self): + gai, op = self._patch() + with gai, op as opened: + with self.assertRaises(RegistrationError): + request_json("http://moodle.example.org/x") + opened.assert_not_called() + + @override_settings(LTI_REGISTRATION_ALLOW_HTTP=True) + def test_allow_http_setting(self): + gai, op = self._patch(ip="127.0.0.1") + with gai, op as opened: + self.assertEqual(request_json("http://localhost:8000/x"), {}) + opened.assert_called_once() + + def test_rejects_loopback_link_local_unspecified(self): + for ip in ( + "127.0.0.1", + "::1", + "169.254.169.254", + "fe80::1", + "fe80::1%eth0", + "0.0.0.0", + "::ffff:127.0.0.1", + ): + with self.subTest(ip=ip): + gai, op = self._patch(ip=ip) + with gai, op as opened: + with self.assertRaises(RegistrationError): + request_json("https://moodle.example.org/x") + opened.assert_not_called() + + def test_rejects_if_any_address_bad(self): + with mock.patch( + "socket.getaddrinfo", side_effect=_addrinfo("93.184.216.34", "::1") + ), mock.patch.object(dynreg_http, "_open") as opened: + with self.assertRaises(RegistrationError): + request_json("https://moodle.example.org/x") + opened.assert_not_called() + + def test_resolution_failure(self): + import socket + + with mock.patch( + "socket.getaddrinfo", side_effect=socket.gaierror("nope") + ), mock.patch.object(dynreg_http, "_open") as opened: + with self.assertRaises(RegistrationError): + request_json("https://moodle.example.org/x") + opened.assert_not_called() + + def test_allows_private_network(self): + gai, op = self._patch(ip="10.1.2.3", body=b'{"ok": true}') + with gai, op as opened: + self.assertEqual( + request_json("https://moodle.example.org/x"), {"ok": True} + ) + opened.assert_called_once() + + def test_bearer_and_post(self): + gai, op = self._patch() + with gai, op as opened: + request_json( + "https://moodle.example.org/x", bearer="t", payload={"a": 1} + ) + req = opened.call_args[0][0] + self.assertEqual(req.get_method(), "POST") + self.assertEqual(req.get_header("Authorization"), "Bearer t") + self.assertEqual(req.get_header("Content-type"), "application/json") + self.assertEqual(req.get_header("Accept"), "application/json") + self.assertEqual(json.loads(req.data), {"a": 1}) + + def test_get_without_payload(self): + gai, op = self._patch() + with gai, op as opened: + request_json("https://moodle.example.org/x") + req = opened.call_args[0][0] + self.assertEqual(req.get_method(), "GET") + self.assertFalse(req.has_header("Authorization")) + + def test_non_json_response(self): + gai, op = self._patch(body=b"Login") + with gai, op: + with self.assertRaises(RegistrationError) as cm: + request_json("https://moodle.example.org/x") + self.assertIn("JSON", str(cm.exception)) + + def test_json_not_object(self): + gai, op = self._patch(body=b"[1, 2]") + with gai, op: + with self.assertRaises(RegistrationError): + request_json("https://moodle.example.org/x") + + def test_http_error_status_in_message(self): + err = urllib.error.HTTPError( + "https://moodle.example.org/x", 401, "Unauthorized", {}, + io.BytesIO(b"secret body " * 100), + ) + with mock.patch( + "socket.getaddrinfo", side_effect=_addrinfo("93.184.216.34") + ), mock.patch.object(dynreg_http, "_open", side_effect=err): + with self.assertRaises(RegistrationError) as cm: + request_json("https://moodle.example.org/x") + self.assertIn("401", str(cm.exception)) + self.assertNotIn("secret", str(cm.exception)) + self.assertIn("secret", cm.exception.detail) + self.assertLessEqual(len(cm.exception.detail), 600) + + def test_url_error(self): + with mock.patch( + "socket.getaddrinfo", side_effect=_addrinfo("93.184.216.34") + ), mock.patch.object( + dynreg_http, "_open", side_effect=urllib.error.URLError("refused") + ): + with self.assertRaises(RegistrationError): + request_json("https://moodle.example.org/x") + + def test_too_large(self): + gai, op = self._patch(body=b" " * (dynreg_http.MAX_BYTES + 1)) + with gai, op: + with self.assertRaises(RegistrationError): + request_json("https://moodle.example.org/x") + + def test_cross_host_redirect_refused(self): + handler = dynreg_http._SameOriginRedirectHandler() + req = urllib.request.Request("https://moodle.example.org/a") + with self.assertRaises(RegistrationError): + handler.redirect_request( + req, None, 302, "Found", {}, + "https://evil.example.net/b", + ) + with self.assertRaises(RegistrationError): + handler.redirect_request( + req, None, 302, "Found", {}, + "http://moodle.example.org/b", + ) + new = handler.redirect_request( + req, None, 302, "Found", {}, + "https://moodle.example.org/b", + ) + self.assertIsInstance(new, urllib.request.Request) + self.assertEqual(new.full_url, "https://moodle.example.org/b") From bcd812dba25bab6cee656f4d5700319ae853af7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 14:42:21 +0100 Subject: [PATCH 3/9] =?UTF-8?q?fix(lti):=20Dynamic-Registration-HTTP-Clien?= =?UTF-8?q?t=20=E2=80=94=20weitere=20Fehlerpfade=20als=20RegistrationError?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../basicbar-lti/basicbar_lti/dynreg_http.py | 21 +++++++++++-- .../basicbar_lti/tests/test_dynreg.py | 30 +++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py b/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py index 63d2aa8..7979ef8 100644 --- a/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py +++ b/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py @@ -11,6 +11,7 @@ size, JSON objects only. Private networks stay allowed (on-prem Moodle). """ +import http.client import ipaddress import json import socket @@ -115,6 +116,17 @@ def request_json( ) if not host: raise RegistrationError("Die Adresse ist ungültig.", detail=url) + try: + parts = urlsplit(url) + parts.port # noqa: B018 - raises ValueError on a bad port + except ValueError as exc: + raise RegistrationError( + "Die Adresse ist ungültig.", detail=url + ) from exc + if parts.username is not None or parts.password is not None: + raise RegistrationError( + "Die Adresse darf keine Zugangsdaten enthalten.", detail=url + ) if not allow_http: _check_address(host, port or _default_port(scheme)) @@ -143,7 +155,12 @@ def request_json( f"Die Plattform hat die Anfrage abgelehnt (HTTP {exc.code}).", detail=f"{exc.code} {url}: {excerpt[:_DETAIL_CHARS]}", ) from exc - except (urllib.error.URLError, OSError, ValueError) as exc: + except ( + urllib.error.URLError, + http.client.HTTPException, + OSError, + ValueError, + ) as exc: raise RegistrationError( "Die Plattform ist nicht erreichbar.", detail=f"{url}: {exc}" ) from exc @@ -154,7 +171,7 @@ def request_json( ) try: result = json.loads(body.decode("utf-8")) - except (UnicodeDecodeError, ValueError) as exc: + except (UnicodeDecodeError, ValueError, RecursionError) as exc: raise RegistrationError( "Die Plattform hat keine gültige JSON-Antwort geliefert.", detail=body[:_DETAIL_CHARS].decode("utf-8", "replace"), diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py index e332414..352ba74 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -3,6 +3,7 @@ """Tests for LTI Dynamic Registration (token model, settings, ...).""" import hashlib +import http.client import io import json import urllib.error @@ -233,3 +234,32 @@ def test_cross_host_redirect_refused(self): ) self.assertIsInstance(new, urllib.request.Request) self.assertEqual(new.full_url, "https://moodle.example.org/b") + + def test_http_exception_becomes_registration_error(self): + with mock.patch( + "socket.getaddrinfo", side_effect=_addrinfo("93.184.216.34") + ), mock.patch.object( + dynreg_http, "_open", side_effect=http.client.BadStatusLine("x") + ): + with self.assertRaises(RegistrationError): + request_json("https://moodle.example.org/x") + + def test_deeply_nested_json(self): + gai, op = self._patch(body=b"[" * 100000) + with gai, op: + with self.assertRaises(RegistrationError): + request_json("https://moodle.example.org/x") + + def test_bad_port_rejected(self): + gai, op = self._patch() + with gai, op as opened: + with self.assertRaises(RegistrationError): + request_json("https://h:abc/") + opened.assert_not_called() + + def test_userinfo_rejected(self): + gai, op = self._patch() + with gai, op as opened: + with self.assertRaises(RegistrationError): + request_json("https://u:p@moodle.example.org/x") + opened.assert_not_called() From 2b6255d4d8692ea0408a44db50e6b47b00f33616 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 14:44:16 +0100 Subject: [PATCH 4/9] =?UTF-8?q?feat(lti):=20Registrierungslogik=20f=C3=BCr?= =?UTF-8?q?=20Dynamic=20Registration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../basicbar-lti/basicbar_lti/dynreg.py | 200 ++++++++++++++ .../basicbar_lti/tests/test_dynreg.py | 245 +++++++++++++++++- .../basicbar-lti/basicbar_lti/tests/urls.py | 6 + 3 files changed, 448 insertions(+), 3 deletions(-) create mode 100644 packages/django/basicbar-lti/basicbar_lti/dynreg.py diff --git a/packages/django/basicbar-lti/basicbar_lti/dynreg.py b/packages/django/basicbar-lti/basicbar_lti/dynreg.py new file mode 100644 index 0000000..da4a3d5 --- /dev/null +++ b/packages/django/basicbar-lti/basicbar_lti/dynreg.py @@ -0,0 +1,200 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""Dynamic Registration logic: validate the platform's OpenID configuration, +build the tool registration payload, register and create the platform.""" + +from dataclasses import dataclass +from urllib.parse import urlsplit + +from django.db import transaction +from django.urls import reverse +from django.utils import timezone + +from . import conf +from .dynreg_http import RegistrationError, request_json +from .models import LtiPlatform, LtiRegistrationToken + +LTI_TOOL_CONFIG = "https://purl.imsglobal.org/spec/lti-tool-configuration" +LTI_PLATFORM_CONFIG = "https://purl.imsglobal.org/spec/lti-platform-configuration" + +_REQUIRED = ( + "issuer", + "authorization_endpoint", + "token_endpoint", + "jwks_uri", + "registration_endpoint", +) +_ENDPOINTS = ( + "authorization_endpoint", + "token_endpoint", + "jwks_uri", + "registration_endpoint", +) + + +@dataclass(frozen=True) +class PlatformConfig: + issuer: str + authorization_endpoint: str + token_endpoint: str + jwks_uri: str + registration_endpoint: str + product_family_code: str = "" + + +def _netloc(url: str) -> str: + return urlsplit(url).netloc.lower() + + +def load_platform_config( + config_url: str, registration_token: str | None +) -> PlatformConfig: + """Fetch and validate the platform's OpenID configuration.""" + data = request_json(config_url, bearer=registration_token) + for key in _REQUIRED: + value = data.get(key) + if not isinstance(value, str) or not value: + raise RegistrationError( + "Die Konfiguration der Plattform ist unvollständig.", + f"missing or invalid field {key!r}", + ) + issuer = data["issuer"] + iss, cfg = urlsplit(issuer), urlsplit(config_url) + if ( + iss.scheme.lower() != cfg.scheme.lower() + or iss.netloc.lower() != cfg.netloc.lower() + or not cfg.path.startswith(iss.path.rstrip("/")) + ): + raise RegistrationError( + "Die Konfigurationsadresse passt nicht zur Kennung (issuer) der Plattform.", + f"config_url={config_url!r} issuer={issuer!r}", + ) + for key in _ENDPOINTS: + if _netloc(data[key]) != iss.netloc.lower(): + raise RegistrationError( + "Die Plattform nennt Endpunkte auf einem anderen Server; " + "das wird nicht akzeptiert.", + f"{key}={data[key]!r} issuer={issuer!r}", + ) + block = data.get(LTI_PLATFORM_CONFIG) + family = block.get("product_family_code") if isinstance(block, dict) else "" + return PlatformConfig( + issuer=issuer, + authorization_endpoint=data["authorization_endpoint"], + token_endpoint=data["token_endpoint"], + jwks_uri=data["jwks_uri"], + registration_endpoint=data["registration_endpoint"], + product_family_code=family if isinstance(family, str) else "", + ) + + +def tool_urls(request) -> dict: + return { + key: request.build_absolute_uri(reverse(name)) + for key, name in ( + ("login", "lti-login"), + ("launch", "lti-launch"), + ("jwks", "lti-jwks"), + ("register", "lti-register"), + ) + } + + +def tool_registration_payload(request) -> dict: + """The registration request body announcing this tool to the platform.""" + urls = tool_urls(request) + settings_ = conf.tool_registration() + logo_uri = "" + if settings_["logo_path"]: + logo_uri = request.build_absolute_uri(settings_["logo_path"]) + if not conf.get("LTI_REGISTRATION_ALLOW_HTTP"): + checked = [urls["login"], urls["launch"], urls["jwks"]] + if logo_uri: + checked.append(logo_uri) + if any(not u.lower().startswith("https://") for u in checked): + raise RegistrationError( + "Die Adressen dieses Tools sind nicht per https erreichbar. " + "Bitte den Betreiber informieren (Proxy-Konfiguration: " + "SECURE_PROXY_SSL_HEADER).", + f"non-https tool URLs: {checked}", + ) + launch = urls["launch"] + messages = [ + {**m, "target_link_uri": m.get("target_link_uri") or launch} + for m in settings_["messages"] + ] + payload = { + "application_type": "web", + "response_types": ["id_token"], + "grant_types": ["implicit", "client_credentials"], + "initiate_login_uri": urls["login"], + "redirect_uris": [launch], + "client_name": settings_["client_name"], + "jwks_uri": urls["jwks"], + "token_endpoint_auth_method": "private_key_jwt", + "scope": settings_["scope"], + LTI_TOOL_CONFIG: { + "domain": urlsplit(launch).netloc, + "target_link_uri": launch, + "claims": list(settings_["claims"]), + "description": settings_["description"], + "custom_parameters": dict(settings_["custom_parameters"]), + "messages": messages, + }, + } + if logo_uri: + payload["logo_uri"] = logo_uri + return payload + + +def known_issuer(config: PlatformConfig) -> bool: + issuer = config.issuer.rstrip("/") + return any( + p.issuer.rstrip("/") == issuer + for p in LtiPlatform.objects.filter(is_active=True) + ) + + +def register_platform( + request, + token: LtiRegistrationToken, + config: PlatformConfig, + registration_token: str | None, +) -> LtiPlatform: + """Register at the platform, create the ``LtiPlatform`` and consume the + token in one transaction; any failure leaves the token open.""" + with transaction.atomic(): + locked = LtiRegistrationToken.objects.select_for_update().get(pk=token.pk) + if locked.used_at is not None or locked.expires_at <= timezone.now(): + raise RegistrationError("Link bereits verwendet oder abgelaufen.") + response = request_json( + config.registration_endpoint, + bearer=registration_token, + payload=tool_registration_payload(request), + ) + client_id = response.get("client_id") + if not isinstance(client_id, str) or not client_id: + raise RegistrationError( + "Die Plattform hat keine client_id geliefert.", + f"response keys: {sorted(response)}", + ) + block = response.get(LTI_TOOL_CONFIG) + deployment_id = block.get("deployment_id") if isinstance(block, dict) else None + deployment_ids = [str(deployment_id)] if deployment_id not in (None, "") else [] + host = urlsplit(config.issuer).hostname or config.issuer + platform = LtiPlatform.objects.create( + name=locked.note or f"{config.product_family_code or 'LMS'} ({host})", + issuer=config.issuer, + client_id=client_id, + auth_login_url=config.authorization_endpoint, + auth_token_url=config.token_endpoint, + key_set_url=config.jwks_uri, + deployment_ids=deployment_ids, + is_active=True, + link_by_email=False, + ) + locked.used_at = timezone.now() + locked.platform = platform + locked.save(update_fields=["used_at", "platform"]) + return platform diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py index 352ba74..2ab5eef 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -11,12 +11,12 @@ from datetime import timedelta from unittest import mock -from django.test import SimpleTestCase, TestCase, override_settings +from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings from django.utils import timezone -from basicbar_lti import conf, dynreg_http +from basicbar_lti import conf, dynreg, dynreg_http from basicbar_lti.dynreg_http import RegistrationError, request_json -from basicbar_lti.models import LtiRegistrationToken +from basicbar_lti.models import LtiPlatform, LtiRegistrationToken class RegistrationTokenTests(TestCase): @@ -263,3 +263,242 @@ def test_userinfo_rejected(self): with self.assertRaises(RegistrationError): request_json("https://u:p@moodle.example.org/x") opened.assert_not_called() + + +ISSUER = "https://moodle.example.org" +CONFIG_URL = ISSUER + "/mod/lti/openid-configuration.php" +LTI_TOOL = "https://purl.imsglobal.org/spec/lti-tool-configuration" +LTI_PLATFORM = "https://purl.imsglobal.org/spec/lti-platform-configuration" + + +def moodle_config(**overrides): + config = { + "issuer": ISSUER, + "authorization_endpoint": ISSUER + "/mod/lti/auth.php", + "token_endpoint": ISSUER + "/mod/lti/token.php", + "jwks_uri": ISSUER + "/mod/lti/certs.php", + "registration_endpoint": ISSUER + "/mod/lti/openid-registration.php", + LTI_PLATFORM: {"product_family_code": "moodle"}, + } + config.update(overrides) + return config + + +def platform_config(**overrides): + return dynreg.PlatformConfig( + **{ + "issuer": ISSUER, + "authorization_endpoint": ISSUER + "/mod/lti/auth.php", + "token_endpoint": ISSUER + "/mod/lti/token.php", + "jwks_uri": ISSUER + "/mod/lti/certs.php", + "registration_endpoint": ISSUER + "/mod/lti/openid-registration.php", + "product_family_code": "moodle", + **overrides, + } + ) + + +def secure_request(): + return RequestFactory().get("/", secure=True) + + +class PlatformConfigTests(SimpleTestCase): + def load(self, config, url=CONFIG_URL, token="reg"): + with mock.patch("basicbar_lti.dynreg.request_json", return_value=config) as m: + result = dynreg.load_platform_config(url, token) + m.assert_called_once_with(url, bearer=token) + return result + + def test_config_ok(self): + cfg = self.load(moodle_config()) + self.assertEqual(cfg, platform_config()) + + def test_config_without_product_family(self): + config = moodle_config() + del config[LTI_PLATFORM] + self.assertEqual(self.load(config).product_family_code, "") + + def test_config_issuer_not_prefix(self): + with self.assertRaises(RegistrationError): + self.load(moodle_config(), url="https://evil.example/mod/lti/x.php") + + def test_config_issuer_host_lookalike(self): + with self.assertRaises(RegistrationError): + self.load( + moodle_config(), + url="https://moodle.example.org.evil.com/mod/lti/x.php", + ) + + def test_config_issuer_path_prefix(self): + issuer = "https://example.org/moodle" + config = moodle_config(issuer=issuer) + for key in ( + "authorization_endpoint", + "token_endpoint", + "jwks_uri", + "registration_endpoint", + ): + config[key] = "https://example.org/moodle/x.php" + self.load(config, url="https://example.org/moodle/openid-configuration.php") + with self.assertRaises(RegistrationError): + self.load(config, url="https://example.org/other/openid-configuration.php") + + def test_config_endpoint_other_host(self): + with self.assertRaises(RegistrationError): + self.load(moodle_config(jwks_uri="https://cdn.example.org/certs.php")) + + def test_config_missing_registration_endpoint(self): + config = moodle_config() + del config["registration_endpoint"] + with self.assertRaises(RegistrationError): + self.load(config) + + def test_config_non_string_field(self): + with self.assertRaises(RegistrationError): + self.load(moodle_config(token_endpoint=5)) + + +class PayloadTests(SimpleTestCase): + def test_payload_shape(self): + p = dynreg.tool_registration_payload(secure_request()) + self.assertEqual(p["application_type"], "web") + self.assertEqual(p["response_types"], ["id_token"]) + self.assertEqual(p["grant_types"], ["implicit", "client_credentials"]) + self.assertEqual(p["token_endpoint_auth_method"], "private_key_jwt") + self.assertEqual(p["initiate_login_uri"], "https://testserver/lti/login/") + self.assertEqual(p["redirect_uris"], ["https://testserver/lti/launch/"]) + self.assertEqual(p["jwks_uri"], "https://testserver/lti/jwks/") + self.assertNotIn("logo_uri", p) + block = p[LTI_TOOL] + self.assertEqual(block["domain"], "testserver") + self.assertEqual(block["target_link_uri"], "https://testserver/lti/launch/") + self.assertEqual( + block["messages"], + [ + { + "type": "LtiResourceLinkRequest", + "target_link_uri": "https://testserver/lti/launch/", + } + ], + ) + self.assertEqual(block["claims"], conf.tool_registration()["claims"]) + + @override_settings( + LTI_TOOL_REGISTRATION={ + "client_name": "abstimmbar", + "logo_path": "/lti/icon.svg", + "messages": [ + {"type": "LtiResourceLinkRequest"}, + {"type": "LtiDeepLinkingRequest", "label": "Raum wählen"}, + ], + } + ) + def test_payload_tool_settings(self): + p = dynreg.tool_registration_payload(secure_request()) + self.assertEqual(p["client_name"], "abstimmbar") + self.assertEqual(p["logo_uri"], "https://testserver/lti/icon.svg") + second = p[LTI_TOOL]["messages"][1] + self.assertEqual(second["target_link_uri"], "https://testserver/lti/launch/") + self.assertEqual(second["label"], "Raum wählen") + + def test_payload_refuses_http_tool_urls(self): + with self.assertRaises(RegistrationError) as cm: + dynreg.tool_registration_payload(RequestFactory().get("/")) + self.assertIn("SECURE_PROXY_SSL_HEADER", str(cm.exception)) + + @override_settings(LTI_REGISTRATION_ALLOW_HTTP=True) + def test_payload_allow_http(self): + p = dynreg.tool_registration_payload(RequestFactory().get("/")) + self.assertEqual(p["redirect_uris"], ["http://testserver/lti/launch/"]) + + +class RegisterTests(TestCase): + RESPONSE = {"client_id": "abc", LTI_TOOL: {"deployment_id": "7"}} + + def register(self, token, response=None, **kw): + with mock.patch( + "basicbar_lti.dynreg.request_json", + return_value=self.RESPONSE if response is None else response, + **kw, + ) as m: + platform = dynreg.register_platform( + secure_request(), token, platform_config(), "reg" + ) + return platform, m + + def test_register_creates_platform_and_consumes_token(self): + token, _ = LtiRegistrationToken.issue(note="Moodle Test") + platform, m = self.register(token) + self.assertEqual(platform.issuer, ISSUER) + self.assertEqual(platform.client_id, "abc") + self.assertEqual(platform.deployment_ids, ["7"]) + self.assertEqual(platform.auth_login_url, ISSUER + "/mod/lti/auth.php") + self.assertEqual(platform.auth_token_url, ISSUER + "/mod/lti/token.php") + self.assertEqual(platform.key_set_url, ISSUER + "/mod/lti/certs.php") + self.assertTrue(platform.is_active) + self.assertFalse(platform.link_by_email) + self.assertEqual(platform.name, "Moodle Test") + token.refresh_from_db() + self.assertEqual(token.status, "used") + self.assertEqual(token.platform, platform) + args, kwargs = m.call_args + self.assertEqual(args[0], ISSUER + "/mod/lti/openid-registration.php") + self.assertEqual(kwargs["bearer"], "reg") + self.assertEqual(kwargs["payload"]["application_type"], "web") + + def test_register_name_fallback(self): + token, _ = LtiRegistrationToken.issue() + platform, _ = self.register(token) + self.assertEqual(platform.name, "moodle (moodle.example.org)") + + def test_register_without_deployment_id(self): + token, _ = LtiRegistrationToken.issue() + platform, _ = self.register(token, response={"client_id": "abc"}) + self.assertEqual(platform.deployment_ids, []) + + def test_register_lms_error_keeps_token_open(self): + token, _ = LtiRegistrationToken.issue() + with self.assertRaises(RegistrationError): + self.register(token, side_effect=RegistrationError("nope")) + self.assertEqual(LtiPlatform.objects.count(), 0) + token.refresh_from_db() + self.assertEqual(token.status, "open") + + def test_register_missing_client_id_keeps_token_open(self): + token, _ = LtiRegistrationToken.issue() + with self.assertRaises(RegistrationError): + self.register(token, response={LTI_TOOL: {"deployment_id": "7"}}) + self.assertEqual(LtiPlatform.objects.count(), 0) + token.refresh_from_db() + self.assertEqual(token.status, "open") + + def test_register_used_token_refused(self): + token, _ = LtiRegistrationToken.issue() + LtiRegistrationToken.objects.filter(pk=token.pk).update( + used_at=timezone.now() + ) + with self.assertRaises(RegistrationError): + self.register(token) + # request_json must not have been called + with mock.patch("basicbar_lti.dynreg.request_json") as m: + with self.assertRaises(RegistrationError): + dynreg.register_platform( + secure_request(), token, platform_config(), "reg" + ) + m.assert_not_called() + + def test_known_issuer(self): + cfg = platform_config() + self.assertFalse(dynreg.known_issuer(cfg)) + platform = LtiPlatform.objects.create( + name="x", + issuer=ISSUER + "/", + client_id="c", + auth_login_url=ISSUER + "/a", + auth_token_url=ISSUER + "/t", + is_active=False, + ) + self.assertFalse(dynreg.known_issuer(cfg)) + platform.is_active = True + platform.save() + self.assertTrue(dynreg.known_issuer(cfg)) diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/urls.py b/packages/django/basicbar-lti/basicbar_lti/tests/urls.py index 2cc3448..226a0bc 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/urls.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/urls.py @@ -35,6 +35,11 @@ def test_launch(request): return JsonResponse({"instructor": False}) +def lti_register(request): + """Placeholder; the real registration view arrives with Dynamic Registration.""" + return HttpResponse("register") + + def embeddable_page(request): return HttpResponse("embed me") @@ -46,6 +51,7 @@ def embeddable_page(request): path("lti/login/", lti_login, name="lti-login"), path("lti/launch/", test_launch, name="lti-launch"), path("lti/jwks/", lti_jwks, name="lti-jwks"), + path("lti/register/", lti_register, name="lti-register"), path("lti/page/", embeddable_page, name="lti-test-page"), path("api/lti/tool-info/", LtiToolInfoView.as_view(), name="lti-tool-info"), path("api/lti/", include(router.urls)), From b040d50e50934bf11e2ac1ea2aec5cf3fb546555 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 14:46:52 +0100 Subject: [PATCH 5/9] =?UTF-8?q?fix(lti):=20L=C3=A4ngenpr=C3=BCfung=20und?= =?UTF-8?q?=20Duplikat-Fehler=20in=20der=20Registrierungslogik?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../basicbar-lti/basicbar_lti/dynreg.py | 41 ++++++++++++++++- .../basicbar_lti/tests/test_dynreg.py | 44 +++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/packages/django/basicbar-lti/basicbar_lti/dynreg.py b/packages/django/basicbar-lti/basicbar_lti/dynreg.py index da4a3d5..f710fc6 100644 --- a/packages/django/basicbar-lti/basicbar_lti/dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/dynreg.py @@ -7,7 +7,7 @@ from dataclasses import dataclass from urllib.parse import urlsplit -from django.db import transaction +from django.db import IntegrityError, transaction from django.urls import reverse from django.utils import timezone @@ -33,6 +33,20 @@ ) +# config field -> LtiPlatform column it is stored in (length limits come +# from the model, SQLite would not enforce them). +_COLUMNS = { + "issuer": "issuer", + "authorization_endpoint": "auth_login_url", + "token_endpoint": "auth_token_url", + "jwks_uri": "key_set_url", +} + + +def _max_len(column: str) -> int: + return LtiPlatform._meta.get_field(column).max_length + + @dataclass(frozen=True) class PlatformConfig: issuer: str @@ -59,6 +73,12 @@ def load_platform_config( "Die Konfiguration der Plattform ist unvollständig.", f"missing or invalid field {key!r}", ) + for key, column in _COLUMNS.items(): + if len(data[key]) > _max_len(column): + raise RegistrationError( + "Die Konfiguration der Plattform enthält zu lange Werte.", + f"{key} longer than {_max_len(column)} characters", + ) issuer = data["issuer"] iss, cfg = urlsplit(issuer), urlsplit(config_url) if ( @@ -164,6 +184,16 @@ def register_platform( ) -> LtiPlatform: """Register at the platform, create the ``LtiPlatform`` and consume the token in one transaction; any failure leaves the token open.""" + try: + return _register(request, token, config, registration_token) + except IntegrityError as exc: + raise RegistrationError( + "Diese Plattform ist bereits mit diesem Tool registriert.", + f"IntegrityError: {exc}", + ) from exc + + +def _register(request, token, config, registration_token) -> LtiPlatform: with transaction.atomic(): locked = LtiRegistrationToken.objects.select_for_update().get(pk=token.pk) if locked.used_at is not None or locked.expires_at <= timezone.now(): @@ -179,12 +209,19 @@ def register_platform( "Die Plattform hat keine client_id geliefert.", f"response keys: {sorted(response)}", ) + if len(client_id) > _max_len("client_id"): + raise RegistrationError( + "Die Plattform hat eine zu lange client_id geliefert.", + f"client_id longer than {_max_len('client_id')} characters", + ) block = response.get(LTI_TOOL_CONFIG) deployment_id = block.get("deployment_id") if isinstance(block, dict) else None deployment_ids = [str(deployment_id)] if deployment_id not in (None, "") else [] host = urlsplit(config.issuer).hostname or config.issuer platform = LtiPlatform.objects.create( - name=locked.note or f"{config.product_family_code or 'LMS'} ({host})", + name=( + locked.note or f"{config.product_family_code or 'LMS'} ({host})" + )[: _max_len("name")], issuer=config.issuer, client_id=client_id, auth_login_url=config.authorization_endpoint, diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py index 2ab5eef..c5e257c 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -353,6 +353,14 @@ def test_config_missing_registration_endpoint(self): with self.assertRaises(RegistrationError): self.load(config) + def test_config_overlong_values(self): + long = ISSUER + "/" + "x" * 600 + for key in ("authorization_endpoint", "token_endpoint", "jwks_uri"): + with self.assertRaises(RegistrationError): + self.load(moodle_config(**{key: long})) + with self.assertRaises(RegistrationError): + self.load(moodle_config(issuer=ISSUER + "/" + "x" * 600)) + def test_config_non_string_field(self): with self.assertRaises(RegistrationError): self.load(moodle_config(token_endpoint=5)) @@ -472,6 +480,42 @@ def test_register_missing_client_id_keeps_token_open(self): token.refresh_from_db() self.assertEqual(token.status, "open") + def test_register_overlong_client_id_keeps_token_open(self): + token, _ = LtiRegistrationToken.issue() + with self.assertRaises(RegistrationError): + self.register(token, response={"client_id": "x" * 300}) + self.assertEqual(LtiPlatform.objects.count(), 0) + token.refresh_from_db() + self.assertEqual(token.status, "open") + + def test_register_long_fallback_name_fits(self): + token, _ = LtiRegistrationToken.issue() + with mock.patch( + "basicbar_lti.dynreg.request_json", return_value=self.RESPONSE + ): + platform = dynreg.register_platform( + secure_request(), + token, + platform_config(product_family_code="m" * 400), + "reg", + ) + self.assertLessEqual(len(platform.name), 200) + + def test_register_duplicate_platform_keeps_token_open(self): + LtiPlatform.objects.create( + name="x", + issuer=ISSUER, + client_id="abc", + auth_login_url=ISSUER + "/a", + auth_token_url=ISSUER + "/t", + ) + token, _ = LtiRegistrationToken.issue() + with self.assertRaises(RegistrationError): + self.register(token) + self.assertEqual(LtiPlatform.objects.count(), 1) + token.refresh_from_db() + self.assertEqual(token.status, "open") + def test_register_used_token_refused(self): token, _ = LtiRegistrationToken.issue() LtiRegistrationToken.objects.filter(pk=token.pk).update( From c4a4b7e0e35b3772a37cfd41d471dfc7adc3dc33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 14:49:19 +0100 Subject: [PATCH 6/9] feat(lti): Registrierungsseite lti_register mit eng gefasstem Einbetten Co-Authored-By: Claude Opus 5.5 --- .../django/basicbar-lti/basicbar_lti/apps.py | 3 + .../basicbar-lti/basicbar_lti/checks.py | 25 ++ .../basicbar-lti/basicbar_lti/dynreg_pages.py | 43 ++++ .../basicbar-lti/basicbar_lti/middleware.py | 7 +- .../basicbar_lti/tests/test_dynreg.py | 235 ++++++++++++++++++ .../basicbar-lti/basicbar_lti/tests/urls.py | 7 +- .../django/basicbar-lti/basicbar_lti/views.py | 137 +++++++++- 7 files changed, 448 insertions(+), 9 deletions(-) create mode 100644 packages/django/basicbar-lti/basicbar_lti/checks.py create mode 100644 packages/django/basicbar-lti/basicbar_lti/dynreg_pages.py diff --git a/packages/django/basicbar-lti/basicbar_lti/apps.py b/packages/django/basicbar-lti/basicbar_lti/apps.py index 6f6578f..b46b47b 100644 --- a/packages/django/basicbar-lti/basicbar_lti/apps.py +++ b/packages/django/basicbar-lti/basicbar_lti/apps.py @@ -8,3 +8,6 @@ class BasicbarLtiConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "basicbar_lti" verbose_name = "Basicbar LTI" + + def ready(self): + from . import checks # noqa: F401 (registers the system checks) diff --git a/packages/django/basicbar-lti/basicbar_lti/checks.py b/packages/django/basicbar-lti/basicbar_lti/checks.py new file mode 100644 index 0000000..7152194 --- /dev/null +++ b/packages/django/basicbar-lti/basicbar_lti/checks.py @@ -0,0 +1,25 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""System checks for the Dynamic Registration settings.""" +from django.conf import settings +from django.core.checks import Warning, register + +from . import conf + + +@register() +def check_registration_settings(app_configs, **kwargs): + if conf.get("LTI_REGISTRATION_ALLOW_HTTP") and not settings.DEBUG: + return [ + Warning( + "LTI_REGISTRATION_ALLOW_HTTP is enabled while DEBUG is off.", + hint=( + "LTI_REGISTRATION_ALLOW_HTTP allows http:// and " + "loopback/link-local targets for Dynamic Registration; " + "use it for local development only." + ), + id="basicbar_lti.W001", + ) + ] + return [] diff --git a/packages/django/basicbar-lti/basicbar_lti/dynreg_pages.py b/packages/django/basicbar-lti/basicbar_lti/dynreg_pages.py new file mode 100644 index 0000000..1324617 --- /dev/null +++ b/packages/django/basicbar-lti/basicbar_lti/dynreg_pages.py @@ -0,0 +1,43 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""Minimal bilingual HTML pages for the Dynamic Registration view. + +Every dynamic value goes through format_html/escape; the inline +scripts contain no dynamic values. +""" +from django.utils.html import format_html +from django.utils.safestring import mark_safe + +# Tells the platform to close the registration iframe/window (IMS LTI DR). +_CLOSE_MESSAGE = ( + '(window.opener || window.parent).postMessage(' + '{subject: "org.imsglobal.lti.close"}, "*");' +) + +CLOSE_SCRIPT = mark_safe(f"") # noqa: S308 + +# Wires the "Abbrechen" button (id=cancel) to the close message. +CANCEL_SCRIPT = mark_safe( # noqa: S308 + '" +) + + +def page(title_de, title_en, body_html, *, close=False): + """A complete HTML document; body_html must already be safe HTML.""" + return format_html( + '' + '' + "{} / {}" + "" + "

{}

{}

{}{}", + title_de, + title_en, + title_de, + title_en, + body_html, + CLOSE_SCRIPT if close else "", + ) diff --git a/packages/django/basicbar-lti/basicbar_lti/middleware.py b/packages/django/basicbar-lti/basicbar_lti/middleware.py index 05a4662..9e1eb0c 100644 --- a/packages/django/basicbar-lti/basicbar_lti/middleware.py +++ b/packages/django/basicbar-lti/basicbar_lti/middleware.py @@ -56,7 +56,10 @@ def __call__(self, request): ct = response.get("Content-Type", "") prefixes = tuple(conf.get("LTI_FRAME_PATH_PREFIXES")) if ct.startswith("text/html") and request.path.startswith(prefixes): - ancestors = " ".join(["'self'", *_lms_origins()]) - response["Content-Security-Policy"] = f"frame-ancestors {ancestors}" + # A view may already have set a narrower policy (the Dynamic + # Registration page); keep it, only drop X-Frame-Options. + if "frame-ancestors" not in response.get("Content-Security-Policy", ""): + ancestors = " ".join(["'self'", *_lms_origins()]) + response["Content-Security-Policy"] = f"frame-ancestors {ancestors}" response.headers.pop("X-Frame-Options", None) return response diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py index c5e257c..b04b8dc 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -546,3 +546,238 @@ def test_known_issuer(self): platform.is_active = True platform.save() self.assertTrue(dynreg.known_issuer(cfg)) + + +class RegisterViewTests(TestCase): + RESPONSE = {"client_id": "abc", LTI_TOOL: {"deployment_id": "7"}} + + def setUp(self): + self.token, self.raw = LtiRegistrationToken.issue(note="Moodle Test") + + def params(self, **overrides): + params = { + "token": self.raw, + "openid_configuration": CONFIG_URL, + "registration_token": "rt", + } + params.update(overrides) + return {k: v for k, v in params.items() if v is not None} + + def get(self, **overrides): + return self.client.get("/lti/register/", self.params(**overrides), secure=True) + + def post(self, **overrides): + return self.client.post( + "/lti/register/", self.params(**overrides), secure=True + ) + + def patched(self, *side_effect): + return mock.patch( + "basicbar_lti.dynreg.request_json", side_effect=list(side_effect) + ) + + def test_invalid_token_403_no_request(self): + with self.patched() as m: + response = self.get(token="nope") + self.assertEqual(response.status_code, 403) + self.assertIn("Link ungültig", response.content.decode()) + m.assert_not_called() + + def test_used_token_403_no_request(self): + self.token.used_at = timezone.now() + self.token.save() + with self.patched() as m: + response = self.get() + self.assertEqual(response.status_code, 403) + m.assert_not_called() + + def test_missing_openid_configuration_400(self): + with self.patched() as m: + response = self.get(openid_configuration=None) + self.assertEqual(response.status_code, 400) + self.assertIn("Tool-URL", response.content.decode()) + m.assert_not_called() + + def test_success_creates_platform_and_closes(self): + with self.patched(moodle_config(), self.RESPONSE) as m: + response = self.get() + self.assertEqual(response.status_code, 200) + body = response.content.decode() + self.assertIn("org.imsglobal.lti.close", body) + self.assertIn("Neues Fenster", body) + self.assertEqual(m.call_count, 2) + self.assertTrue(LtiPlatform.objects.filter(issuer=ISSUER).exists()) + self.token.refresh_from_db() + self.assertEqual(self.token.status, "used") + + def test_success_without_deployment_warns(self): + with self.patched(moodle_config(), {"client_id": "abc"}): + response = self.get() + self.assertEqual(response.status_code, 200) + self.assertIn("Deployment-ID", response.content.decode()) + + def test_success_with_deployment_has_no_warning(self): + with self.patched(moodle_config(), self.RESPONSE): + response = self.get() + self.assertNotIn("Deployment-ID", response.content.decode()) + + def test_config_error_502(self): + with self.patched(RegistrationError("Konfig kaputt")) as m: + response = self.get() + self.assertEqual(response.status_code, 502) + self.assertIn("Konfig kaputt", response.content.decode()) + self.assertEqual(m.call_count, 1) + self.token.refresh_from_db() + self.assertEqual(self.token.status, "open") + + def test_lms_error_502_token_open(self): + with self.patched(moodle_config(), RegistrationError("LMS sagt nein")): + response = self.get() + self.assertEqual(response.status_code, 502) + self.assertIn("LMS sagt nein", response.content.decode()) + self.token.refresh_from_db() + self.assertEqual(self.token.status, "open") + self.assertFalse(LtiPlatform.objects.exists()) + + def _known(self): + LtiPlatform.objects.create( + name="alt", + issuer=ISSUER, + client_id="old", + auth_login_url=ISSUER + "/a", + auth_token_url=ISSUER + "/t", + ) + + def test_known_issuer_asks_first(self): + self._known() + with self.patched(moodle_config()) as m: + response = self.get() + self.assertEqual(response.status_code, 200) + body = response.content.decode() + self.assertIn('name="confirm"', body) + self.assertIn("bestehende Verknüpfung", body) + self.assertEqual(m.call_count, 1) + self.assertEqual(LtiPlatform.objects.count(), 1) + self.token.refresh_from_db() + self.assertEqual(self.token.status, "open") + with self.patched(moodle_config(), self.RESPONSE): + response = self.post(confirm="1") + self.assertEqual(response.status_code, 200) + self.assertEqual(LtiPlatform.objects.count(), 2) + + def test_post_without_confirm_asks_first(self): + self._known() + with self.patched(moodle_config()): + response = self.post() + self.assertIn('name="confirm"', response.content.decode()) + self.assertEqual(LtiPlatform.objects.count(), 1) + + def test_cancel_does_not_consume(self): + self._known() + with self.patched(moodle_config()): + response = self.get() + body = response.content.decode() + self.assertIn("org.imsglobal.lti.close", body) + self.assertIn('type="button"', body) + self.assertNotIn(" onclick", body) + self.token.refresh_from_db() + self.assertEqual(self.token.status, "open") + + def test_values_are_escaped(self): + evil = "" + self.token.note = evil + self.token.save() + with self.patched(moodle_config(), self.RESPONSE): + ok = self.get() + self.assertNotIn(evil, ok.content.decode()) + self.assertIn("<script>x</script>", ok.content.decode()) + # confirm page: hidden fields and URLs + self._known() + with self.patched(moodle_config()): + asks = self.get(registration_token='">') + self.assertNotIn(evil, asks.content.decode()) + # error page (the first token was consumed by the success above) + _, self.raw = LtiRegistrationToken.issue() + with self.patched(RegistrationError(evil)): + err = self.get() + self.assertNotIn(evil, err.content.decode()) + self.assertIn("<script>", err.content.decode()) + + def test_error_is_logged(self): + with self.patched(RegistrationError("kaputt", "detail-xyz")): + with self.assertLogs("basicbar_lti.views", "WARNING") as logs: + self.get() + self.assertIn("detail-xyz", logs.output[0]) + + +class FrameAncestorsRegisterTests(TestCase): + def setUp(self): + self.token, self.raw = LtiRegistrationToken.issue() + + def get(self, **overrides): + params = {"token": self.raw, "openid_configuration": CONFIG_URL} + params.update(overrides) + with mock.patch( + "basicbar_lti.dynreg.request_json", + side_effect=[ + moodle_config(), + {"client_id": "abc", LTI_TOOL: {"deployment_id": "7"}}, + ], + ): + return self.client.get("/lti/register/", params, secure=True) + + def test_valid_token_allows_config_origin(self): + response = self.get() + self.assertEqual( + response["Content-Security-Policy"], + "frame-ancestors 'self' https://moodle.example.org", + ) + self.assertNotIn("X-Frame-Options", response) + + def test_error_page_also_allows_origin(self): + with mock.patch( + "basicbar_lti.dynreg.request_json", side_effect=RegistrationError("x") + ): + response = self.client.get( + "/lti/register/", + {"token": self.raw, "openid_configuration": CONFIG_URL}, + secure=True, + ) + self.assertEqual(response.status_code, 502) + self.assertIn("moodle.example.org", response["Content-Security-Policy"]) + + def test_invalid_token_keeps_default_policy(self): + response = self.get(token="nope") + self.assertNotIn("moodle.example.org", response["Content-Security-Policy"]) + self.assertNotIn("X-Frame-Options", response) + + def test_invalid_origin_keeps_default_policy(self): + response = self.get(openid_configuration="https://evil.example; x/y") + self.assertNotIn("evil", response["Content-Security-Policy"]) + self.assertNotIn(";x", response["Content-Security-Policy"]) + + def test_other_lti_pages_unchanged(self): + response = self.client.get("/lti/page/") + self.assertEqual(response["Content-Security-Policy"], "frame-ancestors 'self'") + self.assertNotIn("X-Frame-Options", response) + + +class CheckTests(SimpleTestCase): + def run_checks(self): + from basicbar_lti.checks import check_registration_settings + + return check_registration_settings(None) + + @override_settings(LTI_REGISTRATION_ALLOW_HTTP=True, DEBUG=False) + def test_w001(self): + messages = self.run_checks() + self.assertEqual([m.id for m in messages], ["basicbar_lti.W001"]) + self.assertIn("LTI_REGISTRATION_ALLOW_HTTP", messages[0].hint) + + @override_settings(LTI_REGISTRATION_ALLOW_HTTP=True, DEBUG=True) + def test_no_warning_in_debug(self): + self.assertEqual(self.run_checks(), []) + + @override_settings(LTI_REGISTRATION_ALLOW_HTTP=False, DEBUG=False) + def test_no_warning_by_default(self): + self.assertEqual(self.run_checks(), []) diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/urls.py b/packages/django/basicbar-lti/basicbar_lti/tests/urls.py index 226a0bc..7b8f935 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/urls.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/urls.py @@ -16,7 +16,7 @@ provision_user, ) from basicbar_lti.tool_conf import build_tool_conf -from basicbar_lti.views import LtiPlatformViewSet, LtiToolInfoView, lti_jwks, lti_login +from basicbar_lti.views import LtiPlatformViewSet, LtiToolInfoView, lti_jwks, lti_login, lti_register @csrf_exempt @@ -35,11 +35,6 @@ def test_launch(request): return JsonResponse({"instructor": False}) -def lti_register(request): - """Placeholder; the real registration view arrives with Dynamic Registration.""" - return HttpResponse("register") - - def embeddable_page(request): return HttpResponse("embed me") diff --git a/packages/django/basicbar-lti/basicbar_lti/views.py b/packages/django/basicbar-lti/basicbar_lti/views.py index 1477b36..fbed5bf 100644 --- a/packages/django/basicbar-lti/basicbar_lti/views.py +++ b/packages/django/basicbar-lti/basicbar_lti/views.py @@ -8,9 +8,12 @@ primitives in :mod:`basicbar_lti.provisioning` and :mod:`.tool_conf`. """ import logging +from urllib.parse import urlsplit from django.conf import settings from django.http import HttpResponse, JsonResponse +from django.utils.html import format_html +from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_exempt from pylti1p3.contrib.django import DjangoOIDCLogin from pylti1p3.exception import LtiException, OIDCException @@ -19,7 +22,11 @@ from rest_framework.response import Response from rest_framework.views import APIView -from .models import LtiPlatform +from . import dynreg +from .dynreg_http import RegistrationError +from .dynreg_pages import CANCEL_SCRIPT, page +from .middleware import _ORIGIN_RE +from .models import LtiPlatform, LtiRegistrationToken from .provisioning import launch_storage from .serializers import LtiPlatformSerializer from .tool_conf import build_tool_conf @@ -134,3 +141,131 @@ def get(self, request): "jwks_url": f"{base}/lti/jwks/", "icon_url": f"{base}/lti/icon.svg", }) + + +def _register_param(request, key): + return request.POST.get(key, request.GET.get(key, "")) + + +def _config_origin(url): + try: + parts = urlsplit(url) + except ValueError: + return None + origin = f"{parts.scheme}://{parts.netloc}" + return origin if _ORIGIN_RE.match(origin) else None + + +def _register_response(status, title_de, title_en, body, origin, **kw): + response = HttpResponse(page(title_de, title_en, body, **kw), status=status) + if origin: + response["Content-Security-Policy"] = f"frame-ancestors 'self' {origin}" + return response + + +def _error_page(status, de, en, origin): + body = format_html("

{}

{}

", de, en) + return _register_response(status, "Registrierung", "Registration", body, origin) + + +@csrf_exempt +def lti_register(request): + """Dynamic Registration endpoint the LMS admin's browser opens. + + Parameter parsing, branching and page rendering only; the registration + itself lives in :mod:`basicbar_lti.dynreg`. + """ + raw = _register_param(request, "token") + config_url = _register_param(request, "openid_configuration") + registration_token = _register_param(request, "registration_token") + confirm = bool(_register_param(request, "confirm")) + + token = LtiRegistrationToken.find_valid(raw) + if token is None: + return _error_page( + 403, + "Link ungültig, bereits verwendet oder abgelaufen — " + "neuen Link beim Tool-Admin anfordern.", + "Link invalid, already used or expired — request a new link " + "from the tool admin.", + None, + ) + origin = _config_origin(config_url) + if not config_url: + return _error_page( + 400, + "Diese Adresse in Moodle als Tool-URL eintragen " + "(Externe Tools → Tools verwalten).", + "Enter this address in Moodle as the tool URL " + "(External tools → Manage tools).", + origin, + ) + + try: + config = dynreg.load_platform_config(config_url, registration_token) + if dynreg.known_issuer(config) and not confirm: + return _confirm_page(raw, config_url, registration_token, origin) + platform = dynreg.register_platform(request, token, config, registration_token) + except RegistrationError as exc: + logger.warning( + "LTI registration failed (config=%r): %s %s", config_url, exc, exc.detail + ) + return _error_page(502, str(exc), "Registration failed.", origin) + + body = format_html( + "

Registrierung abgeschlossen ({}). Nächste Schritte in Moodle: " + "Tool aktivieren; Tool bearbeiten → Standard-Startcontainer " + "„Neues Fenster“.

" + "

Registration complete. Next steps in Moodle: " + "activate the tool; edit the tool → default launch container " + "“New window”.

", + platform.name, + ) + if not platform.deployment_ids: + body += mark_safe( # noqa: S308 — static text, no dynamic values + "

Das LMS hat keine Deployment-ID geliefert — im Tool-Admin " + "nachtragen.

" + "

The LMS did not provide a deployment ID — add " + "it in the tool admin.

" + ) + return _register_response( + 200, "Registrierung abgeschlossen", "Registration complete", body, + origin, close=True, + ) + + +def _confirm_page(raw, config_url, registration_token, origin): + body = format_html( + "

Für {} gibt es bereits eine aktive Verknüpfung. Eine neue " + "Registrierung legt eine zweite an; die bestehende Verknüpfung wird " + "nicht übernommen (Kursverknüpfungen und Konten hängen an der " + "alten).

" + "

An active registration already exists for this " + "platform. A new registration creates a second one; the existing " + "registration is not taken over (course links and accounts stay " + "attached to the old one).

" + "
" + "" + "" + "" + "" + "" + "" + "
{}", + _origin_label(config_url), + raw, + config_url, + registration_token, + CANCEL_SCRIPT, + ) + return _register_response( + 200, "Registrierung bestätigen", "Confirm registration", body, origin + ) + + +def _origin_label(config_url): + try: + return urlsplit(config_url).netloc or config_url + except ValueError: + return config_url From c32fa6cd577db899f606f516dbc7686fe2a5dc7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 15:52:25 +0100 Subject: [PATCH 7/9] =?UTF-8?q?fix(lti):=20Registrierungsfehler=20als=2040?= =?UTF-8?q?0,=20Escaping-Test=20erreicht=20die=20Best=C3=A4tigungsseite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../basicbar_lti/tests/test_dynreg.py | 22 +++++++++++++------ .../django/basicbar-lti/basicbar_lti/views.py | 2 +- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py index b04b8dc..43c9c61 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -621,19 +621,19 @@ def test_success_with_deployment_has_no_warning(self): response = self.get() self.assertNotIn("Deployment-ID", response.content.decode()) - def test_config_error_502(self): + def test_config_error_400(self): with self.patched(RegistrationError("Konfig kaputt")) as m: response = self.get() - self.assertEqual(response.status_code, 502) + self.assertEqual(response.status_code, 400) self.assertIn("Konfig kaputt", response.content.decode()) self.assertEqual(m.call_count, 1) self.token.refresh_from_db() self.assertEqual(self.token.status, "open") - def test_lms_error_502_token_open(self): + def test_lms_error_400_token_open(self): with self.patched(moodle_config(), RegistrationError("LMS sagt nein")): response = self.get() - self.assertEqual(response.status_code, 502) + self.assertEqual(response.status_code, 400) self.assertIn("LMS sagt nein", response.content.decode()) self.token.refresh_from_db() self.assertEqual(self.token.status, "open") @@ -693,9 +693,17 @@ def test_values_are_escaped(self): self.assertIn("<script>x</script>", ok.content.decode()) # confirm page: hidden fields and URLs self._known() + _, self.raw = LtiRegistrationToken.issue() with self.patched(moodle_config()): - asks = self.get(registration_token='">') - self.assertNotIn(evil, asks.content.decode()) + asks = self.get( + registration_token='">', + openid_configuration=CONFIG_URL + '?a=">', + ) + asks_body = asks.content.decode() + self.assertEqual(asks.status_code, 200) + self.assertIn('name="confirm"', asks_body) + self.assertNotIn(evil, asks_body) + self.assertIn(""><script>", asks_body) # error page (the first token was consumed by the success above) _, self.raw = LtiRegistrationToken.issue() with self.patched(RegistrationError(evil)): @@ -743,7 +751,7 @@ def test_error_page_also_allows_origin(self): {"token": self.raw, "openid_configuration": CONFIG_URL}, secure=True, ) - self.assertEqual(response.status_code, 502) + self.assertEqual(response.status_code, 400) self.assertIn("moodle.example.org", response["Content-Security-Policy"]) def test_invalid_token_keeps_default_policy(self): diff --git a/packages/django/basicbar-lti/basicbar_lti/views.py b/packages/django/basicbar-lti/basicbar_lti/views.py index fbed5bf..a69de68 100644 --- a/packages/django/basicbar-lti/basicbar_lti/views.py +++ b/packages/django/basicbar-lti/basicbar_lti/views.py @@ -210,7 +210,7 @@ def lti_register(request): logger.warning( "LTI registration failed (config=%r): %s %s", config_url, exc, exc.detail ) - return _error_page(502, str(exc), "Registration failed.", origin) + return _error_page(400, str(exc), "Registration failed.", origin) body = format_html( "

Registrierung abgeschlossen ({}). Nächste Schritte in Moodle: " From 0e256168f0636659ca620b72af632079212fcf91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 15:54:58 +0100 Subject: [PATCH 8/9] =?UTF-8?q?feat(lti):=20Token-API,=20Tool-Info=20per?= =?UTF-8?q?=20reverse,=20Doku=20=E2=80=94=20basicbar-lti=200.2.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 40 +++++++ CLAUDE.md | 3 +- packages/django/basicbar-lti/README.md | 109 +++++++++++++++++- .../basicbar-lti/basicbar_lti/serializers.py | 22 +++- .../basicbar_lti/tests/test_dynreg.py | 84 ++++++++++++++ .../basicbar_lti/tests/test_lti.py | 4 +- .../basicbar-lti/basicbar_lti/tests/urls.py | 12 +- .../django/basicbar-lti/basicbar_lti/views.py | 62 ++++++++-- packages/django/basicbar-lti/pyproject.toml | 2 +- 9 files changed, 320 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13c9ff9..83606e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,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-lti (→ wird `lti/v0.2.0`) + +**Dynamic Registration:** Der LMS-Admin trägt einen Einmal-Link des Tools in +Moodle ein, Tool und Moodle tauschen alle Werte selbst aus (Details und +Sicherheitsmodell im README). Nur für neue Verknüpfungen; die manuelle +Registrierung bleibt. Ohne Verdrahtung ändert sich nichts. + +- Neu: Model `LtiRegistrationToken` (Migration `0002`, nur SHA-256-Hash), + View `lti_register`, `LtiRegistrationTokenViewSet` (Create liefert die URL + einmal, `list` ohne Token, `destroy` nur für offene Links), + Settings `LTI_REGISTRATION_TOKEN_TTL`, `LTI_REGISTRATION_ALLOW_HTTP`, + `LTI_TOOL_REGISTRATION`, System-Check `basicbar_lti.W001`. +- Geändert: `LtiToolInfoView` baut die Adressen per `reverse()` + + `build_absolute_uri` (URL-Namen `lti-login`, `lti-launch`, `lti-jwks`), + braucht kein `FRONTEND_BASE_URL` mehr, liefert zusätzlich `register_url`; + `icon_url` kommt aus `LTI_TOOL_REGISTRATION["logo_path"]` (leer, wenn + nicht gesetzt — bisher fest `/lti/icon.svg`). +- Geändert: `LtiFrameAncestorsMiddleware` behält ein von einer View + gesetztes `frame-ancestors` auf `/lti/`-Seiten. +- Migration: + 1. `python manage.py migrate` (neue Tabelle `basicbar_lti_ltiregistrationtoken`). + 2. `path("lti/register/", lti_register, name="lti-register")` verdrahten + (Name ohne Namespace; `lti-login`, `lti-launch`, `lti-jwks` müssen + ebenfalls so heißen). + 3. `LtiRegistrationTokenViewSet` im Router registrieren, mit der + Berechtigung des Tools (`permission_classes` überschreiben). + 4. `LTI_TOOL_REGISTRATION` setzen (`client_name`, `description`, + `logo_path`, bei Deep Linking `messages` um `LtiDeepLinkingRequest` + ergänzen). Wer sich bisher auf `icon_url` = `/lti/icon.svg` verlassen + hat, setzt `logo_path`. + 5. Hinter einem Reverse-Proxy `SECURE_PROXY_SSL_HEADER` prüfen (sonst + lehnt die Registrierung `http://`-Tool-URLs ab). Eigene + `frame-ancestors` auf `/lti/`-Seiten dürfen nicht breiter sein als nötig: + die Middleware überschreibt sie nicht mehr. + 6. Admin-UI: Button „Registrierungs-Link erzeugen“, Liste der Links, + Widerrufen; im Dialog die Nachschritte nennen („Neues Fenster“ als + Startcontainer, nur für neue Verknüpfungen) — die Erfolgsseite + schließt sich sofort. + 7. `LtiToolInfoView` braucht kein `FRONTEND_BASE_URL` mehr. + ### basicbar-integrations (→ wird `integrations/v0.6.0`) **Neue Module `gitlab` und `encryption`** (Regel der Zwei: orientierBAR und diff --git a/CLAUDE.md b/CLAUDE.md index ae0e0b9..3b2e063 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,8 @@ GitHub-Actions-Runner öffentlicher „-bar“-Tools die Pakete erreichen könne (`views.whoami_payload`/`logout_view`/`set_language`, `urls`), optionale Limits (`MAX_USERS`, Drift-Fallback). Betreiber-Doku im README. - `packages/django/basicbar-lti` — LTI-1.3-Fundament (PyLTI1p3): - Plattform-Registrierung, Tool-Key, Provisionierung, Middleware. + Plattform-Registrierung, Tool-Key, Provisionierung, Middleware, + Dynamic Registration per Einmal-Link (`lti_register`, Token-API). Launch/Deep-Linking bleiben Tool-Code. - `packages/ui` — `@basicbar/ui`: Tailwind-Preset (`createPreset`), `base.css`, ThemeProvider, `initI18n`, `contentLang`, diff --git a/packages/django/basicbar-lti/README.md b/packages/django/basicbar-lti/README.md index 16118f4..ff39e9e 100644 --- a/packages/django/basicbar-lti/README.md +++ b/packages/django/basicbar-lti/README.md @@ -7,9 +7,10 @@ LTI-1.3-Fundament der „-bar“-Tools (auf Basis von PyLTI1p3): (LTI-Subject ↔ lokaler User, plattform-scoped). - **`tool_conf.build_tool_conf()`** — Brücke von den DB-Registrierungen zu pylti1p3. -- **Views:** `lti_login` (OIDC-Initiation), `lti_jwks`, - `LtiPlatformViewSet` + `LtiToolInfoView` (Staff-API; Permission per - Subclass anpassbar). +- **Views:** `lti_login` (OIDC-Initiation), `lti_jwks`, `lti_register` + (Dynamic Registration), `LtiPlatformViewSet`, + `LtiRegistrationTokenViewSet` + `LtiToolInfoView` (Staff-API; Permission + per Subclass anpassbar). - **`provisioning`** — `provision_user` (JIT-User mit Link-Tabelle, E-Mail-Unifizierung als Plattform-Opt-in, OIDC-Profile werden nie überschrieben), `is_instructor`, `platform_for`, `launch_storage`, `CLAIM`. @@ -37,6 +38,108 @@ path("lti/login/", lti_login), path("lti/jwks/", lti_jwks), # + Tool-eigener /lti/launch/ aus den provisioning-Primitiven ``` +## Dynamic Registration (ab 0.2.0) + +Statt Issuer, Client-ID und Endpunkte von Hand zu kopieren, trägt der +LMS-Admin nur einen **Einmal-Link** in Moodle ein +(IMS LTI Dynamic Registration 1.0; Referenz ist Moodle, andere LMS laufen +weiter über die manuelle Registrierung). Gilt nur für **neue** +Verknüpfungen: Eine Neuregistrierung legt eine neue `LtiPlatform` mit neuer +Client-ID an; Kursverknüpfungen und Konten bestehender Plattformen bleiben +an der alten hängen. + +### Ablauf + +1. Der Tool-Admin erzeugt im Web-Admin einen Link + (`LtiRegistrationTokenViewSet`, `POST`, optional mit Notiz). Die Antwort + enthält `url` = `https:///lti/register/?token=` **genau + einmal**; gespeichert wird nur der SHA-256-Hash. +2. Der Moodle-Admin trägt den Link ein (Website-Administration → Plugins → + Externe Tools → Tools verwalten → Tool-URL → „LTI Advantage hinzufügen“). +3. `lti_register` prüft den Token (offen, nicht abgelaufen), holt die + `openid_configuration`, registriert das Tool beim LMS und legt die + `LtiPlatform` an (`is_active=True`, `link_by_email=False`, Deployment-ID + aus der Antwort, Name = Notiz des Links). Der Token wird im selben + Datenbankvorgang verbraucht. +4. Bei bereits bekanntem Issuer fragt die Seite vorher nach (die bestehende + Verknüpfung wird nicht übernommen); Abbrechen verbraucht den Token nicht. +5. Der Moodle-Admin **aktiviert** das Tool in Moodle. + +**Nachschritt in Moodle:** Moodle setzt bei dynamischer Registration den +Startcontainer fest auf „Eingebettet, ohne Blöcke“. Tool bearbeiten → +Standard-Startcontainer **„Neues Fenster“** (eingebettet braucht +`SESSION_COOKIE_SAMESITE=None` und passende `frame-ancestors` am Tool). Die +Erfolgsseite nennt das, **schickt aber sofort die Schließen-Nachricht** +(`org.imsglobal.lti.close`); der Moodle-Admin sieht den Text womöglich gar +nicht. Deshalb gehören der Nachschritt „Neues Fenster“ und der Hinweis +„nur neue Verknüpfungen“ auch in den **Admin-Dialog** des Tools (neben dem +erzeugten Link) und in die Tool-Doku. + +### Verdrahtung im Tool + +```python +# urls.py — Name ohne Namespace, die Tool-URLs werden per reverse() gebaut +from basicbar_lti.views import lti_register, LtiRegistrationTokenViewSet +path("lti/register/", lti_register, name="lti-register"), +router.register("registration-links", LtiRegistrationTokenViewSet, + basename="lti-registration-link") +``` + +Voraussetzung sind die URL-Namen `lti-login`, `lti-launch`, `lti-jwks`, +`lti-register`; `LtiToolInfoView` und die Registrierung bauen alle +Adressen daraus (`dynreg.tool_urls`), `FRONTEND_BASE_URL` wird nicht mehr +gebraucht. Das ViewSet ist per Default `IsAdminUser`; das Tool +überschreibt `permission_classes` wie bei `LtiPlatformViewSet`. +`list` zeigt Notiz, Ersteller, Ablauf, `status` (`open`/`used`/`expired`), +verknüpfte Plattform, nie den Token. `destroy` (= widerrufen, Zeile wird +gelöscht) geht nur für offene Links, sonst `400`. + +**Hinter einem Reverse-Proxy** muss `SECURE_PROXY_SSL_HEADER` gesetzt sein +(z. B. `("HTTP_X_FORWARDED_PROTO", "https")`), sonst erscheinen die +Tool-URLs als `http://` und die Registrierung lehnt sie ab. + +### Settings (alle optional, Defaults ändern nichts) + +| Setting | Default | Bedeutung | +|---|---|---| +| `LTI_REGISTRATION_TOKEN_TTL` | `timedelta(days=7)` | Gültigkeit eines Links | +| `LTI_REGISTRATION_ALLOW_HTTP` | `False` | erlaubt `http://` und Loopback/link-lokal für lokale Entwicklung; ein System-Check (`basicbar_lti.W001`) warnt bei `DEBUG=False` | +| `LTI_TOOL_REGISTRATION` | siehe unten | was das Tool dem LMS meldet; wird Schlüssel für Schlüssel über die Defaults gelegt | + +`LTI_TOOL_REGISTRATION`-Schlüssel: `client_name` (Default `"LTI Tool"`), +`description`, `logo_path` (z. B. `/lti/icon.svg`, wird absolut gemacht; +leer = kein Logo; liefert auch `icon_url` der `LtiToolInfoView`), +`messages` (Default nur `LtiResourceLinkRequest`; Tools mit Deep Linking +ergänzen `LtiDeepLinkingRequest`), `claims` +(`iss, sub, name, given_name, family_name, email`), `scope` (leer), +`custom_parameters` (`{}`). + +### Sicherheitsmodell + +- **Ohne gültigen Token passiert nichts:** Kein ausgehender Request, keine + Plattform. Der Link ist geheim, einmalig, befristet und widerrufbar. +- **SSRF-Schutz:** Nur `https`; Timeout 10 s, Antworten max. 256 KiB, + Weiterleitungen nur innerhalb desselben Origins. Abgelehnt werden + Loopback, link-lokale (u. a. Cloud-Metadaten) und unspezifizierte + Adressen; private Netze bleiben erlaubt (Campus-Moodle). Die + Plattform-Endpunkte müssen auf dem Host des Issuers liegen. +- **Bekannte Grenze:** Das Festnageln der IP gegen DNS-Rebinding fehlt, und + ausgehende Proxys aus den Umgebungsvariablen (`HTTPS_PROXY` o. ä.) werden + beachtet — die Adressprüfung validiert dann die lokale DNS-Auflösung. Das + ist bewusst akzeptiert, weil der Link geheim, einmalig und kurzlebig ist. +- **Fehler antworten mit `400`, nicht `502`:** 5xx-Antworten loggt + `django.request` auf ERROR mit dem vollständigen Request — der Klartext- + Token stünde im Query-String in Admin-Mails und Sentry. Das Paket loggt + nur den Fehlertext und die Config-URL. Fehlgeschlagene Versuche + verbrauchen den Token nicht. +- **Einbetten:** Nur bei gültigem Token setzt `lti_register` selbst + `frame-ancestors 'self' `. Die + Middleware behält ein von einer View auf `/lti/`-Seiten gesetztes + `frame-ancestors` (nur `X-Frame-Options` entfällt) — ein Tool darf dort + also **keine** breitere Policy selbst setzen. +- Der Token-Klartext steht nur in der Create-Antwort und in dem Link, den + der Admin weitergibt; nie in `list`, nie in der Datenbank. + ## Bestands-Deployment adoptieren (abstimmbar-Muster) Ein Tool, das die Models bisher selbst trug, behält seine diff --git a/packages/django/basicbar-lti/basicbar_lti/serializers.py b/packages/django/basicbar-lti/basicbar_lti/serializers.py index 4807c92..2af9515 100644 --- a/packages/django/basicbar-lti/basicbar_lti/serializers.py +++ b/packages/django/basicbar-lti/basicbar_lti/serializers.py @@ -5,7 +5,7 @@ (private_key / key_set); those stay Django-admin-only.""" from rest_framework import serializers -from .models import LtiPlatform +from .models import LtiPlatform, LtiRegistrationToken class LtiPlatformSerializer(serializers.ModelSerializer): @@ -38,3 +38,23 @@ def validate(self, attrs): "existiert bereits." ) return attrs + + +class LtiRegistrationTokenSerializer(serializers.ModelSerializer): + """One-time Dynamic-Registration links. The plaintext token (``url``) is + added by the viewset to the create response only — it is never stored.""" + + created_by = serializers.SlugRelatedField(slug_field="username", read_only=True) + status = serializers.CharField(read_only=True) + platform_name = serializers.CharField(source="platform.name", read_only=True, default="") + + class Meta: + model = LtiRegistrationToken + fields = [ + "id", "note", "created_by", "created_at", "expires_at", + "used_at", "status", "platform", "platform_name", + ] + read_only_fields = [ + "id", "created_by", "created_at", "expires_at", "used_at", + "status", "platform", "platform_name", + ] diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py index 43c9c61..7223d2a 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -11,6 +11,7 @@ from datetime import timedelta from unittest import mock +from django.contrib.auth import get_user_model from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings from django.utils import timezone @@ -789,3 +790,86 @@ def test_no_warning_in_debug(self): @override_settings(LTI_REGISTRATION_ALLOW_HTTP=False, DEBUG=False) def test_no_warning_by_default(self): self.assertEqual(self.run_checks(), []) + + +class RegistrationTokenApiTests(TestCase): + url = "/api/lti/registration-links/" + + def setUp(self): + User = get_user_model() + self.admin = User.objects.create_user(username="chef", is_staff=True) + self.user = User.objects.create_user(username="teacher") + + def test_requires_admin(self): + self.assertEqual(self.client.get(self.url).status_code, 403) + self.client.force_login(self.user) + self.assertEqual(self.client.get(self.url).status_code, 403) + resp = self.client.post( + self.url, {"note": "x"}, content_type="application/json" + ) + self.assertEqual(resp.status_code, 403) + + def test_create_returns_url_once(self): + self.client.force_login(self.admin) + resp = self.client.post( + self.url, {"note": "Moodle"}, content_type="application/json" + ) + self.assertEqual(resp.status_code, 201) + data = resp.json() + prefix = "http://testserver/lti/register/?token=" + self.assertTrue(data["url"].startswith(prefix)) + raw = data["url"][len(prefix):] + obj = LtiRegistrationToken.find_valid(raw) + self.assertIsNotNone(obj) + self.assertEqual(obj.pk, data["id"]) + self.assertEqual(data["created_by"], "chef") + self.assertEqual(data["status"], "open") + listing = self.client.get(self.url) + self.assertEqual(listing.status_code, 200) + self.assertNotIn("url", listing.json()[0] if isinstance(listing.json(), list) else listing.json()["results"][0]) + self.assertNotIn(raw, listing.content.decode()) + + def test_destroy_open_only(self): + self.client.force_login(self.admin) + open_obj, _ = LtiRegistrationToken.issue() + used_obj, _ = LtiRegistrationToken.issue() + used_obj.used_at = timezone.now() + used_obj.save() + resp = self.client.delete(f"{self.url}{open_obj.pk}/") + self.assertEqual(resp.status_code, 204) + self.assertFalse(LtiRegistrationToken.objects.filter(pk=open_obj.pk).exists()) + resp = self.client.delete(f"{self.url}{used_obj.pk}/") + self.assertEqual(resp.status_code, 400) + self.assertEqual( + resp.json(), {"detail": "Nur offene Links können widerrufen werden."} + ) + self.assertTrue(LtiRegistrationToken.objects.filter(pk=used_obj.pk).exists()) + + def test_destroy_expired_rejected(self): + self.client.force_login(self.admin) + obj, _ = LtiRegistrationToken.issue() + obj.expires_at = timezone.now() - timedelta(hours=1) + obj.save() + self.assertEqual(self.client.delete(f"{self.url}{obj.pk}/").status_code, 400) + + def test_tool_info_uses_reverse(self): + self.client.force_login(self.admin) + info = self.client.get("/api/lti/tool-info/").json() + self.assertEqual(info["register_url"], "http://testserver/lti/register/") + self.assertEqual(info["login_url"], "http://testserver/lti/login/") + self.assertEqual(info["icon_url"], "") + + @override_settings(LTI_TOOL_REGISTRATION={"logo_path": "/static/logo.svg"}) + def test_tool_info_icon_from_logo_path(self): + self.client.force_login(self.admin) + info = self.client.get("/api/lti/tool-info/").json() + self.assertEqual(info["icon_url"], "http://testserver/static/logo.svg") + + def test_tool_info_without_frontend_base_url(self): + from django.conf import settings + + with override_settings(): + del settings.FRONTEND_BASE_URL + self.client.force_login(self.admin) + resp = self.client.get("/api/lti/tool-info/") + self.assertEqual(resp.status_code, 200) diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_lti.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_lti.py index 0b994fc..23697b4 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_lti.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_lti.py @@ -404,7 +404,9 @@ def test_tool_info_admin_only_and_urls(self): self.assertTrue(info["login_url"].endswith("/lti/login/")) self.assertTrue(info["launch_url"].endswith("/lti/launch/")) self.assertTrue(info["jwks_url"].endswith("/lti/jwks/")) - self.assertTrue(info["icon_url"].endswith("/lti/icon.svg")) + self.assertTrue(info["register_url"].endswith("/lti/register/")) + # icon_url comes from LTI_TOOL_REGISTRATION["logo_path"] (empty here) + self.assertEqual(info["icon_url"], "") def test_created_platform_appears_in_jwks(self): from basicbar_lti.tool_conf import build_tool_conf diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/urls.py b/packages/django/basicbar-lti/basicbar_lti/tests/urls.py index 7b8f935..52c3b10 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/urls.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/urls.py @@ -16,7 +16,14 @@ provision_user, ) from basicbar_lti.tool_conf import build_tool_conf -from basicbar_lti.views import LtiPlatformViewSet, LtiToolInfoView, lti_jwks, lti_login, lti_register +from basicbar_lti.views import ( + LtiPlatformViewSet, + LtiRegistrationTokenViewSet, + LtiToolInfoView, + lti_jwks, + lti_login, + lti_register, +) @csrf_exempt @@ -41,6 +48,9 @@ def embeddable_page(request): router = DefaultRouter() router.register("platforms", LtiPlatformViewSet, basename="lti-platform") +router.register( + "registration-links", LtiRegistrationTokenViewSet, basename="lti-registration-link" +) urlpatterns = [ path("lti/login/", lti_login, name="lti-login"), diff --git a/packages/django/basicbar-lti/basicbar_lti/views.py b/packages/django/basicbar-lti/basicbar_lti/views.py index a69de68..50f32e8 100644 --- a/packages/django/basicbar-lti/basicbar_lti/views.py +++ b/packages/django/basicbar-lti/basicbar_lti/views.py @@ -10,25 +10,24 @@ import logging from urllib.parse import urlsplit -from django.conf import settings from django.http import HttpResponse, JsonResponse from django.utils.html import format_html from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_exempt from pylti1p3.contrib.django import DjangoOIDCLogin from pylti1p3.exception import LtiException, OIDCException -from rest_framework import viewsets +from rest_framework import mixins, status, viewsets from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from rest_framework.views import APIView -from . import dynreg +from . import conf, dynreg from .dynreg_http import RegistrationError from .dynreg_pages import CANCEL_SCRIPT, page from .middleware import _ORIGIN_RE from .models import LtiPlatform, LtiRegistrationToken from .provisioning import launch_storage -from .serializers import LtiPlatformSerializer +from .serializers import LtiPlatformSerializer, LtiRegistrationTokenSerializer from .tool_conf import build_tool_conf logger = logging.getLogger(__name__) @@ -126,20 +125,63 @@ class LtiPlatformViewSet(viewsets.ModelViewSet): permission_classes = [IsAdminUser] +class LtiRegistrationTokenViewSet( + mixins.CreateModelMixin, + mixins.ListModelMixin, + mixins.DestroyModelMixin, + viewsets.GenericViewSet, +): + """Staff-only one-time registration links for Dynamic Registration. + + The create response carries the link (``url``) exactly once; only a hash + is stored. Only open links can be revoked (= deleted). Tools override + ``permission_classes`` (default: Django staff).""" + + queryset = LtiRegistrationToken.objects.select_related( + "created_by", "platform" + ).order_by("-created_at", "-id") + serializer_class = LtiRegistrationTokenSerializer + permission_classes = [IsAdminUser] + + def create(self, request, *args, **kwargs): + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + obj, raw = LtiRegistrationToken.issue( + note=serializer.validated_data.get("note", ""), + created_by=request.user, + ) + data = dict(self.get_serializer(obj).data) + data["url"] = f"{dynreg.tool_urls(request)['register']}?token={raw}" + return Response(data, status=status.HTTP_201_CREATED) + + def destroy(self, request, *args, **kwargs): + obj = self.get_object() + if obj.status != "open": + return Response( + {"detail": "Nur offene Links können widerrufen werden."}, + status=status.HTTP_400_BAD_REQUEST, + ) + obj.delete() + return Response(status=status.HTTP_204_NO_CONTENT) + + class LtiToolInfoView(APIView): """The tool's own LTI endpoints, for pasting into the LMS registration. - Assumes the conventional ``/lti/…`` paths under ``FRONTEND_BASE_URL``.""" + Built from the URL names ``lti-login`` / ``lti-launch`` / ``lti-jwks`` / + ``lti-register`` (see :func:`basicbar_lti.dynreg.tool_urls`).""" permission_classes = [IsAdminUser] def get(self, request): - base = settings.FRONTEND_BASE_URL.rstrip("/") + urls = dynreg.tool_urls(request) + logo = conf.tool_registration()["logo_path"] return Response({ - "login_url": f"{base}/lti/login/", - "launch_url": f"{base}/lti/launch/", - "jwks_url": f"{base}/lti/jwks/", - "icon_url": f"{base}/lti/icon.svg", + "login_url": urls["login"], + "launch_url": urls["launch"], + "jwks_url": urls["jwks"], + "register_url": urls["register"], + "icon_url": request.build_absolute_uri(logo) if logo else "", }) diff --git a/packages/django/basicbar-lti/pyproject.toml b/packages/django/basicbar-lti/pyproject.toml index 6135e33..d17a75a 100644 --- a/packages/django/basicbar-lti/pyproject.toml +++ b/packages/django/basicbar-lti/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "basicbar-lti" -version = "0.1.5" +version = "0.2.0" description = "LTI-1.3-Fundament der virtUOS -bar-Tools: Plattform-Registrierung, Tool-Key, OIDC-Initiation, JWKS, Nutzer-Provisionierung, Frame-Ancestors-Middleware" readme = "README.md" requires-python = ">=3.12" From c0ca04f8cc24069c0afa66a0612f9521c6e71a94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Rolf?= Date: Wed, 25 Nov 2026 18:42:36 +0100 Subject: [PATCH 9/9] =?UTF-8?q?fix(lti):=20Feinschliff=20nach=20Gesamt-Rev?= =?UTF-8?q?iew=20=E2=80=94=20keine=20500=20aus=20lti=5Fregister,=20Tool-In?= =?UTF-8?q?fo=20ohne=20lti-register?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 ++-- packages/django/basicbar-lti/README.md | 6 +- .../basicbar-lti/basicbar_lti/dynreg.py | 53 ++++++++--- .../basicbar-lti/basicbar_lti/dynreg_http.py | 7 +- .../basicbar-lti/basicbar_lti/middleware.py | 5 +- .../basicbar_lti/tests/test_dynreg.py | 93 ++++++++++++++++++- .../basicbar_lti/tests/urls_no_register.py | 7 ++ .../django/basicbar-lti/basicbar_lti/views.py | 25 ++++- 8 files changed, 183 insertions(+), 31 deletions(-) create mode 100644 packages/django/basicbar-lti/basicbar_lti/tests/urls_no_register.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 83606e6..b283da7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,7 +70,12 @@ Registrierung bleibt. Ohne Verdrahtung ändert sich nichts. `LTI_TOOL_REGISTRATION`, System-Check `basicbar_lti.W001`. - Geändert: `LtiToolInfoView` baut die Adressen per `reverse()` + `build_absolute_uri` (URL-Namen `lti-login`, `lti-launch`, `lti-jwks`), - braucht kein `FRONTEND_BASE_URL` mehr, liefert zusätzlich `register_url`; + also aus Schema und Host der Anfrage statt aus `FRONTEND_BASE_URL` + (hinter einem Proxy `SECURE_PROXY_SSL_HEADER` und ggf. + `USE_X_FORWARDED_HOST` setzen, sonst stimmen die Adressen für die manuelle + Registrierung nicht), liefert zusätzlich `register_url` (leer, solange + `lti/register/` nicht verdrahtet ist — Tool-Info läuft dann unverändert + weiter); `icon_url` kommt aus `LTI_TOOL_REGISTRATION["logo_path"]` (leer, wenn nicht gesetzt — bisher fest `/lti/icon.svg`). - Geändert: `LtiFrameAncestorsMiddleware` behält ein von einer View @@ -86,15 +91,16 @@ Registrierung bleibt. Ohne Verdrahtung ändert sich nichts. `logo_path`, bei Deep Linking `messages` um `LtiDeepLinkingRequest` ergänzen). Wer sich bisher auf `icon_url` = `/lti/icon.svg` verlassen hat, setzt `logo_path`. - 5. Hinter einem Reverse-Proxy `SECURE_PROXY_SSL_HEADER` prüfen (sonst - lehnt die Registrierung `http://`-Tool-URLs ab). Eigene - `frame-ancestors` auf `/lti/`-Seiten dürfen nicht breiter sein als nötig: - die Middleware überschreibt sie nicht mehr. + 5. Hinter einem Reverse-Proxy `SECURE_PROXY_SSL_HEADER` (und ggf. + `USE_X_FORWARDED_HOST`) prüfen: Die Registrierung lehnt `http://`-Tool-URLs + ab, und die Adressen der Tool-Info (manuelle Registrierung) kommen aus + derselben Anfrage. Ein eigenes `frame-ancestors` einer View auf + `/lti/`-Seiten behält die Middleware unverändert, sie überschreibt es + nicht mehr — es darf nicht breiter sein als nötig. 6. Admin-UI: Button „Registrierungs-Link erzeugen“, Liste der Links, Widerrufen; im Dialog die Nachschritte nennen („Neues Fenster“ als Startcontainer, nur für neue Verknüpfungen) — die Erfolgsseite schließt sich sofort. - 7. `LtiToolInfoView` braucht kein `FRONTEND_BASE_URL` mehr. ### basicbar-integrations (→ wird `integrations/v0.6.0`) diff --git a/packages/django/basicbar-lti/README.md b/packages/django/basicbar-lti/README.md index ff39e9e..cd2d0e8 100644 --- a/packages/django/basicbar-lti/README.md +++ b/packages/django/basicbar-lti/README.md @@ -34,8 +34,10 @@ LTI_FRAME_PATH_PREFIXES = ("/lti/", "/p/") # einbettbare HTML-Pfade # urls.py from basicbar_lti.views import lti_login, lti_jwks -path("lti/login/", lti_login), path("lti/jwks/", lti_jwks), -# + Tool-eigener /lti/launch/ aus den provisioning-Primitiven +path("lti/login/", lti_login, name="lti-login"), +path("lti/jwks/", lti_jwks, name="lti-jwks"), +# + Tool-eigener /lti/launch/ aus den provisioning-Primitiven; die View muss +# `lti-launch` heißen (für Dynamic Registration zusätzlich `lti-register`) ``` ## Dynamic Registration (ab 0.2.0) diff --git a/packages/django/basicbar-lti/basicbar_lti/dynreg.py b/packages/django/basicbar-lti/basicbar_lti/dynreg.py index f710fc6..11a9ddc 100644 --- a/packages/django/basicbar-lti/basicbar_lti/dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/dynreg.py @@ -8,7 +8,7 @@ from urllib.parse import urlsplit from django.db import IntegrityError, transaction -from django.urls import reverse +from django.urls import NoReverseMatch, reverse from django.utils import timezone from . import conf @@ -57,8 +57,15 @@ class PlatformConfig: product_family_code: str = "" +def _split(url: str): + try: + return urlsplit(url) + except ValueError as exc: + raise RegistrationError("Die Adresse ist ungültig.", detail=url) from exc + + def _netloc(url: str) -> str: - return urlsplit(url).netloc.lower() + return _split(url).netloc.lower() def load_platform_config( @@ -80,7 +87,7 @@ def load_platform_config( f"{key} longer than {_max_len(column)} characters", ) issuer = data["issuer"] - iss, cfg = urlsplit(issuer), urlsplit(config_url) + iss, cfg = _split(issuer), _split(config_url) if ( iss.scheme.lower() != cfg.scheme.lower() or iss.netloc.lower() != cfg.netloc.lower() @@ -109,16 +116,24 @@ def load_platform_config( ) -def tool_urls(request) -> dict: - return { - key: request.build_absolute_uri(reverse(name)) - for key, name in ( - ("login", "lti-login"), - ("launch", "lti-launch"), - ("jwks", "lti-jwks"), - ("register", "lti-register"), - ) - } +def tool_urls(request, *, require_register: bool = True) -> dict: + """Absolute URLs of the tool's LTI endpoints. With + ``require_register=False`` a missing ``lti-register`` wiring yields + ``""`` for ``register`` instead of ``NoReverseMatch``.""" + urls = {} + for key, name in ( + ("login", "lti-login"), + ("launch", "lti-launch"), + ("jwks", "lti-jwks"), + ("register", "lti-register"), + ): + try: + urls[key] = request.build_absolute_uri(reverse(name)) + except NoReverseMatch: + if key != "register" or require_register: + raise + urls[key] = "" + return urls def tool_registration_payload(request) -> dict: @@ -195,7 +210,15 @@ def register_platform( def _register(request, token, config, registration_token) -> LtiPlatform: with transaction.atomic(): - locked = LtiRegistrationToken.objects.select_for_update().get(pk=token.pk) + try: + locked = LtiRegistrationToken.objects.select_for_update().get( + pk=token.pk + ) + except LtiRegistrationToken.DoesNotExist: + # revoked between find_valid and the lock + raise RegistrationError( + "Link bereits verwendet oder abgelaufen." + ) from None if locked.used_at is not None or locked.expires_at <= timezone.now(): raise RegistrationError("Link bereits verwendet oder abgelaufen.") response = request_json( @@ -217,7 +240,7 @@ def _register(request, token, config, registration_token) -> LtiPlatform: block = response.get(LTI_TOOL_CONFIG) deployment_id = block.get("deployment_id") if isinstance(block, dict) else None deployment_ids = [str(deployment_id)] if deployment_id not in (None, "") else [] - host = urlsplit(config.issuer).hostname or config.issuer + host = _split(config.issuer).hostname or config.issuer platform = LtiPlatform.objects.create( name=( locked.note or f"{config.product_family_code or 'LMS'} ({host})" diff --git a/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py b/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py index 7979ef8..cd41a8c 100644 --- a/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py +++ b/packages/django/basicbar-lti/basicbar_lti/dynreg_http.py @@ -36,7 +36,12 @@ def __init__(self, message: str, detail: str = ""): def _origin(url: str) -> tuple[str, str, int | None]: - parts = urlsplit(url) + try: + parts = urlsplit(url) + except ValueError as exc: + raise RegistrationError( + "Die Adresse ist ungültig.", detail=url + ) from exc try: port = parts.port except ValueError: diff --git a/packages/django/basicbar-lti/basicbar_lti/middleware.py b/packages/django/basicbar-lti/basicbar_lti/middleware.py index 9e1eb0c..9cecf89 100644 --- a/packages/django/basicbar-lti/basicbar_lti/middleware.py +++ b/packages/django/basicbar-lti/basicbar_lti/middleware.py @@ -56,8 +56,9 @@ def __call__(self, request): ct = response.get("Content-Type", "") prefixes = tuple(conf.get("LTI_FRAME_PATH_PREFIXES")) if ct.startswith("text/html") and request.path.startswith(prefixes): - # A view may already have set a narrower policy (the Dynamic - # Registration page); keep it, only drop X-Frame-Options. + # A view may already have set its own frame-ancestors (the + # Dynamic Registration page); keep it as is, only drop + # X-Frame-Options. if "frame-ancestors" not in response.get("Content-Security-Policy", ""): ancestors = " ".join(["'self'", *_lms_origins()]) response["Content-Security-Policy"] = f"frame-ancestors {ancestors}" diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py index 7223d2a..ce7e1f2 100644 --- a/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py +++ b/packages/django/basicbar-lti/basicbar_lti/tests/test_dynreg.py @@ -211,10 +211,12 @@ def test_url_error(self): request_json("https://moodle.example.org/x") def test_too_large(self): - gai, op = self._patch(body=b" " * (dynreg_http.MAX_BYTES + 1)) + body = b'{"a":"' + b"x" * dynreg_http.MAX_BYTES + b'"}' + gai, op = self._patch(body=body) with gai, op: - with self.assertRaises(RegistrationError): + with self.assertRaises(RegistrationError) as cm: request_json("https://moodle.example.org/x") + self.assertIn("zu groß", str(cm.exception)) def test_cross_host_redirect_refused(self): handler = dynreg_http._SameOriginRedirectHandler() @@ -258,6 +260,14 @@ def test_bad_port_rejected(self): request_json("https://h:abc/") opened.assert_not_called() + def test_bad_bracket_url_rejected(self): + gai, op = self._patch() + with gai, op as opened: + with self.assertRaises(RegistrationError) as cm: + request_json("https://[::1") + self.assertIn("ungültig", str(cm.exception)) + opened.assert_not_called() + def test_userinfo_rejected(self): gai, op = self._patch() with gai, op as opened: @@ -367,6 +377,22 @@ def test_config_non_string_field(self): self.load(moodle_config(token_endpoint=5)) +class PlatformConfigInvalidUrlTests(SimpleTestCase): + def test_issuer_with_bad_bracket(self): + data = moodle_config(issuer="https://[x") + with mock.patch("basicbar_lti.dynreg.request_json", return_value=data): + with self.assertRaises(RegistrationError) as cm: + dynreg.load_platform_config(CONFIG_URL, None) + self.assertIn("ungültig", str(cm.exception)) + + def test_endpoint_with_bad_bracket(self): + data = moodle_config(token_endpoint="https://[x/token") + with mock.patch("basicbar_lti.dynreg.request_json", return_value=data): + with self.assertRaises(RegistrationError) as cm: + dynreg.load_platform_config(CONFIG_URL, None) + self.assertIn("ungültig", str(cm.exception)) + + class PayloadTests(SimpleTestCase): def test_payload_shape(self): p = dynreg.tool_registration_payload(secure_request()) @@ -517,6 +543,14 @@ def test_register_duplicate_platform_keeps_token_open(self): token.refresh_from_db() self.assertEqual(token.status, "open") + def test_register_token_deleted_meanwhile(self): + token, _ = LtiRegistrationToken.issue(note="x") + LtiRegistrationToken.objects.filter(pk=token.pk).delete() + with self.assertRaises(RegistrationError) as cm: + self.register(token) + self.assertIn("Link bereits verwendet", str(cm.exception)) + self.assertFalse(LtiPlatform.objects.exists()) + def test_register_used_token_refused(self): token, _ = LtiRegistrationToken.issue() LtiRegistrationToken.objects.filter(pk=token.pk).update( @@ -640,6 +674,52 @@ def test_lms_error_400_token_open(self): self.assertEqual(self.token.status, "open") self.assertFalse(LtiPlatform.objects.exists()) + def test_bad_openid_configuration_400_token_open(self): + with mock.patch.object(dynreg_http, "_open") as opened: + response = self.get(openid_configuration="https://[::1") + self.assertEqual(response.status_code, 400) + opened.assert_not_called() + self.token.refresh_from_db() + self.assertEqual(self.token.status, "open") + + def test_unexpected_error_400_token_open_no_secrets_logged(self): + with self.patched(moodle_config()), mock.patch( + "basicbar_lti.dynreg.register_platform", + side_effect=RuntimeError("boom"), + ): + with self.assertLogs("basicbar_lti.views", level="ERROR") as logs: + response = self.get() + self.assertEqual(response.status_code, 400) + self.assertIn("Registration failed.", response.content.decode()) + self.token.refresh_from_db() + self.assertEqual(self.token.status, "open") + logged = "\n".join(logs.output) + self.assertNotIn(self.raw, logged) + self.assertIn(CONFIG_URL, logged) + + def test_confirm_zero_still_asks(self): + self._known() + with self.patched(moodle_config()): + response = self.get(confirm="0") + self.assertIn('name="confirm"', response.content.decode()) + self.assertEqual(LtiPlatform.objects.count(), 1) + + def test_pages_are_not_cached_or_referred(self): + self._known() + cases = [ + (self.get(token="nope"), None), + (self.get(openid_configuration=None), None), + ] + with self.patched(moodle_config()): + cases.append((self.get(), None)) + with self.patched(RegistrationError("x")): + cases.append((self.get(), None)) + with self.patched(moodle_config(), self.RESPONSE): + cases.append((self.post(confirm="1"), None)) + for response, _ in cases: + self.assertEqual(response["Cache-Control"], "no-store") + self.assertEqual(response["Referrer-Policy"], "no-referrer") + def _known(self): LtiPlatform.objects.create( name="alt", @@ -865,6 +945,15 @@ def test_tool_info_icon_from_logo_path(self): info = self.client.get("/api/lti/tool-info/").json() self.assertEqual(info["icon_url"], "http://testserver/static/logo.svg") + @override_settings(ROOT_URLCONF="basicbar_lti.tests.urls_no_register") + def test_tool_info_without_register_wiring(self): + self.client.force_login(self.admin) + resp = self.client.get("/api/lti/tool-info/") + self.assertEqual(resp.status_code, 200) + info = resp.json() + self.assertEqual(info["register_url"], "") + self.assertEqual(info["login_url"], "http://testserver/lti/login/") + def test_tool_info_without_frontend_base_url(self): from django.conf import settings diff --git a/packages/django/basicbar-lti/basicbar_lti/tests/urls_no_register.py b/packages/django/basicbar-lti/basicbar_lti/tests/urls_no_register.py new file mode 100644 index 0000000..668339b --- /dev/null +++ b/packages/django/basicbar-lti/basicbar_lti/tests/urls_no_register.py @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Universität Osnabrück (virtUOS) + +"""Test URLconf of a tool that has not wired ``lti-register`` yet.""" +from .urls import urlpatterns as _all + +urlpatterns = [p for p in _all if getattr(p, "name", None) != "lti-register"] diff --git a/packages/django/basicbar-lti/basicbar_lti/views.py b/packages/django/basicbar-lti/basicbar_lti/views.py index 50f32e8..9d7b133 100644 --- a/packages/django/basicbar-lti/basicbar_lti/views.py +++ b/packages/django/basicbar-lti/basicbar_lti/views.py @@ -169,12 +169,13 @@ class LtiToolInfoView(APIView): """The tool's own LTI endpoints, for pasting into the LMS registration. Built from the URL names ``lti-login`` / ``lti-launch`` / ``lti-jwks`` / - ``lti-register`` (see :func:`basicbar_lti.dynreg.tool_urls`).""" + ``lti-register`` (see :func:`basicbar_lti.dynreg.tool_urls`); a missing + ``lti-register`` only yields ``register_url == ""``.""" permission_classes = [IsAdminUser] def get(self, request): - urls = dynreg.tool_urls(request) + urls = dynreg.tool_urls(request, require_register=False) logo = conf.tool_registration()["logo_path"] return Response({ "login_url": urls["login"], @@ -202,6 +203,9 @@ def _register_response(status, title_de, title_en, body, origin, **kw): response = HttpResponse(page(title_de, title_en, body, **kw), status=status) if origin: response["Content-Security-Policy"] = f"frame-ancestors 'self' {origin}" + # the token is in the URL and the form + response["Cache-Control"] = "no-store" + response["Referrer-Policy"] = "no-referrer" return response @@ -220,7 +224,7 @@ def lti_register(request): raw = _register_param(request, "token") config_url = _register_param(request, "openid_configuration") registration_token = _register_param(request, "registration_token") - confirm = bool(_register_param(request, "confirm")) + confirm = _register_param(request, "confirm") == "1" token = LtiRegistrationToken.find_valid(raw) if token is None: @@ -253,6 +257,21 @@ def lti_register(request): "LTI registration failed (config=%r): %s %s", config_url, exc, exc.detail ) return _error_page(400, str(exc), "Registration failed.", origin) + except Exception as exc: # noqa: BLE001 - last resort, never a 5xx + # Deliberately no exc_info and no request: a traceback or a 5xx + # request log would carry the token / registration_token. + logger.error( + "LTI registration failed unexpectedly (config=%r): %s", + config_url, + type(exc).__name__, + ) + return _error_page( + 400, + "Die Registrierung ist unerwartet fehlgeschlagen. Bitte den " + "Betreiber informieren.", + "Registration failed.", + origin, + ) body = format_html( "

Registrierung abgeschlossen ({}). Nächste Schritte in Moodle: "