Implement lab 7 transport security and worker containment
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import asyncio
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from sqlalchemy import text
|
||||
|
||||
from conftest import PASSWORD, basic, new_user, running_app, sql_connection
|
||||
|
||||
|
||||
async def test_login_budget_shared_between_independent_apps(database: str) -> None:
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(text("DELETE FROM login_budget"))
|
||||
async with (
|
||||
running_app(login_attempts=3, login_window_seconds=60) as first,
|
||||
running_app(login_attempts=3, login_window_seconds=60) as second,
|
||||
):
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(
|
||||
text("INSERT INTO login_budget VALUES (1, floor(extract(epoch FROM now())/60), 1)")
|
||||
)
|
||||
responses = await asyncio.gather(
|
||||
*[
|
||||
http.post("/api/v1/auth/sessions", headers=basic("absent_user", PASSWORD))
|
||||
for http in [first, second] * 4
|
||||
]
|
||||
)
|
||||
assert sum(response.status_code == 401 for response in responses) == 2
|
||||
rejected = [response for response in responses if response.status_code == 429]
|
||||
assert len(rejected) == 6
|
||||
assert all(response.headers["retry-after"] == "60" for response in rejected)
|
||||
|
||||
|
||||
async def test_successful_login_upgrades_old_hash_without_changing_password(database: str) -> None:
|
||||
old = PasswordHasher(time_cost=1, memory_cost=8192, parallelism=1)
|
||||
async with running_app() as http:
|
||||
user = new_user("rehash")
|
||||
registered = await http.post("/api/v1/users", json=user)
|
||||
assert registered.status_code == 201
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(
|
||||
text("UPDATE users SET password_hash=:hash WHERE username=:username"),
|
||||
{"hash": old.hash(PASSWORD), "username": user["username"]},
|
||||
)
|
||||
response = await http.post(
|
||||
"/api/v1/auth/sessions", headers=basic(user["username"], PASSWORD)
|
||||
)
|
||||
assert response.status_code == 201
|
||||
async with sql_connection() as connection:
|
||||
current = (
|
||||
await connection.execute(
|
||||
text("SELECT password_hash FROM users WHERE username=:username"),
|
||||
{"username": user["username"]},
|
||||
)
|
||||
).scalar_one()
|
||||
assert "m=19456,t=2,p=1" in current
|
||||
assert old.verify(current, PASSWORD)
|
||||
@@ -0,0 +1,274 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from collections.abc import AsyncIterator, Iterator
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from dishka import Provider, Scope, make_async_container, provide
|
||||
from dishka_faststream import setup_dishka
|
||||
from faststream.rabbit import Channel, RabbitBroker
|
||||
|
||||
from conftest import ROOT, STARTUP_SECONDS, container, free_port, image, published
|
||||
from fakes import NullLogger
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import ProcessJob
|
||||
from messenger.attachments.application.ports import JobObserver
|
||||
from messenger.attachments.domain.jobs import Job, Outcome
|
||||
from messenger.attachments.entrypoints.worker import subscribe
|
||||
from messenger.attachments.infrastructure.rabbitmq import RabbitJobPublisher
|
||||
from messenger.attachments.infrastructure.telemetry import OtelJobObserver
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
RABBITMQ_IMAGE = re.compile(r"image: (rabbitmq:\S+)")
|
||||
PASSWORDS = {role: os.urandom(12).hex() for role in ("api", "worker", "ops")}
|
||||
GRANTS = {
|
||||
"api": ("^$", "^attachments$", "^$"),
|
||||
"worker": ("^$", "^$", "^attachments\\.process$"),
|
||||
"ops": (".*", ".*", ".*"),
|
||||
}
|
||||
|
||||
|
||||
def user(role: str) -> dict[str, Any]:
|
||||
salt = os.urandom(4)
|
||||
digest = hashlib.sha256(salt + PASSWORDS[role].encode()).digest()
|
||||
return {
|
||||
"name": f"messenger-{role}",
|
||||
"password_hash": base64.b64encode(salt + digest).decode(),
|
||||
"hashing_algorithm": "rabbit_password_hashing_sha256",
|
||||
"tags": ["administrator"] if role == "ops" else [],
|
||||
}
|
||||
|
||||
|
||||
def definitions() -> dict[str, Any]:
|
||||
return {
|
||||
"users": [user(role) for role in PASSWORDS],
|
||||
"permissions": [
|
||||
{
|
||||
"user": f"messenger-{role}",
|
||||
"vhost": "messenger",
|
||||
**dict(zip(("configure", "write", "read"), grant, strict=True)),
|
||||
}
|
||||
for role, grant in GRANTS.items()
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def ready(name: str) -> bool:
|
||||
probe = ["docker", "exec", name, "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
|
||||
return subprocess.run(probe, capture_output=True, check=False).returncode == 0
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def rabbitmq() -> Iterator[dict[str, Any]]:
|
||||
name = f"mtusi-lab6-test-rabbitmq-{uuid4().hex[:8]}"
|
||||
folder = ROOT / "build" / name
|
||||
folder.mkdir(parents=True)
|
||||
users = folder / "20-users.json"
|
||||
users.write_text(json.dumps(definitions()))
|
||||
users.chmod(0o644)
|
||||
infra = ROOT / "infra" / "rabbitmq"
|
||||
config = folder / "rabbitmq.conf"
|
||||
config.write_text((infra / "rabbitmq.conf").read_text().replace("127.0.0.1", "0.0.0.0"))
|
||||
mounts = [
|
||||
f"{config}:/etc/rabbitmq/conf.d/20-messenger.conf:ro",
|
||||
f"{infra / 'enabled_plugins'}:/etc/rabbitmq/enabled_plugins:ro",
|
||||
f"{infra / 'definitions.json'}:/etc/rabbitmq/definitions.d/10-topology.json:ro",
|
||||
f"{users}:/etc/rabbitmq/definitions.d/20-users.json:ro",
|
||||
]
|
||||
volumes = [part for mount in mounts for part in ("-v", mount)]
|
||||
container(
|
||||
name,
|
||||
"--hostname",
|
||||
"broker",
|
||||
"--user",
|
||||
"100:101",
|
||||
*volumes,
|
||||
"-p",
|
||||
f"127.0.0.1:{free_port()}:5672",
|
||||
image(RABBITMQ_IMAGE),
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + STARTUP_SECONDS * 2
|
||||
while not ready(name):
|
||||
assert time.monotonic() < deadline, "RabbitMQ не стал готов"
|
||||
time.sleep(1)
|
||||
port = published(name, 5672)
|
||||
urls = {
|
||||
role: f"amqp://messenger-{role}:{secret}@127.0.0.1:{port}/messenger"
|
||||
for role, secret in PASSWORDS.items()
|
||||
}
|
||||
yield {"name": name, "urls": urls}
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
|
||||
users.unlink()
|
||||
config.unlink()
|
||||
folder.rmdir()
|
||||
|
||||
|
||||
def depth(broker: dict[str, Any], queue: str) -> int:
|
||||
listing = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
broker["name"],
|
||||
"rabbitmqctl",
|
||||
"-q",
|
||||
"list_queues",
|
||||
"-p",
|
||||
"messenger",
|
||||
"name",
|
||||
"messages",
|
||||
"--formatter",
|
||||
"json",
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
text=True,
|
||||
).stdout
|
||||
return {row["name"]: row["messages"] for row in json.loads(listing)}[queue]
|
||||
|
||||
|
||||
async def wait_for(probe: Any, seconds: float = 20) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while not probe():
|
||||
assert time.monotonic() < deadline
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
class NoEvents:
|
||||
@asynccontextmanager
|
||||
async def transaction(self) -> AsyncIterator[None]:
|
||||
yield
|
||||
|
||||
async def commit(self) -> None: ...
|
||||
|
||||
def record(self, event: object) -> None: ...
|
||||
|
||||
def collect_new_events(self) -> list[Any]:
|
||||
return []
|
||||
|
||||
|
||||
class Recorder:
|
||||
def __init__(self) -> None:
|
||||
self.jobs: list[Job] = []
|
||||
self.failures = 0
|
||||
|
||||
async def __call__(self, command: ProcessJob) -> Outcome:
|
||||
if self.failures:
|
||||
self.failures -= 1
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
self.jobs.append(command.job)
|
||||
return Outcome.DONE
|
||||
|
||||
|
||||
class FakeBus(Provider):
|
||||
def __init__(self, recorder: Recorder) -> None:
|
||||
super().__init__()
|
||||
self._recorder = recorder
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def logger(self) -> Logger:
|
||||
return NullLogger()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def observer(self) -> JobObserver:
|
||||
return OtelJobObserver()
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def bus(self) -> AttachmentsCommandBus:
|
||||
return AttachmentsCommandBus({ProcessJob: self._recorder}, NoEvents(), NoPublisher())
|
||||
|
||||
|
||||
class NoPublisher:
|
||||
async def publish(self, events: Any) -> None: ...
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def worker(rabbitmq: dict[str, Any], recorder: Recorder) -> AsyncIterator[None]:
|
||||
broker = RabbitBroker(rabbitmq["urls"]["worker"], logger=None, graceful_timeout=2)
|
||||
subscribe(broker, 2)
|
||||
setup_dishka(make_async_container(FakeBus(recorder)), broker=broker, auto_inject=True)
|
||||
await broker.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await broker.stop()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def publisher(
|
||||
rabbitmq: dict[str, Any], role: str = "api"
|
||||
) -> AsyncIterator[RabbitJobPublisher]:
|
||||
broker = RabbitBroker(
|
||||
rabbitmq["urls"][role],
|
||||
default_channel=Channel(publisher_confirms=True, on_return_raises=True),
|
||||
logger=None,
|
||||
)
|
||||
await broker.connect()
|
||||
try:
|
||||
yield RabbitJobPublisher(broker, 5)
|
||||
finally:
|
||||
await broker.stop()
|
||||
|
||||
|
||||
def job() -> Job:
|
||||
return Job(uuid4(), uuid4(), 1, 1, datetime.now(UTC))
|
||||
|
||||
|
||||
def body(payload: dict[str, Any]) -> bytes:
|
||||
return json.dumps(payload).encode()
|
||||
|
||||
|
||||
async def test_confirmed_job_is_consumed_and_acked(rabbitmq: dict[str, Any]) -> None:
|
||||
recorder, sent = Recorder(), job()
|
||||
async with publisher(rabbitmq) as jobs:
|
||||
await jobs.publish(sent.id, body(sent.payload()))
|
||||
await wait_for(lambda: depth(rabbitmq, "attachments.process") == 1)
|
||||
async with worker(rabbitmq, recorder):
|
||||
await wait_for(lambda: recorder.jobs)
|
||||
await wait_for(lambda: depth(rabbitmq, "attachments.process") == 0)
|
||||
assert recorder.jobs == [sent]
|
||||
|
||||
|
||||
async def test_message_off_the_schema_goes_to_the_dead_letter_queue(
|
||||
rabbitmq: dict[str, Any],
|
||||
) -> None:
|
||||
before = depth(rabbitmq, "attachments.process.dlq")
|
||||
async with publisher(rabbitmq) as jobs:
|
||||
await jobs.publish(uuid4(), body({"schema_version": 2, "job_id": str(uuid4())}))
|
||||
async with worker(rabbitmq, Recorder()):
|
||||
await wait_for(lambda: depth(rabbitmq, "attachments.process.dlq") == before + 1)
|
||||
assert depth(rabbitmq, "attachments.process") == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failures", [1, 12])
|
||||
async def test_failed_processing_is_requeued_and_retried(
|
||||
rabbitmq: dict[str, Any], failures: int
|
||||
) -> None:
|
||||
recorder, sent = Recorder(), job()
|
||||
recorder.failures = failures
|
||||
before = depth(rabbitmq, "attachments.process.dlq")
|
||||
async with publisher(rabbitmq) as jobs:
|
||||
await jobs.publish(sent.id, body(sent.payload()))
|
||||
async with worker(rabbitmq, recorder):
|
||||
await wait_for(lambda: recorder.jobs, seconds=40)
|
||||
await wait_for(lambda: depth(rabbitmq, "attachments.process") == 0)
|
||||
assert recorder.jobs == [sent]
|
||||
assert depth(rabbitmq, "attachments.process.dlq") == before
|
||||
|
||||
|
||||
async def test_worker_account_cannot_publish(rabbitmq: dict[str, Any]) -> None:
|
||||
sent = job()
|
||||
with pytest.raises(Unavailable):
|
||||
async with publisher(rabbitmq, "worker") as jobs:
|
||||
await jobs.publish(sent.id, body(sent.payload()))
|
||||
@@ -0,0 +1,120 @@
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from collections.abc import AsyncIterator, Iterator
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from conftest import STARTUP_SECONDS, container, free_port, image, published
|
||||
from messenger.attachments.application.errors import ObjectMissingError
|
||||
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
RUSTFS_IMAGE = re.compile(r"image: (rustfs/rustfs:\S+)")
|
||||
ROOT_KEY, ROOT_SECRET = "testroot", "testroot-secret-key"
|
||||
BUCKET = "messenger-attachments"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def rustfs() -> Iterator[str]:
|
||||
name = f"mtusi-lab6-test-rustfs-{uuid4().hex[:8]}"
|
||||
keys = ["-e", f"RUSTFS_ACCESS_KEY={ROOT_KEY}", "-e", f"RUSTFS_SECRET_KEY={ROOT_SECRET}"]
|
||||
container(name, *keys, "-p", f"127.0.0.1:{free_port()}:9000", image(RUSTFS_IMAGE))
|
||||
try:
|
||||
endpoint = f"http://127.0.0.1:{published(name, 9000)}"
|
||||
deadline = time.monotonic() + STARTUP_SECONDS
|
||||
while True:
|
||||
try:
|
||||
if httpx.get(f"{endpoint}/health/ready", timeout=1).status_code == 200:
|
||||
break
|
||||
except httpx.TransportError:
|
||||
pass
|
||||
assert time.monotonic() < deadline, "RustFS не стал готов"
|
||||
time.sleep(0.3)
|
||||
yield endpoint
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def storage(endpoint: str) -> AsyncIterator[S3ObjectStorage]:
|
||||
async with s3_client(
|
||||
endpoint=endpoint,
|
||||
region="us-east-1",
|
||||
access_key_id=ROOT_KEY,
|
||||
secret_access_key=ROOT_SECRET,
|
||||
connect_timeout=1,
|
||||
read_timeout=2,
|
||||
max_attempts=2,
|
||||
) as client:
|
||||
buckets = await client.list_buckets()
|
||||
if BUCKET not in {bucket["Name"] for bucket in buckets.get("Buckets", [])}:
|
||||
await client.create_bucket(Bucket=BUCKET)
|
||||
yield S3ObjectStorage(client, BUCKET)
|
||||
|
||||
|
||||
async def test_round_trip_of_the_largest_object(rustfs: str) -> None:
|
||||
data = os.urandom(10_485_760)
|
||||
key = f"attachments/{uuid4()}"
|
||||
async with storage(rustfs) as objects:
|
||||
await objects.put(key, data, "image/png")
|
||||
content = await objects.open(key)
|
||||
assert content.size == len(data)
|
||||
assert b"".join([chunk async for chunk in content.chunks]) == data
|
||||
await objects.delete(key)
|
||||
with pytest.raises(ObjectMissingError):
|
||||
await objects.open(key)
|
||||
await objects.delete(key)
|
||||
|
||||
|
||||
async def test_listing_is_paged_in_byte_order_and_stat_reads_size(rustfs: str) -> None:
|
||||
prefix = f"reconcile-{uuid4().hex}/"
|
||||
keys = [f"{prefix}{name}" for name in ("b", "a", "Z", "a-1", "é")]
|
||||
async with storage(rustfs) as objects:
|
||||
for size, key in enumerate(keys, start=1):
|
||||
await objects.put(key, b"x" * size, "image/png")
|
||||
pages = [page async for page in objects.listing(prefix, 2)]
|
||||
assert [len(page) for page in pages] == [2, 2, 1]
|
||||
listed = [item.key for page in pages for item in page]
|
||||
assert listed == sorted(keys, key=str.encode)
|
||||
sizes = {item.key: item.size for page in pages for item in page}
|
||||
assert sizes == {key: size for size, key in enumerate(keys, start=1)}
|
||||
found = await objects.stat(keys[0])
|
||||
assert found is not None
|
||||
assert found.size == 1
|
||||
assert await objects.stat(f"{prefix}absent") is None
|
||||
for key in keys:
|
||||
await objects.delete(key)
|
||||
assert not [item async for page in objects.listing(prefix, 2) for item in page]
|
||||
|
||||
|
||||
async def test_unreachable_endpoint_is_unavailable_in_bounded_time() -> None:
|
||||
started = time.monotonic()
|
||||
async with storage_without_bucket("http://127.0.0.1:1") as objects:
|
||||
with pytest.raises(Unavailable):
|
||||
await objects.put("attachments/x", b"x", "image/png")
|
||||
with pytest.raises(Unavailable):
|
||||
await objects.open("attachments/x")
|
||||
with pytest.raises(Unavailable):
|
||||
await objects.stat("attachments/x")
|
||||
with pytest.raises(Unavailable):
|
||||
await anext(aiter(objects.listing("attachments/", 10)))
|
||||
assert time.monotonic() - started < 12
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def storage_without_bucket(endpoint: str) -> AsyncIterator[S3ObjectStorage]:
|
||||
async with s3_client(
|
||||
endpoint=endpoint,
|
||||
region="us-east-1",
|
||||
access_key_id=ROOT_KEY,
|
||||
secret_access_key=ROOT_SECRET,
|
||||
connect_timeout=1,
|
||||
read_timeout=2,
|
||||
max_attempts=2,
|
||||
) as client:
|
||||
yield S3ObjectStorage(client, BUCKET)
|
||||
Reference in New Issue
Block a user