ЛР 7 — БВТ2301 — Курлова — на 4

Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
This commit is contained in:
alenchha
2026-11-16 10:49:13 +03:00
parent 20afc2c790
commit 861e7722b5
116 changed files with 14522 additions and 63 deletions
+46
View File
@@ -0,0 +1,46 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name bytea NOT NULL
CONSTRAINT users_display_name_size CHECK (octet_length(display_name) BETWEEN 1 AND 400),
password_hash text NOT NULL,
created_at timestamptz NOT NULL
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title bytea NOT NULL
CONSTRAINT chats_title_size CHECK (octet_length(title) BETWEEN 1 AND 400),
created_at timestamptz NOT NULL
);
CREATE INDEX chats_created_idx ON chats (created_at, id);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
text bytea NOT NULL
CONSTRAINT messages_text_size CHECK (octet_length(text) BETWEEN 1 AND 16000),
created_at timestamptz NOT NULL
);
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE INDEX sessions_expires_idx ON sessions (expires_at);
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE idempotency_keys (
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
key text NOT NULL
CONSTRAINT idempotency_key_format CHECK (key ~ '^[A-Za-z0-9._:\-]{1,128}$'),
request_body_hash text NOT NULL,
response_json text NOT NULL,
created_at timestamptz NOT NULL,
PRIMARY KEY (user_id, chat_id, key)
);
CREATE INDEX idempotency_keys_created_idx ON idempotency_keys (created_at);
+28
View File
@@ -0,0 +1,28 @@
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
filename text NOT NULL
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
content_type text NOT NULL
CONSTRAINT attachments_ct CHECK (content_type IN ('image/png', 'image/jpeg')),
size_bytes integer NOT NULL
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 text NOT NULL
CONSTRAINT attachments_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'),
object_key text NOT NULL,
status text NOT NULL DEFAULT 'ready'
CONSTRAINT attachments_status CHECK (status IN ('ready', 'failed')),
error_code text,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE INDEX attachments_chat_idx ON attachments (chat_id);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT,
position smallint NOT NULL,
PRIMARY KEY (message_id, attachment_id)
);
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE messages DROP CONSTRAINT messages_text_size;
ALTER TABLE messages ADD CONSTRAINT messages_text_size CHECK (octet_length(text) BETWEEN 0 AND 16000);
@@ -0,0 +1,5 @@
ALTER TABLE attachments DROP CONSTRAINT attachments_status;
ALTER TABLE attachments ADD CONSTRAINT attachments_status CHECK (status IN ('uploading', 'ready', 'failed'));
ALTER TABLE attachments ALTER COLUMN status DROP DEFAULT;
CREATE UNIQUE INDEX attachments_object_key_idx ON attachments (object_key);
CREATE INDEX attachments_status_created_idx ON attachments (status, created_at);
+75
View File
@@ -0,0 +1,75 @@
-- lab5: upload -> staging -> job/outbox -> broker -> worker -> final prefix + variants.
ALTER TABLE attachments DROP CONSTRAINT attachments_status;
ALTER TABLE attachments ADD CONSTRAINT attachments_status
CHECK (status IN ('uploading', 'queued', 'processing', 'ready', 'failed'));
-- staging_key: private S3 prefix written by the API before 202; object_key: final original written by the worker.
ALTER TABLE attachments ADD COLUMN staging_key text;
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1;
CREATE UNIQUE INDEX attachments_staging_key_idx ON attachments (staging_key) WHERE staging_key IS NOT NULL;
-- Effect key of the pipeline: (attachment_id, pipeline_version, name). A repeated job cannot add a second set.
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
pipeline_version integer NOT NULL,
name text NOT NULL CONSTRAINT variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')),
object_key text NOT NULL UNIQUE,
content_type text NOT NULL CONSTRAINT variants_ct CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')),
size_bytes integer NOT NULL CONSTRAINT variants_size CHECK (size_bytes > 0),
width integer NOT NULL CONSTRAINT variants_width CHECK (width > 0),
height integer NOT NULL CONSTRAINT variants_height CHECK (height > 0),
sha256 text NOT NULL CONSTRAINT variants_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'),
created_at timestamptz NOT NULL,
PRIMARY KEY (attachment_id, pipeline_version, name)
);
-- One logical job per (attachment, pipeline_version); job_id never changes on redelivery or retry.
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
pipeline_version integer NOT NULL,
state text NOT NULL
CONSTRAINT jobs_state CHECK (state IN ('queued', 'processing', 'succeeded', 'failed')),
attempt integer NOT NULL DEFAULT 1 CONSTRAINT jobs_attempt CHECK (attempt >= 1),
max_attempts integer NOT NULL CONSTRAINT jobs_max_attempts CHECK (max_attempts >= 1),
next_attempt_at timestamptz NOT NULL,
lease_owner text,
lease_until timestamptz,
error_code text,
last_error text,
created_at timestamptz NOT NULL,
first_started_at timestamptz,
started_at timestamptz,
finished_at timestamptz,
updated_at timestamptz NOT NULL,
UNIQUE (attachment_id, pipeline_version)
);
CREATE INDEX attachment_jobs_lease_idx ON attachment_jobs (lease_until) WHERE state = 'processing';
CREATE INDEX attachment_jobs_failed_idx ON attachment_jobs (updated_at) WHERE state = 'failed';
CREATE INDEX attachment_jobs_pending_idx ON attachment_jobs (state) WHERE state IN ('queued', 'processing');
-- Transactional outbox: written in the same transaction as the job; the relay publishes with confirms.
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (id) ON DELETE CASCADE,
payload jsonb NOT NULL,
available_at timestamptz NOT NULL,
published_at timestamptz,
publish_attempts integer NOT NULL DEFAULT 0,
last_error text,
created_at timestamptz NOT NULL
);
CREATE INDEX outbox_pending_idx ON outbox (available_at, id) WHERE published_at IS NULL;
CREATE INDEX outbox_published_idx ON outbox (published_at) WHERE published_at IS NOT NULL;
-- Operator-visible history of every state change of a job (including explicit replay).
CREATE TABLE job_audit (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (id) ON DELETE CASCADE,
attachment_id uuid NOT NULL,
action text NOT NULL,
actor text NOT NULL,
attempt integer NOT NULL,
detail jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL
);
CREATE INDEX job_audit_job_idx ON job_audit (job_id, id);
+29
View File
@@ -0,0 +1,29 @@
-- lab7: separate least-privilege DB roles for the services. Passwords are NOT here: scripts/migrate.py sets them
-- from operator bootstrap files and the services read them from OpenBao. The owner role `messenger` is only used
-- by migrations and the operator.
DO $$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app_api') THEN
CREATE ROLE app_api LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT CONNECTION LIMIT 40;
END IF;
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app_worker') THEN
CREATE ROLE app_worker LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT CONNECTION LIMIT 20;
END IF;
END
$$;
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
GRANT CONNECT ON DATABASE messenger TO app_api, app_worker;
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO app_api, app_worker;
-- API: business tables of every endpoint, the outbox relay, the reconciler and scripts/jobs.py.
GRANT SELECT, INSERT, UPDATE, DELETE ON users, chats, chat_members, messages, message_attachments, sessions,
idempotency_keys, attachments, attachment_variants, attachment_jobs, outbox, job_audit TO app_api;
-- Worker: only the processing pipeline. No users/sessions/messages/chats, no DELETE anywhere.
GRANT SELECT, UPDATE ON attachments, attachment_jobs TO app_worker;
GRANT SELECT, INSERT ON attachment_variants, job_audit TO app_worker;
GRANT INSERT ON outbox TO app_worker; -- retry scheduling writes a new outbox row; publishing stays in the API
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO app_api, app_worker;