Complete lab 7 security implementation
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
"""lab7: worker per-job timeout. Подаём тяжёлый job напрямую в broker,
|
||||
минуя API-валидацию, и проверяем, что worker не зависает."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
BASE = sys.argv[sys.argv.index("--base-url") + 1] if "--base-url" in sys.argv else "https://localhost:8443"
|
||||
CA = sys.argv[sys.argv.index("--ca-file") + 1] if "--ca-file" in sys.argv else "infra/certs/ca.crt"
|
||||
JOB_TIMEOUT = int(sys.argv[sys.argv.index("--job-timeout") + 1]) if "--job-timeout" in sys.argv else 60
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None, raw=None, timeout=30):
|
||||
import ssl
|
||||
ctx = ssl.create_default_context(cafile=CA)
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
r = urllib.request.urlopen(req, context=ctx, timeout=timeout)
|
||||
p = r.read()
|
||||
return r.status, json.loads(p) if p else None
|
||||
except urllib.error.HTTPError as e:
|
||||
p = e.read()
|
||||
try:
|
||||
return e.code, json.loads(p) if p else None
|
||||
except Exception:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def s3_put_via_worker_container(key: str, data: bytes) -> None:
|
||||
"""Залить объект в S3 через контейнер worker (у него есть boto3 и TLS к S3).
|
||||
Данные передаём через stdin, чтобы не ловить 'embedded null byte'."""
|
||||
script = r"""
|
||||
import os, sys, boto3
|
||||
from botocore.client import Config
|
||||
body = sys.stdin.buffer.read()
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
|
||||
verify=os.environ.get("TLS_CA_FILE", "/run/secrets/ca.crt"),
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
|
||||
)
|
||||
s3.put_object(Bucket=os.environ["S3_BUCKET"], Key=os.environ["__KEY"], Body=body, ContentType="image/png")
|
||||
print("ok")
|
||||
"""
|
||||
env = ["-e", f"__KEY={key}"]
|
||||
r = subprocess.run(
|
||||
COMPOSE + ["exec", "-T", *env, "worker", "python", "-c", script],
|
||||
input=data, capture_output=True,
|
||||
)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError(f"s3 put failed: {r.stderr.decode(errors='replace')}")
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
r = subprocess.run(
|
||||
COMPOSE + ["exec", "-T", "postgres",
|
||||
"psql", "-U", "messenger", "-d", "messenger", "-t", "-A", "-c", sql],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError(f"psql failed: {r.stderr}")
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
# 1. Создать пользователя, чат
|
||||
username = "wto_" + uuid.uuid4().hex[:10]
|
||||
password = "wto-pass-1234567890"
|
||||
code, user = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "WTO", "password": password,
|
||||
})
|
||||
assert code == 201, f"register: {code} {user}"
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login: {code}"
|
||||
token = session["token"]
|
||||
code, chat = call("POST", "/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
body={"title": "WTO", "member_ids": [user["id"]]})
|
||||
assert code == 201, f"chat: {code}"
|
||||
chat_id = chat["id"]
|
||||
|
||||
# 2. Baseline: обычный файл через API
|
||||
fixture = Path("tests/fixtures/sample.png").read_bytes()
|
||||
code, att = call("POST", f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"},
|
||||
raw=fixture)
|
||||
assert code == 202, f"upload baseline: {code}"
|
||||
baseline_att_id = att["id"]
|
||||
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
code, a = call("GET", f"/api/v1/attachments/{baseline_att_id}",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
if code == 200 and a["status"] == "ready":
|
||||
break
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise AssertionError("baseline not ready in 60s")
|
||||
print(f"baseline ready: {baseline_att_id}")
|
||||
|
||||
# 3. Тяжёлый PNG (41M пикселей) — кладём в staging напрямую в S3
|
||||
from PIL import Image
|
||||
img = Image.new("RGB", (8200, 5000), color=(255, 0, 0))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG", compress_level=9)
|
||||
bomb = buf.getvalue()
|
||||
print(f"bomb PNG: {len(bomb)} bytes, 41M pixels")
|
||||
|
||||
staging_key = f"staging/slowtest-{uuid.uuid4().hex}.png"
|
||||
s3_put_via_worker_container(staging_key, bomb)
|
||||
|
||||
# 4. Вставить attachment + job в БД (минуя API-валидацию)
|
||||
att_id = str(uuid.uuid4())
|
||||
job_id = str(uuid.uuid4())
|
||||
sha = hashlib.sha256(bomb).hexdigest()
|
||||
psql(f"""
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, s3_key, staging_key, status, attempt, created_at, updated_at)
|
||||
VALUES ('{att_id}', '{chat_id}', '{user["id"]}', 'bomb.png', 'image/png', {len(bomb)}, '{sha}', '{staging_key}', '{staging_key}', 'queued', 0, NOW(), NOW());
|
||||
INSERT INTO jobs (job_id, attachment_id, pipeline_version, attempt, status, created_at)
|
||||
VALUES ('{job_id}', '{att_id}', 1, 1, 'pending', NOW());
|
||||
""")
|
||||
print(f"injected heavy job: attachment={att_id} job={job_id}")
|
||||
|
||||
# 5. Ждём, пока worker возьмёт job и таймаутнет
|
||||
started = time.monotonic()
|
||||
deadline = started + JOB_TIMEOUT + 120
|
||||
final_status = None
|
||||
while time.monotonic() < deadline:
|
||||
out = psql(f"SELECT status, COALESCE(error_code,'') FROM attachments WHERE id='{att_id}'")
|
||||
if out:
|
||||
status = out.split("|")[0]
|
||||
if status in ("failed", "ready"):
|
||||
final_status = status
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
elapsed = time.monotonic() - started
|
||||
assert final_status is not None, f"job neither failed nor ready in {JOB_TIMEOUT + 120}s"
|
||||
print(f"heavy job final status: {final_status} in {elapsed:.1f}s")
|
||||
|
||||
# 6. Worker жив — обработать ещё один обычный файл
|
||||
code, att2 = call("POST", f"/api/v1/chats/{chat_id}/attachments?filename=sample2.png",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"},
|
||||
raw=fixture)
|
||||
assert code == 202, f"upload after timeout: {code}"
|
||||
att2_id = att2["id"]
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
code, a = call("GET", f"/api/v1/attachments/{att2_id}",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
if code == 200 and a["status"] == "ready":
|
||||
print("PASS: worker survived heavy job, next file ready")
|
||||
return
|
||||
if code == 200 and a["status"] == "failed":
|
||||
raise AssertionError(f"next file failed: {a.get('error_code')}")
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("next file not ready in 60s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user