"""Parsing of the Authorization header. Any malformed value is 401, never 500. Basic (RFC 7617) is accepted only by POST /auth/sessions; everything else needs Bearer. Basic is an encoding, not encryption: plain HTTP is acceptable only for the local synthetic lab stand (lab 7 adds TLS). """ from __future__ import annotations import base64 import binascii import re from .errors import BASIC_CHALLENGE, BEARER_CHALLENGE, Unauthorized from .validation import USERNAME_RE B64_RE = re.compile(r"[A-Za-z0-9+/]+={0,2}") TOKEN_RE = re.compile(r"[A-Za-z0-9_-]{32,128}") # token_urlsafe(32) gives 43 characters def _split(header: str | None) -> tuple[str, str]: if not header: return "", "" scheme, _, value = header.strip().partition(" ") return scheme.lower(), value.strip() def parse_basic(header: str | None) -> tuple[str, str]: """(username, password) from `Basic base64(username:password)`; the password may contain ':'.""" invalid = Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE) scheme, value = _split(header) if scheme != "basic" or B64_RE.fullmatch(value) is None or len(value) > 1024: raise invalid try: decoded = base64.b64decode(value, validate=True).decode("utf-8") except (binascii.Error, ValueError, UnicodeDecodeError): raise invalid from None username, sep, password = decoded.partition(":") # split at the FIRST colon if not sep or USERNAME_RE.fullmatch(username) is None or not password: raise invalid return username, password def parse_bearer(header: str | None) -> str: scheme, value = _split(header) if scheme != "bearer" or TOKEN_RE.fullmatch(value) is None: # Missing header, Basic on a business endpoint, garbage token: one answer. raise Unauthorized("Требуется действительная Bearer-сессия", challenge=BEARER_CHALLENGE) return value