From 6d1c7fd0f66313d413395ba1584cf8b0368e4981 Mon Sep 17 00:00:00 2001 From: st187468 Date: Tue, 11 Aug 2026 18:29:01 +0200 Subject: [PATCH 1/2] fix: correct ILIAS scraping and session handling bugs Exercise tooling was largely non-functional against real courses: - list_exercise_assignments returned nothing for past or upcoming assignments. The overview URL omitted mode=all, and ILIAS only renders currently running assignments by default. - list_submitted_files, the upload form and the team screen resolved their URLs from ilAssignmentPresentationGUI, which redirects to the overview without the dynamic cmdNode those links need, producing a HTTP 500. They now read the overview page instead. - Deadlines were never parsed: ILIAS writes "4. Mai 2026, 08:00" and mixes full with abbreviated month names, not "04.05.2026". - Status could report "abgegeben" for a row saying "nicht abgegeben", because the positive substring was tested first. - remove_team_member only posted the confirmation step, so it never removed anybody while still reporting success. - Team and delete operations reported status "ok" even when ILIAS ignored the request; they now verify the change and report "unchanged" otherwise. - search_users did not URL-encode the search term. - rtoken was only read from the form action, never from the hidden field, leaving the CSRF token empty on some forms. - Three regex-extracted URLs skipped unescape() unlike the fourth. Repository handling: - download_file and get_file_content on a folder silently returned the first file contained in it, because _detect_file_url ignored the ref_id it was given. Containers now raise instead. - Uploaded .html files could never be downloaded: the guard rejected every text/html response as an ILIAS error page. Real downloads always carry a Content-Disposition filename, error pages never do. - Exercise objects were typed as the generic "item". Session handling: - An expired ILIAS session was never renewed. _logged_in was a one-way latch, so every later call silently parsed the login page. Requests now go through AuthService.get(), which re-authenticates once. - POST transport errors escaped several tools unhandled. - An unparsable calendar seed silently returned events for today. Also fixes the pre-existing ruff violations so CI passes, and grows the test suite from 10 to 31 cases. --- src/core/config.py | 2 +- src/mcp_app/server.py | 17 +- src/services/__init__.py | 10 +- src/services/auth_service.py | 30 ++++ src/services/calendar_service.py | 4 +- src/services/course_service.py | 6 +- src/services/exercise_service.py | 243 +++++++++++++++++++---------- src/services/news_service.py | 9 +- src/services/repository_service.py | 71 ++++++--- tests/test_auth_service.py | 41 +++++ tests/test_exercise_service.py | 107 +++++++++++++ tests/test_repository_service.py | 78 +++++++++ 12 files changed, 492 insertions(+), 126 deletions(-) create mode 100644 tests/test_auth_service.py create mode 100644 tests/test_exercise_service.py diff --git a/src/core/config.py b/src/core/config.py index b985aca..67e2498 100644 --- a/src/core/config.py +++ b/src/core/config.py @@ -1,5 +1,5 @@ -from dataclasses import dataclass import os +from dataclasses import dataclass from pathlib import Path from urllib.parse import urlencode diff --git a/src/mcp_app/server.py b/src/mcp_app/server.py index a007050..76054e2 100644 --- a/src/mcp_app/server.py +++ b/src/mcp_app/server.py @@ -3,7 +3,7 @@ import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager -from datetime import date +from datetime import date, datetime import requests from mcp.server.fastmcp import Context, FastMCP @@ -13,8 +13,8 @@ from services.auth_service import AuthService, IliasAuthError from services.calendar_service import CalendarService, IliasCalendarError from services.course_service import CourseService, IliasCourseError -from services.news_service import IliasNewsError, NewsService from services.exercise_service import ExerciseService, IliasExerciseError +from services.news_service import IliasNewsError, NewsService from services.repository_service import IliasRepositoryError, RepositoryService logging.basicConfig(level=logging.INFO) @@ -144,7 +144,18 @@ async def list_calendar_events( ) -> dict[str, object]: """List calendar agenda events for a given day (`YYYY-MM-DD`).""" app = _app(ctx) - day = seed.strip() or date.today().isoformat() + day = seed.strip() or datetime.now().astimezone().date().isoformat() + try: + # ILIAS silently falls back to today for an unparsable seed, which + # would return events for the wrong day without any error. + date.fromisoformat(day) + except ValueError: + return { + "status": "error", + "message": f"seed must be a date in YYYY-MM-DD format, got {day!r}", + "seed": day, + "events": [], + } try: events = app.calendar_service.list_events(day) except (IliasAuthError, IliasCalendarError) as exc: diff --git a/src/services/__init__.py b/src/services/__init__.py index 6dca40b..1062c1c 100644 --- a/src/services/__init__.py +++ b/src/services/__init__.py @@ -8,13 +8,13 @@ __all__ = [ "AuthService", - "IliasAuthError", - "CourseService", - "IliasCourseError", "CalendarService", + "CourseService", + "IliasAuthError", "IliasCalendarError", - "NewsService", + "IliasCourseError", "IliasNewsError", - "RepositoryService", "IliasRepositoryError", + "NewsService", + "RepositoryService", ] diff --git a/src/services/auth_service.py b/src/services/auth_service.py index 1705733..a122199 100644 --- a/src/services/auth_service.py +++ b/src/services/auth_service.py @@ -79,6 +79,36 @@ def ensure_logged_in(self) -> None: if not self._logged_in: self.login() + def relogin(self) -> str: + """Force a fresh authentication, discarding the cached login state.""" + self._logged_in = False + return self.login() + + def get(self, url: str, **kwargs: Any) -> requests.Response: + """GET a page, transparently re-authenticating once if the session died. + + ILIAS answers requests on an expired session with HTTP 200 and the + login page, so callers would otherwise silently parse the wrong HTML. + """ + self.ensure_logged_in() + kwargs.setdefault("timeout", self.settings.timeout_seconds) + resp = self.session.get(url, **kwargs) + resp.raise_for_status() + + if self._looks_like_login_page(resp): + self.relogin() + resp = self.session.get(url, **kwargs) + resp.raise_for_status() + return resp + + @classmethod + def _looks_like_login_page(cls, resp: requests.Response) -> bool: + if "html" not in (resp.headers.get("Content-Type") or "").lower(): + return False + text = resp.text + has_login_form = "doStandardAuthentication" in text or "cmd=force_login" in text + return has_login_form and not cls._is_logged_in(text) + @staticmethod def _inject_credentials( form: Any, payload: dict[str, Any], user: str, password: str diff --git a/src/services/calendar_service.py b/src/services/calendar_service.py index 15ecace..3e7bded 100644 --- a/src/services/calendar_service.py +++ b/src/services/calendar_service.py @@ -23,12 +23,10 @@ def __init__( self.auth_service = auth_service def list_events(self, seed: str) -> list[CalendarEvent]: - self.auth_service.ensure_logged_in() url = self.settings.calendar_url(seed) try: - resp = self.session.get(url, timeout=self.settings.timeout_seconds) - resp.raise_for_status() + resp = self.auth_service.get(url) except requests.RequestException as exc: raise IliasCalendarError(f"Failed to fetch calendar page: {exc}") from exc diff --git a/src/services/course_service.py b/src/services/course_service.py index a6375d7..967f772 100644 --- a/src/services/course_service.py +++ b/src/services/course_service.py @@ -23,12 +23,8 @@ def __init__( self.auth_service = auth_service def list_courses(self) -> list[Course]: - self.auth_service.ensure_logged_in() try: - resp = self.session.get( - self.settings.memberships_url, timeout=self.settings.timeout_seconds - ) - resp.raise_for_status() + resp = self.auth_service.get(self.settings.memberships_url) except requests.RequestException as exc: raise IliasCourseError(f"Failed to fetch memberships page: {exc}") from exc return self._extract_courses(resp.text) diff --git a/src/services/exercise_service.py b/src/services/exercise_service.py index d70ed02..fd232da 100644 --- a/src/services/exercise_service.py +++ b/src/services/exercise_service.py @@ -3,7 +3,7 @@ import re from html import unescape from pathlib import Path -from urllib.parse import urljoin, urlparse, parse_qs +from urllib.parse import parse_qs, quote, urljoin, urlparse import requests from bs4 import BeautifulSoup @@ -52,14 +52,9 @@ def _extract_assignments(self, html: str, ref_id: str) -> list[ExerciseAssignmen deadline = "" status = "" if row: - text = row.get_text(" ", strip=True) - m = re.search(r"\d{2}\.\d{2}\.\d{4}(?:\s+\d{2}:\d{2})?", text) - if m: - deadline = m.group(0) - for word in ("abgegeben", "nicht abgegeben", "bewertet", "submitted"): - if word.lower() in text.lower(): - status = word - break + text = " ".join(row.get_text(" ", strip=True).split()) + deadline = self._extract_deadline(text) + status = self._extract_status(text) assignments.append( ExerciseAssignment( ass_id=ass_id, title=title, deadline=deadline, status=status @@ -67,6 +62,50 @@ def _extract_assignments(self, html: str, ref_id: str) -> list[ExerciseAssignmen ) return assignments + # ILIAS renders deadlines as "4. Mai 2026, 08:00" or "3. Jul 2026, 23:59", + # mixing full and abbreviated month names, so match any month word rather + # than enumerating them (which also survives a non-German ILIAS_LANG). + _DATE = ( + r"(?:\d{1,2}\.\s*[^\W\d_]{3,10}\.?\s+\d{4}(?:,\s*\d{1,2}:\d{2})?" + r"|\d{2}\.\d{2}\.\d{4}(?:\s+\d{1,2}:\d{2})?)" + ) + + @classmethod + def _extract_deadline(cls, text: str) -> str: + """Pull the submission deadline out of an assignment row.""" + # A row also carries the *own* submission date, so prefer the labelled + # deadline and only fall back to the first date on the row. + labelled = re.search( + rf"(?:Beendet am|Abgabetermin|Abgabe bis|Frist)\D{{0,20}}?({cls._DATE})", + text, + ) + if labelled: + return labelled.group(1).strip() + first = re.search(cls._DATE, text) + return first.group(0).strip() if first else "" + + @staticmethod + def _extract_status(text: str) -> str: + """Classify a row's submission status, negations first. + + "abgegeben" is a substring of "nicht abgegeben", so the negative + variants have to be tested before the positive ones. + """ + lowered = text.lower() + # Submission state is the more useful answer; grading state only + # matters when the row says nothing about a submission. + for needle in ( + "nicht abgegeben", + "bereits abgegeben", + "abgegeben", + "submitted", + "nicht bewertet", + "bewertet", + ): + if needle in lowered: + return needle + return "" + # File submission def submit_file(self, ref_id: str, ass_id: str, local_path: str) -> dict[str, str]: @@ -87,14 +126,9 @@ def submit_file(self, ref_id: str, ass_id: str, local_path: str) -> dict[str, st file_id = self._dropzone_upload(upload_handler_url, path) # Step 3: POST form with the returned identifier - payload = {input_name: file_id} - post_resp = self.session.post( - urljoin(self.settings.ilias_base_url + "/", submit_url), - data=payload, - timeout=self.settings.timeout_seconds, - allow_redirects=True, + self._post( + submit_url, f"submission for ass_id={ass_id}", data={input_name: file_id} ) - post_resp.raise_for_status() return { "status": "submitted", @@ -129,7 +163,9 @@ def _parse_upload_form( html, ) if m: - upload_handler_url = urljoin(self.settings.ilias_base_url + "/", m.group(1)) + upload_handler_url = urljoin( + self.settings.ilias_base_url + "/", unescape(m.group(1)) + ) if not upload_handler_url: raise IliasExerciseError( @@ -145,13 +181,9 @@ def _parse_upload_form( def _dropzone_upload(self, upload_url: str, path: Path) -> str: """POST file to ILIAS Dropzone handler; return the identifier string.""" with path.open("rb") as fh: - resp = self.session.post( - upload_url, - files={"file": (path.name, fh)}, - timeout=self.settings.timeout_seconds, - allow_redirects=True, + resp = self._post( + upload_url, f"upload of {path.name}", files={"file": (path.name, fh)} ) - resp.raise_for_status() try: data = resp.json() except Exception as exc: @@ -195,13 +227,7 @@ def delete_submitted_files( # Step 1: confirmDeleteDelivered → shows confirmation page payload: list[tuple[str, str]] = [("delivered[]", did) for did in delivery_ids] payload.append(("cmd[confirmDeleteDelivered]", "Löschen")) - confirm_resp = self.session.post( - urljoin(self.settings.ilias_base_url + "/", form_action), - data=payload, - timeout=self.settings.timeout_seconds, - allow_redirects=True, - ) - confirm_resp.raise_for_status() + confirm_resp = self._post(form_action, "delete confirmation", data=payload) # Step 2: deleteDelivered → actual deletion confirm_action = self._extract_submission_form_action( @@ -211,18 +237,15 @@ def delete_submitted_files( ("delivered[]", did) for did in delivery_ids ] delete_payload.append(("cmd[deleteDelivered]", "Löschen")) - final_resp = self.session.post( - urljoin(self.settings.ilias_base_url + "/", confirm_action), - data=delete_payload, - timeout=self.settings.timeout_seconds, - allow_redirects=True, - ) - final_resp.raise_for_status() + final_resp = self._post(confirm_action, "file deletion", data=delete_payload) remaining = self._extract_submitted_files(final_resp.text) + remaining_ids = {entry["delivery_id"] for entry in remaining} + actually_deleted = [did for did in delivery_ids if did not in remaining_ids] return { - "status": "deleted", - "deleted_ids": delivery_ids, + "status": "deleted" if actually_deleted else "unchanged", + "deleted_ids": actually_deleted, + "not_deleted_ids": [d for d in delivery_ids if d in remaining_ids], "remaining_count": len(remaining), "remaining": remaining, } @@ -267,12 +290,11 @@ def _extract_submitted_files(self, html: str) -> list[dict[str, str]]: return files def _submission_screen_url(self, ref_id: str, ass_id: str) -> str: - assign_url = ( - f"{self.settings.ilias_base_url}/ilias.php" - f"?baseClass=ilrepositorygui&cmdClass=ilAssignmentPresentationGUI" - f"&cmd=showOverview&ref_id={ref_id}&ass_id={ass_id}&from_overview=1" + # The links carry a dynamic cmdNode and only exist on the exercise + # overview; ilAssignmentPresentationGUI redirects there without them. + resp = self._get( + self._overview_url(ref_id), f"exercise overview {ref_id}/{ass_id}" ) - resp = self._get(assign_url, f"assignment page {ref_id}/{ass_id}") screen_raw = self._find_url_with_ass_id( resp.text, r"ilias\.php\?[^'\"]*cmdClass=ilExSubmissionFileGUI&cmd=submissionScreen[^'\"]*", @@ -292,7 +314,9 @@ def search_users(self, ref_id: str, ass_id: str, term: str) -> list[dict[str, st """Search ILIAS users by name fragment; returns login name + display label.""" self.auth_service.ensure_logged_in() ac_url = self._autocomplete_url(ref_id, ass_id) - resp = self._get(ac_url + f"&term={term}", "user autocomplete") + # Names contain spaces and umlauts; an unencoded term truncates the + # query or injects extra parameters. + resp = self._get(f"{ac_url}&term={quote(term)}", "user autocomplete") try: data = resp.json() except Exception as exc: @@ -318,7 +342,7 @@ def _autocomplete_url(self, ref_id: str, ass_id: str) -> str: team_resp.text, ) if m: - return urljoin(self.settings.ilias_base_url + "/", m.group(0)) + return urljoin(self.settings.ilias_base_url + "/", unescape(m.group(0))) # Fallback using known pattern return ( f"{self.settings.ilias_base_url}/ilias.php" @@ -344,25 +368,28 @@ def add_team_member( page_resp.text, ref_id, ass_id ) + before = {m.user_id for m in self._extract_team_members(page_resp.text)} + payload = { "user_login": username, "cmd[addUserFromAutoComplete]": "Hinzufügen", "rtoken": rtoken, } - resp = self.session.post( - urljoin(self.settings.ilias_base_url + "/", post_url), - data=payload, - timeout=self.settings.timeout_seconds, - allow_redirects=True, - ) - resp.raise_for_status() + resp = self._post(post_url, f"team addition of {username}", data=payload) - # Verify the member now appears on the team page + # Only report success when the team actually grew -- ILIAS answers an + # ignored POST with HTTP 200 and the unchanged team page. updated_members = self._extract_team_members(resp.text) + added = {m.user_id for m in updated_members} - before names = [m.name for m in updated_members] return { - "status": "ok", - "username_added": username, + "status": "ok" if added else "unchanged", + "username_added": username if added else "", + "message": ( + f"Added {username} to the team." + if added + else f"ILIAS did not add {username}; the team is unchanged." + ), "current_team": ", ".join(names) if names else "(no members listed)", } @@ -376,27 +403,64 @@ def remove_team_member( page_resp.text, ref_id, ass_id ) + before = {m.user_id for m in self._extract_team_members(page_resp.text)} + payload = { "id[]": user_id, "cmd[confirmRemoveTeamMember]": "Entfernen", "rtoken": rtoken, } - resp = self.session.post( - urljoin(self.settings.ilias_base_url + "/", post_url), - data=payload, - timeout=self.settings.timeout_seconds, - allow_redirects=True, - ) - resp.raise_for_status() + resp = self._post(post_url, f"team removal of user_id={user_id}", data=payload) + + # confirmRemoveTeamMember only renders a confirmation screen. Submit the + # follow-up command it offers, otherwise nothing is ever removed. + confirmation = self._find_confirmation_command(resp.text, "removeteammember") + if confirmation: + confirm_action, cmd_name = confirmation + resp = self._post( + confirm_action, + f"team removal confirmation for user_id={user_id}", + data={ + "id[]": user_id, + cmd_name: "Entfernen", + "rtoken": self._extract_rtoken(confirm_action) or rtoken, + }, + ) updated_members = self._extract_team_members(resp.text) + removed = before - {m.user_id for m in updated_members} names = [m.name for m in updated_members] return { - "status": "ok", - "user_id_removed": user_id, + "status": "ok" if removed else "unchanged", + "user_id_removed": user_id if removed else "", + "message": ( + f"Removed user_id {user_id} from the team." + if removed + else f"ILIAS did not remove user_id {user_id}; the team is unchanged." + ), "current_team": ", ".join(names) if names else "(no members listed)", } + @staticmethod + def _find_confirmation_command( + html: str, action_keyword: str + ) -> tuple[str, str] | None: + """Find the real command button on an ILIAS confirmation screen. + + Returns (form_action, cmd_field_name), skipping the ``confirm...`` + command that produced the screen in the first place. + """ + soup = BeautifulSoup(html, "html.parser") + for form in soup.find_all("form"): + for button in form.find_all(["input", "button"]): + name = str(button.get("name", "")) + lowered = name.lower() + if not lowered.startswith("cmd["): + continue + if action_keyword in lowered and "confirm" not in lowered: + return str(form.get("action", "")), name + return None + def _extract_team_members(self, html: str) -> list[TeamMember]: soup = BeautifulSoup(html, "html.parser") members: list[TeamMember] = [] @@ -426,7 +490,13 @@ def _team_post_url_and_rtoken( for form in soup.find_all("form"): action = str(form.get("action", "")) if "TeamGUI" in action or "addUserFromAutoComplete" in str(form): + # ILIAS puts the CSRF token either in the action query string + # or in a hidden field; without it the POST is silently ignored. rtoken = self._extract_rtoken(action) + if not rtoken: + field = form.find("input", attrs={"name": "rtoken"}) + if field is not None: + rtoken = str(field.get("value", "")).strip() return action, rtoken raise IliasExerciseError( f"Team form not found for ref_id={ref_id}, ass_id={ass_id}" @@ -435,24 +505,23 @@ def _team_post_url_and_rtoken( # Helpers def _overview_url(self, ref_id: str) -> str: + # Without mode=all ILIAS renders only currently running assignments, so + # past and upcoming Übungsblätter would silently be missing. return ( f"{self.settings.ilias_base_url}/ilias.php" f"?baseClass=ilrepositorygui&cmdClass=ilObjExerciseGUI" - f"&cmd=showOverview&ref_id={ref_id}" + f"&cmd=showOverview&ref_id={ref_id}&mode=all&from_overview=1" ) def _upload_form_url(self, ref_id: str, ass_id: str) -> str: - # Navigate via assignment overview → submission screen → upload form + # Navigate via exercise overview → submission screen → upload form # to discover the dynamic cmdNode at each step. - assign_url = ( - f"{self.settings.ilias_base_url}/ilias.php" - f"?baseClass=ilrepositorygui&cmdClass=ilAssignmentPresentationGUI" - f"&cmd=showOverview&ref_id={ref_id}&ass_id={ass_id}&from_overview=1" + assign_resp = self._get( + self._overview_url(ref_id), f"exercise overview {ref_id}/{ass_id}" ) - assign_resp = self._get(assign_url, f"assignment page {ref_id}/{ass_id}") - # Find submission screen URL matching the correct ass_id (the page may - # contain links to other assignments' screens — pick the right one). + # Find submission screen URL matching the correct ass_id (the page + # contains links for every assignment — pick the right one). screen_raw = self._find_url_with_ass_id( assign_resp.text, r"ilias\.php\?[^'\"]*cmdClass=ilExSubmissionFileGUI&cmd=submissionScreen[^'\"]*", @@ -470,18 +539,15 @@ def _upload_form_url(self, ref_id: str, ass_id: str) -> str: screen_resp.text, ) if m2: - return urljoin(self.settings.ilias_base_url + "/", m2.group(0)) + return urljoin(self.settings.ilias_base_url + "/", unescape(m2.group(0))) # Fallback: replace cmd in the screen URL return screen_url.replace("cmd=submissionScreen", "cmd=uploadForm") def _team_url(self, ref_id: str, ass_id: str) -> str: - # Load assignment presentation to discover the dynamic cmdNode for TeamGUI - assign_url = ( - f"{self.settings.ilias_base_url}/ilias.php" - f"?baseClass=ilrepositorygui&cmdClass=ilAssignmentPresentationGUI" - f"&cmd=showOverview&ref_id={ref_id}&ass_id={ass_id}&from_overview=1" + # Load the exercise overview to discover the dynamic cmdNode for TeamGUI + resp = self._get( + self._overview_url(ref_id), f"exercise overview {ref_id}/{ass_id}" ) - resp = self._get(assign_url, f"assignment page {ref_id}/{ass_id}") team_raw = self._find_url_with_ass_id( resp.text, r"ilias\.php\?[^'\"]*cmdClass=ilExSubmissionTeamGUI&cmd=submissionScreenTeam[^'\"]*", @@ -522,8 +588,19 @@ def _extract_rtoken(url: str) -> str: def _get(self, url: str, label: str) -> requests.Response: try: - resp = self.session.get(url, timeout=self.settings.timeout_seconds) + return self.auth_service.get(url) + except requests.RequestException as exc: + raise IliasExerciseError(f"Failed to fetch {label}: {exc}") from exc + + def _post(self, url: str, label: str, **kwargs: object) -> requests.Response: + """POST relative to the ILIAS base URL, surfacing transport errors.""" + kwargs.setdefault("timeout", self.settings.timeout_seconds) + kwargs.setdefault("allow_redirects", True) + try: + resp = self.session.post( + urljoin(self.settings.ilias_base_url + "/", url), **kwargs + ) resp.raise_for_status() return resp except requests.RequestException as exc: - raise IliasExerciseError(f"Failed to fetch {label}: {exc}") from exc + raise IliasExerciseError(f"Failed to submit {label}: {exc}") from exc diff --git a/src/services/news_service.py b/src/services/news_service.py index f854c46..f146886 100644 --- a/src/services/news_service.py +++ b/src/services/news_service.py @@ -1,7 +1,7 @@ from __future__ import annotations -from urllib.parse import parse_qs, urljoin, urlparse import re +from urllib.parse import parse_qs, urljoin, urlparse import requests from bs4 import BeautifulSoup, Tag @@ -24,13 +24,8 @@ def __init__( self.auth_service = auth_service def list_dashboard_news(self, limit: int = 30) -> list[NewsItem]: - self.auth_service.ensure_logged_in() try: - resp = self.session.get( - self.settings.dashboard_news_url, - timeout=self.settings.timeout_seconds, - ) - resp.raise_for_status() + resp = self.auth_service.get(self.settings.dashboard_news_url) except requests.RequestException as exc: raise IliasNewsError(f"Failed to fetch dashboard news: {exc}") from exc diff --git a/src/services/repository_service.py b/src/services/repository_service.py index fdac1bb..2ac5968 100644 --- a/src/services/repository_service.py +++ b/src/services/repository_service.py @@ -4,6 +4,7 @@ from email.message import Message from io import BytesIO from pathlib import Path +from typing import ClassVar from urllib.parse import parse_qs, unquote, urljoin, urlparse import requests @@ -20,7 +21,15 @@ class IliasRepositoryError(RuntimeError): class RepositoryService: - CONTAINER_TYPES = {"category", "course", "folder", "group", "root", "item"} + CONTAINER_TYPES: ClassVar[set[str]] = { + "category", + "course", + "exercise", + "folder", + "group", + "root", + "item", + } def __init__( self, settings: Settings, session: requests.Session, auth_service: AuthService @@ -228,7 +237,13 @@ def get_item_details(self, ref_id: str) -> dict[str, str]: title = self._clean(title_node.get_text(" ", strip=True)) if title_node else "" file_url = self._detect_file_url(soup, ref_id) - if not file_url and self._page_looks_like_file_object(soup, ref_id): + if ( + not file_url + and self._page_looks_like_file_object(soup, ref_id) + # A container page also links to ilObjFileGUI (for its children), so + # only guess at a download URL when the page lists no child items. + and not self._extract_items(resp.text, current_ref_id=ref_id) + ): file_url = self._permanent_file_download_url(ref_id) return { @@ -359,13 +374,21 @@ def _item_from_linkish( return RepositoryItem(title=title, item_type=item_type, url=url, ref_id=ref_id) def _detect_file_url(self, soup: BeautifulSoup, ref_id: str) -> str: + # A container page also lists download links for the files it contains, + # so a match is only this object's download URL when the ref_id agrees. + # Otherwise download_file() would return the first child file. + def matches(href: str) -> bool: + if not self._is_download_href(href): + return False + return self._extract_ref_id(self._normalize_url(href)) == ref_id + for link in soup.find_all(["a", "button"], href=True): href = str(link.get("href", "")).strip() - if self._is_download_href(href): + if matches(href): return self._normalize_url(href) for node in soup.find_all(["a", "button"], attrs={"data-action": True}): href = str(node.get("data-action", "")).strip() - if self._is_download_href(href): + if matches(href): return self._normalize_url(href) return "" @@ -401,17 +424,15 @@ def _download_response(self, file_url: str, ref_id: str) -> requests.Response: last_error: Exception | None = None for url in candidates: try: - resp = self.session.get( - url, timeout=self.settings.timeout_seconds, allow_redirects=True - ) - resp.raise_for_status() + resp = self.auth_service.get(url, allow_redirects=True) except requests.RequestException as exc: last_error = exc continue if not self._looks_like_html_page(resp): return resp last_error = IliasRepositoryError( - f"Download URL returned HTML instead of a file: {url}" + f"{url} served an ILIAS page rather than a file download " + f"(ref_id={ref_id} is probably a folder/course, not a file)" ) raise IliasRepositoryError( @@ -420,9 +441,7 @@ def _download_response(self, file_url: str, ref_id: str) -> requests.Response: def _get(self, url: str, label: str) -> requests.Response: try: - resp = self.session.get(url, timeout=self.settings.timeout_seconds) - resp.raise_for_status() - return resp + return self.auth_service.get(url) except requests.RequestException as exc: raise IliasRepositoryError(f"Failed to fetch {label}: {exc}") from exc @@ -472,7 +491,7 @@ def _extract_ref_id(url: str) -> str: @staticmethod def _is_repository_href(href: str) -> bool: lower = href.lower() - if not href or href.startswith("#") or href.startswith("javascript:"): + if not href or href.startswith(("#", "javascript:")): return False return "ref_id=" in lower or "/go/" in lower or "goto.php?target=" in lower @@ -518,6 +537,14 @@ def _guess_item_type(url: str, icon_alt: str, title: str = "") -> str: return "group" if "ilobjforumgui" in text or "forum" in text: return "forum" + # Exercises drive the submission tools, so they deserve their own type + # instead of the generic "item" bucket. + if ( + "ilexercisehandlergui" in text + or "ilobjexercisegui" in text + or "/go/exc/" in text + ): + return "exercise" return "item" @staticmethod @@ -528,14 +555,20 @@ def _clean(text: str) -> str: def _looks_like_pdf(blob: bytes) -> bool: return blob[:5] == b"%PDF-" - @staticmethod - def _looks_like_html_page(resp: requests.Response) -> bool: + @classmethod + def _looks_like_html_page(cls, resp: requests.Response) -> bool: + # ILIAS serves every real file download with a Content-Disposition + # filename, while its UI and error pages never set the header. Uploaded + # .html files are therefore indistinguishable from error pages by + # content type alone -- trust the header instead. + disposition = resp.headers.get("Content-Disposition", "") + if cls._filename_from_content_disposition(disposition): + return False + content_type = (resp.headers.get("Content-Type") or "").lower() head = resp.content[:200].lstrip().lower() - return ( - "text/html" in content_type - or head.startswith(b" + Abmelden +

