Проверить уровень 3, устойчивость и отрицательные сценарии, оформить отчёт
This commit is contained in:
@@ -0,0 +1,6 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
|
*.py text eol=lf
|
||||||
|
*.sql text eol=lf
|
||||||
|
*.yaml text eol=lf
|
||||||
|
*.hcl text eol=lf
|
||||||
|
*.cfg text eol=lf
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
## Лабораторная 7
|
## Лабораторная 7
|
||||||
|
|
||||||
Автор / группа: TODO
|
Автор / группа: Ляхонов Сергей, БВТ2301
|
||||||
Целевая оценка (3/4/5): TODO
|
Целевая оценка (3/4/5): 3
|
||||||
Трек 5, если заявлен: TODO
|
Трек 5, если заявлен: не заявлен
|
||||||
|
|
||||||
Что реализовано и что перенесено: TODO
|
Что реализовано и что перенесено: REST/async messenger из собственного №6 адаптирован к HTTPS; mTLS LB→обе API с allowlist identity; TLS DB/S3/broker/telemetry; OpenBao non-dev с certificate auth и scoped policies; limits/ACL/logout/expiry, non-root app/worker.
|
||||||
Команды запуска из чистого clone: TODO
|
Команды запуска из чистого clone: создать venv, установить requirements-bootstrap.txt и requirements-dev.txt; python -X utf8 scripts/bootstrap.py; python -X utf8 scripts/manage.py start --initialize --unseal. Подробности и operator trust — REPORT.md.
|
||||||
Результаты проверок и ссылка на REPORT.md: TODO
|
Результаты проверок и ссылка на REPORT.md: check.py all, durability.py, telemetry.py, audit.py, reproduce.py; реальные результаты в evidence/, критерии и команды в REPORT.md.
|
||||||
Ограничения / известные ошибки: TODO
|
Ограничения / известные ошибки: один Docker-host и singleton stores/LB; ручной unseal/leaf lifecycle, static KV credentials; loopback hop TLS proxies внутри namespace; production HA/ротация не заявлены.
|
||||||
Источники и использование ИИ: TODO
|
Источники и использование ИИ: собственный №6 commit1a14da9, нормативные материалы №7, официальная документация OpenBao/RabbitMQ/OTel/OWASP; Codex помог с кодом, конфигурацией, проверками и отчётом.
|
||||||
|
|
||||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||||
- [ ] Контракт и публичные тесты не ослаблены.
|
- [ ] Контракт и публичные тесты не ослаблены.
|
||||||
|
|||||||
@@ -1,37 +1,143 @@
|
|||||||
# Отчёт — лабораторная 7
|
# Отчёт — лабораторная работа №7
|
||||||
|
|
||||||
- Автор, группа: TODO
|
**Ляхонов Сергей, БВТ2301. Целевая оценка: 3, без исследовательского трека.** Проверки: 4 декабря 2026 года. Ветка `solution/BVT2301-lyakhonov`. Ревизии проверок записаны в `evidence/audit.json` и `evidence/reproduction.json`; итоговую показывает `git rev-parse HEAD`.
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
|
||||||
- Commit/PR: TODO после публикации
|
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Нужны Git, Python 3.11–3.13, Docker Engine с Linux containers, Compose v2 и доступ к registry/PyPI. Проверено на Windows: Python 3.13.7, Docker 28.5.1, Compose 2.40.3; Docker VM — 16 CPU, 8 126 656 512 байт RAM. Свободные loopback-порты: 8443, 8207, 3007.
|
||||||
|
|
||||||
|
Из корня clone в PowerShell:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m venv .venv
|
||||||
|
.venv\Scripts\python -m pip install -r requirements-bootstrap.txt -r requirements-dev.txt
|
||||||
|
.venv\Scripts\python -X utf8 scripts\bootstrap.py
|
||||||
|
.venv\Scripts\python -X utf8 scripts\manage.py start --initialize --unseal
|
||||||
|
.venv\Scripts\python -X utf8 scripts\check.py all
|
||||||
|
.venv\Scripts\python -X utf8 student-tests\durability.py
|
||||||
|
.venv\Scripts\python -X utf8 student-tests\telemetry.py
|
||||||
|
.venv\Scripts\python -X utf8 scripts\audit.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Linux: `.venv/bin/python`, разделители `/`; активируйте venv для hooks и выполните `chmod +x scripts/restart.sh scripts/stop-one.sh`. `-X utf8` обходит локальную cp1251 в штатных проверках Windows без изменения этих проверок и глобальных настроек.
|
||||||
|
|
||||||
|
Другие порты: `scripts/bootstrap.py --project lyakhonov-lab7-demo --port 18443 --bao-port 18207 --grafana-port 13007`. Скрипт создаёт `.env` только при отсутствии; существующий файл оператор редактирует осознанно. Для независимого проекта используйте чистый clone с новыми secrets. `docker compose config --quiet` проверяет Compose.
|
||||||
|
|
||||||
|
Bootstrap сохраняет существующие CA, ключи, passwords, `.env`, KV. Миграции защищены advisory lock и таблицей версий, bucket/policies повторяются безопасно. `manage.py start` строит свои образы, поднимает stores, выполняет операторские действия с явными флагами, миграции, GRANT, приватный bucket, запускает приложение и ждёт HTTPS readiness. API: `https://localhost:8443`, CA — `secrets/ca.crt`. Grafana: `https://localhost:3007`, пользователь `admin`, пароль читает оператор из `secrets/grafana_password`. OpenBao: `https://localhost:8207`, UI выключен. Для браузера импортируется публичный CA; проверки всегда используют CA file.
|
||||||
|
|
||||||
|
Эквиваленты make без установки make:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv\Scripts\python -X utf8 scripts\check_contract.py
|
||||||
|
.venv\Scripts\python -X utf8 scripts\validate_openapi.py
|
||||||
|
.venv\Scripts\python -X utf8 tests\smoke.py --base-url https://localhost:8443 --ca-file secrets\ca.crt
|
||||||
|
.venv\Scripts\python -X utf8 tests\security.py --base-url https://localhost:8443 --ca-file secrets\ca.crt
|
||||||
|
```
|
||||||
|
|
||||||
|
Отдельные проверки: `scripts/check.py internal|public|business|persistence|failover`. Runner сохраняет команду, exit code и небольшой вывод; реплики восстанавливаются через `finally`. Не запускайте сценарии отказов одновременно с другими тестами на том же стенде. Проверка expiry временно задаёт API `SESSION_TTL_SECONDS=2`, затем возвращает 3600.
|
||||||
|
|
||||||
|
Обычная остановка: `docker compose down`, volumes остаются. После restart OpenBao sealed: `docker compose up -d openbao`, `python -X utf8 scripts/bao.py unseal`, затем `python -X utf8 scripts/manage.py start`. Рестарт только API unseal не требует. Полный операторский restart с сохранением данных: `scripts/manage.py restart --unseal`.
|
||||||
|
|
||||||
|
Намеренное удаление собственных учебных данных: из проверенного корня `docker compose down --volumes`; secrets/PKI при этом не удаляются. Это отдельное разрушительное действие, не часть обычного запуска или persistence. Чистое воспроизведение: `python -X utf8 scripts/reproduce.py`; создаётся Git export с новыми secrets/CA/project/images/volumes/портами, временные ресурсы удаляются после проверок.
|
||||||
|
|
||||||
|
## Bootstrap trust и OpenBao
|
||||||
|
|
||||||
|
Оператор создаёт CA RSA-3072 на 365 дней, RSA-2048 leaf на 30 дней с DNS SAN/EKU; CA содержит BasicConstraints/KeyUsage/SKI, leaf — AKI/SKI. Минимальный transport TLS 1.2. Только оператор владеет CA private key и может выпустить identity `lb`. На Windows `secrets` защищён NTFS ACL текущего оператора; на POSIX — каталогом 0700, operator directory 0700 и operator files 0600. Сервисам монтируются только необходимые read-only файлы; leaf читаем разными non-root UID внутри закрытого host-каталога. Администратор Docker/хоста находится внутри доверенной границы.
|
||||||
|
|
||||||
|
OpenBao 2.4.0 — обычный `server`, TLS, file storage на named volume, certificate auth, KV v2. Dev-mode не включён. Явные действия оператора:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -X utf8 scripts/bao.py init
|
||||||
|
python -X utf8 scripts/bao.py unseal
|
||||||
|
python -X utf8 scripts/bao.py configure
|
||||||
|
```
|
||||||
|
|
||||||
|
Учебный Shamir 1-of-1: init сохраняет root token и unseal share в закрытый `secrets/operator/bao-init.json` на хосте. Файл **не монтируется в контейнеры**, не печатается, не входит в Git/image/evidence. Оператор должен иметь защищённую резервную копию отдельно от data volume; для реальной эксплуатации нужны раздельные владельцы долей/защищённое хранилище. Авто-unseal контейнером отсутствует; `restart --unseal` — явно выбранное действие host-оператора. Root применяется только host-скриптом настройки.
|
||||||
|
|
||||||
|
API1/API2 входят своими pinned leaf (`api`/`api2` auth roles), получают policy `api` и читают `secret/data/api`. Worker/dispatcher/cleaner имеют отдельные leaf, policies и KV paths. Tokens TTL/max TTL 300 секунд без default policy. Процесс повторяет certificate login/чтение через 240 секунд; token остаётся в памяти. Статические DB/S3/broker credentials допустимы на 3: срок до ручной смены оператором, TTL Bao token их автоматически не отзывает. Уже открытый DB pool использует полученный DSN до рестарта. Реальные тесты: своё чтение 200; чужое чтение, изменение KV и запись ACL policy — 403. Worker не читает API secret и таблицу users.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Клиент → HTTPS/Bearer → HAProxy → mTLS/CN `lb` → API1/API2. PostgreSQL — источник истины пользователей, memberships, сообщений, hashed sessions, idempotency, metadata/jobs/outbox. Сообщение и idempotency result фиксируются одной транзакцией под advisory lock. Перед 202 полностью принят staging в приватном S3 и зафиксирован job. Dispatcher публикует ссылки с confirms, worker делает manual ack после устойчивого результата. Lease/fencing и immutable keys защищают повторные попытки. `ready` публикуется после оригинала и thumbnail JPEG, для fixture — 256×160. Retention failed/orphan staging 24 часа; queued/processing не удаляются, ready staging удаляет cleaner после COMMIT. 202 не считается успехом обработки.
|
||||||
|
|
||||||
|
Перенесено собственное решение №6 из `6_2`, commit `1a14da9`: FastAPI, SQL, Bearer/Argon2id, идемпотентность, async pipeline, outbox/retry, OTel. Контракты №6/7 отличаются версией/заголовком и HTTPS URL; endpoint и бизнес-семантика сохранены. Redis отсутствует как необязательный компонент, sessions в PostgreSQL. Crop/WebP, fault injection, replay/upgrade CLI, SLO/burn-rate alerts и исследовательские сценарии исключены. Совместимые version/fencing поля схемы сохранены, разрешён только pipeline 1. Публичный alias — случайный UUID на процесс без hostname/IP.
|
||||||
|
|
||||||
|
API TLS proxy слушает 8443, требует client certificate и точную CN allowlist `lb`; uvicorn доступен только на 127.0.0.1:8080. PostgreSQL, MinIO, RabbitMQ, Collector, Grafana и OpenBao имеют native TLS. Prometheus/Loki/Tempo защищены Python mTLS proxy с allowlist в **том же network namespace**; plaintext HTTP/gRPC только loopback. У Tempo отдельные query/ingest TLS ports. Proxy проверяет CA и CN до подключения к upstream. Это учебная граница между процессами, не защита от компрометации backend/host. После restart namespace-owner перезапускаются sidecars; `manage.py` это учитывает.
|
||||||
|
|
||||||
|
| Роль / services | Версия, порты | Хранение / readiness / credentials |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| api1/api2 | свой app:1.0, Python 3.11.10; TLS8443, local8080 | ephemeral; ready проверяет DB+S3; свой leaf, policy api |
|
||||||
|
| worker/dispatcher/cleaner | свой app:1.0, разные процессы | worker lease90s/timeout60s; отдельные DB/S3/broker роли через Bao; worker stop95s |
|
||||||
|
| db | postgres:16.6-alpine, 5432 TLS | postgres_data; local pg_isready; 4 ограниченные login roles, без DDL/superuser |
|
||||||
|
| s3 | MinIO commit07c3a429, mc RELEASE.2025-04-16; checksums/base digests в Dockerfile.s3; 9000 TLS | s3_data; private prefix; разные credentials/prefix rights; console local9001 |
|
||||||
|
| broker | rabbitmq:4.1.0-alpine, 5671 AMQPS | broker_data; local diagnostics; producer/consumer ACL; plaintext AMQP выключен; Erlang/metrics loopback |
|
||||||
|
| lb | haproxy:3.0.6-alpine; host127.0.0.1:8443 | CA+SAN каждой replica; leaf lb; ready probes с mTLS |
|
||||||
|
| openbao | quay.io/openbao/openbao:2.4.0; host127.0.0.1:8207→8200 TLS | bao_data; initialized/unsealed operator; cert auth, KV v2, 4 scoped policies |
|
||||||
|
| otel-collector | contrib:0.137.0; 4318 HTTPS/mTLS | ограниченные RAM queues; native TLS; CA-authenticated ingest, внутренние metrics выключены |
|
||||||
|
| prometheus + TLS proxy | prom/prometheus:v3.7.3; 9443→local9090 | metrics_data; remote write, allowlist collector/grafana; retention24h/256MB |
|
||||||
|
| loki + TLS proxy | grafana/loki:3.5.7; 9443→local3100 | logs_data; local ring/OTLP; allowlist collector/grafana |
|
||||||
|
| tempo + 2 TLS proxies | grafana/tempo:2.9.0; 9443→local3200, 9444→local4318 | traces_data; local ring; query identity grafana, ingest collector |
|
||||||
|
| grafana | grafana/grafana:12.2.1; host127.0.0.1:3007 HTTPS | grafana_data; local password, anonymous off; provisioned datasources/dashboard; CA+client cert |
|
||||||
|
| migrate/bucket-init | свои app/S3 images, профиль operator | one-shot, admin material только этим ролям; миграции/GRANT/bucket |
|
||||||
|
| verifier | свой app image, профиль tests | одноразовый операторский тест, тестовые leaf без CA key/root/unseal |
|
||||||
|
|
||||||
|
Project `lyakhonov-lab7`, свои образы `lyakhonov-lab7-app:1.0`, `lyakhonov-lab7-s3:1.0`; каждый volume/network имеет project prefix. CPU/RAM limits: API/worker .5/512MiB; DB1/512MiB; S3 1/640MiB; broker .75/512MiB; backends/Grafana .5/384MiB; Collector .5/256MiB; proxies .25/96MiB. Точные значения/IDs — `evidence/audit.json`. App UID999, cap_drop ALL, no-new-privileges; нет privileged/host network/socket. Stateful entrypoints имеют стандартные права для chown/drop UID. Образы закреплены тегами/digests, Python graph — `requirements.lock.txt`.
|
||||||
|
|
||||||
|
### Настройки и сигналы
|
||||||
|
|
||||||
|
`.env` — только project/image names и host ports. Штатный `.env.example` сохранён как интерфейс курса: S3 `*_FILE` отображаются на keys `S3_ACCESS_KEY/S3_SECRET_KEY` из Bao, `DATABASE_URL_FILE` используется migrate; runtime получает DSN из Bao. Cache выключен, SESSION_STORE=postgres; API_REPLICAS=2 реализовано двумя services, worker concurrency1. Job timeout/attempt/retention закреплены в Compose, upload10MiB, pixels40M, session3600s. ARGON2_* описывают фиксированную конфигурацию KDF, окружение не позволяет её ослабить. TLS files `/tls/{ca.crt,cert.crt,key.key}`; BAO_ROLE — KV/policy, BAO_AUTH_NAME — pinned auth role; root BAO_TOKEN отсутствует.
|
||||||
|
|
||||||
|
SDK1.38.0 → Collector0.137.0 → Prometheus remote write, Loki OTLP, Tempo OTLP. Resource: messenger-api/messenger-worker, version1.7.0, instance.id, environment=lab. Реальные имена: `messenger_http_requests_total`, `messenger_http_duration_seconds_bucket`, `messenger_jobs_total`, `messenger_job_duration_seconds_bucket`. HTTP labels method/route/status_class, histogram в секундах. Dashboard считает p95 из сумм histogram buckets всех реплик. В логах event/request_id и trace_id/span_id; тела, произвольные headers и credentials не экспортируются. Контекст задания проходит через durable trace_context и broker envelope. Telemetry не входит в синхронную readiness API; DB/S3 входят. SDK/Collector queues ограничены; при длительном отказе backend telemetry может теряться и не является журналом бизнес-транзакций.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий уровня 3 | Команда / сценарий | Наблюдение / доказательство |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Нормативный контракт | check_contract.py, validate_openapi.py, audit.py | structure/OpenAPI PASS, normative files не изменены; evidence/structure.txt, validation.txt, audit.json |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Сборка/запуск | manage.py start --initialize --unseal | свои Dockerfile, миграции, private bucket, HTTPS ready; evidence/reproduction.json |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Предыдущий REST/async pipeline | check.py public | smoke PASS; конечный ready, SHA256 оригинала и реальный JPEG256×160; evidence/smoke.txt |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Устойчивое принятие и повторная доставка | student-tests/durability.py | 202 при stopped worker; broker no-ack disconnect → redelivered=True; затем ready и один thumbnail; completed-job duplicate без повторного эффекта; evidence/durability.txt |
|
||||||
|
| HTTPS CA/hostname | public security + security_suite.py | trusted200; empty CA/wrong hostname certificate error; evidence/security.txt, business-security.txt |
|
||||||
|
| mTLS обеих API, identity LB | check.py internal | no cert/foreign CA/trusted wrong identity отказ; lb200; plaintext8080 закрыт; evidence/internal.txt |
|
||||||
|
| TLS DB/S3/broker | internal | pg_stat_ssl=true, verify-full; plaintext DB/AMQP отказ, scoped ACL; evidence/internal.txt |
|
||||||
|
| TLS Collector/backends/Grafana | internal + telemetry.py | authenticated OTLP, mTLS queries/ingest, wrong identity отказ, реальные сигналы через Grafana; evidence/internal.txt, telemetry.json |
|
||||||
|
| Bao non-dev/storage/auth/policy | internal + restart | cert auth, tokenTTL≤300, свой read200; чужой read/policy write/KV write403; persistent volume; evidence/internal.txt, restart.json |
|
||||||
|
| Argon2id/salt/params | docker compose run --rm -v ./student-tests:/checks:ro api1 python /checks/argon.py | 19456KiB/t2/p1, 12 разных salt; hash+verify median180.83ms/min107.90/max218.93; evidence/argon.json |
|
||||||
|
| Login rate limit | security_suite.py | 11-я попытка429/Retry-After60, окно10/60s по normalized username в DB; evidence/business-security.txt |
|
||||||
|
| ACL/logout/expiry | security_suite.py | outsider metadata/content/attach404; X-User-Id игнорируется; logout/TTL2→401; evidence/business-security.txt |
|
||||||
|
| Размер запросов | security_suite.py | JSON>64KiB, файл>10MiB, chunked без length→413; evidence/business-security.txt |
|
||||||
|
| Сохранность | публичный persistence + restart hook | прежний Bearer, данные и bytes сохранились; реальные start timestamps изменились; evidence/persistence.txt, restart.json |
|
||||||
|
| Отказ каждой replica | check.py failover | ≥2 до отказа, реальные контейнеры поочерёдно stopped; без потерь/дублей, обе восстановлены; evidence/failover-*.txt, stop-api1.json, stop-api2.json |
|
||||||
|
| Non-root/limits/закрытые ports | audit.py | UID≠0, limits, 3 loopback TLS публикации, без privileged/socket/host network; evidence/audit.json |
|
||||||
|
| Secrets вне Git/images/telemetry | audit.py + telemetry.py | actual credentials/private keys отсутствуют в tracked/evidence/exported layers/returned signals/container logs; evidence/audit.json, telemetry.json |
|
||||||
|
| Чистое воспроизведение | reproduce.py | новый Git export/CA/secrets/project/images/volumes/ports, build/Bao/smoke/internal, cleanup; evidence/reproduction.json |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
Argon2id оставлен на минимуме19MiB/t2/p1: измерение при .5CPU даёт приемлемую для учебного входа задержку. Измерена пара hash+verify, 12 образцов с CPU throttling, все включены; PHC строка содержит salt/параметры, значения hashes не публикуются. Это не benchmark промышленного login DoS.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Обязательная гипотеза: подтверждённые session/message/ready attachment сохраняются после restart stores и потери одной API. Публичные сценарии создают синтетические данные; volumes не удаляются. Failover15s, POST с интервалом0.1s, повтор неопределённой записи с тем же ключом. Первый завершённый прогон:64/55 успешных записей,1/2 переходных неудачных попытки, first recovery5.634/5.605s. Более поздние evidence имеют приоритет. Hook сохраняет реальные IDs/StartedAt до/после; в persistence рестартует все stores, Bao и telemetry, затем proxy namespace. Unseal делает host-оператор.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
Короткая closed-loop нагрузка:15s/concurrency2, evidence/load.json; p50/p95/p99 только успешных HTTP-запросов, без прозрачных retry. Прогрев — предшествующие smoke/security; набор накоплен синтетическими проверками. CPU/RAM — evidence/resources.txt. Это наблюдаемый профиль, не поиск максимального RPS/исследовательский трек. Есть coordinated omission клиента.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| TODO | TODO | TODO | TODO |
|
| Воздействие | Ожидание / факт | Граница |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Restart API+stores | Прежний токен/сообщения/S3 bytes сохранились | Volumes и host сохранены |
|
||||||
|
| Stop API1, затем API2 | Другая replica обслуживает запросы, retry без дублей | LB/DB/S3 доступны |
|
||||||
|
| Неверный client leaf | Бизнес-запрос не дошёл до loopback app | CA key/namespace не скомпрометированы |
|
||||||
|
| Запрещённая Bao операция | 403, чужой secret не выдан | Host-оператор вне модели атакующего |
|
||||||
|
| Session expiry | После TTL401 | Server-side session lookup |
|
||||||
|
|
||||||
|
Исправлены ошибки cp1251, strict X.509 AKI/SKI, bootstrap OpenBao, DB row-lock/Rabbit default-exchange ACL, loopback ring/sidecar restart. Краткие точные ошибки и исправления — evidence/setup-notes.txt. Network timeout не засчитывался как правильный отрицательный TLS-тест.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Один Docker-host и singleton LB/DB/S3/broker/Bao: отказ host/stores не покрыт HA. TLS proxy доверяет loopback hop в одном namespace. Администратор Docker может прочитать mounts/память. CA/unseal/root защищены host ACL и резервной копией оператора, HSM отсутствует. Leaf30d требуют ручной перевыдачи. Static KV credentials не отзываются вместе с Bao token; DB connections живут до рестарта. При sealed Bao новые процессы не стартуют до unseal, повторное чтение secrets после240s не имеет fallback; открытые DB connections могут ещё работать. Глобальный distributed DoS и production secret lifecycle не заявлены. Account rate limit может временно блокировать легитимный вход, registration KDF тоже потребляет CPU. Proxy — небольшой учебный transport.
|
||||||
|
|
||||||
|
Secret scan проверяет реальные извлечённые записи/трассы, текущие container logs и известные credentials, а не все мыслимые утечки. Image-layer scan ищет фактические секреты этой PKI/стенда. Заявлены обязательные критерии уровня3; уровни4/5 и исследовательские треки не заявлены.
|
||||||
|
|
||||||
|
## Источники и использование ИИ
|
||||||
|
|
||||||
|
Нормативные источники — README/COURSE/contracts/tests skeleton №7. Собственное решение №6: [репозиторий](https://gitea.privcloud.tech/lyakhonov/mtusi2026lab6.git), commit1a14da9. Дополнительно: [OpenBao certificate auth](https://openbao.org/docs/auth/cert/), [policies](https://openbao.org/docs/concepts/policies/), [RabbitMQ TLS](https://www.rabbitmq.com/docs/ssl), [Collector configuration](https://opentelemetry.io/docs/collector/configuration/), [OWASP Password Storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html). Версии библиотек — lockfile.
|
||||||
|
|
||||||
|
ИИ Codex помог изучить требования, адаптировать код, написать конфигурации/проверки/отчёт. Команды действительно выполнялись на локальном Docker; PASS относится к сохранённым проверкам. Автор должен понимать модель доверия/транзакционные границы и воспроизводить проверки на защите.
|
||||||
|
|||||||
+28
-4
@@ -8,7 +8,7 @@ services:
|
|||||||
stop_grace_period: 12s
|
stop_grace_period: 12s
|
||||||
environment:
|
environment:
|
||||||
BAO_ROLE: api
|
BAO_ROLE: api
|
||||||
BAO_AUTH_NAME: api1
|
BAO_AUTH_NAME: api
|
||||||
BAO_ADDR: https://openbao:8200
|
BAO_ADDR: https://openbao:8200
|
||||||
S3_ENDPOINT: https://s3:9000
|
S3_ENDPOINT: https://s3:9000
|
||||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||||
@@ -258,6 +258,11 @@ services:
|
|||||||
interval: 5s
|
interval: 5s
|
||||||
timeout: 4s
|
timeout: 4s
|
||||||
retries: 30
|
retries: 30
|
||||||
|
environment:
|
||||||
|
ERL_EPMD_ADDRESS: 127.0.0.1
|
||||||
|
RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: -kernel inet_dist_use_interface {127,0,0,1}
|
||||||
|
extra_hosts:
|
||||||
|
broker: 127.0.0.1
|
||||||
openbao:
|
openbao:
|
||||||
image: quay.io/openbao/openbao:2.4.0
|
image: quay.io/openbao/openbao:2.4.0
|
||||||
cpus: 0.5
|
cpus: 0.5
|
||||||
@@ -271,13 +276,13 @@ services:
|
|||||||
BAO_ADDR: https://openbao:8200
|
BAO_ADDR: https://openbao:8200
|
||||||
BAO_CACERT: /tls/ca.crt
|
BAO_CACERT: /tls/ca.crt
|
||||||
volumes:
|
volumes:
|
||||||
- bao_data:/bao/data
|
- bao_data:/openbao/file
|
||||||
- ./infra/openbao/config.hcl:/bao/config/config.hcl:ro
|
- ./infra/openbao/config.hcl:/bao/config/config.hcl:ro
|
||||||
- ./secrets/tls/openbao:/tls:ro
|
- ./secrets/tls/openbao:/tls:ro
|
||||||
ports:
|
ports:
|
||||||
- 127.0.0.1:${BAO_PORT:-8207}:8200
|
- 127.0.0.1:${BAO_PORT:-8207}:8200
|
||||||
cap_drop:
|
tmpfs:
|
||||||
- ALL
|
- /openbao/logs
|
||||||
lb:
|
lb:
|
||||||
image: haproxy:3.0.6-alpine
|
image: haproxy:3.0.6-alpine
|
||||||
cpus: 0.5
|
cpus: 0.5
|
||||||
@@ -464,6 +469,25 @@ services:
|
|||||||
- ./secrets/datasources.yaml:/etc/grafana/provisioning/datasources/sources.yaml:ro
|
- ./secrets/datasources.yaml:/etc/grafana/provisioning/datasources/sources.yaml:ro
|
||||||
- ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro
|
- ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro
|
||||||
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||||
|
verifier:
|
||||||
|
image: ${APP_IMAGE:-lyakhonov-lab7-app:1.0}
|
||||||
|
profiles:
|
||||||
|
- tests
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- /checks/internal.py
|
||||||
|
volumes:
|
||||||
|
- ./student-tests:/checks:ro
|
||||||
|
- ./secrets/tls:/probe:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 256m
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data: {}
|
postgres_data: {}
|
||||||
s3_data: {}
|
s3_data: {}
|
||||||
|
|||||||
+18
-12
@@ -4,21 +4,27 @@
|
|||||||
|
|
||||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | localhost:8443; lab7 CA, DNS SAN localhost; session3600s; `check.py public/business`: trusted200, empty CA/wrong hostname certificate error, logout/TTL401 |
|
||||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | api1/api2:8443; CA + verifyhost api1/api2; client CN строго lb, leaf30d; `check.py internal`: no cert/foreign CA/trusted probe отказ, lb200; network port8080 закрыт |
|
||||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | db:5432, CA+DNS db; роли api/worker/dispatcher/cleaner без DDL/superuser, static до operator rotation; internal: pg_stat_ssl=true, plaintext отказ, worker SELECT users denied; infra/grants.sql |
|
||||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | s3:9000 HTTPS, CA+DNS s3; api writes staging/read results, worker reads staging/writes results, cleaner list/delete staging; static до смены; internal: ListBuckets denied, worker Put staging denied; infra/api.json,worker.json,cleaner.json |
|
||||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | broker:5671 AMQPS CA+DNS broker; API сохраняет outbox в DB, dispatcher producer/worker consumer, vhost lab7/queue attachment.process.v1; static до смены; internal: opposite operation403, port5672 closed |
|
||||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | otel-collector:4318, CA+DNS; client cert необходим, только операторские leaf30d; без cert TLS отказ; SDK cert/CA, collector native TLS; internal positive OTLP/no-cert deny; на 3 отдельной CN allowlist Collector не заявлено |
|
||||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | prometheus/loki:9443, tempo:9444; CA+DNS backend, proxy allowlist CN otel-collector; leaf30d; upstream loopback9090/3100/4318 в том же namespace; internal и telemetry.py: реальные metrics/logs/traces, probe denied |
|
||||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | prometheus/loki/tempo:9443; CA+DNS, client CN grafana, leaf30d; secure provisioning; local upstream9090/3100/3200; internal: Grafana ready200, probe denied, plaintext closed; telemetry.py: datasource queries |
|
||||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | openbao:8200, CA+DNS; pinned leaf auth api/api2/worker/dispatcher/cleaner; KV own path read-only; tokenTTL/maxTTL300s, reauth240s; internal: own200/foreign403/policy write403/KV write403; infra/openbao/*.hcl |
|
||||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | localhost:8207/3007 TLS CA+SAN localhost, host-only Bao root/Grafana password; S3 operator mc → https://s3:9000 CA+DNS (только one-shot bucket-init, host port отсутствует); static до смены, leaf30d; bootstrap/bao/telemetry.py; S3 console loopback-only |
|
||||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | N/A: необязательный cache выключен, sessions в PostgreSQL |
|
||||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | N/A: single-node stores, межузловой репликации нет; Rabbit epmd/distribution/metrics, Bao cluster listener, backend gRPC/rings только loopback; Docker admin вне модели |
|
||||||
|
|
||||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||||
|
|
||||||
|
## Реальные локальные границы решения
|
||||||
|
|
||||||
|
Все CA в таблице — новый CA этого стенда, публичный `secrets/ca.crt`; private key только у host-оператора. Leaf30d, CA365d. Команды `check.py` выполняются через Python из REPORT.md; результаты — `evidence/internal.txt`, `business-security.txt`, `telemetry.json`. TLS/identity ошибки не подменяются timeout. Дополнительные столбцы на 4 сохранены как нормативная часть шаблона, уровень 4 не заявлен.
|
||||||
|
|
||||||
|
API health у LB идёт по тому же mTLS 8443, без отдельного публичного health обхода. Container health — запрос внутри своего namespace на loopback8080. PostgreSQL bootstrap/GRANT/pg_isready используют локальный unix socket внутри DB или TLS verify-full в migrate. MinIO bootstrap mc проверяет CA/DNS, root credentials только one-shot operator. Rabbit health/CLI работает внутри контейнера через loopback distribution. Prometheus не scrape-ит plaintext сеть: Collector делает remote-write по mTLS; внутренние metrics Collector выключены. Python proxy и его backend разделяют namespace, backend HTTP/gRPC слушает только loopback; `internal.py` доказывает недоступность plaintext портов из отдельного контейнера. Нет опубликованных replica/backend/OTLP ports. OpenBao init/unseal — HTTPS с host, operator material в контейнеры не передаётся.
|
||||||
|
|
||||||
## Обязательные отрицательные проверки
|
## Обязательные отрицательные проверки
|
||||||
|
|
||||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"algorithm": "argon2id",
|
||||||
|
"memory_kib": 19456,
|
||||||
|
"time_cost": 2,
|
||||||
|
"parallelism": 1,
|
||||||
|
"samples": 12,
|
||||||
|
"cpu_limit": 0.5,
|
||||||
|
"memory_limit_mib": 512,
|
||||||
|
"operation": "hash + verify",
|
||||||
|
"min_ms": 107.9,
|
||||||
|
"median_ms": 180.83,
|
||||||
|
"max_ms": 218.93,
|
||||||
|
"distinct_salts": true
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
COMMAND: C:\Users\User\Desktop\vysoko-nagr 7\.venv\Scripts\python.exe -X utf8 student-tests/security_suite.py
|
||||||
|
EXIT: 0
|
||||||
|
Container lyakhonov-lab7-api1-1 Recreate
|
||||||
|
Container lyakhonov-lab7-api2-1 Recreate
|
||||||
|
Container lyakhonov-lab7-api1-1 Recreated
|
||||||
|
Container lyakhonov-lab7-api2-1 Recreated
|
||||||
|
Container lyakhonov-lab7-api2-1 Starting
|
||||||
|
Container lyakhonov-lab7-api1-1 Starting
|
||||||
|
Container lyakhonov-lab7-api1-1 Started
|
||||||
|
Container lyakhonov-lab7-api2-1 Started
|
||||||
|
Container lyakhonov-lab7-api1-1 Recreate
|
||||||
|
Container lyakhonov-lab7-api2-1 Recreate
|
||||||
|
Container lyakhonov-lab7-api1-1 Recreated
|
||||||
|
Container lyakhonov-lab7-api2-1 Recreated
|
||||||
|
Container lyakhonov-lab7-api2-1 Starting
|
||||||
|
Container lyakhonov-lab7-api1-1 Starting
|
||||||
|
Container lyakhonov-lab7-api2-1 Started
|
||||||
|
Container lyakhonov-lab7-api1-1 Started
|
||||||
|
PASS attachment ACL, foreign-chat attach=404, spoofed identity ignored, logout=401␍
|
||||||
|
PASS login limit: 10 allowed attempts, 11th=429 with Retry-After␍
|
||||||
|
PASS JSON 64KiB, upload 10MiB and actual chunked stream limits=413␍
|
||||||
|
PASS external wrong hostname rejected by certificate verifier␍
|
||||||
|
HTTPS readiness: 200, CA and localhost SAN verified␍
|
||||||
|
PASS configured SESSION_TTL_SECONDS=2: valid before expiry, 401 after expiry␍
|
||||||
|
HTTPS readiness: 200, CA and localhost SAN verified␍
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
Container lyakhonov-lab7-worker-1 Stopping
|
||||||
|
Container lyakhonov-lab7-worker-1 Stopped
|
||||||
|
PASS durable broker job delivered, disconnected without ack, redelivered=True; left queued for real worker
|
||||||
|
Container lyakhonov-lab7-worker-1 Starting
|
||||||
|
Container lyakhonov-lab7-worker-1 Started
|
||||||
|
PASS completed job duplicate published with broker confirm
|
||||||
|
PASS accepted202 during worker stop -> ready with exact original/one thumbnail; no-ack redelivery and completed-job duplicate did not duplicate effects
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
COMMAND: C:\Users\User\Desktop\vysoko-nagr 7\.venv\Scripts\python.exe -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --base-url https://localhost:8443 --ca-file C:\Users\User\Desktop\vysoko-nagr 7\secrets\ca.crt
|
||||||
|
EXIT: 0
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 55, "failed_attempts": 2, "first_recovery_seconds": 5.66}␍
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.␍
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
COMMAND: C:\Users\User\Desktop\vysoko-nagr 7\.venv\Scripts\python.exe -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --base-url https://localhost:8443 --ca-file C:\Users\User\Desktop\vysoko-nagr 7\secrets\ca.crt
|
||||||
|
EXIT: 0
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 51, "failed_attempts": 3, "first_recovery_seconds": 5.899}␍
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.␍
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"number": 7,
|
||||||
|
"title": "Безопасность, mTLS и OpenBao",
|
||||||
|
"contract_version": "1.7.0",
|
||||||
|
"default_base_url": "https://localhost:8443",
|
||||||
|
"grading": "3; 4 includes 3; 5 includes 4 plus one completed research track",
|
||||||
|
"scaffold_has_application": false
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
COMMAND: docker compose run --rm verifier
|
||||||
|
EXIT: 0
|
||||||
|
PASS api1 no cert / foreign CA / trusted wrong identity rejected; lb=200; port8080 closed
|
||||||
|
PASS api2 no cert / foreign CA / trusted wrong identity rejected; lb=200; port8080 closed
|
||||||
|
PASS OpenBao api cert auth; TTL<=300; own read=200; foreign read/policy write/KV write=403
|
||||||
|
PASS OpenBao api2 cert auth; TTL<=300; own read=200; foreign read/policy write/KV write=403
|
||||||
|
PASS OpenBao worker cert auth; TTL<=300; own read=200; foreign read/policy write/KV write=403
|
||||||
|
PASS OpenBao dispatcher cert auth; TTL<=300; own read=200; foreign read/policy write/KV write=403
|
||||||
|
PASS OpenBao cleaner cert auth; TTL<=300; own read=200; foreign read/policy write/KV write=403
|
||||||
|
PASS PostgreSQL api verify-full, server TLS observed; plaintext rejected
|
||||||
|
PASS PostgreSQL worker verify-full, server TLS observed; plaintext rejected
|
||||||
|
PASS PostgreSQL dispatcher verify-full, server TLS observed; plaintext rejected
|
||||||
|
PASS PostgreSQL cleaner verify-full, server TLS observed; plaintext rejected
|
||||||
|
PASS S3 api TLS; administrative bucket listing denied; scoped permissions
|
||||||
|
PASS S3 worker TLS; administrative bucket listing denied; scoped permissions
|
||||||
|
PASS S3 cleaner TLS; administrative bucket listing denied; scoped permissions
|
||||||
|
PASS RabbitMQ worker TLS; wrong producer/consumer operation=403
|
||||||
|
PASS RabbitMQ dispatcher TLS; wrong producer/consumer operation=403
|
||||||
|
PASS Collector TLS authenticated ingest; no-certificate rejected
|
||||||
|
PASS backend prometheus Grafana mTLS; wrong identity rejected; plaintext closed
|
||||||
|
PASS backend loki Grafana mTLS; wrong identity rejected; plaintext closed
|
||||||
|
PASS backend tempo Grafana mTLS; wrong identity rejected; plaintext closed
|
||||||
|
PASS Collector -> all backends mTLS
|
||||||
|
PASS internal wrong hostname rejected by certificate verifier
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 7,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 15.0,
|
||||||
|
"elapsed_seconds": 15.065,
|
||||||
|
"concurrency": 2,
|
||||||
|
"successful_requests": 419,
|
||||||
|
"failed_requests": 0,
|
||||||
|
"error_ratio": 0.0,
|
||||||
|
"successful_rps": 27.814,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 70.416,
|
||||||
|
"p95": 101.467,
|
||||||
|
"p99": 209.268
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
COMMAND: C:\Users\User\Desktop\vysoko-nagr 7\.venv\Scripts\python.exe -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url https://localhost:8443 --ca-file C:\Users\User\Desktop\vysoko-nagr 7\secrets\ca.crt
|
||||||
|
EXIT: 0
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.␍
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.␍
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
NAME CPU % MEM USAGE / LIMIT
|
||||||
|
lyakhonov-lab7-api1-1 25.92% 132.6MiB / 512MiB
|
||||||
|
lyakhonov-lab7-api2-1 16.54% 130.6MiB / 512MiB
|
||||||
|
lyakhonov-lab7-broker-1 73.58% 170.3MiB / 512MiB
|
||||||
|
lyakhonov-lab7-worker-1 0.04% 73.95MiB / 512MiB
|
||||||
|
lyakhonov-lab7-loki-tls-1 0.03% 7.449MiB / 96MiB
|
||||||
|
lyakhonov-lab7-prometheus-tls-1 0.04% 7.703MiB / 96MiB
|
||||||
|
lyakhonov-lab7-tempo-tls-1 0.01% 7.281MiB / 96MiB
|
||||||
|
lyakhonov-lab7-dispatcher-1 1.16% 54.12MiB / 512MiB
|
||||||
|
lyakhonov-lab7-cleaner-1 0.00% 61.98MiB / 512MiB
|
||||||
|
lyakhonov-lab7-tempo-tls-ingest-1 0.13% 7.297MiB / 96MiB
|
||||||
|
lyakhonov-lab7-lb-1 10.76% 21.3MiB / 128MiB
|
||||||
|
lyakhonov-lab7-grafana-1 0.48% 80.96MiB / 384MiB
|
||||||
|
lyakhonov-lab7-openbao-1 0.41% 20.63MiB / 256MiB
|
||||||
|
lyakhonov-lab7-db-1 12.63% 38.28MiB / 512MiB
|
||||||
|
lyakhonov-lab7-tempo-1 1.26% 237.5MiB / 384MiB
|
||||||
|
lyakhonov-lab7-loki-1 1.05% 74.79MiB / 384MiB
|
||||||
|
lyakhonov-lab7-otel-collector-1 1.72% 53.85MiB / 256MiB
|
||||||
|
lyakhonov-lab7-prometheus-1 0.08% 32.11MiB / 384MiB
|
||||||
|
lyakhonov-lab7-s3-1 0.90% 144.2MiB / 640MiB
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
{
|
||||||
|
"action": "restart",
|
||||||
|
"before": [
|
||||||
|
{
|
||||||
|
"service": "api1",
|
||||||
|
"id": "3f8011e29aac",
|
||||||
|
"started_at": "2026-12-04T04:05:28.455168224Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "api2",
|
||||||
|
"id": "0ad5d03d1795",
|
||||||
|
"started_at": "2026-12-04T04:05:28.448998296Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "broker",
|
||||||
|
"id": "ad179479d203",
|
||||||
|
"started_at": "2026-12-04T04:04:00.291013038Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "cleaner",
|
||||||
|
"id": "4ccfd6831a32",
|
||||||
|
"started_at": "2026-12-04T04:02:49.87623058Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "db",
|
||||||
|
"id": "066deb34f44b",
|
||||||
|
"started_at": "2026-12-04T03:57:32.967205656Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "dispatcher",
|
||||||
|
"id": "b6e967fec6da",
|
||||||
|
"started_at": "2026-12-04T04:02:49.888352079Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "grafana",
|
||||||
|
"id": "96a5e64b1f07",
|
||||||
|
"started_at": "2026-12-04T03:57:32.327647391Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "lb",
|
||||||
|
"id": "6987f231f4ee",
|
||||||
|
"started_at": "2026-12-04T03:45:12.584051263Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki",
|
||||||
|
"id": "f6e1437e4f14",
|
||||||
|
"started_at": "2026-12-04T03:57:33.463655016Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki-tls",
|
||||||
|
"id": "d063732cd20f",
|
||||||
|
"started_at": "2026-12-04T04:02:49.84480467Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "openbao",
|
||||||
|
"id": "b13db1a9bb50",
|
||||||
|
"started_at": "2026-12-04T03:57:33.310863563Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "otel-collector",
|
||||||
|
"id": "65a9667c97a6",
|
||||||
|
"started_at": "2026-12-04T03:57:33.019148392Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus",
|
||||||
|
"id": "c6f6d2c39cb7",
|
||||||
|
"started_at": "2026-12-04T03:57:32.062155512Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus-tls",
|
||||||
|
"id": "75ccd885c898",
|
||||||
|
"started_at": "2026-12-04T04:02:49.832884167Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "s3",
|
||||||
|
"id": "965e69714ae8",
|
||||||
|
"started_at": "2026-12-04T03:57:31.926930327Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo",
|
||||||
|
"id": "86b293fe1216",
|
||||||
|
"started_at": "2026-12-04T03:57:33.096634187Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls",
|
||||||
|
"id": "2bff90ca023b",
|
||||||
|
"started_at": "2026-12-04T04:02:49.829737905Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls-ingest",
|
||||||
|
"id": "ae500cc323a9",
|
||||||
|
"started_at": "2026-12-04T04:02:49.849240657Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "worker",
|
||||||
|
"id": "bc02bc027b94",
|
||||||
|
"started_at": "2026-12-04T04:02:49.886321447Z",
|
||||||
|
"status": "running"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"after": [
|
||||||
|
{
|
||||||
|
"service": "api1",
|
||||||
|
"id": "3f8011e29aac",
|
||||||
|
"started_at": "2026-12-04T04:05:56.379774354Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "api2",
|
||||||
|
"id": "0ad5d03d1795",
|
||||||
|
"started_at": "2026-12-04T04:05:56.34165109Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "broker",
|
||||||
|
"id": "ad179479d203",
|
||||||
|
"started_at": "2026-12-04T04:05:42.735730626Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "cleaner",
|
||||||
|
"id": "4ccfd6831a32",
|
||||||
|
"started_at": "2026-12-04T04:05:57.144558117Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "db",
|
||||||
|
"id": "066deb34f44b",
|
||||||
|
"started_at": "2026-12-04T04:05:39.712347588Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "dispatcher",
|
||||||
|
"id": "b6e967fec6da",
|
||||||
|
"started_at": "2026-12-04T04:06:00.987337652Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "grafana",
|
||||||
|
"id": "96a5e64b1f07",
|
||||||
|
"started_at": "2026-12-04T04:05:39.11568327Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "lb",
|
||||||
|
"id": "6987f231f4ee",
|
||||||
|
"started_at": "2026-12-04T03:45:12.584051263Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki",
|
||||||
|
"id": "f6e1437e4f14",
|
||||||
|
"started_at": "2026-12-04T04:05:40.110312226Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki-tls",
|
||||||
|
"id": "d063732cd20f",
|
||||||
|
"started_at": "2026-12-04T04:05:57.069088892Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "openbao",
|
||||||
|
"id": "b13db1a9bb50",
|
||||||
|
"started_at": "2026-12-04T04:05:39.986508578Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "otel-collector",
|
||||||
|
"id": "65a9667c97a6",
|
||||||
|
"started_at": "2026-12-04T04:05:38.589790006Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus",
|
||||||
|
"id": "c6f6d2c39cb7",
|
||||||
|
"started_at": "2026-12-04T04:05:39.497453883Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus-tls",
|
||||||
|
"id": "75ccd885c898",
|
||||||
|
"started_at": "2026-12-04T04:05:57.064732936Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "s3",
|
||||||
|
"id": "965e69714ae8",
|
||||||
|
"started_at": "2026-12-04T04:05:39.646780612Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo",
|
||||||
|
"id": "86b293fe1216",
|
||||||
|
"started_at": "2026-12-04T04:05:39.819740464Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls",
|
||||||
|
"id": "2bff90ca023b",
|
||||||
|
"started_at": "2026-12-04T04:05:57.060650395Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls-ingest",
|
||||||
|
"id": "ae500cc323a9",
|
||||||
|
"started_at": "2026-12-04T04:05:57.063230533Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "worker",
|
||||||
|
"id": "bc02bc027b94",
|
||||||
|
"started_at": "2026-12-04T04:05:57.906811011Z",
|
||||||
|
"status": "running"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
COMMAND: C:\Users\User\Desktop\vysoko-nagr 7\.venv\Scripts\python.exe -X utf8 tests/security.py --base-url https://localhost:8443 --ca-file C:\Users\User\Desktop\vysoko-nagr 7\secrets\ca.crt
|
||||||
|
EXIT: 0
|
||||||
|
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.␍
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
Дата: 2026-12-04, исходный Git HEAD 20afc2c, main...origin/main, чистый status.
|
||||||
|
Фактический cwd сессии сначала C:\Users\User\Desktop\vysoko-nagr 6.
|
||||||
|
Все изменения выполнялись с явным workdir C:\Users\User\Desktop\vysoko-nagr 7.
|
||||||
|
git rev-parse --show-toplevel: C:/Users/User/Desktop/vysoko-nagr 7
|
||||||
|
lab.json: number=7, contract_version=1.7.0, scaffold_has_application=false.
|
||||||
|
origin: https://gitea.privcloud.tech/lyakhonov/mtusi2026lab7.git
|
||||||
|
whoami: win-24dt7t3o465\lyakhonov
|
||||||
|
docker context show: desktop-linux
|
||||||
|
Docker Client/Server 28.5.1, API1.51, Docker Desktop4.49.0; Compose2.40.3.
|
||||||
|
Docker VM CPUs16, Memory8126656512 bytes.
|
||||||
|
Исходно docker compose ls и docker ps пусты; 8443,8207,3007 свободны.
|
||||||
|
Временная branch codex-write-probe-505a89ba43504bbd9e6edf77aa968956 создана от HEAD без switch и удалена.
|
||||||
|
Вывод: Deleted branch codex-write-probe-505a89ba43504bbd9e6edf77aa968956 (was 20afc2c).
|
||||||
|
Ошибок первичных whoami/Docker/Git/branch probe не было.
|
||||||
|
Git ls-remote origin подтвердил только main=20afc2c.
|
||||||
|
Предыдущие проекты: HEAD6_2/6=1a14da9, HEAD5=9dd2a03, HEAD4=8f112e0.
|
||||||
|
6_2: origin пользовательского fork, untracked vysoko-nagr_gitea/ сохранён.
|
||||||
|
Старый6: origin преподавателя, источником переноса не выбран.
|
||||||
|
AGENTS.md в родительской иерархии/целевых проектах не найден.
|
||||||
|
|
||||||
|
Фактические setup failures, не засчитанные как PASS:
|
||||||
|
1. Штатный Python без UTF8:
|
||||||
|
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1312: character maps to <undefined>
|
||||||
|
Причина cp1251; повтор с python -X utf8 прошёл, публичные scripts/tests не изменены.
|
||||||
|
2. OpenBao с cap_drop ALL до работы root entrypoint:
|
||||||
|
su-exec: setgroups: Operation not permitted
|
||||||
|
Для stateful entrypoint оставлены стандартные права, app/worker cap_drop ALL и nonroot.
|
||||||
|
3. OpenBao bootstrap leaf первоначально не был включён в список генерации:
|
||||||
|
Error initializing listener of type tcp: error loading TLS cert: open /tls/cert.crt: no such file or directory
|
||||||
|
Добавлен leaf openbao; persistent storage расположен в /openbao/file, которым управляет штатный entrypoint.
|
||||||
|
4. Python3.13 strict X509:
|
||||||
|
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Missing Authority Key Identifier (_ssl.c:1032)
|
||||||
|
Добавлены CA KeyUsage/SKI и leaf AKI/SKI; свою свежую PKI исправили с теми же private keys, без отключения verification. Чистый bootstrap создаёт корректные сертификаты сразу.
|
||||||
|
5. Collector:
|
||||||
|
exporters::otlphttp/loki::retry_on_failure: 'max_elapsed_time' must not be less than 'max_interval'
|
||||||
|
Заданы initial_interval1s/max_interval5s/max_elapsed15s.
|
||||||
|
6. API readiness S3 list-prefix403: добавлен ограниченный ListBucket только prefix staging/*.
|
||||||
|
7. Psycopg:
|
||||||
|
psycopg.errors.InsufficientPrivilege: permission denied for table attachments
|
||||||
|
SELECT FOR SHARE требует UPDATE; добавлен GRANT UPDATE(id), без широкого DDL/superuser.
|
||||||
|
8. RabbitMQ:
|
||||||
|
ACCESS_REFUSED - write access to exchange 'amq.default' in vhost 'lab7' refused for user 'dispatcher'
|
||||||
|
Producer write ACL ограничен amq.default, configure — точной queue; worker consumer отдельно.
|
||||||
|
9. Loki при loopback gRPC с прежним ring address:
|
||||||
|
transport: Error while dialing: dial tcp 172.24.0.4:9095: connect: connection refused
|
||||||
|
Ring instance address настроен на loopback; sidecars переподключаются после restart backend.
|
||||||
|
10. В probe Loki пустой OTLP payload:
|
||||||
|
422: error at least one valid stream is required for ingestion
|
||||||
|
Тест теперь отправляет настоящий синтетический logRecord и требует успешный HTTP status.
|
||||||
|
11. Первый stop hook превысил публичный бюджет:
|
||||||
|
FAIL: stop-one hook must return within 10 seconds
|
||||||
|
Заменены 19 отдельных docker inspect одним batch inspect; повтор для каждой replica прошёл.
|
||||||
|
12. Первоначальный секрет-скан отметил публичный Rabbit ACL regex (25 символов).
|
||||||
|
Это открытая конфигурация, не credential; regex исключён из списка secret values. Рабочие passwords/tokens/private keys проверяются.
|
||||||
|
13. Ограничение epmd на loopback до настройки локального hostname:
|
||||||
|
ERROR: epmd error for host broker: address (cannot connect to host/port)
|
||||||
|
Внутри broker добавлен hosts broker=127.0.0.1; межконтейнерный DNS broker сохранён. Диагностика подтверждает Erlang/metrics loopback и AMQPS network.
|
||||||
|
14. Один internal прогон совпал с отдельным failover:
|
||||||
|
socket.gaierror: [Errno -5] No address associated with hostname
|
||||||
|
Network failure не засчитан как TLS rejection; итоговый runner запускает проверки последовательно.
|
||||||
|
|
||||||
|
Автоматическая проверка команд дважды отклонила составные shell-вызовы: blocked by policy.
|
||||||
|
Вызовы разделены, файлы редактировались штатным patch, остановка replica выполняется scoped runner с finally restore.
|
||||||
|
Итоговые exit codes и PASS хранятся отдельно в evidence; перечисленные ошибки не скрыты и не ослабляли assertions.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
COMMAND: C:\Users\User\Desktop\vysoko-nagr 7\.venv\Scripts\python.exe -X utf8 tests/smoke.py --base-url https://localhost:8443 --ca-file C:\Users\User\Desktop\vysoko-nagr 7\secrets\ca.crt
|
||||||
|
EXIT: 0
|
||||||
|
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.␍
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
{
|
||||||
|
"action": "stop-one",
|
||||||
|
"before": [
|
||||||
|
{
|
||||||
|
"service": "api1",
|
||||||
|
"id": "3f8011e29aac",
|
||||||
|
"started_at": "2026-12-04T04:05:56.379774354Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "api2",
|
||||||
|
"id": "0ad5d03d1795",
|
||||||
|
"started_at": "2026-12-04T04:06:24.95818671Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "broker",
|
||||||
|
"id": "ad179479d203",
|
||||||
|
"started_at": "2026-12-04T04:05:42.735730626Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "cleaner",
|
||||||
|
"id": "4ccfd6831a32",
|
||||||
|
"started_at": "2026-12-04T04:05:57.144558117Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "db",
|
||||||
|
"id": "066deb34f44b",
|
||||||
|
"started_at": "2026-12-04T04:05:39.712347588Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "dispatcher",
|
||||||
|
"id": "b6e967fec6da",
|
||||||
|
"started_at": "2026-12-04T04:06:00.987337652Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "grafana",
|
||||||
|
"id": "96a5e64b1f07",
|
||||||
|
"started_at": "2026-12-04T04:05:39.11568327Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "lb",
|
||||||
|
"id": "6987f231f4ee",
|
||||||
|
"started_at": "2026-12-04T03:45:12.584051263Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki",
|
||||||
|
"id": "f6e1437e4f14",
|
||||||
|
"started_at": "2026-12-04T04:05:40.110312226Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki-tls",
|
||||||
|
"id": "d063732cd20f",
|
||||||
|
"started_at": "2026-12-04T04:05:57.069088892Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "openbao",
|
||||||
|
"id": "b13db1a9bb50",
|
||||||
|
"started_at": "2026-12-04T04:05:39.986508578Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "otel-collector",
|
||||||
|
"id": "65a9667c97a6",
|
||||||
|
"started_at": "2026-12-04T04:05:38.589790006Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus",
|
||||||
|
"id": "c6f6d2c39cb7",
|
||||||
|
"started_at": "2026-12-04T04:05:39.497453883Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus-tls",
|
||||||
|
"id": "75ccd885c898",
|
||||||
|
"started_at": "2026-12-04T04:05:57.064732936Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "s3",
|
||||||
|
"id": "965e69714ae8",
|
||||||
|
"started_at": "2026-12-04T04:05:39.646780612Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo",
|
||||||
|
"id": "86b293fe1216",
|
||||||
|
"started_at": "2026-12-04T04:05:39.819740464Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls",
|
||||||
|
"id": "2bff90ca023b",
|
||||||
|
"started_at": "2026-12-04T04:05:57.060650395Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls-ingest",
|
||||||
|
"id": "ae500cc323a9",
|
||||||
|
"started_at": "2026-12-04T04:05:57.063230533Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "worker",
|
||||||
|
"id": "bc02bc027b94",
|
||||||
|
"started_at": "2026-12-04T04:05:57.906811011Z",
|
||||||
|
"status": "running"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"after": [
|
||||||
|
{
|
||||||
|
"service": "api1",
|
||||||
|
"id": "3f8011e29aac",
|
||||||
|
"started_at": "2026-12-04T04:05:56.379774354Z",
|
||||||
|
"status": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "api2",
|
||||||
|
"id": "0ad5d03d1795",
|
||||||
|
"started_at": "2026-12-04T04:06:24.95818671Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "broker",
|
||||||
|
"id": "ad179479d203",
|
||||||
|
"started_at": "2026-12-04T04:05:42.735730626Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "cleaner",
|
||||||
|
"id": "4ccfd6831a32",
|
||||||
|
"started_at": "2026-12-04T04:05:57.144558117Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "db",
|
||||||
|
"id": "066deb34f44b",
|
||||||
|
"started_at": "2026-12-04T04:05:39.712347588Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "dispatcher",
|
||||||
|
"id": "b6e967fec6da",
|
||||||
|
"started_at": "2026-12-04T04:06:00.987337652Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "grafana",
|
||||||
|
"id": "96a5e64b1f07",
|
||||||
|
"started_at": "2026-12-04T04:05:39.11568327Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "lb",
|
||||||
|
"id": "6987f231f4ee",
|
||||||
|
"started_at": "2026-12-04T03:45:12.584051263Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki",
|
||||||
|
"id": "f6e1437e4f14",
|
||||||
|
"started_at": "2026-12-04T04:05:40.110312226Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki-tls",
|
||||||
|
"id": "d063732cd20f",
|
||||||
|
"started_at": "2026-12-04T04:05:57.069088892Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "openbao",
|
||||||
|
"id": "b13db1a9bb50",
|
||||||
|
"started_at": "2026-12-04T04:05:39.986508578Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "otel-collector",
|
||||||
|
"id": "65a9667c97a6",
|
||||||
|
"started_at": "2026-12-04T04:05:38.589790006Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus",
|
||||||
|
"id": "c6f6d2c39cb7",
|
||||||
|
"started_at": "2026-12-04T04:05:39.497453883Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus-tls",
|
||||||
|
"id": "75ccd885c898",
|
||||||
|
"started_at": "2026-12-04T04:05:57.064732936Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "s3",
|
||||||
|
"id": "965e69714ae8",
|
||||||
|
"started_at": "2026-12-04T04:05:39.646780612Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo",
|
||||||
|
"id": "86b293fe1216",
|
||||||
|
"started_at": "2026-12-04T04:05:39.819740464Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls",
|
||||||
|
"id": "2bff90ca023b",
|
||||||
|
"started_at": "2026-12-04T04:05:57.060650395Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls-ingest",
|
||||||
|
"id": "ae500cc323a9",
|
||||||
|
"started_at": "2026-12-04T04:05:57.063230533Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "worker",
|
||||||
|
"id": "bc02bc027b94",
|
||||||
|
"started_at": "2026-12-04T04:05:57.906811011Z",
|
||||||
|
"status": "running"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
{
|
||||||
|
"action": "stop-one",
|
||||||
|
"before": [
|
||||||
|
{
|
||||||
|
"service": "api1",
|
||||||
|
"id": "3f8011e29aac",
|
||||||
|
"started_at": "2026-12-04T04:05:56.379774354Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "api2",
|
||||||
|
"id": "0ad5d03d1795",
|
||||||
|
"started_at": "2026-12-04T04:05:56.34165109Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "broker",
|
||||||
|
"id": "ad179479d203",
|
||||||
|
"started_at": "2026-12-04T04:05:42.735730626Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "cleaner",
|
||||||
|
"id": "4ccfd6831a32",
|
||||||
|
"started_at": "2026-12-04T04:05:57.144558117Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "db",
|
||||||
|
"id": "066deb34f44b",
|
||||||
|
"started_at": "2026-12-04T04:05:39.712347588Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "dispatcher",
|
||||||
|
"id": "b6e967fec6da",
|
||||||
|
"started_at": "2026-12-04T04:06:00.987337652Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "grafana",
|
||||||
|
"id": "96a5e64b1f07",
|
||||||
|
"started_at": "2026-12-04T04:05:39.11568327Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "lb",
|
||||||
|
"id": "6987f231f4ee",
|
||||||
|
"started_at": "2026-12-04T03:45:12.584051263Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki",
|
||||||
|
"id": "f6e1437e4f14",
|
||||||
|
"started_at": "2026-12-04T04:05:40.110312226Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki-tls",
|
||||||
|
"id": "d063732cd20f",
|
||||||
|
"started_at": "2026-12-04T04:05:57.069088892Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "openbao",
|
||||||
|
"id": "b13db1a9bb50",
|
||||||
|
"started_at": "2026-12-04T04:05:39.986508578Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "otel-collector",
|
||||||
|
"id": "65a9667c97a6",
|
||||||
|
"started_at": "2026-12-04T04:05:38.589790006Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus",
|
||||||
|
"id": "c6f6d2c39cb7",
|
||||||
|
"started_at": "2026-12-04T04:05:39.497453883Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus-tls",
|
||||||
|
"id": "75ccd885c898",
|
||||||
|
"started_at": "2026-12-04T04:05:57.064732936Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "s3",
|
||||||
|
"id": "965e69714ae8",
|
||||||
|
"started_at": "2026-12-04T04:05:39.646780612Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo",
|
||||||
|
"id": "86b293fe1216",
|
||||||
|
"started_at": "2026-12-04T04:05:39.819740464Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls",
|
||||||
|
"id": "2bff90ca023b",
|
||||||
|
"started_at": "2026-12-04T04:05:57.060650395Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls-ingest",
|
||||||
|
"id": "ae500cc323a9",
|
||||||
|
"started_at": "2026-12-04T04:05:57.063230533Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "worker",
|
||||||
|
"id": "bc02bc027b94",
|
||||||
|
"started_at": "2026-12-04T04:05:57.906811011Z",
|
||||||
|
"status": "running"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"after": [
|
||||||
|
{
|
||||||
|
"service": "api1",
|
||||||
|
"id": "3f8011e29aac",
|
||||||
|
"started_at": "2026-12-04T04:05:56.379774354Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "api2",
|
||||||
|
"id": "0ad5d03d1795",
|
||||||
|
"started_at": "2026-12-04T04:05:56.34165109Z",
|
||||||
|
"status": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "broker",
|
||||||
|
"id": "ad179479d203",
|
||||||
|
"started_at": "2026-12-04T04:05:42.735730626Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "cleaner",
|
||||||
|
"id": "4ccfd6831a32",
|
||||||
|
"started_at": "2026-12-04T04:05:57.144558117Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "db",
|
||||||
|
"id": "066deb34f44b",
|
||||||
|
"started_at": "2026-12-04T04:05:39.712347588Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "dispatcher",
|
||||||
|
"id": "b6e967fec6da",
|
||||||
|
"started_at": "2026-12-04T04:06:00.987337652Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "grafana",
|
||||||
|
"id": "96a5e64b1f07",
|
||||||
|
"started_at": "2026-12-04T04:05:39.11568327Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "lb",
|
||||||
|
"id": "6987f231f4ee",
|
||||||
|
"started_at": "2026-12-04T03:45:12.584051263Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki",
|
||||||
|
"id": "f6e1437e4f14",
|
||||||
|
"started_at": "2026-12-04T04:05:40.110312226Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "loki-tls",
|
||||||
|
"id": "d063732cd20f",
|
||||||
|
"started_at": "2026-12-04T04:05:57.069088892Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "openbao",
|
||||||
|
"id": "b13db1a9bb50",
|
||||||
|
"started_at": "2026-12-04T04:05:39.986508578Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "otel-collector",
|
||||||
|
"id": "65a9667c97a6",
|
||||||
|
"started_at": "2026-12-04T04:05:38.589790006Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus",
|
||||||
|
"id": "c6f6d2c39cb7",
|
||||||
|
"started_at": "2026-12-04T04:05:39.497453883Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "prometheus-tls",
|
||||||
|
"id": "75ccd885c898",
|
||||||
|
"started_at": "2026-12-04T04:05:57.064732936Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "s3",
|
||||||
|
"id": "965e69714ae8",
|
||||||
|
"started_at": "2026-12-04T04:05:39.646780612Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo",
|
||||||
|
"id": "86b293fe1216",
|
||||||
|
"started_at": "2026-12-04T04:05:39.819740464Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls",
|
||||||
|
"id": "2bff90ca023b",
|
||||||
|
"started_at": "2026-12-04T04:05:57.060650395Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "tempo-tls-ingest",
|
||||||
|
"id": "ae500cc323a9",
|
||||||
|
"started_at": "2026-12-04T04:05:57.063230533Z",
|
||||||
|
"status": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"service": "worker",
|
||||||
|
"id": "bc02bc027b94",
|
||||||
|
"started_at": "2026-12-04T04:05:57.906811011Z",
|
||||||
|
"status": "running"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"grafana_https": true,
|
||||||
|
"provisioned_panels": 6,
|
||||||
|
"http_metric_series": 11,
|
||||||
|
"job_metric_series": 1,
|
||||||
|
"log_services": [
|
||||||
|
"messenger-api",
|
||||||
|
"messenger-worker"
|
||||||
|
],
|
||||||
|
"trace_counts": {
|
||||||
|
"messenger-api": 20,
|
||||||
|
"messenger-worker": 10
|
||||||
|
},
|
||||||
|
"credential_scan": "PASS; returned telemetry and container logs"
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
@@ -20,6 +20,22 @@
|
|||||||
"arn:aws:s3:::attachments/originals/*",
|
"arn:aws:s3:::attachments/originals/*",
|
||||||
"arn:aws:s3:::attachments/variants/*"
|
"arn:aws:s3:::attachments/variants/*"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Effect": "Allow",
|
||||||
|
"Action": [
|
||||||
|
"s3:ListBucket"
|
||||||
|
],
|
||||||
|
"Resource": [
|
||||||
|
"arn:aws:s3:::attachments"
|
||||||
|
],
|
||||||
|
"Condition": {
|
||||||
|
"StringLike": {
|
||||||
|
"s3:prefix": [
|
||||||
|
"staging/*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -7,3 +7,5 @@ GRANT SELECT,UPDATE ON attachments,attachment_jobs TO worker;
|
|||||||
GRANT SELECT,INSERT,UPDATE ON attachment_variants,attachment_replays TO worker;
|
GRANT SELECT,INSERT,UPDATE ON attachment_variants,attachment_replays TO worker;
|
||||||
GRANT SELECT,UPDATE ON attachments,attachment_jobs TO dispatcher;
|
GRANT SELECT,UPDATE ON attachments,attachment_jobs TO dispatcher;
|
||||||
GRANT SELECT ON attachment_jobs TO cleaner;
|
GRANT SELECT ON attachment_jobs TO cleaner;
|
||||||
|
|
||||||
|
GRANT UPDATE(id) ON attachments TO api;
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
ui = false
|
ui = false
|
||||||
disable_mlock = true
|
|
||||||
storage "file" {
|
storage "file" {
|
||||||
path = "/bao/data"
|
path = "/openbao/file"
|
||||||
}
|
}
|
||||||
listener "tcp" {
|
listener "tcp" {
|
||||||
address = "0.0.0.0:8200"
|
address = "0.0.0.0:8200"
|
||||||
|
cluster_address = "127.0.0.1:8201"
|
||||||
tls_cert_file = "/tls/cert.crt"
|
tls_cert_file = "/tls/cert.crt"
|
||||||
tls_key_file = "/tls/key.key"
|
tls_key_file = "/tls/key.key"
|
||||||
tls_min_version = "tls12"
|
tls_min_version = "tls12"
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ exporters:
|
|||||||
timeout: 5s
|
timeout: 5s
|
||||||
retry_on_failure:
|
retry_on_failure:
|
||||||
max_elapsed_time: 15s
|
max_elapsed_time: 15s
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 5s
|
||||||
sending_queue:
|
sending_queue:
|
||||||
queue_size: 128
|
queue_size: 128
|
||||||
num_consumers: 2
|
num_consumers: 2
|
||||||
@@ -35,6 +37,8 @@ exporters:
|
|||||||
timeout: 5s
|
timeout: 5s
|
||||||
retry_on_failure:
|
retry_on_failure:
|
||||||
max_elapsed_time: 15s
|
max_elapsed_time: 15s
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 5s
|
||||||
sending_queue:
|
sending_queue:
|
||||||
queue_size: 128
|
queue_size: 128
|
||||||
num_consumers: 2
|
num_consumers: 2
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ common:
|
|||||||
filesystem:
|
filesystem:
|
||||||
chunks_directory: /loki/chunks
|
chunks_directory: /loki/chunks
|
||||||
rules_directory: /loki/rules
|
rules_directory: /loki/rules
|
||||||
|
instance_addr: 127.0.0.1
|
||||||
schema_config:
|
schema_config:
|
||||||
configs:
|
configs:
|
||||||
- from: 2024-01-01
|
- from: 2024-01-01
|
||||||
|
|||||||
@@ -10,6 +10,12 @@ distributor:
|
|||||||
endpoint: 127.0.0.1:4318
|
endpoint: 127.0.0.1:4318
|
||||||
ingester:
|
ingester:
|
||||||
max_block_duration: 1m
|
max_block_duration: 1m
|
||||||
|
lifecycler:
|
||||||
|
address: 127.0.0.1
|
||||||
|
ring:
|
||||||
|
kvstore:
|
||||||
|
store: inmemory
|
||||||
|
replication_factor: 1
|
||||||
compactor:
|
compactor:
|
||||||
compaction:
|
compaction:
|
||||||
block_retention: 24h
|
block_retention: 24h
|
||||||
|
|||||||
@@ -9,3 +9,4 @@ definitions.import_backend = local_filesystem
|
|||||||
definitions.local.path = /run/private/broker.json
|
definitions.local.path = /run/private/broker.json
|
||||||
default_user = disabled-bootstrap
|
default_user = disabled-bootstrap
|
||||||
default_pass = disabled-bootstrap-not-a-service
|
default_pass = disabled-bootstrap-not-a-service
|
||||||
|
prometheus.tcp.ip = 127.0.0.1
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""Read-only contract, Git, secret, container and image-layer audit."""
|
||||||
|
import ast
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0,str(ROOT/'student-tests'))
|
||||||
|
from telemetry import secret_values
|
||||||
|
|
||||||
|
|
||||||
|
def command(*args):
|
||||||
|
return subprocess.check_output(args,cwd=ROOT,text=True,encoding='utf-8').strip()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
baseline='20afc2c'
|
||||||
|
original=command('git','ls-tree','-r','--name-only',baseline).splitlines()
|
||||||
|
editable={'REPORT.md','contracts/trust-matrix.md','security/THREAT_MODEL.md','.github/pull_request_template.md'}
|
||||||
|
normative=[name for name in original if name not in editable]
|
||||||
|
assert not command('git','diff',baseline,'--',*normative),'Normative materials changed'
|
||||||
|
files=set(command('git','ls-files','--cached','--others','--exclude-standard').splitlines())
|
||||||
|
assert not any(name.startswith('secrets/') or name=='.env' or name.endswith(('.key','.pem')) for name in files)
|
||||||
|
values=[v.encode() for v in secret_values()]
|
||||||
|
for path in (ROOT/'secrets/tls').glob('*/key.key'):values.append(path.read_bytes())
|
||||||
|
values.append((ROOT/'secrets/operator/ca.key').read_bytes())
|
||||||
|
for name in files:
|
||||||
|
path=ROOT/name
|
||||||
|
if not path.is_file():continue
|
||||||
|
data=path.read_bytes()
|
||||||
|
assert not any(value in data for value in values),'Credential in tracked/evidence file: '+name
|
||||||
|
assert not re.search(rb'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----',data),'Private key in '+name
|
||||||
|
if path.suffix=='.py':ast.parse(data,filename=name)
|
||||||
|
previous=[]
|
||||||
|
for name in ('vysoko-nagr 6_2','vysoko-nagr 6','vysoko-nagr 5','vysoko-nagr 4'):
|
||||||
|
folder=ROOT.parent/name
|
||||||
|
if not folder.exists():continue
|
||||||
|
def git(*args):return subprocess.check_output(['git','-C',str(folder),*args],text=True,encoding='utf-8').strip()
|
||||||
|
assert not git('diff','--name-only') and not git('diff','--cached','--name-only'),name+' changed'
|
||||||
|
previous.append({'folder':name,'head':git('rev-parse','HEAD'),'status':git('status','--short','--branch'),'origin':git('remote','get-url','origin')})
|
||||||
|
ids=command('docker','compose','ps','-q').splitlines()
|
||||||
|
objects=json.loads(command('docker','inspect',*ids))
|
||||||
|
containers=[]
|
||||||
|
for item in objects:
|
||||||
|
label=item['Config']['Labels']['com.docker.compose.service'];h=item['HostConfig']
|
||||||
|
assert not h['Privileged'] and h['NetworkMode']!='host'
|
||||||
|
assert h['Memory']>0 and h['NanoCpus']>0
|
||||||
|
assert not any('/docker.sock' in str(m) for m in item['Mounts'])
|
||||||
|
published=h.get('PortBindings') or {}
|
||||||
|
for port,bindings in published.items():
|
||||||
|
assert label in ('lb','openbao','grafana')
|
||||||
|
assert all(binding['HostIp']=='127.0.0.1' for binding in bindings)
|
||||||
|
if label in ('api1','api2','worker','dispatcher','cleaner'):
|
||||||
|
uid=int(command('docker','exec',item['Id'],'id','-u'));assert uid!=0
|
||||||
|
assert 'ALL' in (h['CapDrop'] or [])
|
||||||
|
containers.append({'service':label,'id':item['Id'][:12],'image':item['Config']['Image'],
|
||||||
|
'image_id':item['Image'],'state':item['State']['Status'],'started_at':item['State']['StartedAt'],
|
||||||
|
'cpu_limit':h['NanoCpus']/10**9,'memory_bytes':h['Memory'],'published':published,'user':item['Config']['User']})
|
||||||
|
env=dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line)
|
||||||
|
image_results=[]
|
||||||
|
for image in (env['APP_IMAGE'],env['S3_IMAGE']):
|
||||||
|
print('Scanning exported image layers:',image,flush=True)
|
||||||
|
proc=subprocess.Popen(['docker','image','save',image],stdout=subprocess.PIPE)
|
||||||
|
count=0
|
||||||
|
with tarfile.open(fileobj=proc.stdout,mode='r|*') as bundle:
|
||||||
|
for entry in bundle:
|
||||||
|
if not entry.isfile():continue
|
||||||
|
count+=1
|
||||||
|
source=bundle.extractfile(entry);tail=b''
|
||||||
|
while True:
|
||||||
|
block=source.read(1024*1024)
|
||||||
|
if not block:break
|
||||||
|
data=tail+block
|
||||||
|
assert not any(value in data for value in values),'Credential in exported image'
|
||||||
|
tail=data[-16384:]
|
||||||
|
assert proc.wait()==0
|
||||||
|
image_results.append({'image':image,'archive_members_scanned':count,'actual_credentials':'absent'})
|
||||||
|
commits=command('git','log',baseline+'..HEAD','--format=%h %an <%ae> | %cn <%ce>').splitlines()
|
||||||
|
assert all('Sergey Lyakhonov <lyserg119@gmail.com> | Sergey Lyakhonov <lyserg119@gmail.com>' in line for line in commits)
|
||||||
|
summary={'commit':command('git','rev-parse','HEAD'),'branch':command('git','branch','--show-current'),
|
||||||
|
'origin':command('git','remote','get-url','origin'),'normative_files_unchanged':len(normative),
|
||||||
|
'files_scanned':len(files),'secrets_scan':'PASS; actual credentials, private keys, tracked/evidence and exported layers',
|
||||||
|
'previous_projects':previous,'commits':commits,'containers':containers,'images':image_results}
|
||||||
|
(ROOT/'evidence/audit.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf-8')
|
||||||
|
print('PASS normative materials, credentials, previous checkouts, identities and container hardening')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
+12
-3
@@ -24,7 +24,9 @@ def write(path, data):
|
|||||||
return
|
return
|
||||||
path.write_bytes(data if isinstance(data, bytes) else data.encode())
|
path.write_bytes(data if isinstance(data, bytes) else data.encode())
|
||||||
if os.name != 'nt':
|
if os.name != 'nt':
|
||||||
path.chmod(0o600)
|
# Host root secrets directory is 0700. A role container receives ONLY
|
||||||
|
# its own files; read-only bind mounts must be readable by its nonroot UID.
|
||||||
|
path.chmod(0o600 if 'operator' in path.parts else 0o444)
|
||||||
|
|
||||||
|
|
||||||
def password(name):
|
def password(name):
|
||||||
@@ -47,6 +49,8 @@ def cert(name, ca_key, ca, foreign=False):
|
|||||||
.not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=30))
|
.not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=30))
|
||||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName(n) for n in names]), False)
|
.add_extension(x509.SubjectAlternativeName([x509.DNSName(n) for n in names]), False)
|
||||||
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
|
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
|
||||||
|
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),False)
|
||||||
|
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False)
|
||||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),False)
|
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),False)
|
||||||
.sign(ca_key, hashes.SHA256()))
|
.sign(ca_key, hashes.SHA256()))
|
||||||
key_bytes = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
|
key_bytes = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
|
||||||
@@ -71,6 +75,9 @@ def main():
|
|||||||
subprocess.run(['icacls',str(PRIVATE),'/inheritance:r','/grant:r',account+':(OI)(CI)F'],check=True,stdout=subprocess.DEVNULL)
|
subprocess.run(['icacls',str(PRIVATE),'/inheritance:r','/grant:r',account+':(OI)(CI)F'],check=True,stdout=subprocess.DEVNULL)
|
||||||
else:
|
else:
|
||||||
PRIVATE.chmod(0o700)
|
PRIVATE.chmod(0o700)
|
||||||
|
(PRIVATE/'operator').mkdir(exist_ok=True)
|
||||||
|
if os.name != 'nt':
|
||||||
|
(PRIVATE/'operator').chmod(0o700)
|
||||||
keypath = PRIVATE/'operator/ca.key'
|
keypath = PRIVATE/'operator/ca.key'
|
||||||
capath = PRIVATE/'ca.crt'
|
capath = PRIVATE/'ca.crt'
|
||||||
if not keypath.exists():
|
if not keypath.exists():
|
||||||
@@ -83,12 +90,14 @@ def main():
|
|||||||
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||||
.not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=365))
|
.not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=365))
|
||||||
.add_extension(x509.BasicConstraints(ca=True,path_length=0),True)
|
.add_extension(x509.BasicConstraints(ca=True,path_length=0),True)
|
||||||
|
.add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),True)
|
||||||
|
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False)
|
||||||
.sign(key,hashes.SHA256()))
|
.sign(key,hashes.SHA256()))
|
||||||
write(keypath,key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
|
write(keypath,key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
|
||||||
write(capath,ca.public_bytes(serialization.Encoding.PEM))
|
write(capath,ca.public_bytes(serialization.Encoding.PEM))
|
||||||
key = serialization.load_pem_private_key(keypath.read_bytes(),password=None)
|
key = serialization.load_pem_private_key(keypath.read_bytes(),password=None)
|
||||||
ca = x509.load_pem_x509_certificate(capath.read_bytes())
|
ca = x509.load_pem_x509_certificate(capath.read_bytes())
|
||||||
for name in ('lb','api1','api2','api','worker','dispatcher','cleaner','db','s3','broker','otel-collector','prometheus','loki','tempo','grafana','probe'):
|
for name in ('lb','api1','api2','api','worker','dispatcher','cleaner','openbao','db','s3','broker','otel-collector','prometheus','loki','tempo','grafana','probe'):
|
||||||
cert(name,key,ca)
|
cert(name,key,ca)
|
||||||
foreign_key = rsa.generate_private_key(public_exponent=65537,key_size=2048)
|
foreign_key = rsa.generate_private_key(public_exponent=65537,key_size=2048)
|
||||||
now=datetime.now(timezone.utc)
|
now=datetime.now(timezone.utc)
|
||||||
@@ -115,7 +124,7 @@ def main():
|
|||||||
for role in ('dispatcher','worker'):
|
for role in ('dispatcher','worker'):
|
||||||
definitions['users'].append({'name':role,'password':password('broker_'+role),'tags':[]})
|
definitions['users'].append({'name':role,'password':password('broker_'+role),'tags':[]})
|
||||||
definitions['permissions'].append({'user':role,'vhost':'lab7','configure':'^attachment\\.process\\.v1$',
|
definitions['permissions'].append({'user':role,'vhost':'lab7','configure':'^attachment\\.process\\.v1$',
|
||||||
'write':'^attachment\\.process\\.v1$' if role=='dispatcher' else '^$',
|
'write':'^amq.default$' if role=='dispatcher' else '^$',
|
||||||
'read':'^attachment\\.process\\.v1$' if role=='worker' else '^$'})
|
'read':'^attachment\\.process\\.v1$' if role=='worker' else '^$'})
|
||||||
write(PRIVATE/'broker.json',json.dumps(definitions))
|
write(PRIVATE/'broker.json',json.dumps(definitions))
|
||||||
for role in ('api','worker','dispatcher','cleaner'):
|
for role in ('api','worker','dispatcher','cleaner'):
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""Run checks with captured exit codes, sanitized output and guaranteed restore."""
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0,str(ROOT/'scripts'))
|
||||||
|
from manage import env,ready
|
||||||
|
|
||||||
|
|
||||||
|
def run(name,command):
|
||||||
|
result=subprocess.run(command,cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
||||||
|
output=result.stdout.decode('utf-8',errors='replace')
|
||||||
|
(ROOT/'evidence'/name).write_text('COMMAND: '+' '.join(command)+'\nEXIT: '+str(result.returncode)+'\n'+output,encoding='utf-8')
|
||||||
|
print(output,flush=True)
|
||||||
|
if result.returncode:
|
||||||
|
raise RuntimeError(name+' failed with exit '+str(result.returncode))
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
p=argparse.ArgumentParser();p.add_argument('check',choices=['internal','public','persistence','failover','business','all']);a=p.parse_args()
|
||||||
|
os.chdir(ROOT)
|
||||||
|
base='https://localhost:'+env()['HTTPS_PORT']
|
||||||
|
common=['--base-url',base,'--ca-file',str(ROOT/'secrets/ca.crt')]
|
||||||
|
py=[sys.executable,'-X','utf8']
|
||||||
|
if a.check in ('internal','all'):
|
||||||
|
run('internal.txt',['docker','compose','run','--rm','verifier'])
|
||||||
|
if a.check in ('public','all'):
|
||||||
|
for script in ('smoke','security'):
|
||||||
|
run(script+'.txt',py+['tests/'+script+'.py']+common)
|
||||||
|
if a.check in ('business','all'):
|
||||||
|
run('business-security.txt',py+['student-tests/security_suite.py'])
|
||||||
|
if a.check in ('persistence','all'):
|
||||||
|
hook='scripts/restart.'+('cmd' if os.name=='nt' else 'sh')
|
||||||
|
run('persistence.txt',py+['tests/resilience.py','--mode','persistence','--action-script',hook]+common)
|
||||||
|
if a.check in ('failover','all'):
|
||||||
|
hook='scripts/stop-one.'+('cmd' if os.name=='nt' else 'sh')
|
||||||
|
completed=set()
|
||||||
|
for path in ROOT.glob('evidence/stop-api*.json'):
|
||||||
|
path.unlink() # Only this runner's known generated summaries.
|
||||||
|
for attempt in range(6):
|
||||||
|
try:
|
||||||
|
# Reject execution against a different checkout/project.
|
||||||
|
assert env()['COMPOSE_PROJECT_NAME'].startswith('lyakhonov-lab7')
|
||||||
|
config=subprocess.check_output(['docker','compose','config','--format','json'],cwd=ROOT)
|
||||||
|
import json
|
||||||
|
assert json.loads(config)['name']==env()['COMPOSE_PROJECT_NAME']
|
||||||
|
ready()
|
||||||
|
run('failover-'+str(attempt+1)+'.txt',py+['tests/resilience.py','--mode','failover','--action-script',hook]+common)
|
||||||
|
completed={path.stem for path in ROOT.glob('evidence/stop-api*.json')}
|
||||||
|
finally:
|
||||||
|
subprocess.run(['docker','compose','start','api1','api2'],cwd=ROOT,check=True)
|
||||||
|
ready()
|
||||||
|
if completed=={'stop-api1','stop-api2'}:
|
||||||
|
print('PASS sequential failover proved for both real API containers; both restored.');return
|
||||||
|
raise RuntimeError('Both replica failures were not observed in six public scenarios')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Reproducible orchestration, scoped to this checkout and project."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
os.chdir(ROOT)
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args, **kwargs):
|
||||||
|
return subprocess.run(['docker','compose',*args],check=True,**kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def python(script,*args):
|
||||||
|
subprocess.run([sys.executable,'-X','utf8',str(ROOT/script),*args],check=True)
|
||||||
|
|
||||||
|
|
||||||
|
def env():
|
||||||
|
return dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line)
|
||||||
|
|
||||||
|
|
||||||
|
def ready():
|
||||||
|
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca.crt'))
|
||||||
|
endpoint='https://localhost:'+env()['HTTPS_PORT']+'/health/ready'
|
||||||
|
deadline=time.monotonic()+120
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(endpoint,context=ctx,timeout=3) as response:
|
||||||
|
assert response.status==200
|
||||||
|
print('HTTPS readiness: 200, CA and localhost SAN verified');return
|
||||||
|
except (OSError,AssertionError):
|
||||||
|
time.sleep(.5)
|
||||||
|
raise RuntimeError('HTTPS readiness exceeded 120 seconds')
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot():
|
||||||
|
ids=subprocess.check_output(['docker','compose','ps','-aq'],text=True).split()
|
||||||
|
result=[]
|
||||||
|
objects=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)) if ids else []
|
||||||
|
for d in objects:
|
||||||
|
result.append({'service':d['Config']['Labels']['com.docker.compose.service'],'id':d['Id'][:12],
|
||||||
|
'started_at':d['State']['StartedAt'],'status':d['State']['Status']})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser=argparse.ArgumentParser()
|
||||||
|
parser.add_argument('action',choices=['start','restart','stop-one','ready'])
|
||||||
|
parser.add_argument('--initialize',action='store_true')
|
||||||
|
parser.add_argument('--unseal',action='store_true')
|
||||||
|
a=parser.parse_args()
|
||||||
|
assert env()['COMPOSE_PROJECT_NAME'].startswith('lyakhonov-lab7')
|
||||||
|
if a.action=='ready':
|
||||||
|
ready();return
|
||||||
|
if a.action=='start':
|
||||||
|
compose('build','api1','s3')
|
||||||
|
compose('up','-d','db','s3','broker','openbao','prometheus','loki','tempo','otel-collector')
|
||||||
|
# Health init endpoint works while sealed, and validates CA/hostname.
|
||||||
|
sys.path.insert(0,str(ROOT/'scripts'))
|
||||||
|
from bao import request
|
||||||
|
for _ in range(60):
|
||||||
|
try:
|
||||||
|
request('sys/init');break
|
||||||
|
except OSError:
|
||||||
|
time.sleep(.5)
|
||||||
|
else:
|
||||||
|
raise RuntimeError('OpenBao TLS listener not ready')
|
||||||
|
if a.initialize:
|
||||||
|
python('scripts/bao.py','init')
|
||||||
|
if a.unseal:
|
||||||
|
python('scripts/bao.py','unseal')
|
||||||
|
python('scripts/bao.py','configure')
|
||||||
|
for _ in range(60):
|
||||||
|
probe=subprocess.run(['docker','compose','exec','-T','db','pg_isready','-U','messenger','-d','messenger'],stdout=subprocess.DEVNULL)
|
||||||
|
if probe.returncode==0:break
|
||||||
|
time.sleep(.5)
|
||||||
|
compose('run','--rm','migrate')
|
||||||
|
compose('exec','-T','db','psql','-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger',input=(ROOT/'infra/grants.sql').read_bytes())
|
||||||
|
compose('run','--rm','bucket-init')
|
||||||
|
compose('up','-d')
|
||||||
|
ready();return
|
||||||
|
before=snapshot()
|
||||||
|
if a.action=='restart':
|
||||||
|
compose('restart','api1','api2','worker','dispatcher','cleaner','db','s3','broker','openbao','prometheus','loki','tempo','grafana','otel-collector')
|
||||||
|
compose('restart','prometheus-tls','loki-tls','tempo-tls','tempo-tls-ingest')
|
||||||
|
if not a.unseal:
|
||||||
|
raise RuntimeError('Explicit --unseal operator action required after OpenBao restart')
|
||||||
|
# The key remains on the host. This hook is run by the operator, not app.
|
||||||
|
for _ in range(40):
|
||||||
|
result=subprocess.run([sys.executable,'-X','utf8','scripts/bao.py','unseal'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||||
|
if result.returncode==0:break
|
||||||
|
time.sleep(.5)
|
||||||
|
else:raise RuntimeError('Unseal failed')
|
||||||
|
ready()
|
||||||
|
else:
|
||||||
|
target=os.environ['TARGET_INSTANCE_ID']
|
||||||
|
found=[]
|
||||||
|
code="import urllib.request;print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])"
|
||||||
|
for service in ('api1','api2'):
|
||||||
|
current=subprocess.check_output(['docker','compose','exec','-T',service,'python','-c',code],text=True).strip()
|
||||||
|
if current==target:found.append(service)
|
||||||
|
assert len(found)==1,'Unknown or ambiguous process alias'
|
||||||
|
compose('stop','-t','1',found[0])
|
||||||
|
result={'action':a.action,'before':before,'after':snapshot()}
|
||||||
|
path=ROOT/'evidence'/('restart.json' if a.action=='restart' else 'stop-'+found[0]+'.json')
|
||||||
|
path.write_text(json.dumps(result,indent=2),encoding='utf-8')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""Clean Git export; new CA/secrets, project, images, volumes and free ports."""
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
project='lyakhonov-lab7-repro-'+uuid.uuid4().hex[:8]
|
||||||
|
target=Path(tempfile.mkdtemp(prefix=project+'-')).resolve()
|
||||||
|
assert target.is_relative_to(Path(tempfile.gettempdir()).resolve())
|
||||||
|
assert target.name.startswith(project+'-')
|
||||||
|
commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip()
|
||||||
|
archive=subprocess.check_output(['git','archive','HEAD'],cwd=ROOT)
|
||||||
|
with tarfile.open(fileobj=io.BytesIO(archive)) as bundle:
|
||||||
|
bundle.extractall(target,filter='data')
|
||||||
|
handles=[]
|
||||||
|
for _ in range(3):
|
||||||
|
handle=socket.socket();handle.bind(('127.0.0.1',0));handles.append(handle)
|
||||||
|
ports=[handle.getsockname()[1] for handle in handles]
|
||||||
|
for handle in handles:handle.close()
|
||||||
|
results=[]
|
||||||
|
def run(command,label):
|
||||||
|
print(label,flush=True)
|
||||||
|
result=subprocess.run(command,cwd=target,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
||||||
|
text=result.stdout.decode('utf-8',errors='replace')
|
||||||
|
results.append({'step':label,'exit':result.returncode,'output':text if result.returncode else
|
||||||
|
'\n'.join(line for line in text.splitlines() if any(word in line for word in ('PASS','ready','Initialized','unsealed','configured','preserved')))})
|
||||||
|
if result.returncode:
|
||||||
|
print(text[-5000:]);raise RuntimeError('Clean reproduction failed at '+label)
|
||||||
|
py=[sys.executable,'-X','utf8']
|
||||||
|
summary={'project':project,'exported_commit':commit,'ports':ports,'steps':results}
|
||||||
|
try:
|
||||||
|
run(py+['scripts/bootstrap.py','--project',project,'--port',str(ports[0]),'--bao-port',str(ports[1]),'--grafana-port',str(ports[2])],'new PKI and secrets')
|
||||||
|
# Explicit operator authorization to initialize and unseal THIS new project.
|
||||||
|
run(py+['scripts/manage.py','start','--initialize','--unseal'],'build, bootstrap OpenBao, migrate, readiness')
|
||||||
|
run(py+['scripts/check.py','public'],'public HTTPS smoke and external TLS trust')
|
||||||
|
run(py+['scripts/check.py','internal'],'internal mTLS, TLS links and policy deny')
|
||||||
|
summary['result']='PASS'
|
||||||
|
except Exception:
|
||||||
|
summary['result']='FAIL';raise
|
||||||
|
finally:
|
||||||
|
if (target/'.env').exists():
|
||||||
|
actual=dict(line.split('=',1) for line in (target/'.env').read_text().splitlines() if '=' in line)
|
||||||
|
assert actual['COMPOSE_PROJECT_NAME']==project
|
||||||
|
subprocess.run(['docker','compose','down','--volumes','--remove-orphans'],cwd=target,check=True,stdout=subprocess.DEVNULL)
|
||||||
|
subprocess.run(['docker','image','rm',project+'-app:1.0',project+'-s3:1.0'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||||
|
summary['temporary_resources_removed']=True
|
||||||
|
(ROOT/'evidence/reproduction.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf-8')
|
||||||
|
assert target.is_relative_to(Path(tempfile.gettempdir()).resolve()) and target.name.startswith(project+'-')
|
||||||
|
shutil.rmtree(target)
|
||||||
|
print('PASS clean Git export, new PKI/secrets, startup and security; temporary resources removed.')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
@echo off
|
||||||
|
"%~dp0..\.venv\Scripts\python.exe" -X utf8 "%~dp0manage.py" restart --unseal
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
exec python3 -X utf8 "$(dirname "$0")/manage.py" restart --unseal
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
@echo off
|
||||||
|
"%~dp0..\.venv\Scripts\python.exe" -X utf8 "%~dp0manage.py" stop-one
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
exec python3 -X utf8 "$(dirname "$0")/manage.py" stop-one
|
||||||
@@ -2,18 +2,26 @@
|
|||||||
|
|
||||||
## Активы и акторы
|
## Активы и акторы
|
||||||
|
|
||||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
Активы: password hashes/сессии, сообщения и приватные вложения, metadata/jobs/outbox, CA/service keys и credentials, три telemetry сигнала. Акторы: внешний REST-клиент, участник чата, посторонний зарегистрированный пользователь, сервис с чужим доверенным leaf, worker с его собственными credentials, host-оператор. Атакующий может присылать HTTP/поддельные identity, предъявлять тестовые чужие leaf; не владеет CA private key, Docker admin или памятью хоста. Администратор host/Docker доверен: иначе files/secrets и loopback граница не защищают.
|
||||||
|
|
||||||
## Границы доверия
|
## Границы доверия
|
||||||
|
|
||||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
[Матрица доверия](../contracts/trust-matrix.md) содержит каждую связь/порт/identity/TTL и тест. Внешние interfaces — только loopback HTTPS8443, Bao8207, Grafana3007. API за mTLS8443; plaintext8080 внутри своего namespace. DB/S3/broker/Bao/Collector — native TLS. Telemetry backends — TLS proxy с loopback HTTP/gRPC в том же namespace. Operator bootstrap отделён от app: CA key/root/unseal на host с ACL; сервисы получают только свой leaf, затем read-only KV через certificate auth и scoped token300s. Service leaf не заменяет Bearer пользователя.
|
||||||
|
|
||||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO | TODO |
|
| Чужой пользователь запрашивает metadata/content или прикрепляет вложение другого чата | Изоляция chat membership | Bearer → server-side membership, одинаковый404 | security_suite.py: metadata/content/attach404 | Состав участников фиксирован API курса |
|
||||||
|
| Клиент внутренней сети обходит LB на API | Только LB может передать бизнес-запрос | mTLS + CN lb allowlist, uvicorn loopback | internal.py: обе replica, no cert/foreign CA/trusted wrong CN отказ, lb200 | Компрометация CA/namespace вне модели |
|
||||||
|
| MITM подменяет DB/S3/broker/backend | Конфиденциальность/identity peer | CA+hostname/SAN, verify-full; proxy boundary | internal.py: реальные TLS, wrong hostname certificate error, plaintext закрыт | Host admin может читать память/mounts |
|
||||||
|
| Worker использует свою Bao identity для чтения API/admin secrets | Разделение service credentials | exact leaf auth, отдельный KV path/read-only policy | own200, foreign403, policy/KV write403, DB users denied | Статические KV credentials до ручной смены |
|
||||||
|
| Подбор пароля/повтор украденной session | Ограниченный вход, expiry/revocation | Argon2id19MiB/t2/p1, salted PHC; DB sessions; login10/60s | security_suite.py: 429+Retry-After, logout401, TTL2→401 | Account denial возможен, global distributed DoS не покрыт |
|
||||||
|
| Oversized JSON/chunked/upload | Ограниченные входные bytes | Actual ASGI stream64KiB/10MiB, pixels40M; контейнерные limits | fixed/chunked413, image fixture ready | Сетевой клиент может расходовать соединения до timeout LB |
|
||||||
|
| Credentials попадают в telemetry/image/Git | Нет раскрытия service/user secrets | .gitignore/.dockerignore, targeted COPY, без body/header logging | audit.py: files/layers; telemetry.py: реальные записи/logs | Скан известных значений не доказывает все возможные утечки |
|
||||||
|
|
||||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||||
|
|
||||||
## Lifecycle и инциденты
|
## Lifecycle и инциденты
|
||||||
|
|
||||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
Оператор создаёт CA365d/leaf30d и credentials, init/unseal/configure выполняются явно host-скриптом по REPORT.md. Учебная доля1-of-1 хранится только на host с NTFS ACL/0700; нужна защищённая резервная копия отдельно от data volume. После рестарта Bao sealed, оператор делает unseal. API restart при unsealed Bao автономен. App token TTL300s, повторная аутентификация240s. Leaf/static credentials требуют ручной перевыдачи/смены; автоматическая ротация не заявлена. При компрометации service leaf оператор блокирует auth role, меняет её KV credentials и leaf, перезапускает процессы/соединения; сохранённые static credentials сами не истекут по TTL token. Sealed Bao не имеет plaintext/root fallback, новые app-процессы до unseal не стартуют. Открытый DB pool может продолжить работу; после cache240s S3 secret-read требует Bao.
|
||||||
|
|
||||||
|
Dependency/image CVE scan уровня4 не заявлен. Проверка утечек ищет actual credentials/private keys в Git/evidence/exported layers/real telemetry и container logs. Найденные длинные Rabbit ACL regex являются открытой конфигурацией, а не паролями, и отдельно исключены из списка secret values. Исправленные setup failures перечислены в evidence/setup-notes.txt. Оставшиеся риски — host admin, single-host storage, ручной lifecycle и ограниченность учебного proxy; они не скрываются счётчиком PASS.
|
||||||
|
|||||||
+2
-1
@@ -16,6 +16,7 @@ from src.models import ErrorResponse
|
|||||||
from src.routes import chats, health, messages, users, attachments
|
from src.routes import chats, health, messages, users, attachments
|
||||||
from botocore.exceptions import BotoCoreError, ClientError
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
from src.storage import storage
|
from src.storage import storage
|
||||||
|
from src.identity import INSTANCE_ID
|
||||||
|
|
||||||
|
|
||||||
from src import telemetry
|
from src import telemetry
|
||||||
@@ -32,7 +33,7 @@ def create_app() -> FastAPI:
|
|||||||
finally:
|
finally:
|
||||||
await run_in_threadpool(storage.pool.close)
|
await run_in_threadpool(storage.pool.close)
|
||||||
|
|
||||||
instance_id = uuid.uuid4().hex
|
instance_id = INSTANCE_ID
|
||||||
app = FastAPI(title="MTUSI Messenger Lab7", version="1.7.0", lifespan=lifespan)
|
app = FastAPI(title="MTUSI Messenger Lab7", version="1.7.0", lifespan=lifespan)
|
||||||
|
|
||||||
@app.exception_handler(BotoCoreError)
|
@app.exception_handler(BotoCoreError)
|
||||||
|
|||||||
+2
-2
@@ -1,12 +1,13 @@
|
|||||||
"""Bound the actual ASGI stream, including requests without Content-Length."""
|
"""Bound the actual ASGI stream, including requests without Content-Length."""
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
|
from src.identity import INSTANCE_ID
|
||||||
|
|
||||||
|
|
||||||
class BodyLimit:
|
class BodyLimit:
|
||||||
def __init__(self, app):
|
def __init__(self, app):
|
||||||
self.app = app
|
self.app = app
|
||||||
self.instance = uuid.uuid4().hex.encode()
|
self.instance = INSTANCE_ID.encode()
|
||||||
|
|
||||||
async def __call__(self, scope, receive, send):
|
async def __call__(self, scope, receive, send):
|
||||||
if scope['type'] != 'http':
|
if scope['type'] != 'http':
|
||||||
@@ -20,7 +21,6 @@ class BodyLimit:
|
|||||||
size += len(message.get('body', b''))
|
size += len(message.get('body', b''))
|
||||||
if size > maximum:
|
if size > maximum:
|
||||||
request_id = str(uuid.uuid4())
|
request_id = str(uuid.uuid4())
|
||||||
import socket
|
|
||||||
body = json.dumps({'error': {'code':'payload_too_large', 'message':'размер запроса превышен',
|
body = json.dumps({'error': {'code':'payload_too_large', 'message':'размер запроса превышен',
|
||||||
'request_id':request_id}}).encode()
|
'request_id':request_id}}).encode()
|
||||||
await send({'type':'http.response.start', 'status':413, 'headers':[
|
await send({'type':'http.response.start', 'status':413, 'headers':[
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
"""One public random process alias, without container hostname or address."""
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
INSTANCE_ID = uuid.uuid4().hex
|
||||||
-60
@@ -176,63 +176,3 @@ def recover_expired():
|
|||||||
and not owns(conn, job, job)):
|
and not owns(conn, job, job)):
|
||||||
settle_error(conn, job, 'lease_expired')
|
settle_error(conn, job, 'lease_expired')
|
||||||
|
|
||||||
|
|
||||||
def replay(attachment_id):
|
|
||||||
with storage.pool.connection() as conn:
|
|
||||||
attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',
|
|
||||||
(attachment_id,)).fetchone()
|
|
||||||
if not attachment:
|
|
||||||
return None
|
|
||||||
job = conn.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE',
|
|
||||||
(attachment_id, attachment['target_pipeline_version'])).fetchone()
|
|
||||||
if not job or job['state'] != 'failed':
|
|
||||||
return None
|
|
||||||
source = attachment['object_key'] if attachment['published_pipeline_version'] else job['staging_key']
|
|
||||||
object_lock(conn, source)
|
|
||||||
client().head_object(Bucket=BUCKET, Key=source)
|
|
||||||
new_attempt = job['attempt'] + 1
|
|
||||||
budget = int(setting('JOB_MAX_ATTEMPTS', '5'))
|
|
||||||
conn.execute(
|
|
||||||
"""UPDATE attachment_jobs SET state='queued', attempt=%s, attempt_limit=%s,
|
|
||||||
next_publish_at=clock_timestamp(), published_at=NULL, publish_failures=0, settled_at=NULL
|
|
||||||
WHERE id=%s""", (new_attempt, new_attempt + budget - 1, job['id']),
|
|
||||||
)
|
|
||||||
conn.execute("INSERT INTO attachment_replays(job_id,attempt,reason) VALUES (%s,%s,'operator')",
|
|
||||||
(job['id'], new_attempt))
|
|
||||||
conn.execute("UPDATE attachments SET state='queued',error_code=NULL,updated_at=clock_timestamp() "
|
|
||||||
"WHERE id=%s AND published_pipeline_version IS NULL", (attachment_id,))
|
|
||||||
return job['id'], new_attempt
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade(attachment_id, version):
|
|
||||||
with storage.pool.connection() as conn:
|
|
||||||
attachment = conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE', (attachment_id,)).fetchone()
|
|
||||||
if not attachment or version not in ENCODING or version <= attachment['target_pipeline_version']:
|
|
||||||
return None
|
|
||||||
previous = conn.execute(
|
|
||||||
'SELECT staging_key FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s',
|
|
||||||
(attachment_id, attachment['target_pipeline_version']),
|
|
||||||
).fetchone()
|
|
||||||
if not previous and not attachment['published_pipeline_version']:
|
|
||||||
return None
|
|
||||||
source = attachment['object_key'] if attachment['published_pipeline_version'] else previous['staging_key']
|
|
||||||
object_lock(conn, source)
|
|
||||||
client().head_object(Bucket=BUCKET, Key=source)
|
|
||||||
conn.execute(
|
|
||||||
"""UPDATE attachment_jobs SET state='superseded', lease_token=NULL, lease_until=NULL,
|
|
||||||
next_publish_at=NULL, settled_at=clock_timestamp()
|
|
||||||
WHERE attachment_id=%s AND state IN ('queued','processing')""", (attachment_id,),
|
|
||||||
)
|
|
||||||
conn.execute(
|
|
||||||
"""UPDATE attachments SET target_pipeline_version=%s,
|
|
||||||
state=CASE WHEN published_pipeline_version IS NULL THEN 'queued' ELSE 'ready' END,
|
|
||||||
error_code=NULL,updated_at=clock_timestamp() WHERE id=%s""",
|
|
||||||
(version, attachment_id),
|
|
||||||
)
|
|
||||||
job_id = uuid4()
|
|
||||||
conn.execute(
|
|
||||||
"""INSERT INTO attachment_jobs(id,attachment_id,staging_key,attempt_limit,next_publish_at,pipeline_version)
|
|
||||||
VALUES (%s,%s,%s,%s,clock_timestamp(),%s)""",
|
|
||||||
(job_id, attachment_id, f'staging/{attachment_id}', int(setting('JOB_MAX_ATTEMPTS', '5')), version),
|
|
||||||
)
|
|
||||||
return job_id
|
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
"""Единственный обязательный pipeline."""
|
"""Required pipeline only."""
|
||||||
ENCODING = {1: (85, 82)}
|
ENCODING = {1: (85, 82)}
|
||||||
|
|||||||
@@ -18,6 +18,3 @@ def readiness():
|
|||||||
return Health()
|
return Health()
|
||||||
|
|
||||||
|
|
||||||
@router.get('/stats')
|
|
||||||
def stats():
|
|
||||||
return storage.get_stats()
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
"""KDF measured within the app's 0.5 CPU / 512MiB limit."""
|
||||||
|
import json
|
||||||
|
import statistics
|
||||||
|
import time
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
|
||||||
|
hasher=PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1)
|
||||||
|
hashes=[];values=[]
|
||||||
|
for _ in range(12):
|
||||||
|
started=time.perf_counter();encoded=hasher.hash('synthetic-benchmark-input');hasher.verify(encoded,'synthetic-benchmark-input')
|
||||||
|
values.append((time.perf_counter()-started)*1000);hashes.append(encoded)
|
||||||
|
assert len(set(hashes))==12
|
||||||
|
print(json.dumps({'algorithm':'argon2id','memory_kib':19456,'time_cost':2,'parallelism':1,'samples':12,
|
||||||
|
'cpu_limit':.5,'memory_limit_mib':512,'operation':'hash + verify','min_ms':round(min(values),2),
|
||||||
|
'median_ms':round(statistics.median(values),2),'max_ms':round(max(values),2),'distinct_salts':True},indent=2))
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Accepted queued upload survives worker stop; real broker redelivery and dedupe."""
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0,str(ROOT/'tests'));sys.path.insert(0,str(ROOT/'scripts'))
|
||||||
|
from client import Client
|
||||||
|
from manage import env
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args):subprocess.run(['docker','compose',*args],cwd=ROOT,check=True)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
client=Client('https://localhost:'+env()['HTTPS_PORT'],str(ROOT/'secrets/ca.crt'))
|
||||||
|
alice,bob,eve,chat=client.bootstrap()
|
||||||
|
try:
|
||||||
|
compose('stop','-t','5','worker')
|
||||||
|
attachment,content=client.attachment(alice,chat)
|
||||||
|
assert attachment['status']=='queued'
|
||||||
|
compose('run','--rm','verifier','python','/checks/redelivery.py','redeliver')
|
||||||
|
finally:
|
||||||
|
compose('start','worker')
|
||||||
|
ready=client.wait_ready(alice,attachment)
|
||||||
|
assert client.call('GET','/api/v1/attachments/'+ready['id']+'/content',actor=bob)['bytes']==content
|
||||||
|
assert len(ready['variants'])==1 and ready['variants'][0]['name']=='thumbnail'
|
||||||
|
compose('run','--rm','verifier','python','/checks/redelivery.py','duplicate',ready['id'])
|
||||||
|
time.sleep(3)
|
||||||
|
after=client.call('GET','/api/v1/attachments/'+ready['id'],actor=bob,schema='Attachment')['json']
|
||||||
|
assert after==ready
|
||||||
|
print('PASS accepted202 during worker stop -> ready with exact original/one thumbnail; no-ack redelivery and completed-job duplicate did not duplicate effects')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""Run in the verifier profile. Real TLS, identity and authorization probes."""
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
import uuid
|
||||||
|
import time
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
import pika
|
||||||
|
import psycopg
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
|
||||||
|
|
||||||
|
def context(identity=None):
|
||||||
|
ctx=ssl.create_default_context(cafile='/probe/lb/ca.crt')
|
||||||
|
if identity:
|
||||||
|
ctx.load_cert_chain('/probe/'+identity+'/cert.crt','/probe/'+identity+'/key.key')
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
def http(host,port,path,identity=None,method='GET',body=None,token=None):
|
||||||
|
headers={'Content-Type':'application/json'}
|
||||||
|
if token:headers['X-Vault-Token']=token
|
||||||
|
req=urllib.request.Request(f'https://{host}:{port}'+path,data=json.dumps(body).encode() if body is not None else None,
|
||||||
|
headers=headers,method=method)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req,context=context(identity),timeout=5) as response:
|
||||||
|
return response.status,response.read()
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
return error.code,error.read()
|
||||||
|
|
||||||
|
|
||||||
|
def denied_tls(host,port,path,identity):
|
||||||
|
try:
|
||||||
|
status,_=http(host,port,path,identity)
|
||||||
|
except (ssl.SSLError, ConnectionResetError, __import__('http.client',fromlist=['RemoteDisconnected']).RemoteDisconnected):
|
||||||
|
return
|
||||||
|
except urllib.error.URLError as error:
|
||||||
|
assert isinstance(error.reason,(ssl.SSLError,ConnectionResetError)),type(error.reason).__name__
|
||||||
|
return
|
||||||
|
raise AssertionError('TLS authorization unexpectedly returned HTTP '+str(status))
|
||||||
|
|
||||||
|
|
||||||
|
def plaintext_closed(host,port):
|
||||||
|
try:
|
||||||
|
with socket.create_connection((host,port),timeout=2):pass
|
||||||
|
except ConnectionRefusedError:return
|
||||||
|
raise AssertionError('Plaintext bypass reachable '+host)
|
||||||
|
|
||||||
|
|
||||||
|
def wait_http(host,port,path,identity):
|
||||||
|
deadline=time.monotonic()+60
|
||||||
|
while True:
|
||||||
|
status,_=http(host,port,path,identity)
|
||||||
|
if status==200:return
|
||||||
|
assert time.monotonic()<deadline,(host,'not ready',status)
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
|
def bao(role,identity=None):
|
||||||
|
status,data=http('openbao',8200,'/v1/auth/cert/login',identity or role,'POST',{'name':role})
|
||||||
|
assert status==200,('certificate login',role,status)
|
||||||
|
auth=json.loads(data)['auth']
|
||||||
|
assert 0<auth['lease_duration']<=300
|
||||||
|
token=auth['client_token']
|
||||||
|
own='api' if role=='api2' else role
|
||||||
|
status,data=http('openbao',8200,'/v1/secret/data/'+own,identity or role,token=token)
|
||||||
|
assert status==200
|
||||||
|
for path,method,body in [('/v1/secret/data/'+('worker' if own=='api' else 'api'),'GET',None),
|
||||||
|
('/v1/sys/policies/acl/escalation','PUT',{'policy':'path "*" { capabilities=["root"] }'}),
|
||||||
|
('/v1/secret/data/'+own,'POST',{'data':{'overwritten':True}})]:
|
||||||
|
assert http('openbao',8200,path,identity or role,method,body,token)[0]==403
|
||||||
|
print('PASS OpenBao',role,'cert auth; TTL<=300; own read=200; foreign read/policy write/KV write=403')
|
||||||
|
return json.loads(data)['data']['data']
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
for host in ('api1','api2'):
|
||||||
|
for identity in (None,'foreign','probe'):
|
||||||
|
denied_tls(host,8443,'/health/ready',identity)
|
||||||
|
assert http(host,8443,'/health/ready','lb')[0]==200
|
||||||
|
plaintext_closed(host,8080)
|
||||||
|
print('PASS',host,'no cert / foreign CA / trusted wrong identity rejected; lb=200; port8080 closed')
|
||||||
|
secrets={role:bao(role, 'api1' if role=='api' else role) for role in ('api','api2','worker','dispatcher','cleaner')}
|
||||||
|
assert http('openbao',8200,'/v1/auth/cert/login','probe','POST',{'name':'api'})[0] in (400,403)
|
||||||
|
for role in ('api','worker','dispatcher','cleaner'):
|
||||||
|
with psycopg.connect(secrets[role]['DATABASE_URL']) as conn:
|
||||||
|
assert conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]
|
||||||
|
assert conn.execute('SELECT current_user').fetchone()[0]==role
|
||||||
|
try:
|
||||||
|
with psycopg.connect(secrets[role]['DATABASE_URL'].replace('sslmode=verify-full','sslmode=disable')):pass
|
||||||
|
except psycopg.OperationalError:pass
|
||||||
|
else:raise AssertionError('DB accepted plaintext')
|
||||||
|
if role=='worker':
|
||||||
|
try:
|
||||||
|
with psycopg.connect(secrets[role]['DATABASE_URL']) as conn:conn.execute('SELECT * FROM users LIMIT 1')
|
||||||
|
except psycopg.errors.InsufficientPrivilege:pass
|
||||||
|
else:raise AssertionError('worker can read user credentials')
|
||||||
|
print('PASS PostgreSQL',role,'verify-full, server TLS observed; plaintext rejected')
|
||||||
|
for role in ('api','worker','cleaner'):
|
||||||
|
s3=boto3.client('s3',endpoint_url='https://s3:9000',verify='/probe/s3/ca.crt',region_name='us-east-1',
|
||||||
|
aws_access_key_id=secrets[role]['S3_ACCESS_KEY'],aws_secret_access_key=secrets[role]['S3_SECRET_KEY'])
|
||||||
|
try:s3.list_buckets()
|
||||||
|
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403
|
||||||
|
else:raise AssertionError('S3 identity has admin listing')
|
||||||
|
if role in ('api','cleaner'):s3.list_objects_v2(Bucket='attachments',Prefix='staging/',MaxKeys=1)
|
||||||
|
if role=='worker':
|
||||||
|
try:s3.put_object(Bucket='attachments',Key='staging/denied-'+uuid.uuid4().hex,Body=b'denied')
|
||||||
|
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403
|
||||||
|
else:raise AssertionError('worker can write API staging')
|
||||||
|
print('PASS S3',role,'TLS; administrative bucket listing denied; scoped permissions')
|
||||||
|
for role in ('worker','dispatcher'):
|
||||||
|
params=pika.URLParameters(secrets[role]['BROKER_URL'])
|
||||||
|
params.ssl_options=pika.SSLOptions(context(),'broker')
|
||||||
|
connection=pika.BlockingConnection(params)
|
||||||
|
channel=connection.channel();channel.queue_declare('attachment.process.v1',durable=True)
|
||||||
|
try:
|
||||||
|
if role=='worker':
|
||||||
|
channel.confirm_delivery();channel.basic_publish('','attachment.process.v1',b'{}')
|
||||||
|
else:channel.basic_get('attachment.process.v1')
|
||||||
|
except pika.exceptions.ChannelClosedByBroker as error:assert error.reply_code==403
|
||||||
|
else:raise AssertionError('broker ACL did not reject wrong operation')
|
||||||
|
connection.close()
|
||||||
|
print('PASS RabbitMQ',role,'TLS; wrong producer/consumer operation=403')
|
||||||
|
plaintext_closed('broker',5672)
|
||||||
|
assert http('otel-collector',4318,'/v1/traces','api1','POST',{})[0]==200
|
||||||
|
denied_tls('otel-collector',4318,'/v1/traces',None)
|
||||||
|
print('PASS Collector TLS authenticated ingest; no-certificate rejected')
|
||||||
|
for host,path in [('prometheus','/-/ready'),('loki','/ready'),('tempo','/ready')]:
|
||||||
|
wait_http(host,9443,path,'grafana')
|
||||||
|
denied_tls(host,9443,path,'probe')
|
||||||
|
plaintext_closed(host,{'prometheus':9090,'loki':3100,'tempo':3200}[host])
|
||||||
|
print('PASS backend',host,'Grafana mTLS; wrong identity rejected; plaintext closed')
|
||||||
|
assert http('tempo',9444,'/v1/traces','otel-collector','POST',{})[0]==200
|
||||||
|
payload={'resourceLogs':[{'resource':{'attributes':[{'key':'service.name','value':{'stringValue':'security-probe'}}]},
|
||||||
|
'scopeLogs':[{'logRecords':[{'timeUnixNano':str(time.time_ns()),'body':{'stringValue':'tls.authorization.probe'},'severityNumber':9}]}]}]}
|
||||||
|
status,_=http('loki',9443,'/otlp/v1/logs','otel-collector','POST',payload)
|
||||||
|
assert status in (200,204),('Loki OTLP valid record',status)
|
||||||
|
assert http('prometheus',9443,'/-/ready','otel-collector')[0]==200
|
||||||
|
print('PASS Collector -> all backends mTLS')
|
||||||
|
# Assert hostname rejection, distinct from network timeout/refusal.
|
||||||
|
with socket.create_connection(('s3',9000),timeout=3) as raw:
|
||||||
|
try:context().wrap_socket(raw,server_hostname='wrong.invalid')
|
||||||
|
except ssl.SSLCertVerificationError:pass
|
||||||
|
else:raise AssertionError('wrong hostname accepted')
|
||||||
|
print('PASS internal wrong hostname rejected by certificate verifier')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""Broker no-ack redelivery and duplicate completed job, using scoped identities."""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import pika
|
||||||
|
import psycopg
|
||||||
|
from internal import context,http
|
||||||
|
|
||||||
|
|
||||||
|
def credentials(role):
|
||||||
|
status,data=http('openbao',8200,'/v1/auth/cert/login',role,'POST',{'name':role})
|
||||||
|
assert status==200
|
||||||
|
token=json.loads(data)['auth']['client_token']
|
||||||
|
status,data=http('openbao',8200,'/v1/secret/data/'+role,role,token=token)
|
||||||
|
assert status==200
|
||||||
|
return json.loads(data)['data']['data']
|
||||||
|
|
||||||
|
|
||||||
|
def connect(role):
|
||||||
|
params=pika.URLParameters(credentials(role)['BROKER_URL'])
|
||||||
|
params.ssl_options=pika.SSLOptions(context(),'broker')
|
||||||
|
return pika.BlockingConnection(params)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if sys.argv[1]=='redeliver':
|
||||||
|
bodies=[]
|
||||||
|
for attempt in range(2):
|
||||||
|
conn=connect('worker');channel=conn.channel()
|
||||||
|
deadline=time.monotonic()+15
|
||||||
|
while True:
|
||||||
|
method,properties,body=channel.basic_get('attachment.process.v1',auto_ack=False)
|
||||||
|
if method:break
|
||||||
|
assert time.monotonic()<deadline,'Job not present in durable broker queue'
|
||||||
|
time.sleep(.2)
|
||||||
|
assert properties.delivery_mode==2 and len(body)<4096
|
||||||
|
assert 'job_id' in json.loads(body)
|
||||||
|
if attempt:assert method.redelivered and body==bodies[0]
|
||||||
|
bodies.append(body)
|
||||||
|
conn.close() # No ack: broker MUST redeliver the same durable body.
|
||||||
|
print('PASS durable broker job delivered, disconnected without ack, redelivered=True; left queued for real worker')
|
||||||
|
else:
|
||||||
|
secrets=credentials('worker')
|
||||||
|
with psycopg.connect(secrets['DATABASE_URL']) as conn:
|
||||||
|
row=conn.execute('SELECT id,attachment_id,pipeline_version,attempt,created_at FROM attachment_jobs WHERE attachment_id=%s AND state=\'ready\'',(sys.argv[2],)).fetchone()
|
||||||
|
assert row
|
||||||
|
body={'schema_version':1,'job_id':str(row[0]),'type':'attachment.process.v1','attachment_id':str(row[1]),
|
||||||
|
'pipeline_version':row[2],'attempt':row[3],'created_at':row[4].isoformat(timespec='microseconds').replace('+00:00','Z')}
|
||||||
|
conn=connect('dispatcher');channel=conn.channel();channel.confirm_delivery()
|
||||||
|
channel.basic_publish('','attachment.process.v1',json.dumps(body).encode(),properties=pika.BasicProperties(delivery_mode=2),mandatory=True)
|
||||||
|
conn.close()
|
||||||
|
print('PASS completed job duplicate published with broker confirm')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Host business security, limits and a real two-second session expiry."""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0,str(ROOT/'tests'))
|
||||||
|
sys.path.insert(0,str(ROOT/'scripts'))
|
||||||
|
from client import Client, check
|
||||||
|
from manage import env,ready
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c=Client('https://localhost:'+env()['HTTPS_PORT'],str(ROOT/'secrets/ca.crt'))
|
||||||
|
alice,bob,eve,chat=c.bootstrap()
|
||||||
|
attachment,original=c.attachment(alice,chat)
|
||||||
|
attachment=c.wait_ready(alice,attachment)
|
||||||
|
other=c.call('POST','/api/v1/chats',201,actor=eve,body={'title':'Other','member_ids':[eve['id']]},schema='Chat')['json']
|
||||||
|
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=eve,
|
||||||
|
body={'text':'','attachment_ids':[attachment['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||||
|
for suffix in ('','/content','/content?variant=thumbnail'):
|
||||||
|
c.call('GET','/api/v1/attachments/'+attachment['id']+suffix,404,actor=eve)
|
||||||
|
me=c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json']
|
||||||
|
assert me['id']==alice['id']
|
||||||
|
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||||
|
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||||
|
print('PASS attachment ACL, foreign-chat attach=404, spoofed identity ignored, logout=401')
|
||||||
|
name='limited_'+uuid.uuid4().hex[:12]
|
||||||
|
bad='Basic '+base64.b64encode((name+':synthetic-invalid').encode()).decode()
|
||||||
|
for _ in range(10):c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':bad})
|
||||||
|
response=c.call('POST','/api/v1/auth/sessions',429,headers={'Authorization':bad})
|
||||||
|
assert int(response['headers']['Retry-After'])>0
|
||||||
|
print('PASS login limit: 10 allowed attempts, 11th=429 with Retry-After')
|
||||||
|
c.call('POST','/api/v1/users',413,raw=b'x'*65537,headers={'Content-Type':'application/json'})
|
||||||
|
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=large.png',413,actor=bob,
|
||||||
|
raw=b'x'*(10485760+1),headers={'Content-Type':'image/png'})
|
||||||
|
# urllib uses chunked transfer for an iterable without Content-Length.
|
||||||
|
c.call('POST','/api/v1/users',413,raw=iter([b'x'*40000,b'x'*30000]),headers={'Content-Type':'application/json'})
|
||||||
|
print('PASS JSON 64KiB, upload 10MiB and actual chunked stream limits=413')
|
||||||
|
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca.crt'))
|
||||||
|
import socket
|
||||||
|
with socket.create_connection(('127.0.0.1',int(env()['HTTPS_PORT'])),timeout=3) as raw:
|
||||||
|
try:ctx.wrap_socket(raw,server_hostname='wrong.invalid')
|
||||||
|
except ssl.SSLCertVerificationError:pass
|
||||||
|
else:raise AssertionError('external wrong hostname accepted')
|
||||||
|
print('PASS external wrong hostname rejected by certificate verifier')
|
||||||
|
temporary=dict(os.environ,SESSION_TTL_SECONDS='2')
|
||||||
|
try:
|
||||||
|
subprocess.run(['docker','compose','up','-d','api1','api2'],cwd=ROOT,env=temporary,check=True,stdout=subprocess.DEVNULL)
|
||||||
|
ready()
|
||||||
|
# Ensure BOTH new replicas are ready and serving before making a session.
|
||||||
|
time.sleep(3)
|
||||||
|
actor=c.user('expiry')
|
||||||
|
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||||
|
time.sleep(3)
|
||||||
|
c.call('GET','/api/v1/users/me',401,actor=actor)
|
||||||
|
print('PASS configured SESSION_TTL_SECONDS=2: valid before expiry, 401 after expiry')
|
||||||
|
finally:
|
||||||
|
subprocess.run(['docker','compose','up','-d','api1','api2'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
|
||||||
|
ready()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""Observe real signals through authenticated Grafana HTTPS datasource proxy."""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0,str(ROOT/'scripts'))
|
||||||
|
from manage import env
|
||||||
|
|
||||||
|
|
||||||
|
def get(path):
|
||||||
|
credential=base64.b64encode(('admin:'+(ROOT/'secrets/grafana_password').read_text().strip()).encode()).decode()
|
||||||
|
request=urllib.request.Request('https://localhost:'+env()['GRAFANA_PORT']+path,headers={'Authorization':'Basic '+credential})
|
||||||
|
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca.crt'))
|
||||||
|
with urllib.request.urlopen(request,context=ctx,timeout=15) as response:
|
||||||
|
return json.load(response)
|
||||||
|
|
||||||
|
|
||||||
|
def query(source,path,**params):
|
||||||
|
return get('/api/datasources/proxy/uid/'+source+path+'?'+urllib.parse.urlencode(params))
|
||||||
|
|
||||||
|
|
||||||
|
def secret_values():
|
||||||
|
values=[]
|
||||||
|
def walk(v):
|
||||||
|
if isinstance(v,dict):
|
||||||
|
for item in v.values():walk(item)
|
||||||
|
elif isinstance(v,list):
|
||||||
|
for item in v:walk(item)
|
||||||
|
elif isinstance(v,str) and len(v)>=20 and '\n' not in v and not v.startswith(('-----','^')):
|
||||||
|
values.append(v)
|
||||||
|
for file in (ROOT/'secrets').glob('*'):
|
||||||
|
if not file.is_file() or file.suffix in ('.crt','.yaml'):continue
|
||||||
|
data=file.read_text()
|
||||||
|
try:walk(json.loads(data))
|
||||||
|
except ValueError:
|
||||||
|
if len(data.strip())>=20:values.append(data.strip())
|
||||||
|
operator=ROOT/'secrets/operator/bao-init.json'
|
||||||
|
if operator.exists():walk(json.loads(operator.read_text()))
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
dashboard=get('/api/dashboards/uid/messenger')['dashboard']
|
||||||
|
assert len(dashboard['panels'])>=6
|
||||||
|
result={}
|
||||||
|
result['metrics']=query('prometheus','/api/v1/query',query='messenger_http_requests_total')
|
||||||
|
assert result['metrics']['data']['result'],'No HTTP counters stored'
|
||||||
|
result['jobs']=query('prometheus','/api/v1/query',query='messenger_jobs_total')
|
||||||
|
assert result['jobs']['data']['result'],'No worker metrics stored'
|
||||||
|
result['logs']=query('loki','/loki/api/v1/query_range',query='{service_name=~"messenger-api|messenger-worker"}',limit=1000,
|
||||||
|
start=str(time.time_ns()-3600*10**9),end=str(time.time_ns()))
|
||||||
|
assert result['logs']['data']['result'],'No API or worker logs stored'
|
||||||
|
services=set(stream['stream'].get('service_name') for stream in result['logs']['data']['result'])
|
||||||
|
assert {'messenger-api','messenger-worker'}<=services,services
|
||||||
|
trace_counts={}
|
||||||
|
for service in ('messenger-api','messenger-worker'):
|
||||||
|
traces=query('tempo','/api/search',q='{resource.service.name="'+service+'"}',limit=20)
|
||||||
|
assert traces.get('traces'),('No stored traces',service)
|
||||||
|
trace_counts[service]=len(traces['traces'])
|
||||||
|
trace_id=traces['traces'][0]['traceID']
|
||||||
|
result['trace_'+service]=get('/api/datasources/proxy/uid/tempo/api/traces/'+trace_id)
|
||||||
|
# Inspect returned records, not only Collector configuration.
|
||||||
|
payload=json.dumps(result)
|
||||||
|
for value in secret_values():
|
||||||
|
assert value not in payload,'Credential found in stored telemetry'
|
||||||
|
assert base64.b64encode(value.encode()).decode() not in payload,'Encoded credential found in telemetry'
|
||||||
|
assert 'BEGIN PRIVATE KEY' not in payload
|
||||||
|
# Container logs are scanned in memory and never saved as raw evidence.
|
||||||
|
logs=subprocess.check_output(['docker','compose','logs','--no-color'],cwd=ROOT).decode(errors='replace')
|
||||||
|
for value in secret_values():assert value not in logs,'Credential found in container logs'
|
||||||
|
summary={'grafana_https':True,'provisioned_panels':len(dashboard['panels']),
|
||||||
|
'http_metric_series':len(result['metrics']['data']['result']),'job_metric_series':len(result['jobs']['data']['result']),
|
||||||
|
'log_services':sorted(services),'trace_counts':trace_counts,'credential_scan':'PASS; returned telemetry and container logs'}
|
||||||
|
(ROOT/'evidence/telemetry.json').write_text(json.dumps(summary,indent=2),encoding='utf-8')
|
||||||
|
print(json.dumps(summary,indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
Reference in New Issue
Block a user