forked from mtusi2026/mtusi2026lab3
готово
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
"""Проверка русских событий авторизации и отсутствия секретов в логах Compose."""
|
||||
import subprocess
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Проверка логов авторизации')
|
||||
started = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
actor = client.user('auth_logs')
|
||||
username = actor['registration']['username']
|
||||
wrong_password = 'wrong-password-for-logging'
|
||||
client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + base64.b64encode((username + ':' + wrong_password).encode()).decode()})
|
||||
missing_username = 'missing_' + actor['id'].replace('-', '')[:12]
|
||||
client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + base64.b64encode((missing_username + ':' + wrong_password).encode()).decode()})
|
||||
client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
||||
client.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
result = subprocess.run(
|
||||
['docker', 'compose', 'logs', '--no-color', '--since', started, 'api'],
|
||||
cwd=Path(__file__).resolve().parents[1], check=True, capture_output=True, text=True,
|
||||
)
|
||||
logs = result.stdout + result.stderr
|
||||
check('src.service.auth' in logs, 'Не используется обычный логгер модуля')
|
||||
for message in ('Сессия создана', 'Вход отклонён', 'Сессия завершена', 'Доступ отклонён'):
|
||||
check(message in logs, 'В логах отсутствует событие авторизации')
|
||||
for secret in (actor['token'], actor['registration']['password'], wrong_password):
|
||||
check(secret not in logs, 'В логах обнаружены credentials')
|
||||
print('PASS: русские события входа/отказа/logout; пароли и токены не попали в логи')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,107 @@
|
||||
"""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())
|
||||
@@ -0,0 +1,87 @@
|
||||
"""docker compose exec -T api python < tests/database.py."""
|
||||
import asyncio
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import Column, MetaData, String, Table, func, insert, select, text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from src.core.db.models import Chat, ChatMember, Message, User
|
||||
from src.core.db.repo.chat import create_chat
|
||||
from src.core.db.repo.message import history_query
|
||||
from src.core.db.session import create_engine
|
||||
|
||||
|
||||
async def main():
|
||||
engine = create_engine()
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
try:
|
||||
async def counts():
|
||||
async with factory() as session:
|
||||
return [await session.scalar(select(func.count()).select_from(model))
|
||||
for model in (User, Chat, ChatMember, Message)]
|
||||
|
||||
before = await counts()
|
||||
for _ in range(2):
|
||||
subprocess.run([sys.executable, '-m', 'alembic', 'upgrade', 'head'], check=True)
|
||||
assert before == await counts(), 'Повтор миграций изменил данные'
|
||||
versions = Table('alembic_version', MetaData(), Column('version_num', String(32), primary_key=True))
|
||||
async with factory() as session:
|
||||
assert (await session.scalars(select(versions.c.version_num))).all() == ['006']
|
||||
print('PASS: два повторных запуска миграций не изменили данные; версия 006 одна')
|
||||
|
||||
user_id, chat_id = uuid4(), uuid4()
|
||||
now = datetime.now(timezone.utc)
|
||||
try:
|
||||
async with factory.begin() as session:
|
||||
await create_chat(session, chat_id, 'rollback', [user_id], now)
|
||||
except IntegrityError as error:
|
||||
assert getattr(error.orig, 'sqlstate', None) == '23503'
|
||||
else:
|
||||
raise AssertionError('Ожидался отказ внешнего ключа')
|
||||
async with factory() as session:
|
||||
assert await session.get(Chat, chat_id) is None
|
||||
assert await session.scalar(
|
||||
select(func.count()).select_from(ChatMember).where(ChatMember.chat_id == chat_id)
|
||||
) == 0
|
||||
print('PASS: ошибка участника откатила INSERT чата и участников')
|
||||
|
||||
async with factory() as session:
|
||||
try:
|
||||
session.add(User(id=user_id, username='plan_' + uuid4().hex[:16],
|
||||
display_name='EXPLAIN', password_hash='test-not-for-login', created_at=now))
|
||||
await session.flush()
|
||||
await create_chat(session, chat_id, 'EXPLAIN', [user_id], now)
|
||||
await session.execute(insert(Message), [
|
||||
dict(id=uuid4(), chat_id=chat_id, sender_id=user_id, text=f'message {n}',
|
||||
created_at=now + timedelta(milliseconds=n)) for n in range(1, 10001)
|
||||
])
|
||||
# ANALYZE и EXPLAIN — диагностические команды PostgreSQL, не запросы репозитория.
|
||||
await session.execute(text('ANALYZE messages'))
|
||||
count = await session.scalar(
|
||||
select(func.count()).select_from(Message).where(Message.chat_id == chat_id)
|
||||
)
|
||||
print('Сообщений в исследуемом чате:', count)
|
||||
after = (await session.execute(
|
||||
select(Message.created_at, Message.id).where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id).offset(8999).limit(1)
|
||||
)).one()
|
||||
# Исследуется именно выражение SQLAlchemy, используемое в репозитории.
|
||||
compiled = history_query(chat_id, 51, tuple(after)).compile(
|
||||
dialect=engine.dialect, compile_kwargs={'literal_binds': True},
|
||||
)
|
||||
rows = await session.execute(text('EXPLAIN (ANALYZE, BUFFERS) ' + str(compiled)))
|
||||
plan = '\n'.join(row[0] for row in rows)
|
||||
assert 'messages_history_idx' in plan, plan
|
||||
print(plan)
|
||||
print('PASS: индекс истории используется для глубокой страницы из 10000 сообщений')
|
||||
finally:
|
||||
await session.rollback()
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Проверка отказов только локального Compose-стенда; сервисы восстанавливаются."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, Failure, arguments, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(
|
||||
["docker", "compose", *args], cwd=ROOT, check=True, stdout=subprocess.DEVNULL, timeout=60
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Отказы Redis и PostgreSQL")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
actor = c.user("outage")
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
key = "user:v1:" + actor["id"]
|
||||
|
||||
def redis(*args):
|
||||
return subprocess.check_output(
|
||||
["docker", "compose", "exec", "-T", "redis", "redis-cli", "--raw", *args],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
timeout=10,
|
||||
).strip()
|
||||
|
||||
assert redis("EXISTS", key) == "1", "Профиль не попал в Redis"
|
||||
assert 0 < int(redis("TTL", key)) <= 60
|
||||
|
||||
def hits():
|
||||
return int(
|
||||
next(
|
||||
line.split(":")[1]
|
||||
for line in redis("INFO", "stats").splitlines()
|
||||
if line.startswith("keyspace_hits:")
|
||||
)
|
||||
)
|
||||
|
||||
before = hits()
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
assert hits() > before, "Повторное чтение не использовало Redis"
|
||||
redis("DEL", key)
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
assert redis("EXISTS", key) == "1", "Кэш не восстановился из PostgreSQL"
|
||||
token_key = "session:v1:" + hashlib.sha256(actor["token"].encode()).hexdigest()
|
||||
assert redis("EXISTS", token_key) == "1", "Сессия отсутствует в Redis"
|
||||
ttl_before = int(redis("PTTL", token_key))
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
assert 0 < int(redis("PTTL", token_key)) <= ttl_before, "Чтение продлило сессию"
|
||||
print("PASS: сессия хранится в Redis с TTL; чтение не продлевает срок")
|
||||
print(
|
||||
"PASS: профиль кэшируется с TTL<=60; повторный GET даёт cache hit; потеря ключа восполняется"
|
||||
)
|
||||
lost = c.user("lost")
|
||||
c.call("GET", "/api/v1/users/me", actor=lost, schema="User")
|
||||
lost_key = "session:v1:" + hashlib.sha256(lost["token"].encode()).hexdigest()
|
||||
redis("DEL", lost_key)
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=lost)
|
||||
assert redis("EXISTS", lost_key) == "0", "Удалённая сессия воскресла"
|
||||
print("PASS: отсутствующая сессия не восстанавливается из профиля/БД; Redis — источник истины")
|
||||
# При общей неисправности LB исключает все API. Проверку отдельного
|
||||
# процесса выполняем из контейнера; внешние API-порты не открываем.
|
||||
container = subprocess.check_output(
|
||||
["docker", "compose", "ps", "-q", "api"], cwd=ROOT, text=True
|
||||
).split()[0]
|
||||
|
||||
def probe(method, path, expected=200, actor=None, body=None, schema=None):
|
||||
code = r"""
|
||||
import json, sys, urllib.request, urllib.error
|
||||
p=json.load(sys.stdin)
|
||||
h={"Content-Type":"application/json"}
|
||||
if p["actor"]: h["Authorization"]="Bearer "+p["actor"]["token"]
|
||||
r=urllib.request.Request("http://127.0.0.1:8080"+p["path"], method=p["method"], headers=h,
|
||||
data=json.dumps(p["body"]).encode() if p["body"] is not None else None)
|
||||
try: response=urllib.request.urlopen(r, timeout=6)
|
||||
except urllib.error.HTTPError as e: response=e
|
||||
with response:
|
||||
assert response.headers.get("X-Request-Id") and response.headers.get("X-Instance-Id")
|
||||
print(response.status)
|
||||
"""
|
||||
result = subprocess.check_output(
|
||||
["docker", "exec", "-i", container, "python", "-c", code],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
input=json.dumps(dict(method=method, path=path, actor=actor, body=body)),
|
||||
)
|
||||
assert int(result.strip()) == expected, (method, path, expected, result)
|
||||
|
||||
def wait_lb():
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
time.sleep(0.25)
|
||||
|
||||
try:
|
||||
compose("stop", "redis")
|
||||
probe("GET", "/health/live", schema="Health")
|
||||
probe("GET", "/api/v1/users/me", 503, actor=actor)
|
||||
probe("DELETE", "/api/v1/auth/sessions/current", 503, actor=actor)
|
||||
probe("GET", "/health/ready", 503)
|
||||
probe("GET", "/api/v1/users/me", 503, actor={"token": "invalid-token"})
|
||||
probe("GET", "/api/v1/users/me", 401)
|
||||
print(
|
||||
"PASS: Redis выключен; live=200, ready=503; проверка сессий недоступна, доступ не выдаётся"
|
||||
)
|
||||
finally:
|
||||
compose("up", "-d", "--wait", "redis")
|
||||
wait_lb()
|
||||
probe("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
print("PASS: сессия сохранилась после перезапуска Redis")
|
||||
revoked = c.user("revoked")
|
||||
probe("GET", "/api/v1/users/me", actor=revoked, schema="User")
|
||||
probe("DELETE", "/api/v1/auth/sessions/current", 204, actor=revoked)
|
||||
compose("restart", "redis")
|
||||
compose("up", "-d", "--wait", "redis")
|
||||
probe("GET", "/api/v1/users/me", 401, actor=revoked)
|
||||
probe(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
401,
|
||||
actor=revoked,
|
||||
body={"title": "Нет доступа", "member_ids": [revoked["id"]]},
|
||||
)
|
||||
print(
|
||||
"PASS: logout при отказе Redis возвращает 503; успешный отзыв переживает AOF-рестарт и не даёт доступ"
|
||||
)
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
probe("GET", "/health/live", schema="Health")
|
||||
probe("GET", "/health/ready", 503)
|
||||
probe("GET", "/api/v1/chats", 503, actor=actor)
|
||||
probe("GET", "/api/v1/users/me", 401)
|
||||
probe("GET", "/api/v1/users/me", 401, actor={"token": "invalid-token"})
|
||||
probe("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
print(
|
||||
"PASS: PostgreSQL выключен; live=200, ready=503, чаты=503; действующая сессия и прогретый профиль доступны в Redis"
|
||||
)
|
||||
finally:
|
||||
compose("up", "-d", "--wait", "postgres")
|
||||
probe("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
wait_lb()
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
print("PASS: после восстановления БД прежняя сессия снова работает через HAProxy")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Неожиданное исключение не раскрывает детали и сохраняет обязательные headers.
|
||||
Маршрут добавлен только в этот изолированный процесс, не в работающий API.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from src.main import INSTANCE_ID, app
|
||||
|
||||
|
||||
@app.get("/_audit_unexpected_error")
|
||||
async def unexpected():
|
||||
raise RuntimeError("audit-internal-detail")
|
||||
|
||||
|
||||
async def main():
|
||||
messages = []
|
||||
|
||||
async def receive():
|
||||
await asyncio.Event().wait()
|
||||
|
||||
async def send(message):
|
||||
messages.append(message)
|
||||
|
||||
scope = {
|
||||
"type": "http",
|
||||
"asgi": {"version": "3.0", "spec_version": "2.4"},
|
||||
"http_version": "1.1",
|
||||
"method": "GET",
|
||||
"scheme": "http",
|
||||
"path": "/_audit_unexpected_error",
|
||||
"raw_path": b"/_audit_unexpected_error",
|
||||
"query_string": b"",
|
||||
"root_path": "",
|
||||
"headers": [],
|
||||
"server": ("localhost", 80),
|
||||
"client": ("127.0.0.1", 1),
|
||||
}
|
||||
await app(scope, receive, send)
|
||||
start = next(m for m in messages if m["type"] == "http.response.start")
|
||||
payload = json.loads(
|
||||
b"".join(m.get("body", b"") for m in messages if m["type"] == "http.response.body")
|
||||
)
|
||||
headers = dict(start["headers"])
|
||||
assert start["status"] == 500
|
||||
assert headers[b"x-instance-id"].decode() == INSTANCE_ID
|
||||
assert payload["error"]["request_id"] == headers[b"x-request-id"].decode()
|
||||
assert payload["error"]["code"] == "internal_error"
|
||||
assert "audit-internal-detail" not in json.dumps(payload)
|
||||
print("PASS: 500 has X-Request-Id/X-Instance-Id and hides internal exception details")
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Отдельный стенд/запуск с SESSION_TTL_SECONDS=2, не обычный smoke."""
|
||||
import time
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Истечение короткой сессии')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
actor = c.user('expiry')
|
||||
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
time.sleep(3)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
print('PASS: действующая сессия стала 401 через 3 секунды при TTL=2')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import base64
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Собственные тесты мессенджера")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
chat_path = "/api/v1/chats/" + chat["id"]
|
||||
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
client.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
client.call(
|
||||
"POST",
|
||||
chat_path + "/messages",
|
||||
400,
|
||||
actor=alice,
|
||||
body={"text": " "},
|
||||
)
|
||||
client.call("GET", chat_path, 404, actor=eve)
|
||||
|
||||
# Уникальность защищена ограничением БД, в том числе при гонке.
|
||||
registration = {
|
||||
'username': 'race_' + uuid.uuid4().hex[:16],
|
||||
'display_name': 'Гонка регистрации',
|
||||
'password': 'Пароль:с-двоеточием-123',
|
||||
}
|
||||
def register(_):
|
||||
local = Client(args.base_url, args.ca_file)
|
||||
return local.call('POST', '/api/v1/users', [201, 409], body=registration)['status']
|
||||
with ThreadPoolExecutor(max_workers=6) as pool:
|
||||
statuses = list(pool.map(register, range(6)))
|
||||
check(statuses.count(201) == 1 and statuses.count(409) == 5, 'гонка регистрации не защищена')
|
||||
session = client.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': 'Basic ' + base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()}, schema='Session')['json']
|
||||
actor = {'token': session['token']}
|
||||
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
||||
# Даже прогретый Redis не должен разрешать отозванную сессию.
|
||||
client.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
|
||||
def send_batch(worker_id):
|
||||
local = Client(args.base_url, args.ca_file)
|
||||
result = []
|
||||
for index in range(10):
|
||||
response = local.message(
|
||||
alice,
|
||||
chat,
|
||||
"параллельное-%d-%d" % (worker_id, index),
|
||||
)["json"]
|
||||
result.append(response["id"])
|
||||
return result
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
created_ids = [
|
||||
message_id
|
||||
for batch in pool.map(send_batch, range(10))
|
||||
for message_id in batch
|
||||
]
|
||||
|
||||
check(len(created_ids) == 100, "не все параллельные запросы вернули ответ")
|
||||
check(len(set(created_ids)) == 100, "параллельные запросы вернули повторяющиеся ID")
|
||||
|
||||
received = []
|
||||
cursor = None
|
||||
while True:
|
||||
path = chat_path + "/messages?limit=17"
|
||||
if cursor is not None:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", path, actor=bob, schema="MessagePage")["json"]
|
||||
received.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
|
||||
concurrent_messages = [
|
||||
message for message in received if message["text"].startswith("параллельное-")
|
||||
]
|
||||
received_ids = [message["id"] for message in concurrent_messages]
|
||||
check(len(received_ids) == 100, "в истории нет ровно 100 параллельно созданных сообщений")
|
||||
check(len(set(received_ids)) == 100, "в истории есть повторяющиеся сообщения")
|
||||
check(set(received_ids) == set(created_ids), "ID созданных и прочитанных сообщений не совпадают")
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"результат": "ПРОЙДЕНО",
|
||||
"гонка_регистрации": "1 создан, 5 конфликтов",
|
||||
"unicode_пароль_и_logout_с_кэшем": "ПРОЙДЕНО",
|
||||
"параллельных_клиентов": 10,
|
||||
"создано_сообщений": len(created_ids),
|
||||
"уникальных_сообщений": len(set(received_ids)),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Запуск внутри API: rollback и 24h expiry без ожидания суток."""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import delete, select, text, update
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from src.core.db.models import Chat, ChatMember, Message, MessageRequest, User
|
||||
from src.core.db.repo.message import create_idempotent_message
|
||||
from src.core.db.session import create_engine
|
||||
|
||||
|
||||
async def main():
|
||||
engine = create_engine()
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
user_id, chat_id = uuid4(), uuid4()
|
||||
now = datetime.now(timezone.utc)
|
||||
async with factory.begin() as s:
|
||||
s.add(
|
||||
User(
|
||||
id=user_id,
|
||||
username="idem_" + user_id.hex[:20],
|
||||
display_name="Fixture",
|
||||
password_hash="not-for-login",
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
await s.flush()
|
||||
s.add(Chat(id=chat_id, title="Idempotency fixture", created_at=now))
|
||||
await s.flush()
|
||||
s.add(ChatMember(chat_id=chat_id, user_id=user_id))
|
||||
try:
|
||||
try:
|
||||
async with factory.begin() as s:
|
||||
await create_idempotent_message(
|
||||
s, uuid4(), chat_id, user_id, "rollback", now, "same"
|
||||
)
|
||||
raise RuntimeError("simulated failure before COMMIT")
|
||||
except RuntimeError:
|
||||
pass
|
||||
async with factory() as s:
|
||||
assert not list(await s.scalars(select(Message).where(Message.chat_id == chat_id)))
|
||||
assert not list(
|
||||
await s.scalars(select(MessageRequest).where(MessageRequest.chat_id == chat_id))
|
||||
)
|
||||
async with factory.begin() as s:
|
||||
first = await create_idempotent_message(
|
||||
s, uuid4(), chat_id, user_id, "committed", now, "same"
|
||||
)
|
||||
async with factory.begin() as s:
|
||||
replay = await create_idempotent_message(
|
||||
s, uuid4(), chat_id, user_id, "committed", now, "same"
|
||||
)
|
||||
assert replay == first
|
||||
await s.execute(
|
||||
update(MessageRequest)
|
||||
.where(MessageRequest.chat_id == chat_id)
|
||||
.values(expires_at=text("clock_timestamp() - interval '1 second'"))
|
||||
)
|
||||
async with factory.begin() as s:
|
||||
fresh = await create_idempotent_message(
|
||||
s, uuid4(), chat_id, user_id, "new after expiry", now, "same"
|
||||
)
|
||||
assert fresh.id != first.id
|
||||
print(
|
||||
"PASS: rollback removes both message/key; committed result replays; expired key can be reused"
|
||||
)
|
||||
finally:
|
||||
async with factory.begin() as s:
|
||||
await s.execute(delete(MessageRequest).where(MessageRequest.chat_id == chat_id))
|
||||
await s.execute(delete(Message).where(Message.chat_id == chat_id))
|
||||
await s.execute(delete(Chat).where(Chat.id == chat_id))
|
||||
await s.execute(delete(User).where(User.id == user_id))
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентная идемпотентность, область ключей и повторная авторизация."""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab3 concurrency and idempotency")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
key = uuid.uuid4().hex
|
||||
clients = [Client(args.base_url, args.ca_file) for _ in range(16)]
|
||||
barrier = threading.Barrier(len(clients))
|
||||
|
||||
def send(local):
|
||||
barrier.wait()
|
||||
return local.message(alice, chat, "Одна отправка 👋", key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=len(clients)) as pool:
|
||||
responses = list(pool.map(send, clients))
|
||||
instances = {r["headers"]["X-Instance-Id"] for r in responses}
|
||||
check(len(instances) >= 2, "Parallel repeats did not reach >=2 replicas")
|
||||
original = responses[0]["json"]
|
||||
check(all(r["json"] == original for r in responses), "Concurrent results differ")
|
||||
messages = c.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check(messages == [original], "Concurrent retries duplicated message")
|
||||
# Missing attachment_ids and [] are semantically equal; raw JSON ordering too.
|
||||
replay = c.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
raw=b'{"attachment_ids":[],"text":"' + "Одна отправка 👋".encode() + b'"}',
|
||||
headers={"Idempotency-Key": key, "Content-Type": "application/json"},
|
||||
schema="Message",
|
||||
)
|
||||
check(replay["json"] == original, "Equivalent JSON did not replay")
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
409,
|
||||
actor=alice,
|
||||
body={"text": "Другой текст"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
other = c.message(bob, chat, "Другой отправитель", key=key)["json"]
|
||||
check(other["id"] != original["id"], "Key incorrectly shared across users")
|
||||
chat2 = c.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Другой чат", "member_ids": [alice["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
check(
|
||||
c.message(alice, chat2, "Другой чат", key=key)["json"]["id"] != original["id"],
|
||||
"Key scope includes wrong chat",
|
||||
)
|
||||
for invalid in [None, "", "bad key", "x" * 129, "bad/key"]:
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
400,
|
||||
actor=alice,
|
||||
body={"text": "invalid"},
|
||||
headers={} if invalid is None else {"Idempotency-Key": invalid},
|
||||
)
|
||||
# Validation/access failures must not consume a key.
|
||||
retry_key = uuid.uuid4().hex
|
||||
c.call(
|
||||
"POST", path, 400, actor=alice, body={"text": ""}, headers={"Idempotency-Key": retry_key}
|
||||
)
|
||||
c.message(alice, chat, "После 400", key=retry_key)
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
404,
|
||||
actor=eve,
|
||||
body={"text": original["text"]},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
401,
|
||||
actor=alice,
|
||||
body={"text": original["text"]},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
for route in ["/health/live", "/health/ready", "/missing"]:
|
||||
c.call("GET", route, 404 if route == "/missing" else 200)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"parallel_repeats": len(responses),
|
||||
"instances": sorted(instances),
|
||||
"messages_created": 1,
|
||||
"checks": "normalization, conflict, key scope, invalid keys, access, logout, headers",
|
||||
"result": "PASS",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""docker compose exec -T api python < tests/passwords.py."""
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from src.core import cache, session_store
|
||||
from src.core.db.models import User
|
||||
from src.core.db.session import create_engine
|
||||
from src.core.security import hash_password, hash_token, verify_password
|
||||
|
||||
|
||||
def login(username, password, expected):
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
request = Request('http://127.0.0.1:8080/api/v1/auth/sessions', method='POST',
|
||||
headers={'Authorization': 'Basic ' + credential})
|
||||
try:
|
||||
response = urlopen(request, timeout=10)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
assert response.status == expected, response.status
|
||||
return json.load(response)
|
||||
|
||||
|
||||
async def main():
|
||||
password = 'Я:' + 'ю' * 126
|
||||
hashed = hash_password(password)
|
||||
assert hashed.startswith('$argon2id$')
|
||||
assert hash_password(password) != hashed
|
||||
assert verify_password(password, hashed)
|
||||
assert not verify_password('неверный-пароль', hashed)
|
||||
assert not verify_password(password, 'unsupported$hash')
|
||||
print('PASS: только Argon2id, случайная соль, Unicode 128 символов, неверный пароль')
|
||||
engine = create_engine()
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
user_id, username = uuid4(), 'password_' + uuid4().hex[:16]
|
||||
tokens = []
|
||||
cache.open_cache()
|
||||
try:
|
||||
async with factory.begin() as session:
|
||||
session.add(User(id=user_id, username=username, display_name='Password test',
|
||||
password_hash=hashed, created_at=datetime.now(timezone.utc)))
|
||||
login(username, 'неверный-пароль', 401)
|
||||
for _ in range(2):
|
||||
result = login(username, password, 201)
|
||||
tokens.append(result['token'])
|
||||
stored = await session_store.fetch_session(hash_token(result['token']))
|
||||
assert stored is not None and stored.user_id == user_id
|
||||
async with factory() as session:
|
||||
assert await session.scalar(select(User.password_hash).where(User.id == user_id)) == hashed
|
||||
print('PASS: повторный вход с Argon2id; сессии находятся в Redis; хеш пароля не изменяется')
|
||||
finally:
|
||||
for token in tokens:
|
||||
await session_store.delete_session(hash_token(token))
|
||||
await cache.close_cache()
|
||||
async with factory.begin() as session:
|
||||
await session.execute(delete(User).where(User.id == user_id))
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Негативные HTTP/Redis проверки для production-аудита; только локальный Compose."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import threading
|
||||
import uuid
|
||||
from urllib.parse import urlsplit, quote
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def redis(*args, raw=None):
|
||||
command = ['docker', 'compose', 'exec', '-T', 'redis', 'redis-cli', '--raw']
|
||||
if raw is not None:
|
||||
command += ['-x']
|
||||
return subprocess.check_output(command + list(args), cwd=ROOT, input=raw, timeout=10).rstrip(b'\n')
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Production-аудит входных данных, Redis и изоляции сессий')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
failures = []
|
||||
def expect(label, method, path, status, **kwargs):
|
||||
response = c.call(method, path, [200, 201, 400, 401, 413, 415, 500, 503], **kwargs)
|
||||
if response['status'] != status:
|
||||
failures.append(f'{label}: ожидался {status}, получен {response["status"]}')
|
||||
return response
|
||||
|
||||
payload = {'kind': 'messages', 'owner_id': chat['id'],
|
||||
'created_at': '2026-01-01T00:00:00+00:00', 'item_id': str(uuid.uuid4())}
|
||||
for field, value in [('owner_id', 123), ('item_id', 123), ('owner_id', []),
|
||||
('created_at', '9999-12-31T23:59:59-23:59')]:
|
||||
cursor = base64.urlsafe_b64encode(json.dumps({**payload, field: value}).encode()).decode()
|
||||
expect('Типы/диапазон курсора ' + field, 'GET', path + '?cursor=' + cursor, 400, actor=alice)
|
||||
expect('Длина курсора', 'GET', path + '?cursor=' + 'a' * 5000, 400, actor=alice)
|
||||
for text in ('\ud800', '\udfff'):
|
||||
expect('Непредставимый текст PostgreSQL', 'POST', path, 400, actor=alice,
|
||||
raw=json.dumps({'text': 'valid' + text}).encode(), headers={'Content-Type': 'application/json'})
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:16],
|
||||
'password': 'valid-password-123', 'display_name': 'Valid'}
|
||||
for field, value in [('display_name', '\ud800'),
|
||||
('password', 'secret-audit-\ud800')]:
|
||||
expect('Непредставимая строка ' + field, 'POST', '/api/v1/users', 400,
|
||||
raw=json.dumps({**registration, field: value}).encode(), headers={'Content-Type': 'application/json'})
|
||||
expect('Большое тело с допустимым коротким текстом', 'POST', path, 413, actor=alice,
|
||||
raw=b'{"text":"valid"}' + b' ' * 70000, headers={'Content-Type': 'application/json'})
|
||||
expect('Повторяющиеся ключи JSON', 'POST', path, 400, actor=alice,
|
||||
raw=b'{"text":"first","text":"second"}', headers={'Content-Type': 'application/json'})
|
||||
expect('JSON не в UTF-8', 'POST', path, 400, actor=alice,
|
||||
raw='{"text":"valid"}'.encode('utf-16'), headers={'Content-Type': 'application/json'})
|
||||
expect('Нестандартный NaN', 'POST', path, 400, actor=alice,
|
||||
raw=b'{"text":"valid","extra":NaN}', headers={'Content-Type': 'application/json'})
|
||||
expect('Глубокий JSON', 'POST', path, 400, actor=alice,
|
||||
raw=b'[' * 1200 + b'0' + b']' * 1200, headers={'Content-Type': 'application/json'})
|
||||
|
||||
# Максимально допустимый текст остаётся допустимым и в escaped JSON.
|
||||
emoji = '😀' * 4000
|
||||
maximum = c.call('POST', path, 201, actor=alice, schema='Message',
|
||||
raw=json.dumps({'text': emoji}, ensure_ascii=True).encode(),
|
||||
headers={'Content-Type': 'application/json', 'Idempotency-Key':uuid.uuid4().hex})
|
||||
check(maximum['json']['text'] == emoji, 'Лимит тела отверг/исказил 4000 Unicode-символов')
|
||||
check(maximum['headers'].get('Cache-Control') == 'no-store', 'Ответ API может попасть в кэш')
|
||||
check(maximum['headers'].get('X-Content-Type-Options') == 'nosniff', 'Нет nosniff')
|
||||
|
||||
parsed = urlsplit(c.base)
|
||||
check(parsed.scheme == 'http', 'Сетевые проверки этого Compose-сценария рассчитаны на localhost HTTP')
|
||||
def wire(duplicate=False, chunked=False, slow=False, started=None):
|
||||
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=10)
|
||||
try:
|
||||
if chunked:
|
||||
connection.request('POST', path, body=iter([b'{"text":"valid"}', b' ' * 40000, b' ' * 40000]),
|
||||
headers={'Authorization': 'Bearer ' + alice['token'],
|
||||
'Content-Type': 'application/json'}, encode_chunked=True)
|
||||
elif slow:
|
||||
connection.putrequest('POST', path)
|
||||
connection.putheader('Authorization', 'Bearer ' + alice['token'])
|
||||
connection.putheader('Content-Type', 'application/json')
|
||||
connection.putheader('Content-Length', '100')
|
||||
connection.endheaders(b'{\"text\":')
|
||||
started.set()
|
||||
else:
|
||||
connection.putrequest('GET', '/api/v1/users/me')
|
||||
connection.putheader('Authorization', 'Bearer ' + alice['token'])
|
||||
if duplicate:
|
||||
connection.putheader('Authorization', 'Bearer ' + bob['token'])
|
||||
connection.endheaders()
|
||||
response = connection.getresponse()
|
||||
data = json.loads(response.read())
|
||||
check(data['error']['request_id'] == response.getheader('X-Request-Id'), 'Сетевой запрос потерял request_id')
|
||||
return response.status
|
||||
finally:
|
||||
connection.close()
|
||||
check(wire(chunked=True) == 413, 'Chunked обходит лимит размера тела')
|
||||
check(wire(duplicate=True) == 401, 'Два Authorization принимаются неоднозначно')
|
||||
print('PASS: реальный chunked=413, два Authorization=401, no-store; 4000 emoji в escaped JSON допустимы')
|
||||
started = threading.Event()
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
pending = pool.submit(wire, slow=True, started=started)
|
||||
check(started.wait(2), 'Не началась медленная передача')
|
||||
health = c.call('GET', '/health/live', schema='Health')
|
||||
check(health['elapsed'] < 2, 'Медленная передача заблокировала event loop')
|
||||
check(pending.result(timeout=10) == 408, 'У медленной передачи нет deadline')
|
||||
print('PASS: реальное незавершённое тело получает 408; health работает во время ожидания')
|
||||
|
||||
|
||||
created = [chat]
|
||||
for index in range(12):
|
||||
created.append(c.call('POST', '/api/v1/chats', 201, actor=alice, schema='Chat',
|
||||
body={'title': 'SQL-page-' + str(index), 'member_ids': [alice['id']]})['json'])
|
||||
chats, cursor = [], None
|
||||
while True:
|
||||
url = '/api/v1/chats?limit=3' + ('&cursor=' + quote(cursor, safe='') if cursor else '')
|
||||
page = c.call('GET', url, actor=alice, schema='ChatPage')['json']
|
||||
chats.extend(item['id'] for item in page['items'])
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
c.call('GET', '/api/v1/chats?cursor=' + quote(cursor, safe=''), 400, actor=bob)
|
||||
check(len(chats) <= len(created), 'Зациклилась пагинация чатов')
|
||||
check(chats == [item['id'] for item in sorted(created, key=lambda x: (x['created_at'], uuid.UUID(x['id']).int))],
|
||||
'SQL-пагинация чатов потеряла/повторила объекты')
|
||||
bob_chats = c.call('GET', '/api/v1/chats', actor=bob, schema='ChatPage')['json']
|
||||
check([item['id'] for item in bob_chats['items']] == [chat['id']], 'В список попали чужие чаты')
|
||||
print('PASS: SQL-пагинация 13 чатов по 3; курсор принадлежит пользователю, чужие чаты скрыты')
|
||||
|
||||
profile_key = 'user:v1:' + alice['id']
|
||||
for raw in (b'\xff\xfe', b'null', b'{"id":123}'):
|
||||
redis('SET', profile_key, raw=raw)
|
||||
expect('Повреждённый профиль Redis', 'GET', '/api/v1/users/me', 200, actor=alice)
|
||||
session_key = 'session:v1:' + hashlib.sha256(alice['token'].encode()).hexdigest()
|
||||
saved = redis('GET', session_key)
|
||||
ttl = int(redis('PTTL', session_key))
|
||||
for raw in (b'\xff', json.dumps({'user_id': 123, 'expires_at': '2099-01-01T00:00:00+00:00'}).encode(),
|
||||
b'[]', b'null', json.dumps({'user_id': alice['id'], 'expires_at': '2020-01-01T00:00:00+00:00'}).encode()):
|
||||
try:
|
||||
redis('SET', session_key, raw=raw)
|
||||
redis('PEXPIRE', session_key, str(ttl))
|
||||
expect('Повреждённая/истёкшая сессия Redis', 'GET', '/api/v1/users/me', 401, actor=alice)
|
||||
finally:
|
||||
redis('SET', session_key, raw=saved)
|
||||
redis('PEXPIRE', session_key, str(ttl))
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
|
||||
# NUL недопустим в PostgreSQL text, но пароль хранится как Argon2-хеш.
|
||||
special = {**registration, 'username': 'nulpass_' + uuid.uuid4().hex[:16],
|
||||
'password': ' пароль:\x00с пробелами '}
|
||||
c.call('POST', '/api/v1/users', 201, body=special, schema='User')
|
||||
special_basic = 'Basic ' + base64.b64encode((special['username'] + ':' + special['password']).encode()).decode()
|
||||
special_session = c.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': special_basic}, schema='Session')['json']
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor={'token': special_session['token']})
|
||||
print('PASS: пароль с Unicode, пробелами, двоеточием и NUL не усекается')
|
||||
|
||||
basic = 'Basic ' + base64.b64encode((alice['registration']['username'] + ':' + alice['registration']['password']).encode()).decode()
|
||||
another = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': basic}, schema='Session')['json']
|
||||
check(another['token'] != alice['token'], 'Повторный вход вернул старый токен')
|
||||
def get_profile(_):
|
||||
return Client(args.base_url, args.ca_file).call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
profiles = list(pool.map(get_profile, range(24)))
|
||||
check(all(p['json']['id'] == alice['id'] for p in profiles), 'Смешаны пользователи конкурентных запросов')
|
||||
check(len({p['headers']['X-Request-Id'] for p in profiles}) == 24, 'Повторяется request_id')
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
list(pool.map(lambda _: Client(args.base_url, args.ca_file).call(
|
||||
'DELETE', '/api/v1/auth/sessions/current', [204, 401], actor=alice), range(4)))
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', actor={'token': another['token']}, schema='User')
|
||||
c.call('GET', '/api/v1/users/me', actor=bob, schema='User')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor={'token': another['token']})
|
||||
print('PASS: независимые токены, конкурентные logout/GET, уникальные request_id')
|
||||
if failures:
|
||||
for failure in failures:
|
||||
print('FAIL:', failure)
|
||||
check(False, 'Production-аудит нашёл ошибки: ' + str(len(failures)))
|
||||
print('PASS: типы/диапазон курсора, Unicode, размер/формат JSON и повреждённый Redis')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Изолированные проверки ASGI-лимитов и реального пула Argon2 в образе API."""
|
||||
import asyncio
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
import threading
|
||||
import time
|
||||
from unittest.mock import patch
|
||||
|
||||
from src.core import security
|
||||
from src.core.request_limits import RequestLimitsMiddleware
|
||||
from src.core.settings import settings
|
||||
|
||||
|
||||
def scope(path='/api/v1/users', headers=()):
|
||||
return {'type': 'http', 'asgi': {'version': '3.0'}, 'http_version': '1.1',
|
||||
'method': 'POST', 'scheme': 'http', 'path': path, 'raw_path': path.encode(),
|
||||
'query_string': b'', 'headers': [(b'content-type', b'application/json'), *headers],
|
||||
'state': {'request_id': 'limit-test'}, 'server': ('localhost', 80), 'client': ('localhost', 1)}
|
||||
|
||||
|
||||
async def invoke(app, messages=(), path='/api/v1/users', headers=(), delay=0):
|
||||
sent = []
|
||||
pending = iter(messages or [{'type': 'http.request', 'body': b'{}', 'more_body': False}])
|
||||
async def receive():
|
||||
if delay:
|
||||
await asyncio.sleep(delay)
|
||||
return next(pending)
|
||||
async def send(message):
|
||||
sent.append(message)
|
||||
await app(scope(path, headers), receive, send)
|
||||
if not sent:
|
||||
return None
|
||||
status = next(m['status'] for m in sent if m['type'] == 'http.response.start')
|
||||
data = json.loads(b''.join(m.get('body', b'') for m in sent if m['type'] == 'http.response.body'))
|
||||
if status >= 400:
|
||||
assert data['error']['request_id'] == 'limit-test'
|
||||
return status, data
|
||||
|
||||
|
||||
async def main():
|
||||
assert os.geteuid() != 0, 'API работает от root'
|
||||
status = Path('/proc/self/status').read_text()
|
||||
assert 'NoNewPrivs:\t1' in status
|
||||
assert 'CapEff:\t0000000000000000' in status
|
||||
probe = Path('/app/.production-write-probe')
|
||||
try:
|
||||
probe.write_text('probe')
|
||||
except OSError as error:
|
||||
assert error.errno == errno.EROFS, error.errno
|
||||
else:
|
||||
probe.unlink()
|
||||
raise AssertionError('Корневая файловая система API доступна для записи')
|
||||
with TemporaryDirectory() as directory:
|
||||
Path(directory, 'probe').write_text('temporary')
|
||||
print('PASS: non-root, read-only rootfs, пустые capabilities, no-new-privileges; /tmp доступен')
|
||||
called = 0
|
||||
async def endpoint(scope, receive, send):
|
||||
nonlocal called
|
||||
called += 1
|
||||
message = await receive()
|
||||
await send({'type': 'http.response.start', 'status': 200, 'headers': []})
|
||||
await send({'type': 'http.response.body', 'body': json.dumps({'bytes': len(message['body'])}).encode()})
|
||||
app = RequestLimitsMiddleware(endpoint)
|
||||
maximum = settings.http_max_body_bytes
|
||||
assert (await invoke(app, headers=[(b'content-length', str(maximum+1).encode())]))[0] == 413
|
||||
assert called == 0
|
||||
chunks = [{'type': 'http.request', 'body': b' ' * 40000, 'more_body': True},
|
||||
{'type': 'http.request', 'body': b' ' * 40000, 'more_body': False}]
|
||||
assert (await invoke(app, messages=chunks))[0] == 413
|
||||
assert (await invoke(app, messages=chunks, headers=[(b'content-length', b'1')]))[0] == 413
|
||||
assert (await invoke(app, headers=[(b'content-length', b'-1')]))[0] == 400
|
||||
with patch.object(settings, 'http_body_timeout_seconds', 0.02):
|
||||
assert (await invoke(app, delay=0.1))[0] == 408
|
||||
assert await invoke(app, messages=[{'type': 'http.disconnect'}]) is None
|
||||
assert called == 0
|
||||
assert (await invoke(app))[0] == 200
|
||||
assert app.limiter.borrowed_tokens == 0
|
||||
print('PASS: Content-Length/chunked/ложный размер, timeout, disconnect; слот всегда освобождается')
|
||||
|
||||
gate = asyncio.Event()
|
||||
entered = asyncio.Event()
|
||||
active = 0
|
||||
async def blocked(scope, receive, send):
|
||||
nonlocal active
|
||||
if scope['path'].startswith('/api/'):
|
||||
active += 1
|
||||
if active == 2:
|
||||
entered.set()
|
||||
await gate.wait()
|
||||
await endpoint(scope, receive, send)
|
||||
with patch.object(settings, 'http_concurrency_limit', 2):
|
||||
limited = RequestLimitsMiddleware(blocked)
|
||||
tasks = [asyncio.create_task(invoke(limited)) for _ in range(2)]
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 1)
|
||||
assert (await invoke(limited))[0] == 503
|
||||
assert (await invoke(limited, path='/health/live'))[0] == 200
|
||||
tasks[0].cancel()
|
||||
await asyncio.gather(tasks[0], return_exceptions=True)
|
||||
assert limited.limiter.borrowed_tokens == 1
|
||||
gate.set()
|
||||
assert (await tasks[1])[0] == 200
|
||||
assert (await invoke(limited))[0] == 200
|
||||
finally:
|
||||
gate.set()
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
assert limited.limiter.borrowed_tokens == 0
|
||||
print('PASS: перегрузка=503 в общем JSON, health доступен, отмена запроса не теряет слот')
|
||||
|
||||
lock = threading.Lock()
|
||||
active = peak = 0
|
||||
def slow_hash(password):
|
||||
nonlocal active, peak
|
||||
with lock:
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
try:
|
||||
time.sleep(0.03)
|
||||
return 'hashed-' + password
|
||||
finally:
|
||||
with lock:
|
||||
active -= 1
|
||||
count = settings.password_hash_concurrency * 4
|
||||
with patch.object(security, 'hash_password', slow_hash):
|
||||
result = await asyncio.gather(*(security.hash_password_async(str(i)) for i in range(count)))
|
||||
assert result == ['hashed-' + str(i) for i in range(count)]
|
||||
assert peak == settings.password_hash_concurrency, peak
|
||||
assert security.password_limiter.borrowed_tokens == 0
|
||||
print('PASS: очередь Argon2 соблюдает лимит параллелизма; результаты не смешиваются')
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Изолированная проверка HTTP-бюджета readiness при медленной отмене драйвера."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from unittest.mock import patch
|
||||
|
||||
from src.core import readiness
|
||||
from src.core.errors import ApiError
|
||||
from src.core.settings import settings
|
||||
|
||||
|
||||
async def main():
|
||||
cancelled = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
calls = 0
|
||||
|
||||
async def stalled_driver():
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
except asyncio.CancelledError:
|
||||
cancelled.set()
|
||||
await release.wait()
|
||||
|
||||
with (
|
||||
patch.object(settings, "healthcheck_timeout_seconds", 0.03),
|
||||
patch.object(readiness, "_probe", stalled_driver),
|
||||
):
|
||||
for _ in range(3):
|
||||
began = time.monotonic()
|
||||
try:
|
||||
await readiness.check()
|
||||
except ApiError as error:
|
||||
assert error.status_code == 503
|
||||
else:
|
||||
raise AssertionError("Stalled dependency was declared ready")
|
||||
assert time.monotonic() - began < 0.15, "HTTP waited for slow driver cancellation"
|
||||
assert cancelled.is_set() and calls == 1, "Readiness spawned accumulating probes"
|
||||
release.set()
|
||||
await asyncio.sleep(0)
|
||||
await readiness.close()
|
||||
|
||||
async def healthy():
|
||||
pass
|
||||
|
||||
with patch.object(readiness, "_probe", healthy):
|
||||
await readiness.check()
|
||||
await readiness.close()
|
||||
print("PASS: bounded readiness response, one pending probe, recovery after cancellation")
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Проверки замечаний преподавателя: HTTP, повреждённый Redis и точный курсор."""
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def database(code):
|
||||
container = subprocess.check_output(['docker', 'compose', 'ps', '-q', 'api'], cwd=ROOT, text=True).split()[0]
|
||||
result = subprocess.run(['docker', 'exec', '-i', container, 'python'],
|
||||
input=code, cwd=ROOT, text=True, capture_output=True, timeout=30)
|
||||
check(result.returncode == 0, 'Ошибка подготовки/удаления ORM-фикстуры')
|
||||
return json.loads(result.stdout) if result.stdout.strip() else None
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Регрессии по замечаниям преподавателя')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
registration = {**alice['registration'], 'username': 'blank_' + uuid.uuid4().hex[:16]}
|
||||
for field, value in [('password', ' ' * 12), ('password', '\t\n' * 6),
|
||||
('display_name', ' \t\n')]:
|
||||
c.call('POST', '/api/v1/users', 400, body={**registration, field: value})
|
||||
for body in ({'title': ' \t\n', 'member_ids': [alice['id']]},
|
||||
{'title': 'Duplicate', 'member_ids': [alice['id'], alice['id']]},
|
||||
{'title': 'Unknown', 'member_ids': [alice['id'], str(uuid.uuid4())]},
|
||||
{'title': 'Missing actor', 'member_ids': [bob['id']]}):
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice, body=body)
|
||||
basic = {'Authorization': 'Basic ' + base64.b64encode((
|
||||
alice['registration']['username'] + ':' + alice['registration']['password']
|
||||
).encode()).decode()}
|
||||
for raw in (b'{"extra":"forbidden"}', b'{}', b'null', b' ', b'{'):
|
||||
c.call('POST', '/api/v1/auth/sessions', 400, headers=basic, raw=raw)
|
||||
c.call('POST', '/api/v1/auth/sessions', 401)
|
||||
for credential in ('Basic !!!', 'Basic /w==', 'Bearer something',
|
||||
'Basic ' + base64.b64encode(b'no-colon').decode()):
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': credential})
|
||||
for payload in ('null', '[]', '{}', '123', '{broken'):
|
||||
cursor = base64.urlsafe_b64encode(payload.encode()).decode().rstrip('=')
|
||||
c.call('GET', path + '?cursor=' + quote(cursor, safe=''), 400, actor=alice)
|
||||
for endpoint, body, actor in (
|
||||
('/api/v1/users', registration, None),
|
||||
('/api/v1/chats', {'title': 'MIME', 'member_ids': [alice['id']]}, alice),
|
||||
(path, {'text': 'valid'}, alice),
|
||||
):
|
||||
response = c.call('POST', endpoint, 415, actor=actor, body=body,
|
||||
headers={'Content-Type': 'text/plain'})
|
||||
check(response['json']['error']['code'] == 'unsupported_media_type', 'Неверный код MIME-ошибки')
|
||||
for raw in (b'{"text":"valid"}}', b'{"text":"valid"}]', b'{"text":"valid"}{}'):
|
||||
c.call('POST', path, 400, actor=alice, raw=raw, headers={'Content-Type': 'application/json'})
|
||||
for body in ({'text': ' ' * 12}, {'text': ' ' + 'a' * 4000}, {'text': 123},
|
||||
{'text': 'valid', 'sender_id': eve['id']}):
|
||||
c.call('POST', path, 400, actor=alice, body=body)
|
||||
check(c.call('GET', path, actor=alice, schema='MessagePage')['json']['items'] == [],
|
||||
'Отклонённый запрос сохранил сообщение')
|
||||
print('PASS: обязательные пробельные строки, malformed JSON, типы/лишние поля, MIME 415, Basic без тела')
|
||||
|
||||
# Создаём только синтетические строки через SQLAlchemy; пароли/токены в команды не передаются.
|
||||
fixture = database(f'''
|
||||
import asyncio, json
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID, uuid4
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
from src.core.db.session import create_engine
|
||||
from src.core.db.models import User, Message
|
||||
async def main():
|
||||
engine = create_engine()
|
||||
ids = [uuid4() for _ in range(100)]
|
||||
base = uuid4().int & ~65535
|
||||
message_ids = [UUID(int=base+4), UUID(int=base+3), UUID(int=base+2), UUID(int=base+1)]
|
||||
times = [100000, 200000, 200000, 200000]
|
||||
async with async_sessionmaker(engine).begin() as session:
|
||||
session.add_all([User(id=i, username='fixture_' + i.hex[:20], display_name='Fixture',
|
||||
password_hash='not-for-login', created_at=datetime.now(timezone.utc)) for i in ids])
|
||||
session.add_all([Message(id=i, chat_id=UUID('{chat['id']}'), sender_id=UUID('{alice['id']}'),
|
||||
text='precision', created_at=datetime(2026, 1, 1, 0, 0, 0, us, timezone.utc))
|
||||
for i, us in zip(message_ids, times)])
|
||||
await engine.dispose()
|
||||
print(json.dumps({{'users': [str(i) for i in ids], 'messages': [str(i) for i in message_ids]}}))
|
||||
asyncio.run(main())
|
||||
''')
|
||||
try:
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': '101 участников', 'member_ids': [alice['id'], *fixture['users']]})
|
||||
hundred = c.call('POST', '/api/v1/chats', 201, actor=alice, schema='Chat',
|
||||
body={'title': '100 участников',
|
||||
'member_ids': [alice['id'], *fixture['users'][:99]]})['json']
|
||||
check(len(hundred['member_ids']) == 100, 'Допустимые 100 участников не сохранены')
|
||||
received = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = path + '?limit=1' + ('&cursor=' + quote(cursor, safe='') if cursor else '')
|
||||
page = c.call('GET', url, actor=bob, schema='MessagePage')['json']
|
||||
received.extend(item['id'] for item in page['items'])
|
||||
if cursor is None:
|
||||
first_cursor = page['next_cursor']
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
check(len(received) <= 4, 'Курсор зациклился')
|
||||
expected = [fixture['messages'][0], *reversed(fixture['messages'][1:])]
|
||||
check(received == expected, 'Потеря/повтор сообщений при микросекундах или равном времени')
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(first_cursor, safe=''),
|
||||
400, actor=alice)
|
||||
print('PASS: 101 существующий участник отклонён; курсор сохраняет микросекунды и UUID-порядок, привязан к чату')
|
||||
finally:
|
||||
database(f'''
|
||||
import asyncio
|
||||
from uuid import UUID
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
from src.core.db.session import create_engine
|
||||
from src.core.db.models import User, Chat, ChatMember, Message
|
||||
async def main():
|
||||
engine = create_engine()
|
||||
ids = [UUID(i) for i in {fixture['users']!r}]
|
||||
async with async_sessionmaker(engine).begin() as session:
|
||||
chats = list(await session.scalars(select(ChatMember.chat_id).where(ChatMember.user_id.in_(ids))))
|
||||
await session.execute(delete(Message).where(Message.chat_id.in_(chats)))
|
||||
await session.execute(delete(Chat).where(Chat.id.in_(chats)))
|
||||
await session.execute(delete(User).where(User.id.in_(ids)))
|
||||
await engine.dispose()
|
||||
asyncio.run(main())
|
||||
''')
|
||||
text = ' строка\nс пробелами '
|
||||
saved = c.message(alice, chat, text)['json']
|
||||
check(saved['text'] == text, 'Текст обрезан до сохранения')
|
||||
history = c.call('GET', path, actor=alice, schema='MessagePage')['json']
|
||||
check(next(m for m in history['items'] if m['id'] == saved['id'])['text'] == text,
|
||||
'Сохранённый текст изменён')
|
||||
print('PASS: исходный текст и его длина сохраняются без strip')
|
||||
|
||||
key = 'user:v1:' + alice['id']
|
||||
def redis(*args):
|
||||
return subprocess.check_output(['docker', 'compose', 'exec', '-T', 'redis',
|
||||
'redis-cli', '--raw', *args], cwd=ROOT, text=True, timeout=10).strip()
|
||||
for corrupted in ('null', '[]', '{}', '{broken', '"text"', '{"id":123}',
|
||||
json.dumps({**alice['user'], 'id': bob['id']})):
|
||||
redis('SET', key, corrupted)
|
||||
me = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json']
|
||||
check(me == alice['user'], 'Повреждённый профиль отвергает сессию или меняет пользователя')
|
||||
check(json.loads(redis('GET', key))['id'] == alice['id'], 'Повреждённый кэш не заменён')
|
||||
check(0 < int(redis('TTL', key)) <= 60, 'Восстановленному профилю не назначен TTL')
|
||||
print('PASS: null/повреждённый/чужой профиль заменяется из PostgreSQL с TTL; сессия работает')
|
||||
|
||||
spec = json.loads(c.call('GET', '/openapi.json')['bytes'])
|
||||
login = spec['paths']['/api/v1/auth/sessions']['post']
|
||||
check('requestBody' not in login and {'basicAuth': []} in login['security'], 'Swagger вход не Basic')
|
||||
check({'bearerAuth': []} in spec['paths']['/api/v1/users/me']['get']['security'], 'Swagger не передаёт Bearer')
|
||||
print('PASS: Swagger объявляет Basic для входа и Bearer для защищённых методов')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""docker compose exec -T api python < tests/settings.py."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest.mock import patch
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from src.core.settings import AppSettings
|
||||
|
||||
# Только искусственные значения, соединения с этими адресами не открываются.
|
||||
with patch.dict(os.environ, {
|
||||
'DATABASE_URL': 'postgresql://settings_user:settings_test_password@postgres/settings_db',
|
||||
'REDIS_URL': 'redis://redis:6379/0',
|
||||
}, clear=True):
|
||||
with TemporaryDirectory() as directory:
|
||||
path = Path(directory) / '.env'
|
||||
path.write_text('SESSION_TTL_SECONDS=2\nDATABASE_POOL_SIZE=3\n', encoding='utf-8')
|
||||
config = AppSettings(_env_file=path)
|
||||
assert config.session_ttl_seconds == 2
|
||||
assert config.database_pool_size == 3
|
||||
assert config.sqlalchemy_database_url.startswith('postgresql+asyncpg://')
|
||||
assert 'settings_test_password' not in repr(config)
|
||||
with patch.dict(os.environ, {'SESSION_TTL_SECONDS': '4'}):
|
||||
assert AppSettings(_env_file=path).session_ttl_seconds == 4
|
||||
print('PASS: AppSettings читает .env, окружение имеет приоритет, URL скрыт в repr')
|
||||
|
||||
for values, expected_field in (
|
||||
({'session_ttl_seconds': 0}, 'session_ttl_seconds'),
|
||||
({'session_ttl_seconds': 'invalid'}, 'session_ttl_seconds'),
|
||||
({'database_pool_size': 0}, 'database_pool_size'),
|
||||
({'redis_read_timeout_seconds': -1}, 'redis_read_timeout_seconds'),
|
||||
({'session_token_bytes': 16}, 'session_token_bytes'),
|
||||
):
|
||||
try:
|
||||
AppSettings(_env_file=None, **values)
|
||||
except ValidationError as error:
|
||||
assert any(item['loc'] == (expected_field,) for item in error.errors())
|
||||
else:
|
||||
raise AssertionError('Некорректная настройка принята: ' + expected_field)
|
||||
print('PASS: Pydantic отклоняет неверные TTL, pool, timeout и недостаточную длину токена')
|
||||
for values in ({'app_env': 'production'}, {'admin_password': ' ' * 12},
|
||||
{'admin_display_name': 'bad\x00'}):
|
||||
try:
|
||||
AppSettings(_env_file=None, **values)
|
||||
except ValidationError as error:
|
||||
assert 'settings_test_password' not in str(error)
|
||||
assert 'input_value' not in str(error)
|
||||
else:
|
||||
raise AssertionError('Небезопасная конфигурация принята')
|
||||
assert AppSettings(_env_file=None, app_env='production',
|
||||
admin_password='custom-production-password-123').app_env == 'production'
|
||||
print('PASS: production отвергает учебный пароль; ошибки конфигурации скрывают входные значения')
|
||||
Reference in New Issue
Block a user