from __future__ import annotations from base64 import urlsafe_b64encode from datetime import datetime, timedelta, timezone import hashlib import json import logging import secrets from typing import Any from fastapi import HTTPException, Request, Response from fastapi.responses import JSONResponse from sqlalchemy import select from sqlalchemy.orm import Session from webauthn import ( base64url_to_bytes, generate_authentication_options, generate_registration_options, options_to_json, verify_authentication_response, verify_registration_response, ) from webauthn.helpers.structs import ( AuthenticatorAttachment, AuthenticatorSelectionCriteria, PublicKeyCredentialDescriptor, ResidentKeyRequirement, UserVerificationRequirement, ) import httpx from app.config import Settings from app.database import SessionLocal from app.models import AuthChallenge, AuthSession, PasskeyCredential SESSION_COOKIE = "dzen_session" CHALLENGE_TTL_SECONDS = 300 ADMIN_USER_ID = b"dzen-assistant-admin" logger = logging.getLogger(__name__) def utc_now() -> datetime: return datetime.now(timezone.utc) def as_utc(value: datetime) -> datetime: return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value def b64(value: bytes) -> str: return urlsafe_b64encode(value).rstrip(b"=").decode("ascii") def token_hash(token: str) -> str: return hashlib.sha256(token.encode("utf-8")).hexdigest() def create_challenge(session: Session, kind: str, challenge: bytes) -> str: token = secrets.token_urlsafe(32) session.add( AuthChallenge( token_hash=token_hash(token), challenge=b64(challenge), kind=kind, expires_at=utc_now() + timedelta(seconds=CHALLENGE_TTL_SECONDS), ) ) session.commit() return token def consume_challenge(session: Session, token: str, kind: str) -> bytes: record = session.scalar( select(AuthChallenge).where( AuthChallenge.token_hash == token_hash(token), AuthChallenge.kind == kind, ) ) if not record or as_utc(record.expires_at) <= utc_now(): if record: session.delete(record) session.commit() raise HTTPException(status_code=422, detail="Срок действия запроса авторизации истёк.") challenge = base64url_to_bytes(record.challenge) session.delete(record) session.commit() return challenge def session_cookie(response: Response, settings: Settings) -> None: token = secrets.token_urlsafe(48) with SessionLocal() as session: session.add( AuthSession( token_hash=token_hash(token), expires_at=utc_now() + timedelta(seconds=settings.auth_session_ttl_seconds), ) ) session.commit() response.set_cookie( SESSION_COOKIE, token, max_age=settings.auth_session_ttl_seconds, httponly=True, secure=True, samesite="lax", path="/", ) def clear_session(response: Response, request: Request) -> None: token = request.cookies.get(SESSION_COOKIE) if token: with SessionLocal() as session: record = session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash(token))) if record: session.delete(record) session.commit() response.delete_cookie(SESSION_COOKIE, path="/") def has_valid_session(token: str | None) -> bool: if not token: return False with SessionLocal() as session: record = session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash(token))) if not record: return False if as_utc(record.expires_at) <= utc_now(): session.delete(record) session.commit() return False return True def require_session(request: Request) -> None: if not has_valid_session(request.cookies.get(SESSION_COOKIE)): raise HTTPException(status_code=401, detail="Сначала войдите через VK ID.") async def verify_vk_access_token(access_token: str, settings: Settings) -> None: if not access_token.strip(): raise HTTPException(status_code=422, detail="VK ID не вернул access token.") try: async with httpx.AsyncClient(timeout=15) as client: response = await client.post( settings.vk_id_user_info_url, params={"client_id": settings.vk_id_app_id}, data={"access_token": access_token.strip()}, ) response.raise_for_status() payload = response.json() except (httpx.HTTPError, ValueError) as exc: raise HTTPException(status_code=401, detail="Не удалось проверить VK ID.") from exc if payload.get("error"): logger.warning("VK ID user info returned error=%s", payload.get("error")) raise HTTPException(status_code=401, detail="VK ID не подтвердил access token.") nested_user = payload.get("user") if isinstance(payload.get("user"), dict) else {} candidate_ids = ( payload.get("user_id"), payload.get("id"), payload.get("sub"), nested_user.get("user_id"), nested_user.get("id"), ) logger.warning( "VK ID user info fields=%s candidate_ids=%s allowed_user_id=%s", sorted(payload.keys()), [candidate for candidate in candidate_ids if candidate is not None], settings.vk_id_allowed_user_id, ) valid_user_id = any( isinstance(candidate, (int, str)) and str(candidate).isdigit() and int(candidate) == settings.vk_id_allowed_user_id for candidate in candidate_ids ) if not valid_user_id: raise HTTPException(status_code=403, detail="Этот VK ID не имеет доступа к Дзен-ассистенту.") def credential_id_from_payload(credential: dict[str, Any]) -> bytes: raw_id = credential.get("rawId") or credential.get("id") if not isinstance(raw_id, str) or not raw_id: raise HTTPException(status_code=422, detail="WebAuthn не вернул идентификатор устройства.") try: return base64url_to_bytes(raw_id) except Exception as exc: raise HTTPException(status_code=422, detail="Некорректный идентификатор passkey.") from exc def registration_options(session: Session, settings: Settings) -> dict[str, Any]: existing = [ PublicKeyCredentialDescriptor(id=base64url_to_bytes(item.credential_id)) for item in session.scalars(select(PasskeyCredential)).all() ] options = generate_registration_options( rp_id=settings.webauthn_rp_id, rp_name=settings.webauthn_rp_name, user_id=ADMIN_USER_ID, user_name="admin@nstarikov.ru", user_display_name="Администратор Дзен-ассистента", exclude_credentials=existing, authenticator_selection=AuthenticatorSelectionCriteria( authenticator_attachment=AuthenticatorAttachment.PLATFORM, resident_key=ResidentKeyRequirement.PREFERRED, user_verification=UserVerificationRequirement.REQUIRED, ), ) token = create_challenge(session, "registration", options.challenge) return {"challengeId": token, "options": json.loads(options_to_json(options))} def verify_registration( session: Session, settings: Settings, challenge_id: str, credential: dict[str, Any], ) -> None: challenge = consume_challenge(session, challenge_id, "registration") try: verified = verify_registration_response( credential=credential, expected_challenge=challenge, expected_rp_id=settings.webauthn_rp_id, expected_origin=settings.webauthn_origin, require_user_verification=True, ) except Exception as exc: raise HTTPException(status_code=422, detail=f"Не удалось зарегистрировать устройство: {exc}") from exc session.add( PasskeyCredential( credential_id=b64(verified.credential_id), public_key=b64(verified.credential_public_key), sign_count=verified.sign_count, label="Устройство администратора", ) ) session.commit() def authentication_options(session: Session, settings: Settings) -> dict[str, Any]: credentials = [ PublicKeyCredentialDescriptor(id=base64url_to_bytes(item.credential_id)) for item in session.scalars(select(PasskeyCredential)).all() ] options = generate_authentication_options( rp_id=settings.webauthn_rp_id, allow_credentials=credentials, user_verification=UserVerificationRequirement.REQUIRED, ) token = create_challenge(session, "authentication", options.challenge) return {"challengeId": token, "options": json.loads(options_to_json(options))} def verify_authentication( session: Session, settings: Settings, challenge_id: str, credential: dict[str, Any], ) -> None: challenge = consume_challenge(session, challenge_id, "authentication") credential_id = credential_id_from_payload(credential) record = session.scalar(select(PasskeyCredential).where(PasskeyCredential.credential_id == b64(credential_id))) if not record: raise HTTPException(status_code=401, detail="Это устройство не зарегистрировано.") try: verified = verify_authentication_response( credential=credential, expected_challenge=challenge, expected_rp_id=settings.webauthn_rp_id, expected_origin=settings.webauthn_origin, credential_public_key=base64url_to_bytes(record.public_key), credential_current_sign_count=record.sign_count, require_user_verification=True, ) except Exception as exc: raise HTTPException(status_code=401, detail=f"Не удалось подтвердить passkey: {exc}") from exc record.sign_count = verified.new_sign_count record.last_used_at = utc_now() session.commit() def auth_status() -> bool: return True class AuthMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): path = scope.get("path", "") protected = path.startswith("/api/") and not path.startswith("/api/auth/") if not protected: await self.app(scope, receive, send) return headers = dict(scope.get("headers", [])) cookie_header = headers.get(b"cookie", b"").decode("latin-1") token = next((part.strip().split("=", 1)[1] for part in cookie_header.split(";") if part.strip().startswith(f"{SESSION_COOKIE}=")), None) if has_valid_session(token): await self.app(scope, receive, send) return if scope["type"] == "websocket": await send({"type": "websocket.close", "code": 4401}) return response = JSONResponse({"detail": "Требуется вход по passkey."}, status_code=401) await response(scope, receive, send)