Angemeldet

+ +""" + +LOGIN_PAGE = """ + +
+ + +
+ +""" + + +def _response(body: str, content_type: str = "text/html; charset=UTF-8"): + resp = requests.Response() + resp._content = body.encode() + resp.headers["Content-Type"] = content_type + return resp + + +def test_expired_session_page_is_recognised() -> None: + # ILIAS answers an expired session with HTTP 200 and the login form. + assert AuthService._looks_like_login_page(_response(LOGIN_PAGE)) is True + + +def test_authenticated_page_is_not_mistaken_for_login() -> None: + assert AuthService._looks_like_login_page(_response(LOGGED_IN_PAGE)) is False + + +def test_binary_download_is_never_treated_as_login_page() -> None: + # A PDF must not be decoded and sniffed for login markers. + resp = _response("%PDF-1.7 nonsense", content_type="application/pdf") + assert AuthService._looks_like_login_page(resp) is False diff --git a/tests/test_exercise_service.py b/tests/test_exercise_service.py new file mode 100644 index 0000000..d415d11 --- /dev/null +++ b/tests/test_exercise_service.py @@ -0,0 +1,107 @@ +from services.exercise_service import ExerciseService + +# ILIAS shows a confirmation screen before actually removing a team member. +CONFIRM_SCREEN = """ +
+ + +
+""" + +# The page that produced the confirmation only offers the confirm command. +TEAM_SCREEN = """ +
+ +
+""" + + +def test_confirmation_command_is_found_on_confirm_screen() -> None: + found = ExerciseService._find_confirmation_command( + CONFIRM_SCREEN, "removeteammember" + ) + assert found is not None + action, cmd_name = found + assert cmd_name == "cmd[removeTeamMember]" + assert "rtoken=abc123" in action + + +def test_confirm_command_itself_is_not_reused() -> None: + # Re-posting cmd[confirmRemoveTeamMember] would loop on the same screen. + assert ( + ExerciseService._find_confirmation_command(TEAM_SCREEN, "removeteammember") + is None + ) + + +# Real row text from an ILIAS "mode=all" assignment overview. +SUBMITTED_ROW = ( + "Beendet Blatt 1 Bereits abgegebene Dateien Beendet am 4. Mai 2026, 08:00 " + "Anforderung Verpflichtend Datum der letzten Abgabe 3. Mai 2026, 09:51 " + "Type Datei Status Nicht bewertet" +) + + +def test_deadline_parses_german_long_form_dates() -> None: + # ILIAS writes "4. Mai 2026, 08:00", never "04.05.2026". + assert ExerciseService._extract_deadline(SUBMITTED_ROW) == "4. Mai 2026, 08:00" + + +def test_deadline_prefers_the_deadline_over_the_submission_date() -> None: + # "Datum der letzten Abgabe 3. Mai 2026" must not win over "Beendet am". + assert "3. Mai" not in ExerciseService._extract_deadline(SUBMITTED_ROW) + + +def test_deadline_still_parses_numeric_dates() -> None: + assert ( + ExerciseService._extract_deadline("Abgabetermin 04.05.2026 08:00") + == "04.05.2026 08:00" + ) + + +def test_deadline_is_empty_when_row_has_no_date() -> None: + assert ExerciseService._extract_deadline("Blatt 1 Verpflichtend") == "" + + +def test_status_reports_submission_not_grading() -> None: + assert ExerciseService._extract_status(SUBMITTED_ROW) == "bereits abgegeben" + + +def test_unsubmitted_row_is_not_reported_as_submitted() -> None: + # "abgegeben" is a substring of "nicht abgegeben" -- order matters. + assert ( + ExerciseService._extract_status("Blatt 2 Nicht abgegeben") == "nicht abgegeben" + ) + + +def test_rtoken_is_read_from_the_form_action() -> None: + assert ( + ExerciseService._extract_rtoken( + "/ilias.php?cmdClass=ilExSubmissionTeamGUI&rtoken=abc123" + ) + == "abc123" + ) + + +def test_find_url_with_ass_id_prefers_the_requested_assignment() -> None: + html = ( + "ilias.php?cmdClass=ilExSubmissionFileGUI&cmd=submissionScreen&ass_id=1 " + "ilias.php?cmdClass=ilExSubmissionFileGUI&cmd=submissionScreen&ass_id=42" + ) + url = ExerciseService._find_url_with_ass_id( + html, + r"ilias\.php\?[^'\"\s]*cmdClass=ilExSubmissionFileGUI&cmd=submissionScreen[^'\"\s]*", + "42", + ) + assert url.endswith("ass_id=42") + + +def test_find_url_with_ass_id_unescapes_html_entities() -> None: + html = "ilias.php?cmdClass=ilExSubmissionFileGUI&cmd=submissionScreen&ass_id=42" + url = ExerciseService._find_url_with_ass_id( + html, + r"ilias\.php\?[^'\"\s]*cmdClass=ilExSubmissionFileGUI&cmd=submissionScreen[^'\"\s]*", + "42", + ) + assert "&" not in url + assert url.endswith("ass_id=42") diff --git a/tests/test_repository_service.py b/tests/test_repository_service.py index 3e3c3c0..8c88135 100644 --- a/tests/test_repository_service.py +++ b/tests/test_repository_service.py @@ -1,3 +1,6 @@ +import requests +from bs4 import BeautifulSoup + from core.config import Settings from services.repository_service import RepositoryService @@ -82,5 +85,80 @@ def test_permanent_download_url_matches_ilias_file_goto_route() -> None: ) +FOLDER_PAGE = """ +
+ Slides + Notes +
+""" + +FILE_PAGE = """ + +""" + + +def test_detect_file_url_ignores_downloads_of_contained_files() -> None: + # A folder page lists its children's download links; none belong to the + # folder itself, so download_file() must not grab the first child. + soup = BeautifulSoup(FOLDER_PAGE, "html.parser") + assert _service()._detect_file_url(soup, "111") == "" + + +def test_detect_file_url_returns_download_for_matching_ref_id() -> None: + soup = BeautifulSoup(FILE_PAGE, "html.parser") + assert _service()._detect_file_url(soup, "222").endswith("ref_id=222") + + +def test_detect_file_url_matches_goto_download_target() -> None: + soup = BeautifulSoup(FOLDER_PAGE, "html.parser") + assert _service()._detect_file_url(soup, "333").endswith("file_333_download") + + +def _response(content: bytes, **headers: str) -> requests.Response: + resp = requests.Response() + resp._content = content + resp.headers.update(headers) + return resp + + +def test_uploaded_html_file_is_not_treated_as_an_error_page() -> None: + # ILIAS serves uploaded .html files as text/html, but with a filename. + resp = _response( + b"Reaction test", + **{ + "Content-Type": "text/html;charset=UTF-8", + "Content-Disposition": 'attachment; filename="A.1.html"', + }, + ) + assert RepositoryService._looks_like_html_page(resp) is False + + +def test_inline_pdf_download_is_not_treated_as_an_error_page() -> None: + resp = _response( + b"%PDF-1.7\n", + **{ + "Content-Type": "application/pdf", + "Content-Disposition": 'inline; filename="fsub-01.pdf"', + }, + ) + assert RepositoryService._looks_like_html_page(resp) is False + + +def test_ilias_ui_page_without_disposition_is_still_rejected() -> None: + # Folder views and permission errors come back as HTML with no filename. + resp = _response( + b"ILIAS", + **{"Content-Type": "text/html; charset=UTF-8"}, + ) + assert RepositoryService._looks_like_html_page(resp) is True + + +def test_html_body_without_content_type_is_still_rejected() -> None: + resp = _response(b" error") + assert RepositoryService._looks_like_html_page(resp) is True + + def test_fix_mojibake_filename() -> None: assert RepositoryService._fix_mojibake("Übungsblatt03.pdf") == "Übungsblatt03.pdf" From 6f1e6da83ffd33b875310b6998dccb388cac54f8 Mon Sep 17 00:00:00 2001 From: st187468 Date: Tue, 11 Aug 2026 18:31:25 +0200 Subject: [PATCH 2/2] fix: pin mcp below 2.0.0 mcp 2.0.0 removed create_connected_server_and_client_session from mcp.shared.memory, which tests/test_mcp_server.py imports, so a fresh install resolved to 2.0.0 and broke collection. Earlier CI runs were green only because they predate the 2.0.0 release. Pinning keeps the currently supported API; migrating to the 2.x interface is a separate change. --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 7d19001..1ba7808 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ description = "MCP server for listing ILIAS courses" readme = "README.md" requires-python = ">=3.11" dependencies = [ - "mcp>=1.9.0", + "mcp>=1.9.0,<2.0.0", "requests>=2.32.0", "beautifulsoup4>=4.12.0", "python-dotenv>=1.0.0",