lab7
Skeleton contracts / contracts (pull_request) Blocked by required conditions

This commit is contained in:
2026-12-06 15:56:06 +03:00
parent 20afc2c790
commit 550c2e76ee
47 changed files with 3644 additions and 46 deletions
+58 -4
View File
@@ -1,7 +1,61 @@
# Инфраструктура студента
# Compose + Nginx + MinIO
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
The runnable topology is in the root `compose.yaml`. The example Compose file
and `contracts/infrastructure.json` are teaching worksheets, not deployments.
The supported local entry point is Nginx; API, PostgreSQL, Redis and MinIO ports
are not published to the host.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
| Role | Service / image | Persistence and readiness |
| --- | --- | --- |
| API | `api`, built from `Dockerfile` / Python 3.12.11 | Two stateless replicas; `/health/ready`; no host port |
| Load balancer | `nginx:1.27.5-alpine` | Host port `${APP_PORT:-8080}`; Docker DNS refresh 5 s; passive fail exclusion |
| Database | `postgres:16.8-alpine` | `postgres_data` named volume; `pg_isready` |
| Sessions | `redis:7.4.2-alpine` | `redis_data` named volume; AOF `everysec`; Redis `PING` |
| Object storage | MinIO `RELEASE.2025-09-07T16-13-09Z`, pinned by image digest in Compose | `minio_data` named volume; MinIO readiness endpoint; S3 port 9000 and console 9001 are private |
| Migration job | Same API image | Runs ordered SQL migrations once before API replicas |
| Bucket bootstrap | Same pinned MinIO image, using its `mc` client | Idempotently creates the private bucket, versioned policy, and restricted API user; replaces the prior policy without deleting volumes |
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
PostgreSQL and S3 hold different parts of an attachment: PostgreSQL is the source
of truth for metadata and access control; the private S3 bucket stores original
bytes under a random server-generated key. The bucket name is fixed as
`messenger-attachments`. No endpoint returns object keys or S3 credentials.
The MinIO root credentials are mounted only into MinIO and its one-shot bootstrap
job. The API receives a separate access key restricted to `GetBucketLocation`,
`ListBucket` with the `objects/` prefix, and Get/Put/Delete on `objects/*`.
The bootstrap grants no anonymous policy. Verify
that from inside the Compose network with
`py -3 -X utf8 student-tests/check_private_bucket.py`; it expects an unsigned
bucket-list request to receive HTTP 403 and confirms MinIO has no host port
binding. The administrative console is not exposed.
Create local ignored secrets using `scripts/init-local-secrets.ps1`; never copy
secrets from another lab. Do not rotate credentials while retaining the
corresponding database or MinIO volumes. `scripts/restart.bat` / `.sh` restarts
the API, database, Redis, MinIO and Nginx without deleting volumes.
`scripts/stop-one.bat` / `.sh` stops only the API container whose hostname equals
`TARGET_INSTANCE_ID` and leaves it stopped for the failover check.
Attachment writes reserve PostgreSQL metadata in `processing` state before
writing S3. On success, the row becomes `ready` and the API returns 201. Errors
attempt to delete the object and mark the reservation `failed`; if compensation
cannot reach either store, the processing row remains visible to reconciliation.
Run `scripts/reconcile_attachments.py` in dry-run mode first. It only acts on
records/objects older than a 15-minute minimum grace period, marks stale uploads
failed, deletes old unreferenced objects, and reports missing objects for ready
metadata. `--apply` is required for changes.
MinIO, PostgreSQL, Redis, Nginx, and the Docker host are single-instance
dependencies. This setup survives an API-replica failure and restarts with
volumes, not loss of the Docker host or an individual state-store volume.
## Lab7 TLS
- Public ingress uses TLS on port 8080 and verifies a local CA.
- LB uses mandatory mTLS to API replicas on port 8443.
- PostgreSQL accepts TLS with a server certificate and API/worker use
`sslmode=verify-full`.
- Redis exposes TLS on 6380 for sessions and broker streams.
- MinIO exposes HTTPS on 9000 and the API/worker verify its CA.
- OpenBao exposes HTTPS on 8200 with persistent file storage and AppRole.
- OTLP, Loki, Tempo and Prometheus telemetry links use TLS in the backend network.
+30
View File
@@ -0,0 +1,30 @@
auth_enabled: false
server:
http_listen_port: 3100
http_tls_config:
cert_file: /certs/loki.crt
key_file: /certs/loki.key
common:
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
set -eu
root_user=$(cat /run/secrets/minio_root_user)
root_password=$(cat /run/secrets/minio_root_password)
service_user=$(cat /run/secrets/s3_access_key_id)
service_password=$(cat /run/secrets/s3_secret_access_key)
mkdir -p /root/.mc/certs/CAs
cp /certs/ca.crt /root/.mc/certs/CAs/ca.crt
cat /certs/ca.crt >> /etc/ssl/certs/ca-certificates.crt
until mc alias set local https://minio:9000 "$root_user" "$root_password" >/dev/null 2>&1 \
&& mc ready local >/dev/null 2>&1; do
sleep 2
done
bucket=${S3_BUCKET:-messenger-attachments}
if [ "$bucket" != 'messenger-attachments' ]; then
printf '%s\n' 'S3_BUCKET must be messenger-attachments' >&2
exit 2
fi
policy=messenger-attachments-v2
legacy_policy=messenger-attachments
mc mb --ignore-existing "local/$bucket"
if mc admin policy info local "$policy" >/dev/null 2>&1; then
mc admin policy detach local "$policy" --user "$service_user" >/dev/null 2>&1 || true
mc admin policy remove local "$policy" >/dev/null
fi
mc admin policy create local "$policy" /infra/s3-policy.json
if ! mc admin user info local "$service_user" >/dev/null 2>&1; then
mc admin user add local "$service_user" "$service_password" >/dev/null
fi
mc admin policy attach local "$policy" --user "$service_user" >/dev/null
if mc admin policy info local "$legacy_policy" >/dev/null 2>&1; then
mc admin policy detach local "$legacy_policy" --user "$service_user" >/dev/null
mc admin policy remove local "$legacy_policy" >/dev/null
fi
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
export MINIO_ROOT_USER="$(cat /run/secrets/minio_root_user)"
export MINIO_ROOT_PASSWORD="$(cat /run/secrets/minio_root_password)"
exec minio server /data --address :9000 --console-address :9001 --certs-dir /certs/minio-certs
+37
View File
@@ -0,0 +1,37 @@
resolver 127.0.0.11 valid=5s ipv6=off;
upstream messenger_api {
zone messenger_api 64k;
server api:8443 resolve max_fails=1 fail_timeout=2s;
}
server {
listen 8443 ssl;
server_name _;
ssl_certificate /certs/public.crt;
ssl_certificate_key /certs/public.key;
ssl_trusted_certificate /certs/ca.crt;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_tickets off;
client_max_body_size 11m;
client_body_timeout 20s;
location / {
proxy_pass https://messenger_api;
proxy_ssl_trusted_certificate /certs/ca.crt;
proxy_ssl_verify on;
proxy_ssl_verify_depth 2;
proxy_ssl_name api.lab.local;
proxy_ssl_certificate /certs/lb.crt;
proxy_ssl_certificate_key /certs/lb.key;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_request_buffering off;
proxy_connect_timeout 2s;
proxy_send_timeout 20s;
proxy_read_timeout 20s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
+7
View File
@@ -0,0 +1,7 @@
path "secret/data/lab7/service" {
capabilities = ["read"]
}
path "secret/metadata/lab7/service" {
capabilities = ["read"]
}
+14
View File
@@ -0,0 +1,14 @@
ui = false
disable_mlock = true
storage "file" {
path = "/openbao/file"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/certs/openbao.crt"
tls_key_file = "/certs/openbao.key"
tls_client_ca_file = "/certs/ca.crt"
tls_require_and_verify_client_cert = false
}
+53
View File
@@ -0,0 +1,53 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /certs/otel-collector.crt
key_file: /certs/otel-collector.key
grpc:
endpoint: 0.0.0.0:4317
tls:
cert_file: /certs/otel-collector.crt
key_file: /certs/otel-collector.key
processors:
memory_limiter:
check_interval: 1s
limit_mib: 256
spike_limit_mib: 64
batch:
timeout: 5s
send_batch_size: 512
exporters:
prometheus:
endpoint: 0.0.0.0:8889
tls:
cert_file: /certs/otel-collector.crt
key_file: /certs/otel-collector.key
otlphttp/loki:
endpoint: https://loki:3100/otlp
tls:
ca_file: /certs/ca.crt
server_name_override: loki.lab.local
otlp/tempo:
endpoint: tempo:4317
tls:
ca_file: /certs/ca.crt
service:
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo]
+12
View File
@@ -0,0 +1,12 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: otel-collector
scheme: https
tls_config:
ca_file: /certs/ca.crt
server_name: otel-collector.lab.local
static_configs:
- targets: ['otel-collector:8889']
+28
View File
@@ -0,0 +1,28 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::messenger-attachments"]
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::messenger-attachments"],
"Condition": {
"StringLike": {
"s3:prefix": ["objects/", "objects/*", "staging/", "staging/*"]
}
}
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": [
"arn:aws:s3:::messenger-attachments/objects/*",
"arn:aws:s3:::messenger-attachments/staging/*"
]
}
]
}
+23
View File
@@ -0,0 +1,23 @@
server:
http_listen_port: 3200
http_tls_config:
cert_file: /certs/tempo.crt
key_file: /certs/tempo.key
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
tls:
cert_file: /certs/tempo.crt
key_file: /certs/tempo.key
http:
endpoint: 0.0.0.0:4318
storage:
trace:
backend: local
local:
path: /var/tempo/traces