Coverage for downtify/auth.py: 96%
615 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Sign-in for the web UI and paired apps.
3Everything but the web app's own files and a few public routes needs a
4signed-in user (:mod:`downtify.users`): a browser signed in with a
5username and password (a session cookie), or an app paired to a user's
6account in Settings > Apps.
8* **Web sessions.** ``POST /api/auth/login`` with the username and
9 password sets an HttpOnly cookie that lasts 30 days after it was last
10 used. An *admin* user's session has the admin scope: everything. A
11 normal *user*'s has the user scope: what a paired app may do, plus
12 their own account, preferences and devices.
13* **Paired devices** (the Android app). Settings > Apps shows a short
14 code (and a QR code carrying it); an app that sends it back to
15 ``POST /api/auth/pair`` within five minutes gets a long-lived device
16 token, ``dtfy_<device id>_<secret>``, sent as ``Authorization: Bearer``,
17 tied to the user who paired it. Only a hash of the secret is stored; a
18 device can be revoked at any time. An app may instead sign in with the
19 user's username and password at ``POST /api/auth/token`` and get the
20 same kind of token without the web page. Devices get the *client*
21 scope: they can read and play the library and ask for downloads, but
22 settings, credentials, deleting files and managing devices need a
23 browser.
25Players that can't send headers (a Chromecast receiver fetching a stream
26itself) use **signed URLs**: ``exp``, ``kid`` (the device) and ``sig``
27query parameters, an HMAC over the method, path and every other query
28parameter, valid until ``exp`` and only while the device isn't revoked.
29Long-lived tokens never go in a URL.
31Everything here is stored in ``<data>/downtify_auth.db`` and
32``<data>/.auth_secret`` (the signing key) - never in ``settings.json``,
33which ``GET /api/settings`` hands out. Passwords are hashed with scrypt
34(standard library); tokens and session ids, being random and long, with
35SHA-256. Every comparison of a secret is constant-time.
37:class:`AuthMiddleware` enforces all of it for HTTP routes, static mounts
38and the WebSocket alike, from one table of path rules (:data:`RULES`);
39anything not listed there needs the admin scope, so a new route can't be
40left open by mistake (a test checks every route is listed on purpose).
42``DOWNTIFY_DISABLE_AUTH=true`` turns accounts off for a server nobody
43else can reach: nobody signs in, and every request without a device
44token is the first admin's (:func:`open_principal`). Paired apps, signed
45URLs and the same-site check keep working.
46"""
48from __future__ import annotations
50import asyncio
51import base64
52import hashlib
53import hmac
54import json
55import os
56import re
57import secrets
58import threading
59import time
60from collections import deque
61from collections.abc import (
62 Awaitable,
63 Callable,
64 Iterable,
65 Iterator,
66 MutableMapping,
67)
68from contextlib import contextmanager
69from dataclasses import dataclass
70from datetime import datetime, timedelta, timezone
71from http.cookies import SimpleCookie
72from ipaddress import ip_address, ip_network
73from pathlib import Path
74from typing import Any, Optional
75from urllib.parse import parse_qsl, urlencode
77from loguru import logger
79from .db.config import Dialect
80from .db.core import Connection, Database, as_database
81from .users import ROLE_ADMIN, UserStore, public_user
83# ── Scopes and principals ───────────────────────────────────────────────
85PUBLIC = 'public'
86#: A paired app (or a signed URL for one).
87CLIENT = 'client'
88#: A browser signed in as a normal user: CLIENT, plus their own account.
89USER = 'user'
90#: A browser signed in as an admin: everything.
91ADMIN = 'admin'
93_RANK = {PUBLIC: 0, CLIENT: 1, USER: 2, ADMIN: 3}
96def allows(held: str, needed: str) -> bool:
97 """Whether a principal with scope *held* may use a route that needs
98 *needed*."""
100 return _RANK.get(held, 0) >= _RANK.get(needed, 3)
103#: The cookie a signed-in browser carries.
104SESSION_COOKIE = 'downtify_session'
105#: How long a web session lasts without being used.
106SESSION_TTL = timedelta(days=30)
107#: A web session's expiry is pushed back at most this often.
108SESSION_TOUCH_INTERVAL = timedelta(hours=1)
109#: A device's last-seen time and IP are written at most this often.
110DEVICE_TOUCH_INTERVAL = timedelta(minutes=1)
111#: Seconds a checked session or device token is trusted without asking
112#: the database again (every request is checked, on the event loop).
113#: Signing out, revoking and account changes clear it at once.
114SIGN_IN_CACHE_SECONDS = 30.0
115#: How long a pairing code shown in Settings > Apps can be used.
116PAIRING_TTL_SECONDS = 300
117#: How long a WebSocket ticket can be used.
118WS_TICKET_TTL_SECONDS = 60
119#: Signed URLs: default and longest lifetime, in seconds.
120SIGNED_URL_DEFAULT_TTL = 3600
121SIGNED_URL_MAX_TTL = 24 * 3600
122#: Longest device name kept.
123MAX_DEVICE_NAME = 64
125TOKEN_PREFIX = 'dtfy_'
126_DEVICE_ID_ALPHABET = 'abcdefghijkmnpqrstuvwxyz23456789'
127_DEVICE_ID_LENGTH = 12
128_TOKEN_RE = re.compile(r'^dtfy_([a-z2-9]{12})_([A-Za-z0-9_-]{32,64})$')
130# Pairing codes: Crockford base32 (no I, L, O, U), 8 characters ≈ 40 bits,
131# shown as XXXX-XXXX. Typed codes are normalised (case, dashes, and the
132# letters Crockford reads as digits).
133_PAIR_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
134_PAIR_CODE_LENGTH = 8
135_PAIR_TYPO_MAP = str.maketrans({'I': '1', 'L': '1', 'O': '0', 'U': 'V'})
138@dataclass(frozen=True)
139class Principal:
140 """Who made a request."""
142 #: 'session' (a signed-in browser), 'device' (a paired app, by token),
143 #: 'signed' (a signed URL), 'ticket' (a WebSocket ticket).
144 kind: str
145 scope: str
146 device_id: str = ''
147 #: The signed-in user (``0`` for a signed URL, which only knows the
148 #: device), their name and role.
149 user_id: int = 0
150 username: str = ''
151 role: str = ''
153 @property
154 def is_admin(self) -> bool:
155 return self.role == ROLE_ADMIN
158def _now() -> datetime:
159 return datetime.now(timezone.utc)
162def _iso(when: datetime) -> str:
163 return when.isoformat()
166def _parse(value: Any) -> Optional[datetime]:
167 try:
168 parsed = datetime.fromisoformat(str(value))
169 except (TypeError, ValueError):
170 return None
171 return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
174def _sha256(text: str) -> str:
175 return hashlib.sha256(text.encode()).hexdigest()
178def _b64(data: bytes) -> str:
179 return base64.urlsafe_b64encode(data).rstrip(b'=').decode()
182# ── Pairing codes ───────────────────────────────────────────────────────
185def new_pairing_code() -> str:
186 """A random ``XXXX-XXXX`` pairing code."""
188 raw = ''.join(
189 secrets.choice(_PAIR_ALPHABET) for _ in range(_PAIR_CODE_LENGTH)
190 )
191 return f'{raw[:4]}-{raw[4:]}'
194def normalize_pairing_code(value: Any) -> str:
195 """A typed or scanned code in its canonical form (no dash, upper
196 case, look-alike letters read as Crockford does), or ``''``."""
198 text = re.sub(r'[\s-]', '', str(value or '')).upper()
199 text = text.translate(_PAIR_TYPO_MAP)
200 if len(text) != _PAIR_CODE_LENGTH or any(
201 ch not in _PAIR_ALPHABET for ch in text
202 ):
203 return ''
204 return text
207def clean_device_name(value: Any) -> str:
208 text = ' '.join(str(value or '').split())[:MAX_DEVICE_NAME]
209 return text or 'Unnamed device'
212class PairingStore:
213 """Pairing sessions waiting for an app, kept in memory.
215 Each has an id (for the web page to follow it) and a code (what the
216 app sends). Only the code's hash is kept; claiming it is atomic and
217 single-use. Pending sessions don't survive a restart, which is fine
218 for something that lasts five minutes.
219 """
221 def __init__(self, ttl_seconds: int = PAIRING_TTL_SECONDS) -> None:
222 self._ttl = ttl_seconds
223 self._lock = threading.Lock()
224 # pairing id -> {code_hash, expires, device}
225 self._sessions: dict[str, dict[str, Any]] = {}
227 def _prune(self, now: float) -> None:
228 for pid, entry in list(self._sessions.items()):
229 # A claimed one stays a little longer so the page sees it.
230 if entry['expires'] + (60 if entry['device'] else 0) <= now:
231 del self._sessions[pid]
233 def create(self, user_id: int = 0) -> dict[str, Any]:
234 """A new pairing session for *user_id*'s account:
235 ``{pairing_id, code, expires_in}``."""
237 code = new_pairing_code()
238 pairing_id = secrets.token_urlsafe(12)
239 with self._lock:
240 now = time.monotonic()
241 self._prune(now)
242 self._sessions[pairing_id] = {
243 'code_hash': _sha256(normalize_pairing_code(code)),
244 'expires': now + self._ttl,
245 'device': None,
246 'user_id': user_id,
247 }
248 return {
249 'pairing_id': pairing_id,
250 'code': code,
251 'expires_in': self._ttl,
252 }
254 def claim(self, code: Any) -> Optional[str]:
255 """The id of the pending session *code* belongs to, now used up;
256 ``None`` for a wrong, expired or already used code."""
258 canonical = normalize_pairing_code(code)
259 if not canonical:
260 return None
261 wanted = _sha256(canonical)
262 with self._lock:
263 now = time.monotonic()
264 self._prune(now)
265 for pid, entry in self._sessions.items():
266 if entry['device'] is not None or entry['expires'] <= now:
267 continue
268 if hmac.compare_digest(entry['code_hash'], wanted):
269 # Used up at once, before the token is even made.
270 entry['code_hash'] = ''
271 entry['device'] = {}
272 return pid
273 return None
275 def owner(self, pairing_id: str) -> Optional[int]:
276 """The user a pairing session is for, while it exists."""
278 with self._lock:
279 entry = self._sessions.get(pairing_id)
280 return None if entry is None else int(entry['user_id'])
282 def complete(self, pairing_id: str, device: dict[str, Any]) -> None:
283 with self._lock:
284 entry = self._sessions.get(pairing_id)
285 if entry is not None:
286 entry['device'] = device
288 def status(self, pairing_id: str) -> dict[str, Any]:
289 """``{status: pending|paired|expired, device?, expires_in?}``."""
291 with self._lock:
292 now = time.monotonic()
293 self._prune(now)
294 entry = self._sessions.get(pairing_id)
295 if entry is None:
296 return {'status': 'expired'}
297 if entry['device']:
298 return {'status': 'paired', 'device': entry['device']}
299 if entry['expires'] <= now:
300 return {'status': 'expired'}
301 return {
302 'status': 'pending',
303 'expires_in': max(0, int(entry['expires'] - now)),
304 }
306 def cancel(self, pairing_id: str) -> None:
307 with self._lock:
308 self._sessions.pop(pairing_id, None)
311class TicketStore:
312 """Single-use, short-lived WebSocket tickets, kept in memory."""
314 def __init__(self, ttl_seconds: int = WS_TICKET_TTL_SECONDS) -> None:
315 self._ttl = ttl_seconds
316 self._lock = threading.Lock()
317 self._tickets: dict[str, tuple[float, Principal]] = {}
319 def create(self, principal: Principal) -> str:
320 ticket = secrets.token_urlsafe(24)
321 with self._lock:
322 now = time.monotonic()
323 for key, (expires, _p) in list(self._tickets.items()):
324 if expires <= now:
325 del self._tickets[key]
326 self._tickets[_sha256(ticket)] = (now + self._ttl, principal)
327 return ticket
329 def claim(self, ticket: str) -> Optional[Principal]:
330 with self._lock:
331 found = self._tickets.pop(_sha256(str(ticket or '')), None)
332 if found is None or found[0] <= time.monotonic():
333 return None
334 return found[1]
337# ── Rate limiting and client addresses ──────────────────────────────────
340class RateLimiter:
341 """At most *limit* failures per key within *window* seconds."""
343 def __init__(self, limit: int = 10, window: float = 300.0) -> None:
344 self._limit = limit
345 self._window = window
346 self._lock = threading.Lock()
347 self._hits: dict[str, deque[float]] = {}
349 def _recent(self, key: str, now: float) -> deque[float]:
350 hits = self._hits.setdefault(key, deque())
351 while hits and hits[0] <= now - self._window:
352 hits.popleft()
353 return hits
355 def retry_after(self, key: str) -> int:
356 """Seconds until *key* may try again; ``0`` when it may now."""
358 now = time.monotonic()
359 with self._lock:
360 hits = self._recent(key, now)
361 if len(hits) < self._limit:
362 return 0
363 return max(1, int(hits[0] + self._window - now) + 1)
365 def fail(self, key: str) -> None:
366 now = time.monotonic()
367 with self._lock:
368 self._recent(key, now).append(now)
370 def reset(self, key: str) -> None:
371 with self._lock:
372 self._hits.pop(key, None)
375def trusted_proxies_from_env() -> list[Any]:
376 """``DOWNTIFY_TRUSTED_PROXIES``: comma-separated IPs or networks whose
377 ``X-Forwarded-For`` is believed. Unset: nobody's is."""
379 networks = []
380 for raw in os.getenv('DOWNTIFY_TRUSTED_PROXIES', '').split(','):
381 part = raw.strip()
382 if not part:
383 continue
384 try:
385 networks.append(ip_network(part, strict=False))
386 except ValueError:
387 logger.warning('DOWNTIFY_TRUSTED_PROXIES: ignoring {!r}', part)
388 return networks
391def client_ip(scope: MutableMapping[str, Any], trusted: list[Any]) -> str:
392 """The client's address: the TCP peer, or - only when the peer is a
393 trusted proxy - the last address in ``X-Forwarded-For`` that isn't
394 one. Believing that header from anyone would let a client pick the
395 address its failed logins are counted against."""
397 peer = (scope.get('client') or ('', 0))[0] or ''
398 if not trusted or not _in_networks(peer, trusted):
399 return peer
400 forwarded = _header(scope, 'x-forwarded-for')
401 hops = [h.strip() for h in forwarded.split(',') if h.strip()]
402 for hop in reversed(hops):
403 if not _in_networks(hop, trusted):
404 return hop
405 return peer
408def _in_networks(address: str, networks: list[Any]) -> bool:
409 try:
410 addr = ip_address(address)
411 except ValueError:
412 return False
413 return any(addr in net for net in networks)
416def _header(scope: MutableMapping[str, Any], name: str) -> str:
417 wanted = name.lower().encode()
418 for key, value in scope.get('headers') or []:
419 if key.lower() == wanted:
420 return value.decode('latin-1')
421 return ''
424# ── The store ───────────────────────────────────────────────────────────
427#: Returned by ``AuthStore.peek_*`` when a credential isn't in the sign-in
428#: cache: the caller must then check it against the database.
429MISS: Any = object()
432class _SignInCache:
433 """Recently checked credentials: ``key -> (deadline, user dict)``.
435 :meth:`clear` bumps a generation; a lookup that started before a
436 clear (and so may have read a session that is gone now) doesn't
437 store its answer.
438 """
440 _MAX_ITEMS = 1024
442 def __init__(self, ttl_seconds: float) -> None:
443 self._ttl = ttl_seconds
444 self._items: dict[str, tuple[float, dict[str, Any]]] = {}
445 self._generation = 0
446 self._lock = threading.Lock()
448 def generation(self) -> int:
449 with self._lock:
450 return self._generation
452 def get(self, key: str) -> Optional[dict[str, Any]]:
453 with self._lock:
454 hit = self._items.get(key)
455 if hit is None:
456 return None
457 if hit[0] <= time.monotonic():
458 del self._items[key]
459 return None
460 return dict(hit[1])
462 def put(
463 self,
464 key: str,
465 value: dict[str, Any],
466 *,
467 generation: int,
468 max_age: Optional[float] = None,
469 ) -> None:
470 ttl = self._ttl if max_age is None else min(self._ttl, max_age)
471 if ttl <= 0:
472 return
473 with self._lock:
474 if generation != self._generation:
475 return
476 if len(self._items) >= self._MAX_ITEMS:
477 self._items.clear()
478 self._items[key] = (time.monotonic() + ttl, dict(value))
480 def clear(self) -> None:
481 with self._lock:
482 self._items.clear()
483 self._generation += 1
486class AuthStore:
487 """Users, web sessions, paired devices and the signing key.
489 The accounts themselves are :attr:`users` (:class:`UserStore`); every
490 session and device belongs to one of them.
491 """
493 def __init__(
494 self,
495 db_path: str | Path | Database,
496 secret_path: Path,
497 *,
498 existing_install: bool = False,
499 auth_disabled: bool = False,
500 ) -> None:
501 self.db = as_database(db_path, 'auth')
502 self._path = None if self.db.path is None else str(self.db.path)
503 #: ``DOWNTIFY_DISABLE_AUTH``: no sign-in, one user (the admin).
504 self.auth_disabled = auth_disabled
505 self._lock = threading.Lock()
506 self._signed_in = _SignInCache(SIGN_IN_CACHE_SECONDS)
507 self._init_db()
508 self.users = UserStore(self.db)
509 self.users.add_change_listener(self._signed_in.clear)
510 if self.users.ensure_default_admin(existing_install=existing_install):
511 # Sessions from before accounts belong to nobody.
512 self.end_all_sessions()
513 self.signer = UrlSigner(secret_path, self.device_active)
515 # Storage
517 @contextmanager
518 def _connect(self) -> Iterator[Connection]:
519 with self.db.connect() as conn:
520 if conn.dialect is Dialect.POSTGRES:
521 # First statement of the transaction (SET LOCAL lasts
522 # until it ends): a slow database fails the check
523 # instead of hanging sign-in.
524 conn.execute("SET LOCAL statement_timeout = '2s'")
525 yield conn
527 def _init_db(self) -> None:
528 # PostgreSQL gets its schema from the migrations.
529 if self.db.dialect is not Dialect.SQLITE:
530 return
531 with self._connect() as conn:
532 conn.execute("""
533 CREATE TABLE IF NOT EXISTS auth_devices (
534 id TEXT PRIMARY KEY,
535 name TEXT NOT NULL,
536 platform TEXT NOT NULL DEFAULT '',
537 token_hash TEXT NOT NULL,
538 created_at TEXT NOT NULL,
539 last_seen_at TEXT,
540 last_ip TEXT NOT NULL DEFAULT '',
541 revoked_at TEXT,
542 user_id INTEGER NOT NULL DEFAULT 0
543 )
544 """)
545 conn.execute("""
546 CREATE TABLE IF NOT EXISTS auth_sessions (
547 id_hash TEXT PRIMARY KEY,
548 created_at TEXT NOT NULL,
549 expires_at TEXT NOT NULL,
550 touched_at TEXT NOT NULL,
551 ip TEXT NOT NULL DEFAULT '',
552 user_agent TEXT NOT NULL DEFAULT '',
553 user_id INTEGER NOT NULL DEFAULT 0
554 )
555 """)
556 # Databases from before accounts: sessions and devices gain
557 # their owner.
558 for table in ('auth_devices', 'auth_sessions'):
559 columns = {
560 row[1]
561 for row in conn.execute(f'PRAGMA table_info({table})')
562 }
563 if 'user_id' not in columns:
564 conn.execute(
565 f'ALTER TABLE {table} ADD COLUMN user_id '
566 'INTEGER NOT NULL DEFAULT 0'
567 )
569 # Web sessions
571 def create_session(
572 self, user_id: int, ip: str = '', user_agent: str = ''
573 ) -> str:
574 token = secrets.token_urlsafe(32)
575 now = _now()
576 with self._connect() as conn:
577 conn.execute(
578 """INSERT INTO auth_sessions
579 (id_hash, created_at, expires_at, touched_at, ip,
580 user_agent, user_id)
581 VALUES (?, ?, ?, ?, ?, ?, ?)""",
582 (
583 _sha256(token),
584 _iso(now),
585 _iso(now + SESSION_TTL),
586 _iso(now),
587 ip[:64],
588 user_agent[:200],
589 user_id,
590 ),
591 )
592 return token
594 def session_user(self, token: str) -> Optional[dict[str, Any]]:
595 """The user a live web session *token* belongs to (and keep the
596 session alive); ``None`` for an unknown or expired one."""
598 if not token or len(token) > 128:
599 return None
600 key = _sha256(token)
601 cached = self._signed_in.get('s:' + key)
602 if cached is not None:
603 return cached
604 generation = self._signed_in.generation()
605 with self._connect() as conn:
606 row = conn.execute(
607 'SELECT s.expires_at, s.touched_at, u.* '
608 'FROM auth_sessions s JOIN users u ON u.id = s.user_id '
609 'WHERE s.id_hash = ?',
610 (key,),
611 ).fetchone()
612 if row is None:
613 return None
614 now = _now()
615 expires = _parse(row['expires_at'])
616 if expires is None or expires <= now:
617 conn.execute(
618 'DELETE FROM auth_sessions WHERE id_hash = ?', (key,)
619 )
620 return None
621 touched = _parse(row['touched_at'])
622 if touched is None or now - touched >= SESSION_TOUCH_INTERVAL:
623 conn.execute(
624 'UPDATE auth_sessions SET expires_at = ?, touched_at = ? '
625 'WHERE id_hash = ?',
626 (_iso(now + SESSION_TTL), _iso(now), key),
627 )
628 expires = now + SESSION_TTL
629 user = public_user(row)
630 self._signed_in.put(
631 's:' + key,
632 user,
633 generation=generation,
634 max_age=(expires - now).total_seconds(),
635 )
636 return user
638 def peek_session(self, token: str) -> Any:
639 """What :meth:`session_user` would answer from the sign-in cache,
640 without the database: the user, ``None`` for a token that can't
641 be valid, or :data:`MISS`. Safe to call on the event loop."""
643 if not token or len(token) > 128:
644 return None
645 cached = self._signed_in.get('s:' + _sha256(token))
646 return MISS if cached is None else cached
648 def peek_device(self, token: str) -> Any:
649 """Like :meth:`peek_session` for :meth:`verify_device_token`."""
651 if not _TOKEN_RE.match(token or ''):
652 return None
653 cached = self._signed_in.get('d:' + _sha256(token))
654 return MISS if cached is None else cached
656 def end_session(self, token: str) -> None:
657 with self._connect() as conn:
658 conn.execute(
659 'DELETE FROM auth_sessions WHERE id_hash = ?',
660 (_sha256(token or ''),),
661 )
662 self._signed_in.clear()
664 def end_all_sessions(self) -> int:
665 with self._connect() as conn:
666 count = conn.execute('DELETE FROM auth_sessions').rowcount
667 self._signed_in.clear()
668 return count
670 def end_user_sessions(self, user_id: int, keep: str = '') -> int:
671 """Sign *user_id* out of every browser but the one with the
672 session *keep* (e.g. the one that just changed the password)."""
674 with self._connect() as conn:
675 count = conn.execute(
676 'DELETE FROM auth_sessions WHERE user_id = ? AND id_hash != ?',
677 (user_id, _sha256(keep) if keep else ''),
678 ).rowcount
679 self._signed_in.clear()
680 return count
682 # Devices
684 def create_device(
685 self, name: str, platform: str = '', ip: str = '', user_id: int = 0
686 ) -> tuple[dict[str, Any], str]:
687 """Register a device paired to *user_id*: ``(device, token)``.
688 The token is shown to the app once and never stored."""
690 device_id = ''.join(
691 secrets.choice(_DEVICE_ID_ALPHABET)
692 for _ in range(_DEVICE_ID_LENGTH)
693 )
694 secret = secrets.token_urlsafe(32)
695 now = _iso(_now())
696 with self._connect() as conn:
697 conn.execute(
698 """INSERT INTO auth_devices
699 (id, name, platform, token_hash, created_at,
700 last_seen_at, last_ip, user_id)
701 VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
702 (
703 device_id,
704 clean_device_name(name),
705 str(platform or '')[:32],
706 _sha256(secret),
707 now,
708 now,
709 ip[:64],
710 user_id,
711 ),
712 )
713 return self.get_device(device_id) or {}, (
714 f'{TOKEN_PREFIX}{device_id}_{secret}'
715 )
717 _DEVICE_COLUMNS = (
718 'd.id, d.name, d.platform, d.created_at, d.last_seen_at, '
719 "d.last_ip, d.user_id, COALESCE(u.username, '') AS username"
720 )
722 def get_device(self, device_id: str) -> Optional[dict[str, Any]]:
723 with self._connect() as conn:
724 row = conn.execute(
725 f'SELECT {self._DEVICE_COLUMNS}, d.revoked_at '
726 'FROM auth_devices d LEFT JOIN users u ON u.id = d.user_id '
727 'WHERE d.id = ?',
728 (device_id,),
729 ).fetchone()
730 return dict(row) if row else None
732 def list_devices(
733 self, user_id: Optional[int] = None
734 ) -> list[dict[str, Any]]:
735 """Paired devices - *user_id*'s, or everyone's when ``None``."""
737 where = 'd.revoked_at IS NULL'
738 args: tuple[Any, ...] = ()
739 if user_id is not None:
740 where += ' AND d.user_id = ?'
741 args = (user_id,)
742 with self._connect() as conn:
743 rows = conn.execute(
744 f'SELECT {self._DEVICE_COLUMNS} '
745 'FROM auth_devices d LEFT JOIN users u ON u.id = d.user_id '
746 f'WHERE {where} ORDER BY d.created_at DESC',
747 args,
748 ).fetchall()
749 return [dict(row) for row in rows]
751 def device_active(self, device_id: str) -> bool:
752 with self._connect() as conn:
753 row = conn.execute(
754 'SELECT 1 FROM auth_devices WHERE id = ? '
755 'AND revoked_at IS NULL',
756 (device_id,),
757 ).fetchone()
758 return row is not None
760 def verify_device_token(
761 self, token: str, ip: str = ''
762 ) -> Optional[dict[str, Any]]:
763 """The device *token* belongs to and its user, when it's valid,
764 not revoked and its user still exists (and note that it was
765 seen); else ``None``."""
767 match = _TOKEN_RE.match(token or '')
768 if not match:
769 return None
770 device_id, secret = match.groups()
771 cache_key = 'd:' + _sha256(token)
772 cached = self._signed_in.get(cache_key)
773 if cached is not None:
774 return cached
775 generation = self._signed_in.generation()
776 with self._connect() as conn:
777 row = conn.execute(
778 'SELECT d.id, d.name, d.token_hash, d.last_seen_at, '
779 'd.revoked_at, d.user_id, u.username, u.role '
780 'FROM auth_devices d LEFT JOIN users u ON u.id = d.user_id '
781 'WHERE d.id = ?',
782 (device_id,),
783 ).fetchone()
784 if row is None:
785 # Same work either way, so timing doesn't say it's unknown.
786 hmac.compare_digest(_sha256(secret), _sha256(''))
787 return None
788 if not hmac.compare_digest(row['token_hash'], _sha256(secret)):
789 return None
790 if row['revoked_at'] or row['username'] is None:
791 return None
792 now = _now()
793 seen = _parse(row['last_seen_at'])
794 if seen is None or now - seen >= DEVICE_TOUCH_INTERVAL:
795 conn.execute(
796 'UPDATE auth_devices SET last_seen_at = ?, last_ip = ? '
797 'WHERE id = ?',
798 (_iso(now), ip[:64], device_id),
799 )
800 device = {
801 'id': row['id'],
802 'name': row['name'],
803 'user_id': int(row['user_id']),
804 'username': row['username'],
805 'role': row['role'],
806 }
807 self._signed_in.put(cache_key, device, generation=generation)
808 return device
810 def rename_device(self, device_id: str, name: str) -> bool:
811 with self._connect() as conn:
812 cur = conn.execute(
813 'UPDATE auth_devices SET name = ? WHERE id = ? '
814 'AND revoked_at IS NULL',
815 (clean_device_name(name), device_id),
816 )
817 return cur.rowcount > 0
819 def revoke_device(self, device_id: str) -> bool:
820 with self._connect() as conn:
821 cur = conn.execute(
822 'UPDATE auth_devices SET revoked_at = ? WHERE id = ? '
823 'AND revoked_at IS NULL',
824 (_iso(_now()), device_id),
825 )
826 revoked = cur.rowcount > 0
827 self._signed_in.clear()
828 return revoked
830 def revoke_user(self, user_id: int, keep_session: str = '') -> list[str]:
831 """Sign *user_id* out everywhere - every paired device and every
832 browser but *keep_session*. The ids of the devices unpaired."""
834 with self._connect() as conn:
835 ids = [
836 row['id']
837 for row in conn.execute(
838 'SELECT id FROM auth_devices WHERE user_id = ? '
839 'AND revoked_at IS NULL',
840 (user_id,),
841 ).fetchall()
842 ]
843 conn.execute(
844 'UPDATE auth_devices SET revoked_at = ? WHERE user_id = ? '
845 'AND revoked_at IS NULL',
846 (_iso(_now()), user_id),
847 )
848 self.end_user_sessions(user_id, keep_session)
849 return ids
851 def revoke_everything(self) -> None:
852 """Sign every device and browser out, and void every signed URL
853 (a new signing key)."""
855 with self._lock:
856 with self._connect() as conn:
857 conn.execute(
858 'UPDATE auth_devices SET revoked_at = ? '
859 'WHERE revoked_at IS NULL',
860 (_iso(_now()),),
861 )
862 conn.execute('DELETE FROM auth_sessions')
863 self.signer.rotate()
864 self._signed_in.clear()
866 def reset(self) -> dict[str, Any]:
867 """Recovery (``python main.py auth-reset``): the admin ``admin``
868 with the default password, signed out of every browser. Paired
869 devices stay paired. The admin, as :meth:`UserStore.get` has it."""
871 admin = self.users.reset_admin()
872 self.end_user_sessions(int(admin['id']))
873 return admin
876class UrlSigner:
877 """Signs and checks URLs with the key in ``<data>/.auth_secret``.
879 *device_active* says whether the device a URL was issued to is still
880 paired, so revoking a device voids its URLs at once.
881 """
883 def __init__(
884 self, secret_path: Path, device_active: Callable[[str], bool]
885 ) -> None:
886 self._path = Path(secret_path)
887 self._device_active = device_active
888 self._secret = self._load()
890 def _load(self) -> bytes:
891 try:
892 data = self._path.read_bytes()
893 if len(data) >= 32:
894 return data
895 except OSError:
896 pass
897 return self.rotate()
899 def rotate(self) -> bytes:
900 """A new key: every URL signed so far stops working."""
902 secret = secrets.token_bytes(32)
903 self._path.parent.mkdir(parents=True, exist_ok=True)
904 fd = os.open(
905 str(self._path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600
906 )
907 with os.fdopen(fd, 'wb') as handle:
908 handle.write(secret)
909 self._secret = secret
910 return secret
912 def _signature(
913 self, method: str, path: str, params: list[tuple[str, str]]
914 ) -> str:
915 canonical = '\n'.join([
916 method.upper(),
917 path,
918 urlencode(sorted(params)),
919 ])
920 digest = hmac.new(
921 self._secret, canonical.encode(), hashlib.sha256
922 ).digest()
923 return _b64(digest)
925 def sign_url(
926 self,
927 path: str,
928 params: Iterable[tuple[str, str]] = (),
929 *,
930 device_id: str,
931 ttl: int = SIGNED_URL_DEFAULT_TTL,
932 method: str = 'GET',
933 ) -> str:
934 """*path* with its query and ``exp``/``kid``/``sig`` added."""
936 ttl = max(1, min(int(ttl), SIGNED_URL_MAX_TTL))
937 items = [(k, v) for k, v in params if k not in {'exp', 'kid', 'sig'}]
938 items += [
939 ('exp', str(int(time.time()) + ttl)),
940 ('kid', device_id),
941 ]
942 sig = self._signature(method, path, items)
943 return f'{path}?{urlencode([*items, ("sig", sig)])}'
945 def verify_signed(
946 self, method: str, path: str, query: str
947 ) -> Optional[str]:
948 """The device id a signed URL was issued to, when its signature,
949 expiry and device are all good; else ``None``. Only for reads."""
951 if method.upper() not in {'GET', 'HEAD'}:
952 return None
953 params = parse_qsl(query, keep_blank_values=True)
954 values = dict(params)
955 sig = values.get('sig', '')
956 device_id = values.get('kid', '')
957 try:
958 expires = int(values.get('exp', ''))
959 except ValueError:
960 return None
961 if not sig or not device_id or expires < time.time():
962 return None
963 items = [(k, v) for k, v in params if k != 'sig']
964 # A HEAD is checked like the GET it stands for.
965 expected = self._signature('GET', path, items)
966 if not hmac.compare_digest(sig, expected):
967 return None
968 if not self._device_active(device_id):
969 return None
970 return device_id
973# ── Which routes need what ──────────────────────────────────────────────
975_ALL = frozenset({'*'})
976_READ = frozenset({'GET', 'HEAD'})
979def _m(*methods: str) -> frozenset[str]:
980 return frozenset(methods)
983#: ``(methods, path regex, scope)``, first match wins. Paths outside the
984#: prefixes in :data:`PROTECTED_PREFIXES` are the web app's own files,
985#: public so the sign-in page can load; inside them, anything unmatched
986#: needs the admin scope.
987RULES: list[tuple[frozenset[str], re.Pattern[str], str]] = [
988 (r[0], re.compile(r[1]), r[2])
989 for r in [
990 # Public: an app checks an address, signs in or pairs.
991 (_READ, r'^/api/health$', PUBLIC),
992 (_READ, r'^/api/version$', PUBLIC),
993 (_READ, r'^/api/server/info$', PUBLIC),
994 (_READ, r'^/api/auth/status$', PUBLIC),
995 (_READ, r'^/api/auth/oidc(/callback)?$', PUBLIC),
996 (_m('POST'), r'^/api/auth/login$', PUBLIC),
997 (_m('POST'), r'^/api/auth/logout$', PUBLIC),
998 (_m('POST'), r'^/api/auth/pair$', PUBLIC),
999 (_m('POST'), r'^/api/auth/token$', PUBLIC),
1000 # The Doctor's AI helper: an assistant has no account; the
1001 # endpoint checks the helper's own key (downtify/doctor_ai.py).
1002 (_m('GET', 'POST', 'DELETE'), r'^/api/doctor/ai/mcp$', PUBLIC),
1003 # Any signed-in user: their own account, devices and pairing
1004 # (the routes check whose), and a WebSocket ticket.
1005 (_m('POST'), r'^/api/auth/ws-ticket$', CLIENT),
1006 (_READ, r'^/api/me$', CLIENT),
1007 (_ALL, r'^/api/me(/|$)', USER),
1008 (_ALL, r'^/api/auth/(devices|pairing)(/|$)', USER),
1009 # A signed-in browser (a user or an admin - paired apps stay
1010 # out): their own library rows, playlists, watches, shows and
1011 # queue jobs. Every endpoint still checks whose, so a user only
1012 # ever touches their own. These come before the admin blocks
1013 # below on purpose: first match wins.
1014 (_m('DELETE'), r'^/(delete|delete/batch)$', USER),
1015 (_ALL, r'^/api/library/playlist', USER),
1016 (_m('POST'), r'^/api/library/archive', USER),
1017 (_READ, r'^/api/library/archive/', USER),
1018 (_m('DELETE'), r'^/api/queue', USER),
1019 (_m('POST'), r'^/api/likes/clear$', USER),
1020 (_m('POST'), r'^/api/download/csv$', USER),
1021 (_m('POST'), r'^/api/playlist/m3u$', USER),
1022 (_m('POST', 'DELETE'), r'^/api/playlists/(incomplete|batches)', USER),
1023 (_m('DELETE'), r'^/api/discover/listens$', USER),
1024 (_m('POST'), r'^/api/podcasts/subscribe$', USER),
1025 (_m('PATCH', 'DELETE'), r'^/api/podcasts/shows/\d+$', USER),
1026 (_m('DELETE'), r'^/api/podcasts/episodes/\d+$', USER),
1027 (_m('POST', 'PATCH', 'DELETE'), r'^/api/monitor/playlists', USER),
1028 # Where a song came from and what each watch added (own
1029 # watches; every one for an admin).
1030 (_READ, r'^/api/monitor/(stats|provenance)$', USER),
1031 (
1032 _READ,
1033 r'^/api/monitor/playlists/\d+/(tracks|releases|releases/tracks)$',
1034 USER,
1035 ),
1036 # Artists to suggest following, from one's own listens.
1037 (_READ, r'^/api/monitor/artist-suggestions(/resolve)?$', USER),
1038 # What the artist watches still miss (own watches; every one for
1039 # an admin).
1040 (_READ, r'^/api/monitor/wanted(/job)?$', USER),
1041 (
1042 _m('POST'),
1043 r'^/api/monitor/wanted/(check-all|download-all|stop)$',
1044 USER,
1045 ),
1046 # Admin: signing everyone out, settings and credentials.
1047 (_ALL, r'^/api/auth/', ADMIN),
1048 (_ALL, r'^/api/server(/port)?$', ADMIN),
1049 (_ALL, r'^/api/settings', ADMIN),
1050 (_ALL, r'^/api/backups(/.*)?$', ADMIN),
1051 (_READ, r'^/api/fs/dirs$', ADMIN),
1052 (_ALL, r'^/api/cookies(/check)?$', ADMIN),
1053 (_ALL, r'^/api/(slskd|navidrome|deemix)/test$', ADMIN),
1054 # Why downloads didn't come from slskd (downtify/slskd_misses.py).
1055 (_ALL, r'^/api/slskd/misses$', ADMIN),
1056 (_ALL, r'^/api/proxy/test$', ADMIN),
1057 (_ALL, r'^/api/similar/test$', ADMIN),
1058 (_READ, r'^/api/library/summary$', CLIENT),
1059 (_READ, r'^/api/library/loudness$', CLIENT),
1060 (_ALL, r'^/api/library/loudness/', ADMIN),
1061 (_READ, r'^/api/library/(albums|artists)$', CLIENT),
1062 (_m('POST'), r'^/api/library/lookup$', CLIENT),
1063 (
1064 _ALL,
1065 r'^/api/library/(upgrade|reconcile|archive|replace|external'
1066 r'|visibility|usage|compilation)',
1067 ADMIN,
1068 ),
1069 (_ALL, r'^/api/library/playlist', ADMIN),
1070 (_ALL, r'^/(delete|delete/batch)$', ADMIN),
1071 (_ALL, r'^/(docs|redoc|openapi\.json)', ADMIN),
1072 # Client: what a paired app does.
1073 (_ALL, r'^/api/v1/', CLIENT),
1074 (_ALL, r'^/api/ws$', CLIENT),
1075 (
1076 _READ,
1077 r'^/(tracks|list|playlists|lyrics|cover|playlist-cover)$',
1078 CLIENT,
1079 ),
1080 (_READ, r'^/(downloads|media)/', CLIENT),
1081 (_READ, r'^/api/(songs|albums|artists)/search$', CLIENT),
1082 (_READ, r'^/api/discover/chart$', CLIENT),
1083 (_READ, r'^/api/finder/', CLIENT),
1084 (_READ, r'^/api/similar/', CLIENT),
1085 (_READ, r'^/api/artists/', CLIENT),
1086 (_m('POST'), r'^/api/artists/(art/bulk|profile/ensure)$', CLIENT),
1087 (
1088 _READ,
1089 r'^/api/(song/url|url|url/resolve|preview|stream|buy)$',
1090 CLIENT,
1091 ),
1092 (_READ, r'^/api/stream/file$', CLIENT),
1093 (_m('POST'), r'^/api/stream/prefetch$', CLIENT),
1094 (_m('POST'), r'^/api/download/(url|batch|album)$', CLIENT),
1095 (_READ, r'^/api/queue(/state)?$', CLIENT),
1096 (_READ, r'^/api/playlists/(batches|incomplete)', CLIENT),
1097 (_READ, r'^/api/likes$', CLIENT),
1098 (_m('PUT'), r'^/api/likes$', CLIENT),
1099 (
1100 _m('POST'),
1101 r'^/api/discover(/collections(/deezer|/spotify)?|/listens)?$',
1102 CLIENT,
1103 ),
1104 (_ALL, r'^/api/discover/blocked$', CLIENT),
1105 (_READ, r'^/api/podcasts/', CLIENT),
1106 (
1107 _m('POST'),
1108 r'^/api/podcasts/(resolve|episodes/\d+/download)$',
1109 CLIENT,
1110 ),
1111 (_m('PUT'), r'^/api/podcasts/episodes/\d+/playback$', CLIENT),
1112 (_m('POST'), r'^/api/activity/playback$', CLIENT),
1113 (_READ, r'^/api/monitor/playlists$', CLIENT),
1114 (_READ, r'^/api/check_update$', CLIENT),
1115 # Admin (after the client rules, which carve out exceptions):
1116 # changes to the library, the queue, watches and profiles.
1117 (_m('POST', 'PUT', 'DELETE'), r'^/api/artists/(art|profile)', ADMIN),
1118 (_m('POST'), r'^/api/download/csv$', ADMIN),
1119 (_m('POST'), r'^/api/playlist/m3u$', ADMIN),
1120 (_m('POST', 'DELETE'), r'^/api/playlists/', ADMIN),
1121 (_m('DELETE'), r'^/api/queue', ADMIN),
1122 (_m('POST'), r'^/api/queue/(pause|resume)$', ADMIN),
1123 (_m('POST'), r'^/api/likes/clear$', ADMIN),
1124 (_m('DELETE'), r'^/api/discover/listens$', ADMIN),
1125 (_m('POST', 'PATCH', 'DELETE'), r'^/api/podcasts/', ADMIN),
1126 (_m('POST', 'PATCH', 'DELETE'), r'^/api/monitor/', ADMIN),
1127 (_ALL, r'^/api/(users|activity)(/|$)', ADMIN),
1128 ]
1129]
1131#: Where the rules apply; everything else is the web app itself.
1132PROTECTED_PREFIXES = (
1133 '/api/',
1134 '/downloads/',
1135 '/media/',
1136 '/tracks',
1137 '/list',
1138 '/playlists',
1139 '/lyrics',
1140 '/cover',
1141 '/playlist-cover',
1142 '/delete',
1143 '/docs',
1144 '/redoc',
1145 '/openapi.json',
1146)
1149def classify(method: str, path: str) -> str:
1150 """The scope *method* on *path* needs: PUBLIC, CLIENT or ADMIN."""
1152 if not path.startswith(PROTECTED_PREFIXES):
1153 return PUBLIC
1154 method = method.upper()
1155 for methods, pattern, scope in RULES:
1156 if ('*' in methods or method in methods) and pattern.search(path):
1157 return scope
1158 return ADMIN
1161def rule_for(method: str, path: str) -> Optional[str]:
1162 """The explicit rule *method* on *path* matches, or ``None`` - for the
1163 test that keeps every route deliberately classified."""
1165 method = method.upper()
1166 for methods, pattern, scope in RULES:
1167 if ('*' in methods or method in methods) and pattern.search(path):
1168 return scope
1169 return None
1172# ── The middleware ──────────────────────────────────────────────────────
1174_UNSAFE = frozenset({'POST', 'PUT', 'PATCH', 'DELETE'})
1176ASGIApp = Callable[..., Awaitable[None]]
1179def _cookie(scope: MutableMapping[str, Any], name: str) -> str:
1180 raw = _header(scope, 'cookie')
1181 if not raw:
1182 return ''
1183 jar = SimpleCookie()
1184 try:
1185 jar.load(raw)
1186 except Exception:
1187 return ''
1188 morsel = jar.get(name)
1189 return morsel.value if morsel else ''
1192def _same_origin(scope: MutableMapping[str, Any], trusted: list[Any]) -> bool:
1193 """Whether the request's ``Origin`` (or ``Referer``) is this host.
1194 A request with neither (a non-browser client) passes.
1195 ``X-Forwarded-Host`` only counts from a trusted proxy."""
1197 origin = _header(scope, 'origin') or _header(scope, 'referer')
1198 if not origin:
1199 return True
1200 peer = (scope.get('client') or ('', 0))[0] or ''
1201 forwarded = (
1202 _header(scope, 'x-forwarded-host')
1203 if trusted and _in_networks(peer, trusted)
1204 else ''
1205 )
1206 host = forwarded or _header(scope, 'host')
1207 match = re.match(r'^[a-z][a-z0-9+.-]*://([^/]+)', origin, re.I)
1208 return bool(match and host and match.group(1).lower() == host.lower())
1211def identify(
1212 scope: MutableMapping[str, Any], store: AuthStore, ip: str = ''
1213) -> tuple[Optional[Principal], bool]:
1214 """``(principal, bad_token)`` from a request's device token or web
1215 session cookie - the two credentials any route may be asked with.
1216 *bad_token* is ``True`` when a device token was sent and isn't good."""
1218 auth = _header(scope, 'authorization')
1219 if auth[:7].lower() == 'bearer ':
1220 return _device_identity(
1221 store.verify_device_token(auth[7:].strip(), ip)
1222 )
1223 session = _cookie(scope, SESSION_COOKIE)
1224 return _session_identity(store.session_user(session) if session else None)
1227async def identify_offloop(
1228 scope: MutableMapping[str, Any], store: AuthStore, ip: str = ''
1229) -> tuple[Optional[Principal], bool]:
1230 """:func:`identify` for the event loop. A credential in the sign-in
1231 cache is answered in place; a miss does its database read on a
1232 worker thread, so a slow database never stalls other requests."""
1234 auth = _header(scope, 'authorization')
1235 if auth[:7].lower() == 'bearer ':
1236 token = auth[7:].strip()
1237 device = store.peek_device(token)
1238 if device is MISS:
1239 device = await asyncio.to_thread(
1240 store.verify_device_token, token, ip
1241 )
1242 return _device_identity(device)
1243 session = _cookie(scope, SESSION_COOKIE)
1244 user = store.peek_session(session)
1245 if user is MISS:
1246 user = await asyncio.to_thread(store.session_user, session)
1247 return _session_identity(user)
1250def _device_identity(
1251 device: Optional[dict[str, Any]],
1252) -> tuple[Optional[Principal], bool]:
1253 if device is None:
1254 return None, True
1255 return (
1256 Principal(
1257 'device',
1258 CLIENT,
1259 device['id'],
1260 device['user_id'],
1261 device['username'],
1262 device['role'],
1263 ),
1264 False,
1265 )
1268def _session_identity(
1269 user: Optional[dict[str, Any]],
1270) -> tuple[Optional[Principal], bool]:
1271 if user is None:
1272 return None, False
1273 return (
1274 Principal(
1275 'session',
1276 ADMIN if user['role'] == ROLE_ADMIN else USER,
1277 '',
1278 user['id'],
1279 user['username'],
1280 user['role'],
1281 ),
1282 False,
1283 )
1286def open_principal(store: AuthStore) -> Optional[Principal]:
1287 """Who a request without credentials is when sign-in is turned off
1288 (``DOWNTIFY_DISABLE_AUTH``): the first admin. ``None`` otherwise."""
1290 if not store.auth_disabled:
1291 return None
1292 admin = store.users.first_admin()
1293 if admin is None:
1294 return None
1295 return Principal(
1296 'open', ADMIN, '', admin['id'], admin['username'], ROLE_ADMIN
1297 )
1300def auth_disabled_from_env() -> bool:
1301 """``DOWNTIFY_DISABLE_AUTH``: ``true`` turns accounts and sign-in off."""
1303 raw = os.getenv('DOWNTIFY_DISABLE_AUTH', '').strip().lower()
1304 return raw in {'1', 'true', 'yes', 'on'}
1307def session_cookie(scope: MutableMapping[str, Any]) -> str:
1308 """The web session cookie a request carries, or ``''``."""
1310 return _cookie(scope, SESSION_COOKIE)
1313class AuthMiddleware:
1314 """Enforces :data:`RULES` for HTTP and WebSocket requests.
1316 Whoever is recognised - a web session, a device token, a signed URL
1317 or a WebSocket ticket - is put in ``scope['state']['principal']``
1318 for the routes that need to know (e.g. the WebSocket, to close a
1319 revoked device's socket).
1321 A request that sends a revoked device token is told so (401) even on
1322 a route anyone may use, so an app learns it was unpaired.
1323 """
1325 def __init__(
1326 self,
1327 app: ASGIApp,
1328 *,
1329 get_store: Callable[[], Optional[AuthStore]],
1330 get_tickets: Callable[[], Optional[TicketStore]],
1331 trusted_proxies: Optional[list[Any]] = None,
1332 ) -> None:
1333 self.app = app
1334 self._get_store = get_store
1335 self._get_tickets = get_tickets
1336 self._trusted = (
1337 trusted_proxies
1338 if trusted_proxies is not None
1339 else trusted_proxies_from_env()
1340 )
1342 async def __call__(
1343 self,
1344 scope: MutableMapping[str, Any],
1345 receive: Callable[..., Awaitable[Any]],
1346 send: Callable[..., Awaitable[None]],
1347 ) -> None:
1348 kind = scope.get('type')
1349 if kind not in {'http', 'websocket'}:
1350 await self.app(scope, receive, send)
1351 return
1353 store = self._get_store()
1355 if store is None:
1356 await self._deny(
1357 scope, send, 503, 'Authentication service unavailable'
1358 )
1359 return
1361 method = 'WS' if kind == 'websocket' else scope.get('method', 'GET')
1362 path = scope.get('path', '')
1363 needed = (
1364 classify('GET', path)
1365 if kind == 'websocket'
1366 else classify(method, path)
1367 )
1368 if needed == PUBLIC:
1369 await self.app(scope, receive, send)
1370 return
1372 ip = client_ip(scope, self._trusted)
1373 principal, bad_token = await self._authenticate(
1374 scope, store, ip, method
1375 )
1376 if principal is None and not bad_token and store.auth_disabled:
1377 principal = await asyncio.to_thread(open_principal, store)
1378 scope.setdefault('state', {})['principal'] = principal
1380 if bad_token:
1381 await self._deny(scope, send, 401, 'Invalid or revoked token')
1382 return
1383 if principal is None:
1384 await self._deny(scope, send, 401, 'Sign in required')
1385 return
1386 if not allows(principal.scope, needed):
1387 detail = (
1388 'This needs an admin'
1389 if principal.kind == 'session'
1390 else 'This needs a signed-in browser'
1391 )
1392 await self._deny(scope, send, 403, detail)
1393 return
1394 # A cookie is sent by the browser on its own, to any site that
1395 # asks: only this site's own pages may use it to change things.
1396 if (
1397 principal is not None
1398 and principal.kind in {'session', 'open'}
1399 and (method in _UNSAFE or kind == 'websocket')
1400 and not _same_origin(scope, self._trusted)
1401 ):
1402 await self._deny(scope, send, 403, 'Cross-site request refused')
1403 return
1404 await self.app(scope, receive, send)
1406 async def _authenticate(
1407 self,
1408 scope: MutableMapping[str, Any],
1409 store: AuthStore,
1410 ip: str,
1411 method: str,
1412 ) -> tuple[Optional[Principal], bool]:
1413 """``(principal, bad_token)``: who made the request, and whether
1414 it sent a device token that's no good. Database reads run on a
1415 worker thread (see :func:`identify_offloop`)."""
1417 principal, bad_token = await identify_offloop(scope, store, ip)
1418 if principal is not None or bad_token:
1419 return principal, bad_token
1421 query = (scope.get('query_string') or b'').decode('latin-1')
1422 if 'sig=' in query and method in {'GET', 'HEAD'}:
1423 device_id = await asyncio.to_thread(
1424 store.signer.verify_signed, method, scope['path'], query
1425 )
1426 if device_id:
1427 return Principal('signed', CLIENT, device_id), False
1428 if 'ticket=' in query and scope.get('type') == 'websocket':
1429 tickets = self._get_tickets()
1430 ticket = dict(parse_qsl(query)).get('ticket', '')
1431 principal = tickets.claim(ticket) if tickets else None
1432 if principal is not None and (
1433 not principal.device_id
1434 or await asyncio.to_thread(
1435 store.device_active, principal.device_id
1436 )
1437 ):
1438 return principal, False
1439 return None, False
1441 @staticmethod
1442 async def _deny(
1443 scope: MutableMapping[str, Any],
1444 send: Callable[..., Awaitable[None]],
1445 status: int,
1446 detail: str,
1447 ) -> None:
1448 if scope.get('type') == 'websocket':
1449 # Before accept(), a close is answered with HTTP 403.
1450 await send({'type': 'websocket.close', 'code': 4401})
1451 return
1452 body = json.dumps({'detail': detail}).encode()
1453 headers = [
1454 (b'content-type', b'application/json'),
1455 (b'content-length', str(len(body)).encode()),
1456 (b'cache-control', b'no-store'),
1457 ]
1458 if status == 401:
1459 headers.append((b'www-authenticate', b'Bearer realm="Downtify"'))
1460 await send({
1461 'type': 'http.response.start',
1462 'status': status,
1463 'headers': headers,
1464 })
1465 await send({'type': 'http.response.body', 'body': body})