Files
mtusi2026lab5/app/security.py
T

72 lines
2.0 KiB
Python

"""Пароли (Argon2id), токены, разбор заголовка Authorization."""
import base64
import binascii
import hashlib
import re
import secrets
import threading
from argon2 import PasswordHasher, Type
from argon2.exceptions import InvalidHashError, VerificationError
from . import config
_hasher = PasswordHasher(time_cost=config.ARGON2_TIME_COST, memory_cost=config.ARGON2_MEMORY_KIB,
parallelism=1, hash_len=32, salt_len=16, type=Type.ID)
_DUMMY_HASH = _hasher.hash("dummy-password-for-constant-time")
_hash_slots = threading.BoundedSemaphore(config.HASH_CONCURRENCY)
_TOKEN_RE = re.compile(r"[A-Za-z0-9._~+/=-]{16,512}")
def hash_password(password):
with _hash_slots:
return _hasher.hash(password)
def verify_password(stored_hash, password):
with _hash_slots:
try:
_hasher.verify(stored_hash, password)
except (VerificationError, InvalidHashError):
return False, None
return True, (_hasher.hash(password) if _hasher.check_needs_rehash(stored_hash) else None)
def burn_verify(password):
with _hash_slots:
try:
_hasher.verify(_DUMMY_HASH, password)
except VerificationError:
pass
def new_token():
return secrets.token_urlsafe(32)
def token_hash(token):
return hashlib.sha256(token.encode("ascii")).digest()
def parse_basic(header):
if not header:
return None
scheme, _, rest = header.partition(" ")
if scheme.lower() != "basic":
return None
try:
text = base64.b64decode(rest.strip(), validate=True).decode("utf-8")
except (binascii.Error, UnicodeDecodeError, ValueError):
return None
username, sep, password = text.partition(":")
return (username, password) if sep else None
def parse_bearer(header):
if not header:
return None
scheme, _, rest = header.partition(" ")
token = rest.strip()
if scheme.lower() != "bearer" or not _TOKEN_RE.fullmatch(token):
return None
return token