This commit is contained in:
Бахрам
2026-10-29 17:16:55 +03:00
parent 65003b6119
commit c401ece9b1
30 changed files with 1459 additions and 18 deletions
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Create local synthetic credentials once. Never print their values."""
import os
from pathlib import Path
import secrets
root = Path(__file__).resolve().parents[1]
os.umask(0o077)
folder = root / 'secrets'
folder.mkdir(exist_ok=True)
password_path = folder / 'postgres_password'
if not password_path.exists():
password_path.write_text(secrets.token_hex(24))
password = password_path.read_text().strip()
for name, value in {
'database_url': 'postgresql://messenger:' + password + '@postgres:5432/messenger',
}.items():
path = folder / name
if not path.exists():
path.write_text(value)
# Docker Desktop mounts are read by the non-root API user too. Directory remains private.
for path in folder.iterdir():
path.chmod(0o444)
env = root / '.env'
if not env.exists():
env.write_text('API_PORT=8080\nSESSION_TTL_SECONDS=3600\nDB_POOL_SIZE=8\n')
print('Local secrets and .env ready (values hidden; existing files preserved).')
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# All state stores and API; named volumes remain attached. No reseeding.
docker compose --env-file .env restart postgres api
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Check real session expiry with TTL=2 and restore normal API configuration."""
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT / 'tests'))
from client import Client, Failure, check
COMPOSE = ['docker','compose','--env-file','.env']
def compose(*args, env=None):
subprocess.run(COMPOSE+list(args),cwd=ROOT,env=env,check=True,
stdout=subprocess.DEVNULL)
def ready(c):
deadline=time.monotonic()+60
while time.monotonic()<deadline:
try:
c.call('GET','/health/ready')
return
except Failure:
time.sleep(0.5)
raise AssertionError('Readiness timeout')
def main():
c=Client()
ready(c)
try:
env=dict(os.environ,SESSION_TTL_SECONDS='2')
compose('up','-d','--no-deps','--force-recreate','api',env=env)
ready(c)
short=c.user('expiry')
c.call('GET','/api/v1/users/me',actor=short,schema='User')
time.sleep(2.3)
c.call('GET','/api/v1/users/me',401,actor=short)
c.call('DELETE','/api/v1/auth/sessions/current',401,actor=short)
print('PASS SESSION_TTL_SECONDS=2: session accepted before expiry and rejected afterwards',flush=True)
finally:
compose('up','-d','--no-deps','--force-recreate','api')
ready(c)
print('PASS expiry scenario; normal API configuration restored',flush=True)
if __name__=='__main__':
main()
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Run all lab2 checks and save sanitized evidence. Start Compose first."""
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = ['docker','compose','--env-file','.env']
def capture(name, args):
result = subprocess.run(args,cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
(ROOT/'evidence'/name).write_text(result.stdout)
print(result.stdout,end='',flush=True)
if result.returncode:
raise SystemExit(result.returncode)
def snapshot():
ids = subprocess.check_output(COMPOSE+['ps','-q'],cwd=ROOT,text=True).split()
result = {}
for cid in ids:
# Select fields explicitly: full inspect includes private configuration.
fields = subprocess.check_output(['docker','inspect','--format',
'{{ index .Config.Labels "com.docker.compose.service" }}|{{.Id}}|{{.State.StartedAt}}',cid],text=True).strip().split('|')
result[fields[0]]={'container_id':fields[1],'started_at':fields[2]}
return result
def main():
capture('check.txt',['make','check'])
capture('smoke.txt',['make','test'])
capture('integration.txt',COMPOSE+['exec','-T','api','python','-m','unittest','discover','-s','student-tests','-v'])
before = snapshot()
capture('persistence.txt',['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh'])
after = snapshot()
if set(before) != {'api','postgres'} or set(after) != set(before):
raise AssertionError('Expected API and PostgreSQL')
for role in before:
if before[role]['started_at']==after[role]['started_at']:
raise AssertionError(role+' was not restarted')
(ROOT/'evidence'/'restart-containers.json').write_text(json.dumps({'before':before,'after':after},indent=2)+'\n')
print('PASS restart timestamps changed for API and PostgreSQL',flush=True)
capture('expiry.txt',[sys.executable,'scripts/test_expiry.py'])
print('PASS full verification; evidence/ updated',flush=True)
if __name__ == '__main__':
main()