Implement lab2 PostgreSQL messenger, sessions, SQL research and defense guide

This commit is contained in:
2026-10-02 12:49:09 +03:00
parent 65003b6119
commit 6fe56ec642
43 changed files with 12869 additions and 33 deletions
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Generate local-only credentials. Existing credentials are never overwritten."""
import base64
import os
from pathlib import Path
import secrets
root=Path(__file__).resolve().parents[1]
directory=root/'secrets'
directory.mkdir(mode=0o700,exist_ok=True)
password_file=directory/'postgres_password'
if not password_file.exists():
password=secrets.token_hex(24)
password_file.write_text(password+'\n')
else:
password=password_file.read_text().strip()
cache_file=directory/'valkey_config'
if not cache_file.exists():
cache_password=secrets.token_hex(24)
cache_file.write_text('bind 0.0.0.0\nprotected-mode yes\nport 6379\ndir /data\nsave ""\nappendonly no\nrequirepass '+cache_password+'\n')
else:
cache_password=next(line.split()[1] for line in cache_file.read_text().splitlines() if line.startswith('requirepass '))
values={'database_url':f'postgres://messenger:{password}@postgres:5432/messenger?sslmode=disable',
'cache_url':f'redis://:{cache_password}@valkey:6379/0',
'cursor_key':base64.urlsafe_b64encode(secrets.token_bytes(32)).decode().rstrip('=')}
for name,value in values.items():
p=directory/name
if not p.exists():p.write_text(value+'\n')
# Compose mounts individual files. Readable by container UID 10001; host
# directory 0700 prevents traversal by other local users.
for p in directory.iterdir():os.chmod(p,0o444)
if not (root/'.env').exists():(root/'.env').write_text('APP_PORT=8082\nSESSION_TTL_SECONDS=3600\n')
print('Local secrets ready (values hidden); .env and secrets/ are ignored by Git.')
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""Generate a repeatable Postman scenario with synthetic credentials only."""
import json
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
items=[]
def req(name,method,path,status=200,actor=None,body=None,save=None,pre=None,extra=None,basic=None):
r={'method':method,'header':[],'url':'{{base_url}}'+path}
if actor:r['auth']={'type':'bearer','bearer':[{'key':'token','value':'{{'+actor+'_token}}','type':'string'}]}
if basic:r['auth']={'type':'basic','basic':[{'key':'username','value':basic+'_{{run_id}}','type':'string'},{'key':'password','value':'{{demo_password}}','type':'string'}]}
if body is not None:
r['header'].append({'key':'Content-Type','value':'application/json'})
r['body']={'mode':'raw','raw':json.dumps(body,ensure_ascii=False,indent=2),'options':{'raw':{'language':'json'}}}
tests=[f'pm.test("HTTP {status}", () => pm.response.to.have.status({status}));']
if save:tests.append(f'if (pm.response.code === {status}) pm.collectionVariables.set("{save}", pm.response.json().id);')
if extra:tests+=extra
events=[{'listen':'test','script':{'type':'text/javascript','exec':tests}}]
if pre:events.insert(0,{'listen':'prerequest','script':{'type':'text/javascript','exec':pre}})
items.append({'name':name,'request':r,'event':events,'response':[]})
req('01 — Процесс жив','GET','/health/live')
req('02 — БД готова','GET','/health/ready')
for index,who,title in [(3,'alice','Глеб'),(4,'bob','Боб'),(5,'eve','Посторонний')]:
req(f'{index:02} — Создать {title}','POST','/api/v1/users',201,body={'username':who+'_{{run_id}}','display_name':title,'password':'{{demo_password}}'},save=who+'_id',pre=['pm.collectionVariables.set("run_id", pm.variables.replaceIn("{{$guid}}").replace(/-/g, "").slice(0,16));','["alice_token","bob_token","eve_token","chat_id","next_cursor"].forEach(k => pm.collectionVariables.set(k, ""));'] if who=='alice' else None)
for index,who in [(6,'alice'),(7,'bob'),(8,'eve')]:
req(f'{index:02} — Вход {who} через Basic','POST','/api/v1/auth/sessions',201,basic=who,extra=['if (pm.response.code === 201) {',f' pm.collectionVariables.set("{who}_token", pm.response.json().token);',f' pm.collectionVariables.set("{who}_expires_at", pm.response.json().expires_at);','}'])
req('09 — Кто я через Bearer','GET','/api/v1/users/me',actor='alice')
req('10 — Создать чат','POST','/api/v1/chats',201,'alice',{'title':'Защита лабораторной 2','member_ids':['{{alice_id}}','{{bob_id}}']},'chat_id')
req('11 — Мои чаты','GET','/api/v1/chats?limit=50',actor='bob')
req('12 — Чат участника','GET','/api/v1/chats/{{chat_id}}',actor='bob')
req('13 — Сообщение Глеба','POST','/api/v1/chats/{{chat_id}}/messages',201,'alice',{'text':'Привет, мир 👋'})
req('14 — Сообщение Боба','POST','/api/v1/chats/{{chat_id}}/messages',201,'bob',{'text':'Данные теперь в PostgreSQL'})
req('15 — История','GET','/api/v1/chats/{{chat_id}}/messages?limit=50',actor='alice')
req('16 — Первая страница','GET','/api/v1/chats/{{chat_id}}/messages?limit=1',actor='alice',extra=['if (pm.response.code === 200) {',' pm.test("Есть следующая страница", () => pm.expect(pm.response.json().next_cursor).to.be.a("string"));',' pm.collectionVariables.set("next_cursor", encodeURIComponent(pm.response.json().next_cursor || ""));','}'])
req('17 — Следующая страница','GET','/api/v1/chats/{{chat_id}}/messages?limit=1&cursor={{next_cursor}}',actor='bob',extra=['if (pm.response.code === 200) pm.test("История закончилась", () => pm.expect(pm.response.json().next_cursor).to.equal(null));'])
req('18 — Посторонний получает 404','GET','/api/v1/chats/{{chat_id}}/messages',404,'eve')
req('19 — Аноним получает 401','GET','/api/v1/users/me',401)
req('20 — Basic не подходит для бизнес-запроса','GET','/api/v1/users/me',401,basic='alice')
req('21 — Пустое сообщение получает 400','POST','/api/v1/chats/{{chat_id}}/messages',400,'alice',{'text':''})
req('22 — Logout текущего токена','DELETE','/api/v1/auth/sessions/current',204,'alice')
req('23 — Отозванный токен получает 401','GET','/api/v1/users/me',401,'alice')
collection={'info':{'name':'ЛР 2 — Крайкин БВТ2303 — PostgreSQL и сессии','schema':'https://schema.getpostman.com/json/collection/v2.1.0/collection.json','description':'Запустите make up. Run выполняет 23 запроса сверху вниз, сохраняет ID и токены только в локальные переменные Postman. Новый run_id позволяет повторять сценарий. Для ручной проверки persistence остановитесь после 17, выполните scripts/restart.sh, повторите 09 и 15 с прежним Bearer, затем 22 и 23. Никаких реальных паролей; demo_password синтетический. Для localhost нужен настольный Postman/Desktop Agent. Перед экспортом коллекции очистите значения токенов.'},'variable':[{'key':'base_url','value':'http://localhost:8082','type':'string'},{'key':'demo_password','value':'Synthetic-Postman-Demo-123','type':'string'}]+[{'key':k,'value':'','type':'string'} for k in ['run_id','alice_id','bob_id','eve_id','alice_token','bob_token','eve_token','alice_expires_at','bob_expires_at','eve_expires_at','chat_id','next_cursor']],'item':items}
(ROOT/'postman/lab2.postman_collection.json').write_text(json.dumps(collection,ensure_ascii=False,indent=2)+'\n')
print('Postman collection: 23 requests; no live credentials/tokens')
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Dependency order matters: API bootstrap needs a ready database.
# Restart EVERY runtime service; named volumes and expiry stay unchanged.
docker compose --env-file .env stop api
docker compose --env-file .env restart postgres valkey
docker compose --env-file .env up -d --wait postgres valkey
docker compose --env-file .env start api