ЛР 7: Безопасность, mTLS и OpenBao
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username TEXT NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name TEXT NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
CREATE TABLE chats (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
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,
|
||||
member_position SMALLINT NOT NULL CHECK (member_position BETWEEN 0 AND 99),
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
UNIQUE (chat_id, member_position)
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
text TEXT NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000 AND btrim(text) <> ''),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE sessions (
|
||||
token_hash CHAR(64) PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > created_at)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX chats_order_idx ON chats (created_at, id);
|
||||
@@ -0,0 +1,17 @@
|
||||
CREATE TABLE idempotency_records (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
http_method TEXT NOT NULL CHECK (http_method = 'POST'),
|
||||
request_path TEXT NOT NULL,
|
||||
idempotency_key VARCHAR(128) NOT NULL,
|
||||
request_hash CHAR(64) NOT NULL,
|
||||
response_status SMALLINT,
|
||||
response_body JSONB,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (user_id, http_method, request_path, idempotency_key),
|
||||
CHECK ((response_status IS NULL) = (response_body IS NULL)),
|
||||
CHECK (response_status IS NULL OR response_status = 201)
|
||||
);
|
||||
|
||||
CREATE INDEX idempotency_records_expiry_idx
|
||||
ON idempotency_records (expires_at);
|
||||
@@ -0,0 +1,48 @@
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_check;
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_text_check
|
||||
CHECK (char_length(text) BETWEEN 0 AND 4000 AND (text = '' OR btrim(text) <> ''));
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_chat_id_id_unique UNIQUE (chat_id, id);
|
||||
|
||||
CREATE TABLE attachments (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
chat_id UUID NOT NULL,
|
||||
owner_id UUID NOT NULL,
|
||||
filename TEXT NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
content_type TEXT NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes BIGINT NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 CHAR(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL DEFAULT 'ready' CHECK (status = 'ready'),
|
||||
variants JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(variants) = 'array'),
|
||||
error_code TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (chat_id, id),
|
||||
CHECK (error_code IS NULL),
|
||||
FOREIGN KEY (chat_id, owner_id)
|
||||
REFERENCES chat_members(chat_id, user_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_chat_created_idx
|
||||
ON attachments (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
chat_id UUID NOT NULL,
|
||||
message_id UUID NOT NULL,
|
||||
attachment_id UUID NOT NULL,
|
||||
position SMALLINT NOT NULL CHECK (position BETWEEN 0 AND 9),
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
UNIQUE (message_id, position),
|
||||
FOREIGN KEY (chat_id, message_id)
|
||||
REFERENCES messages(chat_id, id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (chat_id, attachment_id)
|
||||
REFERENCES attachments(chat_id, id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_chat_attachment_idx
|
||||
ON message_attachments (chat_id, attachment_id);
|
||||
@@ -0,0 +1,46 @@
|
||||
ALTER TABLE attachments
|
||||
DROP CONSTRAINT attachments_status_check;
|
||||
|
||||
ALTER TABLE attachments
|
||||
ADD CONSTRAINT attachments_status_check
|
||||
CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
|
||||
|
||||
ALTER TABLE attachments
|
||||
DROP CONSTRAINT IF EXISTS attachments_error_code_check;
|
||||
|
||||
ALTER TABLE attachments
|
||||
DROP CONSTRAINT IF EXISTS attachments_check;
|
||||
|
||||
ALTER TABLE attachments
|
||||
ADD CONSTRAINT attachments_error_code_check
|
||||
CHECK (
|
||||
error_code IS NULL
|
||||
OR error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')
|
||||
);
|
||||
|
||||
ALTER TABLE attachments
|
||||
ADD COLUMN staging_key TEXT UNIQUE;
|
||||
|
||||
CREATE TABLE image_jobs (
|
||||
id UUID PRIMARY KEY,
|
||||
attachment_id UUID NOT NULL UNIQUE
|
||||
REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
pipeline_version INTEGER NOT NULL DEFAULT 1 CHECK (pipeline_version >= 1),
|
||||
attempt INTEGER NOT NULL DEFAULT 1 CHECK (attempt BETWEEN 1 AND 20),
|
||||
max_attempts INTEGER NOT NULL DEFAULT 5 CHECK (max_attempts BETWEEN 1 AND 20),
|
||||
published_attempt INTEGER NOT NULL DEFAULT 0
|
||||
CHECK (published_attempt BETWEEN 0 AND attempt),
|
||||
status TEXT NOT NULL DEFAULT 'queued'
|
||||
CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
|
||||
last_error_code TEXT
|
||||
CHECK (
|
||||
last_error_code IS NULL
|
||||
OR last_error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')
|
||||
),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX image_jobs_outbox_idx
|
||||
ON image_jobs (created_at, id)
|
||||
WHERE status = 'queued' AND published_attempt < attempt;
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE login_attempts (
|
||||
ip_hash CHAR(64) NOT NULL CHECK (ip_hash ~ '^[a-f0-9]{64}$'),
|
||||
attempted_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX login_attempts_recent_idx
|
||||
ON login_attempts (ip_hash, attempted_at DESC);
|
||||
@@ -0,0 +1,34 @@
|
||||
# PostgreSQL schema and transactions
|
||||
|
||||
## Tables and invariants
|
||||
|
||||
- `users`: UUID primary key, unique constrained username, display name, Argon2 password hash, server timestamp.
|
||||
- `chats`: UUID primary key and title.
|
||||
- `chat_members`: composite `(chat_id, user_id)` primary key, foreign keys to both parent tables, unique stable member position per chat. The `(user_id, chat_id)` index supports listing a user's chats.
|
||||
- `messages`: UUID primary key and foreign keys to chat and sender. `(chat_id, created_at, id)` supports the API's ascending keyset history query.
|
||||
- `sessions`: SHA-256 digest of a random opaque token as primary key, user foreign key, creation and expiry timestamps. Raw tokens are returned only once and are never stored.
|
||||
- `idempotency_records`: unique per user, method, request path, and key; stores the request hash and committed response for 24 hours. Expired records are removed when a message is submitted.
|
||||
- `attachments`: PostgreSQL metadata for a chat-scoped image; `object_key` points to the object in the private MinIO bucket and is never exposed by the API.
|
||||
- `message_attachments`: ordered message-to-attachment links with composite foreign keys that prevent linking a file from another chat.
|
||||
- `image_jobs`: durable job/outbox state keyed by a stable `job_id`, including pipeline version, managed attempt, retry limit, publication confirmation, and terminal state.
|
||||
- `schema_migrations`: migration filename and application timestamp; created by the migration runner.
|
||||
|
||||
All timestamps are `TIMESTAMPTZ`. PostgreSQL owns generated UUIDs and creation timestamps. Named migrations run once in lexicographic order; an advisory transaction lock serializes startup migration attempts.
|
||||
|
||||
## Transaction boundaries
|
||||
|
||||
Each HTTP request uses one pooled PostgreSQL connection and one transaction. A successful response is written only after that transaction commits. Creating a chat and inserting every member is one transaction, so a failed member insert rolls back both the chat and any earlier member rows. Registration relies on the unique username constraint as the final arbiter of concurrent registrations; the losing request returns `409`.
|
||||
|
||||
Creating a message, linking its attachments, and recording its idempotency result share one transaction. PostgreSQL's composite primary key serializes concurrent requests across API replicas. Matching bodies replay the original status and message; a different body returns `409`. Authentication, chat membership, and attachment scope are checked before replay. Upload writes bytes to S3 first, then inserts metadata in PostgreSQL; a failed DB transaction triggers a best-effort object delete compensation.
|
||||
|
||||
The original file is authoritative in MinIO; PostgreSQL stores its chat/owner ACL, final object key, durable staging key, checksum, type, size, state, and generated variant metadata. Upload first writes the validated original under `staging/<attachment-id>/original`; only after that succeeds does PostgreSQL commit the attachment and job. After commit, the API publishes the job to RabbitMQ and waits for publisher confirmation before returning `202`. An API outbox loop republishes queued attempts not yet confirmed by the broker.
|
||||
|
||||
The worker reads trusted object keys from PostgreSQL, writes deterministic final keys, and only marks the attachment ready after both original and thumbnail objects are stored and metadata commits. It acknowledges the broker message after that commit. The job row and RabbitMQ message are both durable; duplicate deliveries are serialized by a PostgreSQL advisory lock and use deterministic S3 keys. Staging is removed only after the ready transaction commits. The API and worker currently use the local MinIO root credentials, acceptable only for this grade-3 isolated lab topology; use a scoped service account for a stronger deployment.
|
||||
|
||||
Migration `012_attachment_jobs.sql` expands the attachment status constraint to `queued`, `processing`, `ready`, and `failed`, adds the staging key and creates the job/outbox table. Existing Lab4-ready attachments remain valid; their staging key and job row may remain null/absent.
|
||||
|
||||
Message history uses `WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4`, matching `messages_chat_history_idx`. Cursors include their resource scope and the last row's timestamp and UUID.
|
||||
|
||||
## Durability
|
||||
|
||||
Compose mounts PostgreSQL, MinIO, and RabbitMQ data directories on named `postgres_data`, `minio_data`, and `rabbitmq_data` volumes. The persistence hook restarts the API, worker, database, MinIO, and broker without removing those volumes. Backups and destructive volume resets are deliberately separate operator actions.
|
||||
Reference in New Issue
Block a user