forked from mtusi2026/mtusi2026lab5
Скопировано из mtusi2026lab4 (ветка solution/bvt2302-bodanyuk, commit 17c33cd) через git archive: исходники, миграции, собственные тесты, Dockerfile, compose, конфигурации infra/, скрипты и bench/. README, COURSE, contracts/, tests/ и отчёт lab4 не копировались. Makefile и .env.example — версии lab4 (skeleton-часть совпадает с lab5, строки broker добавляются в следующих коммитах). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
49 lines
1.9 KiB
Python
49 lines
1.9 KiB
Python
"""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
|