121 lines
3.7 KiB
Python
121 lines
3.7 KiB
Python
import base64
|
|
import binascii
|
|
import hashlib
|
|
import re
|
|
import secrets
|
|
import threading
|
|
|
|
from argon2 import PasswordHasher
|
|
from argon2.exceptions import InvalidHashError, VerificationError
|
|
import psycopg
|
|
|
|
from cache import REVOKED, cache
|
|
from config import settings
|
|
from db import iso
|
|
from errors import BASIC_CHALLENGE, BEARER_CHALLENGE, unauthorized
|
|
import store
|
|
|
|
REVOCATION_MARGIN_SECONDS = 5
|
|
|
|
USERNAME = re.compile(r'^[a-z0-9_]{3,32}$')
|
|
|
|
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
|
hashing = threading.BoundedSemaphore(settings.password_hash_concurrency)
|
|
DUMMY_HASH = hasher.hash('dummy-password-for-equal-timing')
|
|
|
|
|
|
def hash_password(password):
|
|
with hashing:
|
|
return hasher.hash(password)
|
|
|
|
|
|
def verify_password(password_hash, password):
|
|
try:
|
|
with hashing:
|
|
return hasher.verify(password_hash, password)
|
|
except (VerificationError, InvalidHashError):
|
|
return False
|
|
|
|
|
|
def token_hash(token):
|
|
return hashlib.sha256(token.encode('ascii')).digest()
|
|
|
|
|
|
def parse_credentials(header, scheme):
|
|
name, _, value = (header or '').strip().partition(' ')
|
|
value = value.strip()
|
|
if name.lower() != scheme or not value or ' ' in value:
|
|
return None
|
|
return value
|
|
|
|
|
|
def parse_basic(header):
|
|
value = parse_credentials(header, 'basic')
|
|
if value is None:
|
|
return None
|
|
try:
|
|
decoded = base64.b64decode(value, validate=True).decode('utf-8')
|
|
except (binascii.Error, UnicodeDecodeError):
|
|
return None
|
|
username, separator, password = decoded.partition(':')
|
|
if not separator or not USERNAME.match(username) or not 12 <= len(password) <= 128:
|
|
return None
|
|
return username, password
|
|
|
|
|
|
def login(header):
|
|
credentials = parse_basic(header)
|
|
row = store.find_credentials(credentials[0]) if credentials else None
|
|
if row is None:
|
|
verify_password(DUMMY_HASH, credentials[1] if credentials else 'x' * 12)
|
|
raise unauthorized(BASIC_CHALLENGE, 'Неверное имя пользователя или пароль')
|
|
if not verify_password(row['password_hash'], credentials[1]):
|
|
raise unauthorized(BASIC_CHALLENGE, 'Неверное имя пользователя или пароль')
|
|
token = secrets.token_urlsafe(32)
|
|
digest = token_hash(token)
|
|
expires_at = store.create_session(row['id'], digest, settings.session_ttl)
|
|
user = store.user_out(row)
|
|
cache.put(digest, user, expires_at)
|
|
return {'token': token, 'token_type': 'Bearer', 'expires_at': iso(expires_at), 'user': user}
|
|
|
|
|
|
def authenticate(header):
|
|
token = parse_credentials(header, 'bearer')
|
|
if token is None or not token.isascii():
|
|
raise unauthorized(BEARER_CHALLENGE)
|
|
digest = token_hash(token)
|
|
if cache.client is not None and not cache.trusted():
|
|
sync_revocations()
|
|
user = cache.get(digest)
|
|
if user == REVOKED:
|
|
raise unauthorized(BEARER_CHALLENGE)
|
|
if user is None:
|
|
row = store.session_user(digest)
|
|
if row is None:
|
|
raise unauthorized(BEARER_CHALLENGE)
|
|
user = store.user_out(row)
|
|
cache.put(digest, user, row['expires_at'])
|
|
return {'user': user, 'token_hash': digest}
|
|
|
|
|
|
def sync_revocations():
|
|
errors_before = cache.errors
|
|
pending = store.pending_revocations()
|
|
if not cache.revoke_all(pending):
|
|
return
|
|
if pending:
|
|
try:
|
|
store.clear_revocations(pending)
|
|
except psycopg.Error:
|
|
pass
|
|
cache.mark_synced(errors_before)
|
|
|
|
|
|
def logout(session):
|
|
store.revoke_session(session['token_hash'], cache.max_ttl + REVOCATION_MARGIN_SECONDS)
|
|
if cache.revoke(session['token_hash']):
|
|
try:
|
|
store.clear_revocations([session['token_hash']])
|
|
except psycopg.Error:
|
|
pass
|