[+] add project

This commit is contained in:
2026-11-10 23:47:45 +03:00
parent 65003b6119
commit 982fe0e6d2
19 changed files with 1398 additions and 25 deletions
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
import base64
import time
from datetime import datetime, timezone
from client import Client, Failure, arguments, check, run, timestamp
def main():
args = arguments("Short session expiry acceptance check")
client = Client(args.base_url, args.ca_file)
client.call("GET", "/health/ready", schema="Health")
username = "expiry_" + __import__("uuid").uuid4().hex[:16]
password = "Expiry-test-" + __import__("uuid").uuid4().hex
user = client.call(
"POST",
"/api/v1/users",
201,
body={
"username": username,
"display_name": "Expiry test",
"password": password,
},
schema="User",
)["json"]
basic = base64.b64encode((username + ":" + password).encode()).decode()
session = client.call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": "Basic " + basic},
schema="Session",
)["json"]
expires_at = timestamp(session["expires_at"])
remaining = (expires_at - datetime.now(timezone.utc)).total_seconds()
check(0 < remaining <= 5, "start API with SESSION_TTL_SECONDS=2 for this check")
client.call("GET", "/api/v1/users/me", actor={"id": user["id"], "token": session["token"]}, schema="User")
time.sleep(max(0, remaining) + 0.2)
client.call(
"GET",
"/api/v1/users/me",
expected=401,
actor={"id": user["id"], "token": session["token"]},
)
print("PASS: session expired at its configured deadline")
if __name__ == "__main__":
run(main)
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
import base64
import subprocess
from concurrent.futures import ThreadPoolExecutor
from client import Client, Failure, arguments, check, run
def main():
args = arguments("Grade 4 concurrency and dependency outage checks")
client = Client(args.base_url, args.ca_file, timeout=4)
client.call("GET", "/health/ready", schema="Health")
username = "race_" + __import__("uuid").uuid4().hex[:16]
password = "Concurrent-test-" + __import__("uuid").uuid4().hex
registration = {
"username": username,
"display_name": "Registration race",
"password": password,
}
def register_once():
return Client(args.base_url, args.ca_file, timeout=10).call(
"POST", "/api/v1/users", expected=[201, 409], body=registration
)["status"]
with ThreadPoolExecutor(max_workers=8) as executor:
statuses = list(executor.map(lambda _: register_once(), range(8)))
check(statuses.count(201) == 1, "concurrent registration created other than one user")
check(statuses.count(409) == 7, "duplicate registrations did not return 409")
credentials = base64.b64encode((username + ":wrong-password-123").encode()).decode()
client.call(
"POST",
"/api/v1/auth/sessions",
expected=401,
headers={"Authorization": "Basic " + credentials},
)
actor = client.user("grade4")
client.call("GET", "/api/v1/users/me", expected=401)
missing_id = str(__import__("uuid").uuid4())
rollback_title = "invalid-member-" + __import__("uuid").uuid4().hex
client.call(
"POST",
"/api/v1/chats",
expected=400,
actor=actor,
body={"title": rollback_title, "member_ids": [actor["id"], missing_id]},
)
chats = client.call(
"GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage"
)["json"]["items"]
check(all(chat["title"] != rollback_title for chat in chats), "invalid chat was persisted")
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
subprocess.run(
["docker", "compose", "stop", "redis"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
finally:
subprocess.run(
["docker", "compose", "start", "redis"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
client.call("GET", "/health/ready", schema="Health")
subprocess.run(
["docker", "compose", "stop", "postgres"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
client.call("GET", "/health/ready", expected=503)
client.call("GET", "/api/v1/users/me", expected=503, actor=actor)
finally:
subprocess.run(
["docker", "compose", "start", "postgres"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
for _ in range(60):
try:
client.call("GET", "/health/ready", schema="Health")
break
except Failure:
import time
time.sleep(1)
else:
raise Failure("PostgreSQL did not recover")
client.call("DELETE", "/api/v1/auth/sessions/current", expected=204, actor=actor)
client.call("GET", "/api/v1/users/me", expected=401, actor=actor)
print("PASS: registration race, invalid password, logout and dependency outages")
if __name__ == "__main__":
run(main)
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
import subprocess
import uuid
from client import Client, Failure, arguments, check, run
TRIGGER = "grade4_fail_member_insert"
FUNCTION = "grade4_fail_member_insert_fn"
def psql(sql, capture=False):
return subprocess.run(
[
"docker",
"compose",
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
"-At",
"-c",
sql,
],
check=True,
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
text=True,
).stdout if capture else ""
def cleanup():
result = psql(
"DROP TRIGGER IF EXISTS " + TRIGGER + " ON chat_members; "
"DROP FUNCTION IF EXISTS " + FUNCTION + "(); "
"SELECT count(*) FROM pg_trigger "
"WHERE tgrelid = 'public.chat_members'::regclass "
"AND tgname = '" + TRIGGER + "' AND NOT tgisinternal",
capture=True,
)
check(result.strip().splitlines()[-1:] == ["0"], "rollback test trigger cleanup failed")
def main():
args = arguments("Force a failure during chat membership insert and verify transaction rollback")
client = Client(args.base_url, args.ca_file)
actor = client.user("rollback")
other = client.user("rollback_member")
title = "rollback-" + uuid.uuid4().hex
setup_sql = (
"DROP TRIGGER IF EXISTS " + TRIGGER + " ON chat_members; "
"DROP FUNCTION IF EXISTS " + FUNCTION + "(); "
"CREATE FUNCTION " + FUNCTION + "() RETURNS trigger LANGUAGE plpgsql AS $$ "
"BEGIN IF EXISTS (SELECT 1 FROM chat_members WHERE chat_id = NEW.chat_id) "
"THEN RAISE EXCEPTION 'injected rollback test'; END IF; "
"RETURN NEW; END $$; "
"CREATE TRIGGER " + TRIGGER
+ " BEFORE INSERT ON chat_members FOR EACH ROW EXECUTE FUNCTION "
+ FUNCTION + "(); "
"SELECT count(*) FROM pg_trigger WHERE tgrelid = 'public.chat_members'::regclass "
"AND tgname = '" + TRIGGER + "' AND tgenabled = 'O'"
)
try:
setup_result = psql(setup_sql, capture=True).strip().splitlines()
check(setup_result and setup_result[-1] == "1", "rollback test trigger was not installed")
client.call(
"POST",
"/api/v1/chats",
expected=503,
actor=actor,
body={"title": title, "member_ids": [actor["id"], other["id"]]},
)
count = psql(
"SELECT count(*) FROM chats WHERE title = '" + title + "'",
capture=True,
).strip()
check(count == "0", "failed chat creation left a partial chat row")
finally:
cleanup()
print("PASS: injected membership failure rolled back the chat transaction")
if __name__ == "__main__":
run(main)