Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

Merge pull request #1122 from evan188199-tech/codex/feat-device-credentials

Bingxi Zhao (Frank)15c79a055f7a
diff --cc deeptutor/api/routers/auth.py
index eb9d85664,461482066..f0f1885ce
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@@ -29,9 -30,15 +30,17 @@@ from deeptutor.services.config import l
_SECURE = bool(load_auth_settings()["cookie_secure"])
_SAMESITE = "none" if _SECURE else "lax"
+ from deeptutor.multi_user.audit import log_admin_action
from deeptutor.multi_user.context import set_current_user, user_from_token_payload
+ from deeptutor.multi_user.device_credentials import (
+ heartbeat_device_credential,
+ issue_device_credential,
+ list_device_credentials,
+ revoke_device_credential,
+ )
+ from deeptutor.multi_user.identity import get_user_by_id
+from deeptutor.multi_user.learning_access import learning_policy_for_user
+from deeptutor.multi_user.models import AccountPreset
from deeptutor.multi_user.paths import local_admin_user
from deeptutor.services.auth import (
AUTH_ENABLED,
@@@ -526,6 -506,80 +552,82 @@@ async def login(body: LoginRequest, res
}
+ def _require_builtin_device_auth() -> None:
+ if not AUTH_ENABLED:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Device credentials require built-in authentication.",
+ )
+ if POCKETBASE_ENABLED:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Device credentials are not supported in PocketBase mode.",
+ )
+
+
+ @router.post("/device-login")
+ async def device_login(body: DeviceLoginRequest, response: Response) -> dict:
+ """Exchange a device pairing code and PIN for the account's normal cookie."""
+
+ _require_builtin_device_auth()
+ payload = authenticate_device(body.pairing_code, body.pin)
+ if payload is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Incorrect device credentials",
+ )
+
+ token = create_token(
+ payload.username,
+ payload.role,
+ payload.user_id,
+ device_credential_id=payload.device_credential_id,
++ device_session_nonce=payload.device_session_nonce,
+ )
+ response.set_cookie(value=token, max_age=_COOKIE_MAX_AGE, **_cookie_attrs())
+ logger.info(f"User '{payload.username}' logged in with a device credential")
+ return {
+ "ok": True,
+ "user_id": payload.user_id,
+ "username": payload.username,
+ "role": payload.role,
+ "is_admin": payload.role == "admin",
+ "device_credential_id": payload.device_credential_id,
+ }
+
+
+ @router.post("/device/heartbeat")
+ async def device_heartbeat(
+ response: Response,
+ payload: TokenPayload | None = Depends(require_auth),
+ ) -> dict:
+ """Refresh a device lease and account bounded daily usage."""
+
+ if not AUTH_ENABLED:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Device credentials require built-in authentication.",
+ )
- if payload is None or not payload.device_credential_id:
++ if payload is None or not payload.device_credential_id or not payload.device_session_nonce:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="This session does not use a device credential.",
+ )
+ try:
+ device = heartbeat_device_credential(
+ payload.device_credential_id,
+ user_id=payload.user_id,
++ session_nonce=payload.device_session_nonce,
+ )
+ except ValueError:
+ response.delete_cookie(**_cookie_attrs())
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Device session is no longer active",
+ ) from None
+ return {"ok": not device.pop("limit_reached"), **device}
+
+
@router.post("/logout")
async def logout(response: Response) -> dict:
"""Clear the JWT cookie.
diff --cc deeptutor/multi_user/device_credentials.py
index 000000000,3e007045d..8749a18e7
mode 000000,100644..100644
--- a/deeptutor/multi_user/device_credentials.py
+++ b/deeptutor/multi_user/device_credentials.py
@@@ -1,0 -1,345 +1,419 @@@
-"""Revocable device credentials for ordinary local user accounts."""
++"""Revocable device credentials for local learner accounts."""
+
+ from __future__ import annotations
+
+ from copy import deepcopy
+ from datetime import datetime, timedelta, timezone
+ import hashlib
+ import json
+ import secrets
+ import threading
+ from typing import Any
+ from uuid import uuid4
+
+ from deeptutor.services.file_io import atomic_write_text
+
+ from .identity import get_user_by_id
+ from .paths import SYSTEM_ROOT
+
+ DEVICE_CREDENTIALS_FILE = SYSTEM_ROOT / "auth" / "device_credentials.json"
+ HEARTBEAT_TIMEOUT_SECONDS = 5 * 60
++MAX_PIN_ATTEMPTS = 5
++PIN_LOCKOUT_SECONDS = 15 * 60
+ MIN_DAILY_LIMIT_MINUTES = 5
+ MAX_DAILY_LIMIT_MINUTES = 24 * 60
+
+ _DEVICE_WRITE_LOCK = threading.Lock()
+
+
+ def utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+ def _iso(value: datetime) -> str:
+ return value.isoformat()
+
+
+ def _parse_iso(value: Any) -> datetime | None:
+ if not isinstance(value, str) or not value:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+
+ def _hash_pairing_code(code: str) -> str:
+ return hashlib.sha256(code.encode("utf-8")).hexdigest()
+
+
++def _hash_session_nonce(nonce: str) -> str:
++ return hashlib.sha256(nonce.encode("utf-8")).hexdigest()
++
++
+ def _canonical_record(value: Any) -> dict[str, Any] | None:
+ if not isinstance(value, dict):
+ return None
+ credential_id = str(value.get("id") or f"dc_{uuid4().hex}")
+ user_id = str(value.get("user_id") or "")
+ pairing_hash = str(value.get("pairing_code_hash") or "")
+ pin_hash = str(value.get("pin_hash") or "")
+ expires_at = _parse_iso(value.get("expires_at"))
+ daily_limit = value.get("daily_limit_minutes")
+ if not user_id or not pairing_hash or not pin_hash or expires_at is None:
+ return None
+ if not isinstance(daily_limit, int) or not (
+ MIN_DAILY_LIMIT_MINUTES <= daily_limit <= MAX_DAILY_LIMIT_MINUTES
+ ):
+ return None
+ revoked_at = _parse_iso(value.get("revoked_at"))
+ last_heartbeat = _parse_iso(value.get("last_heartbeat_at"))
+ used_seconds = value.get("used_seconds", 0)
+ if not isinstance(used_seconds, int) or used_seconds < 0:
+ used_seconds = 0
+ usage_day = str(value.get("usage_day") or "")
+ if usage_day and not _valid_usage_day(usage_day):
+ usage_day = ""
++ failed_pin_attempts = value.get("failed_pin_attempts", 0)
++ if not isinstance(failed_pin_attempts, int) or failed_pin_attempts < 0:
++ failed_pin_attempts = 0
++ pin_locked_until = _parse_iso(value.get("pin_locked_until"))
+ return {
+ "id": credential_id,
+ "user_id": user_id,
+ "device_name": str(value.get("device_name") or "Device")[:80],
+ "pairing_code_hash": pairing_hash,
+ "pin_hash": pin_hash,
+ "created_at": str(value.get("created_at") or ""),
+ "expires_at": _iso(expires_at),
+ "daily_limit_minutes": daily_limit,
+ "last_login_at": str(value.get("last_login_at") or ""),
+ "last_heartbeat_at": _iso(last_heartbeat) if last_heartbeat else "",
+ "usage_day": usage_day,
+ "used_seconds": min(used_seconds, daily_limit * 60),
++ "session_nonce_hash": str(value.get("session_nonce_hash") or ""),
++ "failed_pin_attempts": min(failed_pin_attempts, MAX_PIN_ATTEMPTS),
++ "pin_locked_until": _iso(pin_locked_until) if pin_locked_until else "",
+ "revoked_at": _iso(revoked_at) if revoked_at else None,
+ "revoked_by": str(value.get("revoked_by") or "") if revoked_at else "",
+ }
+
+
+ def _valid_usage_day(value: str) -> bool:
+ try:
+ datetime.strptime(value, "%Y-%m-%d")
+ except ValueError:
+ return False
+ return True
+
+
+ def _load_records() -> list[dict[str, Any]]:
+ try:
+ loaded = json.loads(DEVICE_CREDENTIALS_FILE.read_text(encoding="utf-8"))
+ except Exception:
+ return []
+ if not isinstance(loaded, list):
+ return []
+ records: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for value in loaded:
+ record = _canonical_record(value)
+ if record is None or record["id"] in seen:
+ continue
+ seen.add(record["id"])
+ records.append(record)
+ return records
+
+
+ def _write_records(records: list[dict[str, Any]]) -> None:
+ DEVICE_CREDENTIALS_FILE.parent.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(
+ DEVICE_CREDENTIALS_FILE,
+ json.dumps(records, indent=2, ensure_ascii=False),
+ )
+
+
+ def _public_record(record: dict[str, Any]) -> dict[str, Any]:
+ return {
+ key: deepcopy(value)
+ for key, value in record.items()
- if key not in {"pairing_code_hash", "pin_hash"}
++ if key
++ not in {
++ "pairing_code_hash",
++ "pin_hash",
++ "session_nonce_hash",
++ "failed_pin_attempts",
++ "pin_locked_until",
++ }
+ }
+
+
+ def _active_account(user_id: str) -> tuple[str, dict[str, Any]] | None:
+ account = get_user_by_id(user_id)
+ if account is None:
+ return None
+ username, record = account
+ if str(record.get("role") or "user") != "user" or bool(record.get("disabled")):
+ return None
++ if str(record.get("preset") or "standard") != "learner":
++ return None
+ return username, record
+
+
+ def _usage_for(record: dict[str, Any], now: datetime) -> tuple[str, int]:
+ current_day = now.date().isoformat()
+ if record["usage_day"] != current_day:
+ return current_day, 0
+ return current_day, int(record["used_seconds"])
+
+
+ def _is_usable(record: dict[str, Any], now: datetime) -> bool:
+ if record["revoked_at"] is not None:
+ return False
+ expires_at = _parse_iso(record["expires_at"])
+ if expires_at is None or expires_at <= now:
+ return False
+ if _active_account(record["user_id"]) is None:
+ return False
+ _usage_day, used_seconds = _usage_for(record, now)
+ if used_seconds >= record["daily_limit_minutes"] * 60:
+ return False
+ last_heartbeat = _parse_iso(record["last_heartbeat_at"])
+ if last_heartbeat is None:
+ return False
+ elapsed = (now - last_heartbeat).total_seconds()
+ return 0 <= elapsed <= HEARTBEAT_TIMEOUT_SECONDS
+
+
++def _charge_previous_lease(record: dict[str, Any], now: datetime) -> None:
++ """Account for an active lease before a same-day re-login rotates it."""
++ usage_day, used_seconds = _usage_for(record, now)
++ last_heartbeat = _parse_iso(record["last_heartbeat_at"])
++ elapsed = 0
++ if last_heartbeat is not None and last_heartbeat.date() == now.date():
++ elapsed = min(
++ max(int((now - last_heartbeat).total_seconds()), 0),
++ HEARTBEAT_TIMEOUT_SECONDS,
++ )
++ record["usage_day"] = usage_day
++ record["used_seconds"] = min(
++ used_seconds + elapsed,
++ record["daily_limit_minutes"] * 60,
++ )
++
++
+ def issue_device_credential(
+ *,
+ user_id: str,
+ device_name: str,
+ expires_at: datetime,
+ daily_limit_minutes: int,
+ now: datetime | None = None,
+ ) -> tuple[dict[str, Any], str, str]:
+ """Create a credential and return its public view, code, and one-time PIN."""
+
+ current = now or utc_now()
+ if _active_account(user_id) is None:
- raise ValueError("Device credentials require an active ordinary user.")
++ raise ValueError("Device credentials require an active learner account.")
+ if expires_at <= current:
+ raise ValueError("Device credential expiry must be in the future.")
+ if expires_at - current > timedelta(days=365):
+ raise ValueError("Device credential expiry cannot exceed 365 days.")
+ if not (MIN_DAILY_LIMIT_MINUTES <= daily_limit_minutes <= MAX_DAILY_LIMIT_MINUTES):
+ raise ValueError("Daily limit must be between 5 and 1440 minutes.")
+ device = device_name.strip() or "Device"
+ if len(device) > 80:
+ raise ValueError("Device name cannot exceed 80 characters.")
+
+ from deeptutor.services.auth import hash_password
+
+ pairing_code = f"dc_{secrets.token_urlsafe(24)}"
+ pin = f"{secrets.randbelow(1_000_000):06d}"
+ record = {
+ "id": f"dc_{uuid4().hex}",
+ "user_id": user_id,
+ "device_name": device,
+ "pairing_code_hash": _hash_pairing_code(pairing_code),
+ "pin_hash": hash_password(pin),
+ "created_at": _iso(current),
+ "expires_at": _iso(expires_at),
+ "daily_limit_minutes": daily_limit_minutes,
+ "last_login_at": "",
+ "last_heartbeat_at": "",
+ "usage_day": "",
+ "used_seconds": 0,
++ "session_nonce_hash": "",
++ "failed_pin_attempts": 0,
++ "pin_locked_until": "",
+ "revoked_at": None,
+ "revoked_by": "",
+ }
+ with _DEVICE_WRITE_LOCK:
+ records = _load_records()
+ records.append(record)
+ _write_records(records)
+ return _public_record(record), pairing_code, pin
+
+
+ def list_device_credentials(
+ *, user_id: str | None = None, include_revoked: bool = False
+ ) -> list[dict[str, Any]]:
+ return [
+ _public_record(record)
+ for record in _load_records()
+ if (include_revoked or record["revoked_at"] is None)
+ and (user_id is None or record["user_id"] == user_id)
+ ]
+
+
+ def begin_device_session(
+ pairing_code: str, pin: str, now: datetime | None = None
-) -> tuple[dict[str, Any], str, str, str] | None:
++) -> tuple[dict[str, Any], str, str, str, str] | None:
+ """Verify a code and PIN, then start a bounded heartbeat session."""
+
+ current = now or utc_now()
+ pairing_hash = _hash_pairing_code(pairing_code)
+ from deeptutor.services.auth import verify_password
+
+ with _DEVICE_WRITE_LOCK:
+ records = _load_records()
+ record = next(
+ (item for item in records if item["pairing_code_hash"] == pairing_hash),
+ None,
+ )
+ if record is None or not secrets.compare_digest(record["pairing_code_hash"], pairing_hash):
+ return None
- if not verify_password(pin, record["pin_hash"]):
- return None
+ account = _active_account(record["user_id"])
+ if account is None:
+ return None
+ if record["revoked_at"] is not None:
+ return None
+ expires_at = _parse_iso(record["expires_at"])
+ if expires_at is None or expires_at <= current:
+ return None
- usage_day, used_seconds = _usage_for(record, current)
- if used_seconds >= record["daily_limit_minutes"] * 60:
++ locked_until = _parse_iso(record["pin_locked_until"])
++ if locked_until is not None and locked_until > current:
+ return None
- record["usage_day"] = usage_day
- record["used_seconds"] = used_seconds
++ if not verify_password(pin, record["pin_hash"]):
++ record["failed_pin_attempts"] += 1
++ if record["failed_pin_attempts"] >= MAX_PIN_ATTEMPTS:
++ record["pin_locked_until"] = _iso(current + timedelta(seconds=PIN_LOCKOUT_SECONDS))
++ _write_records(records)
++ return None
++ record["failed_pin_attempts"] = 0
++ record["pin_locked_until"] = ""
++ _charge_previous_lease(record, current)
++ if record["used_seconds"] >= record["daily_limit_minutes"] * 60:
++ _write_records(records)
++ return None
++ session_nonce = secrets.token_urlsafe(32)
++ record["session_nonce_hash"] = _hash_session_nonce(session_nonce)
+ record["last_login_at"] = _iso(current)
+ record["last_heartbeat_at"] = _iso(current)
+ _write_records(records)
+ username, user_record = account
+ return (
+ _public_record(record),
+ username,
+ str(user_record.get("role") or "user"),
+ record["user_id"],
++ session_nonce,
+ )
+
+
-def validate_device_token(user_id: str, credential_id: str) -> bool:
++def validate_device_token(user_id: str, credential_id: str, session_nonce: str) -> bool:
+ record = next(
+ (item for item in _load_records() if item["id"] == credential_id),
+ None,
+ )
- return record is not None and record["user_id"] == user_id and _is_usable(record, utc_now())
++ return (
++ record is not None
++ and record["user_id"] == user_id
++ and bool(session_nonce)
++ and secrets.compare_digest(
++ record["session_nonce_hash"],
++ _hash_session_nonce(session_nonce),
++ )
++ and _is_usable(record, utc_now())
++ )
+
+
+ def heartbeat_device_credential(
+ credential_id: str,
+ *,
+ user_id: str,
++ session_nonce: str,
+ now: datetime | None = None,
+ ) -> dict[str, Any]:
+ """Advance daily usage and refresh the server heartbeat lease."""
+
+ current = now or utc_now()
+ with _DEVICE_WRITE_LOCK:
+ records = _load_records()
+ record = next(
+ (item for item in records if item["id"] == credential_id),
+ None,
+ )
- if record is None or record["user_id"] != user_id or not _is_usable(record, current):
++ nonce_matches = bool(record and session_nonce) and secrets.compare_digest(
++ record["session_nonce_hash"],
++ _hash_session_nonce(session_nonce),
++ )
++ if (
++ record is None
++ or record["user_id"] != user_id
++ or not nonce_matches
++ or not _is_usable(record, current)
++ ):
+ raise ValueError("Device credential is not active.")
+
+ last_heartbeat = _parse_iso(record["last_heartbeat_at"])
+ if last_heartbeat is None:
+ raise ValueError("Device credential is not active.")
+ elapsed = int((current - last_heartbeat).total_seconds())
+ usage_day, used_seconds = _usage_for(record, current)
+ record["usage_day"] = usage_day
+ record["used_seconds"] = min(
+ used_seconds + max(elapsed, 0),
+ record["daily_limit_minutes"] * 60,
+ )
+ record["last_heartbeat_at"] = _iso(current)
+ _write_records(records)
+ limit_seconds = record["daily_limit_minutes"] * 60
+ view = _public_record(record)
+ view["remaining_seconds"] = max(limit_seconds - record["used_seconds"], 0)
+ view["limit_reached"] = record["used_seconds"] >= limit_seconds
+ return view
+
+
+ def revoke_device_credential(
+ credential_id: str, *, revoked_by: str, now: datetime | None = None
+ ) -> dict[str, Any] | None:
+ current = now or utc_now()
+ with _DEVICE_WRITE_LOCK:
+ records = _load_records()
+ for record in records:
+ if record["id"] != credential_id:
+ continue
+ if record["revoked_at"] is None:
+ record["revoked_at"] = _iso(current)
+ record["revoked_by"] = revoked_by
+ _write_records(records)
+ return _public_record(record)
+ return None
+
+
+ __all__ = [
+ "DEVICE_CREDENTIALS_FILE",
+ "HEARTBEAT_TIMEOUT_SECONDS",
++ "MAX_PIN_ATTEMPTS",
++ "PIN_LOCKOUT_SECONDS",
+ "begin_device_session",
+ "heartbeat_device_credential",
+ "issue_device_credential",
+ "list_device_credentials",
+ "revoke_device_credential",
+ "validate_device_token",
+ ]
diff --cc deeptutor/services/auth.py
index 42aaea6a7,4d42aa783..da5427fb4
--- a/deeptutor/services/auth.py
+++ b/deeptutor/services/auth.py
@@@ -73,6 -72,7 +73,8 @@@ class TokenPayload
username: str
role: str
user_id: str = ""
+ device_credential_id: str = ""
++ device_session_nonce: str = ""
# ---------------------------------------------------------------------------
@@@ -239,7 -218,12 +241,13 @@@ def get_user_info(username: str) -> dic
# ---------------------------------------------------------------------------
- def create_token(username: str, role: str = "user", user_id: str | None = None) -> str:
+ def create_token(
+ username: str,
+ role: str = "user",
+ user_id: str | None = None,
+ device_credential_id: str = "",
++ device_session_nonce: str = "",
+ ) -> str:
"""Create a signed JWT for the given username and role."""
from jose import jwt
@@@ -251,6 -235,7 +259,8 @@@
"sub": username,
"role": role,
"uid": user_id,
+ "dcid": device_credential_id,
++ "dcs": device_session_nonce,
"exp": datetime.now(timezone.utc) + timedelta(hours=TOKEN_EXPIRE_HOURS),
"iat": datetime.now(timezone.utc),
}
@@@ -297,7 -282,18 +307,24 @@@ def decode_token(token: str) -> TokenPa
if not user_id:
record = _load_users().get(str(username)) or {}
user_id = str(record.get("id") or "")
- return TokenPayload(username=username, role=payload.get("role", "user"), user_id=user_id)
+ device_credential_id = str(payload.get("dcid") or "")
++ device_session_nonce = str(payload.get("dcs") or "")
+ if device_credential_id:
+ from deeptutor.multi_user.device_credentials import validate_device_token
+
- if not validate_device_token(user_id, device_credential_id):
++ if not validate_device_token(
++ user_id,
++ device_credential_id,
++ device_session_nonce,
++ ):
+ return None
+ return TokenPayload(
+ username=username,
+ role=payload.get("role", "user"),
+ user_id=user_id,
+ device_credential_id=device_credential_id,
++ device_session_nonce=device_session_nonce,
+ )
except JWTError:
return None
@@@ -398,3 -394,22 +425,23 @@@ def authenticate(username: str, passwor
role = record.get("role", "user") if isinstance(record, dict) else "user"
user_id = str(record.get("id") or "") if isinstance(record, dict) else ""
return TokenPayload(username=username, role=role, user_id=user_id)
+
+
+ def authenticate_device(pairing_code: str, pin: str) -> TokenPayload | None:
+ """Exchange a learner device credential for the account's normal JWT identity."""
+
+ if not AUTH_ENABLED or POCKETBASE_ENABLED:
+ return None
+ from deeptutor.multi_user.device_credentials import begin_device_session
+
+ session = begin_device_session(pairing_code, pin)
+ if session is None:
+ return None
- _view, username, role, user_id = session
++ _view, username, role, user_id, session_nonce = session
+ return TokenPayload(
+ username=username,
+ role=role,
+ user_id=user_id,
+ device_credential_id=str(_view["id"]),
++ device_session_nonce=session_nonce,
+ )
diff --cc tests/multi_user/conftest.py
index 31416e832,6a1da6684..d0e42b961
--- a/tests/multi_user/conftest.py
+++ b/tests/multi_user/conftest.py
@@@ -24,7 -24,7 +24,14 @@@ def mu_isolated_root(tmp_path, monkeypa
Also clears the ``_path_services`` cache so ``get_path_service()`` can be
re-resolved per test without leaking instances created in earlier tests.
"""
- from deeptutor.multi_user import audit, grants, guardians, identity, paths
- from deeptutor.multi_user import device_credentials, grants, identity, paths
++ from deeptutor.multi_user import (
++ audit,
++ device_credentials,
++ grants,
++ guardians,
++ identity,
++ paths,
++ )
project_root = tmp_path
admin_root = (project_root / "data").resolve()
@@@ -55,8 -55,11 +62,13 @@@
)
monkeypatch.setattr(grants, "GRANTS_DIR", system_root / "grants")
+ monkeypatch.setattr(guardians, "GUARDIANS_FILE", system_root / "guardians.json")
+ monkeypatch.setattr(audit, "SYSTEM_ROOT", system_root)
+ monkeypatch.setattr(
+ device_credentials,
+ "DEVICE_CREDENTIALS_FILE",
+ system_root / "auth" / "device_credentials.json",
+ )
# The ``auth.json`` bootstrap admin is process-global state rather than a
# path, and it now takes part in the first-user promotion decision (#849).
diff --cc tests/multi_user/test_device_credentials.py
index 000000000,3b7fcb2cb..1be9ebe0b
mode 000000,100644..100644
--- a/tests/multi_user/test_device_credentials.py
+++ b/tests/multi_user/test_device_credentials.py
@@@ -1,0 -1,411 +1,515 @@@
+ from __future__ import annotations
+
+ from datetime import datetime, timedelta, timezone
+ import json
+
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+
+ def _auth(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}"}
+
+
+ def _client(mu_isolated_root, monkeypatch) -> tuple[TestClient, dict]:
+ from deeptutor.api.routers import auth as auth_router
+ from deeptutor.multi_user.identity import save_user
+ from deeptutor.services import auth as auth_service
+ from deeptutor.services.auth import create_token, hash_password
+
+ admin = save_user("root", hash_password("root-password"), role="admin")
- learner = save_user("learner", hash_password("learner-password"))
++ learner = save_user("learner", hash_password("learner-password"), preset="learner")
+ monkeypatch.setattr(auth_service, "AUTH_ENABLED", True)
+ monkeypatch.setattr(auth_service, "AUTH_SECRET", "device-credential-test-secret")
+ monkeypatch.setattr(auth_service, "POCKETBASE_ENABLED", False)
+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", True)
+ monkeypatch.setattr(auth_router, "POCKETBASE_ENABLED", False)
+
+ app = FastAPI()
+ app.include_router(auth_router.router, prefix="/api/v1/auth")
+ client = TestClient(app)
+ return client, {
+ "admin": admin,
+ "learner": learner,
+ "admin_token": create_token("root", "admin", admin["id"]),
+ }
+
+
+ def test_admin_issue_lists_and_secrets_are_not_persisted(mu_isolated_root, monkeypatch):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ learner_id = users["learner"]["id"]
+
+ created = client.post(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ json={
+ "user_id": learner_id,
+ "device_name": "Learner tablet",
+ "expires_in_days": 30,
+ "daily_limit_minutes": 30,
+ },
+ )
+ assert created.status_code == 201, created.text
+ body = created.json()
+ assert body["pairing_code"].startswith("dc_")
+ assert len(body["pin"]) == 6 and body["pin"].isdigit()
+ assert body["device"]["user_id"] == learner_id
+ assert body["device"]["daily_limit_minutes"] == 30
+
+ listed = client.get(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ )
+ assert listed.status_code == 200
+ device = listed.json()["devices"][0]
+ assert device["username"] == "learner"
+ assert "pairing_code_hash" not in device
+ assert "pin_hash" not in device
+
+ stored = mu_isolated_root.joinpath(
+ "data", "system", "auth", "device_credentials.json"
+ ).read_text(encoding="utf-8")
+ assert body["pairing_code"] not in stored
+ assert body["pin"] not in stored
+ audit = mu_isolated_root.joinpath("data", "system", "audit", "usage.jsonl").read_text(
+ encoding="utf-8"
+ )
+ assert body["pairing_code"] not in audit
+ assert body["pin"] not in audit
+
+
+ def test_only_admins_can_issue_device_credentials(mu_isolated_root, monkeypatch):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ from deeptutor.services.auth import create_token
+
+ learner_token = create_token(
+ "learner",
+ "user",
+ users["learner"]["id"],
+ )
+ denied = client.post(
+ "/api/v1/auth/devices",
+ headers=_auth(learner_token),
+ json={
+ "user_id": users["learner"]["id"],
+ "device_name": "Learner tablet",
+ "expires_in_days": 30,
+ "daily_limit_minutes": 30,
+ },
+ )
+ assert denied.status_code == 403
+
++ from deeptutor.multi_user.identity import save_user
++ from deeptutor.services.auth import hash_password
++
++ standard = save_user("standard", hash_password("standard-password"))
++ wrong_preset = client.post(
++ "/api/v1/auth/devices",
++ headers=_auth(users["admin_token"]),
++ json={
++ "user_id": standard["id"],
++ "device_name": "Standard tablet",
++ "expires_in_days": 30,
++ "daily_limit_minutes": 30,
++ },
++ )
++ assert wrong_preset.status_code == 400
++ assert "learner" in wrong_preset.json()["detail"]
++
+
+ def test_only_admins_can_list_and_revoke_device_credentials(mu_isolated_root, monkeypatch):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ from deeptutor.services.auth import create_token
+
+ learner_token = create_token(
+ "learner",
+ "user",
+ users["learner"]["id"],
+ )
+ empty = client.get("/api/v1/auth/devices", headers=_auth(users["admin_token"]))
+ assert empty.status_code == 200
+ assert empty.json() == {"devices": []}
+
+ assert client.get("/api/v1/auth/devices", headers=_auth(learner_token)).status_code == 403
+ assert (
+ client.delete(
+ "/api/v1/auth/devices/dc_missing",
+ headers=_auth(learner_token),
+ ).status_code
+ == 403
+ )
+ assert (
+ client.delete(
+ "/api/v1/auth/devices/dc_missing",
+ headers=_auth(users["admin_token"]),
+ ).status_code
+ == 404
+ )
+
+
+ def test_device_login_returns_normal_identity_and_revocation_invalidates_token(
+ mu_isolated_root, monkeypatch
+ ):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ learner_id = users["learner"]["id"]
+ issued = client.post(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ json={
+ "user_id": learner_id,
+ "device_name": "Learner tablet",
+ "expires_in_days": 30,
+ "daily_limit_minutes": 30,
+ },
+ ).json()
+
+ unknown_code = client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": "dc_not-real", "pin": "123456"},
+ )
+ assert unknown_code.status_code == 401
+
+ wrong_pin = client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": "000000"},
+ )
+ assert wrong_pin.status_code == 401
+
+ login = client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ )
+ assert login.status_code == 200, login.text
+ body = login.json()
+ assert body["username"] == "learner"
+ assert body["role"] == "user"
+ token = login.cookies["dt_token"]
+
+ status = client.get("/api/v1/auth/status", headers=_auth(token))
+ assert status.status_code == 200
+ assert status.json()["username"] == "learner"
+
+ revoked = client.delete(
+ f"/api/v1/auth/devices/{issued['device']['id']}",
+ headers=_auth(users["admin_token"]),
+ )
+ assert revoked.status_code == 200
+ revoked_status = client.get("/api/v1/auth/status", headers=_auth(token))
+ assert revoked_status.status_code == 200
+ assert revoked_status.json()["authenticated"] is False
+ assert (
+ client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ ).status_code
+ == 401
+ )
+
+
++def test_relogin_rotates_the_lease_and_charges_elapsed_usage(mu_isolated_root, monkeypatch):
++ client, users = _client(mu_isolated_root, monkeypatch)
++ issued = client.post(
++ "/api/v1/auth/devices",
++ headers=_auth(users["admin_token"]),
++ json={
++ "user_id": users["learner"]["id"],
++ "device_name": "Learner tablet",
++ "expires_in_days": 30,
++ "daily_limit_minutes": 30,
++ },
++ ).json()
++ first = client.post(
++ "/api/v1/auth/device-login",
++ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
++ )
++ first_token = first.cookies["dt_token"]
++ started = datetime.fromisoformat(
++ client.get("/api/v1/auth/devices", headers=_auth(users["admin_token"])).json()["devices"][
++ 0
++ ]["last_heartbeat_at"]
++ )
++
++ from deeptutor.multi_user import device_credentials
++
++ monkeypatch.setattr(device_credentials, "utc_now", lambda: _add_seconds(started, 60))
++ second = client.post(
++ "/api/v1/auth/device-login",
++ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
++ )
++ assert second.status_code == 200
++ second_token = second.cookies["dt_token"]
++
++ first_status = client.get("/api/v1/auth/status", headers=_auth(first_token))
++ assert first_status.json()["authenticated"] is False
++ assert (
++ client.get("/api/v1/auth/status", headers=_auth(second_token)).json()["authenticated"]
++ is True
++ )
++ listed = client.get("/api/v1/auth/devices", headers=_auth(users["admin_token"])).json()[
++ "devices"
++ ]
++ assert listed[0]["used_seconds"] == 60
++
++
++def test_pin_failures_are_rate_limited(mu_isolated_root, monkeypatch):
++ client, users = _client(mu_isolated_root, monkeypatch)
++ issued = client.post(
++ "/api/v1/auth/devices",
++ headers=_auth(users["admin_token"]),
++ json={
++ "user_id": users["learner"]["id"],
++ "device_name": "Learner tablet",
++ "expires_in_days": 30,
++ "daily_limit_minutes": 30,
++ },
++ ).json()
++ wrong_pin = "000001" if issued["pin"] == "000000" else "000000"
++ for _ in range(5):
++ denied = client.post(
++ "/api/v1/auth/device-login",
++ json={"pairing_code": issued["pairing_code"], "pin": wrong_pin},
++ )
++ assert denied.status_code == 401
++
++ locked = client.post(
++ "/api/v1/auth/device-login",
++ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
++ )
++ assert locked.status_code == 401
++
++ from deeptutor.multi_user import device_credentials
++
++ records = json.loads(device_credentials.DEVICE_CREDENTIALS_FILE.read_text())
++ locked_until = datetime.fromisoformat(records[0]["pin_locked_until"])
++ monkeypatch.setattr(
++ device_credentials,
++ "utc_now",
++ lambda: locked_until + timedelta(seconds=1),
++ )
++ recovered = client.post(
++ "/api/v1/auth/device-login",
++ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
++ )
++ assert recovered.status_code == 200
++
++
+ def test_expired_and_deleted_accounts_fail_closed(mu_isolated_root, monkeypatch):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ learner_id = users["learner"]["id"]
+ issued = client.post(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ json={
+ "user_id": learner_id,
+ "device_name": "Learner tablet",
+ "expires_in_days": 1,
+ "daily_limit_minutes": 30,
+ },
+ ).json()
+
+ from deeptutor.multi_user import device_credentials
+
+ real_now = device_credentials.utc_now
+ future = datetime.fromisoformat(issued["device"]["expires_at"])
+ if future.tzinfo is None:
+ future = future.replace(tzinfo=timezone.utc)
+ monkeypatch.setattr(device_credentials, "utc_now", lambda: future + timedelta(seconds=1))
+ assert (
+ client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ ).status_code
+ == 401
+ )
+ monkeypatch.setattr(device_credentials, "utc_now", real_now)
+
+ login = client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ )
+ assert login.status_code == 200
+ token = login.cookies["dt_token"]
+
+ monkeypatch.setattr(device_credentials, "utc_now", lambda: future + timedelta(seconds=1))
+ expired_status = client.get("/api/v1/auth/status", headers=_auth(token))
+ assert expired_status.status_code == 200
+ assert expired_status.json()["authenticated"] is False
+ monkeypatch.setattr(device_credentials, "utc_now", real_now)
+
+ from deeptutor.multi_user.identity import delete_user
+
+ assert delete_user("learner") is True
+ deleted_status = client.get("/api/v1/auth/status", headers=_auth(token))
+ assert deleted_status.status_code == 200
+ assert deleted_status.json()["authenticated"] is False
+
+
+ def test_disabled_account_fails_closed(mu_isolated_root, monkeypatch):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ issued = client.post(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ json={
+ "user_id": users["learner"]["id"],
+ "device_name": "Learner tablet",
+ "expires_in_days": 30,
+ "daily_limit_minutes": 30,
+ },
+ ).json()
+ login = client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ )
+ assert login.status_code == 200
+ token = login.cookies["dt_token"]
+
+ from deeptutor.multi_user import identity
+
+ users_on_disk = json.loads(identity.USERS_FILE.read_text(encoding="utf-8"))
+ users_on_disk["learner"]["disabled"] = True
+ identity.USERS_FILE.write_text(json.dumps(users_on_disk), encoding="utf-8")
+
+ assert (
+ client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ ).status_code
+ == 401
+ )
+ disabled_status = client.get("/api/v1/auth/status", headers=_auth(token))
+ assert disabled_status.status_code == 200
+ assert disabled_status.json()["authenticated"] is False
+
+
+ def test_heartbeat_enforces_freshness_daily_limit_and_day_rollover(mu_isolated_root, monkeypatch):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ learner_id = users["learner"]["id"]
+ issued = client.post(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ json={
+ "user_id": learner_id,
+ "device_name": "Learner tablet",
+ "expires_in_days": 30,
+ "daily_limit_minutes": 5,
+ },
+ ).json()
+ login = client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ )
+ assert login.status_code == 200
+ token = login.cookies["dt_token"]
+
+ listed = client.get(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ ).json()["devices"]
+ started = datetime.fromisoformat(listed[0]["last_heartbeat_at"])
+
+ from deeptutor.multi_user import device_credentials
+
+ monkeypatch.setattr(device_credentials, "utc_now", lambda: started)
+ first = client.post("/api/v1/auth/device/heartbeat", headers=_auth(token))
+ assert first.status_code == 200
+ assert first.json()["remaining_seconds"] == 300
+
+ monkeypatch.setattr(device_credentials, "utc_now", lambda: _add_seconds(started, 60))
+ second = client.post("/api/v1/auth/device/heartbeat", headers=_auth(token))
+ assert second.status_code == 200
+ assert second.json()["used_seconds"] == 60
+ assert client.get("/api/v1/auth/status", headers=_auth(token)).status_code == 200
+
+ monkeypatch.setattr(device_credentials, "utc_now", lambda: _add_seconds(started, 300))
+ limited = client.post("/api/v1/auth/device/heartbeat", headers=_auth(token))
+ assert limited.status_code == 200
+ assert limited.json()["ok"] is False
+ assert limited.json()["remaining_seconds"] == 0
+ limited_status = client.get("/api/v1/auth/status", headers=_auth(token))
+ assert limited_status.status_code == 200
+ assert limited_status.json()["authenticated"] is False
+ assert (
+ client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ ).status_code
+ == 401
+ )
+
+ monkeypatch.setattr(device_credentials, "utc_now", lambda: _add_seconds(started, 86_400))
+ rolled = client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ )
+ assert rolled.status_code == 200
+ rolled_list = client.get(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ ).json()["devices"]
+ assert rolled_list[0]["used_seconds"] == 0
+
+
+ def test_stale_heartbeat_cannot_access_authenticated_api(mu_isolated_root, monkeypatch):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ learner_id = users["learner"]["id"]
+ issued = client.post(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ json={
+ "user_id": learner_id,
+ "device_name": "Learner tablet",
+ "expires_in_days": 30,
+ "daily_limit_minutes": 30,
+ },
+ ).json()
+ login = client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": issued["pairing_code"], "pin": issued["pin"]},
+ )
+ token = login.cookies["dt_token"]
+ listed = client.get(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ ).json()["devices"]
+ started = datetime.fromisoformat(listed[0]["last_heartbeat_at"])
+
+ from deeptutor.multi_user import device_credentials
+
+ monkeypatch.setattr(device_credentials, "utc_now", lambda: _add_seconds(started, 301))
+ stale_status = client.get("/api/v1/auth/status", headers=_auth(token))
+ assert stale_status.status_code == 200
+ assert stale_status.json()["authenticated"] is False
+ assert client.post("/api/v1/auth/device/heartbeat", headers=_auth(token)).status_code == 401
+
+
+ def test_pocketbase_mode_rejects_local_device_credentials(mu_isolated_root, monkeypatch):
+ client, users = _client(mu_isolated_root, monkeypatch)
+ from deeptutor.api.routers import auth as auth_router
+
+ monkeypatch.setattr(auth_router, "POCKETBASE_ENABLED", True)
+ assert (
+ client.post(
+ "/api/v1/auth/devices",
+ headers=_auth(users["admin_token"]),
+ json={
+ "user_id": users["learner"]["id"],
+ "device_name": "Learner tablet",
+ "expires_in_days": 30,
+ "daily_limit_minutes": 30,
+ },
+ ).status_code
+ == 400
+ )
+ assert (
+ client.post(
+ "/api/v1/auth/device-login",
+ json={"pairing_code": "dc_not-real", "pin": "123456"},
+ ).status_code
+ == 400
+ )
+
+
+ def _add_seconds(value: datetime, seconds: int) -> datetime:
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=timezone.utc)
+ return value + timedelta(seconds=seconds)