From 3e37df980c6e359b739577ab0d58072e002ae93a Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Thu, 8 Oct 2026 02:19:26 +0330 Subject: [PATCH] fix: restore Ravin login and scanning compatibility - Fall back to Chromium when Firefox/Zen SSO fails - Restore saved browser sessions and follow login tabs - Validate LMS responses before saving scan results - Preserve local exams when linked quizzes are hidden - Add regression tests and bump version to 0.16.3 --- CHANGELOG.md | 22 +++ README.md | 19 +++ pyproject.toml | 4 +- src/ravin/assessments.py | 11 +- src/ravin/auth.py | 259 ++++++++++++++++++++++++++++++---- src/ravin/client.py | 34 ++++- src/ravin/constants.py | 2 +- tests/test_assessments.py | 29 ++++ tests/test_auth_update.py | 285 ++++++++++++++++++++++++++++++++++++++ tests/test_ravin.py | 11 +- 10 files changed, 632 insertions(+), 44 deletions(-) create mode 100644 tests/test_auth_update.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f6339eb..e8ec1ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ All notable changes to this project will be documented here. +## 0.16.3 - 2026-10-08 + +- Recover from Ravin single-sign-on rejecting Firefox/Zen keys by transferring the authorized portal session to a persistent Chromium browser. +- Reuse the successful Chromium profile on subsequent logins, without repeating the failed Firefox transfer. +- Include Playwright with the base installation so Chromium does not depend on a downloadable ChromeDriver. +- Preserve linked local exams and their artifacts when Moodle hides or removes the linked quiz; reconnect when it reappears. +- Verify the installed login command against the live LMS and scan all enrolled courses. + +## 0.16.2 - 2026-10-08 + +- Reuse an authenticated persistent Moodle browser profile before launching portal single sign-on. +- Activate the portal's actual course link once, preserving normal browser navigation and event handlers. +- Follow newly opened login tabs and report invalid sign-in keys without replaying the transfer. +- Keep credential submission limited to the configured login and Moodle origins. + +## 0.16.1 - 2026-10-08 + +- Recognize authenticated Moodle sessions in the updated Ravin theme without a static logout link. +- Follow Moodle launch links inside closed portal dropdowns and wait for manual CAPTCHA login. +- Reject guest sessions, malformed course-list responses, expired course/activity pages, and unrecognized course layouts before writing scan results. +- Fix error reporting for rejected web logins. + ## 0.16.0 - 2026-08-30 - Treat Moodle activity IDs as stable local bundle identities while retaining sortable `SECTION--POSITION--ID` paths. diff --git a/README.md b/README.md index c022d35..8f7b981 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,25 @@ ravin scan --offline `ravin login` opens a persistent, Git-ignored browser profile. For Ravin Academy it begins at `https://lms.ravinacademy.com/`, follows the Moodle launch into `training.ravinacademy.com`, and stores the resulting User-Agent and cookies in `.env`. +If the account portal shows a CAPTCHA, complete the login in that browser window. +The command waits for you and does not submit the CAPTCHA form automatically. +It first checks the persistent browser's existing Moodle session. If login is +needed, it clicks the dashboard's course or **Offline class** link once (including +links in closed dropdowns), follows a newly opened login tab, and recognizes the +new Moodle theme without requiring a logout link. If the portal rejects a sign-in +key, the command does not replay that key or repeatedly launch single sign-on. +If Ravin rejects a Firefox/Zen transfer, the command switches to Chromium with the +existing authorized portal session. Later logins reuse that separate persistent +Chromium profile. Install the Chromium browser once if it is not already available: + +```bash +python -m playwright install chromium +``` + +Logging in through Codex's internal browser does not refresh the separate session +used by this command. After a site update or rejected session, run `ravin login` +and then `ravin scan` to scan all enrolled courses. + Missing credentials are requested interactively. You can also copy [`.env.example`](.env.example) and fill it yourself: ```dotenv diff --git a/pyproject.toml b/pyproject.toml index d5c5fba..a8154fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "ravin-moodle-downloader" -version = "0.16.0" +version = "0.16.3" description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials" readme = "README.md" requires-python = ">=3.10" @@ -24,7 +24,7 @@ classifiers = [ "Programming Language :: Python :: 3.14", "Topic :: Education", ] -dependencies = ["selenium>=4.46,<5", "argcomplete>=3.6,<4"] +dependencies = ["selenium>=4.46,<5", "argcomplete>=3.6,<4", "playwright>=1.50,<2"] [project.optional-dependencies] pdf = ["playwright>=1.50,<2", "markdown-it-py>=3,<5"] diff --git a/src/ravin/assessments.py b/src/ravin/assessments.py index 8b11435..f6ffd85 100644 --- a/src/ravin/assessments.py +++ b/src/ravin/assessments.py @@ -99,6 +99,8 @@ def merge_assessments(public: Path, course: dict[str, Any]) -> dict[str, Any]: raise MoodleError( f"invalid activity ID for assessment {assessment['id']}: {activity_id!r}" ) from exc + if resolved_activity_id <= 0: + raise MoodleError(f"invalid activity ID for assessment {assessment['id']}: {activity_id!r}") for section in sections: for item in section.get("items", []): if int(item.get("activity_id") or 0) == resolved_activity_id: @@ -106,11 +108,9 @@ def merge_assessments(public: Path, course: dict[str, Any]) -> dict[str, Any]: break if linked is not None: break - if linked is None: - raise MoodleError( - f"assessment {assessment['id']} links to missing activity {resolved_activity_id} " - f"in course {course_id}" - ) + # A linked quiz can disappear from the visible LMS tree. Its local + # assessment and stable artifact bundle must survive that scan; + # retain the desired link so it reconnects if the quiz reappears. common = { "assessment_id": assessment["id"], @@ -134,6 +134,7 @@ def merge_assessments(public: Path, course: dict[str, Any]) -> dict[str, Any]: "section_id": None, "section_number": None, "activity_id": None, + "linked_activity_id": int(activity_id) if activity_id is not None else None, "activity_position": position, "activity_type": "assessment", "title": assessment["title"], diff --git a/src/ravin/auth.py b/src/ravin/auth.py index 415fafa..343a6b6 100644 --- a/src/ravin/auth.py +++ b/src/ravin/auth.py @@ -17,6 +17,10 @@ from .constants import DEFAULT_RAVIN_LOGIN_URL, ENV_KEYS from .models import MoodleError +class _InvalidSSOKey(MoodleError): + """The portal transfer failed before establishing a Moodle session.""" + + def _env_value(args: argparse.Namespace, key: str) -> str: return os.environ.get(key) or args.env_values.get(key, "") @@ -163,6 +167,169 @@ def _browser_login_url(args: argparse.Namespace) -> str: return urllib.parse.urljoin(args.site.rstrip("/") + "/", "my/courses.php") +def _authenticated_browser_session(driver, site: str) -> tuple[str, str] | None: + """Capture only a signed-in Moodle page on the configured site.""" + location = urllib.parse.urlsplit(driver.current_url) + target = urllib.parse.urlsplit(site) + if (location.scheme, location.netloc.casefold()) != (target.scheme, target.netloc.casefold()): + return None + if "/login/" in location.path or location.path.endswith("/auth/userkey/login.php"): + return None + logged_in = driver.execute_script( + """return Boolean( + window.M && M.cfg && Number(M.cfg.userId) > 0 && M.cfg.sesskey + );""" + ) + if not logged_in: + return None + cookie_header = "; ".join( + f"{cookie['name']}={cookie['value']}" + for cookie in driver.get_cookies() + if cookie.get("name") and cookie.get("value") + ) + if not cookie_header: + raise MoodleError("browser login succeeded, but no site cookies were available") + return str(driver.execute_script("return navigator.userAgent;")), cookie_header + + +def _select_login_tab(driver, known_handles: set[str]) -> set[str]: + """Follow a newly opened login tab, or recover when the active tab closes.""" + from selenium.common.exceptions import NoSuchWindowException + + handles = driver.window_handles + if not handles: + raise MoodleError("the authentication browser was closed before login finished") + new_handles = [handle for handle in handles if handle not in known_handles] + if new_handles: + driver.switch_to.window(new_handles[-1]) + else: + try: + current = driver.current_window_handle + except NoSuchWindowException: + current = None + if current not in handles: + driver.switch_to.window(handles[-1]) + return set(handles) + + +def _launch_moodle_from_portal(driver, login_url: str, by) -> bool: + """Activate the actual portal link so browser navigation preserves its context.""" + links = driver.find_elements(by.CSS_SELECTOR, 'a[href*="/moodle/login_student_user/"]') + candidates = [ + link for link in links + if urllib.parse.urlsplit(link.get_attribute("href") or "").hostname + == urllib.parse.urlsplit(login_url).hostname + ] + if not candidates: + return False + visible = next((link for link in candidates if link.is_displayed()), None) + if visible is not None: + visible.click() + else: + # Closed dropdowns still contain the real link and its event handlers. + driver.execute_script("arguments[0].click();", candidates[0]) + return True + + +def _capture_chromium_session(args: argparse.Namespace, portal_cookies=()) -> tuple[str, str]: + """Use a persistent Chromium context when Firefox's portal transfer fails.""" + try: + from playwright.sync_api import sync_playwright, Error as PlaywrightError + except ImportError as exc: + raise MoodleError("Chromium login requires Playwright; reinstall the updated package") from exc + + profile = args.browser_profile.expanduser().resolve() / "chromium" + profile.mkdir(parents=True, exist_ok=True, mode=0o700) + deadline = time.monotonic() + max(args.login_timeout, 30) + login_url = _browser_login_url(args) + target = urllib.parse.urlsplit(args.site) + saved = _browser_session_values(args) + # A browser restart may discard session-only cookies. Rehydrate only a + # previous Chromium session, using its matching User-Agent. + chromium_saved = saved if saved and "Chrome/" in saved[0] and not portal_cookies else None + with sync_playwright() as playwright: + if not Path(playwright.chromium.executable_path).is_file(): + raise MoodleError("Chromium is not installed. Run `python -m playwright install chromium` and retry login") + try: + context = playwright.chromium.launch_persistent_context( + str(profile), headless=False, + **({"user_agent": chromium_saved[0]} if chromium_saved else {}), + ) + try: + if chromium_saved: + context.add_cookies([ + {"name": name.strip(), "value": value, "url": args.site.rstrip("/") + "/", "secure": target.scheme == "https"} + for pair in chromium_saved[1].split(";") + for name, separator, value in [pair.strip().partition("=")] + if separator and name.strip() + ]) + if portal_cookies: + # Keep the authorized portal session when changing engines. + # Analytics cookies are unnecessary and can have invalid flags. + cookies = [] + for cookie in portal_cookies: + if cookie["name"].startswith(("_ga", "_gid", "_gat")): + continue + copied = {key: cookie[key] for key in ("name", "value", "domain", "path")} + copied.update(secure=cookie.get("secure", False), httpOnly=cookie.get("httpOnly", False)) + if cookie.get("expiry"): + copied["expires"] = cookie["expiry"] + cookies.append(copied) + context.add_cookies(cookies) + page = context.pages[0] if context.pages else context.new_page() + page.goto(args.site.rstrip("/") + "/my/courses.php") + launched = False + opened_portal = False + known_pages = set(context.pages) + while time.monotonic() < deadline: + pages = [item for item in context.pages if not item.is_closed()] + if not pages: + raise MoodleError("the authentication browser was closed before login finished") + new_pages = [item for item in pages if item not in known_pages] + if new_pages or page.is_closed(): + page = (new_pages or pages)[-1] + known_pages = set(pages) + location = urllib.parse.urlsplit(page.url) + if (location.scheme, location.netloc.casefold()) == (target.scheme, target.netloc.casefold()): + if page.locator('a[href*="/error/moodle/invalidkey"]').count(): + raise _InvalidSSOKey("Moodle rejected the portal sign-in key in Chromium too; no new session was saved") + if "/login/" not in location.path and page.evaluate( + "Boolean(window.M && M.cfg && Number(M.cfg.userId) > 0 && M.cfg.sesskey)" + ): + cookie_header = "; ".join( + f"{cookie['name']}={cookie['value']}" for cookie in context.cookies(page.url) + if cookie.get("name") and cookie.get("value") + ) + if not cookie_header: + raise MoodleError("Chromium login succeeded, but no cookies were available") + return page.evaluate("navigator.userAgent"), cookie_header + if not opened_portal: + page.goto(login_url) + opened_portal = True + continue + if not launched and location.hostname == urllib.parse.urlsplit(login_url).hostname: + links = page.locator('a[href*="/moodle/login_student_user/"]').all() + links = [link for link in links if urllib.parse.urlsplit( + urllib.parse.urljoin(page.url, link.get_attribute("href") or "") + ).hostname == location.hostname] + if links: + visible = next((link for link in links if link.is_visible()), None) + if visible is not None: + visible.click() + else: + links[0].evaluate("element => element.click()") + launched = True + print("Opening the Moodle course portal in Chromium...", file=sys.stderr) + continue + time.sleep(1) + raise MoodleError(f"Chromium login did not finish within {max(args.login_timeout, 30)} seconds") + finally: + context.close() + except PlaywrightError as exc: + # Browser exceptions can embed the one-time login URL. + raise MoodleError("Chromium authentication could not complete; check the browser or retry login") from None + + def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]: """Open an installed browser through Selenium and capture its authenticated session.""" try: @@ -189,6 +356,10 @@ def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]: except OSError: pass + if not args.browser_executable and (profile / "chromium" / "Local State").is_file(): + print("Opening the previously verified Chromium login profile...", file=sys.stderr) + return _capture_chromium_session(args) + browser_name = executable.name.casefold() try: if "firefox" in browser_name or "zen" in browser_name: @@ -223,55 +394,76 @@ def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]: print(f"Opening {executable.name} for LMS authentication...", file=sys.stderr) print("Complete Cloudflare or LMS login in that window if requested.", file=sys.stderr) try: + # A persistent profile may already hold a valid Moodle session. Reuse it + # before issuing another single-sign-on launch from the account portal. + driver.get(args.site.rstrip("/") + "/my/courses.php") + session = _authenticated_browser_session(driver, args.site) + if session is not None: + return session driver.get(login_url) + known_handles = set(driver.window_handles) + launched_moodle = False submitted_credentials = False credential_attempts = 0 + captcha_notice_shown = False last_location = "" while time.monotonic() < deadline: + known_handles = _select_login_tab(driver, known_handles) current_location = urllib.parse.urlsplit(driver.current_url)._replace(query="", fragment="").geturl() if current_location != last_location: print(f"Browser is at {current_location}", file=sys.stderr) last_location = current_location try: - logged_in = bool( - driver.execute_script( - """return Boolean( - window.M && M.cfg && Number(M.cfg.userId) > 0 && - document.querySelector('a[href*="/login/logout.php"]') - );""" - ) - ) + session = _authenticated_browser_session(driver, args.site) except WebDriverException: - logged_in = False - if logged_in: - cookies = driver.get_cookies() - user_agent = str(driver.execute_script("return navigator.userAgent;")) - cookie_header = "; ".join( - f"{cookie['name']}={cookie['value']}" - for cookie in cookies - if cookie.get("name") and cookie.get("value") + session = None + if session is not None: + return session + + if driver.find_elements(By.CSS_SELECTOR, 'a[href*="/error/moodle/invalidkey"]'): + raise _InvalidSSOKey( + "Moodle rejected the portal's sign-in key (invalidkey). " + "The browser did not establish a session; no new session was saved. " + "The account portal's single-sign-on may need attention." ) - if not cookie_header: - raise MoodleError("browser login succeeded, but no site cookies were available") - return user_agent, cookie_header + + if launched_moodle: + # A click may open its destination asynchronously. Do not issue + # another launch or submit the portal form during that transfer. + time.sleep(1) + continue + + location = urllib.parse.urlsplit(driver.current_url) + allowed_origins = { + (parsed.scheme, parsed.netloc.casefold()) + for parsed in (urllib.parse.urlsplit(args.site), urllib.parse.urlsplit(login_url)) + } + if (location.scheme, location.netloc.casefold()) not in allowed_origins: + time.sleep(1) + continue # Ravin's account portal owns the login. Its Moodle launch link creates # the session on training.ravinacademy.com and redirects there. - launch_links = driver.find_elements( - By.CSS_SELECTOR, - 'a[href*="/moodle/login_student_user/"]', - ) - launch_urls = [ - element.get_attribute("href") - for element in launch_links - if element.is_displayed() and element.get_attribute("href") - ] - if launch_urls: + if not launched_moodle and _launch_moodle_from_portal(driver, login_url, By): print("LMS login accepted; opening the Moodle course portal.", file=sys.stderr) - driver.get(launch_urls[0]) + launched_moodle = True submitted_credentials = False continue + # The portal now requires a human-entered CAPTCHA. Leave the form + # untouched rather than submitting incomplete credentials repeatedly. + captcha_controls = driver.find_elements( + By.CSS_SELECTOR, + 'input[name="captcha_1"], input[name="g-recaptcha-response"], ' + '.g-recaptcha, .h-captcha, iframe[src*="recaptcha"], iframe[src*="hcaptcha"]', + ) + if any(element.is_displayed() for element in captcha_controls): + if not captcha_notice_shown: + print("CAPTCHA detected; complete login in the browser window.", file=sys.stderr) + captcha_notice_shown = True + time.sleep(1) + continue + if submitted_credentials: error_elements = driver.find_elements( By.CSS_SELECTOR, @@ -364,6 +556,13 @@ def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]: print("Submitted the stored LMS credentials.", file=sys.stderr) time.sleep(1) raise MoodleError(f"browser login did not finish within {max(args.login_timeout, 30)} seconds") + except _InvalidSSOKey: + if not ("firefox" in browser_name or "zen" in browser_name): + raise + print("Firefox/Zen rejected the portal transfer; switching to Chromium.", file=sys.stderr) + driver.get(login_url) + portal_cookies = driver.get_cookies() + return _capture_chromium_session(args, portal_cookies) except WebDriverException as exc: raise MoodleError(f"browser authentication failed: {exc}") from exc finally: diff --git a/src/ravin/client.py b/src/ravin/client.py index 6a2c03f..c3246a0 100644 --- a/src/ravin/client.py +++ b/src/ravin/client.py @@ -2,6 +2,7 @@ import http.client import http.cookiejar +import html import json import mimetypes import re @@ -233,6 +234,8 @@ class MoodleClient: self.user_id = int(config["userId"]) if not self.sesskey: raise MoodleError("the page opened, but Moodle's session key was not found") + if not self.user_id or self.user_id <= 0: + raise MoodleError("the browser session is not logged in as a Moodle user") def api_call(self, function: str, **params: Any) -> Any: if not self.token: @@ -295,7 +298,9 @@ class MoodleClient: "requiredfields": ["id", "fullname", "shortname", "visible", "enddate"], }, ) - raw_courses = data.get("courses", []) if isinstance(data, dict) else [] + if not isinstance(data, dict) or not isinstance(data.get("courses"), list): + raise MoodleError("Moodle returned an unexpected enrolled-course response") + raw_courses = data["courses"] courses = [ Course(int(item["id"]), str(item.get("fullname") or item.get("displayname") or item["id"]), str(item.get("shortname") or "")) for item in raw_courses @@ -346,9 +351,7 @@ class MoodleClient: def _list_files_web(self, course_id: int) -> list[FileItem]: page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}") - structure_parser = _CourseStructureParser(final_url) - structure_parser.feed(page) - structure = structure_parser.result() + structure = self._parse_course_structure(page, final_url, course_id) self._course_structure_cache[course_id] = structure activity_by_url: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {} for section in structure: @@ -392,6 +395,7 @@ class MoodleClient: if not (content_type.startswith("text/") or content_type in {"application/xhtml+xml", "application/xml"}): files.append(self._web_file_item(course_id, "Course files", activity, module_final_url, metadata)) continue + self._validate_web_page(module_page, module_final_url) module_parser = _LinkParser(module_final_url) module_parser.feed(module_page) candidates = list(module_parser.media) @@ -432,12 +436,32 @@ class MoodleClient: if cached is not None: return cached page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}") + structure = self._parse_course_structure(page, final_url, course_id) + self._course_structure_cache[course_id] = structure + return structure + + def _parse_course_structure(self, page: str, final_url: str, course_id: int) -> list[dict[str, Any]]: + self._validate_web_page(page, final_url) parser = _CourseStructureParser(final_url) parser.feed(page) structure = parser.result() - self._course_structure_cache[course_id] = structure + if not structure: + raise MoodleError( + f"course {course_id} exposed no readable sections; check access and the site's course format" + ) return structure + @staticmethod + def _validate_web_page(page: str, final_url: str) -> None: + if _is_cloudflare_challenge(page): + raise MoodleError("Cloudflare rejected the LMS page; run `ravin login` again") + forms = _FormParser() + forms.feed(page) + if "/login/" in urllib.parse.urlsplit(final_url).path or any( + "password" in form["inputs"] for form in forms.forms + ): + raise MoodleError("the session expired while reading the LMS; run `ravin login` again") + def download( self, item: FileItem, diff --git a/src/ravin/constants.py b/src/ravin/constants.py index c5cf072..85cf2dd 100644 --- a/src/ravin/constants.py +++ b/src/ravin/constants.py @@ -5,7 +5,7 @@ from pathlib import Path DEFAULT_SITE = "https://training.ravinacademy.com" DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/" -__version__ = "0.16.0" +__version__ = "0.16.3" USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)" DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"} LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"} diff --git a/tests/test_assessments.py b/tests/test_assessments.py index 2b8423b..cdecd62 100644 --- a/tests/test_assessments.py +++ b/tests/test_assessments.py @@ -130,6 +130,35 @@ class CourseAssessmentTests(unittest.TestCase): self.assertEqual(item["bundle_path"], "assessments/final-exam") self.assertEqual(item["state"]["questions"], "complete") + def test_hidden_linked_quiz_keeps_local_exam_and_reconnects_when_visible(self) -> None: + course = self.write_course(53) + self.write_overlay(course, activity_id=6126) + questions = course / "assessments" / "final-exam" / "artifacts" / "questions.fa.md" + questions.parent.mkdir(parents=True) + questions.write_text("# Preserved exam", encoding="utf-8") + scan_offline(self.public, [53]) + scan_offline(self.public, [53]) + manifest_path = course / "manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + exam = manifest["course"]["sections"][-1]["items"][0] + self.assertEqual(exam["linked_activity_id"], 6126) + self.assertIsNone(exam["activity_id"]) + self.assertEqual(exam["state"]["questions"], "complete") + self.assertEqual(exam["bundle_path"], "assessments/final-exam") + manifest["course"]["sections"][0]["items"].append({ + "activity_id": 6126, "activity_position": 1, "activity_type": "quiz", + "title": "Visible quiz", "kind": "quiz", "filename": "", + }) + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + scan_offline(self.public, [53]) + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + exams = [item for section in manifest["course"]["sections"] for item in section["items"] + if item.get("assessment_id") == "final-exam"] + self.assertEqual(len(exams), 1) + self.assertEqual(exams[0]["activity_id"], 6126) + self.assertEqual(exams[0]["state"]["questions"], "complete") + self.assertEqual(questions.read_text(encoding="utf-8"), "# Preserved exam") + def test_active_exam_is_visible_but_cannot_publish_answers(self) -> None: course = self.write_course(56) self.write_overlay(course, status="active") diff --git a/tests/test_auth_update.py b/tests/test_auth_update.py new file mode 100644 index 0000000..73f441e --- /dev/null +++ b/tests/test_auth_update.py @@ -0,0 +1,285 @@ +"""Regressions for the Ravin portal and its October 2026 Moodle theme.""" +import email.message +import io +import json +import sys +import tempfile +import unittest +from contextlib import redirect_stderr +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) +from ravin.auth import _capture_browser_session, _authenticated_browser_session, _select_login_tab +from ravin.client import MoodleClient +from ravin.models import MoodleError + + +class BrowserUpdateTests(unittest.TestCase): + def capture(self, *, captcha=False, existing_session=False, new_tab=False, invalid_key=False, use_zen=False): + test = self + + class Element: + def __init__(self, visible): + self.visible = visible + + def is_displayed(self): + return self.visible + + def get_attribute(self, name): + return 'https://lms.example/moodle/login_student_user/162/' if name == 'href' else None + + def click(self): + driver.launch() + + class Driver: + current_url = 'about:blank' + awaiting_captcha = captcha + quit_called = False + launches = 0 + + def __init__(self): + self.window_handles = ['portal'] + self.current_window_handle = 'portal' + self.switch_to = SimpleNamespace(window=self.switch_window) + + def switch_window(self, handle): + self.current_window_handle = handle + self.current_url = 'https://training.example/my/' + + def launch(self): + self.launches += 1 + test.assertEqual(self.launches, 1, 'SSO link must only be activated once') + if new_tab: + self.window_handles.append('moodle') + elif invalid_key: + self.current_url = 'https://training.example/auth/userkey/login.php?key=synthetic' + else: + self.current_url = 'https://training.example/my/' + + def get(self, url): + test.assertNotIn('login_student_user', url, 'Use the portal link instead of direct navigation') + self.current_url = url + + def execute_script(self, script, *args): + if script == 'arguments[0].click();': + args[0].click() + return None + test.assertFalse(args, 'CAPTCHA form must not be auto-submitted') + if 'navigator.userAgent' in script: + return 'Synthetic Browser/1' + test.assertNotIn('logout.php', script) + test.assertIn('M.cfg.sesskey', script) + return self.current_url == 'https://training.example/my/' or ( + existing_session and self.current_url == 'https://training.example/my/courses.php' + ) + + def find_elements(self, by, selector): + if 'invalidkey' in selector: + return [Element(True)] if '/auth/userkey/' in self.current_url else [] + if 'login_student_user' in selector: + return [] if self.awaiting_captcha else [Element(False)] + if 'captcha' in selector and self.awaiting_captcha: + return [Element(True)] + return [] + + def get_cookies(self): + return [{'name': 'MoodleSession', 'value': 'synthetic'}] + + def quit(self): + self.quit_called = True + + driver = Driver() + output = io.StringIO() + with tempfile.TemporaryDirectory() as directory: + args = SimpleNamespace( + site='https://training.example', login_url='https://lms.example/', + browser_executable=None, browser_profile=Path(directory) / 'profile', + login_timeout=30, env_values={'RAVIN_USERNAME': 'synthetic', 'RAVIN_PASSWORD': 'synthetic'}, + ) + with patch('ravin.auth._find_browser_executable', return_value=Path('/synthetic/zen' if use_zen else '/synthetic/chrome')), \ + patch('selenium.webdriver.Chrome', return_value=driver), \ + patch('selenium.webdriver.Firefox', return_value=driver), \ + patch('selenium.webdriver.firefox.service.Service'), \ + patch('ravin.auth._capture_chromium_session', return_value=('Synthetic Browser/1', 'MoodleSession=synthetic')) as fallback, \ + patch('ravin.auth.time.sleep', side_effect=lambda _: setattr(driver, 'awaiting_captcha', False)), \ + redirect_stderr(output): + if invalid_key and not use_zen: + with self.assertRaisesRegex(MoodleError, 'invalidkey'): + _capture_browser_session(args) + self.assertTrue(driver.quit_called) + self.assertEqual(driver.launches, 1) + self.assertNotIn('key=synthetic', output.getvalue()) + return output.getvalue() + result = _capture_browser_session(args) + if invalid_key and use_zen: + fallback.assert_called_once_with(args, [{'name': 'MoodleSession', 'value': 'synthetic'}]) + else: + fallback.assert_not_called() + self.assertTrue(driver.quit_called) + self.assertEqual(result, ('Synthetic Browser/1', 'MoodleSession=synthetic')) + self.assertEqual(driver.launches, 0 if existing_session else 1) + return output.getvalue() + + def test_hidden_launch_link_and_theme_without_logout_link(self): + self.capture() + + def test_captcha_waits_for_human_without_submitting_stored_credentials(self): + self.assertIn('CAPTCHA detected', self.capture(captcha=True)) + + def test_existing_profile_session_skips_portal_launch(self): + self.capture(existing_session=True) + + def test_new_login_tab_is_followed_without_relaunching(self): + self.capture(new_tab=True) + + def test_invalid_key_is_reported_without_replaying_the_link(self): + self.capture(invalid_key=True) + + def test_zen_invalid_key_switches_engine_with_portal_session(self): + self.assertIn('switching to Chromium', self.capture(invalid_key=True, use_zen=True)) + + def test_session_from_another_origin_is_not_captured(self): + driver = SimpleNamespace(current_url='https://another.example/my/') + self.assertIsNone(_authenticated_browser_session(driver, 'https://training.example')) + + def test_closed_browser_reports_actionable_error(self): + with self.assertRaisesRegex(MoodleError, 'browser was closed'): + _select_login_tab(SimpleNamespace(window_handles=[]), {'portal'}) + + def test_closed_active_tab_switches_to_remaining_tab(self): + from selenium.common.exceptions import NoSuchWindowException + + class Driver: + window_handles = ['moodle'] + + @property + def current_window_handle(self): + raise NoSuchWindowException() + + switched = [] + driver = Driver() + driver.switch_to = SimpleNamespace(window=switched.append) + self.assertEqual(_select_login_tab(driver, {'moodle', 'portal'}), {'moodle'}) + self.assertEqual(switched, ['moodle']) + + +class ScanUpdateTests(unittest.TestCase): + def setUp(self): + self.client = MoodleClient('https://training.example', cookie_header='MoodleSession=synthetic') + + def test_browser_session_accepts_new_theme_without_logout_link(self): + page = '' + with patch.object(self.client, '_read_text', return_value=(page, 'https://training.example/my/courses.php', None)): + self.assertEqual(self.client.authenticate(), 'browser-session') + + def test_guest_session_with_sesskey_is_rejected(self): + for user in (0, -1, None): + page = '' + with self.subTest(user=user), patch.object(self.client, '_read_text', return_value=(page, 'https://training.example/my/courses.php', None)): + with self.assertRaises(MoodleError): + self.client.authenticate() + + def test_login_or_unrecognized_page_cannot_become_empty_course(self): + for page, url in ( + ('
', 'https://lms.example/employee/user/login/'), + ('