"""docker compose exec -T api python < tests/callbacks.py.""" import asyncio import base64 import json from uuid import uuid4 from urllib.error import HTTPError from urllib.request import Request, urlopen from unittest.mock import patch from pydantic import SecretStr from sqlalchemy import delete, func, select from sqlalchemy.ext.asyncio import async_sessionmaker from src.api.v1.routers.auth.callback import create_admin from src.core.db.models import User from src.core.db.session import create_engine from src.core.settings import settings from src.service.exceptions import UserAlreadyExistsException from src.service.user import UserService def call(method, path, expected, headers=None, body=None): data = None if body is None else json.dumps(body).encode() request_headers = dict(headers or {}) if body is not None: request_headers['Content-Type'] = 'application/json' request = Request(f'http://127.0.0.1:{settings.app_port}' + path, method=method, headers=request_headers, data=data) try: response = urlopen(request, timeout=10) except HTTPError as error: response = error with response: assert response.status == expected, response.status return json.load(response) if response.status != 204 else None async def main(): engine = create_engine() factory = async_sessionmaker(engine, expire_on_commit=False) try: async with factory() as session: admin = await session.scalar(select(User).where(User.username == settings.admin_username)) assert admin is not None and admin.is_admin identity = (admin.id, admin.password_hash, admin.created_at) await asyncio.gather(create_admin(factory), create_admin(factory)) async with factory() as session: admin = await session.scalar(select(User).where(User.username == settings.admin_username)) assert (admin.id, admin.password_hash, admin.created_at) == identity assert await session.scalar(select(func.count()).select_from(User).where( User.username == settings.admin_username, )) == 1 print('PASS: стартовый администратор создан; повторные callbacks не дублируют и не меняют пароль') with patch.object(settings, 'app_env', 'production'), patch.object( settings, 'admin_password', SecretStr('different-production-password-123') ): try: await create_admin(factory) except RuntimeError: pass else: raise AssertionError('Production запущен с несовпадающим паролем в БД') print('PASS: production не принимает старый пароль администратора при изменённой конфигурации') credential = base64.b64encode((settings.admin_username + ':' + settings.admin_password.get_secret_value()).encode()).decode() result = call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}) bearer = {'Authorization': 'Bearer ' + result['token']} me = call('GET', '/api/v1/users/me', 200, bearer) assert me['id'] == str(identity[0]) call('DELETE', '/api/v1/auth/sessions/current', 204, bearer) print('PASS: администратор входит через Basic, читает профиль через Bearer и выходит') username = 'seed_test_' + uuid4().hex[:12] password = 'valid-password-for-seed-test' normal = call('POST', '/api/v1/users', 201, body={ 'username': username, 'display_name': 'Обычный пользователь', 'password': password, }) try: try: async with factory.begin() as session: await UserService(session).create_admin( username=username, display_name='Администратор', password=password, ) except UserAlreadyExistsException: pass else: raise AssertionError('Обычный пользователь стал администратором') async with factory() as session: assert not await session.scalar(select(User.is_admin).where(User.username == username)) finally: from uuid import UUID async with factory.begin() as session: await session.execute(delete(User).where(User.id == UUID(normal['id']))) print('PASS: callback не повышает права обычного пользователя с совпавшим username') base = {'username': 'constraints_' + uuid4().hex[:12], 'display_name': 'Проверка', 'password': password} call('POST', '/api/v1/users', 400, body={**base, 'username': 'user@example.com'}) call('POST', '/api/v1/users', 400, body={**base, 'password': 'admin'}) call('POST', '/api/v1/users', 400, body={**base, 'is_admin': True}) print('PASS: ограничения username/password сохранены; is_admin нельзя передать при регистрации') finally: await engine.dispose() asyncio.run(main())