ЛР 4: вложения в S3 и двусторонняя сверка хранилищ
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
# Собственные проверки HighLoad, лабораторная 4
|
||||
|
||||
S3-инфраструктура на `highload-lab4:8081`: [автоматические проверки и запуск](lab4/S3.md).
|
||||
Они подключены к прежнему `attachment_bucket_security` hook; результаты
|
||||
не подменяют проверку Go upload/download.
|
||||
|
||||
Один актуальный набор: [lab4/run.py](lab4/run.py), общий запуск
|
||||
[verify.py](verify.py), существовавшие собственные Go-проверки в `auth_tests/`.
|
||||
Go-проверки перенесены из собственных тестов lab2; устаревшие конструкторы
|
||||
обновлены до `NewMiddleware(auth, instanceID)` и
|
||||
`NewMessageRepository(queries, pool)`. HTTP/HA runner переиспользован из lab3
|
||||
и дополнен под контракт lab4. Соседние репозитории при запуске не нужны.
|
||||
Параллельного альтернативного набора для тех же сценариев нет.
|
||||
|
||||
`tests/`, `contracts/`, приложение, миграции и рабочие настройки не меняются.
|
||||
Тесты создают синтетические данные; restart/failover hooks останавливают
|
||||
процессы выбранного учебного проекта. Volumes не удаляются.
|
||||
|
||||
```sh
|
||||
# Запускать из HighLoad на учебном стенде. Выбрать именно свой project.
|
||||
export COMPOSE_PROJECT_NAME=highload-lab4
|
||||
python3 student-tests/verify.py --project "$COMPOSE_PROJECT_NAME" \
|
||||
--config student-tests/lab4/config.example.json \
|
||||
--output student-tests/results/run-01
|
||||
```
|
||||
|
||||
В конфигурации укажите **публичный адрес LB**, CA при HTTPS и hooks.
|
||||
Каталог результатов должен быть новым/пустым. Общий запуск включает
|
||||
`make check`, `go test -count=1 -json ./...`, проверки runner и все HTTP-сценарии,
|
||||
включая реальные вызовы публичных `make test`, `make test-persistence` и
|
||||
`make test-failover`. Для stand-alone Go достаточно `go test ./...`.
|
||||
При ограничениях на системный кэш: `GOCACHE=/private/tmp/highload-lab4-go-cache go test ./...`.
|
||||
|
||||
`PASS` означает выполненный конкретный сценарий. `FAIL` означает нарушение
|
||||
проверки; `PENDING_INFRA` — нет стенда, адаптера или фактических lifecycle
|
||||
доказательств. Ненулевой итоговый код возвращается и при FAIL, и при PENDING.
|
||||
Go `SKIP` сохраняются поимённо в общем summary и отдельно помечаются
|
||||
`PENDING_INFRA`: успешная сборка не доказывает проверку PostgreSQL/Redis/restart.
|
||||
|
||||
Для существующих Go-интеграционных проверок задаются
|
||||
`AUTH_TEST_DATABASE_URL`, `AUTH_TEST_REDIS_ADDR`, `AUTH_TEST_REDIS_RESTART_HOOK`,
|
||||
`AUTH_TEST_BASE_URL` (тот же публичный LB), `AUTH_TEST_STACK_RESTART_HOOK` и
|
||||
`MIGRATE_TEST_DATABASE_URL`. Используйте выделенные учебные stores; PostgreSQL
|
||||
фикстуры создают/удаляют собственные уникальные schemas, Redis-проверки
|
||||
перезапускают указанный Redis и работают с синтетическими ключами. DSN/пароли
|
||||
передавайте в окружении локально, не в команде/отчёте/Git. Наличие настройки
|
||||
не означает успешный тест: все assertions сохранены. Существующие проверки
|
||||
диагностики, durability и временных бюджетов — наши дополнительные требования
|
||||
качества там, где они строже обязательного контракта преподавателя.
|
||||
|
||||
Для транзакции сообщения с вложениями до подключения S3 добавлены проверки
|
||||
`TestMessageAttachments*` в том же Go-пакете. Они используют только
|
||||
`LAB4_TEST_DATABASE_URL` и общую изолированную PostgreSQL-фикстуру; Redis/S3
|
||||
не нужны. Запуск и точное покрытие — в разделе «Транзакция Message + attachments»
|
||||
[lab4/README.md](lab4/README.md). Без DSN — явный SKIP/PENDING, не PASS.
|
||||
Исключение — сервисная `TestMessageAttachmentsSingleIDServiceRegression`:
|
||||
она не требует внешних сервисов, ловит panic на одном вложении и проверяет
|
||||
два вызова с теми же значениями и UUID заглавными буквами. Реальную SQL-idempotency
|
||||
проверяют прежние PostgreSQL-группы, расширенные таким же неизменным JSON.
|
||||
|
||||
Подробные сценарии, границы доказательства и интерфейс адаптеров:
|
||||
[lab4/README.md](lab4/README.md). Итоговые результаты приведены в [REPORT.md](../REPORT.md). Прогон не выставляет оценку автоматически:
|
||||
lab4 на «4» требует всех критериев её уровня 3 и уровня 4; для «5» дополнительно
|
||||
нужен один завершённый исследовательский трек. Нагрузочные исследования на «5»
|
||||
в этот набор не включены.
|
||||
@@ -0,0 +1,538 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab2 auth acceptance tests. Uses the unchanged teacher HTTP client.
|
||||
|
||||
No server startup, automatic Docker actions, retries of writes or secret output.
|
||||
Infrastructure hooks run only in explicitly selected suites.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, LAB, check, timestamp # noqa: E402
|
||||
|
||||
LOGIN = "/api/v1/auth/sessions"
|
||||
LOGOUT = LOGIN + "/current"
|
||||
ME = "/api/v1/users/me"
|
||||
ARGS = None
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
value = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + value}
|
||||
|
||||
|
||||
def registration(password=None):
|
||||
return {
|
||||
"username": "auth_" + uuid.uuid4().hex[:20],
|
||||
"display_name": "Проверка auth",
|
||||
"password": password if password is not None else "Aa:" + uuid.uuid4().hex,
|
||||
}
|
||||
|
||||
|
||||
def new_client(timeout=None):
|
||||
return Client(ARGS.base_url, ARGS.ca_file, timeout=timeout or ARGS.timeout)
|
||||
|
||||
|
||||
def error(c, method, path, status, code, **kwargs):
|
||||
if LAB >= 3 and method == "POST" and path.endswith("/messages"):
|
||||
kwargs["headers"] = {**kwargs.get("headers", {}), "Idempotency-Key": uuid.uuid4().hex}
|
||||
response = c.call(method, path, status, **kwargs)
|
||||
check(response["json"]["error"]["code"] == code, "incorrect contract error code")
|
||||
if status == 401:
|
||||
challenge = ('Basic realm="messenger", charset="UTF-8"'
|
||||
if path == LOGIN else 'Bearer realm="messenger"')
|
||||
check(response["headers"].get("WWW-Authenticate") == challenge,
|
||||
"incorrect authentication challenge")
|
||||
return response
|
||||
|
||||
|
||||
def create_actor(c, password=None):
|
||||
body = registration(password)
|
||||
user = c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
session = c.call("POST", LOGIN, 201,
|
||||
headers=basic(body["username"], body["password"]), schema="Session")["json"]
|
||||
check(session["user"] == user, "login returned a different user")
|
||||
check(timestamp(session["expires_at"]) > dt.datetime.now(dt.timezone.utc),
|
||||
"new session is already expired")
|
||||
return {"id": user["id"], "user": user, "registration": body,
|
||||
"token": session["token"], "expires_at": session["expires_at"]}
|
||||
|
||||
|
||||
def login(c, actor):
|
||||
return c.call("POST", LOGIN, 201, schema="Session",
|
||||
headers=basic(actor["registration"]["username"],
|
||||
actor["registration"]["password"]))["json"]
|
||||
|
||||
|
||||
def chat(c, owner, members=None):
|
||||
members = members if members is not None else [owner["id"]]
|
||||
return c.call("POST", "/api/v1/chats", 201, actor=owner,
|
||||
body={"title": "Auth regression", "member_ids": members}, schema="Chat")["json"]
|
||||
|
||||
|
||||
class AuthContract(unittest.TestCase):
|
||||
"""Independent cases: a logout or rejection never poisons another test."""
|
||||
|
||||
def setUp(self):
|
||||
self.c = new_client()
|
||||
|
||||
def test_public_health_and_registration(self):
|
||||
for path in ("/health/live", "/health/ready"):
|
||||
with self.subTest(path=path):
|
||||
self.c.call("GET", path, schema="Health")
|
||||
body = registration()
|
||||
# Registration is public even when a stale credential is supplied.
|
||||
user = self.c.call("POST", "/api/v1/users", 201, body=body,
|
||||
headers={"Authorization": "Bearer invalid"}, schema="User")["json"]
|
||||
check(user["username"] == body["username"], "username changed")
|
||||
check(user["display_name"] == body["display_name"], "display_name changed")
|
||||
|
||||
def test_password_unicode_boundaries_and_colon(self):
|
||||
for label, password in (
|
||||
("ascii_min", "a" * 12), ("ascii_max", "b" * 128),
|
||||
("unicode_min", "😀" * 12), ("unicode_max", "😀" * 128),
|
||||
("colon", "начало:пароль:конец"),
|
||||
("spaces_are_significant", " significant-password "),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
actor = create_actor(self.c, password)
|
||||
me = self.c.call("GET", ME, actor=actor, schema="User")["json"]
|
||||
check(me == actor["user"], "current user differs from registration")
|
||||
altered = password.strip() if password != password.strip() else password + "x"
|
||||
error(self.c, "POST", LOGIN, 401, "unauthorized",
|
||||
headers=basic(actor["registration"]["username"], altered))
|
||||
|
||||
def test_invalid_password_length_and_blank(self):
|
||||
for label, value in (
|
||||
("empty", ""), ("ascii_short", "a" * 11), ("ascii_long", "a" * 129),
|
||||
("unicode_short", "😀" * 11), ("unicode_long", "😀" * 129),
|
||||
("blank_ascii", " " * 12), ("blank_unicode", "\u2003" * 12),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
body = registration(value)
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
|
||||
def test_registration_required_fields_types_and_names(self):
|
||||
for field in ("username", "display_name", "password"):
|
||||
for label, value in (("missing", None), ("null", None), ("integer", 1),
|
||||
("boolean", True), ("array", []), ("object", {})):
|
||||
with self.subTest(field=field, case=label):
|
||||
body = registration()
|
||||
if label == "missing":
|
||||
body.pop(field)
|
||||
else:
|
||||
body[field] = value
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
for alias in (field.upper(), field[0].upper() + field[1:]):
|
||||
for extra in (False, True):
|
||||
with self.subTest(field=field, alias=alias, extra=extra):
|
||||
body = registration()
|
||||
body[alias] = body[field] if extra else body.pop(field)
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
for root in (None, True, 1, "string", []):
|
||||
with self.subTest(root_type=type(root).__name__):
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
|
||||
raw=json.dumps(root).encode(), headers={"Content-Type": "application/json"})
|
||||
body = registration()
|
||||
body["sender_id"] = str(uuid.uuid4())
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
|
||||
def test_registration_bytes_json_and_content_type(self):
|
||||
for label, raw in (
|
||||
("empty", b""), ("malformed", b'{"username":'),
|
||||
("second_json", json.dumps(registration()).encode() + b"{}"),
|
||||
("trailing_garbage", json.dumps(registration()).encode() + b" garbage"),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
|
||||
raw=raw, headers={"Content-Type": "application/json"})
|
||||
for field in ("username", "display_name", "password"):
|
||||
for label, bad in (("ff", b"\xff"), ("overlong", b"\xc0\xaf"),
|
||||
("truncated", b"\xe2\x82"), ("surrogate", b"\xed\xa0\x80")):
|
||||
with self.subTest(field=field, encoding=label):
|
||||
body = registration()
|
||||
body[field] = "BYTE_MARKER"
|
||||
raw = json.dumps(body).encode().replace(b"BYTE_MARKER", b"prefix" + bad + b"suffix")
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
|
||||
raw=raw, headers={"Content-Type": "application/json"})
|
||||
for media in ("text/plain", "application/octet-stream"):
|
||||
with self.subTest(media=media):
|
||||
error(self.c, "POST", "/api/v1/users", 415, "unsupported_media_type",
|
||||
raw=json.dumps(registration()).encode(), headers={"Content-Type": media})
|
||||
|
||||
def test_username_and_display_name_constraints(self):
|
||||
for username in ("ab", "a" * 33, "ABC", "имя", "bad-name", "bad name", " bad"):
|
||||
with self.subTest(case="username", length=len(username)):
|
||||
body = registration()
|
||||
body["username"] = username
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
for name in ("", " \t\n", "\u00a0\u2003", "😀" * 101):
|
||||
with self.subTest(case="display_name", length=len(name)):
|
||||
body = registration()
|
||||
body["display_name"] = name
|
||||
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
for length in (1, 100):
|
||||
with self.subTest(case="valid_display_name", length=length):
|
||||
body = registration()
|
||||
body["display_name"] = "😀" * length
|
||||
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
check(user["display_name"] == body["display_name"], "Unicode display name changed")
|
||||
body = registration()
|
||||
body["username"] = uuid.uuid4().hex
|
||||
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
check(user["username"] == body["username"], "maximum-length username changed")
|
||||
|
||||
def test_wrong_credentials_have_same_public_error(self):
|
||||
actor = create_actor(self.c)
|
||||
responses = []
|
||||
for label, username, password in (
|
||||
("wrong_password", actor["registration"]["username"], "wrong-password"),
|
||||
("unknown_user", registration()["username"], actor["registration"]["password"]),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
responses.append(error(self.c, "POST", LOGIN, 401, "unauthorized",
|
||||
headers=basic(username, password)))
|
||||
if len(responses) == 2:
|
||||
check(responses[0]["json"]["error"]["message"] ==
|
||||
responses[1]["json"]["error"]["message"],
|
||||
"credentials errors reveal whether username exists")
|
||||
self.c.call("GET", ME, actor=actor, schema="User")
|
||||
|
||||
def test_login_rejects_missing_or_malformed_basic(self):
|
||||
actor = create_actor(self.c)
|
||||
encoded_no_colon = base64.b64encode(b"username-only").decode()
|
||||
for label, headers in (
|
||||
("absent", {}), ("legacy_id", {"X-User-Id": actor["id"]}),
|
||||
("bearer", {"Authorization": "Bearer " + actor["token"]}),
|
||||
("empty_basic", {"Authorization": "Basic"}),
|
||||
("invalid_base64", {"Authorization": "Basic !!!"}),
|
||||
("missing_separator", {"Authorization": "Basic " + encoded_no_colon}),
|
||||
("invalid_username_utf8", {"Authorization": "Basic " + base64.b64encode(b"\xffuser:synthetic-password").decode("ascii")}),
|
||||
("username_contains_nul", {"Authorization": "Basic " + base64.b64encode(b"bad\x00user:synthetic-password").decode("ascii")}),
|
||||
("wrong_scheme", {"Authorization": "Digest anything"}),
|
||||
("empty_password", basic(actor["registration"]["username"], "")),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
error(self.c, "POST", LOGIN, 401, "unauthorized", headers=headers)
|
||||
|
||||
def test_login_does_not_accept_json_credentials(self):
|
||||
actor = create_actor(self.c)
|
||||
body = {"username": actor["registration"]["username"],
|
||||
"password": actor["registration"]["password"]}
|
||||
# Authentication precedes payload validation.
|
||||
error(self.c, "POST", LOGIN, 401, "unauthorized", body=body)
|
||||
error(self.c, "POST", LOGIN, 400, "invalid_request", body=body,
|
||||
headers=basic(body["username"], body["password"]))
|
||||
|
||||
def test_protected_routes_require_bearer_before_validation(self):
|
||||
actor = create_actor(self.c)
|
||||
basic_headers = basic(actor["registration"]["username"], actor["registration"]["password"])
|
||||
unknown = str(uuid.uuid4())
|
||||
routes = (
|
||||
("GET", ME, None), ("GET", "/api/v1/chats", None),
|
||||
("POST", "/api/v1/chats", {"title": "", "member_ids": []}),
|
||||
("GET", "/api/v1/chats/" + unknown, None),
|
||||
("GET", "/api/v1/chats/not-a-uuid/messages?limit=0", None),
|
||||
("POST", "/api/v1/chats/" + unknown + "/messages", {"text": ""}),
|
||||
("DELETE", LOGOUT, None),
|
||||
)
|
||||
for method, path, body in routes:
|
||||
for label, headers in (
|
||||
("absent", {}), ("basic", basic_headers), ("legacy_id", {"X-User-Id": actor["id"]}),
|
||||
("empty_bearer", {"Authorization": "Bearer"}),
|
||||
("unknown_token", {"Authorization": "Bearer " + uuid.uuid4().hex * 2}),
|
||||
("space_in_token", {"Authorization": "Bearer invalid token"}),
|
||||
):
|
||||
with self.subTest(method=method, path=path, auth=label):
|
||||
error(self.c, method, path, 401, "unauthorized", body=body, headers=headers)
|
||||
|
||||
def test_identity_acl_and_sender_ignore_legacy_header(self):
|
||||
alice, bob, eve = (create_actor(self.c) for _ in range(3))
|
||||
room = chat(self.c, alice, [alice["id"], bob["id"]])
|
||||
path = "/api/v1/chats/" + room["id"]
|
||||
me = self.c.call("GET", ME, actor=alice, headers={"X-User-Id": eve["id"]},
|
||||
schema="User")["json"]
|
||||
check(me == alice["user"], "legacy ID overrode session identity")
|
||||
result = self.c.call("POST", path + "/messages", 201, actor=alice,
|
||||
headers={"X-User-Id": bob["id"],
|
||||
**({"Idempotency-Key": uuid.uuid4().hex} if LAB >= 3 else {})},
|
||||
body={"text": "Auth sender"}, schema="Message")["json"]
|
||||
check(result["sender_id"] == alice["id"], "sender not derived from session")
|
||||
for suffix in ("", "/messages"):
|
||||
error(self.c, "GET", path + suffix, 404, "not_found", actor=eve,
|
||||
headers={"X-User-Id": alice["id"]})
|
||||
error(self.c, "POST", path + "/messages", 404, "not_found", actor=eve,
|
||||
body={"text": "Forbidden"}, headers={"X-User-Id": alice["id"]})
|
||||
hidden = self.c.call("GET", "/api/v1/chats?limit=100", actor=eve,
|
||||
schema="ChatPage")["json"]
|
||||
check(all(item["id"] != room["id"] for item in hidden["items"]), "foreign chat leaked")
|
||||
page = self.c.call("GET", path + "/messages", actor=bob, schema="MessagePage")["json"]
|
||||
check(page["items"] == [result], "confirmed message is not immediately visible")
|
||||
error(self.c, "POST", path + "/messages", 400, "invalid_request", actor=alice,
|
||||
body={"text": "Forged sender", "sender_id": bob["id"]})
|
||||
|
||||
def test_invalid_chat_does_not_leave_visible_partial_chat(self):
|
||||
actor = create_actor(self.c)
|
||||
before = self.c.call("GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage")["json"]
|
||||
for members in ([actor["id"], str(uuid.uuid4())],
|
||||
[actor["id"], actor["id"]],
|
||||
[actor["id"], actor["id"].upper()], [str(uuid.uuid4())]):
|
||||
with self.subTest(member_count=len(members)):
|
||||
error(self.c, "POST", "/api/v1/chats", 400, "invalid_request", actor=actor,
|
||||
body={"title": "Must not exist", "member_ids": members})
|
||||
after = self.c.call("GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage")["json"]
|
||||
check(after == before, "rejected chat request left visible partial data")
|
||||
|
||||
def test_logout_revokes_only_current_session(self):
|
||||
actor = create_actor(self.c)
|
||||
other = login(self.c, actor)
|
||||
check(other["token"] != actor["token"], "separate logins reused a token")
|
||||
self.c.call("DELETE", LOGOUT, 204, actor=actor)
|
||||
error(self.c, "GET", ME, 401, "unauthorized", actor=actor)
|
||||
error(self.c, "DELETE", LOGOUT, 401, "unauthorized", actor=actor)
|
||||
second = dict(actor, token=other["token"])
|
||||
me = self.c.call("GET", ME, actor=second, schema="User")["json"]
|
||||
check(me == actor["user"], "logout revoked another session")
|
||||
fresh = login(self.c, actor)
|
||||
check(fresh["token"] not in (actor["token"], other["token"]), "login reused an earlier token")
|
||||
self.c.call("GET", ME, actor=dict(actor, token=fresh["token"]), schema="User")
|
||||
|
||||
def test_session_ttl_matches_configuration(self):
|
||||
actor = create_actor(self.c)
|
||||
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
check(ARGS.ttl - 5 <= remaining <= ARGS.ttl + 5, "SESSION_TTL_SECONDS not respected")
|
||||
for _ in range(3):
|
||||
self.c.call("GET", ME, actor=actor, schema="User")
|
||||
# Exact non-sliding deadline is checked by the storage and short-TTL suites.
|
||||
|
||||
def test_tokens_distinct_opaque_and_tamper_rejected(self):
|
||||
actor = create_actor(self.c)
|
||||
issued = [actor["token"]] + [login(self.c, actor)["token"] for _ in range(3)]
|
||||
check(len(set(issued)) == len(issued), "independent logins reused tokens")
|
||||
for token in issued:
|
||||
check(token != actor["id"] and token != actor["registration"]["username"],
|
||||
"token contains identity instead of an opaque credential")
|
||||
check(token != actor["registration"]["password"], "password used as session token")
|
||||
token = actor["token"]
|
||||
changed = token[:-1] + ("A" if token[-1] != "A" else "B")
|
||||
error(self.c, "GET", ME, 401, "unauthorized", actor=dict(actor, token=changed))
|
||||
self.c.call("GET", ME, actor=actor, schema="User")
|
||||
# Length/uniqueness is not proof of entropy. RNG is reviewed separately.
|
||||
|
||||
def test_duplicate_username_concurrent_registration(self):
|
||||
body = registration()
|
||||
barrier = threading.Barrier(4)
|
||||
|
||||
def send(index):
|
||||
c = new_client()
|
||||
candidate = dict(body, display_name="Race " + str(index), password=body["password"] + str(index))
|
||||
barrier.wait(timeout=ARGS.timeout)
|
||||
result = c.call("POST", "/api/v1/users", (201, 409), body=candidate, schema="User")
|
||||
if result["status"] == 409:
|
||||
check(result["json"]["error"]["code"] == "conflict", "race loser did not receive conflict")
|
||||
return candidate, result
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(send, range(4)))
|
||||
winners = [(body, result) for body, result in results if result["status"] == 201]
|
||||
check(len(winners) == 1, "username race must have exactly one winner")
|
||||
winner_body, result = winners[0]
|
||||
session = self.c.call("POST", LOGIN, 201, headers=basic(winner_body["username"],
|
||||
winner_body["password"]), schema="Session")["json"]
|
||||
check(session["user"] == result["json"], "race winner was overwritten")
|
||||
for candidate, response in results:
|
||||
if response["status"] == 409:
|
||||
error(self.c, "POST", LOGIN, 401, "unauthorized",
|
||||
headers=basic(candidate["username"], candidate["password"]))
|
||||
|
||||
|
||||
def hook(path):
|
||||
script = Path(path).expanduser().resolve()
|
||||
check(script.is_file() and os.access(script, os.X_OK), "hook must exist and be executable")
|
||||
check(".example." not in script.name, "implement a real hook first")
|
||||
try:
|
||||
result = subprocess.run([str(script)], stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, timeout=ARGS.hook_timeout)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
raise Failure("infrastructure hook failed or timed out; inspect it locally") from None
|
||||
check(result.returncode == 0, "infrastructure hook returned an error")
|
||||
|
||||
|
||||
def wait_ready(c):
|
||||
deadline = time.monotonic() + ARGS.hook_timeout
|
||||
while True:
|
||||
try:
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "API readiness did not recover")
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def expiry():
|
||||
c = new_client()
|
||||
actor = create_actor(c)
|
||||
start = time.monotonic()
|
||||
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
check(0 < remaining <= ARGS.ttl + 5, "short TTL not applied")
|
||||
c.call("GET", ME, actor=actor, schema="User")
|
||||
# Reading halfway must not renew the original deadline.
|
||||
time.sleep(max(0, remaining / 2))
|
||||
c.call("GET", ME, actor=actor, schema="User")
|
||||
time.sleep(max(0, remaining + 0.25 - (time.monotonic() - start)))
|
||||
error(c, "GET", ME, 401, "unauthorized", actor=actor)
|
||||
error(c, "DELETE", LOGOUT, 401, "unauthorized", actor=actor)
|
||||
fresh = login(c, actor)
|
||||
check(fresh["token"] != actor["token"], "expired token reused")
|
||||
c.call("GET", ME, actor=dict(actor, token=fresh["token"]), schema="User")
|
||||
|
||||
|
||||
def persistence():
|
||||
c = new_client(timeout=2)
|
||||
actor = create_actor(c)
|
||||
revoked = dict(actor, token=login(c, actor)["token"])
|
||||
c.call("DELETE", LOGOUT, 204, actor=revoked)
|
||||
room = chat(c, actor)
|
||||
original = c.message(actor, room, "Auth persistence")["json"]
|
||||
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
check(remaining > 2 * ARGS.hook_timeout + 10, "TTL too short for restart bounds")
|
||||
hook(ARGS.restart_hook)
|
||||
wait_ready(c)
|
||||
# No re-login before checking the original token.
|
||||
check(c.call("GET", ME, actor=actor, schema="User")["json"] == actor["user"],
|
||||
"original session/user did not survive restart")
|
||||
check(c.call("GET", "/api/v1/chats/" + room["id"], actor=actor, schema="Chat")["json"] == room,
|
||||
"chat/membership changed after restart")
|
||||
page = c.call("GET", "/api/v1/chats/" + room["id"] + "/messages",
|
||||
actor=actor, schema="MessagePage")["json"]
|
||||
check(page["items"] == [original], "confirmed message changed after restart")
|
||||
error(c, "GET", ME, 401, "unauthorized", actor=revoked)
|
||||
error(c, "DELETE", LOGOUT, 401, "unauthorized", actor=revoked)
|
||||
c.call("DELETE", LOGOUT, 204, actor=actor)
|
||||
error(c, "GET", ME, 401, "unauthorized", actor=actor)
|
||||
check(login(c, actor)["user"] == actor["user"], "password/user not persistent")
|
||||
# HTTP exposes expiry only at login. Storage test verifies deadline stability.
|
||||
|
||||
|
||||
def dependency():
|
||||
c = new_client()
|
||||
actor = create_actor(c)
|
||||
failures = []
|
||||
fallback_session = None
|
||||
revoked_during_outage = False
|
||||
sql_with_redis = ARGS.dependency == "postgres" and getattr(ARGS, "session_store", "redis") == "redis"
|
||||
if sql_with_redis:
|
||||
fallback_session = dict(actor, token=login(c, actor)["token"])
|
||||
|
||||
def observe(name, operation):
|
||||
try:
|
||||
operation()
|
||||
print("PASS:", name)
|
||||
return True
|
||||
except Failure as exc:
|
||||
failures.append(name + ": " + str(exc))
|
||||
print("FAIL:", name + ": " + str(exc))
|
||||
return False
|
||||
|
||||
try:
|
||||
hook(ARGS.failure_hook)
|
||||
observe("liveness during outage", lambda: c.call("GET", "/health/live", schema="Health"))
|
||||
critical = not (ARGS.dependency == "redis" and ARGS.cache_policy == "fallback")
|
||||
if critical:
|
||||
observe("readiness during outage", lambda: error(c, "GET", "/health/ready", 503, "unavailable"))
|
||||
observe("valid session during outage", lambda: error(c, "GET", ME, 503, "unavailable", actor=actor))
|
||||
else:
|
||||
observe("fallback readiness", lambda: c.call("GET", "/health/ready", schema="Health"))
|
||||
observe("fallback identity", lambda: c.call("GET", ME, actor=actor, schema="User"))
|
||||
for name, headers in (("missing auth", {}), ("legacy identity", {"X-User-Id": actor["id"]})):
|
||||
observe(name, lambda headers=headers: error(c, "GET", ME, 401, "unauthorized", headers=headers))
|
||||
# A syntactically valid Bearer cannot be declared unknown while the
|
||||
# sole session store is unavailable. The lookup failed, not identity.
|
||||
unknown_status = 503 if ARGS.dependency == "redis" and critical else 401
|
||||
observe("unknown bearer during outage", lambda: error(c, "GET", ME, unknown_status,
|
||||
"unavailable" if unknown_status == 503 else "unauthorized",
|
||||
headers={"Authorization": "Bearer " + uuid.uuid4().hex * 2}))
|
||||
if critical:
|
||||
observe("login during outage", lambda: error(c, "POST", LOGIN, 503, "unavailable",
|
||||
headers=basic(actor["registration"]["username"], actor["registration"]["password"])))
|
||||
if not critical:
|
||||
fallback_session = dict(actor, token=login(c, actor)["token"])
|
||||
if sql_with_redis or not critical:
|
||||
revoked_during_outage = observe("Redis logout independent of SQL", lambda: c.call("DELETE", LOGOUT, 204, actor=actor))
|
||||
else:
|
||||
observe("logout during outage", lambda: error(c, "DELETE", LOGOUT, 503, "unavailable", actor=actor))
|
||||
if ARGS.dependency == "postgres":
|
||||
body = registration()
|
||||
observe("registration during SQL outage", lambda: error(c, "POST", "/api/v1/users", 503, "unavailable", body=body))
|
||||
finally:
|
||||
hook(ARGS.recovery_hook)
|
||||
observe("readiness recovers", lambda: wait_ready(c))
|
||||
observe("liveness recovers", lambda: c.call("GET", "/health/live", schema="Health"))
|
||||
survivor = fallback_session or actor
|
||||
observe("independent session after recovery", lambda: c.call("GET", ME, actor=survivor, schema="User"))
|
||||
if revoked_during_outage:
|
||||
observe("logout remains revoked after recovery", lambda: error(c, "GET", ME, 401, "unauthorized", actor=actor))
|
||||
if ARGS.dependency == "postgres":
|
||||
observe("failed registration left no user", lambda: c.call("POST", "/api/v1/users", 201, body=body, schema="User"))
|
||||
check(not failures, "; ".join(failures))
|
||||
|
||||
|
||||
def main():
|
||||
global ARGS
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--ca-file", default=None)
|
||||
p.add_argument("--timeout", type=float, default=15)
|
||||
p.add_argument("--ttl", type=int, default=3600, help="actual server SESSION_TTL_SECONDS")
|
||||
p.add_argument("--suite", choices=("normal", "expiry", "persistence", "dependency"), default="normal")
|
||||
p.add_argument("--restart-hook")
|
||||
p.add_argument("--failure-hook")
|
||||
p.add_argument("--recovery-hook")
|
||||
p.add_argument("--dependency", choices=("postgres", "redis"))
|
||||
p.add_argument("--cache-policy", choices=("critical", "fallback"))
|
||||
p.add_argument("--session-store", choices=("postgres", "redis"), default="redis",
|
||||
help="declared session backend; controls logout expectation during a SQL outage")
|
||||
p.add_argument("--hook-timeout", type=float, default=90)
|
||||
ARGS = p.parse_args()
|
||||
if LAB not in (2, 3, 4):
|
||||
p.error("this suite targets the lab2 auth contract retained in lab3 and lab4")
|
||||
if ARGS.timeout <= 0 or ARGS.hook_timeout <= 0:
|
||||
p.error("timeouts must be positive")
|
||||
if ARGS.suite == "expiry":
|
||||
if not 2 <= ARGS.ttl <= 10:
|
||||
p.error("expiry needs a separately configured server with TTL 2..10")
|
||||
elif ARGS.ttl < 300:
|
||||
p.error("normal, restart and dependency suites require TTL >= 300")
|
||||
if ARGS.suite == "persistence" and not ARGS.restart_hook:
|
||||
p.error("persistence requires an explicit --restart-hook")
|
||||
if ARGS.suite == "dependency":
|
||||
if not (ARGS.failure_hook and ARGS.recovery_hook and ARGS.dependency):
|
||||
p.error("dependency suite needs failure/recovery hooks and the dependency name")
|
||||
if ARGS.dependency == "redis" and not ARGS.cache_policy:
|
||||
p.error("declare whether Redis is critical or has a safe fallback")
|
||||
if ARGS.suite == "normal":
|
||||
result = unittest.TextTestRunner(verbosity=2).run(
|
||||
unittest.defaultTestLoader.loadTestsFromTestCase(AuthContract))
|
||||
raise SystemExit(0 if result.wasSuccessful() else 1)
|
||||
try:
|
||||
{"expiry": expiry, "persistence": persistence, "dependency": dependency}[ARGS.suite]()
|
||||
except (Failure, ValueError, OSError) as exc:
|
||||
print("FAIL:", str(exc))
|
||||
raise SystemExit(1)
|
||||
print("PASS:", ARGS.suite, "(hook scope and runtime settings need separate evidence)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,217 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/service"
|
||||
"highload/internal/storage"
|
||||
"highload/internal/storage/s3"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
)
|
||||
|
||||
type cleanupRepo struct {
|
||||
repository.AttachmentRepository
|
||||
referenced map[string]bool
|
||||
busy string
|
||||
existsErr error
|
||||
checked []string
|
||||
locked string
|
||||
}
|
||||
|
||||
type cleanupTx struct{ repo *cleanupRepo }
|
||||
|
||||
func (tx cleanupTx) CreateAttachment(context.Context, repository.CreateAttachmentParams) (*model.Attachment, error) {
|
||||
return nil, errors.New("unexpected INSERT")
|
||||
}
|
||||
func (tx cleanupTx) GetAttachmentByID(context.Context, string) (*model.Attachment, error) {
|
||||
return nil, errors.New("unexpected attachment lookup")
|
||||
}
|
||||
func (tx cleanupTx) ExistsByObjectKey(ctx context.Context, key string) (bool, error) {
|
||||
r := tx.repo
|
||||
if r.locked != key {
|
||||
return false, errors.New("EXISTS outside locked transaction")
|
||||
}
|
||||
r.checked = append(r.checked, key)
|
||||
return r.referenced[key], r.existsErr
|
||||
}
|
||||
func (r *cleanupRepo) WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, repository.AttachmentTx) error) (bool, error) {
|
||||
if key == r.busy {
|
||||
return false, nil
|
||||
}
|
||||
r.locked = key
|
||||
defer func() { r.locked = "" }()
|
||||
return true, fn(ctx, cleanupTx{repo: r})
|
||||
}
|
||||
|
||||
type cleanupStore struct {
|
||||
pages map[string][]storage.ObjectInfo
|
||||
next map[string]string
|
||||
listed, deleted []string
|
||||
repo *cleanupRepo
|
||||
listErr, deleteErr error
|
||||
waitList bool
|
||||
}
|
||||
|
||||
func (s *cleanupStore) ListPage(ctx context.Context, token *string, prefix string) ([]storage.ObjectInfo, *string, error) {
|
||||
if prefix != "attachments/" {
|
||||
return nil, nil, errors.New("unexpected prefix")
|
||||
}
|
||||
if _, ok := ctx.Deadline(); !ok {
|
||||
return nil, nil, errors.New("LIST did not receive deadline")
|
||||
}
|
||||
if s.waitList {
|
||||
<-ctx.Done()
|
||||
return nil, nil, ctx.Err()
|
||||
}
|
||||
key := aws.ToString(token)
|
||||
s.listed = append(s.listed, key)
|
||||
if s.listErr != nil {
|
||||
return nil, nil, s.listErr
|
||||
}
|
||||
if next, ok := s.next[key]; ok {
|
||||
return s.pages[key], &next, nil
|
||||
}
|
||||
return s.pages[key], nil, nil
|
||||
}
|
||||
func (s *cleanupStore) Delete(_ context.Context, key string) error {
|
||||
if s.repo.locked != key {
|
||||
return errors.New("DELETE outside locked transaction")
|
||||
}
|
||||
s.deleted = append(s.deleted, key)
|
||||
return s.deleteErr
|
||||
}
|
||||
|
||||
func TestAttachmentCleanupPagesAndCutoff(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
now := time.Now()
|
||||
old := now.Add(-time.Minute - time.Nanosecond)
|
||||
orphan := "attachments/orphan"
|
||||
opts := &service.AttachmentCleanupOptions{GracePeriod: time.Minute, ListTimeout: time.Second}
|
||||
repo := &cleanupRepo{referenced: map[string]bool{"attachments/referenced": true}, busy: "attachments/busy"}
|
||||
objects := &cleanupStore{repo: repo, pages: map[string][]storage.ObjectInfo{
|
||||
"": {{Key: "attachments/equal", LastModified: now.Add(-time.Minute)},
|
||||
{Key: "attachments/fresh", LastModified: now.Add(-time.Second)},
|
||||
{Key: "attachments/future", LastModified: now.Add(time.Hour)},
|
||||
{Key: "attachments/zero"},
|
||||
{Key: "other/orphan", LastModified: old},
|
||||
{Key: "attachments/busy", LastModified: old}},
|
||||
"last": {{Key: "attachments/referenced", LastModified: old}, {Key: orphan, LastModified: old}},
|
||||
}, next: map[string]string{"": "empty", "empty": "last"}}
|
||||
svc := service.NewAttachmentCleanupService(repo, objects, opts)
|
||||
opts.DryRun = true
|
||||
if err := svc.RunOnce(context.Background()); err != nil || len(objects.deleted) != 0 ||
|
||||
!slices.Equal(repo.checked, []string{"attachments/referenced", orphan}) {
|
||||
t.Fatalf("dry-run must check old unlocked keys without deleting: err=%v checked=%v deletes=%v", err, repo.checked, objects.deleted)
|
||||
}
|
||||
opts.DryRun = false
|
||||
objects.listed = nil
|
||||
if err := svc.RunOnce(context.Background()); err != nil || !slices.Equal(objects.listed, []string{"", "empty", "last"}) ||
|
||||
!slices.Equal(objects.deleted, []string{orphan}) {
|
||||
t.Fatalf("wrong cutoff or page walk: err=%v pages=%v deletes=%v", err, objects.listed, objects.deleted)
|
||||
}
|
||||
})
|
||||
}
|
||||
func TestAttachmentCleanupFaults(t *testing.T) {
|
||||
for _, name := range []string{"list", "exists", "delete", "list_timeout", "pass_timeout", "canceled"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
repo := &cleanupRepo{}
|
||||
objects := &cleanupStore{repo: repo, pages: map[string][]storage.ObjectInfo{"": {{Key: "attachments/old", LastModified: time.Now().Add(-time.Hour)}}}}
|
||||
svc := service.NewAttachmentCleanupService(repo, objects, &service.AttachmentCleanupOptions{GracePeriod: time.Second, ListTimeout: time.Second})
|
||||
sentinel := errors.New("synthetic " + name + " error")
|
||||
var want error = sentinel
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
switch name {
|
||||
case "list":
|
||||
objects.listErr = sentinel
|
||||
case "exists":
|
||||
repo.existsErr = sentinel
|
||||
case "delete":
|
||||
objects.deleteErr = sentinel
|
||||
case "list_timeout":
|
||||
objects.waitList = true
|
||||
want = context.DeadlineExceeded
|
||||
case "pass_timeout":
|
||||
var stop context.CancelFunc
|
||||
ctx, stop = context.WithTimeout(ctx, 100*time.Millisecond)
|
||||
defer stop()
|
||||
objects.waitList = true
|
||||
want = context.DeadlineExceeded
|
||||
case "canceled":
|
||||
cancel()
|
||||
want = context.Canceled
|
||||
}
|
||||
start := time.Now()
|
||||
got := svc.RunOnce(ctx)
|
||||
if !errors.Is(got, want) {
|
||||
t.Fatalf("want %v, got %v", want, got)
|
||||
}
|
||||
if (name == "list_timeout" && time.Since(start) != time.Second) ||
|
||||
(name == "pass_timeout" && time.Since(start) != 100*time.Millisecond) {
|
||||
t.Fatal("wrong cancellation budget")
|
||||
}
|
||||
if name != "delete" && len(objects.deleted) > 0 {
|
||||
t.Fatal("DELETE ran after unsafe precondition")
|
||||
}
|
||||
if name == "delete" && len(objects.deleted) != 1 {
|
||||
t.Fatal("DELETE fault not reached")
|
||||
}
|
||||
repo.existsErr, objects.listErr, objects.deleteErr = nil, nil, nil
|
||||
objects.waitList = false
|
||||
objects.deleted = nil
|
||||
if err := svc.RunOnce(context.Background()); err != nil || !slices.Equal(objects.deleted, []string{"attachments/old"}) {
|
||||
t.Fatalf("cleanup did not recover: %v %v", err, objects.deleted)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type cleanupListTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (fn cleanupListTransport) Do(req *http.Request) (*http.Response, error) { return fn(req) }
|
||||
|
||||
func TestAttachmentCleanupS3InvalidNextToken(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
token *string
|
||||
xml string
|
||||
}{
|
||||
{"missing", nil, ""},
|
||||
{"empty", nil, "<NextContinuationToken></NextContinuationToken>"},
|
||||
{"repeat", aws.String("same"), "<NextContinuationToken>same</NextContinuationToken>"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
n := 0
|
||||
obj := &s3.Storage{Bucket: "test", Client: awss3.New(awss3.Options{
|
||||
Region: "us-east-1", UsePathStyle: true, BaseEndpoint: aws.String("http://cleanup.invalid"),
|
||||
Credentials: aws.AnonymousCredentials{}, Retryer: aws.NopRetryer{},
|
||||
HTTPClient: cleanupListTransport(func(req *http.Request) (*http.Response, error) {
|
||||
n++
|
||||
if req.URL.Query().Get("continuation-token") != aws.ToString(tc.token) {
|
||||
return nil, errors.New("wrong request token")
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(
|
||||
"<ListBucketResult><IsTruncated>true</IsTruncated>" + tc.xml + "</ListBucketResult>"))}, nil
|
||||
}),
|
||||
})}
|
||||
_, _, err := obj.ListPage(context.Background(), tc.token, "attachments/")
|
||||
if !errors.Is(err, storage.ErrStorage) || n != 1 {
|
||||
t.Fatalf("invalid token was not rejected: %v, calls=%d", err, n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
repo "highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/storage"
|
||||
"highload/internal/storage/s3"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func newAttachmentTxFixture(t *testing.T) (*fixture, repo.CreateAttachmentParams) {
|
||||
t.Helper()
|
||||
f := newDatabaseFixture(t, "LAB4_TEST_DATABASE_URL", 4)
|
||||
owner := uuid.NewString()
|
||||
if _, err := f.pool.Exec(f.ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,'tx_fixture','TX fixture','unused')", owner); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat, err := postgres.NewChatRepository(f.queries, f.pool).CreateChat(f.ctx, "Attachment transaction", []string{owner})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f, repo.CreateAttachmentParams{
|
||||
ChatID: chat.ID, OwnerID: owner, ObjectKey: "attachments/" + uuid.NewString(),
|
||||
Filename: "fixture.png", ContentType: "image/png", SizeBytes: 1, Sha256: strings.Repeat("a", 64),
|
||||
}
|
||||
}
|
||||
|
||||
func assertAttachmentCount(t *testing.T, f *fixture, want int) {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := f.pool.QueryRow(f.ctx, "SELECT count(*) FROM attachments").Scan(&count); err != nil || count != want {
|
||||
t.Fatalf("expected %d committed attachments, got %d (%v)", want, count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentTxLockAndRollback(t *testing.T) {
|
||||
f, params := newAttachmentTxFixture(t)
|
||||
// Run the isolation check on the very connection doing the callback INSERT.
|
||||
// A query through the pool would only establish the observer's isolation.
|
||||
if _, err := f.pool.Exec(f.ctx, `
|
||||
CREATE FUNCTION assert_attachment_isolation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF current_setting('transaction_isolation') <> 'read committed' THEN
|
||||
RAISE EXCEPTION 'expected read committed during attachment INSERT';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER assert_attachment_isolation BEFORE INSERT ON attachments
|
||||
FOR EACH ROW EXECUTE FUNCTION assert_attachment_isolation();
|
||||
`, pgx.QueryExecModeSimpleProtocol); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
attachments := postgres.NewAttachmentRepository(f.queries, f.pool)
|
||||
key := params.ObjectKey
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
type outcome struct {
|
||||
locked bool
|
||||
err error
|
||||
}
|
||||
done := make(chan outcome, 1)
|
||||
holdCtx, cancelHold := context.WithCancel(f.ctx)
|
||||
defer cancelHold()
|
||||
go func() {
|
||||
locked, err := attachments.WithObjectKeyLock(holdCtx, key, func(ctx context.Context, _ repo.AttachmentTx) error {
|
||||
close(entered)
|
||||
select {
|
||||
case <-release:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
})
|
||||
done <- outcome{locked, err}
|
||||
}()
|
||||
select {
|
||||
case <-entered:
|
||||
case result := <-done:
|
||||
t.Fatalf("holder never entered callback: %+v", result)
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("holder did not acquire the lock")
|
||||
}
|
||||
unexpected := func(context.Context, repo.AttachmentTx) error {
|
||||
return errors.New("contending callback ran")
|
||||
}
|
||||
if locked, err := attachments.WithObjectKeyLock(f.ctx, key, unexpected); locked || err != nil {
|
||||
t.Fatalf("same key must return false, nil without callback: %t, %v", locked, err)
|
||||
}
|
||||
noop := func(context.Context, repo.AttachmentTx) error { return nil }
|
||||
if locked, err := attachments.WithObjectKeyLock(f.ctx, key+"-other", noop); !locked || err != nil {
|
||||
t.Fatalf("another key was blocked: %t, %v", locked, err)
|
||||
}
|
||||
close(release)
|
||||
select {
|
||||
case result := <-done:
|
||||
if !result.locked || result.err != nil {
|
||||
t.Fatalf("holder did not complete: %+v", result)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("holder did not close its transaction")
|
||||
}
|
||||
if locked, err := attachments.WithObjectKeyLock(f.ctx, key, noop); !locked || err != nil {
|
||||
t.Fatalf("committed lock was not released: %t, %v", locked, err)
|
||||
}
|
||||
|
||||
for _, name := range []string{"callback_error", "context_canceled"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
sentinel := errors.New("synthetic callback failure")
|
||||
ctx, cancel := context.WithCancel(f.ctx)
|
||||
defer cancel()
|
||||
want := error(sentinel)
|
||||
if name == "context_canceled" {
|
||||
want = context.Canceled
|
||||
}
|
||||
locked, err := attachments.WithObjectKeyLock(ctx, key, func(txCtx context.Context, tx repo.AttachmentTx) error {
|
||||
if _, err := tx.CreateAttachment(txCtx, params); err != nil {
|
||||
return err
|
||||
}
|
||||
exists, err := tx.ExistsByObjectKey(txCtx, key)
|
||||
if err != nil || !exists {
|
||||
return fmt.Errorf("transaction did not see its INSERT: %w", err)
|
||||
}
|
||||
assertAttachmentCount(t, f, 0)
|
||||
if name == "context_canceled" {
|
||||
cancel()
|
||||
return txCtx.Err()
|
||||
}
|
||||
return sentinel
|
||||
})
|
||||
if !locked || err != want {
|
||||
t.Fatalf("callback error must pass through unchanged with true: %t, %v", locked, err)
|
||||
}
|
||||
assertAttachmentCount(t, f, 0)
|
||||
if locked, err = attachments.WithObjectKeyLock(f.ctx, key, noop); !locked || err != nil {
|
||||
t.Fatalf("rollback failed to free lock/pool: %t, %v", locked, err)
|
||||
}
|
||||
t.Log("INSERT ran at read committed, rollback left zero rows and released the lock")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// txS3Transport observes the real SDK requests and retains synthetic bytes for GET.
|
||||
// Before accepting a PUT it challenges the lock from a separate PostgreSQL session.
|
||||
type txS3Transport struct {
|
||||
fixture *fixture
|
||||
key string
|
||||
data []byte
|
||||
put, get, delete int
|
||||
failPut bool
|
||||
}
|
||||
|
||||
func (s *txS3Transport) Do(request *http.Request) (*http.Response, error) {
|
||||
resp := &http.Response{StatusCode: 200, Header: make(http.Header), Body: http.NoBody}
|
||||
key := strings.TrimPrefix(request.URL.Path, "/tx-test/")
|
||||
if !strings.HasPrefix(key, "attachments/") {
|
||||
return nil, errors.New("unexpected synthetic S3 key")
|
||||
}
|
||||
switch request.Method {
|
||||
case http.MethodPut:
|
||||
s.put++
|
||||
s.key = key
|
||||
var acquired bool
|
||||
err := s.fixture.pool.QueryRow(request.Context(),
|
||||
"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))", key).Scan(&acquired)
|
||||
if err != nil || acquired {
|
||||
return nil, fmt.Errorf("PUT ran without held object lock: acquired=%t, error=%v", acquired, err)
|
||||
}
|
||||
if s.failPut {
|
||||
resp.StatusCode = 503
|
||||
resp.Header.Set("Content-Type", "application/xml")
|
||||
resp.Body = io.NopCloser(strings.NewReader("<Error><Code>SlowDown</Code><Message>Synthetic outage</Message></Error>"))
|
||||
return resp, nil
|
||||
}
|
||||
defer request.Body.Close()
|
||||
s.data, err = io.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case http.MethodGet:
|
||||
s.get++
|
||||
if key != s.key || s.data == nil {
|
||||
return nil, errors.New("object unavailable in fixture")
|
||||
}
|
||||
resp.Body = io.NopCloser(bytes.NewReader(s.data))
|
||||
resp.ContentLength = int64(len(s.data))
|
||||
case http.MethodDelete:
|
||||
s.delete++
|
||||
s.data = nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected S3 method %s", request.Method)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func TestAttachmentTxHTTP(t *testing.T) {
|
||||
_, source, _, _ := runtime.Caller(0)
|
||||
png, err := os.ReadFile(filepath.Join(filepath.Dir(source), "../../tests/fixtures/sample.png"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash := fmt.Sprintf("%x", sha256.Sum256(png))
|
||||
for _, scenario := range []struct {
|
||||
name string
|
||||
faultSQL string
|
||||
http int
|
||||
errorCode string
|
||||
}{
|
||||
{name: "s3_unavailable", http: 503, errorCode: "unavailable"},
|
||||
{name: "insert_after_put", faultSQL: "ALTER TABLE attachments ADD CHECK (filename <> 'fixture.png')", http: 500, errorCode: "internal_error"},
|
||||
{name: "commit_after_insert", faultSQL: `
|
||||
CREATE FUNCTION reject_attachment_commit() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'synthetic deferred failure'; END $$;
|
||||
CREATE CONSTRAINT TRIGGER reject_attachment_commit AFTER INSERT ON attachments
|
||||
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_attachment_commit();
|
||||
`, http: 500, errorCode: "internal_error"},
|
||||
{name: "committed_upload_and_get", http: 201},
|
||||
} {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
f, params := newAttachmentTxFixture(t)
|
||||
if scenario.faultSQL != "" {
|
||||
if _, err := f.pool.Exec(f.ctx, scenario.faultSQL, pgx.QueryExecModeSimpleProtocol); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
transport := &txS3Transport{fixture: f, failPut: scenario.http == 503}
|
||||
objects := &s3.Storage{Bucket: "tx-test", Client: awss3.New(awss3.Options{
|
||||
Region: "us-east-1", UsePathStyle: true, BaseEndpoint: aws.String("http://tx-s3.invalid"),
|
||||
Credentials: aws.AnonymousCredentials{}, Retryer: aws.NopRetryer{}, HTTPClient: transport,
|
||||
})}
|
||||
chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), nil, nil)
|
||||
attachments := postgres.NewAttachmentRepository(f.queries, f.pool)
|
||||
svc := service.NewAttachmentService(attachments, chats, objects)
|
||||
h := handler.NewAttachmentHandler(svc)
|
||||
call := func(method, path, param, value string, data []byte, next http.HandlerFunc) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, bytes.NewReader(data))
|
||||
r = r.WithContext(middleware.WithUserID(f.ctx, params.OwnerID))
|
||||
r.SetPathValue(param, value)
|
||||
r.Header.Set("Content-Type", "image/png")
|
||||
w := httptest.NewRecorder()
|
||||
mid := middleware.NewMiddleware(nil, "attachment-tx")
|
||||
mid.InstanceID(mid.RequestID(next)).ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
w := call(http.MethodPost, "/attachments?filename=fixture.png", "chat_id", params.ChatID, png, h.CreateAttachment)
|
||||
if transport.put != 1 || transport.delete != 0 {
|
||||
t.Fatalf("expected one PUT and zero DELETE, got %d/%d", transport.put, transport.delete)
|
||||
}
|
||||
if scenario.http != 201 {
|
||||
assertContractError(t, w, scenario.http, scenario.errorCode)
|
||||
assertAttachmentCount(t, f, 0)
|
||||
if scenario.http == 503 {
|
||||
if transport.data != nil {
|
||||
t.Fatal("failed S3 PUT stored an object")
|
||||
}
|
||||
_, err := svc.CreateAttachment(f.ctx, params.ChatID, params.OwnerID, "fixture.png", "image/png", bytes.NewReader(png), int64(len(png)))
|
||||
if !errors.Is(err, service.ErrServiceUnavailable) || errors.Is(err, storage.ErrStorage) {
|
||||
t.Fatalf("storage category did not reach service as unavailable: %v", err)
|
||||
}
|
||||
} else if !bytes.Equal(transport.data, png) {
|
||||
t.Fatal("failed database write did not leave the already stored original")
|
||||
}
|
||||
if locked, err := attachments.WithObjectKeyLock(f.ctx, transport.key, func(context.Context, repo.AttachmentTx) error { return nil }); !locked || err != nil {
|
||||
t.Fatalf("failed upload left key locked: %t, %v", locked, err)
|
||||
}
|
||||
t.Logf("direct handler HTTP %d; committed rows=0; DELETE=0", w.Code)
|
||||
return
|
||||
}
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("expected 201 after commit, got %d", w.Code)
|
||||
}
|
||||
assertAttachmentCount(t, f, 1)
|
||||
var response struct {
|
||||
ID string `json:"id"`
|
||||
SHA string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil || response.SHA != hash || response.Status != "ready" {
|
||||
t.Fatal("invalid upload response or SHA-256")
|
||||
}
|
||||
row, err := attachments.GetAttachmentForUser(f.ctx, params.OwnerID, response.ID)
|
||||
if err != nil || row.SHA256 != hash || row.ObjectKey != transport.key || row.SizeBytes != int64(len(png)) {
|
||||
t.Fatal("committed row does not match uploaded file")
|
||||
}
|
||||
get := call(http.MethodGet, "/attachments/"+response.ID, "attachment_id", response.ID, nil, h.GetAttachment)
|
||||
if get.Code != 200 || !bytes.Equal(bytes.TrimSpace(get.Body.Bytes()), bytes.TrimSpace(w.Body.Bytes())) {
|
||||
t.Fatal("metadata GET changed")
|
||||
}
|
||||
body := call(http.MethodGet, "/attachments/"+response.ID+"/content", "attachment_id", response.ID, nil, h.GetAttachmentContent)
|
||||
if body.Code != 200 || transport.get != 1 || !bytes.Equal(body.Body.Bytes(), png) || body.Header().Get("Content-Type") != "image/png" {
|
||||
t.Fatal("content GET did not return the original")
|
||||
}
|
||||
t.Logf("HTTP 201, committed rows=1, GET metadata/content=200, SHA-256=%s", hash)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func TestStorageAuthHandlerRejectsJSONBody(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
writes := f.redis.audit.writeCount()
|
||||
auth := handler.NewAuthHandler(f.auth)
|
||||
mid := middleware.NewMiddleware(f.auth, "auth-test")
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
request.SetBasicAuth(user.Username, password)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
// Exercise the real handler independently of Router wiring.
|
||||
// This component test does not replace the end-to-end login acceptance test.
|
||||
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Errorf("login with JSON body must return 400; received %d", recorder.Code)
|
||||
}
|
||||
if f.redis.audit.writeCount() != writes {
|
||||
t.Error("login with forbidden JSON body attempted to create a session")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"highload/internal/database"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
)
|
||||
|
||||
func operationBudget(t *testing.T) time.Duration {
|
||||
t.Helper()
|
||||
value := os.Getenv("AUTH_TEST_OPERATION_BUDGET_MS")
|
||||
if value == "" {
|
||||
t.Log("budget_policy=provisional_3000ms; teacher has no numeric threshold; approval remains pending")
|
||||
return 3 * time.Second
|
||||
}
|
||||
n, err := strconv.Atoi(value)
|
||||
if err != nil || n < 500 || n > 10000 {
|
||||
t.Fatal("AUTH_TEST_OPERATION_BUDGET_MS must be 500..10000")
|
||||
}
|
||||
return time.Duration(n) * time.Millisecond
|
||||
}
|
||||
|
||||
func applicationPool(t *testing.T, f *fixture) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
u, err := url.Parse(os.Getenv("AUTH_TEST_DATABASE_URL"))
|
||||
if err != nil {
|
||||
t.Fatal("invalid test URL")
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("search_path", f.config.ConnConfig.RuntimeParams["search_path"])
|
||||
u.RawQuery = q.Encode()
|
||||
// Actual production constructor: never inherit fixture statement_timeout.
|
||||
pool, err := database.NewPostgres(f.ctx, u.String())
|
||||
if err != nil {
|
||||
t.Fatal("application pool unavailable")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.pool = pool
|
||||
f.queries = sqlc.New(pool)
|
||||
return pool
|
||||
}
|
||||
|
||||
func blockOperation(t *testing.T, f *fixture, mode string) func() {
|
||||
t.Helper()
|
||||
if mode == "blocked_query" {
|
||||
tx, err := f.admin.Begin(f.ctx)
|
||||
if err != nil {
|
||||
t.Fatal("lock transaction failed")
|
||||
}
|
||||
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "users"}.Sanitize()
|
||||
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
|
||||
t.Fatal("isolated table lock failed")
|
||||
}
|
||||
return func() {
|
||||
ctx, c := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer c()
|
||||
_ = tx.Rollback(ctx)
|
||||
}
|
||||
}
|
||||
max := f.pool.Config().MaxConns
|
||||
if max <= 0 || max > 128 {
|
||||
t.Fatal("test refuses unbounded/oversized pool")
|
||||
}
|
||||
held := make([]*pgxpool.Conn, 0, max)
|
||||
for range max {
|
||||
conn, err := f.pool.Acquire(f.ctx)
|
||||
if err != nil {
|
||||
for _, h := range held {
|
||||
h.Release()
|
||||
}
|
||||
t.Fatal("pool saturation failed")
|
||||
}
|
||||
held = append(held, conn)
|
||||
}
|
||||
return func() {
|
||||
for _, h := range held {
|
||||
h.Release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresOperationsHaveBoundedWaits(t *testing.T) {
|
||||
budget := operationBudget(t)
|
||||
for _, mode := range []string{"blocked_query", "exhausted_pool"} {
|
||||
for _, scenario := range []string{"application_budget", "shorter_caller_deadline", "released_before_budget"} {
|
||||
t.Run(mode+"/"+scenario, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
applicationPool(t, f)
|
||||
release := blockOperation(t, f, mode)
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
release()
|
||||
}
|
||||
}()
|
||||
safety := budget + 2*time.Second
|
||||
if scenario == "shorter_caller_deadline" {
|
||||
safety = 150 * time.Millisecond
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), safety)
|
||||
defer cancel()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil).WithContext(ctx)
|
||||
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recorder := httptest.NewRecorder()
|
||||
done := make(chan struct{})
|
||||
started := time.Now()
|
||||
go func() { defer close(done); redisRouter(f, f.redis.client).ServeHTTP(recorder, request) }()
|
||||
if scenario == "released_before_budget" {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
release()
|
||||
released = true
|
||||
}
|
||||
<-done
|
||||
elapsed := time.Since(started)
|
||||
t.Logf("mode=%s scenario=%s elapsed_ms=%.3f caller_deadline_ms=%d budget_ms=%d caller_canceled=%t", mode, scenario, float64(elapsed)/float64(time.Millisecond), safety.Milliseconds(), budget.Milliseconds(), ctx.Err() != nil)
|
||||
switch scenario {
|
||||
case "application_budget":
|
||||
if ctx.Err() != nil || elapsed > budget+250*time.Millisecond {
|
||||
t.Error("application did not independently enforce its operation budget before test safety cancellation")
|
||||
}
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
case "shorter_caller_deadline":
|
||||
if elapsed > 750*time.Millisecond {
|
||||
t.Error("short caller deadline was not honored")
|
||||
}
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
case "released_before_budget":
|
||||
if recorder.Code != 200 || elapsed >= budget {
|
||||
t.Error("unblocked operation failed or missed the declared budget")
|
||||
}
|
||||
}
|
||||
if !released {
|
||||
release()
|
||||
released = true
|
||||
}
|
||||
recovery := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/api/v1/users/me", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recoveryCtx, c := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer c()
|
||||
redisRouter(f, f.redis.client).ServeHTTP(recovery, req.WithContext(recoveryCtx))
|
||||
if recovery.Code != 200 {
|
||||
t.Error("service did not recover after releasing lock/pool")
|
||||
}
|
||||
if f.pool.Stat().AcquiredConns() != 0 {
|
||||
t.Error("application pool leaked an acquired connection")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresChatCancellationBeforeCommitIsAtomic(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, _ := f.user(t)
|
||||
applicationPool(t, f)
|
||||
tx, err := f.admin.Begin(f.ctx)
|
||||
if err != nil {
|
||||
t.Fatal("cannot start membership blocker")
|
||||
}
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
_ = tx.Rollback(context.Background())
|
||||
}
|
||||
}()
|
||||
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "chat_members"}.Sanitize()
|
||||
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
|
||||
t.Fatal("cannot block membership insertion")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
repo := postgres.NewChatRepository(f.queries, f.pool)
|
||||
_, err = repo.CreateChat(ctx, "Canceled before membership", []string{user.ID})
|
||||
if !errors.Is(err, repository.ErrServiceUnavailable) {
|
||||
t.Errorf("want unavailable after controlled pre-commit cancellation, got category %v", err)
|
||||
}
|
||||
// The membership INSERT cannot finish while this lock is held, so COMMIT
|
||||
// has not been reached. No ambiguous-commit inference is made here.
|
||||
_ = tx.Rollback(context.Background())
|
||||
released = true
|
||||
for _, name := range []string{"chats", "chat_members"} {
|
||||
var count int
|
||||
if f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+name).Scan(&count) != nil || count != 0 {
|
||||
t.Error("pre-commit cancellation left partial chat data")
|
||||
}
|
||||
}
|
||||
if _, err = repo.CreateChat(f.ctx, "Works after cancellation", []string{user.ID}); err != nil {
|
||||
t.Error("chat repository failed to recover")
|
||||
}
|
||||
if f.pool.Stat().AcquiredConns() != 0 {
|
||||
t.Error("chat cancellation leaked a connection")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
repository "highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func TestErrorDiagnosticsRecordedOnceAndPublicResponseIsSafe(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
original := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil)))
|
||||
defer slog.SetDefault(original)
|
||||
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: errors.New("synthetic-storage-diagnostic")})))
|
||||
_, cause := users.GetUser(context.Background(), uuid.NewString())
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-secret-not-for-logs")
|
||||
recorder := httptest.NewRecorder()
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = httputils.WriteServiceError(w, cause, middleware.RequestIDFromContext(r.Context()))
|
||||
})).ServeHTTP(recorder, request)
|
||||
assertContractError(t, recorder, 500, "internal_error")
|
||||
if strings.Contains(recorder.Body.String(), "synthetic-storage-diagnostic") {
|
||||
t.Error("public response exposed internal cause")
|
||||
}
|
||||
if strings.Contains(output.String(), "synthetic-secret-not-for-logs") {
|
||||
t.Error("server log exposed a Bearer credential")
|
||||
}
|
||||
var records []map[string]any
|
||||
for _, line := range strings.Split(strings.TrimSpace(output.String()), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var record map[string]any
|
||||
if json.Unmarshal([]byte(line), &record) != nil {
|
||||
t.Error("diagnostic log is not structured JSON")
|
||||
continue
|
||||
}
|
||||
// Access records are not detailed duplicate error records.
|
||||
if record["msg"] != "http request" {
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
if len(records) != 1 {
|
||||
t.Errorf("want exactly one detailed error at response boundary, got %d", len(records))
|
||||
return
|
||||
}
|
||||
record := records[0]
|
||||
if _, malformed := record["!BADKEY"]; malformed {
|
||||
t.Error("structured error log contains !BADKEY: slog arguments are not valid key/value pairs")
|
||||
}
|
||||
if record["request_id"] != recorder.Header().Get("X-Request-Id") || record["status"] != float64(500) ||
|
||||
(record["code"] != "internal_error" && record["error_code"] != "internal_error") {
|
||||
t.Error("diagnostic is missing matching request_id/status/error code")
|
||||
}
|
||||
encoded, _ := json.Marshal(record)
|
||||
if !bytes.Contains(encoded, []byte("synthetic-storage-diagnostic")) {
|
||||
t.Error("diagnostic lost storage cause")
|
||||
}
|
||||
}
|
||||
|
||||
// Faults enter through sqlc's database interface, then pass through the real
|
||||
// repository, service and HTTP error mapper. Driver causes are deliberately
|
||||
// not required to survive: the public category and response are the contract.
|
||||
type errorCase struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
status int
|
||||
code string
|
||||
}
|
||||
|
||||
func databaseErrorCases() []errorCase {
|
||||
cases := []errorCase{
|
||||
{"no_rows", pgx.ErrNoRows, service.ErrNotFound, 404, "not_found"},
|
||||
{"duplicate", &pgconn.PgError{Code: "23505"}, service.ErrAlreadyExists, 409, "conflict"},
|
||||
{"eof", io.EOF, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"deadline", context.DeadlineExceeded, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"unexpected_eof", io.ErrUnexpectedEOF, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"closed_connection", pgconn.ErrConnClosed, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"connection_refused", unavailableRow{}.Scan(), service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
// Docker removes the stopped service from DNS. The real outage probe
|
||||
// returned a ConnectError containing this error, without a net.OpError.
|
||||
{"database_dns_missing", &net.DNSError{Err: "no such host", Name: "postgres", IsNotFound: true}, service.ErrServiceUnavailable, 503, "unavailable"},
|
||||
{"sql_syntax", &pgconn.PgError{Code: "42601", Message: "private SQL diagnostic"}, service.ErrServerError, 500, "internal_error"},
|
||||
{"unexpected", errors.New("private database diagnostic"), service.ErrServerError, 500, "internal_error"},
|
||||
}
|
||||
for _, code := range []string{"53300", "57P03", "08006", "08001", "57P01", "57P02"} {
|
||||
cases = append(cases, errorCase{"sqlstate_" + code, &pgconn.PgError{Code: code}, service.ErrServiceUnavailable, 503, "unavailable"})
|
||||
}
|
||||
// Wrapping must not change how an existing error category is recognized.
|
||||
originals := append([]errorCase(nil), cases...)
|
||||
for _, tc := range originals {
|
||||
tc.name = "wrapped_" + tc.name
|
||||
tc.cause = fmt.Errorf("database operation: %w", tc.cause)
|
||||
cases = append(cases, tc)
|
||||
}
|
||||
return cases
|
||||
}
|
||||
|
||||
type faultRow struct{ cause error }
|
||||
|
||||
func (r faultRow) Scan(...any) error { return r.cause }
|
||||
|
||||
type faultDB struct {
|
||||
unavailableDB
|
||||
cause error
|
||||
}
|
||||
|
||||
func (d faultDB) QueryRow(context.Context, string, ...any) pgx.Row {
|
||||
return faultRow{d.cause}
|
||||
}
|
||||
|
||||
func assertContractError(t *testing.T, recorder *httptest.ResponseRecorder, status int, code string) {
|
||||
t.Helper()
|
||||
if recorder.Code != status {
|
||||
t.Fatalf("want HTTP %d, got %d", status, recorder.Code)
|
||||
}
|
||||
if recorder.Header().Get("Content-Type") != "application/json" {
|
||||
t.Fatal("error response must have application/json content type")
|
||||
}
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
decoder := json.NewDecoder(recorder.Body)
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
t.Fatal("error response is not valid JSON")
|
||||
}
|
||||
if decoder.Decode(new(any)) != io.EOF {
|
||||
t.Fatal("error response contains more than one JSON value")
|
||||
}
|
||||
if payload.Error.Code != code || payload.Error.RequestID == "" ||
|
||||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
|
||||
t.Fatal("error category or request ID violates the API contract")
|
||||
}
|
||||
if payload.Error.Message == "" || strings.Contains(payload.Error.Message, "private") {
|
||||
t.Fatal("error message is empty or discloses internal diagnostics")
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorDatabaseCategoryReachesHTTP(t *testing.T) {
|
||||
for _, tc := range databaseErrorCases() {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: tc.cause})))
|
||||
_, err := users.GetUser(context.Background(), uuid.NewString())
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("want category %v, got %v", tc.want, err)
|
||||
}
|
||||
if errors.Is(tc.cause, context.DeadlineExceeded) && !strings.Contains(err.Error(), context.DeadlineExceeded.Error()) {
|
||||
t.Error("deadline diagnostic context lost between repository and service")
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = httputils.WriteServiceError(w, err, middleware.RequestIDFromContext(r.Context()))
|
||||
})).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
|
||||
assertContractError(t, recorder, tc.status, tc.code)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorUnavailableSQLLoginKeepsCategory(t *testing.T) {
|
||||
for _, tc := range databaseErrorCases() {
|
||||
if tc.status != 503 {
|
||||
continue
|
||||
}
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
queries := sqlc.New(faultDB{cause: tc.cause})
|
||||
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
|
||||
mid := middleware.NewMiddleware(auth, "auth-test")
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("synthetic_user", "Synthetic:password")
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The caller exists; the other member lookup fails. This isolates the service
|
||||
// branch that used to replace the received err with ErrServerError.
|
||||
type memberFaultDB struct {
|
||||
unavailableDB
|
||||
caller uuid.UUID
|
||||
cause error
|
||||
}
|
||||
|
||||
func (d memberFaultDB) QueryRow(_ context.Context, _ string, args ...any) pgx.Row {
|
||||
id := uuid.UUID(args[0].(pgtype.UUID).Bytes)
|
||||
if id == d.caller {
|
||||
return memberUserRow{id}
|
||||
}
|
||||
return faultRow{d.cause}
|
||||
}
|
||||
|
||||
type memberUserRow struct{ id uuid.UUID }
|
||||
|
||||
func (r memberUserRow) Scan(dst ...any) error {
|
||||
*dst[0].(*pgtype.UUID) = pgtype.UUID{Bytes: [16]byte(r.id), Valid: true}
|
||||
*dst[1].(*string) = "error_test_caller"
|
||||
*dst[2].(*string) = "Error test caller"
|
||||
*dst[3].(*string) = "unused password hash"
|
||||
*dst[4].(*pgtype.Timestamptz) = pgtype.Timestamptz{Time: time.Unix(1, 0), Valid: true}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestErrorChatMemberLookupKeepsOperationMeaning(t *testing.T) {
|
||||
for _, tc := range databaseErrorCases() {
|
||||
if tc.status != 503 && tc.status != 404 && tc.status != 500 {
|
||||
continue
|
||||
}
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
caller := uuid.New()
|
||||
queries := sqlc.New(memberFaultDB{caller: caller, cause: tc.cause})
|
||||
users := repository.NewUserRepository(queries)
|
||||
// No writable repository: an invalid member list must never reach
|
||||
// chat insertion. Accidentally continuing is a test failure.
|
||||
chats := service.NewChatService(nil, users, service.NewUserService(users))
|
||||
_, err := chats.Create(context.Background(), "Error regression", []string{caller.String(), uuid.NewString()}, caller.String())
|
||||
want, status, code := tc.want, tc.status, tc.code
|
||||
if tc.status == 404 {
|
||||
// contracts/README.md:17: unknown members make POST /chats invalid.
|
||||
want, status, code = service.ErrInvalidInput, 400, "invalid_request"
|
||||
}
|
||||
if !errors.Is(err, want) {
|
||||
t.Fatalf("want category %v, got %v", want, err)
|
||||
}
|
||||
gotStatus, gotCode := httputils.ErrorFromService(err)
|
||||
if gotStatus != status || gotCode != code {
|
||||
t.Fatalf("want %d/%s, got %d/%s", status, code, gotStatus, gotCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorMissingBasicPrecedesForbiddenBody(t *testing.T) {
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
auth := handler.NewAuthHandler(nil)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
|
||||
assertContractError(t, recorder, 401, "unauthorized")
|
||||
if recorder.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatal("missing Basic challenge")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
"highload/internal/repository"
|
||||
)
|
||||
|
||||
type logoutObservationKey struct{}
|
||||
type logoutObservation struct {
|
||||
Group int `json:"clients"`
|
||||
Round int `json:"round"`
|
||||
PauseMS int `json:"pause_ms"`
|
||||
ElapsedMS float64 `json:"elapsed_ms"`
|
||||
WaitMS float64 `json:"waitaof_ms"`
|
||||
DelID int64 `json:"del_connection_id"`
|
||||
WaitID int64 `json:"wait_connection_id"`
|
||||
Local *int64 `json:"local_fsynced"`
|
||||
Replicas *int64 `json:"replicas_fsynced"`
|
||||
Kind string `json:"kind"`
|
||||
CommandError string `json:"command_error,omitempty"`
|
||||
RepositoryError string `json:"repository_error,omitempty"`
|
||||
}
|
||||
type logoutAOFObservation struct{}
|
||||
|
||||
func (h logoutAOFObservation) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (h logoutAOFObservation) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (h logoutAOFObservation) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
started := time.Now()
|
||||
err := next(ctx, cmd)
|
||||
row, _ := ctx.Value(logoutObservationKey{}).(*logoutObservation)
|
||||
if row == nil {
|
||||
return err
|
||||
}
|
||||
name := cmd.Name()
|
||||
if name != "del" && name != "waitaof" {
|
||||
return err
|
||||
}
|
||||
if name == "waitaof" {
|
||||
row.WaitMS = float64(time.Since(started)) / float64(time.Millisecond)
|
||||
if err != nil {
|
||||
row.CommandError = err.Error()
|
||||
row.Kind = "command_error"
|
||||
} else {
|
||||
if value, ok := cmd.(*redisclient.Cmd); ok {
|
||||
if reply, ok := value.Val().([]any); ok && len(reply) == 2 {
|
||||
local, lok := reply[0].(int64)
|
||||
replicas, rok := reply[1].(int64)
|
||||
if lok && rok {
|
||||
row.Local = &local
|
||||
row.Replicas = &replicas
|
||||
row.Kind = "acknowledged"
|
||||
if local != 1 {
|
||||
row.Kind = "unacknowledged"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if row.Local == nil {
|
||||
row.Kind = "unexpected_reply"
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
// next is bound to this Conn's processing path. The observation adds a
|
||||
// read-only CLIENT ID on that same path; it never gets a second pool slot.
|
||||
id := redisclient.NewIntCmd(ctx, "CLIENT", "ID")
|
||||
if e := next(ctx, id); e == nil {
|
||||
if name == "del" {
|
||||
row.DelID = id.Val()
|
||||
} else {
|
||||
row.WaitID = id.Val()
|
||||
}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisLogoutPersistenceDiagnostic(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
f.client.AddHook(logoutAOFObservation{})
|
||||
before := f.client.PoolStats()
|
||||
rows := []logoutObservation{}
|
||||
var mu sync.Mutex
|
||||
stop := make(chan struct{})
|
||||
sampled := make(chan struct{})
|
||||
poolSamples := []map[string]any{}
|
||||
go func() {
|
||||
defer close(sampled)
|
||||
ticker := time.NewTicker(50 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
poolSamples = append(poolSamples, map[string]any{"at": time.Now().UTC().Format(time.RFC3339Nano), "stats": f.client.PoolStats()})
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
close(stop)
|
||||
<-sampled
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for f.client.PoolStats().TotalConns != f.client.PoolStats().IdleConns && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
after := f.client.PoolStats()
|
||||
if after.TotalConns != after.IdleConns || after.PendingRequests != 0 {
|
||||
t.Error("logout left acquired/pending pool connections")
|
||||
}
|
||||
report := map[string]any{"pool_before": before, "pool_after": after, "pool_samples": poolSamples, "samples": rows, "production_options": map[string]any{"read_timeout_ms": f.client.Options().ReadTimeout.Milliseconds(), "pool_size": f.client.Options().PoolSize, "pool_timeout_ms": f.client.Options().PoolTimeout.Milliseconds()}, "instrumentation": "read-only CLIENT ID after DEL and WAITAOF, on the pinned processing path"}
|
||||
if directory := os.Getenv("AUTH_TEST_DIAGNOSTICS_DIR"); directory != "" {
|
||||
_ = os.MkdirAll(directory, 0700)
|
||||
data, _ := json.MarshalIndent(report, "", " ")
|
||||
if os.WriteFile(filepath.Join(directory, "redis-logout.json"), data, 0600) != nil {
|
||||
t.Error("cannot save Redis diagnostics")
|
||||
}
|
||||
}
|
||||
t.Logf("logout samples=%d pool_wait_count=%d wait_ns=%d pool_timeouts=%d final_busy=%d", len(rows), after.WaitCount-before.WaitCount, after.WaitDurationNs-before.WaitDurationNs, after.Timeouts-before.Timeouts, after.TotalConns-after.IdleConns)
|
||||
}()
|
||||
run := func(clients, round, pause int) {
|
||||
var workers sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for range clients {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
// Two sessions for one synthetic identity: revoking one must leave the
|
||||
// other valid, even while other workers revoke their own sessions.
|
||||
first, other := f.trackSafe(uuid.NewString()), f.trackSafe(uuid.NewString())
|
||||
user := uuid.NewString()
|
||||
if _, err := f.repo.Create(f.ctx, first[:], user, time.Minute); err != nil {
|
||||
t.Error("create logout fixture failed")
|
||||
return
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, other[:], user, time.Minute); err != nil {
|
||||
t.Error("create independent fixture failed")
|
||||
return
|
||||
}
|
||||
<-start
|
||||
time.Sleep(time.Duration(pause) * time.Millisecond)
|
||||
row := logoutObservation{Group: clients, Round: round, PauseMS: pause}
|
||||
ctx := context.WithValue(f.ctx, logoutObservationKey{}, &row)
|
||||
began := time.Now()
|
||||
_, err := f.repo.RevokeSession(ctx, first[:])
|
||||
row.ElapsedMS = float64(time.Since(began)) / float64(time.Millisecond)
|
||||
if err != nil {
|
||||
row.RepositoryError = err.Error()
|
||||
t.Errorf("logout clients=%d kind=%s category=%v", clients, row.Kind, err)
|
||||
}
|
||||
if row.Kind == "unacknowledged" && !errors.Is(err, repository.ErrServiceUnavailable) {
|
||||
t.Error("unacknowledged local fsync must preserve unavailable category")
|
||||
}
|
||||
if row.DelID == 0 || row.DelID != row.WaitID {
|
||||
t.Error("DEL/WAITAOF connection identity not preserved")
|
||||
}
|
||||
if _, err = f.repo.GetSessionByTokenHash(f.ctx, other[:]); err != nil {
|
||||
t.Error("concurrent logout affected independent session")
|
||||
}
|
||||
if _, err = f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repository.ErrNotFound) {
|
||||
t.Error("revoked session still available")
|
||||
}
|
||||
mu.Lock()
|
||||
rows = append(rows, row)
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
}
|
||||
for i, pause := range []int{0, 137, 359, 613, 887, 1109} {
|
||||
run(1, i+1, pause)
|
||||
}
|
||||
for _, clients := range []int{5, 10} {
|
||||
for round := 1; round <= 3; round++ {
|
||||
run(clients, round, 137*round)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// track modifies fixture cleanup bookkeeping; concurrent probes synchronize it.
|
||||
var diagnosticTrackMu sync.Mutex
|
||||
|
||||
func (f *redisFixture) trackSafe(token string) [32]byte {
|
||||
diagnosticTrackMu.Lock()
|
||||
defer diagnosticTrackMu.Unlock()
|
||||
return f.track(token)
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/model"
|
||||
domainrepo "highload/internal/repository"
|
||||
postgresrepo "highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Uses the real handler/service/PostgreSQL repository and metadata-only fixtures.
|
||||
// Authentication is already covered by the existing auth tests: only the current
|
||||
// user context is injected here. No S3 server, upload endpoint or Redis is needed.
|
||||
type messageAttachmentFixture struct {
|
||||
*fixture
|
||||
http http.Handler
|
||||
alice, bob string
|
||||
chat, other *model.Chat
|
||||
ids, foreign []string
|
||||
}
|
||||
|
||||
type attachmentMessage struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
// Small dependencies for the real service's one-attachment regression. They
|
||||
// compare UUID identity without prescribing where normalization takes place.
|
||||
// They do not implement persistence/idempotency: PostgreSQL cases prove that.
|
||||
type singleAttachmentChatRepo struct {
|
||||
domainrepo.ChatRepository
|
||||
chat *model.Chat
|
||||
}
|
||||
|
||||
func (r *singleAttachmentChatRepo) GetChatByID(_ context.Context, id string) (*model.Chat, error) {
|
||||
if id != r.chat.ID {
|
||||
return nil, domainrepo.ErrNotFound
|
||||
}
|
||||
return r.chat, nil
|
||||
}
|
||||
|
||||
type singleAttachmentMessageRepo struct {
|
||||
domainrepo.MessageRepository
|
||||
message *model.Message
|
||||
key string
|
||||
calls [][]string
|
||||
}
|
||||
|
||||
func (r *singleAttachmentMessageRepo) CreateMessage(_ context.Context, chatID, userID, text, key string, ids []string) (*model.Message, error) {
|
||||
r.calls = append(r.calls, append([]string{}, ids...))
|
||||
if chatID != r.message.ChatID || userID != r.message.SenderID || text != r.message.Text || key != r.key {
|
||||
return nil, domainrepo.ErrServerError
|
||||
}
|
||||
if len(ids) != len(r.message.AttachmentIDs) {
|
||||
return nil, domainrepo.ErrInvalidInput
|
||||
}
|
||||
for index, raw := range ids {
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil || id.String() != r.message.AttachmentIDs[index] {
|
||||
return nil, domainrepo.ErrInvalidInput
|
||||
}
|
||||
}
|
||||
return r.message, nil
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsSingleIDServiceRegression(t *testing.T) {
|
||||
const attachmentID = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
|
||||
for _, scenario := range []struct {
|
||||
name, inputID string
|
||||
requests int
|
||||
}{
|
||||
{name: "single_attachment_without_panic", inputID: attachmentID, requests: 1},
|
||||
{name: "identical_uppercase_body_replay", inputID: strings.ToUpper(attachmentID), requests: 2},
|
||||
} {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
t.Errorf("CreateMessage with one valid attachment panicked: %v", recovered)
|
||||
}
|
||||
}()
|
||||
userID, chatID, key := uuid.NewString(), uuid.NewString(), uuid.NewString()
|
||||
original := &model.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: userID,
|
||||
Text: "", AttachmentIDs: []string{attachmentID}, CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
repo := &singleAttachmentMessageRepo{message: original, key: key}
|
||||
chatRepo := &singleAttachmentChatRepo{chat: &model.Chat{ID: chatID, MemberIDs: []string{userID}}}
|
||||
chats := service.NewChatService(chatRepo, nil, nil)
|
||||
messages := service.NewMessageService(repo, chats, nil)
|
||||
for range scenario.requests {
|
||||
// The uppercase case starts uppercase and repeats EXACTLY the same
|
||||
// values. It never assumes different string bodies must be equivalent.
|
||||
input := []string{scenario.inputID}
|
||||
message, err := messages.CreateMessage(context.Background(), "", chatID, userID, key, input)
|
||||
if err != nil || !reflect.DeepEqual(message, original) {
|
||||
t.Fatalf("one attachment / identical uppercase replay: expected original Message without conflict, got %v", err)
|
||||
}
|
||||
}
|
||||
if len(repo.calls) == 0 {
|
||||
t.Fatal("service did not create the message through its repository")
|
||||
}
|
||||
for _, ids := range repo.calls {
|
||||
if len(ids) != 1 {
|
||||
t.Fatal("service lost the single attachment")
|
||||
}
|
||||
id, err := uuid.Parse(ids[0])
|
||||
if err != nil || id.String() != attachmentID {
|
||||
t.Fatal("service changed the attachment UUID identity")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newMessageAttachmentFixture(t *testing.T) *messageAttachmentFixture {
|
||||
t.Helper()
|
||||
f := newDatabaseFixture(t, "LAB4_TEST_DATABASE_URL", 12)
|
||||
result := &messageAttachmentFixture{fixture: f, alice: uuid.NewString(), bob: uuid.NewString()}
|
||||
for _, id := range []string{result.alice, result.bob} {
|
||||
_, err := f.pool.Exec(f.ctx, `INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES($1,$2,'Synthetic attachment test','fixture-only-not-used-for-login')`,
|
||||
id, "attach_"+strings.ReplaceAll(id, "-", "")[:18])
|
||||
if err != nil {
|
||||
t.Fatal("cannot prepare synthetic users")
|
||||
}
|
||||
}
|
||||
chatRepo := postgresrepo.NewChatRepository(f.queries, f.pool)
|
||||
var err error
|
||||
result.chat, err = chatRepo.CreateChat(f.ctx, "Message attachments", []string{result.alice, result.bob})
|
||||
if err != nil {
|
||||
t.Fatal("cannot prepare primary chat")
|
||||
}
|
||||
result.other, err = chatRepo.CreateChat(f.ctx, "Other attachment scope", []string{result.alice})
|
||||
if err != nil {
|
||||
t.Fatal("cannot prepare other chat")
|
||||
}
|
||||
attachments := postgresrepo.NewAttachmentRepository(f.queries, f.pool)
|
||||
for _, chat := range []*model.Chat{result.chat, result.other} {
|
||||
for i := 0; i < 11; i++ {
|
||||
att, err := attachments.CreateAttachment(f.ctx, domainrepo.CreateAttachmentParams{
|
||||
ChatID: chat.ID, OwnerID: result.alice, Filename: fmt.Sprintf("synthetic-%d.png", i),
|
||||
ObjectKey: "metadata-only/" + uuid.NewString(), ContentType: "image/png",
|
||||
Sha256: strings.Repeat("a", 64), SizeBytes: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal("cannot seed attachment metadata through its PostgreSQL repository")
|
||||
}
|
||||
if chat.ID == result.chat.ID {
|
||||
result.ids = append(result.ids, att.ID)
|
||||
} else {
|
||||
result.foreign = append(result.foreign, att.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deliberately disagree with UUID ordering to catch accidental ORDER BY id.
|
||||
slices.Sort(result.ids)
|
||||
slices.Reverse(result.ids)
|
||||
users := service.NewUserService(postgresrepo.NewUserRepository(f.queries))
|
||||
chats := service.NewChatService(chatRepo, postgresrepo.NewUserRepository(f.queries), users)
|
||||
messages := service.NewMessageService(postgresrepo.NewMessageRepository(f.queries, f.pool), chats, users)
|
||||
h := handler.NewMessageHandler(messages)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", h.CreateMessage)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", h.GetMessagesByChatID)
|
||||
mid := middleware.NewMiddleware(nil, "message-pg-test")
|
||||
result.http = mid.InstanceID(mid.RequestID(mux))
|
||||
return result
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) call(actor, method, chatID, key string, body any) *httptest.ResponseRecorder {
|
||||
var raw []byte
|
||||
if body != nil {
|
||||
raw, _ = json.Marshal(body)
|
||||
}
|
||||
request := httptest.NewRequest(method, "/api/v1/chats/"+chatID+"/messages?limit=100", bytes.NewReader(raw))
|
||||
request = request.WithContext(middleware.WithUserID(f.ctx, actor))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if key != "" {
|
||||
request.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
f.http.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func attachmentBody(text string, ids []string) map[string]any {
|
||||
return map[string]any{"text": text, "attachment_ids": ids}
|
||||
}
|
||||
|
||||
func decodeAttachmentMessage(t *testing.T, response *httptest.ResponseRecorder) attachmentMessage {
|
||||
t.Helper()
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("POST message: expected HTTP 201, got %d", response.Code)
|
||||
}
|
||||
var value map[string]json.RawMessage
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &value); err != nil || len(value) != 6 {
|
||||
t.Fatal("Message must contain exactly the six lab4 contract fields, including attachment_ids")
|
||||
}
|
||||
var message attachmentMessage
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil || message.AttachmentIDs == nil {
|
||||
t.Fatal("attachment_ids must be an array, including [] for a text-only message")
|
||||
}
|
||||
for _, id := range []string{message.ID, message.ChatID, message.SenderID} {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
t.Fatal("Message contains an invalid UUID")
|
||||
}
|
||||
}
|
||||
if _, err := time.Parse(time.RFC3339Nano, message.CreatedAt); err != nil || !strings.HasSuffix(message.CreatedAt, "Z") {
|
||||
t.Fatal("Message must preserve a server UTC timestamp")
|
||||
}
|
||||
if response.Header().Get("X-Request-Id") == "" || response.Header().Get("X-Instance-Id") != "message-pg-test" {
|
||||
t.Fatal("message response is missing request/instance identity")
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) history(t *testing.T) []attachmentMessage {
|
||||
t.Helper()
|
||||
r := f.call(f.bob, "GET", f.chat.ID, "", nil)
|
||||
var page struct {
|
||||
Items []attachmentMessage `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
if r.Code != 200 || json.Unmarshal(r.Body.Bytes(), &page) != nil || page.NextCursor != nil {
|
||||
t.Fatal("cannot read the complete synthetic history")
|
||||
}
|
||||
for _, message := range page.Items {
|
||||
if message.AttachmentIDs == nil {
|
||||
t.Fatal("history must include attachment_ids arrays")
|
||||
}
|
||||
}
|
||||
return page.Items
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) assertLinks(t *testing.T, message attachmentMessage, expected []string) {
|
||||
t.Helper()
|
||||
if !sameOrderedAttachmentUUIDs(message.AttachmentIDs, expected) {
|
||||
t.Fatal("Message attachment order or contents differ from request")
|
||||
}
|
||||
rows, err := f.pool.Query(f.ctx, `SELECT attachment_id::text, position, chat_id::text
|
||||
FROM messages_attachments WHERE message_id=$1 ORDER BY position`, message.ID)
|
||||
if err != nil {
|
||||
t.Fatal("cannot inspect attachment links")
|
||||
}
|
||||
defer rows.Close()
|
||||
var actual []string
|
||||
for rows.Next() {
|
||||
var id, chatID string
|
||||
var position int
|
||||
if rows.Scan(&id, &position, &chatID) != nil || position != len(actual) || chatID != f.chat.ID {
|
||||
t.Fatal("attachment link has incorrect position or chat scope")
|
||||
}
|
||||
actual = append(actual, id)
|
||||
}
|
||||
if rows.Err() != nil || !slices.Equal(actual, expected) {
|
||||
t.Fatal("database links do not match exactly the submitted attachment order")
|
||||
}
|
||||
}
|
||||
|
||||
func sameOrderedAttachmentUUIDs(actual, expected []string) bool {
|
||||
if actual == nil || len(actual) != len(expected) {
|
||||
return false
|
||||
}
|
||||
for index, raw := range actual {
|
||||
id, err := uuid.Parse(raw)
|
||||
want, wantErr := uuid.Parse(expected[index])
|
||||
if err != nil || wantErr != nil || id != want {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sameHistoryMessage(actual, expected attachmentMessage) bool {
|
||||
if !sameOrderedAttachmentUUIDs(actual.AttachmentIDs, expected.AttachmentIDs) {
|
||||
return false
|
||||
}
|
||||
actual.AttachmentIDs = expected.AttachmentIDs
|
||||
return reflect.DeepEqual(actual, expected)
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) snapshot(t *testing.T) map[string][]string {
|
||||
t.Helper()
|
||||
state := make(map[string][]string)
|
||||
for _, table := range []string{"messages", "messages_attachments", "message_idempotency", "attachments"} {
|
||||
// Table names are fixed test constants, never request input.
|
||||
rows, err := f.pool.Query(f.ctx, "SELECT to_jsonb(item)::text FROM "+table+" AS item ORDER BY to_jsonb(item)::text")
|
||||
if err != nil {
|
||||
t.Fatal("cannot inspect transaction state")
|
||||
}
|
||||
for rows.Next() {
|
||||
var row string
|
||||
if rows.Scan(&row) != nil {
|
||||
t.Fatal("cannot decode transaction state")
|
||||
}
|
||||
state[table] = append(state[table], row)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
t.Fatal("cannot finish inspecting transaction state")
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) assertUnchanged(t *testing.T, before map[string][]string) {
|
||||
t.Helper()
|
||||
if !reflect.DeepEqual(before, f.snapshot(t)) {
|
||||
t.Fatal("failed/conflicting request changed messages, links, idempotency or metadata")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsTextCompatibility(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
key := uuid.NewString()
|
||||
first := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, map[string]any{"text": "Legacy text 👋"}))
|
||||
second := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody(first.Text, []string{})))
|
||||
if first.ChatID != f.chat.ID || first.SenderID != f.alice || first.Text != "Legacy text 👋" || !reflect.DeepEqual(first, second) {
|
||||
t.Fatal("absent attachment_ids and [] must preserve the same text-only Message")
|
||||
}
|
||||
f.assertLinks(t, first, []string{})
|
||||
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
|
||||
t.Fatal("text-only replay changed or duplicated history")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsOnlyAndOrderZeroToTen(t *testing.T) {
|
||||
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
|
||||
}
|
||||
for count := 0; count <= 10; count++ {
|
||||
t.Run(fmt.Sprintf("count_%d", count), func(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
ids := append([]string{}, f.ids[:count]...)
|
||||
text := ""
|
||||
if count == 0 {
|
||||
text = "Text without attachments"
|
||||
}
|
||||
key := uuid.NewString()
|
||||
body := attachmentBody(text, ids)
|
||||
if count == 1 {
|
||||
body = attachmentBody(text, []string{strings.ToUpper(ids[0])})
|
||||
}
|
||||
first := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body))
|
||||
if count == 1 {
|
||||
before := f.snapshot(t)
|
||||
if replay := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(replay, first) {
|
||||
t.Fatal("identical JSON with uppercase attachment UUID must replay the same 201/Message")
|
||||
}
|
||||
f.assertUnchanged(t, before)
|
||||
}
|
||||
if first.Text != text || first.SenderID != f.bob || first.ChatID != f.chat.ID {
|
||||
t.Fatal("message-only/attachment-only content or sender changed")
|
||||
}
|
||||
f.assertLinks(t, first, ids)
|
||||
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
|
||||
t.Fatal("history lost the message or attachment order")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsInvalidReferencesAreAtomic(t *testing.T) {
|
||||
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
|
||||
}
|
||||
for _, kind := range []string{"unknown_id", "attachment_from_other_chat", "foreign_chat"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
ids, actor, chatID := []string{f.ids[0], uuid.NewString()}, f.alice, f.chat.ID
|
||||
if kind == "attachment_from_other_chat" {
|
||||
ids[1] = f.foreign[0]
|
||||
} else if kind == "foreign_chat" {
|
||||
actor, chatID, ids = f.bob, f.other.ID, []string{f.foreign[0]}
|
||||
}
|
||||
before, key := f.snapshot(t), uuid.NewString()
|
||||
response := f.call(actor, "POST", chatID, key, attachmentBody("Must not be written", ids))
|
||||
assertContractError(t, response, 404, "not_found")
|
||||
f.assertUnchanged(t, before)
|
||||
// A rejected attempt must not reserve this user's key as a final result.
|
||||
valid := decodeAttachmentMessage(t, f.call(actor, "POST", f.chat.ID, key, attachmentBody("Valid after 404", f.ids[:1])))
|
||||
f.assertLinks(t, valid, f.ids[:1])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsInvalidListLeavesNoRows(t *testing.T) {
|
||||
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
|
||||
}
|
||||
for _, kind := range []string{"duplicate", "eleven"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
ids := f.ids
|
||||
if kind == "duplicate" {
|
||||
ids = []string{f.ids[0], f.ids[0]}
|
||||
}
|
||||
before := f.snapshot(t)
|
||||
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, uuid.NewString(), attachmentBody("invalid list", ids)), 400, "invalid_request")
|
||||
f.assertUnchanged(t, before)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsIdempotencyIncludesListAndOrder(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
key, ids := uuid.NewString(), f.ids[:2]
|
||||
upperIDs := []string{strings.ToUpper(ids[0]), strings.ToUpper(ids[1])}
|
||||
if slices.Equal(upperIDs, ids) {
|
||||
t.Fatal("normalization fixture must contain a UUID with hexadecimal letters")
|
||||
}
|
||||
body := attachmentBody("Same text", upperIDs)
|
||||
first := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, body))
|
||||
before := f.snapshot(t)
|
||||
for range 3 {
|
||||
if replay := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(replay, first) {
|
||||
t.Fatal("same key/body did not return the same Message")
|
||||
}
|
||||
f.assertUnchanged(t, before)
|
||||
}
|
||||
for _, changed := range [][]string{{ids[1], ids[0]}, {ids[0], f.ids[2]}, {ids[0]}, {}} {
|
||||
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Same text", changed)), 409, "conflict")
|
||||
f.assertUnchanged(t, before)
|
||||
}
|
||||
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Changed text", ids)), 409, "conflict")
|
||||
f.assertUnchanged(t, before)
|
||||
f.assertLinks(t, first, ids)
|
||||
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
|
||||
t.Fatal("idempotency conflict changed history")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsConcurrentReplayDoesNotMultiplyLinks(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
const workers = 8
|
||||
key, ids := uuid.NewString(), f.ids[:3]
|
||||
gate := make(chan struct{})
|
||||
results := make(chan *httptest.ResponseRecorder, workers)
|
||||
var group sync.WaitGroup
|
||||
for range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
<-gate
|
||||
results <- f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Concurrent attachment replay", ids))
|
||||
}()
|
||||
}
|
||||
close(gate)
|
||||
group.Wait()
|
||||
close(results)
|
||||
var first attachmentMessage
|
||||
for response := range results {
|
||||
message := decodeAttachmentMessage(t, response)
|
||||
if first.ID == "" {
|
||||
first = message
|
||||
} else if !reflect.DeepEqual(message, first) {
|
||||
t.Fatal("concurrent replay returned a different Message")
|
||||
}
|
||||
}
|
||||
f.assertLinks(t, first, ids)
|
||||
state := f.snapshot(t)
|
||||
if len(state["messages"]) != 1 || len(state["messages_attachments"]) != len(ids) || len(state["message_idempotency"]) != 1 {
|
||||
t.Fatal("concurrent replay multiplied message, link or idempotency rows")
|
||||
}
|
||||
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
|
||||
t.Fatal("concurrent replay changed history")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsLinkFailureRollsBackEverything(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
ids, key := f.ids[:2], uuid.NewString()
|
||||
// The sequence survives rollback. It proves that the fault was reached only
|
||||
// after the first link was visible inside the actual application transaction.
|
||||
_, err := f.pool.Exec(f.ctx, `CREATE SEQUENCE test_link_fault_reached;
|
||||
CREATE FUNCTION fail_second_test_link() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (SELECT count(*) FROM messages_attachments WHERE message_id=NEW.message_id) >= 1 THEN
|
||||
PERFORM nextval('test_link_fault_reached');
|
||||
RAISE EXCEPTION 'synthetic link failure';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER test_link_fault BEFORE INSERT ON messages_attachments
|
||||
FOR EACH ROW EXECUTE FUNCTION fail_second_test_link();`)
|
||||
if err != nil {
|
||||
t.Fatal("cannot prepare isolated link fault")
|
||||
}
|
||||
before := f.snapshot(t)
|
||||
response := f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Rollback all writes", ids))
|
||||
assertContractError(t, response, 500, "internal_error")
|
||||
var faultReached bool
|
||||
if f.pool.QueryRow(f.ctx, "SELECT is_called FROM test_link_fault_reached").Scan(&faultReached) != nil || !faultReached {
|
||||
t.Fatal("test did not reach an injected link failure after one real link insert")
|
||||
}
|
||||
f.assertUnchanged(t, before)
|
||||
if strings.Contains(response.Body.String(), "synthetic link failure") {
|
||||
t.Fatal("response exposed internal SQL fault details")
|
||||
}
|
||||
if _, err := f.pool.Exec(f.ctx, "DROP TRIGGER test_link_fault ON messages_attachments"); err != nil {
|
||||
t.Fatal("cannot clear isolated link fault")
|
||||
}
|
||||
message := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Rollback all writes", ids)))
|
||||
f.assertLinks(t, message, ids)
|
||||
state := f.snapshot(t)
|
||||
if len(state["messages"]) != 1 || len(state["messages_attachments"]) != 2 || len(state["message_idempotency"]) != 1 {
|
||||
t.Fatal("retry after transient link failure did not commit exactly one complete message")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"highload/internal/security"
|
||||
)
|
||||
|
||||
// These are tests of the selected Argon2id implementation, not a requirement
|
||||
// that lab2 use particular parameters or a particular encoded hash format.
|
||||
func TestPasswordRoundTripAndRandomSalt(t *testing.T) {
|
||||
password := "Синтетический:пароль:😀"
|
||||
first, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
second, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
if first == password || second == password || first == second {
|
||||
t.Fatal("hash must differ from plaintext and have a fresh random salt")
|
||||
}
|
||||
if !strings.HasPrefix(first, "$argon2id$") {
|
||||
t.Fatal("selected password implementation did not encode Argon2id")
|
||||
}
|
||||
for _, encoded := range []string{first, second} {
|
||||
ok, err := security.VerifyPassword(password, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("stored hash does not verify the original password")
|
||||
}
|
||||
ok, err = security.VerifyPassword(password+"x", encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("wrong password was accepted or verifier failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordDoesNotTruncateLongUTF8(t *testing.T) {
|
||||
// Both passwords share much more than bcrypt's 72-byte limit; each is
|
||||
// within the lab's 128-code-point maximum.
|
||||
password := strings.Repeat("😀", 127) + "A"
|
||||
different := strings.Repeat("😀", 127) + "B"
|
||||
encoded, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("maximum-length UTF-8 password cannot be hashed")
|
||||
}
|
||||
ok, err := security.VerifyPassword(password, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("maximum-length UTF-8 password cannot be verified")
|
||||
}
|
||||
ok, err = security.VerifyPassword(different, encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("password suffix was truncated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordWhitespaceIsSignificant(t *testing.T) {
|
||||
password := " synthetic-password "
|
||||
encoded, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
ok, err := security.VerifyPassword(strings.TrimSpace(password), encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("password whitespace was discarded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedPasswordHashRejectedWithoutPanic(t *testing.T) {
|
||||
valid, err := security.HashPassword("synthetic-password")
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
parts := strings.Split(valid, "$")
|
||||
if len(parts) != 6 {
|
||||
t.Fatal("unexpected encoded hash format")
|
||||
}
|
||||
cases := map[string]string{
|
||||
"empty": "",
|
||||
"plaintext": "synthetic-password",
|
||||
"wrong_algorithm": strings.Replace(valid, "argon2id", "argon2i", 1),
|
||||
"wrong_version": strings.Replace(valid, "$v=19$", "$v=999$", 1),
|
||||
"missing_version": strings.Replace(valid, "$v=19$", "$19$", 1),
|
||||
"extra_field": valid + "$extra",
|
||||
}
|
||||
for name, params := range map[string]string{
|
||||
"zero_iterations": "m=65536,t=0,p=2",
|
||||
"zero_threads": "m=65536,t=3,p=0",
|
||||
"tiny_memory": "m=1,t=3,p=2",
|
||||
"huge_memory": "m=4294967295,t=3,p=2",
|
||||
"huge_iterations": "m=65536,t=4294967295,p=2",
|
||||
"huge_threads": "m=65536,t=3,p=255",
|
||||
"negative": "m=-1,t=3,p=2",
|
||||
"non_numeric": "m=no,t=3,p=2",
|
||||
"missing_param": "m=65536,t=3",
|
||||
} {
|
||||
copyParts := append([]string(nil), parts...)
|
||||
copyParts[3] = params
|
||||
cases[name] = strings.Join(copyParts, "$")
|
||||
}
|
||||
for name, field := range map[string]int{"salt": 4, "hash": 5} {
|
||||
for label, value := range map[string]string{
|
||||
"empty": "", "bad_base64": "!!!", "wrong_size": "YQ",
|
||||
} {
|
||||
copyParts := append([]string(nil), parts...)
|
||||
copyParts[field] = value
|
||||
cases[name+"_"+label] = strings.Join(copyParts, "$")
|
||||
}
|
||||
}
|
||||
for name, encoded := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
t.Error("malformed stored hash caused a panic")
|
||||
}
|
||||
}()
|
||||
ok, err := security.VerifyPassword("synthetic-password", encoded)
|
||||
if ok || !errors.Is(err, security.ErrInvalidHash) {
|
||||
t.Error("malformed stored hash was not rejected")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/config"
|
||||
"highload/internal/database"
|
||||
repoerrors "highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
redisrepo "highload/internal/repository/redis"
|
||||
"highload/internal/service"
|
||||
httptransport "highload/internal/transport/http"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/google/uuid"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func TestRedisAddressIsAnAddressNotAFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "postgres_url")
|
||||
if err := os.WriteFile(path, []byte("postgres://fixture:fixture@postgres/messenger"), 0600); err != nil {
|
||||
t.Fatal("cannot create synthetic config fixture")
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", path)
|
||||
t.Setenv("REDIS_ADDR", "redis:6379")
|
||||
t.Setenv("SESSION_TTL_SECONDS", "3600")
|
||||
t.Setenv("SESSION_STORE", "redis")
|
||||
t.Setenv("S3_ENDPOINT", "http://s3-fixture.invalid")
|
||||
t.Setenv("S3_REGION", "us-east-1")
|
||||
t.Setenv("S3_BUCKET", "health-fixture")
|
||||
for variable, value := range map[string]string{
|
||||
"S3_ACCESS_KEY_ID_FILE": "fixture-access-key",
|
||||
"S3_SECRET_ACCESS_KEY_FILE": "fixture-secret-key",
|
||||
} {
|
||||
keyFile := filepath.Join(dir, variable)
|
||||
if err := os.WriteFile(keyFile, []byte(value), 0600); err != nil {
|
||||
t.Fatal("cannot create synthetic S3 key file")
|
||||
}
|
||||
t.Setenv(variable, keyFile)
|
||||
}
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("cannot load synthetic config with REDIS_ADDR=redis:6379: %v", err)
|
||||
}
|
||||
if cfg.Database.RedisAddr != "redis:6379" {
|
||||
t.Fatal("REDIS_ADDR did not reach the Redis configuration")
|
||||
}
|
||||
}
|
||||
|
||||
type redisFixture struct {
|
||||
ctx context.Context
|
||||
client *redisclient.Client
|
||||
repo *redisrepo.SessionRepository
|
||||
keys []string
|
||||
audit *sessionWriteAudit
|
||||
}
|
||||
|
||||
// Only observe writes through this test's client. No global key counting or
|
||||
// FLUSH commands: other clients' sessions must not affect assertions/cleanup.
|
||||
type sessionWriteAudit struct {
|
||||
sync.Mutex
|
||||
keys map[string]bool
|
||||
writes int
|
||||
}
|
||||
|
||||
func (a *sessionWriteAudit) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (a *sessionWriteAudit) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (a *sessionWriteAudit) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
if cmd.Name() == "set" && len(cmd.Args()) > 1 {
|
||||
if key, ok := cmd.Args()[1].(string); ok {
|
||||
a.Lock()
|
||||
a.keys[key] = true
|
||||
a.writes++
|
||||
a.Unlock()
|
||||
}
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
func (a *sessionWriteAudit) writeCount() int { a.Lock(); defer a.Unlock(); return a.writes }
|
||||
func (a *sessionWriteAudit) ownedKeys() []string {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
keys := make([]string, 0, len(a.keys))
|
||||
for key := range a.keys {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
type aofReplyHook struct {
|
||||
reply any
|
||||
err error
|
||||
}
|
||||
|
||||
func (h aofReplyHook) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (h aofReplyHook) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (h aofReplyHook) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
if cmd.Name() == "waitaof" {
|
||||
// DEL still runs on the real test Redis. Only its persistence
|
||||
// acknowledgement is fault-injected deterministically.
|
||||
value := cmd.(*redisclient.Cmd)
|
||||
value.SetVal(h.reply)
|
||||
value.SetErr(h.err)
|
||||
return h.err
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisUnconfirmedAOFNeverReturnsSuccessfulLogout(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
reply any
|
||||
err error
|
||||
}{
|
||||
{"local_not_fsynced", []any{int64(0), int64(0)}, nil},
|
||||
{"only_replica_fsynced", []any{int64(0), int64(1)}, nil},
|
||||
{"malformed_reply", []any{int64(1)}, nil},
|
||||
{"command_failure", nil, errors.New("synthetic acknowledgement failure")},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
f.redis.client.AddHook(aofReplyHook{tc.reply, tc.err})
|
||||
request := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
|
||||
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recorder := httptest.NewRecorder()
|
||||
redisRouter(f, f.redis.client).ServeHTTP(recorder, request)
|
||||
if recorder.Code != 500 && recorder.Code != 503 {
|
||||
t.Fatalf("unconfirmed persistence must fail logout, got HTTP %d", recorder.Code)
|
||||
}
|
||||
if (tc.name == "local_not_fsynced" || tc.name == "only_replica_fsynced") && recorder.Code != 503 {
|
||||
t.Errorf("valid reply without local acknowledgement must be HTTP 503, got %d", recorder.Code)
|
||||
}
|
||||
code := "internal_error"
|
||||
if recorder.Code == 503 {
|
||||
code = "unavailable"
|
||||
}
|
||||
assertContractError(t, recorder, recorder.Code, code)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
if f.redis.client.Exists(f.ctx, "session:"+hex.EncodeToString(hash[:])).Val() != 0 {
|
||||
t.Fatal("fault fixture did not actually execute DEL before WAITAOF")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newRedisFixture(t *testing.T) *redisFixture {
|
||||
t.Helper()
|
||||
addr := os.Getenv("AUTH_TEST_REDIS_ADDR")
|
||||
if addr == "" {
|
||||
t.Skip("Redis not verified: set AUTH_TEST_REDIS_ADDR to a dedicated test Redis with AOF")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
client, err := database.NewRedis(ctx, addr)
|
||||
if err != nil {
|
||||
t.Fatal("dedicated test Redis is unavailable")
|
||||
}
|
||||
audit := &sessionWriteAudit{keys: make(map[string]bool)}
|
||||
client.AddHook(audit)
|
||||
f := &redisFixture{ctx: ctx, client: client, repo: redisrepo.NewSessionRepository(client), audit: audit}
|
||||
t.Cleanup(func() {
|
||||
cleanup, done := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer done()
|
||||
// No FLUSHDB/FLUSHALL: delete only this test's own random token keys.
|
||||
keys := append(f.audit.ownedKeys(), f.keys...)
|
||||
if len(keys) > 0 {
|
||||
if err := client.Del(cleanup, keys...).Err(); err != nil {
|
||||
t.Error("test-owned Redis key cleanup failed")
|
||||
}
|
||||
}
|
||||
_ = client.Close()
|
||||
})
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *redisFixture) track(token string) [32]byte {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
f.keys = append(f.keys, "session:"+hex.EncodeToString(hash[:]))
|
||||
return hash
|
||||
}
|
||||
|
||||
func TestRedisSessionHasTTLAndReadsDoNotExtendIt(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track("synthetic-" + uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 5*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create Redis session")
|
||||
}
|
||||
key := f.keys[0]
|
||||
before := f.client.PTTL(f.ctx, key).Val()
|
||||
if before <= 0 || before > 5*time.Second {
|
||||
t.Fatal("session key has no bounded positive TTL")
|
||||
}
|
||||
time.Sleep(120 * time.Millisecond)
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || loaded == nil {
|
||||
t.Fatal("cannot read Redis session")
|
||||
}
|
||||
if loaded.UserID != created.UserID || !loaded.ExpiresAt.Equal(created.ExpiresAt) ||
|
||||
!loaded.CreatedAt.Equal(created.CreatedAt) {
|
||||
t.Fatal("session identity or original timestamps changed on read")
|
||||
}
|
||||
after := f.client.PTTL(f.ctx, key).Val()
|
||||
if after <= 0 || after >= before {
|
||||
t.Fatal("reading refreshed or removed the session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisExpiredAndUnknownSessionsAreNotFound(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track(uuid.NewString())
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("unknown session must be not found")
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 200*time.Millisecond); err != nil {
|
||||
t.Fatal("cannot create short-lived test session")
|
||||
}
|
||||
time.Sleep(350 * time.Millisecond)
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("expired Redis session is still available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisLogoutOnlyRemovesSelectedSession(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
first, second := f.track(uuid.NewString()), f.track(uuid.NewString())
|
||||
userID := uuid.NewString()
|
||||
for _, hash := range [][32]byte{first, second} {
|
||||
if _, err := f.repo.Create(f.ctx, hash[:], userID, time.Minute); err != nil {
|
||||
t.Fatal("cannot create independent sessions")
|
||||
}
|
||||
}
|
||||
count, err := f.repo.RevokeSession(f.ctx, first[:])
|
||||
if err != nil || count != 1 {
|
||||
t.Fatal("logout failed to remove exactly one session or acknowledge persistence")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("revoked session is still readable")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, second[:]); err != nil {
|
||||
t.Fatal("logout removed another session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisSessionsSurviveActualRestartWithoutExtendingTTL(t *testing.T) {
|
||||
hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK")
|
||||
if hook == "" {
|
||||
t.Skip("Redis restart not verified: set an explicit dedicated test restart hook")
|
||||
}
|
||||
f := newRedisFixture(t)
|
||||
active, revoked := f.track(uuid.NewString()), f.track(uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, active[:], uuid.NewString(), 30*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create active session")
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, revoked[:], created.UserID, time.Minute); err != nil {
|
||||
t.Fatal("cannot create revocation fixture")
|
||||
}
|
||||
if _, err := f.repo.RevokeSession(f.ctx, revoked[:]); err != nil {
|
||||
t.Fatal("cannot persist logout before restart")
|
||||
}
|
||||
before := f.client.PTTL(f.ctx, f.keys[0]).Val()
|
||||
if err := exec.CommandContext(f.ctx, hook).Run(); err != nil {
|
||||
t.Fatal("explicit Redis restart hook failed (private output suppressed)")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, active[:])
|
||||
if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) {
|
||||
t.Fatal("restart lost active session or changed its original deadline")
|
||||
}
|
||||
if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before {
|
||||
t.Fatal("restart extended or lost remaining TTL")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, revoked[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("restart revived a revoked session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisActiveSessionSurvivesRestartIndependentlyOfLogout(t *testing.T) {
|
||||
hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK")
|
||||
if hook == "" {
|
||||
t.Skip("Redis restart not verified: set an explicit dedicated test restart hook")
|
||||
}
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track(uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 30*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create active session")
|
||||
}
|
||||
before := f.client.PTTL(f.ctx, f.keys[0]).Val()
|
||||
if err := exec.CommandContext(f.ctx, hook).Run(); err != nil {
|
||||
t.Fatal("explicit Redis restart hook failed (private output suppressed)")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) || loaded.UserID != created.UserID {
|
||||
t.Fatal("restart lost active session identity or changed its deadline")
|
||||
}
|
||||
if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before {
|
||||
t.Fatal("restart extended or removed the session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func refusedRedis(t *testing.T) *redisclient.Client {
|
||||
t.Helper()
|
||||
client := redisclient.NewClient(&redisclient.Options{
|
||||
Addr: "synthetic-unavailable:6379", MaxRetries: -1,
|
||||
Dialer: func(context.Context, string, string) (net.Conn, error) {
|
||||
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
|
||||
},
|
||||
})
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
return client
|
||||
}
|
||||
|
||||
func TestRedisUnavailableKeepsUnavailableCategory(t *testing.T) {
|
||||
repo := redisrepo.NewSessionRepository(refusedRedis(t))
|
||||
hash := sha256.Sum256([]byte("synthetic-failed-token"))
|
||||
t.Run("create", func(t *testing.T) {
|
||||
_, err := repo.Create(context.Background(), hash[:], uuid.NewString(), time.Minute)
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
t.Run("read", func(t *testing.T) {
|
||||
_, err := repo.GetSessionByTokenHash(context.Background(), hash[:])
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
t.Run("logout", func(t *testing.T) {
|
||||
_, err := repo.RevokeSession(context.Background(), hash[:])
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
auth := service.NewAuthService(nil, repo, time.Hour)
|
||||
_, err := auth.ValidateSession(context.Background(), "synthetic-error-context")
|
||||
if !errors.Is(err, service.ErrServiceUnavailable) || !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("service lost Redis unavailable category or diagnostic context")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func redisRouter(f *fixture, client *redisclient.Client) http.Handler {
|
||||
users := postgres.NewUserRepository(f.queries)
|
||||
auth := service.NewAuthService(users, redisrepo.NewSessionRepository(client), time.Hour)
|
||||
userService := service.NewUserService(users)
|
||||
chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), users, userService)
|
||||
messages := service.NewMessageService(postgres.NewMessageRepository(f.queries, f.pool), chats, userService)
|
||||
objects := readyS3Storage()
|
||||
attachments := service.NewAttachmentService(postgres.NewAttachmentRepository(f.queries, f.pool), chats, objects)
|
||||
return httptransport.NewRouter(middleware.NewMiddleware(auth, "auth-test"), handler.NewAuthHandler(auth),
|
||||
handler.NewHealthHandler(f.pool, client, objects), handler.NewChatHandler(chats), handler.NewUserHandler(userService),
|
||||
handler.NewMessageHandler(messages), handler.NewAttachmentHandler(attachments)).Handler()
|
||||
}
|
||||
|
||||
func TestRedisCriticalOutageHTTPAndReadiness(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
router := redisRouter(f, refusedRedis(t))
|
||||
for _, tc := range []struct {
|
||||
name, path string
|
||||
status int
|
||||
}{
|
||||
{"liveness", "/health/live", 200},
|
||||
{"readiness", "/health/ready", 503},
|
||||
{"protected_request", "/api/v1/users/me", 503},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-outage-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
if recorder.Code != tc.status {
|
||||
t.Fatalf("want HTTP %d, got %d", tc.status, recorder.Code)
|
||||
}
|
||||
if tc.status == 503 {
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisPublicHTTPContractIsUnchanged(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
r := newRedisFixture(t)
|
||||
server := httptest.NewServer(redisRouter(f, r.client))
|
||||
t.Cleanup(server.Close)
|
||||
_, source, _, _ := runtime.Caller(0)
|
||||
root := filepath.Clean(filepath.Join(filepath.Dir(source), "..", ".."))
|
||||
// The full acceptance suite performs many Argon2id operations. Under -race
|
||||
// it needs its own budget rather than the 45-second SQL fixture budget.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"teacher_smoke", []string{filepath.Join(root, "tests/smoke.py"), "--base-url", server.URL}},
|
||||
{"auth_normal", []string{filepath.Join(root, "student-tests/auth_contract.py"), "--base-url", server.URL, "--ttl", "3600"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Each independent subprocess gets the full acceptance budget. A smoke
|
||||
// run must not consume part of the following auth suite's allowance.
|
||||
acceptanceCtx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(acceptanceCtx, "python3", tc.args...)
|
||||
cmd.Dir = root
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
for _, line := range strings.Split(string(output), "\n") {
|
||||
if strings.HasPrefix(line, "test_") {
|
||||
// Only method names: never print credentials or subtest values.
|
||||
name, _, _ := strings.Cut(line, " ")
|
||||
t.Log("acceptance progress: " + name)
|
||||
}
|
||||
}
|
||||
if acceptanceCtx.Err() != nil {
|
||||
t.Fatal("HTTP acceptance subprocess exceeded its own execution budget; application operation budgets are unchanged")
|
||||
}
|
||||
// Public clients keep tokens in memory. Show only status diagnostics.
|
||||
for _, line := range strings.Split(string(output), "\n") {
|
||||
if strings.Contains(line, "expected [") && strings.Contains(line, "received") {
|
||||
t.Log(line)
|
||||
}
|
||||
}
|
||||
t.Fatal("HTTP acceptance contract failed with Redis-backed sessions")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestRedisHTTPFullRestartKeepsDeadlineAndRevocation(t *testing.T) {
|
||||
base, hook := os.Getenv("AUTH_TEST_BASE_URL"), os.Getenv("AUTH_TEST_STACK_RESTART_HOOK")
|
||||
if base == "" || hook == "" {
|
||||
t.Skip("set AUTH_TEST_BASE_URL and AUTH_TEST_STACK_RESTART_HOOK for a disposable API+stores stack")
|
||||
}
|
||||
for _, withLogout := range []bool{false, true} {
|
||||
name := "active_only"
|
||||
if withLogout {
|
||||
name = "active_and_revoked"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
username := "restart_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
|
||||
password := "Synthetic:" + uuid.NewString()
|
||||
call := func(method, path, token string, body any, basic bool, want int, dst any) {
|
||||
t.Helper()
|
||||
var data bytes.Buffer
|
||||
if body != nil {
|
||||
if json.NewEncoder(&data).Encode(body) != nil {
|
||||
t.Fatal("cannot encode test request")
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(base, "/")+path, &data)
|
||||
if err != nil {
|
||||
t.Fatal("cannot construct test request")
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if basic {
|
||||
req.SetBasicAuth(username, password)
|
||||
} else if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal("restart HTTP request failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != want {
|
||||
t.Fatalf("%s %s: want %d, got %d", method, path, want, response.StatusCode)
|
||||
}
|
||||
if dst != nil && json.NewDecoder(response.Body).Decode(dst) != nil {
|
||||
t.Fatal("invalid restart response JSON")
|
||||
}
|
||||
}
|
||||
call("POST", "/api/v1/users", "", map[string]string{"username": username, "password": password, "display_name": "Restart fixture"}, false, 201, nil)
|
||||
var active struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &active)
|
||||
hash := f.track(active.Token)
|
||||
before, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
|
||||
if err != nil {
|
||||
t.Fatal("cannot inspect issued session")
|
||||
}
|
||||
if !before.ExpiresAt.Equal(active.ExpiresAt) {
|
||||
t.Fatal("HTTP and Redis expiry differ")
|
||||
}
|
||||
remaining := f.client.PTTL(ctx, f.keys[0]).Val()
|
||||
if remaining < 2*time.Minute {
|
||||
t.Fatal("normal restart suite requires long session TTL")
|
||||
}
|
||||
revoked := ""
|
||||
if withLogout {
|
||||
var other struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &other)
|
||||
revoked = other.Token
|
||||
f.track(revoked)
|
||||
call("DELETE", "/api/v1/auth/sessions/current", revoked, nil, false, 204, nil)
|
||||
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
|
||||
}
|
||||
if exec.CommandContext(ctx, hook).Run() != nil {
|
||||
t.Fatal("real API+stores restart hook failed")
|
||||
}
|
||||
call("GET", "/health/live", "", nil, false, 200, nil)
|
||||
call("GET", "/health/ready", "", nil, false, 200, nil)
|
||||
call("GET", "/api/v1/users/me", active.Token, nil, false, 200, nil)
|
||||
after, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
|
||||
if err != nil {
|
||||
t.Fatal("restart lost session")
|
||||
}
|
||||
if !after.ExpiresAt.Equal(before.ExpiresAt) || after.UserID != before.UserID || !after.CreatedAt.Equal(before.CreatedAt) {
|
||||
t.Fatal("actual API+Redis restart changed session identity/deadline")
|
||||
}
|
||||
if ttl := f.client.PTTL(ctx, f.keys[0]).Val(); ttl <= 0 || ttl >= remaining {
|
||||
t.Fatal("restart reset/removed original TTL")
|
||||
}
|
||||
if revoked != "" {
|
||||
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
|
||||
revokedHash := sha256.Sum256([]byte(revoked))
|
||||
if _, err = f.repo.GetSessionByTokenHash(ctx, revokedHash[:]); err == nil {
|
||||
t.Fatal("revoked credential reappeared after restart")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
repository "highload/internal/repository/postgres"
|
||||
redisrepo "highload/internal/repository/redis"
|
||||
"highload/internal/security"
|
||||
"highload/internal/service"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type fixture struct {
|
||||
admin *pgxpool.Pool
|
||||
pool *pgxpool.Pool
|
||||
config *pgxpool.Config
|
||||
queries *sqlc.Queries
|
||||
users *service.UserService
|
||||
auth *service.AuthService
|
||||
redis *redisFixture
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T) *fixture {
|
||||
t.Helper()
|
||||
f := newDatabaseFixture(t, "AUTH_TEST_DATABASE_URL", 4)
|
||||
f.redis = newRedisFixture(t)
|
||||
userRepo := repository.NewUserRepository(f.queries)
|
||||
f.users = service.NewUserService(userRepo)
|
||||
f.auth = service.NewAuthService(userRepo, redisrepo.NewSessionRepository(f.redis.client), time.Hour)
|
||||
return f
|
||||
}
|
||||
|
||||
// Shared PostgreSQL fixture: attachment transaction checks do not require Redis/S3.
|
||||
func newDatabaseFixture(t *testing.T, environment string, maxConnections int32) *fixture {
|
||||
t.Helper()
|
||||
url := os.Getenv(environment)
|
||||
if url == "" {
|
||||
t.Skip("PENDING_INFRA: set " + environment + " for a dedicated test PostgreSQL")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
config, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
t.Fatal("cannot parse test PostgreSQL configuration (credentials suppressed)")
|
||||
}
|
||||
config.MaxConns = maxConnections
|
||||
config.MinConns = 0
|
||||
config.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
config.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
admin, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
t.Fatal("cannot open test PostgreSQL pool")
|
||||
}
|
||||
t.Cleanup(admin.Close)
|
||||
if err := admin.Ping(ctx); err != nil {
|
||||
t.Fatal("test PostgreSQL is unavailable")
|
||||
}
|
||||
// Only this uniquely named schema is created and dropped. Existing tables
|
||||
// and volumes are never removed. The role needs CREATE SCHEMA permission.
|
||||
schema := "auth_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
quoted := pgx.Identifier{schema}.Sanitize()
|
||||
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+quoted); err != nil {
|
||||
t.Fatal("cannot create isolated test schema")
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx, done := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer done()
|
||||
if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA "+quoted+" CASCADE"); err != nil {
|
||||
t.Error("isolated test schema cleanup failed")
|
||||
}
|
||||
})
|
||||
config = config.Copy()
|
||||
config.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
pool, err := pgxpool.NewWithConfig(ctx, config.Copy())
|
||||
if err != nil {
|
||||
t.Fatal("cannot connect to isolated test schema")
|
||||
}
|
||||
f := &fixture{admin: admin, config: config, ctx: ctx, pool: pool, queries: sqlc.New(pool)}
|
||||
t.Cleanup(func() { f.pool.Close() })
|
||||
_, source, _, ok := runtime.Caller(0)
|
||||
if !ok {
|
||||
t.Fatal("cannot locate migration files")
|
||||
}
|
||||
migrations, err := filepath.Glob(filepath.Join(filepath.Dir(source), "..", "..", "db", "migrations", "*.sql"))
|
||||
if err != nil || len(migrations) == 0 {
|
||||
t.Fatal("migration SQL is missing")
|
||||
}
|
||||
sort.Strings(migrations)
|
||||
for _, path := range migrations {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal("cannot read migration SQL")
|
||||
}
|
||||
// Current migrations are ordinary SQL with Goose Up/Down markers.
|
||||
// This applies schema fixtures; it is NOT a test of Goose version tracking.
|
||||
up, _, _ := strings.Cut(string(data), "-- +goose Down")
|
||||
if !strings.Contains(up, "-- +goose Up") {
|
||||
t.Fatal("test fixture expects SQL migrations with Goose Up/Down markers")
|
||||
}
|
||||
if _, err := f.pool.Exec(ctx, up, pgx.QueryExecModeSimpleProtocol); err != nil {
|
||||
t.Fatal("migration cannot initialize isolated schema")
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fixture) connect(t *testing.T, ttl time.Duration) {
|
||||
t.Helper()
|
||||
pool, err := pgxpool.NewWithConfig(f.ctx, f.config.Copy())
|
||||
if err != nil {
|
||||
t.Fatal("cannot connect to isolated schema")
|
||||
}
|
||||
f.pool = pool
|
||||
f.queries = sqlc.New(pool)
|
||||
userRepo := repository.NewUserRepository(f.queries)
|
||||
sessionRepo := redisrepo.NewSessionRepository(f.redis.client)
|
||||
f.users = service.NewUserService(userRepo)
|
||||
f.auth = service.NewAuthService(userRepo, sessionRepo, ttl)
|
||||
}
|
||||
|
||||
func (f *fixture) user(t *testing.T) (*model.User, string) {
|
||||
t.Helper()
|
||||
password := "Synthetic:" + uuid.NewString()
|
||||
username := "auth_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
|
||||
user, err := f.users.CreateUser(f.ctx, username, "Auth storage", password)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create synthetic user")
|
||||
}
|
||||
return user, password
|
||||
}
|
||||
|
||||
func (f *fixture) session(t *testing.T, user *model.User, password string) *service.CreatedSession {
|
||||
t.Helper()
|
||||
session, err := f.auth.CreateSession(f.ctx, user.Username, password)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create synthetic session")
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
func TestStoragePasswordIsKDFAndDuplicateCannotOverwrite(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
stored, err := f.queries.GetUserByUsername(f.ctx, user.Username)
|
||||
if err != nil || stored.PasswordHash == password || !strings.HasPrefix(stored.PasswordHash, "$argon2id$") {
|
||||
t.Fatal("database did not preserve the selected password KDF")
|
||||
}
|
||||
ok, err := security.VerifyPassword(password, stored.PasswordHash)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("stored password does not verify")
|
||||
}
|
||||
_, err = f.users.CreateUser(f.ctx, user.Username, "Overwrite", password+"x")
|
||||
if !errors.Is(err, service.ErrAlreadyExists) {
|
||||
t.Fatal("duplicate username was not rejected")
|
||||
}
|
||||
after, err := f.queries.GetUserByUsername(f.ctx, user.Username)
|
||||
if err != nil || after.ID != stored.ID || after.PasswordHash != stored.PasswordHash ||
|
||||
after.DisplayName != stored.DisplayName {
|
||||
t.Fatal("failed duplicate registration changed the original user")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageSessionHashAndReconnectPreserveDeadline(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
key := "session:" + hex.EncodeToString(hash[:])
|
||||
row, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
value, getErr := f.redis.client.Get(f.ctx, key).Result()
|
||||
if err != nil || getErr != nil || strings.Contains(key, session.Token) || strings.Contains(value, session.Token) {
|
||||
t.Fatal("selected session storage did not use SHA-256 of the opaque token")
|
||||
}
|
||||
for _, ownedKey := range f.redis.audit.ownedKeys() {
|
||||
storedValue, err := f.redis.client.Get(f.ctx, ownedKey).Result()
|
||||
if err != nil || strings.Contains(ownedKey, session.Token) || strings.Contains(storedValue, session.Token) {
|
||||
t.Fatal("raw session token was persisted in Redis")
|
||||
}
|
||||
}
|
||||
if f.redis.client.Exists(f.ctx, "session:"+session.Token, session.Token).Val() != 0 {
|
||||
t.Fatal("raw token was stored as a Redis key")
|
||||
}
|
||||
if ttl := f.redis.client.PTTL(f.ctx, key).Val(); ttl <= 0 || ttl > time.Hour {
|
||||
t.Fatal("session must have a positive bounded Redis TTL")
|
||||
}
|
||||
if session.TokenType != "Bearer" || len(session.Token) < 32 || row.RevokedAt != nil ||
|
||||
!row.ExpiresAt.Equal(session.ExpiresAt) || !row.ExpiresAt.After(row.CreatedAt) {
|
||||
t.Fatal("invalid stored session metadata")
|
||||
}
|
||||
beforeDeadline := row.ExpiresAt
|
||||
for range 3 {
|
||||
id, err := f.auth.ValidateSession(f.ctx, session.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("valid session rejected or mapped to another user")
|
||||
}
|
||||
}
|
||||
f.pool.Close()
|
||||
// A different process configuration must not reset already stored expiry.
|
||||
f.connect(t, 24*time.Hour)
|
||||
id, err := f.auth.ValidateSession(f.ctx, session.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("new pool/services lost the existing session")
|
||||
}
|
||||
after, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || !after.ExpiresAt.Equal(beforeDeadline) {
|
||||
t.Fatal("reads or reconnection extended session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageWrongCredentialsNeverCreateSession(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
writes := f.redis.audit.writeCount()
|
||||
for _, credentials := range [][2]string{
|
||||
{user.Username, password + "x"}, {"unknown_auth_user", password},
|
||||
} {
|
||||
_, err := f.auth.CreateSession(f.ctx, credentials[0], credentials[1])
|
||||
if !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("wrong credentials did not yield the same unauthorized error")
|
||||
}
|
||||
}
|
||||
if f.redis.audit.writeCount() != writes {
|
||||
t.Fatal("failed login created a session")
|
||||
}
|
||||
for _, token := range []string{"", uuid.NewString()} {
|
||||
if _, err := f.auth.ValidateSession(f.ctx, token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("empty or unknown token accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageRevocationIsPersistentAndSessionSpecific(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
first, second := f.session(t, user, password), f.session(t, user, password)
|
||||
if first.Token == second.Token {
|
||||
t.Fatal("two logins reused the same token")
|
||||
}
|
||||
if err := f.auth.RevokeSession(f.ctx, first.Token); err != nil {
|
||||
t.Fatal("logout failed")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.connect(t, time.Hour)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, first.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("revoked session revived after reconnect")
|
||||
}
|
||||
id, err := f.auth.ValidateSession(f.ctx, second.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("logout affected another session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageExpiredSessionCannotRevive(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
key := "session:" + hex.EncodeToString(hash[:])
|
||||
if err := f.redis.client.PExpire(f.ctx, key, time.Millisecond).Err(); err != nil {
|
||||
t.Fatal("cannot set an expired fixture")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("expired session accepted")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.connect(t, 24*time.Hour)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("new TTL configuration revived an expired session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageShortTTLExpiresAndReLoginWorks(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.auth = service.NewAuthService(repository.NewUserRepository(f.queries),
|
||||
redisrepo.NewSessionRepository(f.redis.client), 2*time.Second)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
if remaining := time.Until(session.ExpiresAt); remaining <= 0 || remaining > 3*time.Second {
|
||||
t.Fatal("two-second TTL was not used for the stored session")
|
||||
}
|
||||
if id, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil || id != user.ID {
|
||||
t.Fatal("fresh short-lived session was rejected")
|
||||
}
|
||||
time.Sleep(max(0, time.Until(session.ExpiresAt)/2))
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil {
|
||||
t.Fatal("session expired before its original deadline")
|
||||
}
|
||||
timer := time.NewTimer(max(0, time.Until(session.ExpiresAt)) + 100*time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-f.ctx.Done():
|
||||
t.Fatal("expiry fixture exceeded its deadline")
|
||||
}
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("short-lived session was accepted after its stored deadline")
|
||||
}
|
||||
fresh := f.session(t, user, password)
|
||||
if fresh.Token == session.Token {
|
||||
t.Fatal("re-login reused the expired token")
|
||||
}
|
||||
if id, err := f.auth.ValidateSession(f.ctx, fresh.Token); err != nil || id != user.ID {
|
||||
t.Fatal("re-login did not produce a usable session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageChatRollbackAfterMemberInsertFailure(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, _ := f.user(t)
|
||||
repo := repository.NewChatRepository(f.queries, f.pool)
|
||||
// A valid first member is inserted before the nonexistent member fails.
|
||||
// Calling the repository bypasses prevalidation and tests real rollback.
|
||||
_, err := repo.CreateChat(f.ctx, "Must roll back", []string{user.ID, uuid.NewString()})
|
||||
if err == nil {
|
||||
t.Fatal("chat with nonexistent member unexpectedly committed")
|
||||
}
|
||||
for _, table := range []string{"chats", "chat_members"} {
|
||||
var count int
|
||||
err := f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+table).Scan(&count)
|
||||
if err != nil || count != 0 {
|
||||
t.Fatal("failed transaction left partial chat or membership rows")
|
||||
}
|
||||
}
|
||||
created, err := repo.CreateChat(f.ctx, "Valid after rollback", []string{user.ID})
|
||||
if err != nil || created == nil {
|
||||
t.Fatal("rollback poisoned subsequent valid transaction")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
repository "highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/storage/s3"
|
||||
httptransport "highload/internal/transport/http"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
const healthFixtureBucket = "health-fixture"
|
||||
|
||||
type readyS3Client struct {
|
||||
mu sync.Mutex
|
||||
objects map[string][]byte
|
||||
}
|
||||
|
||||
func (s *readyS3Client) Do(req *http.Request) (*http.Response, error) {
|
||||
bucketPath := "/" + healthFixtureBucket
|
||||
response := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: http.NoBody}
|
||||
if req.Method == http.MethodHead && req.URL.Path == bucketPath {
|
||||
return response, nil
|
||||
}
|
||||
if !strings.HasPrefix(req.URL.Path, bucketPath+"/attachments/") {
|
||||
return nil, fmt.Errorf("unexpected path in S3 fixture")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
switch req.Method {
|
||||
case http.MethodPut:
|
||||
defer req.Body.Close()
|
||||
data, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.objects[req.URL.Path] = data
|
||||
case http.MethodGet:
|
||||
data, ok := s.objects[req.URL.Path]
|
||||
if !ok {
|
||||
response.StatusCode = http.StatusNotFound
|
||||
return response, nil
|
||||
}
|
||||
response.Body = io.NopCloser(bytes.NewReader(data))
|
||||
response.ContentLength = int64(len(data))
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected method in S3 fixture")
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// Supply local S3 responses for readiness and the attachment upload in the HTTP smoke test.
|
||||
func readyS3Storage() *s3.Storage {
|
||||
return &s3.Storage{
|
||||
Bucket: healthFixtureBucket,
|
||||
Client: awss3.New(awss3.Options{
|
||||
Region: "us-east-1",
|
||||
BaseEndpoint: aws.String("http://s3-fixture.invalid"),
|
||||
UsePathStyle: true,
|
||||
Credentials: aws.AnonymousCredentials{},
|
||||
HTTPClient: &readyS3Client{objects: make(map[string][]byte)},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
type unavailableDB struct{}
|
||||
type unavailableRow struct{}
|
||||
|
||||
func (unavailableRow) Scan(...any) error {
|
||||
return &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
|
||||
}
|
||||
|
||||
func (unavailableDB) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {
|
||||
return pgconn.CommandTag{}, unavailableRow{}.Scan()
|
||||
}
|
||||
|
||||
func (unavailableDB) Query(context.Context, string, ...any) (pgx.Rows, error) {
|
||||
return nil, unavailableRow{}.Scan()
|
||||
}
|
||||
|
||||
func (unavailableDB) QueryRow(context.Context, string, ...any) pgx.Row {
|
||||
return unavailableRow{}
|
||||
}
|
||||
|
||||
func TestSQLUnavailableLoginStopsBeforeSessionCreation(t *testing.T) {
|
||||
queries := sqlc.New(unavailableDB{})
|
||||
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
|
||||
mid := middleware.NewMiddleware(auth, "auth-test")
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("synthetic_user", "Synthetic:password")
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
}
|
||||
|
||||
func TestMiddlewareMalformedAuthWritesExactlyOneError(t *testing.T) {
|
||||
// Invalid syntax must be rejected before asking an auth service or DB.
|
||||
// A nil service deliberately makes an accidental dependency call visible.
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
for _, header := range []string{"", "Basic invalid", "Bearer", "Bearer ",
|
||||
"Bearer invalid token", "Digest invalid"} {
|
||||
t.Run("malformed", func(t *testing.T) {
|
||||
nextCalled := false
|
||||
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { nextCalled = true })
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", header)
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(mid.Auth(next)).ServeHTTP(recorder, request)
|
||||
if nextCalled || recorder.Code != http.StatusUnauthorized {
|
||||
t.Fatal("malformed auth reached business handler or did not yield 401")
|
||||
}
|
||||
if recorder.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
|
||||
t.Fatal("missing contract Bearer challenge")
|
||||
}
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
decoder := json.NewDecoder(recorder.Body)
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
t.Fatal("401 is not one valid JSON object")
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
t.Fatal("middleware wrote more than one response after 401")
|
||||
}
|
||||
if payload.Error.Code != "unauthorized" || payload.Error.RequestID == "" ||
|
||||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
|
||||
t.Fatal("error request ID or code violates contract")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageHTTPAuthRoutingAndLogout(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
userRepo := repository.NewUserRepository(f.queries)
|
||||
chatRepo := repository.NewChatRepository(f.queries, f.pool)
|
||||
chatService := service.NewChatService(chatRepo, userRepo, f.users)
|
||||
messageService := service.NewMessageService(repository.NewMessageRepository(f.queries, f.pool), chatService, f.users)
|
||||
objects := readyS3Storage()
|
||||
attachmentService := service.NewAttachmentService(repository.NewAttachmentRepository(f.queries, f.pool), chatService, objects)
|
||||
router := httptransport.NewRouter(
|
||||
middleware.NewMiddleware(f.auth, "auth-test"), handler.NewAuthHandler(f.auth),
|
||||
handler.NewHealthHandler(f.pool, f.redis.client, objects),
|
||||
handler.NewChatHandler(chatService), handler.NewUserHandler(f.users),
|
||||
handler.NewMessageHandler(messageService),
|
||||
handler.NewAttachmentHandler(attachmentService),
|
||||
).Handler()
|
||||
|
||||
call := func(method, path, token string, login bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(method, path, nil)
|
||||
if login {
|
||||
request.SetBasicAuth(user.Username, password)
|
||||
} else if token != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
if recorder.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("auth response missing X-Request-Id")
|
||||
}
|
||||
return recorder
|
||||
}
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
t.Error("auth router panicked; check constructor/handler wiring")
|
||||
}
|
||||
}()
|
||||
response := call("POST", "/api/v1/auth/sessions", "", true)
|
||||
if response.Code != 201 {
|
||||
t.Fatal("Basic login route did not return 201")
|
||||
}
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &session); err != nil ||
|
||||
session.Token == "" || session.TokenType != "Bearer" {
|
||||
t.Fatal("login route returned invalid session")
|
||||
}
|
||||
other := f.session(t, user, password)
|
||||
response = call("GET", "/api/v1/users/me", session.Token, false)
|
||||
if response.Code != 200 || strings.Contains(response.Body.String(), "password") {
|
||||
t.Fatal("Bearer user route failed or exposed password fields")
|
||||
}
|
||||
response = call("DELETE", "/api/v1/auth/sessions/current", session.Token, false)
|
||||
if response.Code != 204 || response.Body.Len() != 0 {
|
||||
t.Fatal("contract logout path must return empty 204")
|
||||
}
|
||||
for _, route := range [][2]string{
|
||||
{"GET", "/api/v1/users/me"}, {"DELETE", "/api/v1/auth/sessions/current"},
|
||||
} {
|
||||
response = call(route[0], route[1], session.Token, false)
|
||||
if response.Code != 401 || response.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
|
||||
t.Fatal("revoked token was accepted or challenged with wrong scheme")
|
||||
}
|
||||
}
|
||||
if response := call("GET", "/api/v1/users/me", other.Token, false); response.Code != 200 {
|
||||
t.Fatal("logout invalidated an independent session of the same user")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
# Проверки уборки вложений
|
||||
|
||||
Go-проверки используют управляемые ответы для граничного времени, пагинации с
|
||||
пустой страницей и отказов LIST, EXISTS и DELETE. С переменной
|
||||
`LAB4_TEST_DATABASE_URL` существующие тесты транзакции и сообщений дополнительно
|
||||
используют выделенный PostgreSQL.
|
||||
|
||||
```sh
|
||||
go test -count=1 -v ./student-tests/auth_tests -run '^Test(AttachmentCleanup|AttachmentTx|MessageAttachments)'
|
||||
```
|
||||
|
||||
Для сквозной проверки нужен отдельный Compose-проект с именем
|
||||
`lab4-cleanup-<10 шестнадцатеричных символов>`, выделенными volumes и
|
||||
синтетическими credentials от `scripts/init-local.sh`. Запустите его через
|
||||
`up -d --build --wait`, задав отдельные loopback-порты через `LAB4_HTTP_PORT`
|
||||
и `LAB4_POSTGRES_PORT`. Например, значение `0` поручает Docker выбрать порт.
|
||||
Периодический сервис запускайте с `LAB4_CLEANUP_DRY_RUN=true`.
|
||||
На отдельной копии исходников положите локальные credentials вне каталога
|
||||
снимка и задайте отдельный `--project-directory` с путями к этим файлам.
|
||||
При этом в тестовом override укажите абсолютные пути к build contexts,
|
||||
`infra/haproxy.cfg` и `infra/s3/bootstrap.sh` из снимка.
|
||||
|
||||
Передайте тесту локальный JSON с полями `project`, `runtime`, `snapshot`
|
||||
и `base`. `runtime` указывает на каталог временных `.env` и `secrets/`,
|
||||
`snapshot` на проверяемое дерево, а `base` содержит массив аргументов
|
||||
`["docker", "compose", "-p", "<project>", …]`, с которым поднят проект.
|
||||
Файл спецификации содержит пути. Значения ключей в JSON не записываются.
|
||||
|
||||
```sh
|
||||
python3 student-tests/lab4/attachment_compensation.py --spec /tmp/cleanup-spec.json \
|
||||
--output student-tests/results/cleanup-run
|
||||
```
|
||||
|
||||
Сценарий останавливает штатный dry-run сервис в выделенном проекте,
|
||||
выполняет one-shot и поднимает отдельный периодический процесс на время теста.
|
||||
Grace составляет 8 секунд. Пробные объекты, чаты и триггеры принадлежат
|
||||
одноразовому проекту. После проверки удалите только этот проект и его volumes.
|
||||
|
||||
Чтобы запустить тот же сценарий из существующего `run.py`, добавьте в
|
||||
локальный конфиг `hooks.attachment_compensation` со значением
|
||||
`["python3", "student-tests/lab4/attachment_compensation.py", "--spec", "/tmp/cleanup-spec.json", "--as-hook"]`.
|
||||
Режим hook выдаёт наблюдения для существующего валидатора после всех проверок.
|
||||
`--only killed_api_after_put` и `--only lost_response` запускают один сбой
|
||||
и сохраняют его доказательства.
|
||||
|
||||
Потеря ответа моделируется локальным посредником, получающим фактический
|
||||
upstream 201 и закрывающим downstream без передачи HTTP-ответа. После SIGKILL
|
||||
контейнера PostgreSQL может продолжать ждать тестовую advisory-блокировку.
|
||||
Поэтому сначала фиксируются совпадение IP и контейнера, ожидание конкретного
|
||||
PID, появление объекта в S3 и отсутствие строки. Затем проверяются события
|
||||
Docker signal 9 и exit 137, снимается тестовый блокер и проверяется исчезновение
|
||||
того же PID, отсутствие COMMIT и удаление объекта после grace.
|
||||
@@ -0,0 +1,205 @@
|
||||
# Покрытие и воспроизводимость
|
||||
|
||||
Подключённый S3 adapter и результаты на `highload-lab4:8081`: [S3.md](S3.md).
|
||||
Старое описание bucket adapter ниже задаёт его интерфейс; теперь он
|
||||
реализован в `s3_infrastructure.py`, а не остаётся пустой точкой расширения.
|
||||
|
||||
## Источники требований
|
||||
|
||||
Проверены `README.md`, `COURSE.md`, `CONTRIBUTING.md`, `MAINTAINERS.md`,
|
||||
`contracts/README.md`, весь OpenAPI и `contracts/examples.json`,
|
||||
`contracts/infrastructure.json`, `examples/requests.http`, `tests/README.md`,
|
||||
`tests/fixtures/README.md`, публичные HTTP-клиент/сценарии, `infra/README.md`,
|
||||
`infra/haproxy.cfg`, `.env.example`, `compose.example.yaml`, `compose.yaml`,
|
||||
Dockerfile/API/migrate, Makefile, restart/stop hooks и их examples,
|
||||
`evidence/README.md`, `REPORT.md` и `.github/pull_request_template.md`.
|
||||
Каталога `infrastructure/` в этом checkout нет; требования инфраструктуры
|
||||
находятся в `contracts/infrastructure.json` и `infra/`.
|
||||
`.env` и значения secrets не читаются и не копируются в результаты.
|
||||
|
||||
Не следует путать rubric lab4 с rubric lab3: новая задача lab4 — S3/вложения.
|
||||
Идемпотентность, общие сессии, ≥2 API и LB — обязательные сохраняемые
|
||||
возможности. Запрошенные lifecycle/лимиты/rolling проверки включены отдельно;
|
||||
они не заменяют четыре новых пункта уровня 4 lab4.
|
||||
|
||||
| Основание | Проверки |
|
||||
| --- | --- |
|
||||
| Обязательный унаследованный контракт | 400 для отсутствующего/неверного ключа; допустимые 1/128 ASCII и запрещённые символы; тот же 201 и полный Message; эквивалентный JSON с `attachment_ids: []`; 409 без записи; scope user/chat; одновременные повторы через ≥2 реплики; потерянный ответ, подтверждённый COMMIT с клиентским timeout; replay после restart/смены реплики; logout и чужой чат; live/ready |
|
||||
| Повторная проверка ACL | До/после удаления членства исходного пользователя replay даёт 404, после восстановления возвращает исходный Message. Это дополнительная fault-injection проверка обязательного ACL: публичного API изменения участников нет |
|
||||
| Запрошенные эксплуатационные сценарии | Каждая наблюдаемая API-реплика по очереди останавливается/возвращается; тот же токен; чтение/запись ≤10 с от начала stop; исключение ready=503 при live=200; SIGTERM и отказ нового соединения; enforced CPU/RAM всех контейнеров, закрытые API-порты, readiness/grace; rolling с реальной заменой обоих контейнеров; миграции один раз до старта API |
|
||||
| Обязательный lab4, уровень 3 | Публичный smoke с SHA-256 и ACL, persistence всех stores и файла, failover вложения, private S3; собственные attachment-only message, побайтный download, чужой/неизвестный attachment и другой чат, pixel/byte limits, S3 outage |
|
||||
| Обязательный lab4, уровень 4 | Oversize/corrupt/MIME/foreign references; компенсация разрыва и отказа S3/DB с grace; ≥10 параллельных upload с CPU/RAM; повтор bootstrap, отдельные ограниченные credentials и закрытая console/private bucket |
|
||||
| Наше дополнительное качество | `rolling_update_zero_http_errors_quality`: строго ноль ошибок HTTP. Отдельный результат, не подмена буквальной рубрики |
|
||||
| Необязательные рекомендации | Более долгий soak, k6/open-loop, несколько физических hosts, исследования на «5». Не включены в PASS этих сценариев |
|
||||
|
||||
## Запуски и результаты
|
||||
|
||||
```sh
|
||||
export COMPOSE_PROJECT_NAME=highload-lab4
|
||||
python3 student-tests/lab4/run.py --config student-tests/lab4/config.example.json \
|
||||
--output student-tests/results/idempotency-01 --scenario idempotency
|
||||
```
|
||||
|
||||
Другие значения `--scenario`: `restart`, `failover`, `grade4`, `rolling`,
|
||||
`attachments`, `public`, `all`. Полный запуск: `student-tests/verify.py`.
|
||||
Конфиг — JSON без секретов: `base_url`, `ca_file`, `concurrency` (2..64 для race),
|
||||
`request_timeout_seconds`, `failover_window_seconds` (11..60),
|
||||
`rolling_window_seconds` (минимальная длительность), `rolling_max_seconds`
|
||||
(60..300, верхняя граница всего update), `compose_base_argv`,
|
||||
`compose_config_argv`, `api_services`, `lb_services`, `restart_services`, `hooks`.
|
||||
Это Docker Compose runner, не Swarm runner. Rolling рассчитан на две API.
|
||||
Для другого Compose проекта установите `COMPOSE_PROJECT_NAME`/`COMPOSE_FILE`
|
||||
во внешнем окружении; все Docker и public subprocess наследуют их.
|
||||
|
||||
`events.jsonl` содержит каждую операцию GET/POST нагрузки, monotonic время от
|
||||
начала воздействия, latency, успех/ошибку, instance и ID подтверждения,
|
||||
hook timings, Docker IDs/StartedAt/volumes, агрегаты и статусы. Пароли, токены,
|
||||
Authorization, signed URL и bodies регистрации не сохраняются. `summary.json`
|
||||
содержит статусы каждого case; stdout/stderr каждой публичной make-команды
|
||||
сохраняются дословно в `*.stdout.txt`/`*.stderr.txt`.
|
||||
|
||||
Нагрузка — последовательный closed-loop POST+GET; race отдельно запускает
|
||||
`concurrency` одновременных POST одного ключа. Это измерение доступности,
|
||||
не максимальной производительности. RPS, ошибки и error fraction считаются
|
||||
по реальным попыткам. p50/p95/p99 — nearest-rank только успешных POST.
|
||||
При неопределённом ответе повторяется тот же ключ/body. После нагрузки история
|
||||
проверяется на сохранность подтверждений и отсутствие дублей всех попыток.
|
||||
Stop работает параллельно с нагрузкой; recovery считается от начала hook,
|
||||
первый успешный запрос должен быть начат после окончания stop и закончиться
|
||||
≤10 с. Это консервативная верхняя оценка с интервалом опроса клиента.
|
||||
Rolling нагружается до завершения hook, затем проверяются ID, шаги замены и
|
||||
история. Эксперимент на одном Docker-host не доказывает HA PostgreSQL/LB/host.
|
||||
|
||||
`public_lb_endpoint` сверяет порт URL с опубликованным портом выбранного LB
|
||||
и запрещает прямые host bindings API. DNS/соответствие hostname выбранному
|
||||
Docker-host оператор фиксирует при настройке; совпадение порта само по себе
|
||||
не доказывает удалённую DNS-топологию. С одним токеном должны наблюдаться все
|
||||
работающие API-контейнеры; каждый остановленный alias проверяется Docker inspect.
|
||||
Пока LB не работает или есть только одна API, это не PASS. Текущий checkout
|
||||
уже объявляет `api.scale: 2` и `lb`; это декларация, не runtime-доказательство.
|
||||
|
||||
Restart сравнивает все API, PostgreSQL, Redis, S3 и LB до/после: прежние IDs и
|
||||
volumes, новый StartedAt и running. Migrator должен сохранить StartedAt.
|
||||
После restart прежний токен и тот же ключ обязаны вернуть исходный Message.
|
||||
Публичный persistence дополнительно проверяет оригинал файла. Проверки не
|
||||
выжидают 24 часа и не доказывают полный срок удержания ключа этим ожиданием.
|
||||
|
||||
## Hooks: готовые сценарии, ожидающие инфраструктуры
|
||||
|
||||
Hooks — argv-массивы без shell interpolation. Отсутствующий hook даёт
|
||||
`PENDING_INFRA`; фиктивные команды, возвращающие 0, не заменяют доказательства.
|
||||
`config.example.json` подключает существующие restart/stop и собственные
|
||||
start/recover адаптеры. Последние только запускают уже существующие контейнеры
|
||||
API выбранного проекта и проверяют Docker health, не создавая инфраструктуру.
|
||||
Оператору нужны запущенный Docker и готовый синтетический стенд.
|
||||
|
||||
Перед fault проверяется наличие restoration hooks. `TARGET_INSTANCE_ID` —
|
||||
alias целевого процесса; stdout/stderr hook скрыты, кроме описанного JSON.
|
||||
Не применять SQL/network fault adapters к рабочей БД: только одноразовый
|
||||
учебный проект и точно выбранные UUID. Не использовать `down -v`, flush или seed.
|
||||
|
||||
| Hook | Действие и возвращаемое наблюдение |
|
||||
| --- | --- |
|
||||
| `stop_one` / `start_one` | Остановить ровно выбранный API за ≤10 с и оставить остановленным; вернуть тот же контейнер/volume. Stop stdout не нужен |
|
||||
| `restart` | Реально перезапустить API и все stores, сохранив volumes; миграции не повторять. ≤90 с |
|
||||
| `recover_all` | Вернуть обе API после public failover. Пример подключён в config |
|
||||
| `make_unready` / `restore_ready` | Нарушить только доступ выбранного API к критичной зависимости, сохранив доступ LB к API; восстановить. Нужна подходящая сеть/fault adapter, сейчас PENDING |
|
||||
| `probe_health` | Внутренний GET выбранного API: `{"live_status":200,"ready_status":503}`. Private probe не публикует host-порт API |
|
||||
| `lb_timing_evidence` | По действующей конфигурации: `health_interval_seconds`, `health_timeout_seconds`, `configured_max_detection_seconds` — положительные числа; detection ≤10 |
|
||||
| `sigterm_one` / `probe_stopped` | Послать SIGTERM без принудительного SIGKILL, подтвердить остановку/новое TCP-соединение. Probe: `{"accepting":false,"signal":"SIGTERM","forced_kill":false,"exit_code":0,"connection_probe_performed":true}` |
|
||||
| `rolling_update` | Поочерёдно заменить обе API при ≥1 ready, stdout JSON по формату ниже. Самого механизма rolling в текущем checkout нет: PENDING |
|
||||
| `migration_evidence` | Захватить lifecycle до первого старта проекта, вернуть исходные события по формату ниже. `compose ps`/RestartCount не доказывают однократность |
|
||||
| `revoke_access` / `restore_access` | В изолированной синтетической фикстуре временно убрать членство и вернуть его; вход `TEST_CHAT_ID`, `TEST_USER_ID`, `TEST_REPLACEMENT_USER_ID`, `TEST_MESSAGE_ID`, `TEST_IDEMPOTENCY_KEY`. Учитывать FK sender→member. Вернуть `{"action":"revoke_access","validated_exact_message":true}` или restore. Не нужен новый публичный API |
|
||||
|
||||
Rolling JSON: `replaced_processes >= 2`, `min_ready_during_update >= 1`,
|
||||
`steps` для обоих реальных старых/новых ID. Шаг:
|
||||
`{"old_id":"...","new_id":"...","begin_ns":1,"end_ns":2,"ready_survivor_ids":["..."]}`.
|
||||
Шаги не перекрываются; другой готовый backend подтверждён на каждом шаге.
|
||||
Нужны реальные timestamps и IDs, не константы из этого описания.
|
||||
|
||||
Migration JSON: `capture_started_before_stack: true`, `events` — реальные
|
||||
Docker lifecycle события `{service, action, container_id, time_ns, exit_code?}`.
|
||||
Ровно один `migrate/start`, один `migrate/die` с exit_code=0, ≥2 разных
|
||||
`api/start`, все после успешного `die`. Capture должен покрывать также rolling,
|
||||
чтобы повторный migrator не пропал из доказательства. Имена в событиях — роли
|
||||
`api`/`migrate`, адаптер сопоставляет им реальные services.
|
||||
|
||||
## Специальные lab4 adapters
|
||||
|
||||
Эти готовые точки запуска выполняют реализационно-зависимые сценарии и
|
||||
проверяют наблюдения. Пока соответствующие hooks не подключены, результат
|
||||
`PENDING_INFRA`. JSON adapter должен быть обезличенным, без credentials,
|
||||
URL объектов или содержимого S3. Он не должен просто печатать ожидаемые поля:
|
||||
оператор реализует воздействие и измерение, сохраняет первичные доказательства
|
||||
и описывает команды в REPORT. Runner проверяет их структуру/критерии; истинность
|
||||
внутренних воздействий требует ревью адаптера и защиты, как у публичных hooks.
|
||||
|
||||
| Hook | Обязательные наблюдения |
|
||||
| --- | --- |
|
||||
| `attachment_compensation` | `injected_faults` включает `client_disconnect`, `after_s3_before_db`; `grace_seconds > 0`, `untracked_objects_after_grace = 0`, `fresh_objects_preserved = true`, `referenced_objects_preserved = true`. Документировать механизм и cutoff; проверить исходные объекты до/после |
|
||||
| `attachment_parallel_memory` | `concurrent_uploads >= 10`, `successful_uploads >= 10`, `body_bytes > 0`, `duration_seconds > 0`, `memory_limit_bytes`, `oom_kills = 0`, исходные `samples: [{time_seconds,memory_bytes,cpu_percent}]`. Пик RAM ≤ лимита; указать sampling interval и ограничения. Только константа peak без samples не принимается |
|
||||
| `attachment_bucket_security` | `bootstrap_runs >= 2`, `bucket_survived_second_bootstrap = true`; unauthenticated direct GET и LIST (`anonymous_get_status`, `anonymous_list_status`) дают 401/403/404; `api_credentials_are_admin = false`, `api_can_administer_other_buckets = false`, `console_reachable_from_shared_network = false` |
|
||||
| `attachment_s3_failure` | `fault = s3_unreachable`, `upload_status = 503`, `ready_status = 503`, `live_status = 200`, `false_ready_attachments = 0`, `restored_original_checksum_equal = true` |
|
||||
| `attachment_pixels_limit` | Валидная картинка: `width*height > 40000000`, `0 < encoded_bytes <= 10485760`, `upload_status = 413`; fixture генерируется временно, не коммитится большим файлом |
|
||||
|
||||
Базовые negative upload и ACL не требуют этих hooks и запускаются как обычные
|
||||
HTTP cases. Проверка private S3 обращается к внутреннему S3 только из адаптера;
|
||||
весь пользовательский API-трафик идёт через публичный LB.
|
||||
|
||||
## Транзакция Message + attachments до подключения S3
|
||||
|
||||
`student-tests/auth_tests/message_attachments_test.go` дополняет тот же набор
|
||||
Go-тестов и переиспользует общую PostgreSQL-фикстуру из `storage_test.go`.
|
||||
Новая переменная `LAB4_TEST_DATABASE_URL` указывает на выделенную учебную БД
|
||||
с правом CREATE SCHEMA. Redis, S3, сетевой HTTP-сервер и работающий API не нужны.
|
||||
Создаётся уникальная схема, в ней применяются существующие миграции; по
|
||||
завершении удаляется только эта схема. Без переменной каждый case даёт явный
|
||||
`SKIP: PENDING_INFRA`. Если DSN задан, но БД недоступна, это FAIL, а не PASS.
|
||||
|
||||
Проверки вызывают настоящий MessageHandler → MessageService → PostgreSQL
|
||||
repository через `httptest.ResponseRecorder`. Текущий пользователь подставляется
|
||||
в request context: аутентификация проверяется прежними auth-тестами. Вложения
|
||||
заранее создаются как **метаданные**, без настоящих объектов S3. Такой прогон
|
||||
проверяет транзакцию/ACL/историю, но не подтверждает upload/download.
|
||||
|
||||
```sh
|
||||
# DSN подготовить в локальном окружении, не публиковать credentials.
|
||||
GOCACHE=/private/tmp/highload-lab4-go-cache go test -count=1 -json \
|
||||
./student-tests/auth_tests -run '^TestMessageAttachments' \
|
||||
> student-tests/results/message-attachments.jsonl
|
||||
```
|
||||
|
||||
| TestMessageAttachments… | Проверяемое поведение |
|
||||
| --- | --- |
|
||||
| SingleIDServiceRegression | Без БД: настоящий MessageService создаёт сообщение с одним ID без panic; первый и повторный вызов с одинаковыми значениями и UUID в верхнем регистре проходят до репозитория с сохранением UUID-идентичности. Подставной repository не доказывает SQL-idempotency — это проверяют группы ниже |
|
||||
| TextCompatibility | Прежний текстовый JSON без attachment_ids, явный [] на replay: тот же 201/Message, одна строка истории, ноль связей |
|
||||
| OnlyAndOrderZeroToTen | Для каждого количества 0..10 — точный список/порядок в ответе, истории и SQL position=0..n−1. При n>0 текст пуст; другой участник прикрепляет доступные ему файлы чата. Для n=1 первый и повторный POST используют одинаковый JSON с верхним регистром UUID: оба 201, тот же Message, снимок БД не меняется |
|
||||
| InvalidReferencesAreAtomic | Валидный первый ID + неизвестный/ID другого чата; чужой чат. 404, полный снимок messages/links/idempotency/metadata не меняется, ключ можно использовать после исправления запроса |
|
||||
| InvalidListLeavesNoRows | Дубликаты и 11 ID: 400 без изменений БД |
|
||||
| IdempotencyIncludesListAndOrder | Первый body уже содержит UUID заглавными буквами; повторяется тот же body: прежний 201/Message без изменений. Другой порядок/список/количество/text: 409, полный снимок БД неизменен |
|
||||
| ConcurrentReplayDoesNotMultiplyLinks | Восемь одновременных запросов одного ключа: все 201 и один Message, ровно одна запись ключа и три связи, без дублей истории |
|
||||
| LinkFailureRollsBackEverything | Test-only trigger в уникальной схеме падает при второй связи после видимой первой. Неоткатываемая sequence подтверждает достижение fault; сообщение, связи, ключ и metadata полностью откатываются. После снятия fault тот же ключ успешно создаёт ровно одно полное сообщение |
|
||||
|
||||
В `lab4/run.py` расширен существующий `attachment_acl_bytes_and_idempotency`,
|
||||
а не создан второй HTTP-набор: 0..10 ID в порядке запроса, attachment-only,
|
||||
404 без изменения истории, replay и 409 для изменённого порядка/списка,
|
||||
конкурентный повтор. Этот сквозной case требует уже работающего upload и LB;
|
||||
число SQL-связей и настоящий rollback доказываются PostgreSQL-проверками выше.
|
||||
|
||||
Проверка регистра не объявляет изменение строки UUID между запросами
|
||||
эквивалентным body. Первый запрос **сразу** использует верхний регистр,
|
||||
повтор использует точно тот же JSON/ключ. Обязательные оговорки контракта про
|
||||
порядок ключей JSON и отсутствие `attachment_ids` вместо `[]` сохранены;
|
||||
новое правило равенства разных строк запроса не вводится. Порядок и количество
|
||||
ID в ответе проверяются с учётом UUID-идентичности: сервер вправе вернуть
|
||||
каноническое написание. Сами Message первого ответа и replay сравниваются полностью.
|
||||
|
||||
Только сервисная регрессия, без БД/Redis/S3/LB:
|
||||
|
||||
```sh
|
||||
GOCACHE=/private/tmp/highload-lab4-go-cache go test -count=1 -v \
|
||||
./student-tests/auth_tests -run '^TestMessageAttachmentsSingleIDServiceRegression$'
|
||||
```
|
||||
|
||||
Итоговый прогон транзакций, файлового API и унаследованных сценариев
|
||||
приведён в [REPORT.md](../../REPORT.md).
|
||||
@@ -0,0 +1,73 @@
|
||||
# Автоматические проверки S3-инфраструктуры
|
||||
|
||||
Запуск из HighLoad на разрешённом учебном проекте:
|
||||
|
||||
```sh
|
||||
python3 student-tests/lab4/s3_infrastructure.py \
|
||||
--project highload-lab4 --base-url http://127.0.0.1:8081 \
|
||||
--output student-tests/results/s3-run-01
|
||||
```
|
||||
|
||||
Нужен Docker с доступом к выбранному проекту, его `s3`, `s3-init`, две API и LB.
|
||||
Поддержан `highload-lab4` или явно выбранный изолированный `lab4-s3-test-*`.
|
||||
Каталог результатов должен быть новым. Программа **не создаёт стенд**,
|
||||
не меняет Compose/Go/миграции, не удаляет volumes. Она работает с текущим
|
||||
`s3-init` и установленным `rustfs/rc`, использует секреты внутри одноразовых
|
||||
клиентских контейнеров, а не читает/печатает их в Python на host.
|
||||
|
||||
Это реализация уже предусмотренного `hooks.attachment_bucket_security`,
|
||||
подключённая в `config.example.json` через `--as-hook`. Отдельного альтернативного
|
||||
набора проверок нет: standalone и общий lab4 runner вызывают один код.
|
||||
Общий runner передаёт каталог `STUDENT_TEST_EVIDENCE_DIR`, где сохраняется
|
||||
дочерний summary/events. В hook mode stdout содержит только итоговый JSON
|
||||
наблюдений для прежнего валидатора, и только после успеха всех cases.
|
||||
Код 0 — PASS, 1 — FAIL, 2 — PENDING_INFRA; недоступный Docker не становится PASS.
|
||||
|
||||
Конфигурация собственных проверок теперь указывает **8081 и highload-lab4**,
|
||||
чтобы случайно не проверить работающую lab3 на 8080. Для другого проекта
|
||||
поменяйте также `compose_base_argv`, `compose_config_argv` и аргументы hook,
|
||||
а не только URL. Рабочий Compose при этом не редактируется тестом.
|
||||
|
||||
| Сценарий | Наблюдение / основание |
|
||||
| --- | --- |
|
||||
| Реальный API Put/Get/List/Delete | API-ключ записывает синтетические бинарные bytes в `messenger-attachments`; скачивание сравнивается `cmp` и SHA-256; LIST находит объект; после DELETE успешный LIST его не содержит |
|
||||
| Bootstrap дважды | Уже записанный объект переживает **два реальных выполнения** `/bootstrap.sh` через одноразовый `s3-init`. RustFS ID/StartedAt/named volume не меняются. Критерий lab4/4 |
|
||||
| Restart RustFS | Перезапускается только `s3`, без `up/down` и пересоздания stores. ID/volume прежние, StartedAt новый; скачанные bytes совпадают. Сохранность S3 — часть lab4/3 |
|
||||
| Private bucket вне API | Unsigned GET **существующего** объекта и unsigned LIST дают строго HTTP 403. Предшествующий signed GET подтверждает, что ресурс есть. Private bucket — lab4/3 и доказательство на 4 |
|
||||
| Права в другом bucket | Root подготавливает новый временный bucket и известный sentinel. API Put/Get/Delete/List должны дать AccessDenied, а не произвольную сетевую ошибку/NoSuchBucket. Критерий lab4/4 |
|
||||
| CreateBucket и IAM/admin | Создание нового bucket ключом API и IAM user/policy list отклоняются. Дополнительно root читает **реальную** привязку пользователя: ровно `messenger-attachments-api-v1`, без групп; документ разрешает только пять S3-действий ниже. IAM/admin grants отсутствуют. Критерий lab4/4 |
|
||||
| Console | Отдельный клиент в общей сети успешно получает health:9000=200, но соединение к :9001 отклонено. DNS/недоступность всей сети не засчитывается как закрытая консоль. Критерий lab4/4 |
|
||||
| API ×2 за HAProxy | Docker inspect подтверждает ≥2 healthy API без host ports; URL принадлежит опубликованному LB. До/после restart одним и тем же Bearer наблюдаются все реальные X-Instance-Id. Сохраняемая возможность lab3 |
|
||||
| Cleanup | Удаляются только созданные тестом objects и два bucket с UUID в имени. У bucket приложения удаляется только точный тестовый key; рекурсивного удаления bucket, reset IAM, flush и удаления volumes нет |
|
||||
|
||||
Разрешения runtime policy проверяются по точным парам Action/Resource:
|
||||
|
||||
- `s3:ListBucket`, `s3:GetBucketLocation` → `arn:aws:s3:::messenger-attachments`;
|
||||
- `s3:PutObject`, `s3:GetObject`, `s3:DeleteObject` → тот же bucket с `/*`.
|
||||
|
||||
Wildcard для других buckets/IAM, дополнительная policy или унаследованная
|
||||
группа не принимаются. Успешные операции дополнительно проверяют, что это
|
||||
не просто декларация прав при неработающем ключе. Проверяется текущая
|
||||
конкретная bootstrap policy; это не общий аудит всех API RustFS.
|
||||
|
||||
`events.jsonl` хранит исходные exit codes, факт AccessDenied, HTTP statuses,
|
||||
cmp/SHA-256/размер, реальные Docker IDs/StartedAt/volumes и время готовности.
|
||||
Сохраняются также имена **сгенерированных тестом** namespaces для разбора cleanup.
|
||||
Исходные ответы `rc` не сохраняются: IAM user info и ошибки могут содержать
|
||||
access key. В evidence выводятся только проверенные grants и обезличенные
|
||||
наблюдения. Сессионные токены остаются в памяти публичного клиента. Синтетический
|
||||
пользователь для проверки LB остаётся в PostgreSQL: публичный API не имеет
|
||||
удаления пользователей; его данные тест не удаляет через обходной SQL.
|
||||
|
||||
Проверено 11.11.2026 на `highload-lab4`: RustFS 1.0.4, rc v0.1.30, HAProxy 3.2.24.
|
||||
Основной прогон — 10 PASS в
|
||||
[итоговое подтверждение приватности и прав](../../evidence/lab4-final/s3-security.json).
|
||||
Дополнительная read-only проверка реальной policy, уже включённая в общий
|
||||
код, — PASS в `effective-policy/summary.json`. Все 19 проверок runner — PASS.
|
||||
Дополнительный запрос policy не перезапускал S3 повторно.
|
||||
|
||||
Прогон проверяет инфраструктуру и прямой S3 I/O. Go upload/download,
|
||||
ACL вложений через API, компенсация БД/S3 и нагрузка из ≥10 upload здесь
|
||||
не проверяются и не объявляются пройденными. Оценка всей lab4 автоматически
|
||||
не подтверждается. Ручной исходный протокол:
|
||||
[отчёте по лабораторной](../../REPORT.md).
|
||||
@@ -0,0 +1,428 @@
|
||||
"""Section 2.4 runtime checks for a disposable lab4-cleanup-* Compose project."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import quote, urlsplit
|
||||
import uuid
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from run import Client, Evidence, Failure, check
|
||||
|
||||
BUCKET = "messenger-attachments"
|
||||
GRACE = 8
|
||||
LOCK = 9031427
|
||||
|
||||
|
||||
class Experiment:
|
||||
def __init__(self, spec, evidence):
|
||||
check(re.fullmatch(r"lab4-(?:cleanup-[a-f0-9]{10}|final-[a-z0-9-]+)", spec["project"]), "requires an isolated cleanup project")
|
||||
check(spec["base"][:4] == ["docker", "compose", "-p", spec["project"]], "invalid project command")
|
||||
self.spec, self.base, self.e = spec, spec["base"], evidence
|
||||
self.runtime = Path(spec["runtime"])
|
||||
path = Path(spec["snapshot"]) / "tests/fixtures/sample.png"
|
||||
self.png = path.read_bytes()
|
||||
self.sha = hashlib.sha256(self.png).hexdigest()
|
||||
self.c = Client("http://" + self.port("lb", 8080), timeout=8)
|
||||
self.nonce = uuid.uuid4().hex[:10]
|
||||
self.flags = dict(os.environ, LAB4_HTTP_PORT="0", LAB4_POSTGRES_PORT="0")
|
||||
|
||||
def run(self, args, data=None, allowed=(0,), timeout=28):
|
||||
result = subprocess.run(args, input=data, capture_output=True, timeout=timeout, env=self.flags if hasattr(self, "flags") else None)
|
||||
check(result.returncode in allowed, "command failed: " + " ".join(args[:4]) + " exit " + str(result.returncode))
|
||||
return result
|
||||
|
||||
def port(self, service, internal):
|
||||
binding = self.run(self.base + ["port", service, str(internal)]).stdout.decode().strip()
|
||||
check(re.fullmatch(r"127\.0\.0\.1:\d+", binding), "expected loopback binding")
|
||||
return binding
|
||||
|
||||
def sql(self, query):
|
||||
return self.run(self.base + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-X", "-At", "-v", "ON_ERROR_STOP=1", "-c", query]).stdout.decode().strip()
|
||||
|
||||
def s3(self, method, key="", query="", body=None):
|
||||
# Credentials travel over stdin to curl in the isolated S3 container.
|
||||
access = (self.runtime / "secrets/s3_access_key_id").read_text().strip()
|
||||
secret = (self.runtime / "secrets/s3_secret_access_key").read_text().strip()
|
||||
config = f'user = "{access}:{secret}"\n'
|
||||
args = self.base + ["exec", "-T", "s3", "curl", "--config", "-", "-fsS", "--max-time", "8",
|
||||
"--aws-sigv4", "aws:amz:us-east-1:s3", "-X", method]
|
||||
if body is not None:
|
||||
check(body == b"fixture", "unexpected synthetic body")
|
||||
args += ["--data-binary", "fixture"]
|
||||
url = "http://127.0.0.1:9000/" + BUCKET + ("/" + quote(key, safe="/") if key else "") + query
|
||||
return self.run(args + [url], config.encode()).stdout
|
||||
|
||||
def objects(self):
|
||||
xml = ET.fromstring(self.s3("GET", query="?list-type=2"))
|
||||
check(xml.findtext("{*}IsTruncated") in ("false", "False"), "unexpectedly large runtime fixture")
|
||||
return {item.findtext("{*}Key"): datetime.fromisoformat(item.findtext("{*}LastModified").replace("Z", "+00:00"))
|
||||
for item in xml.findall("{*}Contents")}
|
||||
|
||||
def put(self, key):
|
||||
self.s3("PUT", key, body=b"fixture")
|
||||
|
||||
def key(self, label):
|
||||
return "attachments/cleanup-" + self.nonce + "-" + label
|
||||
|
||||
def await_old(self, key, timeout=23):
|
||||
self.wait(lambda: self.age(key) > GRACE + 1, "object never crossed grace period", timeout)
|
||||
|
||||
def age(self, key):
|
||||
date = self.objects().get(key)
|
||||
check(date is not None, "object absent before age check")
|
||||
return (datetime.now(timezone.utc) - date).total_seconds()
|
||||
|
||||
@staticmethod
|
||||
def wait(test, message, timeout=12):
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
result = test()
|
||||
if result:
|
||||
return result
|
||||
check(time.monotonic() < deadline, message)
|
||||
time.sleep(.15)
|
||||
|
||||
def once(self, dry=False, grace=GRACE, exit_code=0):
|
||||
argv = self.base + ["run", "--rm", "--no-deps", "-T", "attachment-cleanup", "/app/attachment-cleanup", "-once",
|
||||
"-dry-run=" + str(dry).lower(), "-grace-period=" + str(grace) + "s", "-pass-timeout=12s"]
|
||||
proc = self.run(argv, allowed=(0,1), timeout=24)
|
||||
self.e.record("one_shot", dry_run=dry, grace_seconds=grace, exit_code=proc.returncode)
|
||||
check(proc.returncode == exit_code, "incorrect cleanup command exit code")
|
||||
|
||||
def setup(self):
|
||||
self.run(self.base + ["stop", "attachment-cleanup"])
|
||||
a,b,e,c = self.c.bootstrap()
|
||||
self.owner,self.member,self.outsider,self.chat = a,b,e,c
|
||||
self.e.record("sql_isolation", value=self.sql("SHOW transaction_isolation"))
|
||||
check(self.sql("SHOW transaction_isolation") == "read committed", "unexpected postgres isolation")
|
||||
|
||||
def upload(self, filename="fixture.png", status=201):
|
||||
return self.c.call("POST", f"/api/v1/chats/{self.chat['id']}/attachments?filename={filename}", status,
|
||||
actor=self.owner, raw=self.png, headers={"Content-Type":"image/png"},
|
||||
schema="Attachment" if status == 201 else None)
|
||||
|
||||
def key_for(self, attachment):
|
||||
aid = str(uuid.UUID(attachment["id"]))
|
||||
return self.sql(f"SELECT object_key FROM attachments WHERE id='{aid}'")
|
||||
|
||||
def count(self, where):
|
||||
return int(self.sql("SELECT count(*) FROM attachments WHERE " + where))
|
||||
|
||||
def count_upload(self, filename):
|
||||
chat_id = str(uuid.UUID(self.chat["id"]))
|
||||
check(re.fullmatch(r"[a-z-]+\.png", filename), "unexpected fixture filename")
|
||||
return self.count(f"chat_id='{chat_id}' AND filename='{filename}'")
|
||||
|
||||
def get(self, attachment):
|
||||
path = "/api/v1/attachments/" + attachment["id"]
|
||||
check(self.c.call("GET", path, actor=self.member, schema="Attachment")["json"] == attachment, "metadata changed")
|
||||
body = self.c.call("GET", path + "/content", actor=self.member)["bytes"]
|
||||
check(body == self.png and hashlib.sha256(body).hexdigest() == self.sha, "original changed")
|
||||
self.c.call("GET", path + "/content", 404, actor=self.outsider)
|
||||
|
||||
def hold_sql(self, statement, lock_visible):
|
||||
p = subprocess.Popen(self.base + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-v", "ON_ERROR_STOP=1"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
p.stdin.write((statement + "\n").encode())
|
||||
p.stdin.flush()
|
||||
self.wait(lock_visible, "SQL holder did not acquire lock")
|
||||
return p
|
||||
except BaseException:
|
||||
p.stdin.close()
|
||||
p.wait(timeout=8)
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def end_holder(proc, sql="ROLLBACK;"):
|
||||
proc.stdin.write((sql + "\n").encode())
|
||||
proc.stdin.close()
|
||||
check(proc.wait(timeout=8) == 0, "lock transaction failed to close")
|
||||
|
||||
def retention(self):
|
||||
orphan = self.key("orphan")
|
||||
outside = "other/cleanup-" + self.nonce
|
||||
busy_commit = self.key("busy-commit")
|
||||
busy_rollback = self.key("busy-rollback")
|
||||
fresh = self.key("fresh")
|
||||
first = self.upload("without-message.png")["json"]
|
||||
linked = self.upload("with-message.png")["json"]
|
||||
self.c.message(self.owner, self.chat, "", attachments=[linked["id"]])
|
||||
referenced = [self.key_for(first), self.key_for(linked)]
|
||||
for key in [orphan, outside, busy_commit, busy_rollback]:
|
||||
self.put(key)
|
||||
self.await_old(busy_rollback)
|
||||
before = self.objects()
|
||||
for key in [orphan, *referenced, busy_commit, busy_rollback]:
|
||||
check((datetime.now(timezone.utc)-before[key]).total_seconds() > GRACE, "expected old fixture")
|
||||
self.once(dry=True)
|
||||
check(self.objects() == before, "dry run changed S3")
|
||||
user, chat = self.owner["id"], self.chat["id"]
|
||||
values = f"('{chat}','{user}','held.png','{busy_commit}','image/png',{len(self.png)},'{self.sha}')"
|
||||
holder = self.hold_sql(f"""BEGIN;
|
||||
SELECT pg_advisory_xact_lock(hashtextextended('{busy_commit}',0));
|
||||
INSERT INTO attachments(chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) VALUES {values};
|
||||
SELECT pg_advisory_xact_lock({LOCK});""",
|
||||
lambda: self.sql(f"SELECT NOT pg_try_advisory_xact_lock({LOCK})")=="t")
|
||||
try:
|
||||
rollback = self.hold_sql(f"""BEGIN;
|
||||
SELECT pg_advisory_xact_lock(hashtextextended('{busy_rollback}',0));
|
||||
SELECT pg_advisory_xact_lock({LOCK + 1});""",
|
||||
lambda: self.sql(f"SELECT NOT pg_try_advisory_xact_lock({LOCK + 1})")=="t")
|
||||
try:
|
||||
check(self.count(f"object_key='{busy_commit}'")==0, "held row visible before COMMIT")
|
||||
self.put(fresh)
|
||||
check(self.age(fresh)<GRACE, "fresh fixture too old")
|
||||
self.once()
|
||||
after = self.objects()
|
||||
check(orphan not in after and all(key in after for key in [outside,fresh,*referenced,busy_commit,busy_rollback]), "apply deleted protected fixtures or kept orphan")
|
||||
finally:
|
||||
self.end_holder(rollback)
|
||||
finally:
|
||||
self.end_holder(holder,"COMMIT;")
|
||||
check(self.count(f"object_key='{busy_commit}'")==1 and self.count(f"object_key='{busy_rollback}'")==0,"unexpected committed rows")
|
||||
self.once()
|
||||
after_unlock = self.objects()
|
||||
check(busy_commit in after_unlock and busy_rollback not in after_unlock, "incorrect disposition after lock release")
|
||||
check(self.age(fresh) < GRACE - 1, "fresh fixture aged before repeated pass")
|
||||
self.once()
|
||||
check(self.objects() == after_unlock, "repeat pass unexpectedly changed objects")
|
||||
self.get(first)
|
||||
self.get(linked)
|
||||
self.e.record("retention", keys={"orphan":orphan,"fresh":fresh,"outside":outside,"linked":referenced[1],
|
||||
"unlinked":referenced[0],"commit":busy_commit,"rowless":busy_rollback},
|
||||
last_modified={k:v.isoformat() for k,v in before.items() if k in [orphan,outside,*referenced,busy_commit,busy_rollback]},
|
||||
dry_run_kept=True, applied=True, fresh_preserved=True, referenced_preserved=True,
|
||||
held_keys_preserved=True, referenced_after_lock=True, rowless_after_lock_deleted=True, repeated=True)
|
||||
|
||||
def rejected_insert(self):
|
||||
before = self.objects()
|
||||
self.sql("""CREATE FUNCTION cleanup_reject_insert() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'synthetic insert failure'; END $$;
|
||||
CREATE TRIGGER cleanup_reject_insert BEFORE INSERT ON attachments FOR EACH ROW
|
||||
WHEN (NEW.filename='cleanup-fault.png') EXECUTE FUNCTION cleanup_reject_insert();""")
|
||||
try:
|
||||
response = self.upload("cleanup-fault.png",500)
|
||||
check(response["json"]["error"]["code"]=="internal_error", "wrong application error")
|
||||
finally:
|
||||
self.sql("DROP TRIGGER cleanup_reject_insert ON attachments; DROP FUNCTION cleanup_reject_insert()")
|
||||
orphan = set(self.objects()) - set(before)
|
||||
check(len(orphan)==1 and self.count_upload("cleanup-fault.png")==0,"fault did not leave exactly one rowless object")
|
||||
key, = orphan
|
||||
check(self.age(key)<GRACE, "orphan check missed grace")
|
||||
self.once()
|
||||
check(key in self.objects(),"cleanup removed a young orphan")
|
||||
self.await_old(key)
|
||||
before_apply = self.objects()[key]
|
||||
self.once()
|
||||
check(key not in self.objects(), "old orphan survived")
|
||||
self.e.record("after_s3_before_db", key=key,last_modified=before_apply.isoformat(),http_status=500,rows=0,
|
||||
survived_young=True, deleted_after_grace=True)
|
||||
|
||||
def raw_request(self, filename):
|
||||
parsed=urlsplit(self.c.base)
|
||||
conn=socket.create_connection((parsed.hostname,parsed.port),timeout=4)
|
||||
headers=f"POST /api/v1/chats/{self.chat['id']}/attachments?filename={filename} HTTP/1.1\r\nHost: {parsed.netloc}\r\nAuthorization: Bearer {self.owner['token']}\r\nContent-Type: image/png\r\nContent-Length: {len(self.png)}\r\nConnection: close\r\n\r\n"
|
||||
conn.sendall(headers.encode())
|
||||
return conn
|
||||
|
||||
def aborted_body(self):
|
||||
before=self.objects()
|
||||
with self.raw_request("cleanup-abort.png") as conn:
|
||||
conn.sendall(self.png[:256])
|
||||
time.sleep(.5)
|
||||
check(self.count_upload("cleanup-abort.png")==0 and self.objects()==before,"interrupted body left an object or row")
|
||||
valid=self.upload("after-abort.png")
|
||||
self.get(valid["json"])
|
||||
self.e.record("client_disconnect", bytes_sent=256,bytes_declared=len(self.png),rows=0,objects_created=0,subsequent_status=valid["status"])
|
||||
|
||||
def killed_api(self):
|
||||
# Block the INSERT in a row trigger. PostgreSQL reports the waiting
|
||||
# client's IP, which identifies the API that already completed PUT.
|
||||
self.sql(f"""CREATE FUNCTION cleanup_hold_insert() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN PERFORM pg_advisory_xact_lock({LOCK}); RETURN NEW; END $$;
|
||||
CREATE TRIGGER cleanup_hold_insert BEFORE INSERT ON attachments FOR EACH ROW
|
||||
WHEN (NEW.filename='cleanup-kill.png') EXECUTE FUNCTION cleanup_hold_insert();""")
|
||||
holder = self.hold_sql(f"BEGIN; SELECT pg_advisory_xact_lock({LOCK});",
|
||||
lambda: self.sql(f"SELECT NOT pg_try_advisory_xact_lock({LOCK})") == "t")
|
||||
target = None
|
||||
result = {}
|
||||
before = self.objects()
|
||||
|
||||
def upload():
|
||||
try:
|
||||
result["status"] = self.upload("cleanup-kill.png", [201, 500, 503])["status"]
|
||||
except Exception as exc:
|
||||
result["error"] = type(exc).__name__
|
||||
|
||||
worker = threading.Thread(target=upload)
|
||||
worker.start()
|
||||
try:
|
||||
waiting = self.wait(lambda: self.sql("""SELECT pid || '|' || host(client_addr) FROM pg_stat_activity
|
||||
WHERE wait_event='advisory' AND query LIKE '%INSERT INTO attachments%'"""),
|
||||
"upload never reached blocked INSERT", timeout=7)
|
||||
pid, ip = waiting.split("|")
|
||||
check(pid.isdecimal(), "invalid blocked backend PID")
|
||||
ids = self.run(self.base + ["ps", "-q", "api"]).stdout.decode().split()
|
||||
replicas = json.loads(self.run(["docker", "inspect", *ids]).stdout)
|
||||
matches = [r["Id"] for r in replicas if any(n["IPAddress"] == ip
|
||||
for n in r["NetworkSettings"]["Networks"].values())]
|
||||
check(len(matches) == 1, "blocked INSERT did not identify a single API")
|
||||
key, = set(self.objects()) - set(before)
|
||||
check(self.count_upload("cleanup-kill.png") == 0, "row already committed")
|
||||
self.e.record("kill_boundary", api=matches[0], backend_pid=int(pid), api_ip=ip,
|
||||
key=key, row_count=0, insert_waiting=True)
|
||||
target = matches[0]
|
||||
since = datetime.now(timezone.utc).isoformat()
|
||||
self.run(["docker", "kill", "--signal", "SIGKILL", target])
|
||||
until = datetime.now(timezone.utc).isoformat()
|
||||
logs = self.run(["docker", "events", "--since", since, "--until", until, "--filter",
|
||||
"container=" + target, "--format", "{{json .}}"]).stdout.decode().splitlines()
|
||||
events = [(item["Action"], item["Actor"]["Attributes"]) for item in map(json.loads, logs)]
|
||||
signal9 = any(action == "kill" and attrs.get("signal") == "9" for action, attrs in events)
|
||||
exit137 = any(action == "die" and attrs.get("exitCode") == "137" for action, attrs in events)
|
||||
check(signal9 and exit137, "Docker did not record SIGKILL and exit 137")
|
||||
# A backend waiting for an advisory lock may not detect a closed
|
||||
# socket until it can continue. Release our fixture blocker first.
|
||||
waiting_after_kill = self.sql(f"SELECT coalesce((SELECT wait_event FROM pg_stat_activity WHERE pid={pid}), 'gone')")
|
||||
self.e.record("sigkill", api=target, signal=9, exit_code=137, backend_wait_before_unblock=waiting_after_kill,
|
||||
client_connection_check_interval=self.sql("SHOW client_connection_check_interval"))
|
||||
self.end_holder(holder)
|
||||
holder = None
|
||||
self.wait(lambda: self.sql(f"SELECT NOT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid={pid})") == "t",
|
||||
"specific upload backend survived after fixture lock release")
|
||||
worker.join(timeout=9)
|
||||
check(result.get("status") not in (None, 201) or "error" in result,
|
||||
"client unexpectedly received successful upload or did not finish")
|
||||
check(self.count_upload("cleanup-kill.png") == 0 and self.age(key) < GRACE, "kill did not leave a young orphan")
|
||||
self.once()
|
||||
check(key in self.objects(), "young orphan was deleted after API kill")
|
||||
self.await_old(key)
|
||||
self.once()
|
||||
check(key not in self.objects(), "orphan survived after grace")
|
||||
self.e.record("killed_api", api=target, key=key, rows=0, young_preserved=True, old_deleted=True,
|
||||
client=result, backend_released=True)
|
||||
finally:
|
||||
if holder:
|
||||
self.end_holder(holder)
|
||||
self.sql("DROP TRIGGER cleanup_hold_insert ON attachments; DROP FUNCTION cleanup_hold_insert()")
|
||||
if target:
|
||||
self.run(["docker", "start", target])
|
||||
worker.join(timeout=9)
|
||||
|
||||
def lost_response(self):
|
||||
# A local test proxy receives the actual upstream response and drops it
|
||||
# before forwarding any bytes. The client sees EOF, then we verify COMMIT.
|
||||
listener=socket.socket()
|
||||
listener.bind(("127.0.0.1",0))
|
||||
listener.listen(1)
|
||||
listener.settimeout(8)
|
||||
result={}
|
||||
def proxy():
|
||||
try:
|
||||
with listener:
|
||||
sock,_=listener.accept()
|
||||
with sock, sock.makefile("rb") as stream:
|
||||
check(stream.readline()==b"POST /lose-response HTTP/1.0\r\n","bad local client")
|
||||
check(stream.readline()==b"\r\n","bad local request headers")
|
||||
result["response"]=self.upload("lost-response.png")
|
||||
except Exception as exc:
|
||||
result["error"]=type(exc).__name__
|
||||
worker=threading.Thread(target=proxy)
|
||||
port=listener.getsockname()[1]
|
||||
worker.start()
|
||||
with socket.create_connection(("127.0.0.1",port),timeout=8) as sock:
|
||||
sock.sendall(b"POST /lose-response HTTP/1.0\r\n\r\n")
|
||||
check(sock.recv(1)==b"", "downstream received response bytes")
|
||||
worker.join(timeout=10)
|
||||
check("response" in result,"upstream failed before COMMIT")
|
||||
att=result["response"]["json"]
|
||||
key=self.key_for(att)
|
||||
check(key and self.count_upload("lost-response.png")==1, "COMMIT not observed")
|
||||
self.await_old(key)
|
||||
self.once()
|
||||
self.get(att)
|
||||
self.e.record("lost_response", key=key, upstream_status=201, downstream_bytes=0, rows=1, survived_apply=True,sha256=self.sha)
|
||||
|
||||
def periodic(self):
|
||||
name=self.spec["project"]+"-periodic"
|
||||
obj=self.key("periodic")
|
||||
self.put(obj)
|
||||
cmd=self.base+["run","-d","--name",name,"--no-deps","attachment-cleanup","/app/attachment-cleanup",
|
||||
"-dry-run=false",f"-grace-period={GRACE}s","-interval=1s","-pass-timeout=9s"]
|
||||
started=time.monotonic()
|
||||
self.run(cmd)
|
||||
try:
|
||||
check(obj in self.objects(),"first pass deleted fresh periodic fixture")
|
||||
self.wait(lambda:obj not in self.objects(),"periodic process did not delete aged object",GRACE+11)
|
||||
self.e.record("periodic", key=obj, deleted_seconds=round(time.monotonic()-started,3))
|
||||
waiting=self.key("signal")
|
||||
self.put(waiting)
|
||||
self.run(["docker","stop","--time","5",name])
|
||||
self.await_old(waiting)
|
||||
holder=self.hold_sql("BEGIN; LOCK TABLE attachments IN ACCESS EXCLUSIVE MODE; SELECT pg_advisory_xact_lock("+str(LOCK)+");",
|
||||
lambda:self.sql(f"SELECT NOT pg_try_advisory_xact_lock({LOCK})")=="t")
|
||||
try:
|
||||
self.run(["docker","start",name])
|
||||
self.wait(lambda:self.sql("SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE wait_event_type='Lock' AND query LIKE '%object_key = $1%' AND pid<>pg_backend_pid())")=="t",
|
||||
"cleanup was not observed waiting in EXISTS",8)
|
||||
self.run(["docker","stop","--time","5",name])
|
||||
state=json.loads(self.run(["docker","inspect",name]).stdout)[0]["State"]
|
||||
check(not state["Running"] and state["ExitCode"]==0, "SIGTERM did not terminate cleanly")
|
||||
check(self.sql("SELECT EXISTS(SELECT 1 FROM pg_locks WHERE locktype='advisory' AND NOT (classid=0 AND objid="+str(LOCK)+"))")=="f",
|
||||
"cleanup session retained its advisory lock")
|
||||
check(waiting in self.objects(),"SIGTERM deleted object without EXISTS")
|
||||
finally:
|
||||
self.end_holder(holder)
|
||||
self.run(["docker","start",name])
|
||||
self.wait(lambda:waiting not in self.objects(),"restart failed to reconcile",12)
|
||||
self.e.record("sigterm", during="EXISTS", exit_code=0, key=waiting, lock_released=True, restart_deleted=True)
|
||||
finally:
|
||||
self.run(["docker","rm","-f",name],allowed=(0,1))
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--spec",required=True,help="private temporary Compose specification")
|
||||
p.add_argument("--output",default=os.environ.get("STUDENT_TEST_EVIDENCE_DIR"))
|
||||
p.add_argument("--as-hook",action="store_true")
|
||||
p.add_argument("--only", choices=["killed_api_after_put", "lost_response"])
|
||||
args=p.parse_args()
|
||||
if not args.output:
|
||||
p.error("--output is required")
|
||||
import contextlib
|
||||
import sys
|
||||
with contextlib.redirect_stdout(sys.stderr if args.as_hook else sys.stdout):
|
||||
e=Evidence(args.output)
|
||||
x=Experiment(json.loads(Path(args.spec).read_text()),e)
|
||||
e.case("setup",x.setup)
|
||||
if e.summary["setup"]["status"]=="PASS":
|
||||
for name,job in [("retention",x.retention),("fault_after_put",x.rejected_insert),
|
||||
("aborted_body",x.aborted_body),("killed_api_after_put",x.killed_api),
|
||||
("lost_response",x.lost_response),("periodic_sigterm",x.periodic)]:
|
||||
if not args.only or name == args.only:
|
||||
e.case(name,job)
|
||||
code=e.finish()
|
||||
if args.as_hook and code==0 and not args.only:
|
||||
rows=[json.loads(line) for line in e.path.read_text().splitlines()]
|
||||
observations={value["event"]:value for value in rows}
|
||||
print(json.dumps({
|
||||
"injected_faults":[name for name in ("client_disconnect","after_s3_before_db") if name in observations],
|
||||
"grace_seconds":observations["one_shot"]["grace_seconds"],
|
||||
"untracked_objects_after_grace":int(not observations["after_s3_before_db"]["deleted_after_grace"]),
|
||||
"fresh_objects_preserved":observations["retention"]["fresh_preserved"],
|
||||
"referenced_objects_preserved":observations["retention"]["referenced_preserved"],
|
||||
}))
|
||||
return code
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
import argparse
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path.cwd()/"tests"))
|
||||
from client import Client
|
||||
parser = argparse.ArgumentParser(description="Check the decoded pixel limit")
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
p = args.output
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
def chunk(name,data):
|
||||
return struct.pack(">I",len(data))+name+data+struct.pack(">I",zlib.crc32(name+data))
|
||||
w,h=6500,6200
|
||||
obj=zlib.compressobj()
|
||||
row=bytes(w+1)
|
||||
blob=b"".join(obj.compress(row) for _ in range(h))+obj.flush()
|
||||
data=b"\x89PNG\r\n\x1a\n"+chunk(b"IHDR",struct.pack(">IIBBBBB",w,h,8,0,0,0,0))+chunk(b"IDAT",blob)+chunk(b"IEND",b"")
|
||||
c=Client(args.base_url)
|
||||
alice,_,_,chat=c.bootstrap()
|
||||
response=c.call("POST","/api/v1/chats/"+chat["id"]+"/attachments?filename=large.png",413,actor=alice,raw=data,headers={"Content-Type":"image/png"})
|
||||
assert response["json"]["error"]["code"]=="payload_too_large"
|
||||
(p/"pixel-limit.json").write_text(json.dumps({"width":w,"height":h,"encoded_bytes":len(data),"upload_status":response["status"]},indent=2)+"\n")
|
||||
@@ -0,0 +1,89 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path.cwd() / "tests"))
|
||||
from client import Client, check
|
||||
parser = argparse.ArgumentParser(description="Check attachment failover and S3 outage on a disposable stack")
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--probe", type=Path, required=True, help="Path to the Linux direct HTTP probe")
|
||||
parser.add_argument("--probe-image", required=True, help="Locally built API image used to run the probe")
|
||||
args = parser.parse_args()
|
||||
project = os.environ["COMPOSE_PROJECT_NAME"]
|
||||
if not project.startswith("lab4-final-"):
|
||||
parser.error("use an isolated lab4-final-* project")
|
||||
c = Client(args.base_url, timeout=3)
|
||||
compose = ["docker", "compose", "--env-file", ".env"]
|
||||
out = args.output
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def run(*argv, **kw):
|
||||
return subprocess.run(argv, check=True, capture_output=True, timeout=65, **kw).stdout
|
||||
|
||||
def sql(query):
|
||||
return run(*compose, "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-Atqc", query).decode().strip()
|
||||
|
||||
def ready():
|
||||
end = time.monotonic()+30
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
return c.call("GET", "/health/ready", schema="Health")
|
||||
except AssertionError:
|
||||
time.sleep(.2)
|
||||
raise AssertionError("API did not recover")
|
||||
|
||||
def direct(cid, method, path, data=b"", token=None):
|
||||
request = (f"{method} {path} HTTP/1.1\n" + (token or "") + "\n").encode()+data
|
||||
response=json.loads(run("docker","run","--rm","-i","--network","container:"+cid,
|
||||
"-v",str(args.probe.resolve())+":/direct:ro","--entrypoint","/direct",args.probe_image,input=request))
|
||||
check(response["instance"], "response from API expected")
|
||||
return response["status"],response["body"].encode()
|
||||
|
||||
def download(bob, att, data):
|
||||
end = time.monotonic()+20
|
||||
failures = 0
|
||||
start=time.monotonic()
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
saved=c.call("GET","/api/v1/attachments/"+att["id"]+"/content",actor=bob)
|
||||
check(saved["bytes"]==data, "download changed")
|
||||
return {"replica":saved["headers"]["X-Instance-Id"], "failures":failures, "seconds":round(time.monotonic()-start,3),"sha256":hashlib.sha256(data).hexdigest()}
|
||||
except AssertionError:
|
||||
failures+=1
|
||||
time.sleep(.2)
|
||||
raise AssertionError("download recovery timed out")
|
||||
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
att,data=c.attachment(alice,chat)
|
||||
phase = c.call("POST", "/api/v1/chats/"+chat["id"]+"/attachments?filename=failover.png",201,actor=alice,raw=data,headers={"Content-Type":"image/png"},schema="Attachment")
|
||||
instance=phase["headers"]["X-Instance-Id"]
|
||||
run("sh","scripts/stop-one.sh",env=dict(os.environ,TARGET_INSTANCE_ID=instance))
|
||||
try:
|
||||
failover=download(bob,phase["json"],data)
|
||||
check(failover["replica"]!=instance,"same replica served failover")
|
||||
finally:
|
||||
run(*compose, "up", "-d","--no-build","--wait","api","lb")
|
||||
(out/"file-failover.json").write_text(json.dumps({"source":instance,**failover},indent=2)+"\n")
|
||||
|
||||
cid=run(*compose,"ps","-q","api").decode().splitlines()[0]
|
||||
before=sql("SELECT count(*) FROM attachments")
|
||||
run(*compose, "stop", "-t", "10", "s3")
|
||||
try:
|
||||
live,_=direct(cid,"GET","/health/live")
|
||||
rd,_=direct(cid,"GET","/health/ready")
|
||||
upload,body=direct(cid,"POST","/api/v1/chats/"+chat["id"]+"/attachments?filename=outage.png",data,alice["token"])
|
||||
print("outage statuses",live,rd,upload,flush=True)
|
||||
check((live,rd,upload)==(200,503,503) and b'unavailable' in body, "wrong API outage statuses")
|
||||
check(sql("SELECT count(*) FROM attachments")==before,"outage created an attachment row")
|
||||
finally:
|
||||
run(*compose,"start","s3")
|
||||
ready()
|
||||
saved=download(bob,att,data)
|
||||
(out/"s3-failure.json").write_text(json.dumps({"fault":"s3_unreachable","live_status":live,"ready_status":rd,"upload_status":upload,"false_ready_attachments":0,"restored_original_checksum_equal":saved["sha256"]==att["sha256"]},indent=2)+"\n")
|
||||
print("PASS: file failover and actual S3 outage/recovery")
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test lifecycle hooks: operate only on existing API containers in an explicit project."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def execute(argv):
|
||||
p = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=15, check=False)
|
||||
if p.returncode:
|
||||
raise RuntimeError("Docker action failed; inspect the selected test project")
|
||||
return p.stdout
|
||||
|
||||
|
||||
def inspect(identifier):
|
||||
return json.loads(execute(["docker", "inspect", identifier]))[0]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=["start_one", "recover_all"])
|
||||
args = parser.parse_args()
|
||||
project = os.environ.get("COMPOSE_PROJECT_NAME")
|
||||
if not project:
|
||||
raise RuntimeError("set COMPOSE_PROJECT_NAME to the explicit synthetic test project")
|
||||
ids = execute(["docker", "ps", "-aq", "--filter", "label=com.docker.compose.project=" + project,
|
||||
"--filter", "label=com.docker.compose.service=api"]).decode().split()
|
||||
values = [inspect(identifier) for identifier in ids]
|
||||
if len(values) < 2:
|
||||
raise RuntimeError("selected project needs at least two existing API containers")
|
||||
for value in values:
|
||||
labels = value["Config"]["Labels"]
|
||||
if labels.get("com.docker.compose.project") != project or labels.get("com.docker.compose.service") != "api":
|
||||
raise RuntimeError("container ownership mismatch")
|
||||
if args.action == "start_one":
|
||||
target = os.environ.get("TARGET_INSTANCE_ID")
|
||||
values = [v for v in values if v["Config"]["Hostname"] == target]
|
||||
if len(values) != 1:
|
||||
raise RuntimeError("target must identify exactly one owned API container")
|
||||
for value in values:
|
||||
if not value["State"]["Running"]:
|
||||
execute(["docker", "start", value["Id"]])
|
||||
deadline = time.monotonic() + 40
|
||||
while time.monotonic() < deadline:
|
||||
current = [inspect(value["Id"])["State"] for value in values]
|
||||
if all(s["Running"] and s.get("Health", {}).get("Status") == "healthy" for s in current):
|
||||
print(json.dumps({"action": args.action, "recovered_containers": len(values)}))
|
||||
return
|
||||
time.sleep(.25)
|
||||
raise RuntimeError("API did not regain Docker health in 40 seconds")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, RuntimeError, ValueError, KeyError, subprocess.SubprocessError) as exc:
|
||||
raise SystemExit("FAIL: " + type(exc).__name__ + ": lifecycle hook unavailable") from None
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"base_url": "http://127.0.0.1:8081",
|
||||
"request_timeout_seconds": 3,
|
||||
"concurrency": 12,
|
||||
"failover_window_seconds": 15,
|
||||
"rolling_window_seconds": 20,
|
||||
"rolling_max_seconds": 120,
|
||||
"compose_base_argv": ["docker", "compose", "--project-name", "highload-lab4"],
|
||||
"compose_config_argv": ["docker", "compose", "--project-name", "highload-lab4", "config", "--format", "json"],
|
||||
"api_services": ["api"],
|
||||
"lb_services": ["lb"],
|
||||
"restart_services": ["api", "postgres", "redis", "s3", "lb", "migrate", "attachment-cleanup"],
|
||||
"hooks": {
|
||||
"restart": ["scripts/restart.sh"],
|
||||
"stop_one": ["scripts/stop-one.sh"],
|
||||
"start_one": ["student-tests/lab4/hooks/start-one.sh"],
|
||||
"recover_all": ["student-tests/lab4/hooks/recover-all.sh"],
|
||||
"attachment_bucket_security": ["python3", "student-tests/lab4/s3_infrastructure.py", "--project", "highload-lab4", "--base-url", "http://127.0.0.1:8081", "--as-hook"]
|
||||
}
|
||||
}
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
exec "${PYTHON:-python3}" "$(dirname "$0")/../compose_action.py" recover_all
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
exec "${PYTHON:-python3}" "$(dirname "$0")/../compose_action.py" start_one
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate both repair directions and measure the scan on a dedicated lab4-final-grade5 project."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
BUCKET = "messenger-attachments"
|
||||
|
||||
|
||||
class Experiment:
|
||||
def __init__(self, args):
|
||||
self.root = args.stack.resolve()
|
||||
self.base = ["docker", "compose", "-p", args.project, "--env-file", ".env"]
|
||||
self.client = Client(args.base_url, timeout=15)
|
||||
self.fixture = ROOT / "tests/fixtures/sample.png"
|
||||
self.original = self.fixture.read_bytes()
|
||||
self.digest = hashlib.sha256(self.original).hexdigest()
|
||||
self.report = {}
|
||||
self.prefix = "attachments/reconcile-" + uuid.uuid4().hex[:12]
|
||||
self.output = args.output.resolve()
|
||||
self.output.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def run(self, command, *, data=None, expected=0, timeout=60):
|
||||
proc = subprocess.run(command, cwd=self.root, input=data, capture_output=True, timeout=timeout)
|
||||
if proc.returncode != expected:
|
||||
raise RuntimeError(f"unexpected exit {proc.returncode}, expected {expected}: {proc.stderr.decode(errors='replace')[-1200:]}")
|
||||
return proc
|
||||
|
||||
def compose(self, *args, **kwargs):
|
||||
return self.run(self.base + list(args), **kwargs)
|
||||
|
||||
def sql(self, statement):
|
||||
return self.compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-X", "-At", "-v", "ON_ERROR_STOP=1", "-c", statement).stdout.decode().strip()
|
||||
|
||||
def s3(self, method, key, status, body=None, conditional=False):
|
||||
access = (self.root / "secrets/s3_access_key_id").read_text().strip()
|
||||
secret = (self.root / "secrets/s3_secret_access_key").read_text().strip()
|
||||
command = ["exec", "-T", "s3", "curl", "--config", "-", "-sS", "--max-time", "10",
|
||||
"-o", "/dev/null", "-w", "%{http_code}", "--aws-sigv4", "aws:amz:us-east-1:s3"]
|
||||
command += ["--head"] if method == "HEAD" else ["-X", method]
|
||||
if body is not None:
|
||||
command += ["--data-binary", body]
|
||||
if conditional:
|
||||
command += ["-H", "If-None-Match: *"]
|
||||
command += ["http://127.0.0.1:9000/" + BUCKET + "/" + quote(key, safe="/")]
|
||||
result = self.compose(*command, data=f'user = "{access}:{secret}"\n'.encode())
|
||||
check(int(result.stdout) == status, f"S3 {method} returned {result.stdout!r}, want {status}")
|
||||
|
||||
def command(self, flags, *, extra=(), expected=0):
|
||||
start = time.monotonic()
|
||||
proc = self.compose("run", "--rm", "--no-deps", "-T", *extra, "attachment-cleanup",
|
||||
"/app/attachment-cleanup", *flags, expected=expected, timeout=150)
|
||||
report = json.loads(proc.stdout)
|
||||
check(report["complete"] == (expected == 0), "incorrect complete flag")
|
||||
report["wall_ms"] = round((time.monotonic() - start) * 1000, 2)
|
||||
return report
|
||||
|
||||
def scan(self, dry=True, grace="4s", **kwargs):
|
||||
return self.command(["-reconcile", f"-dry-run={str(dry).lower()}", "-grace-period=" + grace], **kwargs)
|
||||
|
||||
def restore(self, aid, path, dry, expected=0):
|
||||
return self.command(["-restore-id", aid, "-backup-file", "/backup", "-grace-period=4s",
|
||||
f"-dry-run={str(dry).lower()}"],
|
||||
extra=("-v", f"{path.resolve()}:/backup:ro"), expected=expected)
|
||||
|
||||
def key(self, aid):
|
||||
aid = str(uuid.UUID(aid))
|
||||
key = self.sql(f"SELECT object_key FROM attachments WHERE id='{aid}'")
|
||||
check(re.fullmatch(r"attachments/[0-9a-f-]+", key), "unexpected application key")
|
||||
return key
|
||||
|
||||
def faults(self):
|
||||
self.compose("stop", "attachment-cleanup")
|
||||
alice, bob, eve, chat = self.client.bootstrap()
|
||||
self.owner_id, self.chat_id = str(uuid.UUID(alice["id"])), str(uuid.UUID(chat["id"]))
|
||||
missing, _ = self.client.attachment(alice, chat)
|
||||
orphan, _ = self.client.attachment(alice, chat)
|
||||
used, _ = self.client.attachment(alice, chat)
|
||||
unused, _ = self.client.attachment(alice, chat)
|
||||
msg = self.client.message(alice, chat, "", attachments=[used["id"], missing["id"]])["json"]
|
||||
|
||||
missing_key, orphan_key, used_key, unused_key = map(self.key, (missing["id"], orphan["id"], used["id"], unused["id"]))
|
||||
self.sql(f"DELETE FROM attachments WHERE id='{uuid.UUID(orphan['id'])}'")
|
||||
self.s3("DELETE", missing_key, 204)
|
||||
self.client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 404, actor=bob)
|
||||
self.client.call("GET", "/api/v1/attachments/" + missing["id"], actor=bob, schema="Attachment")
|
||||
|
||||
time.sleep(5)
|
||||
fresh = self.prefix + "-fresh"
|
||||
self.s3("PUT", fresh, 200, body="fresh")
|
||||
dry = self.scan()
|
||||
check(dry["orphan_scan"]["orphan_candidates"] == 1 and dry["orphan_scan"]["objects_deleted"] == 0,
|
||||
"dry-run must find exactly the old orphan")
|
||||
check(dry["missing_scan"]["missing_attachment_ids"] == [missing["id"]], "wrong missing ID")
|
||||
self.s3("HEAD", orphan_key, 200)
|
||||
self.s3("HEAD", missing_key, 404)
|
||||
|
||||
with tempfile.NamedTemporaryFile() as wrong:
|
||||
wrong.write(b"X" + self.original[1:])
|
||||
wrong.flush()
|
||||
os.chmod(wrong.name, 0o644)
|
||||
rejected = self.restore(missing["id"], Path(wrong.name), False, expected=1)
|
||||
self.s3("HEAD", missing_key, 404)
|
||||
restore_dry = self.restore(missing["id"], self.fixture, True)
|
||||
check(restore_dry["restore"] == "would_restore", "dry-run restore did not detect missing object")
|
||||
self.s3("HEAD", missing_key, 404)
|
||||
restored = self.restore(missing["id"], self.fixture, False)
|
||||
check(restored["restore"] == "restored", "restore did not recreate original")
|
||||
again = self.restore(missing["id"], self.fixture, False)
|
||||
check(again["restore"] == "already_present", "repeat restore changed object")
|
||||
self.s3("PUT", missing_key, 412, body="must not overwrite", conditional=True)
|
||||
|
||||
# Use a separate young key so the grace check is deterministic at apply time.
|
||||
self.s3("DELETE", fresh, 204)
|
||||
self.s3("PUT", fresh, 200, body="fresh")
|
||||
applied = self.scan(False)
|
||||
check(applied["orphan_scan"]["objects_deleted"] == 1 and applied["missing_scan"]["missing_objects"] == 0,
|
||||
"apply did not reconcile both directions")
|
||||
self.s3("HEAD", orphan_key, 404)
|
||||
self.s3("HEAD", fresh, 200)
|
||||
self.s3("HEAD", used_key, 200)
|
||||
self.s3("HEAD", unused_key, 200)
|
||||
self.s3("DELETE", fresh, 204)
|
||||
repeated = self.scan(False)
|
||||
check(repeated["orphan_scan"]["orphan_candidates"] == repeated["orphan_scan"]["objects_deleted"] ==
|
||||
repeated["missing_scan"]["missing_objects"] == 0, "repeat performed unexpected work")
|
||||
|
||||
resource = "/api/v1/attachments/" + missing["id"]
|
||||
received = self.client.call("GET", resource + "/content", actor=bob)
|
||||
check(hashlib.sha256(received["bytes"]).hexdigest() == self.digest, "restored bytes changed")
|
||||
check(self.client.call("GET", resource, schema="Attachment", actor=bob)["json"] == missing, "metadata changed")
|
||||
self.client.call("GET", resource + "/content", 404, actor=eve)
|
||||
history = self.client.call("GET", f"/api/v1/chats/{chat['id']}/messages", actor=bob)
|
||||
check(msg in json.loads(history["bytes"])["items"], "restored attachment link changed")
|
||||
|
||||
outage = self.scan(extra=("-e", "S3_ENDPOINT=http://127.0.0.1:1"), expected=1)
|
||||
check("orphan_scan" not in outage and outage["missing_scan"]["missing_objects"] == 0, "outage classified as missing")
|
||||
self.report["faults"] = {
|
||||
"injected": ["delete PostgreSQL row", "delete S3 object", "S3 connection refused"],
|
||||
"dry_run": dry, "bad_backup_rejected": rejected, "restore_dry_run": restore_dry,
|
||||
"restore": restored, "repeat_restore": again, "conditional_existing_put_status": 412,
|
||||
"apply": applied, "repeat": repeated, "s3_outage": outage,
|
||||
"fresh_preserved": True, "linked_preserved": True, "unlinked_preserved": True,
|
||||
"sha256": self.digest, "message_and_metadata_preserved": True, "outsider_status": 404,
|
||||
}
|
||||
|
||||
def seed(self, start, end):
|
||||
access = (self.root / "secrets/s3_access_key_id").read_text().strip()
|
||||
secret = (self.root / "secrets/s3_secret_access_key").read_text().strip()
|
||||
check(re.fullmatch(r"[a-f0-9]+", access) and re.fullmatch(r"[a-f0-9]+", secret), "expected synthetic credentials")
|
||||
seed_script = f"""
|
||||
set -eu
|
||||
export AUTH={shlex.quote(access + ':' + secret)} PREFIX={shlex.quote(self.prefix)}
|
||||
seq {start} {end} | xargs -P 8 -n 1 sh -c 'curl -fsS --max-time 10 -o /dev/null --aws-sigv4 aws:amz:us-east-1:s3 -u "$AUTH" -X PUT --data-binary x "http://127.0.0.1:9000/{BUCKET}/$PREFIX-$1"' sh
|
||||
"""
|
||||
self.compose("exec", "-T", "s3", "sh", data=seed_script.encode(), timeout=120)
|
||||
self.sql(f"""INSERT INTO attachments(chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at)
|
||||
SELECT '{self.chat_id}', '{self.owner_id}', 'synthetic.png', '{self.prefix}-' || i, 'image/png', 1,
|
||||
'{hashlib.sha256(b"x").hexdigest()}', now() - interval '1 minute'
|
||||
FROM generate_series({start}, {end}) AS i""")
|
||||
|
||||
def cost(self):
|
||||
stages = []
|
||||
size = 0
|
||||
for target in (30, 230, 1050):
|
||||
self.seed(size + 1, target)
|
||||
size = target
|
||||
# S3 LastModified may have second resolution. Exclude the boundary.
|
||||
time.sleep(2.1)
|
||||
runs = [self.scan(grace="1s") for _ in range(3)]
|
||||
for run in runs:
|
||||
check(run["orphan_scan"]["objects_scanned"] == size + 3, "unexpected object count")
|
||||
check(run["orphan_scan"]["checked_in_db"] == size + 3, "not all object keys checked")
|
||||
check(run["missing_scan"]["s3_head_attempts"] == size + 3, "not all DB keys checked")
|
||||
check(run["orphan_scan"]["orphan_candidates"] == run["missing_scan"]["missing_objects"] == 0, "benchmark has anomalies")
|
||||
stages.append({"synthetic_pairs": size, "measured_pairs": size + 3, "runs": runs,
|
||||
"median_scan_ms": statistics.median(run["duration_ms"] for run in runs)})
|
||||
self.report["cost"] = stages
|
||||
self.save()
|
||||
|
||||
def save(self):
|
||||
(self.output / "reconcile.json").write_text(json.dumps(self.report, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--stack", type=Path, required=True)
|
||||
p.add_argument("--project", required=True)
|
||||
p.add_argument("--base-url", required=True)
|
||||
p.add_argument("--output", type=Path, required=True)
|
||||
args = p.parse_args()
|
||||
if not re.fullmatch(r"lab4-final-grade5(?:-[a-z0-9-]+)?", args.project):
|
||||
p.error("use an empty disposable lab4-final-grade5 project")
|
||||
experiment = Experiment(args)
|
||||
try:
|
||||
experiment.faults()
|
||||
experiment.save()
|
||||
experiment.cost()
|
||||
finally:
|
||||
experiment.save()
|
||||
print("PASS: bidirectional reconciliation, preservation, repeated apply, and cost profiles")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,365 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Runtime S3 checks for an explicitly selected synthetic Compose project.
|
||||
|
||||
Reuses lab4 Evidence/Client. Secrets stay in the existing one-shot client's
|
||||
secret mounts; raw rc output (which may contain account IDs) is never saved.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import run as checks
|
||||
|
||||
BUCKET = "messenger-attachments"
|
||||
POLICY = "messenger-attachments-api-v1"
|
||||
|
||||
|
||||
def validate_api_policy(user, envelope):
|
||||
"""Validate actual attached grants, including absence of inherited groups."""
|
||||
checks.check(user.get("status") == "enabled" and user.get("policies") == [POLICY] and
|
||||
user.get("memberOf") == [], "API identity has unexpected policies/groups or is disabled")
|
||||
document = envelope.get("policy", {}).get("policy", {})
|
||||
checks.check(isinstance(document, dict) and document.get("Version") == "2012-10-17",
|
||||
"runtime policy document missing")
|
||||
granted = set()
|
||||
for statement in document.get("Statement", []):
|
||||
checks.check(statement.get("Effect") == "Allow" and "NotAction" not in statement and
|
||||
"NotResource" not in statement, "unexpected policy statement")
|
||||
actions, resources = statement.get("Action"), statement.get("Resource")
|
||||
actions = [actions] if isinstance(actions, str) else actions
|
||||
resources = [resources] if isinstance(resources, str) else resources
|
||||
checks.check(isinstance(actions, list) and isinstance(resources, list), "policy grant arrays missing")
|
||||
granted.update((action, resource) for action in actions for resource in resources)
|
||||
bucket = "arn:aws:s3:::" + BUCKET
|
||||
expected = {("s3:ListBucket", bucket), ("s3:GetBucketLocation", bucket),
|
||||
("s3:PutObject", bucket + "/*"), ("s3:GetObject", bucket + "/*"),
|
||||
("s3:DeleteObject", bucket + "/*")}
|
||||
checks.check(granted == expected, "API policy contains unexpected IAM/admin/bucket grants")
|
||||
return [{"action": action, "resource": resource} for action, resource in sorted(granted)]
|
||||
|
||||
|
||||
def denied(result):
|
||||
"""A network/CLI error must never pass as an authorization denial."""
|
||||
text = result.stdout + result.stderr
|
||||
return result.returncode != 0 and bool(re.search(rb"access.?denied|\b403\b|\bforbidden\b", text, re.I))
|
||||
|
||||
|
||||
class Stack:
|
||||
def __init__(self, project, evidence):
|
||||
if project != "highload-lab4" and not re.fullmatch(r"lab4-(s3-test|final)-[a-z0-9-]+", project):
|
||||
raise checks.Failure("use highload-lab4 or an isolated lab4-s3-test-* or lab4-final-* project")
|
||||
self.project, self.evidence = project, evidence
|
||||
self.base = ["docker", "compose", "--project-name", project]
|
||||
self.nonce = uuid.uuid4().hex
|
||||
self.prefix = "student-tests/s3-" + self.nonce + "/"
|
||||
self.key = "roundtrip-" + self.nonce + ".bin"
|
||||
self.control = "student-control-" + self.nonce
|
||||
self.forbidden = "student-forbidden-" + self.nonce
|
||||
self.payload = bytes(range(256)) * 257 + self.nonce.encode()
|
||||
self.digest = hashlib.sha256(self.payload).hexdigest()
|
||||
self.failures, self.bootstrap_runs = [], 0
|
||||
|
||||
def execute(self, argv, input=None, timeout=30):
|
||||
try:
|
||||
return subprocess.run(argv, input=input, cwd=checks.ROOT, capture_output=True,
|
||||
timeout=timeout, check=False)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise checks.Failure("test command unavailable/timed out: " + type(exc).__name__) from None
|
||||
|
||||
def docker_json(self, argv):
|
||||
result = self.execute(argv)
|
||||
if result.returncode:
|
||||
raise checks.Pending("Docker inspection unavailable for selected project")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
def containers(self, service):
|
||||
result = self.execute(self.base + ["ps", "-aq", service])
|
||||
if result.returncode:
|
||||
raise checks.Pending("Docker Compose inspection unavailable")
|
||||
values = []
|
||||
for identifier in result.stdout.decode().split():
|
||||
value = self.docker_json(["docker", "inspect", identifier])[0]
|
||||
labels = value["Config"].get("Labels", {})
|
||||
checks.check(labels.get("com.docker.compose.project") == self.project and
|
||||
labels.get("com.docker.compose.service") == service, "container ownership mismatch")
|
||||
values.append(value)
|
||||
checks.check(values, "selected project has no " + service + " container")
|
||||
return values
|
||||
|
||||
def s3(self):
|
||||
values = self.containers("s3")
|
||||
checks.check(len(values) == 1, "expected one owned RustFS container")
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def snapshot(value):
|
||||
return {"id": value["Id"], "started_at": value["State"]["StartedAt"],
|
||||
"image": value["Config"]["Image"], "running": value["State"]["Running"],
|
||||
"volumes": checks.volume_names(value)}
|
||||
|
||||
def client(self, command, root=False, payload=False):
|
||||
# Only allow generated bucket/key paths and fixed argv. No credentials
|
||||
# enter host Python variables, command arguments or evidence files.
|
||||
setup = '''set -eu
|
||||
rc=/usr/bin/rc
|
||||
app_key=$(cat /run/secrets/s3_access_key_id)
|
||||
app_secret=$(cat /run/secrets/s3_secret_access_key)
|
||||
root_key=$(cat /run/secrets/rustfs_root_access_key)
|
||||
root_secret=$(cat /run/secrets/rustfs_root_secret_key)
|
||||
test "$app_key" != "$root_key"
|
||||
"$rc" alias set app http://s3:9000 "$app_key" "$app_secret" --region us-east-1 --bucket-lookup path >/dev/null 2>&1
|
||||
'''
|
||||
if root:
|
||||
setup += '"$rc" alias set root http://s3:9000 "$root_key" "$root_secret" --region us-east-1 --bucket-lookup path >/dev/null 2>&1\n'
|
||||
if payload:
|
||||
setup += "printf '%s' " + shlex.quote(base64.b64encode(self.payload).decode()) + " | base64 -d > /tmp/source\n"
|
||||
result = self.execute(self.base + ["run", "--rm", "--no-deps", "-T", "--entrypoint", "/bin/sh", "s3-init", "-s"],
|
||||
input=(setup + command + "\n").encode(), timeout=40)
|
||||
return result
|
||||
|
||||
def rc(self, args, *, root=False, payload=False, expect_denied=False, label):
|
||||
command = '"$rc" --json ' + shlex.join(args)
|
||||
result = self.client(command, root=root, payload=payload)
|
||||
refusal = denied(result)
|
||||
self.evidence.record("s3_operation", operation=label, exit_code=result.returncode,
|
||||
authorization_denied=refusal,
|
||||
s3_error_code="AccessDenied" if refusal else None)
|
||||
checks.check(refusal if expect_denied else result.returncode == 0,
|
||||
label + (": expected S3 authorization denial" if expect_denied else ": S3 operation failed"))
|
||||
return result
|
||||
|
||||
def verify_download(self, label):
|
||||
command = '"$rc" --json object copy ' + shlex.quote("app/" + BUCKET + "/" + self.prefix + self.key) + ''' /tmp/received >/dev/null 2>&1
|
||||
cmp /tmp/source /tmp/received
|
||||
sha256sum /tmp/received
|
||||
'''
|
||||
result = self.client(command, payload=True)
|
||||
digest = result.stdout.decode(errors="replace").split()[0] if result.stdout.strip() else ""
|
||||
checks.check(result.returncode == 0 and digest == self.digest,
|
||||
label + ": downloaded bytes differ or GET failed")
|
||||
self.evidence.record("s3_roundtrip", phase=label, byte_equal=True, size_bytes=len(self.payload), sha256=digest)
|
||||
|
||||
def unsigned(self, path):
|
||||
result = self.execute(self.base + ["exec", "-T", "s3", "curl", "-sS", "--max-time", "5",
|
||||
"-o", "/dev/null", "-w", "%{http_code}", "http://127.0.0.1:9000/" + path])
|
||||
checks.check(result.returncode == 0 and re.fullmatch(rb"\d{3}", result.stdout), "unsigned HTTP probe failed")
|
||||
return int(result.stdout)
|
||||
|
||||
def wait_s3(self):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
value = self.s3()
|
||||
if value["State"]["Running"] and value["State"].get("Health", {}).get("Status") == "healthy":
|
||||
return value
|
||||
time.sleep(.5)
|
||||
raise checks.Failure("RustFS did not regain Docker health in 60 seconds")
|
||||
|
||||
def bootstrap(self):
|
||||
# Reuses the actual bootstrap mounted by the existing service. Does not
|
||||
# recreate API/DB, alter Compose or delete/recreate the RustFS volume.
|
||||
for _ in range(2):
|
||||
before = self.snapshot(self.s3())
|
||||
result = self.execute(self.base + ["run", "--rm", "--no-deps", "-T", "s3-init"], timeout=45)
|
||||
self.evidence.record("s3_bootstrap", attempt=self.bootstrap_runs + 1, exit_code=result.returncode)
|
||||
checks.check(result.returncode == 0, "repeated real bootstrap failed")
|
||||
self.bootstrap_runs += 1
|
||||
checks.check(self.snapshot(self.s3()) == before, "bootstrap replaced/restarted RustFS or changed its volume")
|
||||
self.verify_download("bootstrap_" + str(self.bootstrap_runs))
|
||||
|
||||
def restart(self):
|
||||
before = self.snapshot(self.s3())
|
||||
started = time.monotonic()
|
||||
result = self.execute(self.base + ["restart", "--no-deps", "--timeout", "20", "s3"], timeout=35)
|
||||
checks.check(result.returncode == 0, "RustFS restart command failed")
|
||||
after = self.snapshot(self.wait_s3())
|
||||
checks.check(before["id"] == after["id"] and before["volumes"] == after["volumes"] and
|
||||
before["volumes"] and before["started_at"] != after["started_at"],
|
||||
"restart did not preserve the real container/volume or restart its process")
|
||||
self.evidence.record("s3_restart", before=before, after=after, ready_seconds=round(time.monotonic() - started, 3))
|
||||
self.verify_download("after_restart")
|
||||
|
||||
def permissions(self):
|
||||
target = "app/" + BUCKET + "/" + self.prefix
|
||||
listing = self.rc(["bucket", "list", target], label="api_list_allowed_bucket")
|
||||
checks.check(self.key.encode() in listing.stdout, "API LIST did not include its uploaded object")
|
||||
# A real second bucket and known root-written sentinel distinguish a
|
||||
# policy denial from a nonexistent bucket/object and network failures.
|
||||
self.rc(["bucket", "create", "root/" + self.control], root=True, label="prepare_control_bucket")
|
||||
self.rc(["object", "copy", "/tmp/source", "root/" + self.control + "/sentinel.bin"],
|
||||
root=True, payload=True, label="prepare_control_object")
|
||||
for label, args in [
|
||||
("api_other_bucket_put", ["object", "copy", "/tmp/source", "app/" + self.control + "/api-write.bin"]),
|
||||
("api_other_bucket_get", ["object", "copy", "app/" + self.control + "/sentinel.bin", "/tmp/received"]),
|
||||
("api_other_bucket_delete", ["object", "remove", "app/" + self.control + "/sentinel.bin"]),
|
||||
("api_other_bucket_list", ["bucket", "list", "app/" + self.control]),
|
||||
("api_create_bucket", ["bucket", "create", "app/" + self.forbidden]),
|
||||
("api_iam_user_list", ["admin", "user", "list", "app/"]),
|
||||
("api_iam_policy_list", ["admin", "policy", "ls", "app/"]),
|
||||
]:
|
||||
try:
|
||||
self.rc(args, payload=True, expect_denied=True, label=label)
|
||||
except checks.Failure as exc:
|
||||
# Probe every boundary even if one permission is too broad.
|
||||
self.failures.append(str(exc))
|
||||
checks.check(not self.failures, "; ".join(self.failures))
|
||||
|
||||
def private_bucket(self):
|
||||
self.anonymous_get = self.unsigned(BUCKET + "/" + self.prefix + self.key)
|
||||
self.anonymous_list = self.unsigned(BUCKET + "?list-type=2")
|
||||
self.evidence.record("s3_unsigned", object_get_status=self.anonymous_get, bucket_list_status=self.anonymous_list)
|
||||
checks.check(self.anonymous_get == 403 and self.anonymous_list == 403,
|
||||
"known existing object and bucket must return HTTP 403 without a signature")
|
||||
|
||||
def effective_policy(self):
|
||||
# The user-info response contains an access key. Keep it only in memory;
|
||||
# save the validated grants, never the original response/account fields.
|
||||
user = self.client('"$rc" --json admin user info root/ "$app_key"', root=True)
|
||||
policy = self.client('"$rc" --json admin policy info root/ ' + POLICY, root=True)
|
||||
checks.check(user.returncode == policy.returncode == 0, "cannot read actual API policy binding")
|
||||
try:
|
||||
grants = validate_api_policy(json.loads(user.stdout), json.loads(policy.stdout))
|
||||
except ValueError:
|
||||
raise checks.Failure("runtime IAM evidence was not valid JSON") from None
|
||||
self.evidence.record("s3_effective_policy", policy_name=POLICY, inherited_groups=0, grants=grants,
|
||||
root_credentials_distinct=True, iam_admin_grants=0)
|
||||
|
||||
def console(self):
|
||||
raw = self.s3()
|
||||
networks = list(raw.get("NetworkSettings", {}).get("Networks", {}))
|
||||
checks.check(len(networks) == 1, "select a single shared Compose network for the console probe")
|
||||
network = networks[0]
|
||||
labels = self.docker_json(["docker", "network", "inspect", network])[0].get("Labels", {})
|
||||
checks.check(labels.get("com.docker.compose.project") == self.project, "network ownership mismatch")
|
||||
base = ["docker", "run", "--rm", "--pull=never", "--network", network, "--read-only", "--cap-drop", "ALL",
|
||||
"--security-opt", "no-new-privileges:true", "--entrypoint", "curl", raw["Config"]["Image"],
|
||||
"-sS", "--connect-timeout", "2", "--max-time", "3", "-o", "/dev/null", "-w", "%{http_code}"]
|
||||
control = self.execute(base + ["http://s3:9000/health/ready"])
|
||||
checks.check(control.returncode == 0 and control.stdout == b"200", "shared-network control probe failed")
|
||||
result = self.execute(base + ["http://s3:9001/"])
|
||||
self.evidence.record("s3_console", control_status=200, console_curl_exit=result.returncode,
|
||||
console_http_status=result.stdout.decode(errors="replace")[:3])
|
||||
checks.check(result.returncode == 7 and result.stdout == b"000", "console accepts connections on shared network")
|
||||
|
||||
def delete_probe(self):
|
||||
path = "app/" + BUCKET + "/" + self.prefix + self.key
|
||||
self.rc(["object", "remove", path], label="api_delete_allowed_object")
|
||||
listing = self.rc(["bucket", "list", "app/" + BUCKET + "/" + self.prefix], label="api_list_after_delete")
|
||||
checks.check(self.key.encode() not in listing.stdout, "API DELETE left its known object present")
|
||||
|
||||
def cleanup(self):
|
||||
# Fixed generated paths only. Never recursive-delete the application
|
||||
# bucket, remove volumes, reset IAM or touch pre-existing objects.
|
||||
commands = [
|
||||
["object", "remove", "root/" + BUCKET + "/" + self.prefix + self.key],
|
||||
["object", "remove", "root/" + self.control + "/sentinel.bin"],
|
||||
["object", "remove", "root/" + self.control + "/api-write.bin"],
|
||||
["bucket", "remove", "root/" + self.control],
|
||||
["bucket", "remove", "root/" + self.forbidden],
|
||||
]
|
||||
errors = []
|
||||
for args in commands:
|
||||
try:
|
||||
result = self.client('"$rc" --json ' + shlex.join(args), root=True)
|
||||
# Missing generated objects/buckets are normal after an expected
|
||||
# denial; any other error is retained while cleanup continues.
|
||||
missing = bool(re.search(rb"nosuchkey|nosuchbucket|not.?found|\b404\b|does not exist", result.stdout + result.stderr, re.I))
|
||||
self.evidence.record("s3_cleanup", operation=" ".join(args[:2]), target=args[-1],
|
||||
exit_code=result.returncode, already_absent=missing)
|
||||
checks.check(result.returncode == 0 or missing, "could not clean generated S3 fixture")
|
||||
except checks.Failure as exc:
|
||||
errors.append(str(exc))
|
||||
checks.check(not errors, "; ".join(errors))
|
||||
|
||||
|
||||
def topology(stack, base_url, evidence):
|
||||
apis, lbs = stack.containers("api"), stack.containers("lb")
|
||||
checks.check(len(apis) >= 2 and len(lbs) == 1, "expected >=2 API containers behind one LB")
|
||||
for raw in apis:
|
||||
checks.check(raw["State"]["Running"] and raw["State"].get("Health", {}).get("Status") == "healthy",
|
||||
"API is not healthy")
|
||||
checks.check(not any((raw["HostConfig"].get("PortBindings") or {}).values()), "API has a direct host port")
|
||||
config = {"base_url": base_url, "compose_base_argv": stack.base, "api_services": ["api"], "lb_services": ["lb"]}
|
||||
# Bind the check to this explicit project; common inspection defaults would
|
||||
# otherwise risk probing the concurrently running lab3 stack on port 8080.
|
||||
checks.public_endpoint(config, evidence)
|
||||
client = checks.client_for(config)
|
||||
if not hasattr(stack, "actor"):
|
||||
stack.actor = client.user("s3infra")
|
||||
actor = stack.actor
|
||||
aliases = checks.observe_instances(client, actor, count=32)
|
||||
expected = {raw["Config"]["Hostname"] for raw in apis}
|
||||
checks.check(set(aliases) == expected, "same token did not traverse every actual API replica")
|
||||
evidence.record("s3_api_topology", api_ids=sorted(raw["Id"] for raw in apis), observed_instances=aliases,
|
||||
lb_id=lbs[0]["Id"], lb_image=lbs[0]["Config"]["Image"], same_token=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--project", required=True)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8081")
|
||||
parser.add_argument("--output")
|
||||
parser.add_argument("--as-hook", action="store_true", help="emit only the existing attachment_bucket_security observation JSON")
|
||||
args = parser.parse_args()
|
||||
directory = args.output or os.environ.get("STUDENT_TEST_EVIDENCE_DIR")
|
||||
if not directory:
|
||||
if not args.as_hook:
|
||||
parser.error("--output is required outside hook mode")
|
||||
directory = checks.ROOT / "student-tests/results" / ("s3-" + uuid.uuid4().hex)
|
||||
evidence = checks.Evidence(directory)
|
||||
stack = Stack(args.project, evidence)
|
||||
def execute():
|
||||
ready = stack.wait_s3()
|
||||
evidence.record("s3_initial", **stack.snapshot(ready), project=args.project,
|
||||
payload_size_bytes=len(stack.payload), payload_sha256=stack.digest,
|
||||
fixture_prefix=stack.prefix, control_bucket=stack.control, create_probe_bucket=stack.forbidden)
|
||||
checks.check(checks.volume_names(ready), "RustFS has no persistent named volume")
|
||||
try:
|
||||
stack.rc(["object", "copy", "/tmp/source", "app/" + BUCKET + "/" + stack.prefix + stack.key],
|
||||
payload=True, label="api_put_allowed_object")
|
||||
stack.verify_download("before_bootstrap")
|
||||
evidence.case("s3_bootstrap_preserves_object_and_volume", stack.bootstrap)
|
||||
evidence.case("s3_restart_preserves_original_bytes", stack.restart)
|
||||
evidence.case("s3_unsigned_known_object_403", stack.private_bucket)
|
||||
evidence.case("s3_api_bucket_scope_and_iam_denials", stack.permissions)
|
||||
evidence.case("s3_api_effective_policy", stack.effective_policy)
|
||||
evidence.case("s3_console_closed_on_shared_network", stack.console)
|
||||
evidence.case("s3_api_delete_effect", stack.delete_probe)
|
||||
evidence.case("s3_two_replicas_after_restart", lambda: topology(stack, args.base_url, evidence))
|
||||
finally:
|
||||
evidence.case("s3_fixture_cleanup", stack.cleanup)
|
||||
failed = [name for name, value in evidence.summary.items() if value["status"] == "FAIL"]
|
||||
pending = [name for name, value in evidence.summary.items() if value["status"] == "PENDING_INFRA"]
|
||||
checks.check(not failed, "S3 cases failed: " + ", ".join(failed))
|
||||
if pending:
|
||||
raise checks.Pending("S3 cases pending: " + ", ".join(pending))
|
||||
capture = io.StringIO()
|
||||
with contextlib.redirect_stdout(capture if args.as_hook else sys.stdout):
|
||||
evidence.case("s3_two_replicas_before", lambda: topology(stack, args.base_url, evidence))
|
||||
evidence.case("s3_setup_and_scenarios", execute)
|
||||
code = evidence.finish()
|
||||
if code and all(value["status"] != "FAIL" for value in evidence.summary.values()):
|
||||
code = 2 # PENDING_INFRA is distinct from a failed capability check.
|
||||
if args.as_hook:
|
||||
if code:
|
||||
print("S3 checks incomplete/failed; inspect " + str(evidence.directory / "summary.json"), file=sys.stderr)
|
||||
else:
|
||||
print(json.dumps({"bootstrap_runs": stack.bootstrap_runs, "bucket_survived_second_bootstrap": True,
|
||||
"anonymous_get_status": stack.anonymous_get, "anonymous_list_status": stack.anonymous_list,
|
||||
"api_credentials_are_admin": False, "api_can_administer_other_buckets": False,
|
||||
"console_reachable_from_shared_network": False}))
|
||||
return code
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Regression checks for false-positive paths in the student test runner."""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import run
|
||||
import s3_infrastructure
|
||||
|
||||
|
||||
class HarnessTests(unittest.TestCase):
|
||||
def test_s3_cleanup_continues_after_error_and_never_removes_application_bucket(self):
|
||||
stack = s3_infrastructure.Stack("highload-lab4", self.evidence())
|
||||
results = [subprocess.CompletedProcess([], 1, b"", b"AccessDenied")] + [
|
||||
subprocess.CompletedProcess([], 0, b"", b"") for _ in range(4)]
|
||||
with patch.object(stack, "client", side_effect=results) as client:
|
||||
with self.assertRaises(run.Failure):
|
||||
stack.cleanup()
|
||||
self.assertEqual(client.call_count, 5)
|
||||
for call in client.call_args_list:
|
||||
self.assertNotIn("bucket remove root/messenger-attachments", call.args[0])
|
||||
|
||||
def test_s3_policy_rejects_broad_or_inherited_grants(self):
|
||||
bucket = "arn:aws:s3:::messenger-attachments"
|
||||
user = {"status": "enabled", "policies": [s3_infrastructure.POLICY], "memberOf": []}
|
||||
document = {"Version": "2012-10-17", "Statement": [
|
||||
{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": [bucket]},
|
||||
{"Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"], "Resource": [bucket + "/*"]}]}
|
||||
envelope = {"policy": {"policy": document}}
|
||||
s3_infrastructure.validate_api_policy(user, envelope)
|
||||
for defect in ("admin", "other_bucket", "group"):
|
||||
changed_user, changed = json.loads(json.dumps(user)), json.loads(json.dumps(envelope))
|
||||
if defect == "admin":
|
||||
changed["policy"]["policy"]["Statement"][0]["Action"].append("admin:*")
|
||||
elif defect == "other_bucket":
|
||||
changed["policy"]["policy"]["Statement"][1]["Resource"] = ["arn:aws:s3:::*/*"]
|
||||
else:
|
||||
changed_user["memberOf"] = ["unexpected-group"]
|
||||
with self.assertRaises(run.Failure):
|
||||
s3_infrastructure.validate_api_policy(changed_user, changed)
|
||||
|
||||
def test_missing_s3_infrastructure_emits_no_success_hook_json(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = ["s3_infrastructure.py", "--project", "highload-lab4", "--as-hook", "--output", directory]
|
||||
output, errors = io.StringIO(), io.StringIO()
|
||||
with patch("sys.argv", args), patch.object(s3_infrastructure, "Stack") as stack, \
|
||||
patch.object(s3_infrastructure, "topology", side_effect=run.Pending("no Docker")), \
|
||||
contextlib.redirect_stdout(output), contextlib.redirect_stderr(errors):
|
||||
stack.return_value.wait_s3.side_effect = run.Pending("no Docker")
|
||||
code = s3_infrastructure.main()
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(output.getvalue(), "")
|
||||
summary = json.loads((Path(directory) / "summary.json").read_text())
|
||||
self.assertTrue(all(case["status"] == "PENDING_INFRA" for case in summary.values()))
|
||||
|
||||
def test_s3_network_failure_is_not_permission_denial(self):
|
||||
for data in (b"connection refused", b"unrecognized subcommand", b"NoSuchBucket"):
|
||||
self.assertFalse(s3_infrastructure.denied(subprocess.CompletedProcess([], 1, b"", data)))
|
||||
self.assertFalse(s3_infrastructure.denied(subprocess.CompletedProcess([], 0, b"AccessDenied", b"")))
|
||||
self.assertTrue(s3_infrastructure.denied(subprocess.CompletedProcess([], 1, b"", b'{"error":"AccessDenied (403)"}')))
|
||||
|
||||
def test_s3_rejects_unrelated_compose_project(self):
|
||||
with self.assertRaises(run.Failure):
|
||||
s3_infrastructure.Stack("highload-lab3", self.evidence())
|
||||
|
||||
def test_attachment_uuid_response_check_preserves_identity_and_order(self):
|
||||
first = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
|
||||
second = "bbbbbbbb-cccc-4ddd-8eee-ffffffffffff"
|
||||
body = {"text": "", "attachment_ids": [first.upper(), second.upper()]}
|
||||
actor, chat = {"id": "actor"}, {"id": "chat"}
|
||||
|
||||
class Client:
|
||||
def __init__(self, ids):
|
||||
self.ids = ids
|
||||
|
||||
def call(self, *args, **kwargs):
|
||||
return {"json": {"chat_id": "chat", "sender_id": "actor", "text": "", "attachment_ids": self.ids}}
|
||||
|
||||
run.post(Client([first, second]), actor, chat, body, "key")
|
||||
for invalid in ([second, first], [first], [first, first]):
|
||||
with self.assertRaises(run.Failure):
|
||||
run.post(Client(invalid), actor, chat, body, "key")
|
||||
|
||||
def evidence(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
return run.Evidence(temp.name)
|
||||
|
||||
def test_pending_and_failure_never_produce_success_exit(self):
|
||||
for exception, expected in [(run.Pending("LB absent"), "PENDING_INFRA"),
|
||||
(run.Failure("contract mismatch"), "FAIL")]:
|
||||
ev = self.evidence()
|
||||
def action():
|
||||
raise exception
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
ev.case("example", action)
|
||||
self.assertEqual(ev.finish(), 1)
|
||||
self.assertEqual(ev.summary["example"]["status"], expected)
|
||||
|
||||
def test_output_reuse_does_not_overwrite_raw_results(self):
|
||||
ev = self.evidence()
|
||||
ev.record("original")
|
||||
with self.assertRaises(ValueError):
|
||||
run.Evidence(ev.directory)
|
||||
self.assertEqual(json.loads(ev.path.read_text())["event"], "original")
|
||||
|
||||
def test_fault_needs_both_injection_and_restoration(self):
|
||||
with self.assertRaises(run.Pending):
|
||||
run.require_hooks({"hooks": {"make_unready": ["inject"]}}, "make_unready", "restore_ready")
|
||||
|
||||
def test_credential_bearing_or_non_origin_urls_are_rejected(self):
|
||||
for url in ["http://alice:secret@localhost:8080", "http://localhost:8080/path",
|
||||
"http://localhost:8080?token=secret", "http://localhost:8080#fragment"]:
|
||||
with self.assertRaises(run.Failure):
|
||||
run.client_for({"base_url": url})
|
||||
|
||||
def snapshots(self):
|
||||
before, after = {}, {}
|
||||
for name in ["api", "postgres", "redis", "s3", "lb", "migrate"]:
|
||||
value = {"id": name + "-id", "started_at": "before", "volumes": [name + "-data"], "running": True}
|
||||
before[name] = [value]
|
||||
after[name] = [{**value, "started_at": "before" if name == "migrate" else "after"}]
|
||||
return before, after
|
||||
|
||||
def test_restart_rejects_noop_store_and_volume_loss(self):
|
||||
for defect in ["no_restart", "volume_loss", "migrate_reran"]:
|
||||
before, after = self.snapshots()
|
||||
if defect == "no_restart":
|
||||
after["s3"][0]["started_at"] = "before"
|
||||
elif defect == "volume_loss":
|
||||
after["postgres"][0]["volumes"] = []
|
||||
else:
|
||||
after["migrate"][0]["started_at"] = "after"
|
||||
with self.assertRaises(run.Failure):
|
||||
run.verify_restart(before, after, self.evidence())
|
||||
|
||||
def test_restart_accepts_observed_process_transition(self):
|
||||
run.verify_restart(*self.snapshots(), self.evidence())
|
||||
|
||||
def events(self):
|
||||
return {"capture_started_before_stack": True, "events": [
|
||||
{"service": "migrate", "action": "start", "container_id": "m", "time_ns": 1},
|
||||
{"service": "migrate", "action": "die", "container_id": "m", "time_ns": 2, "exit_code": 0},
|
||||
{"service": "api", "action": "start", "container_id": "a", "time_ns": 3},
|
||||
{"service": "api", "action": "start", "container_id": "b", "time_ns": 4}]}
|
||||
|
||||
def test_migration_summary_without_raw_events_is_rejected(self):
|
||||
with self.assertRaises(run.Failure):
|
||||
run.validate_migration_events({"migration_starts": 1, "migration_exit_code": 0})
|
||||
|
||||
def test_duplicate_migration_or_early_api_is_rejected(self):
|
||||
for defect in ["duplicate", "early_api", "failed_exit", "capture_too_late"]:
|
||||
value = self.events()
|
||||
if defect == "duplicate":
|
||||
value["events"].append(dict(value["events"][0]))
|
||||
elif defect == "early_api":
|
||||
value["events"][2]["time_ns"] = 1
|
||||
elif defect == "failed_exit":
|
||||
value["events"][1]["exit_code"] = 1
|
||||
else:
|
||||
value["capture_started_before_stack"] = False
|
||||
with self.assertRaises(run.Failure):
|
||||
run.validate_migration_events(value)
|
||||
|
||||
def test_one_successful_migration_before_two_apis_is_accepted(self):
|
||||
run.validate_migration_events(self.events())
|
||||
|
||||
def test_rolling_summary_needs_nonoverlapping_real_container_steps(self):
|
||||
with self.assertRaises(run.Failure):
|
||||
run.validate_rolling_steps({"replaced_processes": 2, "min_ready_during_update": 1}, {"a", "b"}, {"c", "d"})
|
||||
value = {"steps": [
|
||||
{"old_id": "a", "new_id": "c", "begin_ns": 1, "end_ns": 3, "ready_survivor_ids": ["b"]},
|
||||
{"old_id": "b", "new_id": "d", "begin_ns": 4, "end_ns": 6, "ready_survivor_ids": ["c"]}]}
|
||||
run.validate_rolling_steps(value, {"a", "b"}, {"c", "d"})
|
||||
value["steps"][1]["begin_ns"] = 2
|
||||
with self.assertRaises(run.Failure):
|
||||
run.validate_rolling_steps(value, {"a", "b"}, {"c", "d"})
|
||||
|
||||
def test_adapters_cannot_return_only_pass_true(self):
|
||||
for name in ["attachment_compensation", "attachment_parallel_memory", "attachment_bucket_security",
|
||||
"attachment_s3_failure", "attachment_pixels_limit"]:
|
||||
with self.assertRaises(run.Failure):
|
||||
run.validate_attachment_observations(name, {"pass": True})
|
||||
|
||||
def test_load_history_rejects_duplicates_and_lost_confirmations(self):
|
||||
result = {"_attempted_texts": {"a", "b"}, "_confirmed_texts": {"a"}}
|
||||
for messages in [[{"text": "a"}, {"text": "a"}], [{"text": "b"}]]:
|
||||
with patch.object(run, "history", return_value=messages), self.assertRaises(run.Failure):
|
||||
run.verify_load_history(None, None, None, result)
|
||||
|
||||
def test_public_lb_check_rejects_direct_api_port_binding(self):
|
||||
def identifiers(_config, service, all_containers=False):
|
||||
return [service]
|
||||
def inspect(identifier):
|
||||
if identifier == "lb":
|
||||
return {"NetworkSettings": {"Ports": {"8080/tcp": [{"HostPort": "8080", "HostIp": "127.0.0.1"}]}}}
|
||||
return {"HostConfig": {"PortBindings": {"8080/tcp": [{"HostPort": "8081"}]}}}
|
||||
with patch.object(run, "compose_ids", identifiers), patch.object(run, "inspect_container", inspect):
|
||||
with self.assertRaises(run.Failure):
|
||||
run.public_endpoint({"base_url": "http://localhost:8080"}, self.evidence())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,118 @@
|
||||
import argparse
|
||||
import collections
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
|
||||
root = Path.cwd()
|
||||
sys.path.insert(0, str(root / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
parser = argparse.ArgumentParser(description="Measure memory on two disposable API replicas")
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--project", required=True)
|
||||
parser.add_argument("--fixtures", type=Path, required=True, help="Directory containing generated load.png and load.jpg")
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
out = args.output
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
base, project, fixture_dir = args.base_url, args.project, args.fixtures
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(["docker", *args], text=True, timeout=20).strip()
|
||||
|
||||
def api_ids():
|
||||
return docker("ps", "-q", "--filter", "label=com.docker.compose.project=" + project,
|
||||
"--filter", "label=com.docker.compose.service=api").splitlines()
|
||||
|
||||
def memory(cid):
|
||||
values = docker("exec", cid, "sh", "-c", "cd /sys/fs/cgroup && cat memory.current memory.peak memory.max memory.events").splitlines()
|
||||
return dict(zip(("current", "peak", "limit"), map(int, values[:3]))) | {
|
||||
"events": {k: int(v) for k, v in (line.split() for line in values[3:])},
|
||||
"state": json.loads(docker("inspect", "--format", "{{json .State}}", cid)),
|
||||
"restarts": int(docker("inspect", "--format", "{{.RestartCount}}", cid)),
|
||||
}
|
||||
|
||||
def profile(name, files):
|
||||
c = Client(base)
|
||||
actor = c.user("load")
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=actor, body={
|
||||
"title": "Load " + name, "member_ids": [actor["id"]]}, schema="Chat")["json"]
|
||||
ids = api_ids()
|
||||
check(len(ids) == 2, "expected both API replicas")
|
||||
before = {cid: memory(cid) for cid in ids}
|
||||
workers = len(files)
|
||||
gate = threading.Barrier(workers + 1)
|
||||
samplers = []
|
||||
stop = threading.Event()
|
||||
sampled = {cid: [] for cid in ids}
|
||||
def sample(cid):
|
||||
proc = subprocess.Popen(["docker", "exec", cid, "sh", "-c",
|
||||
"for i in $(seq 1 240); do read -r m </sys/fs/cgroup/memory.current || exit; printf '%s\\n' \"$m\"; sleep 0.05; done"],
|
||||
stdout=subprocess.PIPE, text=True)
|
||||
try:
|
||||
for line in proc.stdout:
|
||||
sampled[cid].append((round(time.monotonic() - start, 3), int(line)))
|
||||
if stop.is_set():
|
||||
break
|
||||
finally:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
def upload_item(item):
|
||||
i, (filename, mime, data) = item
|
||||
client = Client(base, timeout=18)
|
||||
gate.wait(timeout=12)
|
||||
try:
|
||||
res = client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename),
|
||||
[201, 429, 500, 503], actor=actor, raw=data, headers={"Content-Type": mime})
|
||||
if res["status"] == 201:
|
||||
check(json.loads(res["bytes"])["sha256"] == hashlib.sha256(data).hexdigest(), "checksum changed")
|
||||
return {"index": i, "status": res["status"], "instance": res["headers"]["X-Instance-Id"], "seconds": res["elapsed"]}
|
||||
except Exception as exc:
|
||||
return {"index": i, "error": str(exc)}
|
||||
start = time.monotonic()
|
||||
for cid in ids:
|
||||
worker = threading.Thread(target=sample, args=(cid,))
|
||||
worker.start()
|
||||
samplers.append(worker)
|
||||
time.sleep(0.35)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
|
||||
pending = [executor.submit(upload_item, item) for item in enumerate(files)]
|
||||
gate.wait(timeout=12)
|
||||
results = [job.result() for job in pending]
|
||||
time.sleep(0.25)
|
||||
stop.set()
|
||||
for worker in samplers:
|
||||
worker.join(timeout=10)
|
||||
after = {cid: memory(cid) for cid in ids}
|
||||
states = {}
|
||||
for cid in ids:
|
||||
first, last = before[cid], after[cid]
|
||||
states[cid] = {"before_peak": first["peak"], "after_peak": last["peak"], "limit": last["limit"],
|
||||
"samples": sampled[cid], "events_delta": {k: v - first["events"][k] for k,v in last["events"].items()},
|
||||
"restart_delta": last["restarts"] - first["restarts"],
|
||||
"same_start": first["state"]["StartedAt"] == last["state"]["StartedAt"],
|
||||
"oom_killed": last["state"]["OOMKilled"]}
|
||||
report = {"clients": workers, "files": [{"name": a, "mime": b, "bytes": len(c), "sha256": hashlib.sha256(c).hexdigest()} for a,b,c in files],
|
||||
"statuses": dict(collections.Counter(r.get("status", "error") for r in results)),
|
||||
"results": results, "replicas": states, "sampling_seconds": 0.05}
|
||||
(out / ("memory-" + name + ".json")).write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(name, report["statuses"], {k: v["after_peak"] for k,v in states.items()}, flush=True)
|
||||
check(all(v["samples"] and v["same_start"] and v["restart_delta"] == 0 and not v["oom_killed"]
|
||||
and not v["events_delta"].get("oom") and not v["events_delta"].get("oom_kill") for v in states.values()), "OOM or restart")
|
||||
check(all(r.get("status") in (201, 429) for r in results), "unexpected upload results")
|
||||
check(len({r["instance"] for r in results if r["status"] == 201}) == 2, "need successes on both replicas")
|
||||
if name == "normal":
|
||||
check(report["statuses"].get(201, 0) >= 10, "normal profile did not complete ten uploads")
|
||||
|
||||
normal = (root / "tests/fixtures/sample.png").read_bytes()
|
||||
png = (fixture_dir / "load.png").read_bytes()
|
||||
jpeg = (fixture_dir / "load.jpg").read_bytes()
|
||||
profile("normal", [("sample.png", "image/png", normal)] * 12)
|
||||
profile("heavy", [("load.png", "image/png", png), ("load.jpg", "image/jpeg", jpeg)] * 6)
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One entry point: existing Go checks, runner regression checks, public and student scenarios."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--config", default="student-tests/lab4/config.example.json")
|
||||
p.add_argument("--project", required=True, help="explicit synthetic Compose project to test")
|
||||
p.add_argument("--output", required=True, help="new, empty directory for original results")
|
||||
args = p.parse_args()
|
||||
output = Path(args.output).resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
if any(output.iterdir()):
|
||||
p.error("output must be empty; never overwrite a previous experiment")
|
||||
env = dict(os.environ, COMPOSE_PROJECT_NAME=args.project)
|
||||
env.setdefault("GOCACHE", "/private/tmp/highload-lab4-go-cache" if sys.platform == "darwin"
|
||||
else "/tmp/highload-lab4-go-cache")
|
||||
summary = {"time_utc": datetime.now(timezone.utc).isoformat(), "project": args.project,
|
||||
"scope": "lab4 student checks; no automatic grade", "checks": {}}
|
||||
commands = [
|
||||
("contract_structure", ["make", "check", "PYTHON=" + sys.executable], 30),
|
||||
("go_tests", ["go", "test", "-count=1", "-json", "./..."], 180),
|
||||
("runner_regressions", [sys.executable, "-m", "unittest", "discover", "-s", "student-tests/lab4", "-p", "test_*.py", "-v"], 30),
|
||||
("lab4_scenarios", [sys.executable, "student-tests/lab4/run.py", "--config", args.config,
|
||||
"--output", str(output / "lab4"), "--scenario", "all"], 1800)]
|
||||
for name, argv, timeout in commands:
|
||||
print("Running " + name, flush=True)
|
||||
try:
|
||||
with (output / (name + ".stdout.txt")).open("wb") as stdout, (output / (name + ".stderr.txt")).open("wb") as stderr:
|
||||
proc = subprocess.run(argv, cwd=ROOT, env=env, stdout=stdout, stderr=stderr, timeout=timeout, check=False)
|
||||
item = {"status": "PASS" if proc.returncode == 0 else "FAIL", "exit_code": proc.returncode}
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
item = {"status": "FAIL", "detail": type(exc).__name__}
|
||||
if name == "go_tests":
|
||||
events = []
|
||||
for line in (output / (name + ".stdout.txt")).read_text(errors="replace").splitlines():
|
||||
try:
|
||||
events.append(json.loads(line))
|
||||
except ValueError:
|
||||
pass
|
||||
counts = Counter(e["Action"] for e in events if "Test" in e and e.get("Action") in ("pass", "skip", "fail"))
|
||||
item["test_events"] = dict(counts)
|
||||
item["pending_tests"] = [e["Package"] + "/" + e["Test"] for e in events if e.get("Action") == "skip" and "Test" in e]
|
||||
if counts["skip"]:
|
||||
summary["checks"]["go_storage_and_restart_coverage"] = {
|
||||
"status": "PENDING_INFRA", "detail": "Go skip events are not proof of storage/restart behavior"}
|
||||
if name == "lab4_scenarios" and (output / "lab4/summary.json").is_file():
|
||||
statuses = Counter(v["status"] for v in json.loads((output / "lab4/summary.json").read_text()).values())
|
||||
item["case_statuses"] = dict(statuses)
|
||||
if not statuses["FAIL"] and statuses["PENDING_INFRA"]:
|
||||
item["status"] = "PENDING_INFRA"
|
||||
summary["checks"][name] = item
|
||||
print(item["status"] + " " + name, flush=True)
|
||||
summary["status"] = "PASS" if all(v["status"] == "PASS" for v in summary["checks"].values()) else "INCOMPLETE"
|
||||
(output / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
|
||||
print(summary["status"] + ": " + str(output / "summary.json"), flush=True)
|
||||
return 0 if summary["status"] == "PASS" else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user