forked from mtusi2026/mtusi2026lab7
feat: drop capabilities, run read-only and non-root in every container, mTLS for the S3 gRPC gateway
Every service of the stand gets the x-hardening anchor (cap_drop ALL, no-new-privileges, read-only root) with an empty exception table, tmpfs with size limits, pids limits by measurement and non-root users for PostgreSQL, Valkey, RabbitMQ and SeaweedFS. The S3 gateway gRPC accepts only mTLS with the stand CA. make hardening_check checks inspect data, processes and listeners against the compose model; a fast test keeps the override files from removing restrictions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,372 @@
|
||||
# Ограничения контейнеров (change `container-hardening`)
|
||||
|
||||
- Снято на рабочем дереве поверх `1f45bfe` (propose) с правками apply, **до коммита**; стенд «до» — код `3ef21c2`
|
||||
(compose рабочего дерева до первой правки apply совпадал с ним), 2026-11-27.
|
||||
- Docker Desktop 29.9.2 (arm64, cgroup v2), Compose 5.6.1, ВМ 12 CPU; параллельно на машине работал стенд другого
|
||||
агента (CPU общий).
|
||||
- Спеки: `container-security` (все требования), `container-image` («Работа с корнем только на чтение»),
|
||||
`transport-security` и `object-storage` (gRPC шлюза S3). Design change `container-hardening`, решения 2–11 и
|
||||
«Уточнения apply».
|
||||
- **Роль оператора OpenBao** (`make bao_unseal` после пересоздания `openbao` рабочего стенда, init и unseal
|
||||
временных стендов) на этом автономном прогоне исполнял агент; материалы оператора — только через `make bao_*` и
|
||||
`bao.py` временных стендов, их файлы не читались. В выводах ниже нет токенов, долей, ключей и значений `.env`.
|
||||
|
||||
## 1. «До»: `make hardening_check REPORT=1` и проверка на стенде `3ef21c2`
|
||||
|
||||
Рабочий стенд на коде до правок compose (`make run_docker` → код 2 «OpenBao is sealed: run make bao_unseal» →
|
||||
`make bao_unseal` → `make run_docker`), 23 контейнера (20 работающих, `migrate`, `postgres-bootstrap`,
|
||||
`s3-bootstrap` — завершены с кодом 0). Сводка `REPORT=1` по контейнерам — `cap_drop` | `no-new-privileges` |
|
||||
корень только на чтение | пользователь контейнера | tmpfs | `pids` | UID процессов | `CapBnd` процессов |
|
||||
`NoNewPrivs`:
|
||||
|
||||
```
|
||||
api-1 | none | no | no | app | none | none | uids 10001 | 00000000a80425fb | 0
|
||||
cleaner-1 | none | no | no | app | none | none | uids 10001 | 00000000a80425fb | 0
|
||||
grafana-1 | none | no | no | 472 | /var/lib/grafana | none | uids 472 | 00000000a80425fb | 0
|
||||
haproxy-1 | none | no | no | haproxy | none | none | uids 99 | 00000000a80425fb | 0,1
|
||||
loki-1 | none | no | no | 10001 | none | none | uids 10001 | 00000000a80425fb | 0
|
||||
openbao-1 | ALL | yes | no | openbao | none | none | uids 100 | 0 | 1
|
||||
otel-collector-1 | none | no | no | 10001:10001 | none | none | uids 10001 | 00000000a80425fb | 0
|
||||
postgres-1 | none | no | no | root (image user root) | none | none | uids 999 | 00000000a80425fb | 0
|
||||
prometheus-1 | none | no | no | nobody | none | none | uids 65534 | 00000000a80425fb | 0
|
||||
rabbitmq-1 | none | no | no | root (image user root) | /run/rabbitmq | none | uids 999 | 00000000a80425fb | 0
|
||||
relay-1 | none | no | no | app | none | none | uids 10001 | 00000000a80425fb | 0
|
||||
s3-1 | none | no | no | root (image user root) | none | none | uids 1000 | 00000000a80425fb | 0
|
||||
s3-bootstrap-1 | none | no | no | seaweed | /data /tmp | none | (завершён)
|
||||
valkey-1 | none | no | no | root (image user root) | /run/valkey | none | uids 999 | 00000000a80425fb | 0
|
||||
worker-1 | none | no | no | app | none | none | uids 10001 | 00000000a80425fb | 0
|
||||
(api-2, loki-gateway, otel-gateway, prometheus-gateway, tempo-gateway, tempo — как соседи своего образа)
|
||||
create /.hardening-probe EACCES (api-1, api-2, cleaner, relay, worker)
|
||||
create /var/tmp/.hardening-probe written (те же пять)
|
||||
one-off worker threads until refusal 4096 (cap reached)
|
||||
```
|
||||
|
||||
`make hardening_check` (без отчёта) — код 1, `FAIL: 147 check(s) failed`, по видам: `read-only root` 23, `pids
|
||||
limit` 23, `no-new-privileges` 22, `cap_drop` 22, `process NoNewPrivs` 19, `process CapBnd` 19, `create
|
||||
/var/tmp` 5 и `create /` 5, tmpfs без `size=` 4 (`/var/lib/grafana`, `/run/rabbitmq`, `/run/valkey`, `/data`
|
||||
и `/tmp` у `s3-bootstrap`), пользователь контейнера root 4 (`postgres`, `valkey`, `rabbitmq`, `s3` — от него
|
||||
шли healthcheck и `exec`, сами серверы уже понижены entrypoint), поток worker без предела 1. Команда видит то,
|
||||
что чинит change; gRPC шлюза S3 открытым текстом ловит `make s3_check` (раздел 5).
|
||||
|
||||
Стенд остановлен (`make stop`, контейнеры не удалены) — `make hardening_check` → `hardening-check: no running
|
||||
containers of project mtusi-lab7`, код 2.
|
||||
|
||||
## 2. Пики процессов и пределы (задача 2.2)
|
||||
|
||||
`docker stats --no-stream` (столбец PIDS — процессы и потоки cgroup) по всем контейнерам стенда «до», 120
|
||||
выборок под `make test`, `make load`, `make student_test` и 2 × 5 параллельных `driver.py upload`:
|
||||
|
||||
| Сервис | Пик PIDS | Предел `pids` | Правило |
|
||||
|---|---|---|---|
|
||||
| `api` (на реплику) | 14 | 64 | 4 × 14 = 56 → 64 |
|
||||
| `worker` | 8 | 64 | минимум |
|
||||
| `relay` / `cleaner` | 6 / 3 | 64 | минимум |
|
||||
| `migrate`, `postgres-bootstrap` | одноразовые | 64 | минимум |
|
||||
| `s3-bootstrap` | одноразовый | 128 | `weed shell` — Go |
|
||||
| `postgres` | 29 | 512 | нижняя граница: клиенты `fill-connections` стенда отказов |
|
||||
| `valkey` | 7 | 64 | минимум |
|
||||
| `rabbitmq` | 87 | 512 | 4 × 87 = 348 → 512 |
|
||||
| `s3` / `openbao` | 17 / 15 | 128 | Go: не меньше 128 |
|
||||
| `haproxy`, четыре шлюза | 5 | 64 | минимум |
|
||||
| `otel-collector` / `prometheus` / `loki` / `tempo` | 8 / 7 / 8 / 8 | 128 | Go |
|
||||
| `grafana` | 38 | 256 | 4 × 38 = 152 → 256 |
|
||||
|
||||
Суммы CPU и памяти прежние (лимиты не менялись).
|
||||
|
||||
## 3. Переход рабочего стенда (задача 7.1)
|
||||
|
||||
```
|
||||
$ make run_docker → Container mtusi-lab7-openbao-1 Recreate … OpenBao is sealed: run make bao_unseal (код 2)
|
||||
$ make bao_unseal → unsealed OpenBao with 3 shares
|
||||
$ make run_docker → код 0
|
||||
```
|
||||
|
||||
Все сервисы `healthy` / `running`, одноразовые — `Exited (0)`; bootstrap S3 — `checks passed (api key put/get;
|
||||
cleaner key get/delete and list …; worker key put/get; … anonymous get and list denied)`. Журнал `s3` — 3 строки
|
||||
`W … propagating_store.go:124 failed to propagate change to s3 server 127.0.0.1:18333: … error reading server
|
||||
preface: EOF` (толчок filer без TLS отвергнут шлюзом mTLS, ожидаемо — `docker.md`). Данные прежнего стенда на
|
||||
месте (`old_data.py` во временном каталоге, только статусы и SHA-256):
|
||||
|
||||
```
|
||||
GET /users/me with the token issued before the migration: 200
|
||||
GET /chats: 200 chats: 1
|
||||
attachment a4b6d8ca: meta 200 ready, content 200 sha256 99ea7533c441f79c
|
||||
attachment 0f65e59c: meta 200 ready, content 200 sha256 99ea7533c441f79c (= tests/fixtures/sample.png)
|
||||
```
|
||||
|
||||
`make hardening_check` — код 0, `PASS: 631 checks`; поток worker — `63 (RuntimeError: can't start new thread)`
|
||||
при пределе 64, `/health/ready via LB meanwhile 200`.
|
||||
|
||||
## 4. «После»: `make hardening_check REPORT=1`
|
||||
|
||||
Та же сводка (после `make rolling_update` реплики — `api-3`, `api-4`):
|
||||
|
||||
```
|
||||
api-3 | ALL | yes | yes | app | /tmp(size=16m,mode=1777) | 64 | uids 10001 | 0 | 1
|
||||
cleaner-1 | ALL | yes | yes | app | /tmp(size=16m,mode=1777) | 64 | uids 10001 | 0 | 1
|
||||
grafana-1 | ALL | yes | yes | 472 | /tmp(size=16m,mode=1777) /var/lib/grafana(size=128m,uid=472,gid=0,mode=0770) | 256 | uids 472 | 0 | 1
|
||||
haproxy-1 | ALL | yes | yes | haproxy | none | 64 | uids 99 | 0 | 1
|
||||
loki-1 | ALL | yes | yes | 10001 | none | 128 | uids 10001 | 0 | 1
|
||||
openbao-1 | ALL | yes | yes | openbao | none | 128 | uids 100 | 0 | 1
|
||||
otel-collector-1 | ALL | yes | yes | 10001:10001 | none | 128 | uids 10001 | 0 | 1
|
||||
postgres-1 | ALL | yes | yes | 999:999 | /tmp(size=16m,mode=1777) /var/run/postgresql(size=1m,uid=999,gid=999,mode=3775) | 512 | uids 999 | 0 | 1
|
||||
prometheus-1 | ALL | yes | yes | nobody | none | 128 | uids 65534 | 0 | 1
|
||||
rabbitmq-1 | ALL | yes | yes | 999:999 | /run/rabbitmq(size=1m,uid=999,gid=999,mode=0700) | 512 | uids 999 | 0 | 1
|
||||
relay-1 | ALL | yes | yes | app | /tmp(size=16m,mode=1777) | 64 | uids 10001 | 0 | 1
|
||||
s3-1 | ALL | yes | yes | 1000:1000 | /tmp(size=16m,mode=1777) | 128 | uids 1000 | 0 | 1
|
||||
s3-bootstrap-1 | ALL | yes | yes | seaweed | /data(size=16m,mode=1777) /tmp(size=16m,mode=1777) | 128 | (завершён)
|
||||
valkey-1 | ALL | yes | yes | 999:999 | /run/valkey(size=1m,uid=999,gid=999,mode=0700) | 64 | uids 999 | 0 | 1
|
||||
worker-1 | ALL | yes | yes | app | /tmp(size=16m,mode=1777) | 64 | uids 10001 | 0 | 1
|
||||
(api-4, migrate, postgres-bootstrap, четыре шлюза, tempo — как соседи своего образа; Seccomp 2 у всех)
|
||||
create /.hardening-probe, create /var/tmp/.hardening-probe EROFS (api-3, api-4, cleaner, relay, worker)
|
||||
one-off worker threads until refusal 63 (RuntimeError: can't start new thread)
|
||||
one-off worker /health/ready via LB meanwhile 200
|
||||
```
|
||||
|
||||
Слушатели вне loopback = таблица решения 6 (`api` 8080; `haproxy` 8443 8404; `postgres` 5432; `valkey` 6379; `s3`
|
||||
8333 18333; `rabbitmq` 5671; `openbao` 8200; `otel-gateway` 4318 8888 8889; шлюзы хранилищ 3100 / 3200 4318 / 9090;
|
||||
`grafana` 3000), опубликованные порты — только `127.0.0.1` и только список, монтирования — volumes модели, tmpfs и
|
||||
bind только на чтение, «matches compose model» — `yes` у всех.
|
||||
|
||||
## 5. gRPC шлюза S3 — mTLS (задачи 4.1–4.3)
|
||||
|
||||
`make s3_check`, строки gRPC (stdlib `ssl` на образе API из сети `mtusi-lab7_default`, разовый клиентский leaf
|
||||
`s3-grpc-probe` CA стенда и leaf постороннего CA во временном каталоге, удалены):
|
||||
|
||||
```
|
||||
до (3ef21c2, gRPC открытым текстом):
|
||||
network gRPC of gateway without TLS no HTTP/2 answer HTTP/2 answer FAIL
|
||||
network gRPC of gateway TLS without client certificate refused refused ok
|
||||
network gRPC of gateway TLS with other CA client certificate refused refused ok
|
||||
network gRPC of gateway TLS with stand CA client certificate HTTP/2 answer refused FAIL
|
||||
FAIL: 2 check(s) failed
|
||||
|
||||
после:
|
||||
gRPC of gateway without TLS: no HTTP/2 answer (closed)
|
||||
gRPC of gateway TLS without client certificate: refused (TLSV13_ALERT_CERTIFICATE_REQUIRED)
|
||||
gRPC of gateway TLS with other CA client certificate: refused (SSLV3_ALERT_BAD_CERTIFICATE)
|
||||
gRPC of gateway TLS with stand CA client certificate: HTTP/2 answer (TLSv1.3)
|
||||
server listening outside loopback 8333 18333 8333 18333 ok
|
||||
PASS: 94 checks, bucket messenger is private
|
||||
```
|
||||
|
||||
`make storage_tls_check` — `s3: port 18333 — gRPC of the gateway, mTLS (checked by make s3_check)`, PASS.
|
||||
|
||||
**Токен поверх mTLS** (проба, как `evidence/s3/grpc-admin.md` лабы 4): одноразовый контейнер
|
||||
`python:3.12.14-slim-trixie@sha256:f77ac9e4…` в сети стенда (`--cap-drop ALL`, `no-new-privileges`), `grpcio`
|
||||
1.84.0, `protobuf` 7.35.1, `boto3` 1.43.115; `PutIdentityRequest` (учётная запись `evil`, `actions: ["Admin"]`,
|
||||
случайные ключ и секрет) собран вручную по `iam.proto` SeaweedFS 4.48; разовый клиентский leaf CA стенда
|
||||
(1 день), материал удалён после пробы:
|
||||
|
||||
```
|
||||
grpcio 1.84.0, boto3 1.43.115
|
||||
PutIdentity, stand CA client certificate, no token: UNAUTHENTICATED missing authorization metadata
|
||||
PutIdentity, no client certificate: UNAVAILABLE failed to connect to all addresses; … Unwrap failed (TSI_DATA_CORRUPTED)
|
||||
evil S3 access: InvalidAccessKeyId
|
||||
```
|
||||
|
||||
С сертификатом CA стенда рукопожатие проходит, но вызов без токена отклонён, учётная запись не создана; без
|
||||
сертификата клиента до вызова не доходит (сервер шлёт `CERTIFICATE_REQUIRED`).
|
||||
|
||||
## 6. Проверки через LB и проверки безопасности (задача 7.2)
|
||||
|
||||
```
|
||||
test: exit 0 PASS: lab7 public API scenario …
|
||||
test-security: exit 0 PASS: trusted HTTPS works; untrusted CA rejected …
|
||||
student_test: exit 2 1 failed, 234 passed, 164 deselected — test_exclusion_evidence_exists (известное: 25 файлов evidence исключений — последний шаг лабы)
|
||||
test-persistence: exit 0 PASS: persistence preserved confirmed data and existing session
|
||||
test-failover (stop): exit 0 PASS: failover preserved confirmed data and existing session
|
||||
test-failover (kill): exit 0 PASS
|
||||
rolling_update: exit 0 done: 2 replicas … UP in 17s
|
||||
mtls_check: exit 0 PASS: replicas accept only the haproxy identity of the stand CA …
|
||||
storage_tls_check: exit 0 PASS
|
||||
storage_roles_check: exit 0 PASS
|
||||
broker_mtls_check: exit 0 PASS
|
||||
telemetry_tls_check: exit 0 PASS (data source prometheus / loki / tempo check — OK)
|
||||
bao_check: exit 0 PASS
|
||||
s3_check: exit 0 PASS: 94 checks
|
||||
openbao-outage: exit 0 PASS: running stand served without OpenBao; new processes waited and started after make bao_unseal
|
||||
hardening_check: exit 0 PASS: 631 checks
|
||||
```
|
||||
|
||||
Журналы всех 22 сервисов после этих прогонов: `Read-only file system`, `Operation not permitted`, `EACCES`, `can't
|
||||
start new thread`, `failed to create new OS thread` — 0; Grafana `plugin init error` — 0. Строки `permission denied`
|
||||
в журналах PostgreSQL и OpenBao — отказы, которые сами вызывают `storage_roles_check` (42501) и `bao_check` (403).
|
||||
|
||||
## 7. Контроли `make hardening_check` (задача 7.3)
|
||||
|
||||
Разовые контейнеры сервиса `relay` (`--entrypoint python`, без зависимостей): `--cap-add NET_RAW`;
|
||||
`-p 0.0.0.0:18997:8080` с `python -m http.server 8080 --bind 0.0.0.0`; временный override с `read_only: false`:
|
||||
|
||||
```
|
||||
mtusi-probe-harden-capadd cap_add none NET_RAW FAIL
|
||||
mtusi-probe-harden-capadd matches compose model yes cap_add FAIL
|
||||
mtusi-probe-harden-capadd process CapBnd 0 0000000000002000 FAIL
|
||||
mtusi-probe-harden-port published ports none 0.0.0.0->8080 FAIL
|
||||
mtusi-probe-harden-port listeners outside loopback none 8080 FAIL
|
||||
mtusi-probe-harden-rw read-only root yes no FAIL
|
||||
mtusi-probe-harden-rw matches compose model yes read_only FAIL
|
||||
mtusi-probe-harden-rw create /.hardening-probe EROFS EACCES FAIL
|
||||
mtusi-probe-harden-rw create /var/tmp/.hardening-probe EROFS written FAIL
|
||||
FAIL: 9 check(s) failed (код 1)
|
||||
```
|
||||
|
||||
После `docker rm -f` трёх контейнеров — `PASS: 631 checks`, код 0; контейнеров `mtusi-probe-harden-*` — 0.
|
||||
|
||||
**Уборка проб по сигналу**: SIGINT процессу команды через 6 с (пробы процессов и слушателей) и через 17 с (проба
|
||||
потоков worker) — `hardening-check: interrupted (SIGINT)`, `cleanup: probe containers left 0`, код 1; после
|
||||
выхода контейнеров с меткой `mtusi.hardening-check` — 0.
|
||||
|
||||
## 8. Стенд с нуля и `make test_isolated` (задача 7.4)
|
||||
|
||||
`driver.py stand-from-scratch --runs 1` (проект `mtusi-lab7-scratch`, пустые volumes: PostgreSQL, брокер, S3 и
|
||||
OpenBao инициализируют данные от своих пользователей): код 0, `make run_docker` — с первой попытки, все сервисы
|
||||
`running` (одноразовые — `exited:0`), `RestartCount` брокера, OpenBao, шлюзов и телеметрии — 0, `make test` PASS;
|
||||
PKI и материалы OpenBao рабочего стенда не изменились; `PASS: make run_docker on empty volumes passed 1 times at
|
||||
the first attempt`.
|
||||
|
||||
`make test_isolated`: `make test` — PASS; `make student_test EXPECT_REPLICAS=1` — 227 passed, 7 skipped (тесты
|
||||
реплик), 1 failed — тот же `test_exclusion_evidence_exists`; уборка контейнеров, базы, префикса и очереди прошла.
|
||||
|
||||
## 9. Полный `make failure_checks` (задачи 5.1, 7.5)
|
||||
|
||||
Рабочий стенд остановлен (`make stop`); стенд отказов `mtusi-lab7-failures` из того же compose с override (якорь,
|
||||
пользователи хранилищ, tmpfs и `pids` основного файла; `init: true` у PostgreSQL совместим с `user: "999:999"`):
|
||||
|
||||
```
|
||||
========== 1 failed, 163 passed, 235 deselected in 2901.50s (0:48:21) ==========
|
||||
FAILED test_hung_worker_lease_fencing — no worker-second record 'Attachment became ready' … in 30 s
|
||||
[failure_checks] postgres log: 665 lines, crash markers 0; "too many clients" 23, "administrator command" 195, "no encryption" 0, "permission denied" 0
|
||||
[failure_checks] secrets log: 8 containers, roles ttl 20 s / max 60 s; relogins max_ttl 341 expired 23 renew_refused 0;
|
||||
unavailable 23 / available again 23; refused access, renewal failures, missing fields 0; … error responses none; s.-tokens in plaintext 0
|
||||
```
|
||||
|
||||
164 проверки — прежнее число; единственное падение — известный ложный FAIL `test_hung_worker_lease_fencing`
|
||||
(`KNOWN_ISSUES.md`, срок соединения S3 по TLS). `fill-connections` (до `max_connections` клиентов `psql` в контейнере
|
||||
PostgreSQL от 999 с файлом PID в tmpfs `/tmp`) — «too many clients» 23, аварийных перезапусков нет. В выводе прогона
|
||||
`Read-only file system`, `Operation not permitted`, `can't start new thread` — 0.
|
||||
|
||||
## 10. Быстрые профили `bench/` (задачи 5.2, 7.6)
|
||||
|
||||
Рабочий стенд остановлен; стенд `mtusi-bench` из того же compose с `bench.compose.yml` (ограничения не сбрасываются:
|
||||
быстрый тест; `pids` PostgreSQL 512 ≥ `BENCH_DB_MAX_CONNECTIONS` 100), OpenBao и PKI прогона; метки `quick-*` в git
|
||||
не идут. Хост выгружал память (предупреждения `host swapped out … pages: rerun`) — результаты не для отчёта, только
|
||||
работоспособность профилей:
|
||||
|
||||
```
|
||||
make bench_uploads_quick: exit 0, complete: 6/6 runs
|
||||
unlimited-10MiB-c40-r1: peak 493.7 MiB (sampled), 5xx 800, OOM ← вариант «без лимита», ожидаемо (H1)
|
||||
limited-10MiB-c40-r1: peak 210.0 MiB (reset), 202 218, 429 405, 5xx 0
|
||||
make bench_queue_quick TELEMETRY=on: exit 0, complete: 6/6 runs
|
||||
gate-on-s-c2p2-r1: accepted 82, 429 134 (backlog 134), oom 0; kill-worker-s-c2p2-r1: worker die command 1, flags []
|
||||
make bench_login_quick: exit 0, complete: 4/4 runs
|
||||
before-l40-r1: good 201 0/30, hashes 342; full-l40-r1: flood 429 1200, good 201 30/30, hashes 30
|
||||
```
|
||||
|
||||
Ячейки ведут себя как в прежних прогонах профилей; ошибок записи и отказов создания потоков у сервисов стенда нет
|
||||
(сводки `oom 0`, `worker die other 0`, кроме намеренного OOM варианта «без лимита» загрузок).
|
||||
|
||||
## 11. CI: override, быстрые тесты, эмуляция job (задачи 5.3, 6.1, 7.7)
|
||||
|
||||
- `service-tests/unit/test_compose_hardening.py` — 9 passed (основной файл, override стенда отказов, `bench/` и CI,
|
||||
четыре контроля на изменённой копии: сервис без якоря, без `pids`, строка исключений без причины, `read_only:
|
||||
false` в override стенда отказов). На `docker-compose.yml` `HEAD` (до правок) — 92 расхождения (`no top-level
|
||||
x-hardening-exceptions`, `postgres: cap_drop is not [ALL]`, `postgres: no no-new-privileges`, `postgres: root is
|
||||
writable without exception`, …). `test_ci_override.py` — 5 passed (новый `configs` `s3_security` вместо bind
|
||||
`security.toml`).
|
||||
- Эмуляция job (скрипт во временном каталоге): копия файлов будущего clone (`git ls-files -co --exclude-standard`),
|
||||
проект `mtusi-lab7-safronov-ci-local`, `COMPOSE_FILE=docker-compose.yml:.github/ci/compose.yml`, PKI прогона
|
||||
(`PKI_OPERATOR_DIR` во временном каталоге), `. .github/ci/stand-env.sh`; оператор OpenBao — одноразовый
|
||||
контейнер образа API в сети стенда по `https://openbao:8200` (как job после `docker network connect`), модель
|
||||
compose — файл 0600, удалён сразу после `ready`; клиенты job — одноразовые контейнеры в сети стенда. Рабочий
|
||||
стенд остановлен. Две первые попытки упали на самом скрипте эмуляции (каталог материалов `/op` — `bao.py`
|
||||
меняет права родителя `/`; пересозданный тот же путь Docker Desktop монтировал как несуществующий), третья:
|
||||
|
||||
```
|
||||
docker compose config --quiet: ok
|
||||
initialized OpenBao: 5 unseal shares, threshold 3; root token and shares — files 0600 in /ops/openbao
|
||||
configure: 12 changes; seed: 9 of 9 paths written
|
||||
api ×2, cleaner, haproxy, openbao, postgres, rabbitmq, s3, valkey, шлюзы, телеметрия — Up (healthy);
|
||||
migrate, postgres-bootstrap, s3-bootstrap — Exited (0)
|
||||
== ограничения CI (у всех 22): ro=false drop=[ALL] add=[] opt=[no-new-privileges:true], пользователь — как на рабочем
|
||||
стенде (postgres, valkey, rabbitmq 999:999; s3 1000:1000; …), pids и tmpfs — основного файла
|
||||
postgres 999:999 400 /run/secrets/postgres.key; valkey 999:999 400 …/valkey.key; s3 1000:1000 400 …/s3.key;
|
||||
rabbitmq 999:999 400 …/rabbitmq.key; openbao 100:1000 400 …/openbao.key; s3 0:0 444 /etc/seaweedfs/security.toml
|
||||
make check: ok
|
||||
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||
anonymous GET https://s3:8333/ -> 403; …/messenger -> 403; …/messenger?list-type=2 -> 403
|
||||
wait_replicas: LB ready 2 replicas
|
||||
s3-bootstrap: checks passed (…)
|
||||
write errors in stand logs: 0
|
||||
result: PASS
|
||||
left: containers 0, volumes 0, image tag 0, temp dir no
|
||||
```
|
||||
|
||||
Отличие CI от рабочего стенда — только `read_only: false` (строки `x-hardening-exceptions` override с причиной
|
||||
`&ci-delivery`); Compose предупреждает «uid / gid / mode is not supported outside Swarm mode», но `stat`
|
||||
показывает владельца и права из override (прежнее наблюдение `docker.md`).
|
||||
|
||||
## 12. Команды драйвера на своих стендах и в контейнерах стенда (задачи 5.4, 7.8)
|
||||
|
||||
Первый прогон `freeze-lb`, `reconcile-signal` и `reconcile-signal --pace` — код 1 на `docker compose up`:
|
||||
`container mtusi-lab7-freeze-s3-1 exited (255)`. Причина — временный стенд драйвера (`TS_OVERRIDE`): tmpfs данных
|
||||
без `uid=` Docker создаёт `root:root 0755`, а не 1777 (как считал design, решение 8), и шлюз S3 от `1000:1000` в
|
||||
него не пишет:
|
||||
|
||||
```
|
||||
$ docker run --rm --user 1000:1000 --read-only --cap-drop ALL --security-opt no-new-privileges \
|
||||
--tmpfs /tmp:size=16m,mode=1777 --tmpfs /data --entrypoint sh chrislusf/seaweedfs:4.48@… -c 'ls -ld /data; touch /data/x'
|
||||
drwxr-xr-x 2 root root 40 Nov 27 00:49 /data
|
||||
touch: /data/x: Permission denied
|
||||
```
|
||||
|
||||
Правка (design, «Уточнения apply», п. 13): tmpfs данных PostgreSQL, Valkey, S3 и OpenBao временного стенда — с
|
||||
владельцем сервиса и `size=`, bind `security.toml` у `s3` сохраняется. После неё:
|
||||
|
||||
```
|
||||
worker-process: exit 0 PASS: the worker process matches the spec
|
||||
stop-at-start: exit 0 PASS: SIGTERM during start stops the replica at once, exit 0
|
||||
lb-upload-timeouts: exit 0 PASS: the upload path waits 30 s for the replica, other paths 10 s …
|
||||
freeze-lb: exit 0 PASS: frozen PostgreSQL: 503 from the replicas before timeout server of LB, no sessions over the pool
|
||||
reconcile-signal --pace: exit 0 PASS: one-off reconcile stopped by SIGTERM during the rate limit pause: exit 1 within a second
|
||||
reconcile-signal: exit 1 Finished reconcile pass interrupted_by — object_storage вместо stop (известный ложный FAIL
|
||||
KNOWN_ISSUES.md: «driver.py reconcile-signal без --pace — гонка с сроком соединения S3 по TLS»)
|
||||
relay-process: exit 1 только «early stop 0.2 s» / «0.3 s»: код 2 вместо 0 за 6–7 с («Invalid client TLS settings»)
|
||||
hardening_check: exit 0 PASS: 631 checks (после команд — контейнеров проб нет)
|
||||
```
|
||||
|
||||
`relay-process` — прежняя нестабильная проверка драйвера, не регрессия change (`evidence/security/broker-mtls.md`,
|
||||
«relay-process, первый прогон»): разовый `docker run` пробы (без ограничений compose, образ не менялся) при 0,25
|
||||
CPU иногда получает SIGTERM раньше `early_stop.install()` (окно 0, `run-modes.md`), PID 1 сигнал теряет и доходит до
|
||||
проверки настроек; на загруженном хосте (второй стенд на машине) — по одной из трёх задержек во всех трёх
|
||||
прогонах. Голый `docker run … -m src.relay` с `--cpus 0.25` и `docker stop` через 0,2 с без compose — 2 из 6
|
||||
попыток «Invalid client TLS settings», код 2 за 6,7–7,7 с, остальные «Stopped relay before startup» за 0,12–0,15
|
||||
с; записан в `KNOWN_ISSUES.md`.
|
||||
Остальные проверки команды (PID 1, лимиты, неверные `RELAY__*`, остановка простаивающего, при замороженном брокере,
|
||||
рестарт хранилищ, «Stopped relay before startup» увиден) — ok.
|
||||
|
||||
## 13. Сверка покрытия и проверки проекта (задачи 9.2, 9.3)
|
||||
|
||||
- Сверка покрытия на копии репозитория (`git archive HEAD` + рабочее дерево, `openspec archive container-hardening
|
||||
--yes` на копии): `all_scenarios` по `CAPABILITIES` — 423 → 423, добавленных и убранных нет (дельты в
|
||||
`container-security`, `container-image`, `transport-security`, `object-storage` вне `CAPABILITIES`); маркеров и
|
||||
исключений не нужно, копия удалена.
|
||||
- После возврата рабочего стенда (`make run_docker` → код 2 «run make bao_unseal» → `make bao_unseal` → `make
|
||||
run_docker`):
|
||||
|
||||
```
|
||||
make lint All checks passed!
|
||||
make check PASS: offline skeleton structure, local refs and Python syntax
|
||||
openspec validate container-hardening --strict Change 'container-hardening' is valid
|
||||
driver.py: ast.parse(feature_version=(3, 9)) ok
|
||||
make service_test 732 passed
|
||||
make test PASS: lab7 public API scenario
|
||||
make hardening_check PASS: 631 checks
|
||||
```
|
||||
|
||||
- Поиск утечек в изменённых и новых файлах — по шаблонам (токены `s.…` / `hvs.…`, заголовки PEM закрытых ключей,
|
||||
значения секретов `.env` длиной от 8, без печати значений): 26 файлов, совпадение одно — `SECRETS__ADDRESS`
|
||||
(адрес OpenBao, не секрет; было в `contracts/trust-matrix.md` и до change). Материалы оператора рабочего стенда
|
||||
не читались.
|
||||
- В конце рабочий стенд остановлен (`make stop`); контейнеров проб, временных проектов, сетей, volumes и временных
|
||||
каталогов прогона не осталось.
|
||||
Reference in New Issue
Block a user