This commit is contained in:
+4
-4
@@ -4,9 +4,9 @@ Python **3.9+**, стандартная библиотека. Сервер уж
|
||||
|
||||
```sh
|
||||
make check
|
||||
make test BASE_URL=http://localhost:8080
|
||||
make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
|
||||
# без make:
|
||||
python3 tests/smoke.py --base-url http://localhost:8080
|
||||
python3 tests/smoke.py --base-url https://localhost:8443 --ca-file /absolute/path/to/ca.crt
|
||||
```
|
||||
|
||||
`smoke.py` выполняет **один сквозной сценарий**, автоматически выбирая профиль из `lab.json`: health → три пользователя → вход с lab2 → чат → сообщения → пагинация → ошибки доступа → идемпотентность с lab3 → файл с lab4 → thumbnail с lab5 → logout. Он проверяет JSON по используемому подмножеству схемы, коды/headers, Unicode, SHA-256 оригинала и фактические JPEG-размеры thumbnail. Это публичный минимум, не полный fuzz/security/load suite.
|
||||
@@ -50,8 +50,8 @@ make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
|
||||
make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
|
||||
```
|
||||
|
||||
Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. **Внутреннее mTLS, identity/authorization, OpenBao policy и hardening проверяют отдельные тесты студента** по trust matrix. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях.
|
||||
Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. `make test-mtls` подключается к API из закрытой Compose-сети и проверяет четыре случая: без сертификата, сертификат от чужого CA, доверенный сертификат с неверной URI identity и разрешённый сертификат LB. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях. OpenBao policy и остальные проверки hardening выполняются отдельно по trust matrix.
|
||||
|
||||
## Что ещё остаётся доказать
|
||||
|
||||
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
|
||||
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей или полноту telemetry. Другие обязательные проверки решения описаны в README.md. Проверки рассчитаны на localhost-стенд, не на production.
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the API's client-certificate and URI SAN allowlist on the TLS socket."""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
CA = "/run/pki/ca.crt"
|
||||
API_HOST = "api-1"
|
||||
API_TLS_NAME = "api"
|
||||
API_PORT = 8443
|
||||
|
||||
|
||||
def request(certificate=None, key=None, trust=CA):
|
||||
context = ssl.create_default_context(cafile=trust)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if certificate:
|
||||
context.load_cert_chain(certificate, key)
|
||||
raw_socket = socket.create_connection((API_HOST, API_PORT), timeout=5)
|
||||
with raw_socket:
|
||||
with context.wrap_socket(raw_socket, server_hostname=API_TLS_NAME) as tls:
|
||||
tls.sendall(
|
||||
b"GET /health/live HTTP/1.1\r\n"
|
||||
b"Host: api\r\n"
|
||||
b"Connection: close\r\n\r\n"
|
||||
)
|
||||
response = bytearray()
|
||||
while True:
|
||||
chunk = tls.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
response.extend(chunk)
|
||||
status_line = bytes(response).split(b"\r\n", 1)[0]
|
||||
if not status_line:
|
||||
raise ConnectionError("server closed connection before returning HTTP")
|
||||
return int(status_line.split()[1])
|
||||
|
||||
|
||||
def must_fail_handshake(label, certificate=None, key=None, trust=CA):
|
||||
try:
|
||||
request(certificate, key, trust)
|
||||
except (ssl.SSLError, ConnectionError, OSError):
|
||||
print(f"PASS: {label} rejected before receiving an HTTP response")
|
||||
return
|
||||
raise AssertionError(f"{label} unexpectedly completed TLS handshake")
|
||||
|
||||
|
||||
def main():
|
||||
must_fail_handshake("missing client certificate")
|
||||
must_fail_handshake(
|
||||
"client certificate from an untrusted CA",
|
||||
"/run/pki/foreign-client.crt",
|
||||
"/run/pki/foreign-client.key",
|
||||
)
|
||||
wrong_identity_status = request(
|
||||
"/run/pki/worker-client.crt", "/run/pki/worker-client.key"
|
||||
)
|
||||
if wrong_identity_status != 401:
|
||||
raise AssertionError(
|
||||
f"trusted but unauthorized SAN returned HTTP {wrong_identity_status}, expected 401"
|
||||
)
|
||||
print("PASS: trusted client certificate with wrong URI SAN rejected by API")
|
||||
|
||||
allowed_status = request("/run/pki/lb-client.crt", "/run/pki/lb-client.key")
|
||||
if allowed_status != 200:
|
||||
raise AssertionError(
|
||||
f"allowlisted load-balancer identity returned HTTP {allowed_status}, expected 200"
|
||||
)
|
||||
print("PASS: allowlisted load-balancer URI SAN accepted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (AssertionError, OSError, ssl.SSLError, ValueError) as exc:
|
||||
print(f"FAIL: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
+1
-1
@@ -76,7 +76,7 @@ def main():
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice)
|
||||
print('PASS: lab%d public API scenario; infrastructure and grading evidence remain separate.' % LAB)
|
||||
print('PASS: lab%d public API scenario.' % LAB)
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
|
||||
Reference in New Issue
Block a user