Skip to content
This repository was archived by the owner on Nov 18, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ ampliar el contrato y cualquier cambio incompatible debe explicarse expresamente
- `USC_CACHE_DIR` cambia la carpeta de estas cachés, y `USC_LOCATION_CACHE=0` y
`USC_TIMETABLE_DISCOVERY_CACHE=0` las desactivan.

### Cerrar sesión de verdad y sesiones sin llavero

- `end_campus_session` cierra la sesión en el propio Campus (`login/logout.php` con su sesskey),
así que esa cookie deja de valer en cualquier sitio, y después la olvida en este equipo;
- sin llavero del sistema (un Linux sin escritorio, una VM por SSH), la sesión se guarda en un
archivo privado (0600, carpeta 0700) en la configuración del usuario, en vez de fallar;
`USC_CREDENTIALS_FILE` cambia su ruta.

### Editar una entrega que ya está en el límite de archivos

- con la tarea en su máximo de archivos, Moodle esconde «Engadir» hasta que hay sitio, así que
Expand Down
72 changes: 68 additions & 4 deletions src/mcp_usc/credentials.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
from __future__ import annotations

import contextlib
import json
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path

import keyring
from keyring.errors import KeyringError
from keyring.errors import KeyringError, NoKeyringError
from platformdirs import user_config_path

from .request_credentials import current_moodle_session

Expand All @@ -18,9 +23,52 @@ class CredentialStoreError(RuntimeError):
pass


def fallback_path() -> Path:
"""Where credentials go when the system has no keyring (a server, a VM over SSH)."""

override = os.getenv("USC_CREDENTIALS_FILE", "").strip()
if override:
return Path(override).expanduser()
return Path(user_config_path("mcp-usc", appauthor=False)) / "credenciales.json"


