ЛР 7: безопасность, mTLS и OpenBao на оценку 3
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from uuid import UUID
|
||||
|
||||
from app.worker import async_session_maker, engine
|
||||
from app.models.attachment import Attachment
|
||||
|
||||
|
||||
async def main():
|
||||
attachment_id = UUID(sys.argv[1])
|
||||
|
||||
try:
|
||||
async with async_session_maker() as session:
|
||||
att = await session.get(Attachment, attachment_id)
|
||||
|
||||
if att is None:
|
||||
print("Attachment not found")
|
||||
return
|
||||
|
||||
print("Attachment ID:", att.id)
|
||||
print("Status:", att.status)
|
||||
print("Error code:", att.error_code)
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional checks against the local lab7 HTTPS endpoint."""
|
||||
import base64
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
import socket
|
||||
import ssl
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from client import Client, arguments, check, run, timestamp
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify lab7 login limit, body limit, foreign attachment, and optional session expiry",
|
||||
lambda parser: parser.add_argument("--expiry-only", action="store_true"))
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
if args.expiry_only:
|
||||
username = "expiry_" + uuid.uuid4().hex[:12]
|
||||
registration = {"username": username, "display_name": "Expiry", "password": "Пароль-" + uuid.uuid4().hex}
|
||||
client.call("POST", "/api/v1/users", 201, body=registration)
|
||||
auth = base64.b64encode(f"{username}:{registration['password']}".encode()).decode()
|
||||
session = client.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + auth}, schema="Session")["json"]
|
||||
actor = {"token": session["token"]}
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
until = (timestamp(session["expires_at"]) - datetime.now(timezone.utc)).total_seconds()
|
||||
check(0 < until < 30, "run expiry verification on a stand using SESSION_TTL_SECONDS=8")
|
||||
time.sleep(until + 0.6)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS HTTPS session works before TTL and returns 401 after expiry")
|
||||
return
|
||||
|
||||
context = ssl.create_default_context(cafile=args.ca_file or os.getenv('CA_FILE'))
|
||||
address = urlparse(client.base)
|
||||
try:
|
||||
with socket.create_connection((address.hostname, address.port or 443), timeout=5) as conn:
|
||||
with context.wrap_socket(conn, server_hostname="wrong-name.invalid"):
|
||||
raise AssertionError("incorrect TLS hostname accepted")
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
check(exc.verify_code == 62, "expected hostname mismatch")
|
||||
print("PASS HTTPS rejects an incorrect hostname with the trusted CA")
|
||||
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
other_chat = client.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "Another chat", "member_ids": [eve["id"], bob["id"]]},
|
||||
schema="Chat")["json"]
|
||||
client.call("POST", f"/api/v1/chats/{other_chat['id']}/messages", (400, 404),
|
||||
actor=eve, headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
body={"text": "Foreign attachment", "attachment_ids": [attachment["id"]]})
|
||||
print("PASS attachment cannot be linked into another chat")
|
||||
|
||||
request = Request(client.base + "/api/v1/users", data=b"x" * (10 * 1024**2 + 1), method="POST")
|
||||
try:
|
||||
urlopen(request, context=context, timeout=10)
|
||||
except HTTPError as exc:
|
||||
check(exc.code == 413, "oversize body must return 413")
|
||||
except BrokenPipeError:
|
||||
raise AssertionError("oversize body response was not observed") from None
|
||||
else:
|
||||
raise AssertionError("oversize body was accepted")
|
||||
print("PASS oversized body returns 413")
|
||||
|
||||
auth = base64.b64encode(b"unknown-user:invalid-password").decode()
|
||||
request = Request(client.base + "/api/v1/auth/sessions", method="POST",
|
||||
headers={"Authorization": "Basic " + auth})
|
||||
for _ in range(25):
|
||||
try:
|
||||
urlopen(request, context=context, timeout=5)
|
||||
except HTTPError as exc:
|
||||
with exc:
|
||||
check(exc.code in (401, 429), f"unexpected login status {exc.code}")
|
||||
if exc.code == 429:
|
||||
check(int(exc.headers.get("Retry-After", "0")) >= 1, "missing Retry-After")
|
||||
print("PASS login limit returns 429 with Retry-After")
|
||||
return
|
||||
else:
|
||||
raise AssertionError("login unexpectedly accepted")
|
||||
raise AssertionError("login limiter did not activate")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Verify retries with a synthetic missing object, using the local operator socket."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_CA = Path(os.environ.get("LAB7_STATE", ROOT / "secrets/lab7")) / "ca/ca.crt"
|
||||
|
||||
|
||||
def sql(statement, **values):
|
||||
arguments = [f"--set={key}={value}" for key, value in values.items()]
|
||||
subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "db", "psql", "-X", "-q",
|
||||
"--set=ON_ERROR_STOP=1", "-U", "messenger_admin", "-d", "messenger_db", *arguments],
|
||||
cwd=ROOT, input=statement, text=True, check=True,
|
||||
)
|
||||
|
||||
|
||||
def verify(base_url=None, ca_file=None):
|
||||
client = Client(base_url, ca_file or str(DEFAULT_CA))
|
||||
owner, _, _, chat = client.bootstrap()
|
||||
fixture = {
|
||||
"attachment_id": str(uuid.uuid4()),
|
||||
"event_id": str(uuid.uuid4()),
|
||||
"owner_id": str(uuid.UUID(owner["id"])),
|
||||
"chat_id": str(uuid.UUID(chat["id"])),
|
||||
}
|
||||
sql(
|
||||
"""
|
||||
BEGIN;
|
||||
INSERT INTO attachments (id, object_key, filename, mime_type, size_bytes, sha256,
|
||||
chat_id, user_id, status, created_at, updated_at)
|
||||
VALUES (:'attachment_id', 'originals/lab7-missing-' || :'attachment_id', 'missing.png',
|
||||
'image/png', 1, repeat('0', 64), :'chat_id', :'owner_id', 'queued', now(), now());
|
||||
INSERT INTO outbox_events (id, attachment_id) VALUES (:'event_id', :'attachment_id');
|
||||
COMMIT;
|
||||
""", **fixture,
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
response = client.call("GET", f"/api/v1/attachments/{fixture['attachment_id']}",
|
||||
actor=owner, schema="Attachment")["json"]
|
||||
if response["status"] == "failed":
|
||||
check(response["error_code"] == "s3_download_error", "incorrect worker error code")
|
||||
print("PASS HTTPS worker retry reached failed with s3_download_error")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("worker did not reach failed within 60 seconds")
|
||||
finally:
|
||||
sql(
|
||||
"BEGIN; DELETE FROM outbox_events WHERE attachment_id = :'attachment_id';"
|
||||
" DELETE FROM attachments WHERE id = :'attachment_id'; COMMIT;",
|
||||
attachment_id=fixture["attachment_id"],
|
||||
)
|
||||
|
||||
|
||||
def test_worker_retry():
|
||||
verify()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify worker retries on the local TLS-enabled compose stand")
|
||||
verify(args.base_url, args.ca_file)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user