Проверка публичной безопасности

This commit is contained in:
EgorAnti
2026-11-27 09:52:10 +03:00
parent 87a3f9d8e5
commit ac39f303d5
7 changed files with 100 additions and 3 deletions
+4 -1
View File
@@ -4,7 +4,7 @@ CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover test-security test-mtls
.PHONY: help check validate test load test-persistence test-failover test-security test-session-expiry test-mtls
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@@ -32,5 +32,8 @@ test-failover:
test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-session-expiry:
$(PYTHON) tests/session_expiry.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-mtls:
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-mtls.ps1
+1 -1
View File
@@ -95,7 +95,7 @@ docker compose --env-file .env up -d --build
# Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md.
```
Для HTTPS передайте публичный CA: `make test CA_FILE=/absolute/path/to/ca.crt`. CA certificate можно распространять; private keys создаются локально. `make test-security` проверяет только внешний TLS trust; внутренние отрицательные тесты реализуйте по [trust matrix](contracts/trust-matrix.md).
Для HTTPS передайте публичный CA: `make test CA_FILE=/absolute/path/to/ca.crt`. CA certificate можно распространять; private keys создаются локально. `make test-security` проверяет внешний TLS trust, ACL, upload/session/login limits и logout; `make test-session-expiry` управляемо истекает одну синтетическую сессию локального Compose-стенда и подтверждает `401`. Внутренние отрицательные тесты реализованы отдельно по [trust matrix](contracts/trust-matrix.md).
Проверка hardening и lifecycle не требует запущенного приложения:
+1
View File
@@ -24,6 +24,7 @@ TODO: схема процессов/хранилищ, источник исти
| OpenBao runtime boundaries | `scripts/test-openbao-runtime-boundaries.ps1` | PASS: server mode + persistent Raft volume; отдельные AppRole/bootstrap/rendered volumes; API/worker получают только allowlisted keys через read-only file и не имеют root token/unseal material | `evidence/openbao-runtime-boundaries.txt`, `contracts/trust-matrix.md` |
| Compose hardening | `scripts/check-compose-hardening.ps1` | PASS: только три loopback HTTPS-порта; limits/capability/read-only policy проверены | `compose.yaml`, самопроверка скрипта |
| Runtime isolation и утечки secrets | `scripts/test-container-secret-boundaries.ps1` | PASS: API/worker фактически non-root; privileged/host network/Docker socket отсутствуют; runtime limits и только разрешённые loopback bindings подтверждены; локальные secret values не найдены в Git, image metadata/filesystem и логах; redaction включён для traces/metrics/logs | `evidence/container-secret-boundaries.txt` |
| Публичная security-проверка и session lifecycle | `tests/security.py`, `tests/smoke.py`, `tests/session_expiry.py` | PASS: verified HTTPS и отказ пустого trust store; outsider ACL, attachment isolation, 10 MiB limit, session cap, `429 Retry-After`, logout/revocation и управляемое expiry → `401` | `evidence/public-security.txt` |
| Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 20 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | `evidence/security-lifecycle.txt` |
| Публичный smoke | `scripts/verify-https-resilience.ps1` | PASS: полный API-сценарий, включая ACL и вложения, выполнен через HTTPS с проверкой CA и hostname | `evidence/verify-https-resilience.txt` |
| Перезапуск с сохранением | тот же сценарий, mode `persistence` | PASS: после остановки и запуска stateful-сервисов, worker, двух API и LB сохранились сессия, сообщение и байты вложения | `evidence/verify-https-resilience.txt` |
+1 -1
View File
@@ -10,7 +10,7 @@
| Связь | Endpoint / порт | Протокол и server trust | Client identity и минимальные права | Lifecycle | Проверяемый отказ / доказательство | Статус |
| --- | --- | --- | --- | --- | --- | --- |
| Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/tls/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement revoke; leaf 30 d | `make test-security`; чужой/пустой CA, wrong hostname, expired leaf → certificate error; revoked token → 401; login burst → 429 + Retry-After | **PASS** для внешнего TLS/auth/session/rate-limit контракта |
| Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/pki/public-ca/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement/expiry revoke access; leaf 30 d | `make test-security`, `make test-session-expiry`; пустой trust store → certificate error; revoked/expired token → 401; login burst → 429 + Retry-After | **PASS** для внешнего TLS/auth/session/rate-limit контракта |
| nginx → API replicas | `https://api:8443` | mTLS; service CA + SAN `spiffe://hla-lab7/api`; API доверяет отдельному LB client CA | nginx SAN `spiffe://hla-lab7/lb`; точный URI SAN до auth проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, local regeneration/restart | `scripts/test-mtls.ps1` обращается к каждой реплике отдельно: no cert и foreign CA отклоняются handshake; trusted cert SAN `.../worker` получает 403; LB cert → health 200; прямой published port отсутствует | **PASS** |
| API → PostgreSQL | `postgres:5432` | TLS `verify-full`; service CA + SAN `DNS:postgres`; plaintext rejected by `pg_hba.conf` | `messenger_api`: runtime CRUD без superuser/DDL/role management | Static stand secret, rotate/reconnect; dynamic credentials remain extension | Wrong CA/hostname fails; DDL/role management denied | **PASS (уровень 3)** |
| Worker → PostgreSQL | `postgres:5432` | TLS `verify-full` | `messenger_worker`: jobs/attachments/variants; нет users password/session/membership | Отдельный secret | `SELECT password_hash`, update membership denied; job transitions allowed | **PASS (уровень 3)** |
+23
View File
@@ -0,0 +1,23 @@
Public HTTPS security verification
Date: 2026-11-27 (Europe/Moscow)
Commands:
python tests/security.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
python tests/session_expiry.py --base-url https://localhost:8443 --ca-file secrets/pki/public-ca/ca.crt
Observed:
PASS: trusted HTTPS, ACL/attachment isolation, session cap, upload and login limits.
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
PASS: an expired server-side session is rejected over verified HTTPS.
Verified failures and boundaries:
- empty trust store rejects the ingress certificate with a certificate verification error;
- outsider and cross-chat access return 404 without object disclosure;
- attachment body above 10 MiB returns 413;
- the fifth failed login in the configured window returns 429 with positive Retry-After;
- session replacement, logout and expiry make the old Bearer token return 401;
- all positive and negative HTTP probes use HTTPS with CA and hostname verification.
Certificates and credentials were created locally. No token, password, private key
or secret value is included in this file.
+7
View File
@@ -52,10 +52,17 @@ python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json
```sh
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
make test-session-expiry BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
```
Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. `test-security` сначала проверяет доверенное соединение и отказ пустого trust store, затем выполняет негативные проверки user/chat/attachment ACL, запрет cross-chat attachment, 10 MiB upload limit, максимум трёх активных сессий и общий Redis-backed login limit с `429 Retry-After`. Network timeout не засчитывается как правильный TLS-отказ. **Внутреннее mTLS и OpenBao policy проверяют отдельные тесты** по trust matrix. Клиентский сертификат внешнему REST-клиенту не требуется: mTLS находится на внутренних связях.
`test-session-expiry` — локальный Compose-тест: он создаёт отдельного синтетического
пользователя, операторской командой переводит только его единственную сессию за
границу `expires_at`, затем проверяет по HTTPS ответы `401` для Bearer-запроса и
logout. Token, пароль и SQL credentials не печатаются. Это не публичный black-box
тест, поскольку управляемое истечение часа ожидать непрактично.
## Что ещё остаётся доказать
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env python3
"""End-to-end session expiry check for the local Compose stand."""
import pathlib
import subprocess
from client import Client, LAB, arguments, check, run
def read_env(path):
values = {}
env_path = pathlib.Path(path)
if not env_path.is_file():
return values
for raw in env_path.read_text(encoding='utf-8-sig').splitlines():
line = raw.strip()
if not line or line.startswith('#') or '=' not in line:
continue
name, value = line.split('=', 1)
values[name.strip()] = value.strip()
return values
def configure(parser):
parser.add_argument('--env-file', default='.env')
def main():
args = arguments('Local Compose end-to-end session expiry check', configure)
check(LAB >= 2, 'session expiry requires lab2 or later')
client = Client(args.base_url, args.ca_file)
client.call('GET', '/health/ready', schema='Health')
actor = client.user('expiry')
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
env = read_env(args.env_file)
database_user = env.get('DATABASE_USER', 'messenger')
database_name = env.get('DATABASE_NAME', 'messenger')
username = actor['registration']['username']
sql = """
UPDATE sessions
SET expires_at = created_at + INTERVAL '1 microsecond'
WHERE user_id = (SELECT id FROM users WHERE username = :'target_username')
AND revoked_at IS NULL
AND expires_at > CURRENT_TIMESTAMP
RETURNING 1;
"""
result = subprocess.run([
'docker', 'compose', '--env-file', args.env_file, 'exec', '-T', 'postgres',
'psql', '--username', database_user, '--dbname', database_name,
'--set', 'ON_ERROR_STOP=1', '--set', 'target_username=' + username,
'--tuples-only', '--no-align',
], cwd=pathlib.Path(__file__).resolve().parents[1], input=sql,
capture_output=True, text=True, timeout=20)
check(result.returncode == 0, 'operator expiry update failed')
check('1' in result.stdout.splitlines(), 'operator expiry update did not select exactly one synthetic session')
client.call('GET', '/api/v1/users/me', 401, actor=actor)
client.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor)
print('PASS: an expired server-side session is rejected over verified HTTPS.')
if __name__ == '__main__':
run(main)