Реализовать лабораторную 4 на оценку 5

Добавить приватное S3-хранилище, вложения, presigned upload, reconciler и доказательства.
This commit is contained in:
Чиняева
2026-11-07 01:37:21 +03:00
parent ec540a1a72
commit f39ae06ef3
69 changed files with 5254 additions and 31 deletions
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Lab4 infrastructure checks: private bucket and no published admin UIs."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import urllib.error
import urllib.request
import uuid
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
ROOT = Path(__file__).resolve().parents[1]
def read_env() -> dict[str, str]:
values = dict(os.environ)
path = ROOT / ".env"
if path.is_file():
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
values.setdefault(key.strip(), value.strip())
return values
def s3_client(env: dict[str, str]):
return boto3.client(
"s3",
endpoint_url=env["S3_PUBLIC_ENDPOINT"],
region_name=env.get("S3_REGION", "us-east-1"),
aws_access_key_id=env["S3_ACCESS_KEY_ID"],
aws_secret_access_key=env["S3_SECRET_ACCESS_KEY"],
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
def check_public_ports() -> None:
result = subprocess.run(
["docker", "compose", "--env-file", ".env", "ps", "--format", "json"],
cwd=ROOT,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
raise AssertionError("could not inspect compose publishers")
services = [json.loads(line) for line in result.stdout.splitlines() if line.strip()]
for service in services:
name = service.get("Service") or service.get("Name", "")
publishers = service.get("Publishers") or []
published = [p for p in publishers if p.get("PublishedPort")]
if name == "seaweedfs":
ports = {int(p["PublishedPort"]) for p in published}
if ports != {int(os.environ.get("S3_PORT", read_env().get("S3_PORT", "9000")))}:
raise AssertionError(f"unexpected published SeaweedFS ports: {ports}")
elif name in ("api", "postgres", "redis", "migrate", "s3-init"):
if published:
raise AssertionError(f"{name} publishes a host port: {published}")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
del args
env = read_env()
for key in ("S3_PUBLIC_ENDPOINT", "S3_BUCKET", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"):
if not env.get(key):
raise AssertionError(f"missing {key} in environment/.env")
client = s3_client(env)
key = "reconcile-tests/private-bucket-" + uuid.uuid4().hex
client.put_object(Bucket=env["S3_BUCKET"], Key=key, Body=b"private", ContentType="text/plain")
try:
url = env["S3_PUBLIC_ENDPOINT"].rstrip("/") + "/" + env["S3_BUCKET"] + "/" + key
try:
urllib.request.urlopen(url, timeout=10)
except urllib.error.HTTPError as error:
if error.code not in (401, 403):
raise AssertionError(f"anonymous GET returned HTTP {error.code}, expected 403") from error
else:
raise AssertionError("anonymous GET succeeded on a private bucket")
for operation in ("create_bucket", "delete_bucket"):
try:
if operation == "create_bucket":
client.create_bucket(Bucket="forbidden-" + uuid.uuid4().hex[:12])
else:
client.delete_bucket(Bucket=env["S3_BUCKET"])
except ClientError as error:
if "AccessDenied" not in str(error):
raise AssertionError(f"{operation} failed with an unexpected error: {error}") from error
else:
raise AssertionError(f"restricted identity was allowed to {operation}")
finally:
client.delete_object(Bucket=env["S3_BUCKET"], Key=key)
check_public_ports()
print("PASS: bucket rejects anonymous reads; API identity cannot administer it; no admin UI is published")
if __name__ == "__main__":
main()