mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 23:09:47 +08:00
* feat(video-learning): connect Invidious accounts * fix(video-learning): harden Invidious authorization state --------- Co-authored-by: XZH <cto@xzh.ai> Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
This commit is contained in:
@@ -7,16 +7,18 @@ from typing import Any
|
||||
from urllib.parse import urljoin, urlparse
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
||||
import httpx
|
||||
from pydantic import BaseModel, Field
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from deeptutor.multi_user.paths import current_owner_id
|
||||
from deeptutor.services.notebook.service import NotebookCorruptedError
|
||||
from deeptutor.video_learning import (
|
||||
TimedMediaError,
|
||||
TimedMediaNotFound,
|
||||
get_timed_media_store,
|
||||
invidious_account,
|
||||
load_video_learning_settings,
|
||||
material_with_playback,
|
||||
refresh_invidious_transcript,
|
||||
@@ -111,6 +113,44 @@ async def test_invidious(payload: VideoLearningSettingsRequest) -> dict[str, Any
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
|
||||
@router.post("/invidious/account/authorize")
|
||||
async def authorize_invidious_account() -> dict[str, str]:
|
||||
try:
|
||||
url = invidious_account.begin_invidious_account_authorization(
|
||||
owner_id=current_owner_id(),
|
||||
redirect_uri=invidious_account.invidious_redirect_uri(),
|
||||
)
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
return {"authorize_url": url}
|
||||
|
||||
|
||||
@router.get("/invidious/account/callback")
|
||||
async def invidious_account_callback(token: str = "", state: str = "") -> JSONResponse:
|
||||
try:
|
||||
status = await invidious_account.complete_invidious_account_authorization(
|
||||
owner_id=current_owner_id(),
|
||||
state=state,
|
||||
token=token,
|
||||
)
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
return JSONResponse(status, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/invidious/account/status")
|
||||
async def get_invidious_account_status() -> dict[str, Any]:
|
||||
return invidious_account.invidious_account_status(current_owner_id())
|
||||
|
||||
|
||||
@router.post("/invidious/account/disconnect")
|
||||
async def disconnect_invidious_account() -> dict[str, Any]:
|
||||
try:
|
||||
return await invidious_account.disconnect_invidious_account(owner_id=current_owner_id())
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
|
||||
@router.post("/materials/resolve")
|
||||
async def resolve_video(payload: ResolveRequest) -> dict[str, Any]:
|
||||
try:
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
"""Video-learning domain API."""
|
||||
|
||||
from .invidious_account import (
|
||||
begin_invidious_account_authorization,
|
||||
complete_invidious_account_authorization,
|
||||
disconnect_invidious_account,
|
||||
invidious_account_status,
|
||||
invidious_redirect_uri,
|
||||
)
|
||||
from .service import (
|
||||
PROVIDER_RESOLVERS,
|
||||
ProviderResolution,
|
||||
@@ -25,7 +32,12 @@ __all__ = [
|
||||
"TimedMediaNotFound",
|
||||
"TimedMediaStore",
|
||||
"build_segments",
|
||||
"begin_invidious_account_authorization",
|
||||
"complete_invidious_account_authorization",
|
||||
"disconnect_invidious_account",
|
||||
"get_timed_media_store",
|
||||
"invidious_account_status",
|
||||
"invidious_redirect_uri",
|
||||
"load_video_learning_settings",
|
||||
"material_with_playback",
|
||||
"normalize_cues",
|
||||
|
||||
401
deeptutor/video_learning/invidious_account.py
Normal file
401
deeptutor/video_learning/invidious_account.py
Normal file
@@ -0,0 +1,401 @@
|
||||
"""Secure per-owner Invidious account connections.
|
||||
|
||||
Invidious token authorization is deliberately small: DeepTutor sends the learner
|
||||
to the instance's consent page, receives a signed token through a one-time
|
||||
callback, verifies it by reading preferences, and stores only that token in the
|
||||
owner-private secrets tree. No password or browser cookie is handled here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import stat
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode, urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
from deeptutor.multi_user.paths import owner_secrets_dir
|
||||
from deeptutor.video_learning.service import (
|
||||
TimedMediaError,
|
||||
load_video_learning_settings,
|
||||
normalize_video_learning_settings,
|
||||
)
|
||||
|
||||
CALLBACK_PATH = "/api/video-learning/invidious/account/callback"
|
||||
FLOW_TIMEOUT_S = 600.0
|
||||
PUBLIC_URL_ENV = "DEEPTUTOR_PUBLIC_URL"
|
||||
DEFAULT_PUBLIC_URL = "http://localhost:3782"
|
||||
ACCOUNT_SCOPES = ("GET:preferences", "POST:tokens/unregister")
|
||||
_SECRETS_SUBDIR = ("private", "video-learning-invidious")
|
||||
_MAX_TOKEN_BYTES = 8192
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PendingFlow:
|
||||
owner_id: str
|
||||
api_base_url: str
|
||||
callback_url: str
|
||||
expires_at: float
|
||||
|
||||
|
||||
def _asset_dir(owner_id: str) -> Path:
|
||||
path = owner_secrets_dir(owner_id)
|
||||
for part in _SECRETS_SUBDIR:
|
||||
path = path / part
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
os.chmod(path, stat.S_IRWXU)
|
||||
return path
|
||||
|
||||
|
||||
def _store_path(owner_id: str) -> Path:
|
||||
return _asset_dir(owner_id) / "account.json"
|
||||
|
||||
|
||||
def _pending_dir(owner_id: str) -> Path:
|
||||
path = _asset_dir(owner_id) / "pending"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
os.chmod(path, stat.S_IRWXU)
|
||||
return path
|
||||
|
||||
|
||||
def _flow_path(owner_id: str, state: str) -> Path:
|
||||
# State never becomes a path segment. Besides avoiding traversal hazards,
|
||||
# hashing keeps a filesystem backup from disclosing a still-live callback
|
||||
# state to someone who can list filenames but not read owner-private files.
|
||||
digest = hashlib.sha256(state.encode("utf-8")).hexdigest()
|
||||
return _pending_dir(owner_id) / f"{digest}.json"
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
return {}
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
|
||||
|
||||
def _write_private_json(path: Path, payload: dict[str, Any]) -> None:
|
||||
temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")
|
||||
try:
|
||||
descriptor = os.open(
|
||||
temporary,
|
||||
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
|
||||
stat.S_IRUSR | stat.S_IWUSR,
|
||||
)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _pending_flow(path: Path) -> _PendingFlow | None:
|
||||
payload = _read_json(path)
|
||||
owner_id = payload.get("owner_id")
|
||||
api_base_url = payload.get("api_base_url")
|
||||
callback_url = payload.get("callback_url")
|
||||
expires_at = payload.get("expires_at")
|
||||
if (
|
||||
not isinstance(owner_id, str)
|
||||
or not owner_id
|
||||
or not isinstance(api_base_url, str)
|
||||
or not api_base_url
|
||||
or not isinstance(callback_url, str)
|
||||
or not callback_url
|
||||
or not isinstance(expires_at, (int, float))
|
||||
):
|
||||
return None
|
||||
return _PendingFlow(
|
||||
owner_id=owner_id,
|
||||
api_base_url=api_base_url,
|
||||
callback_url=callback_url,
|
||||
expires_at=float(expires_at),
|
||||
)
|
||||
|
||||
|
||||
def _purge_expired(owner_id: str, now: float | None = None) -> None:
|
||||
current = time.time() if now is None else now
|
||||
for path in _pending_dir(owner_id).glob("*.json"):
|
||||
flow = _pending_flow(path)
|
||||
if flow is None or flow.owner_id != owner_id or flow.expires_at <= current:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _consume_pending_flow(owner_id: str, state: str) -> _PendingFlow | None:
|
||||
if not state:
|
||||
return None
|
||||
source = _flow_path(owner_id, state)
|
||||
claim = source.with_name(f".{source.name}.{secrets.token_hex(8)}.claim")
|
||||
try:
|
||||
# Same-filesystem rename is the one-time claim. It works across Uvicorn
|
||||
# workers and across restarts, unlike a process-local dictionary.
|
||||
source.rename(claim)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
try:
|
||||
flow = _pending_flow(claim)
|
||||
finally:
|
||||
claim.unlink(missing_ok=True)
|
||||
if flow is None or flow.owner_id != owner_id or flow.expires_at <= time.time():
|
||||
return None
|
||||
return flow
|
||||
|
||||
|
||||
def _read(owner_id: str) -> dict[str, Any]:
|
||||
return _read_json(_store_path(owner_id))
|
||||
|
||||
|
||||
def _write(owner_id: str, payload: dict[str, Any]) -> None:
|
||||
_write_private_json(_store_path(owner_id), payload)
|
||||
|
||||
|
||||
def _forget(owner_id: str) -> None:
|
||||
_store_path(owner_id).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _configured_public_url() -> str:
|
||||
configured = os.environ.get(PUBLIC_URL_ENV, "").strip().rstrip("/")
|
||||
if configured:
|
||||
# Reuse the provider-origin rules rather than accepting an arbitrary
|
||||
# redirect target from an environment typo.
|
||||
normalized = normalize_video_learning_settings(
|
||||
{
|
||||
"version": 1,
|
||||
"default_provider": "youtube",
|
||||
"invidious": {"api_base_url": "", "public_base_url": configured},
|
||||
}
|
||||
)
|
||||
return normalized["invidious"]["public_base_url"]
|
||||
# Request Host and X-Forwarded-* headers are attacker-controlled unless a
|
||||
# deployment has explicitly configured and constrained trusted proxies.
|
||||
# Remote deployments therefore opt into their canonical external origin;
|
||||
# local installs retain the shipped frontend URL.
|
||||
return DEFAULT_PUBLIC_URL
|
||||
|
||||
|
||||
def invidious_redirect_uri() -> str:
|
||||
return f"{_configured_public_url()}{CALLBACK_PATH}"
|
||||
|
||||
|
||||
def begin_invidious_account_authorization(*, owner_id: str, redirect_uri: str) -> str:
|
||||
settings = load_video_learning_settings()
|
||||
base = settings["invidious"]["api_base_url"]
|
||||
if not base:
|
||||
raise TimedMediaError("Configure the Invidious API base URL before connecting an account.")
|
||||
|
||||
parsed_redirect = urlparse(redirect_uri)
|
||||
try:
|
||||
parsed_redirect.port
|
||||
except ValueError as exc:
|
||||
raise TimedMediaError("Invidious callback URL contains an invalid port.") from exc
|
||||
if (
|
||||
parsed_redirect.scheme not in {"http", "https"}
|
||||
or not parsed_redirect.hostname
|
||||
or parsed_redirect.username
|
||||
or parsed_redirect.password
|
||||
or parsed_redirect.fragment
|
||||
):
|
||||
raise TimedMediaError("Invidious callback URL must be a plain HTTP(S) URL.")
|
||||
|
||||
_purge_expired(owner_id)
|
||||
state = secrets.token_urlsafe(32)
|
||||
separator = "&" if parsed_redirect.query else "?"
|
||||
callback_url = f"{redirect_uri}{separator}{urlencode({'state': state})}"
|
||||
authorize_url = f"{base}/authorize_token?{urlencode({'scopes': ','.join(ACCOUNT_SCOPES), 'callback_url': callback_url})}"
|
||||
|
||||
# Starting again replaces the prior pending consent for this owner and
|
||||
# instance. The browser can then follow only the most recent redirect.
|
||||
for path in _pending_dir(owner_id).glob("*.json"):
|
||||
flow = _pending_flow(path)
|
||||
if flow is None or flow.owner_id != owner_id or flow.api_base_url == base:
|
||||
path.unlink(missing_ok=True)
|
||||
_write_private_json(
|
||||
_flow_path(owner_id, state),
|
||||
{
|
||||
"version": 1,
|
||||
"owner_id": owner_id,
|
||||
"api_base_url": base,
|
||||
"callback_url": callback_url,
|
||||
"expires_at": time.time() + FLOW_TIMEOUT_S,
|
||||
},
|
||||
)
|
||||
return authorize_url
|
||||
|
||||
|
||||
def _parse_token(raw_token: str) -> dict[str, Any]:
|
||||
if not raw_token or len(raw_token.encode("utf-8")) > _MAX_TOKEN_BYTES:
|
||||
raise TimedMediaError("Invidious returned an invalid account token.")
|
||||
try:
|
||||
token = json.loads(raw_token)
|
||||
except (json.JSONDecodeError, UnicodeError) as exc:
|
||||
raise TimedMediaError("Invidious returned an invalid account token.") from exc
|
||||
if not isinstance(token, dict):
|
||||
raise TimedMediaError("Invidious returned an invalid account token.")
|
||||
|
||||
session = token.get("session")
|
||||
scopes = token.get("scopes")
|
||||
signature = token.get("signature")
|
||||
if (
|
||||
not isinstance(session, str)
|
||||
or not session
|
||||
or not isinstance(signature, str)
|
||||
or not signature
|
||||
or not isinstance(scopes, list)
|
||||
or any(not isinstance(scope, str) for scope in scopes)
|
||||
):
|
||||
raise TimedMediaError("Invidious returned an incomplete account token.")
|
||||
if not _scopes_include_required(scopes):
|
||||
raise TimedMediaError("Invidious account token is missing a required scope.")
|
||||
expire = token.get("expire")
|
||||
if expire is not None and (not isinstance(expire, int) or expire <= 0):
|
||||
raise TimedMediaError("Invidious returned an invalid token expiration.")
|
||||
return token
|
||||
|
||||
|
||||
def _scopes_include_required(scopes: Any) -> bool:
|
||||
if not isinstance(scopes, list) or any(not isinstance(scope, str) for scope in scopes):
|
||||
return False
|
||||
return set(ACCOUNT_SCOPES).issubset(set(scopes))
|
||||
|
||||
|
||||
def _bearer_token(token: dict[str, Any]) -> str:
|
||||
return json.dumps(token, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def _stored_token_is_usable(token: Any) -> bool:
|
||||
if not isinstance(token, dict):
|
||||
return False
|
||||
session = token.get("session")
|
||||
signature = token.get("signature")
|
||||
expire = token.get("expire")
|
||||
if not isinstance(session, str) or not session:
|
||||
return False
|
||||
if not isinstance(signature, str) or not signature:
|
||||
return False
|
||||
if expire is not None and (not isinstance(expire, int) or expire <= 0):
|
||||
return False
|
||||
return not (isinstance(expire, int) and expire <= datetime.now(timezone.utc).timestamp())
|
||||
|
||||
|
||||
async def _request_preferences(*, api_base_url: str, token: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{api_base_url}/api/v1/auth/preferences",
|
||||
headers={"Authorization": f"Bearer {_bearer_token(token)}"},
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
raise TimedMediaError("Invidious account verification request failed.") from exc
|
||||
if response.status_code != 200:
|
||||
raise TimedMediaError(
|
||||
f"Invidious account verification failed with HTTP {response.status_code}."
|
||||
)
|
||||
try:
|
||||
preferences = response.json()
|
||||
except ValueError as exc:
|
||||
raise TimedMediaError("Invidious returned invalid account preferences.") from exc
|
||||
if not isinstance(preferences, dict):
|
||||
raise TimedMediaError("Invidious returned invalid account preferences.")
|
||||
return preferences
|
||||
|
||||
|
||||
async def complete_invidious_account_authorization(
|
||||
*, owner_id: str, state: str, token: str
|
||||
) -> dict[str, Any]:
|
||||
_purge_expired(owner_id)
|
||||
flow = _consume_pending_flow(owner_id, state)
|
||||
if flow is None:
|
||||
raise TimedMediaError("Invidious account callback is unknown, expired, or already used.")
|
||||
|
||||
parsed_token = _parse_token(token)
|
||||
await _request_preferences(api_base_url=flow.api_base_url, token=parsed_token)
|
||||
|
||||
_write(
|
||||
owner_id,
|
||||
{
|
||||
"version": 1,
|
||||
"api_base_url": flow.api_base_url,
|
||||
"scopes": list(ACCOUNT_SCOPES),
|
||||
"connected_at": datetime.now(timezone.utc).isoformat(),
|
||||
"token": parsed_token,
|
||||
},
|
||||
)
|
||||
return invidious_account_status(owner_id)
|
||||
|
||||
|
||||
def invidious_account_status(owner_id: str) -> dict[str, Any]:
|
||||
payload = _read(owner_id)
|
||||
token = payload.get("token")
|
||||
base = payload.get("api_base_url")
|
||||
scopes = payload.get("scopes")
|
||||
connected_at = payload.get("connected_at")
|
||||
if not _stored_token_is_usable(token) or not isinstance(base, str) or not base:
|
||||
return {"connected": False}
|
||||
if not _scopes_include_required(scopes):
|
||||
return {"connected": False}
|
||||
if not isinstance(connected_at, str) or not connected_at:
|
||||
return {"connected": False}
|
||||
return {
|
||||
"connected": True,
|
||||
"api_base_url": base,
|
||||
"scopes": [str(scope) for scope in scopes],
|
||||
"connected_at": connected_at,
|
||||
}
|
||||
|
||||
|
||||
async def _revoke_token(*, api_base_url: str, token: dict[str, Any]) -> None:
|
||||
async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:
|
||||
response = await client.post(
|
||||
f"{api_base_url}/api/v1/auth/tokens/unregister",
|
||||
headers={"Authorization": f"Bearer {_bearer_token(token)}"},
|
||||
json={"session": token["session"]},
|
||||
)
|
||||
if response.status_code < 200 or response.status_code >= 300:
|
||||
raise TimedMediaError(
|
||||
f"Invidious account disconnection failed with HTTP {response.status_code}."
|
||||
)
|
||||
|
||||
|
||||
async def disconnect_invidious_account(*, owner_id: str) -> dict[str, Any]:
|
||||
payload = _read(owner_id)
|
||||
token = payload.get("token")
|
||||
base = payload.get("api_base_url")
|
||||
if not _stored_token_is_usable(token) or not isinstance(base, str) or not base:
|
||||
_forget(owner_id)
|
||||
return {"connected": False}
|
||||
|
||||
try:
|
||||
await _revoke_token(api_base_url=base, token=token)
|
||||
except httpx.HTTPError as exc:
|
||||
raise TimedMediaError(
|
||||
"Invidious account disconnection request failed. The saved connection was kept so it can be retried."
|
||||
) from exc
|
||||
except TimedMediaError:
|
||||
# Do not delete first: if the instance is temporarily unavailable, doing
|
||||
# so would leave a valid token registered upstream with no local revoke.
|
||||
raise
|
||||
|
||||
_forget(owner_id)
|
||||
return {"connected": False}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ACCOUNT_SCOPES",
|
||||
"CALLBACK_PATH",
|
||||
"FLOW_TIMEOUT_S",
|
||||
"begin_invidious_account_authorization",
|
||||
"complete_invidious_account_authorization",
|
||||
"disconnect_invidious_account",
|
||||
"invidious_account_status",
|
||||
"invidious_redirect_uri",
|
||||
]
|
||||
566
tests/video_learning/test_invidious_account.py
Normal file
566
tests/video_learning/test_invidious_account.py
Normal file
@@ -0,0 +1,566 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from deeptutor.api.routers import video_learning
|
||||
from deeptutor.multi_user import paths
|
||||
from deeptutor.video_learning import invidious_account as account
|
||||
from deeptutor.video_learning.service import TimedMediaError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def system_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
root = (tmp_path / "data" / "system").resolve()
|
||||
monkeypatch.setattr(paths, "SYSTEM_ROOT", root)
|
||||
monkeypatch.setattr(paths, "ADMIN_WORKSPACE_ROOT", (tmp_path / "data").resolve())
|
||||
monkeypatch.setattr(paths, "USERS_ROOT", (tmp_path / "data" / "users").resolve())
|
||||
return root
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def configured_instance(monkeypatch: pytest.MonkeyPatch) -> str:
|
||||
base = "https://invidious.example.test"
|
||||
monkeypatch.setattr(
|
||||
account,
|
||||
"load_video_learning_settings",
|
||||
lambda: {
|
||||
"version": 1,
|
||||
"default_provider": "youtube",
|
||||
"youtube": {"transcript_provider": "none"},
|
||||
"invidious": {"api_base_url": base, "public_base_url": ""},
|
||||
},
|
||||
)
|
||||
return base
|
||||
|
||||
|
||||
def _token(scopes: list[str] | None = None) -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"session": "v1:test-session",
|
||||
"scopes": scopes or list(account.ACCOUNT_SCOPES),
|
||||
"signature": "test-signature",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _state_from_authorize_url(url: str) -> str:
|
||||
callback_url = parse_qs(urlsplit(url).query)["callback_url"][0]
|
||||
return parse_qs(urlsplit(callback_url).query)["state"][0]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> TestClient:
|
||||
app = FastAPI()
|
||||
app.include_router(video_learning.router, prefix="/api/video-learning")
|
||||
monkeypatch.setattr(video_learning, "current_owner_id", lambda: "u_ada")
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_authorization_uses_minimal_scopes_and_one_time_state(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
async def preferences(*, api_base_url: str, token: dict[str, object]) -> dict[str, object]:
|
||||
assert api_base_url == configured_instance
|
||||
assert token["session"] == "v1:test-session"
|
||||
return {"locale": "en-US"}
|
||||
|
||||
monkeypatch.setattr(account, "_request_preferences", preferences)
|
||||
|
||||
url = account.begin_invidious_account_authorization(
|
||||
owner_id="u_ada", redirect_uri="https://app.example.test/callback"
|
||||
)
|
||||
query = parse_qs(urlsplit(url).query)
|
||||
state = _state_from_authorize_url(url)
|
||||
|
||||
assert urlsplit(url).path == "/authorize_token"
|
||||
assert query["scopes"] == [",".join(account.ACCOUNT_SCOPES)]
|
||||
pending = account._flow_path("u_ada", state)
|
||||
assert pending.is_file()
|
||||
assert stat.S_IMODE(pending.stat().st_mode) == 0o600
|
||||
|
||||
status = asyncio.run(
|
||||
account.complete_invidious_account_authorization(
|
||||
owner_id="u_ada", state=state, token=_token()
|
||||
)
|
||||
)
|
||||
secret = (
|
||||
system_root
|
||||
/ "user-secrets"
|
||||
/ "u_ada"
|
||||
/ "private"
|
||||
/ "video-learning-invidious"
|
||||
/ "account.json"
|
||||
)
|
||||
assert status["connected"] is True
|
||||
assert status["api_base_url"] == configured_instance
|
||||
assert "token" not in status
|
||||
assert "test-session" not in status
|
||||
assert "v1:test-session" in secret.read_text(encoding="utf-8")
|
||||
assert stat.S_IMODE(secret.stat().st_mode) == 0o600
|
||||
for directory in (secret.parent, secret.parent.parent):
|
||||
assert stat.S_IMODE(directory.stat().st_mode) == 0o700
|
||||
|
||||
|
||||
def test_callback_cannot_be_replayed_or_used_by_another_owner(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
async def preferences(*, api_base_url: str, token: dict[str, object]) -> dict[str, object]:
|
||||
return {"locale": "en-US"}
|
||||
|
||||
monkeypatch.setattr(account, "_request_preferences", preferences)
|
||||
url = account.begin_invidious_account_authorization(
|
||||
owner_id="u_ada", redirect_uri="https://app.example.test/callback"
|
||||
)
|
||||
state = _state_from_authorize_url(url)
|
||||
|
||||
with pytest.raises(TimedMediaError):
|
||||
asyncio.run(
|
||||
account.complete_invidious_account_authorization(
|
||||
owner_id="u_bob", state=state, token=_token()
|
||||
)
|
||||
)
|
||||
|
||||
# Looking under another owner's state directory must not consume the real
|
||||
# owner's pending callback.
|
||||
status = asyncio.run(
|
||||
account.complete_invidious_account_authorization(
|
||||
owner_id="u_ada", state=state, token=_token()
|
||||
)
|
||||
)
|
||||
assert status["connected"] is True
|
||||
with pytest.raises(TimedMediaError):
|
||||
asyncio.run(
|
||||
account.complete_invidious_account_authorization(
|
||||
owner_id="u_ada", state=state, token=_token()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_pending_callback_claim_is_atomic_across_workers(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
) -> None:
|
||||
url = account.begin_invidious_account_authorization(
|
||||
owner_id="u_ada", redirect_uri="https://app.example.test/callback"
|
||||
)
|
||||
state = _state_from_authorize_url(url)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
claimed = list(
|
||||
executor.map(
|
||||
lambda _: account._consume_pending_flow("u_ada", state),
|
||||
range(2),
|
||||
)
|
||||
)
|
||||
|
||||
assert sum(flow is not None for flow in claimed) == 1
|
||||
assert not account._flow_path("u_ada", state).exists()
|
||||
|
||||
|
||||
def test_expired_callback_is_rejected_and_never_writes_a_token(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
) -> None:
|
||||
url = account.begin_invidious_account_authorization(
|
||||
owner_id="u_ada", redirect_uri="https://app.example.test/callback"
|
||||
)
|
||||
state = _state_from_authorize_url(url)
|
||||
pending = account._flow_path("u_ada", state)
|
||||
payload = account._read_json(pending)
|
||||
payload["expires_at"] = 0
|
||||
account._write_private_json(pending, payload)
|
||||
|
||||
with pytest.raises(TimedMediaError):
|
||||
asyncio.run(
|
||||
account.complete_invidious_account_authorization(
|
||||
owner_id="u_ada", state=state, token=_token()
|
||||
)
|
||||
)
|
||||
assert not list(system_root.rglob("account.json"))
|
||||
|
||||
|
||||
def test_token_missing_disconnect_scope_is_rejected(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
) -> None:
|
||||
url = account.begin_invidious_account_authorization(
|
||||
owner_id="u_ada", redirect_uri="https://app.example.test/callback"
|
||||
)
|
||||
state = _state_from_authorize_url(url)
|
||||
|
||||
with pytest.raises(TimedMediaError, match="missing a required scope"):
|
||||
asyncio.run(
|
||||
account.complete_invidious_account_authorization(
|
||||
owner_id="u_ada", state=state, token=_token(["GET:preferences"])
|
||||
)
|
||||
)
|
||||
assert not list(system_root.rglob("account.json"))
|
||||
|
||||
|
||||
def test_failed_preference_verification_never_writes_a_token(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
original_client = account.httpx.AsyncClient
|
||||
|
||||
def refusing_client(**kwargs: object) -> object:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(403, json={"error": "invalid token"})
|
||||
|
||||
return original_client(transport=httpx.MockTransport(handler), **kwargs)
|
||||
|
||||
monkeypatch.setattr(account.httpx, "AsyncClient", refusing_client)
|
||||
url = account.begin_invidious_account_authorization(
|
||||
owner_id="u_ada", redirect_uri="https://app.example.test/callback"
|
||||
)
|
||||
state = _state_from_authorize_url(url)
|
||||
|
||||
with pytest.raises(TimedMediaError, match="verification failed with HTTP 403"):
|
||||
asyncio.run(
|
||||
account.complete_invidious_account_authorization(
|
||||
owner_id="u_ada", state=state, token=_token()
|
||||
)
|
||||
)
|
||||
assert not list(system_root.rglob("account.json"))
|
||||
|
||||
|
||||
def test_preference_network_failure_is_a_user_facing_error(
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
import json
|
||||
|
||||
original_client = account.httpx.AsyncClient
|
||||
|
||||
def offline_client(**kwargs: object) -> object:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
raise httpx.ConnectError("offline")
|
||||
|
||||
return original_client(transport=httpx.MockTransport(handler), **kwargs)
|
||||
|
||||
monkeypatch.setattr(account.httpx, "AsyncClient", offline_client)
|
||||
|
||||
with pytest.raises(TimedMediaError, match="verification request failed"):
|
||||
asyncio.run(
|
||||
account._request_preferences(
|
||||
api_base_url=configured_instance, token=json.loads(_token())
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_disconnect_revokes_upstream_and_removes_only_the_local_secret(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
account._write(
|
||||
"u_ada",
|
||||
{
|
||||
"version": 1,
|
||||
"api_base_url": configured_instance,
|
||||
"scopes": list(account.ACCOUNT_SCOPES),
|
||||
"connected_at": "2026-09-02T00:00:00+00:00",
|
||||
"token": {"session": "v1:test-session", "signature": "test-signature"},
|
||||
},
|
||||
)
|
||||
account._write(
|
||||
"u_bob",
|
||||
{
|
||||
"version": 1,
|
||||
"api_base_url": configured_instance,
|
||||
"scopes": list(account.ACCOUNT_SCOPES),
|
||||
"connected_at": "2026-09-02T00:00:00+00:00",
|
||||
"token": {"session": "v1:bob-session", "signature": "bob-signature"},
|
||||
},
|
||||
)
|
||||
revoked: dict[str, object] = {}
|
||||
|
||||
async def revoke(*, api_base_url: str, token: dict[str, object]) -> None:
|
||||
revoked["api_base_url"] = api_base_url
|
||||
revoked["session"] = token["session"]
|
||||
|
||||
monkeypatch.setattr(account, "_revoke_token", revoke)
|
||||
|
||||
status = asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))
|
||||
|
||||
assert status == {"connected": False}
|
||||
assert revoked == {
|
||||
"api_base_url": configured_instance,
|
||||
"session": "v1:test-session",
|
||||
}
|
||||
assert "u_ada" not in (system_root / "user-secrets").iterdir()
|
||||
assert account.invidious_account_status("u_bob")["connected"] is True
|
||||
|
||||
|
||||
def test_failed_upstream_disconnect_keeps_the_saved_connection_for_retry(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
account._write(
|
||||
"u_ada",
|
||||
{
|
||||
"version": 1,
|
||||
"api_base_url": configured_instance,
|
||||
"scopes": list(account.ACCOUNT_SCOPES),
|
||||
"connected_at": "2026-09-02T00:00:00+00:00",
|
||||
"token": {"session": "v1:test-session", "signature": "test-signature"},
|
||||
},
|
||||
)
|
||||
|
||||
original_client = account.httpx.AsyncClient
|
||||
|
||||
def failing_client(**kwargs: object) -> object:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(503)
|
||||
|
||||
return original_client(transport=httpx.MockTransport(handler), **kwargs)
|
||||
|
||||
monkeypatch.setattr(account.httpx, "AsyncClient", failing_client)
|
||||
|
||||
with pytest.raises(TimedMediaError, match="failed with HTTP 503"):
|
||||
asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))
|
||||
assert account.invidious_account_status("u_ada")["connected"] is True
|
||||
|
||||
|
||||
def test_public_url_override_is_the_only_remote_callback_origin(
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv(account.PUBLIC_URL_ENV, "https://public.example.test")
|
||||
assert account.invidious_redirect_uri() == "https://public.example.test" + account.CALLBACK_PATH
|
||||
|
||||
|
||||
def test_default_callback_never_trusts_request_host_headers(
|
||||
client: TestClient,
|
||||
system_root: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.delenv(account.PUBLIC_URL_ENV, raising=False)
|
||||
response = client.post(
|
||||
"/api/video-learning/invidious/account/authorize",
|
||||
headers={
|
||||
"host": "attacker.example.test",
|
||||
"x-forwarded-proto": "https",
|
||||
"x-forwarded-host": "forwarded-attacker.example.test",
|
||||
},
|
||||
)
|
||||
callback_url = parse_qs(urlsplit(response.json()["authorize_url"]).query)["callback_url"][0]
|
||||
assert callback_url.startswith(account.DEFAULT_PUBLIC_URL + account.CALLBACK_PATH)
|
||||
assert "attacker.example.test" not in callback_url
|
||||
|
||||
|
||||
def test_invidious_requests_use_bearer_json_and_unregister_session(
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
import json
|
||||
|
||||
token = json.loads(_token())
|
||||
requests: list[httpx.Request] = []
|
||||
original_client = account.httpx.AsyncClient
|
||||
|
||||
def recording_client(**kwargs: object) -> object:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request)
|
||||
if request.url.path == "/api/v1/auth/preferences":
|
||||
return httpx.Response(200, json={"locale": "en-US"})
|
||||
return httpx.Response(204)
|
||||
|
||||
return original_client(transport=httpx.MockTransport(handler), **kwargs)
|
||||
|
||||
monkeypatch.setattr(account.httpx, "AsyncClient", recording_client)
|
||||
|
||||
preferences = asyncio.run(
|
||||
account._request_preferences(api_base_url=configured_instance, token=token)
|
||||
)
|
||||
asyncio.run(account._revoke_token(api_base_url=configured_instance, token=token))
|
||||
|
||||
assert preferences == {"locale": "en-US"}
|
||||
assert [request.method for request in requests] == ["GET", "POST"]
|
||||
assert [request.url.path for request in requests] == [
|
||||
"/api/v1/auth/preferences",
|
||||
"/api/v1/auth/tokens/unregister",
|
||||
]
|
||||
expected_authorization = f"Bearer {account._bearer_token(token)}"
|
||||
assert all(request.headers["authorization"] == expected_authorization for request in requests)
|
||||
assert json.loads(requests[-1].content) == {"session": "v1:test-session"}
|
||||
|
||||
|
||||
def test_status_rejects_expired_or_incomplete_stored_tokens(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
) -> None:
|
||||
account._write(
|
||||
"u_ada",
|
||||
{
|
||||
"version": 1,
|
||||
"api_base_url": configured_instance,
|
||||
"scopes": list(account.ACCOUNT_SCOPES),
|
||||
"connected_at": "2026-09-02T00:00:00+00:00",
|
||||
"token": {"session": "v1:test-session", "signature": "sig"},
|
||||
},
|
||||
)
|
||||
assert account.invidious_account_status("u_ada")["connected"] is True
|
||||
|
||||
account._write(
|
||||
"u_ada",
|
||||
{
|
||||
"version": 1,
|
||||
"api_base_url": configured_instance,
|
||||
"scopes": list(account.ACCOUNT_SCOPES),
|
||||
"connected_at": "2026-09-02T00:00:00+00:00",
|
||||
"token": {"signature": "sig"},
|
||||
},
|
||||
)
|
||||
assert account.invidious_account_status("u_ada") == {"connected": False}
|
||||
|
||||
|
||||
def test_disconnect_removes_an_expired_local_connection_without_upstream_call(
|
||||
system_root: Path,
|
||||
configured_instance: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
account._write(
|
||||
"u_ada",
|
||||
{
|
||||
"version": 1,
|
||||
"api_base_url": configured_instance,
|
||||
"scopes": list(account.ACCOUNT_SCOPES),
|
||||
"connected_at": "2026-09-02T00:00:00+00:00",
|
||||
"token": {
|
||||
"session": "v1:test-session",
|
||||
"signature": "sig",
|
||||
"expire": int(datetime.now(timezone.utc).timestamp()) - 1,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
async def revoke(*, api_base_url: str, token: dict[str, object]) -> None:
|
||||
raise AssertionError("an expired token must not be sent upstream")
|
||||
|
||||
monkeypatch.setattr(account, "_revoke_token", revoke)
|
||||
status = asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))
|
||||
assert status == {"connected": False}
|
||||
assert "u_ada" not in (system_root / "user-secrets").iterdir()
|
||||
|
||||
|
||||
def test_router_authorize_callback_status_and_disconnect(
|
||||
client: TestClient,
|
||||
configured_instance: str,
|
||||
system_root: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv(account.PUBLIC_URL_ENV, "https://app.example.test")
|
||||
response = client.post(
|
||||
"/api/video-learning/invidious/account/authorize",
|
||||
headers={
|
||||
"x-forwarded-proto": "https",
|
||||
"x-forwarded-host": "forwarded.example.test",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
url = response.json()["authorize_url"]
|
||||
state = _state_from_authorize_url(url)
|
||||
callback_url = parse_qs(urlsplit(url).query)["callback_url"][0]
|
||||
assert callback_url.startswith("https://app.example.test")
|
||||
|
||||
async def complete(*, owner_id: str, state: str, token: str) -> dict[str, object]:
|
||||
assert owner_id == "u_ada"
|
||||
assert state
|
||||
assert "v1:test-session" in token
|
||||
return {"connected": True, "api_base_url": configured_instance}
|
||||
|
||||
monkeypatch.setattr(
|
||||
video_learning.invidious_account, "complete_invidious_account_authorization", complete
|
||||
)
|
||||
callback = client.get(
|
||||
"/api/video-learning/invidious/account/callback",
|
||||
params={"state": state, "token": _token()},
|
||||
)
|
||||
assert callback.status_code == 200
|
||||
assert callback.headers["cache-control"] == "no-store"
|
||||
assert "v1:test-session" not in callback.text
|
||||
|
||||
account._write(
|
||||
"u_ada",
|
||||
{
|
||||
"version": 1,
|
||||
"api_base_url": configured_instance,
|
||||
"scopes": list(account.ACCOUNT_SCOPES),
|
||||
"connected_at": "2026-09-02T00:00:00+00:00",
|
||||
"token": {"session": "v1:test-session", "signature": "test-signature"},
|
||||
},
|
||||
)
|
||||
status_response = client.get("/api/video-learning/invidious/account/status")
|
||||
assert status_response.status_code == 200
|
||||
assert status_response.json()["connected"] is True
|
||||
assert "v1:test-session" not in status_response.text
|
||||
|
||||
disconnected: dict[str, object] = {}
|
||||
|
||||
async def disconnect(*, owner_id: str) -> dict[str, object]:
|
||||
disconnected["owner_id"] = owner_id
|
||||
return {"connected": False}
|
||||
|
||||
monkeypatch.setattr(
|
||||
video_learning.invidious_account, "disconnect_invidious_account", disconnect
|
||||
)
|
||||
disconnect_response = client.post("/api/video-learning/invidious/account/disconnect")
|
||||
assert disconnect_response.status_code == 200
|
||||
assert disconnect_response.json() == {"connected": False}
|
||||
assert disconnected == {"owner_id": "u_ada"}
|
||||
|
||||
|
||||
def test_unknown_callback_returns_400_without_calling_invidious(
|
||||
client: TestClient,
|
||||
) -> None:
|
||||
response = client.get(
|
||||
"/api/video-learning/invidious/account/callback",
|
||||
params={"state": "forged", "token": _token()},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "forged" not in response.text
|
||||
assert "v1:test-session" not in response.text
|
||||
|
||||
|
||||
def test_router_start_returns_400_when_invidious_is_not_configured(
|
||||
client: TestClient,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
account,
|
||||
"load_video_learning_settings",
|
||||
lambda: {
|
||||
"version": 1,
|
||||
"default_provider": "youtube",
|
||||
"youtube": {"transcript_provider": "none"},
|
||||
"invidious": {"api_base_url": "", "public_base_url": ""},
|
||||
},
|
||||
)
|
||||
response = client.post("/api/video-learning/invidious/account/authorize")
|
||||
assert response.status_code == 400
|
||||
assert response.json()["detail"] == (
|
||||
"Configure the Invidious API base URL before connecting an account."
|
||||
)
|
||||
Reference in New Issue
Block a user