def _read_fallback() -> dict[str, str]:
try:
data = json.loads(fallback_path().read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return {str(key): str(value) for key, value in data.items()} if isinstance(data, dict) else {}


def _write_fallback(values: dict[str, str]) -> None:
path = fallback_path()
if not values:
with contextlib.suppress(FileNotFoundError):
path.unlink()
return
path.parent.mkdir(parents=True, exist_ok=True)
with contextlib.suppress(OSError):
path.parent.chmod(0o700)
handle, temporary = tempfile.mkstemp(dir=path.parent, prefix=".credenciales-")
try:
if hasattr(os, "fchmod"):
os.fchmod(handle, 0o600) # only you can read your Campus session
with os.fdopen(handle, "w", encoding="utf-8") as stream:
json.dump(values, stream)
os.replace(temporary, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(temporary)
raise


@dataclass(slots=True)
class CredentialStore:
"""Small adapter over request, environment and OS credential stores."""
"""Small adapter over request, environment and OS credential stores.

Without a usable OS keyring (headless Linux, a VM reached by SSH) values live in a
private file (0600, folder 0700) under the user's config directory instead.
"""

service_name: str = SERVICE_NAME

Expand All @@ -33,26 +81,42 @@ def get(self, name: str) -> str | None:
if environment_value:
return environment_value
try:
return keyring.get_password(self.service_name, name)
value = keyring.get_password(self.service_name, name)
except NoKeyringError:
return _read_fallback().get(name)
except KeyringError as exc:
raise CredentialStoreError(
"No se pudo leer el almacén seguro de credenciales del sistema."
) from exc
return value if value is not None else _read_fallback().get(name)

def set(self, name: str, value: str) -> None:
if not value:
raise ValueError("No se puede guardar una credencial vacía")
try:
keyring.set_password(self.service_name, name, value)
except NoKeyringError:
values = _read_fallback()
values[name] = value
try:
_write_fallback(values)
except OSError as exc:
raise CredentialStoreError(
"No hay llavero del sistema y no se pudo guardar el archivo privado."
) from exc
except KeyringError as exc:
raise CredentialStoreError(
"No se pudo escribir en el almacén seguro de credenciales del sistema."
) from exc

def delete(self, name: str) -> None:
values = _read_fallback()
if name in values:
values.pop(name)
_write_fallback(values)
try:
keyring.delete_password(self.service_name, name)
except keyring.errors.PasswordDeleteError:
except (keyring.errors.PasswordDeleteError, NoKeyringError):
return
except KeyringError as exc:
raise CredentialStoreError(
Expand Down
42 changes: 42 additions & 0 deletions src/mcp_usc/session_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from __future__ import annotations

import os
import re
from dataclasses import dataclass
from urllib.parse import urljoin, urlparse
Expand Down Expand Up @@ -220,6 +221,47 @@ async def import_session_cookie(
return imported.as_dict()


async def end_campus_session(
settings: Settings, *, credential_store: CredentialStore | None = None
) -> dict[str, object]:
"""Log out of the Campus itself (the cookie stops working anywhere) and forget it here."""

store = credential_store or CredentialStore()
try:
cookie = store.get(SESSION_CREDENTIAL_NAME)
except Exception:
cookie = None
remote: bool | None = None
if cookie:
base = validate_usc_url(settings.moodle_url, campus=True).rstrip("/")
try:
async with httpx.AsyncClient(
timeout=settings.request_timeout_seconds,
follow_redirects=False,
cookies={"MoodleSession": cookie},
headers={"User-Agent": USER_AGENT, "Accept": "text/html"},
) as client:
page = await client.get(f"{base}/user/preferences.php")
if page.is_redirect or page.status_code >= 400:
remote = False # already over on the Campus
else:
soup = BeautifulSoup(page.text, "html.parser")
sesskey = _sesskey(soup, page.text)
answer = await client.get(
f"{base}/login/logout.php", params={"sesskey": sesskey}
)
remote = answer.status_code < 400
except (httpx.HTTPError, SessionImportError, ValueError):
remote = None # could not tell; the local copy is forgotten anyway
forget_session_cookie(credential_store=store)
return {
"authenticated": False,
"local_session_removed": True,
"remote_logout": remote,
"environment_session_kept": bool(os.getenv("USC_MOODLE_SESSION", "").strip()),
}


def forget_session_cookie(*, credential_store: CredentialStore | None = None) -> dict[str, object]:
"""Delete only the local credential; do not make a remote logout request."""

Expand Down
96 changes: 96 additions & 0 deletions tests/test_credentials_fallback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Without an OS keyring (a server, a VM over SSH) the session lives in a private file."""

from __future__ import annotations

import os
import stat

import httpx
import pytest
import respx
from keyring.errors import NoKeyringError

from mcp_usc import credentials
from mcp_usc.credentials import CredentialStore
from mcp_usc.session_auth import SESSION_CREDENTIAL_NAME, end_campus_session
from mcp_usc.settings import Settings


@pytest.fixture
def no_keyring(tmp_path, monkeypatch):
def fail(*args, **kwargs):
raise NoKeyringError("no backend")

monkeypatch.setattr(credentials.keyring, "get_password", fail)
monkeypatch.setattr(credentials.keyring, "set_password", fail)
monkeypatch.setattr(credentials.keyring, "delete_password", fail)
monkeypatch.setenv("USC_CREDENTIALS_FILE", str(tmp_path / "conf" / "credenciales.json"))
monkeypatch.delenv("USC_MOODLE_SESSION", raising=False)
return tmp_path / "conf" / "credenciales.json"


def test_private_file_when_there_is_no_keyring(no_keyring):
store = CredentialStore()
assert store.get(SESSION_CREDENTIAL_NAME) is None
store.set(SESSION_CREDENTIAL_NAME, "abc123")
assert store.get(SESSION_CREDENTIAL_NAME) == "abc123"
if os.name != "nt":
assert stat.S_IMODE(no_keyring.stat().st_mode) == 0o600
assert stat.S_IMODE(no_keyring.parent.stat().st_mode) == 0o700
store.delete(SESSION_CREDENTIAL_NAME)
assert store.get(SESSION_CREDENTIAL_NAME) is None and not no_keyring.exists()


class _Store:
def __init__(self, value: str | None) -> None:
self.value = value

def get(self, name: str) -> str | None:
return self.value

def delete(self, name: str) -> None:
self.value = None


def _settings() -> Settings:
from pathlib import Path

return Settings(
moodle_url="https://cv.usc.es",
moodle_token=None,
browser_channel="auto",
browser_profile_dir=Path("/tmp/none"),
exam_sources=(),
)


@respx.mock
async def test_logging_out_ends_the_session_on_the_campus_too(monkeypatch):
monkeypatch.delenv("USC_MOODLE_SESSION", raising=False)
respx.get("https://cv.usc.es/user/preferences.php").mock(
return_value=httpx.Response(200, text='<input name="sesskey" value="abcdef123">')
)
logout = respx.get("https://cv.usc.es/login/logout.php").mock(
return_value=httpx.Response(303, headers={"location": "https://cv.usc.es/"})
)
store = _Store("cookie-value")

result = await end_campus_session(_settings(), credential_store=store)

assert logout.called and logout.calls[0].request.url.params["sesskey"] == "abcdef123"
assert result["remote_logout"] is True and result["local_session_removed"] is True
assert store.value is None


@respx.mock
async def test_an_already_expired_session_is_just_forgotten(monkeypatch):
monkeypatch.delenv("USC_MOODLE_SESSION", raising=False)
respx.get("https://cv.usc.es/user/preferences.php").mock(
return_value=httpx.Response(303, headers={"location": "https://cv.usc.es/login/"})
)
logout = respx.get("https://cv.usc.es/login/logout.php")
store = _Store("old")

result = await end_campus_session(_settings(), credential_store=store)

assert not logout.called and result["remote_logout"] is False and store.value is None
Loading