Добавил вложения и очистку
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import subprocess
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
|
||||
from helpers import Client, ROOT, arguments, cleanup_once, image_bytes, lab, object_exists, s3, sql, wait
|
||||
|
||||
|
||||
@contextmanager
|
||||
def fault(chat_id, action):
|
||||
name = "fault_" + uuid4().hex
|
||||
sql("CREATE FUNCTION " + name + "() RETURNS trigger LANGUAGE plpgsql AS $body$ BEGIN "
|
||||
"IF NEW.chat_id='" + chat_id + "'::uuid THEN " + action + "; END IF; RETURN NEW; END; $body$; "
|
||||
"CREATE TRIGGER " + name + " BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION " + name + "()")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
sql("DROP TRIGGER IF EXISTS " + name + " ON attachments; DROP FUNCTION IF EXISTS " + name + "()")
|
||||
|
||||
|
||||
def intent(chat, actor, key=None):
|
||||
identity = str(uuid4())
|
||||
key = key or "originals/" + uuid4().hex
|
||||
sql("INSERT INTO upload_intents(id,chat_id,owner_id,object_key) VALUES ('"
|
||||
+ identity + "','" + chat["id"] + "','" + actor["id"] + "','" + key + "')")
|
||||
return identity, key
|
||||
|
||||
|
||||
def age(identity):
|
||||
sql("UPDATE upload_intents SET created_at=clock_timestamp()-INTERVAL '11 minutes' WHERE id='" + identity + "'")
|
||||
|
||||
|
||||
def present(identity):
|
||||
return sql("SELECT count(*) FROM upload_intents WHERE id='" + identity + "'") == "1"
|
||||
|
||||
|
||||
def put(key):
|
||||
s3("c.put_object(Bucket=b,Key=" + repr(key) + ",Body=b'cleanup-test'); print('true')")
|
||||
|
||||
|
||||
def privacy(client, actor, chat):
|
||||
args = arguments()
|
||||
current = lab.states(args)
|
||||
networks = {}
|
||||
for name in ("api1", "s3", "s3-storage"):
|
||||
networks[name] = set(json.loads(lab.run(args, ["docker", "inspect", "--format",
|
||||
"{{json .NetworkSettings.Networks}}", current[name]["id"]], quiet=True)))
|
||||
assert not networks["api1"] & networks["s3-storage"], "Storage interfaces share the application network"
|
||||
assert networks["api1"] & networks["s3"] and networks["s3-storage"] & networks["s3"]
|
||||
for name in ("api1", "api2", "db", "s3", "s3-storage"):
|
||||
ports = json.loads(lab.run(args, ["docker", "inspect", "--format",
|
||||
"{{json .HostConfig.PortBindings}}", current[name]["id"]], quiet=True))
|
||||
assert not ports, "Internal service has public ports"
|
||||
att, raw = client.attachment(actor, chat)
|
||||
key = sql("SELECT object_key FROM attachments WHERE id='" + att["id"] + "'")
|
||||
anonymous = s3(
|
||||
"import boto3, os; from botocore import UNSIGNED; from botocore.config import Config; "
|
||||
"from botocore.exceptions import ClientError\n"
|
||||
"u=boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],config=Config(signature_version=UNSIGNED,proxies={}))\n"
|
||||
"try:\n u.get_object(Bucket=b,Key=" + repr(key) + "); status=200\n"
|
||||
"except ClientError as e:\n status=e.response['ResponseMetadata']['HTTPStatusCode']\n"
|
||||
"print(json.dumps(status))"
|
||||
)
|
||||
assert anonymous == 403, "Anonymous S3 access is allowed"
|
||||
other = "other-" + uuid4().hex
|
||||
forbidden = "forbidden-" + uuid4().hex
|
||||
s3("c.create_bucket(Bucket=" + repr(other) + "); "
|
||||
"c.put_object(Bucket=" + repr(other) + ",Key='private',Body=b'x'); print('true')")
|
||||
try:
|
||||
denied = s3(
|
||||
"from botocore.exceptions import ClientError\n"
|
||||
"checks=[('get_object',dict(Bucket=" + repr(other) + ",Key='private')),"
|
||||
"('create_bucket',dict(Bucket=" + repr(forbidden) + ")),"
|
||||
"('put_bucket_acl',dict(Bucket=b,ACL='public-read'))]\n"
|
||||
"result=[]\n"
|
||||
"for operation,values in checks:\n"
|
||||
" try:\n getattr(c,operation)(**values); result.append(200)\n"
|
||||
" except ClientError as e:\n result.append(e.response['ResponseMetadata']['HTTPStatusCode'])\n"
|
||||
"print(json.dumps(result))", admin=False,
|
||||
)
|
||||
assert denied == [403, 403, 403], "Application credentials are too broad"
|
||||
finally:
|
||||
s3("c.delete_object(Bucket=" + repr(other) + ",Key='private'); "
|
||||
"c.delete_bucket(Bucket=" + repr(other) + "); print('true')")
|
||||
lab.compose(arguments(), "run", "--rm", "--no-deps", "bootstrap")
|
||||
downloaded = client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=actor)["bytes"]
|
||||
assert downloaded == raw
|
||||
return {"anonymous_get": anonymous, "other_bucket_get": denied[0],
|
||||
"create_bucket": denied[1], "change_acl": denied[2], "bootstrap_replay": "PASS",
|
||||
"storage_network_isolated": True, "internal_ports_not_published": True}, att, key
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments()
|
||||
client = lab.client(args)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
result = {}
|
||||
lab.compose(args, "stop", "--timeout", "3", "cleanup")
|
||||
try:
|
||||
result["privacy"], good, good_key = privacy(client, alice, chat)
|
||||
fresh_id, fresh_key = intent(chat, alice)
|
||||
put(fresh_key)
|
||||
cleanup_once()
|
||||
assert present(fresh_id) and object_exists(fresh_key)
|
||||
result["fresh_intent_protected"] = "PASS"
|
||||
age(fresh_id)
|
||||
|
||||
lock_name = "lab4_lock_" + uuid4().hex
|
||||
command = ["docker", "compose", "--project-name", args.project, "--env-file", ".env",
|
||||
"exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c",
|
||||
"SET application_name='" + lock_name + "'; BEGIN; SELECT id FROM upload_intents WHERE id='"
|
||||
+ fresh_id + "' FOR UPDATE; SELECT pg_sleep(60); COMMIT"]
|
||||
with subprocess.Popen(command, cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as process:
|
||||
try:
|
||||
wait(lambda: sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='"
|
||||
+ lock_name + "' AND wait_event='PgSleep'") == "1", 10)
|
||||
cleanup_once()
|
||||
assert present(fresh_id) and object_exists(fresh_key)
|
||||
result["locked_intent_skipped"] = "PASS"
|
||||
finally:
|
||||
sql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='" + lock_name + "'")
|
||||
process.wait(timeout=10)
|
||||
cleanup_once()
|
||||
assert not present(fresh_id) and not object_exists(fresh_key)
|
||||
cleanup_once()
|
||||
result["orphan_removed_and_repeat_safe"] = "PASS"
|
||||
|
||||
protected_id, _ = intent(chat, alice, good_key)
|
||||
age(protected_id)
|
||||
cleaned = cleanup_once()
|
||||
assert cleaned["protected"] >= 1 and not present(protected_id) and object_exists(good_key)
|
||||
import hashlib
|
||||
protected = client.call("GET", "/api/v1/attachments/" + good["id"] + "/content", actor=bob)["bytes"]
|
||||
assert hashlib.sha256(protected).hexdigest() == good["sha256"]
|
||||
result["ready_unlinked_attachment_protected"] = "PASS"
|
||||
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?" + urlencode({"filename": "fault.png"})
|
||||
with fault(chat["id"], "RAISE EXCEPTION 'test failure after S3 write'"):
|
||||
client.call("POST", path, 500, actor=alice, raw=image_bytes(), headers={"Content-Type": "image/png"})
|
||||
row = json.loads(sql("SELECT row_to_json(x) FROM (SELECT id,object_key FROM upload_intents WHERE chat_id='"
|
||||
+ chat["id"] + "' ORDER BY created_at DESC LIMIT 1) x"))
|
||||
assert object_exists(row["object_key"])
|
||||
age(row["id"])
|
||||
cleanup_once()
|
||||
assert not present(row["id"]) and not object_exists(row["object_key"])
|
||||
result["sql_failure_after_put_compensated"] = "PASS"
|
||||
|
||||
mapping = lab.instance_map(args)
|
||||
addresses = {}
|
||||
for service, item in mapping.items():
|
||||
networks = json.loads(lab.run(args, ["docker", "inspect", "--format",
|
||||
"{{json .NetworkSettings.Networks}}", item["container_id"]], quiet=True))
|
||||
for network in networks.values():
|
||||
addresses[network["IPAddress"]] = service
|
||||
|
||||
def interrupted_upload():
|
||||
try:
|
||||
Client(lab.base_url(args), timeout=20).call(
|
||||
"POST", path, 201, actor=alice, raw=image_bytes(), headers={"Content-Type": "image/png"},
|
||||
)
|
||||
except (AssertionError, OSError):
|
||||
return
|
||||
|
||||
with fault(chat["id"], "PERFORM pg_sleep(30)"):
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
pending = pool.submit(interrupted_upload)
|
||||
def session():
|
||||
return sql("SELECT json_build_object('address',host(client_addr)) FROM pg_stat_activity "
|
||||
"WHERE wait_event='PgSleep' AND query LIKE 'INSERT INTO attachments%' LIMIT 1")
|
||||
wait(lambda: bool(session()), 10)
|
||||
service = addresses[json.loads(session())["address"]]
|
||||
row = json.loads(sql("SELECT row_to_json(x) FROM (SELECT id,object_key FROM upload_intents WHERE chat_id='"
|
||||
+ chat["id"] + "' ORDER BY created_at DESC LIMIT 1) x"))
|
||||
lab.run(args, ["docker", "kill", mapping[service]["container_id"]])
|
||||
pending.result(timeout=25)
|
||||
assert object_exists(row["object_key"]), "Fault was not injected after S3 PUT"
|
||||
lab.restore(args)
|
||||
assert present(row["id"])
|
||||
assert sql("SELECT count(*) FROM attachments WHERE id='" + row["id"] + "'") == "0"
|
||||
age(row["id"])
|
||||
cleanup_once()
|
||||
assert not present(row["id"]) and not object_exists(row["object_key"])
|
||||
result["api_killed_after_put_compensated"] = {"status": "PASS", "service": service}
|
||||
|
||||
retry_id, retry_key = intent(chat, alice)
|
||||
put(retry_key)
|
||||
age(retry_id)
|
||||
try:
|
||||
lab.compose(args, "stop", "--timeout", "3", "s3")
|
||||
cleanup_once(expected=False)
|
||||
assert present(retry_id)
|
||||
client.call("GET", "/health/live", schema="Health")
|
||||
lab.outage_response(args, "/health/ready")
|
||||
finally:
|
||||
lab.compose(args, "start", "s3")
|
||||
lab.wait_ready(args)
|
||||
cleanup_once()
|
||||
assert not present(retry_id) and not object_exists(retry_key)
|
||||
result["s3_outage_keeps_intent_then_recovers"] = "PASS"
|
||||
|
||||
import socket
|
||||
from urllib.parse import urlsplit
|
||||
endpoint = urlsplit(client.base)
|
||||
before = sql("SELECT count(*) FROM attachments WHERE chat_id='" + chat["id"] + "'")
|
||||
with socket.create_connection((endpoint.hostname, endpoint.port), timeout=5) as connection:
|
||||
request = ("POST " + path + " HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer "
|
||||
+ alice["token"] + "\r\nContent-Type: image/png\r\nContent-Length: 1000000\r\n\r\n")
|
||||
connection.sendall(request.encode("ascii") + image_bytes())
|
||||
import time
|
||||
time.sleep(0.5)
|
||||
assert sql("SELECT count(*) FROM attachments WHERE chat_id='" + chat["id"] + "'") == before
|
||||
assert sql("SELECT count(*) FROM upload_intents WHERE chat_id='" + chat["id"] + "'") == "0"
|
||||
result["client_disconnect_has_no_publication"] = "PASS"
|
||||
|
||||
worker_id, worker_key = intent(chat, alice)
|
||||
put(worker_key)
|
||||
age(worker_id)
|
||||
lab.compose(args, "start", "cleanup")
|
||||
wait(lambda: not present(worker_id), 45)
|
||||
assert not object_exists(worker_key)
|
||||
result["periodic_cleanup_worker"] = "PASS"
|
||||
lab.evidence("cleanup.json", result)
|
||||
print("PASS: private S3, restricted credentials, real faults and safe cleanup")
|
||||
finally:
|
||||
lab.compose(args, "start", "s3", "cleanup")
|
||||
lab.restore(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user