117 lines
4.3 KiB
Python
117 lines
4.3 KiB
Python
"""Prepare a private fingerprint, then verify a restored DB and API without source DB."""
|
|
|
|
import hashlib
|
|
import json
|
|
import secrets
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
from uuid import UUID
|
|
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
|
|
from src.auth import token_hash
|
|
from src.db import database_url
|
|
|
|
|
|
TABLES = {
|
|
"users": "id",
|
|
"chats": "id",
|
|
"memberships": "chat_id,user_id",
|
|
"messages": "id",
|
|
"sessions": "token_hash",
|
|
}
|
|
|
|
|
|
def fingerprints(conn):
|
|
result = {}
|
|
for table, order in TABLES.items():
|
|
digest = hashlib.sha256()
|
|
count = 0
|
|
with conn.cursor(name="fingerprint_" + table) as cursor:
|
|
cursor.execute(f"SELECT * FROM {table} ORDER BY {order}")
|
|
for row in cursor:
|
|
digest.update(repr(tuple(row.values())).encode("utf-8"))
|
|
digest.update(b"\n")
|
|
count += 1
|
|
result[table] = {"count": count, "sha256": digest.hexdigest()}
|
|
return result
|
|
|
|
|
|
def samples(conn, chat_id):
|
|
found = []
|
|
for offset in (0, 39_999, 79_999):
|
|
row = conn.execute(
|
|
"SELECT id,text FROM messages WHERE chat_id=%s "
|
|
"ORDER BY created_at,id OFFSET %s LIMIT 1", (UUID(chat_id), offset)
|
|
).fetchone()
|
|
assert row is not None, "benchmark chat must contain 80000 messages"
|
|
found.append({"id": str(row["id"]), "text_sha256": hashlib.sha256(row["text"].encode()).hexdigest()})
|
|
return found
|
|
|
|
|
|
def request(url, token=None):
|
|
headers = {"Authorization": "Bearer " + token} if token else {}
|
|
try:
|
|
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=10) as response:
|
|
return response.status, json.load(response)
|
|
except urllib.error.HTTPError as error:
|
|
return error.code, None
|
|
|
|
|
|
def prepare():
|
|
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
|
|
chat = conn.execute(
|
|
"SELECT c.id,m.user_id FROM chats c JOIN memberships m ON m.chat_id=c.id "
|
|
"WHERE c.title='Track 2 hot' ORDER BY c.created_at DESC LIMIT 1"
|
|
).fetchone()
|
|
assert chat is not None
|
|
active = secrets.token_urlsafe(32)
|
|
expired = secrets.token_urlsafe(32)
|
|
conn.execute(
|
|
"INSERT INTO sessions(token_hash,user_id,expires_at) "
|
|
"VALUES (%s,%s,clock_timestamp()+interval '1 hour'),"
|
|
"(%s,%s,clock_timestamp()-interval '1 second')",
|
|
(token_hash(active), chat["user_id"], token_hash(expired), chat["user_id"]),
|
|
)
|
|
conn.commit()
|
|
expected = {
|
|
"chat_id": str(chat["id"]), "active_token": active, "expired_token": expired,
|
|
"tables": fingerprints(conn), "samples": samples(conn, str(chat["id"])),
|
|
}
|
|
print(json.dumps(expected)) # Redirect only into a temporary chmod-600 file.
|
|
|
|
|
|
def verify():
|
|
expected = json.load(sys.stdin)
|
|
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
|
|
actual_tables = fingerprints(conn)
|
|
actual_samples = samples(conn, expected["chat_id"])
|
|
assert actual_tables == expected["tables"], "restored table count/content mismatch"
|
|
assert actual_samples == expected["samples"], "restored selected message mismatch"
|
|
base = "http://127.0.0.1:8080"
|
|
assert request(base + "/health/ready")[0] == 200
|
|
status, page = request(base + "/api/v1/chats/" + expected["chat_id"] + "/messages?limit=50",
|
|
expected["active_token"])
|
|
assert status == 200
|
|
assert expected["samples"][0]["id"] in {item["id"] for item in page["items"]}
|
|
assert request(base + "/api/v1/chats/" + expected["chat_id"] + "/messages?limit=50",
|
|
expected["expired_token"])[0] == 401
|
|
print("Restore fingerprint PASS (all rows, ordered by primary key):")
|
|
for table, value in actual_tables.items():
|
|
print(f" {table}: count={value['count']} sha256={value['sha256']}")
|
|
print("Selected synthetic messages PASS (id, text SHA-256):")
|
|
for sample in actual_samples:
|
|
print(f" {sample['id']} {sample['text_sha256']}")
|
|
print("Restored API PASS: readiness 200, active token reads first message 200, expired token 401")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if sys.argv[1:] == ["prepare"]:
|
|
prepare()
|
|
elif sys.argv[1:] == ["verify"]:
|
|
verify()
|
|
else:
|
|
raise SystemExit("usage: test_restore.py prepare|verify")
|