forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL, Bearer-сессии, Valkey и исследование восстановления
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
"""Verify the committed tree using a fresh clone and isolated Compose volumes."""
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
project='mtusi-lab2-clean-'+uuid.uuid4().hex[:8]
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1',0))
|
||||
port=s.getsockname()[1]
|
||||
report={'date_utc':dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
'source_commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip(),
|
||||
'fresh_project_and_volumes':True}
|
||||
with tempfile.TemporaryDirectory(prefix='mtusi-lab2-clean-') as directory:
|
||||
clone=Path(directory)/'repo'
|
||||
subprocess.run(['git','clone','--no-local',str(ROOT),str(clone)],check=True)
|
||||
assert not subprocess.check_output(['git','status','--porcelain'],cwd=clone)
|
||||
environment={**os.environ,'COMPOSE_PROJECT_NAME':project,'HOST_PORT':str(port),'BASE_URL':'http://127.0.0.1:'+str(port)}
|
||||
def run(*command):
|
||||
subprocess.run(command,cwd=clone,env=environment,check=True)
|
||||
run(sys.executable,'scripts/bootstrap.py')
|
||||
try:
|
||||
run('docker','compose','build','--no-cache')
|
||||
run('docker','compose','up','-d','--wait','--wait-timeout','60')
|
||||
run('make','check','test','student-test','PYTHON='+sys.executable,'BASE_URL='+environment['BASE_URL'])
|
||||
run(sys.executable,'student-tests/infrastructure.py')
|
||||
report['checks']={'build_from_source':True,'public_smoke':True,'own_http_tests':True,
|
||||
'infrastructure_and_public_persistence':True}
|
||||
report['infrastructure']=json.loads((clone/'evidence/infrastructure.json').read_text())
|
||||
api_id=subprocess.check_output(['docker','compose','ps','-q','api'],cwd=clone,env=environment,text=True).strip()
|
||||
user=subprocess.check_output(['docker','exec',api_id,'id','-u'],text=True).strip()
|
||||
assert user=='10001'
|
||||
report['checks']['api_uid_10001']=True
|
||||
report['status']='PASS'
|
||||
finally:
|
||||
# Only this fresh disposable test project's volumes are removed.
|
||||
subprocess.run(['docker','compose','down','--volumes','--remove-orphans'],cwd=clone,env=environment,check=True)
|
||||
(ROOT/'evidence/clean-clone.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print(json.dumps(report,ensure_ascii=False,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Explicit, recoverable failure tests for THIS Compose project only."""
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'tests'))
|
||||
from client import Client
|
||||
|
||||
|
||||
def compose(*args,input=None):
|
||||
return subprocess.run(['docker','compose',*args],cwd=ROOT,input=input,text=True,capture_output=True,check=True).stdout.strip()
|
||||
|
||||
|
||||
def internal(code):
|
||||
return json.loads(compose('exec','-T','api','python','-',input=code))
|
||||
|
||||
|
||||
def ready(client):
|
||||
deadline=time.monotonic()+30
|
||||
while True:
|
||||
try:
|
||||
client.call('GET','/health/ready',schema='Health')
|
||||
return
|
||||
except AssertionError:
|
||||
if time.monotonic()>deadline:
|
||||
raise
|
||||
time.sleep(.2)
|
||||
|
||||
|
||||
def main():
|
||||
base=os.environ.get('BASE_URL','http://localhost:8082')
|
||||
client=Client(base,timeout=8)
|
||||
alice,bob,eve,chat=client.bootstrap()
|
||||
report={'date_utc':dt.datetime.now(dt.timezone.utc).isoformat(),'checks':{}}
|
||||
checks=report['checks']
|
||||
def state_counts():
|
||||
return internal("""import json,os,psycopg
|
||||
from pathlib import Path
|
||||
with psycopg.connect(Path(os.environ['DATABASE_URL_FILE']).read_text().strip()) as c:
|
||||
print(json.dumps({name:c.execute('SELECT count(*) FROM '+name).fetchone()[0] for name in ('chats','chat_members')}))
|
||||
""")
|
||||
prior=state_counts()
|
||||
client.call('POST','/api/v1/chats',400,actor=alice,body={'title':'Rollback probe','member_ids':[alice['id'],bob['id'],str(uuid.uuid4())]})
|
||||
assert prior==state_counts()
|
||||
checks['failed_chat_transaction_leaves_no_chat_or_members']=True
|
||||
client.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
cache=internal('''import json,os,redis
|
||||
from pathlib import Path
|
||||
r=redis.Redis.from_url(Path(os.environ['CACHE_URL_FILE']).read_text().strip(),decode_responses=True)
|
||||
keys=r.keys('profile:v1:*')
|
||||
values=[json.loads(r.get(k)) for k in keys]
|
||||
assert keys and all(set(v)=={'id','username','display_name','created_at'} for v in values)
|
||||
print(json.dumps({'cached_profiles':len(keys),'all_profiles_public_fields_only':True,'positive_ttl':all(r.ttl(k)>0 for k in keys)}))
|
||||
''')
|
||||
assert cache['positive_ttl']
|
||||
checks['valkey_really_caches_profiles']=cache
|
||||
checks['password_kdf_and_hashed_tokens']=internal('''import json,os,psycopg
|
||||
from pathlib import Path
|
||||
with psycopg.connect(Path(os.environ['DATABASE_URL_FILE']).read_text().strip()) as c:
|
||||
p=c.execute("SELECT bool_and(password_hash LIKE 'scrypt$16384$8$1$%') FROM users").fetchone()[0]
|
||||
t=c.execute('SELECT bool_and(octet_length(token_hash)=32) FROM sessions').fetchone()[0]
|
||||
print(json.dumps({'all_passwords_scrypt':p,'all_token_digests_32_bytes':t}))
|
||||
''')
|
||||
assert all(checks['password_kdf_and_hashed_tokens'].values())
|
||||
try:
|
||||
compose('stop','valkey')
|
||||
started=time.monotonic()
|
||||
me=client.call('GET','/api/v1/users/me',actor=alice,schema='User')['json']
|
||||
assert me==alice['user']
|
||||
client.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']})
|
||||
message=client.message(alice,chat,'cache outage synthetic')['json']
|
||||
page=client.call('GET','/api/v1/chats/'+chat['id']+'/messages',actor=bob,schema='MessagePage')['json']
|
||||
assert message in page['items']
|
||||
# Revocation remains authoritative while the cache is down.
|
||||
client.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
client.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
checks['cache_outage']={'fallback_profile_and_history':True,'anonymous_rejected':True,'logout_effective':True,'scenario_seconds':round(time.monotonic()-started,3)}
|
||||
finally:
|
||||
compose('up','-d','--wait','valkey')
|
||||
client.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
client.call('GET','/api/v1/users/me',actor=bob,schema='User')
|
||||
checks['cache_restart_no_revoked_session_resurrection']=True
|
||||
internal('''import json,os,redis
|
||||
from pathlib import Path
|
||||
r=redis.Redis.from_url(Path(os.environ['CACHE_URL_FILE']).read_text().strip())
|
||||
r.flushdb()
|
||||
print(json.dumps({'flushed':True}))
|
||||
''')
|
||||
assert client.call('GET','/api/v1/users/me',actor=bob,schema='User')['json']==bob['user']
|
||||
checks['cache_flush_repopulates_from_postgres']=True
|
||||
try:
|
||||
compose('stop','postgres')
|
||||
started=time.monotonic()
|
||||
unavailable=client.call('GET','/api/v1/users/me',503,actor=bob)
|
||||
elapsed=time.monotonic()-started
|
||||
assert elapsed<7
|
||||
assert unavailable['json']['error']['code']=='unavailable'
|
||||
client.call('GET','/health/live',schema='Health')
|
||||
client.call('GET','/health/ready',503)
|
||||
client.call('GET','/api/v1/users/me',401)
|
||||
checks['postgres_outage']={'authenticated_request_503_seconds':round(elapsed,3),'live_200':True,'ready_503':True,'no_anonymous_trust':True}
|
||||
finally:
|
||||
compose('up','-d','--wait','postgres')
|
||||
ready(client)
|
||||
assert client.call('GET','/api/v1/users/me',actor=bob,schema='User')['json']==bob['user']
|
||||
checks['postgres_recovery_same_session']=True
|
||||
# A second API container uses the same PostgreSQL and Valkey, short TTL only.
|
||||
name='mtusi-lab2-short-ttl-'+uuid.uuid4().hex[:8]
|
||||
try:
|
||||
compose('run','-d','--no-deps','--name',name,'-p','127.0.0.1::8080','-e','SESSION_TTL_SECONDS=2','api')
|
||||
mapping=subprocess.check_output(['docker','port',name,'8080/tcp'],text=True).strip()
|
||||
short=Client('http://127.0.0.1:'+mapping.rsplit(':',1)[1])
|
||||
ready(short)
|
||||
actor=short.user('expiry')
|
||||
short.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
time.sleep(2.2)
|
||||
short.call('GET','/api/v1/users/me',401,actor=actor)
|
||||
checks['expiry_ttl_2_seconds']=True
|
||||
finally:
|
||||
subprocess.run(['docker','rm','-f',name],capture_output=True)
|
||||
migrations_before=internal('''import json,os,psycopg
|
||||
from pathlib import Path
|
||||
with psycopg.connect(Path(os.environ['DATABASE_URL_FILE']).read_text().strip()) as c:
|
||||
print(json.dumps({'migrations':c.execute('SELECT count(*) FROM schema_migrations').fetchone()[0],'users':c.execute('SELECT count(*) FROM users').fetchone()[0]}))
|
||||
''')
|
||||
compose('exec','-T','api','python','src/app.py','--migrate')
|
||||
migrations_after=internal('''import json,os,psycopg
|
||||
from pathlib import Path
|
||||
with psycopg.connect(Path(os.environ['DATABASE_URL_FILE']).read_text().strip()) as c:
|
||||
print(json.dumps({'migrations':c.execute('SELECT count(*) FROM schema_migrations').fetchone()[0],'users':c.execute('SELECT count(*) FROM users').fetchone()[0]}))
|
||||
''')
|
||||
assert migrations_before==migrations_after
|
||||
checks['repeat_migration_does_not_duplicate_data']=migrations_after
|
||||
# Actual process start times around the public all-service restart scenario.
|
||||
def states():
|
||||
values={}
|
||||
for service in ('api','postgres','valkey'):
|
||||
cid=compose('ps','-q',service)
|
||||
values[service]=json.loads(subprocess.check_output(['docker','inspect',cid],text=True))[0]['State']['StartedAt']
|
||||
return values
|
||||
before=states()
|
||||
started=time.monotonic()
|
||||
completed=subprocess.run(['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+base],cwd=ROOT,text=True,capture_output=True,check=True)
|
||||
(ROOT/'evidence/persistence.txt').write_text(completed.stdout+completed.stderr)
|
||||
after=states()
|
||||
assert all(before[s]!=after[s] for s in before)
|
||||
checks['full_stack_persistence']={'api_and_all_stores_restarted':True,'before':before,'after':after,'elapsed_seconds':round(time.monotonic()-started,3)}
|
||||
report['status']='PASS'
|
||||
(ROOT/'evidence/infrastructure.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print(json.dumps(report,ensure_ascii=False,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Independent HTTP checks against the real PostgreSQL/Valkey Compose stack."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
|
||||
|
||||
def basic(username,password):
|
||||
return 'Basic ' + base64.b64encode((username + ':' + password).encode()).decode()
|
||||
|
||||
|
||||
class APItests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.base = os.environ.get('BASE_URL','http://localhost:8082')
|
||||
cls.c = Client(cls.base)
|
||||
cls.c.call('GET','/health/ready',schema='Health')
|
||||
|
||||
def setUp(self):
|
||||
self.alice,self.bob,self.eve,self.chat = self.c.bootstrap()
|
||||
self.path = '/api/v1/chats/' + self.chat['id']
|
||||
|
||||
def test_malformed_json_and_types(self):
|
||||
for raw in (b'{',b'null',b'[]',b'{} {}',b'\xff',b'{"username":NaN}',b'{"username":"one","username":"two"}'):
|
||||
self.c.call('POST','/api/v1/users',400,raw=raw,headers={'Content-Type':'application/json'})
|
||||
valid = dict(self.alice['registration'])
|
||||
for field, value in [('username',True),('username','ab'),('display_name',None),('display_name',123),('password',False),('password','a'*11),('password','a'*129)]:
|
||||
self.c.call('POST','/api/v1/users',400,body={**valid,field:value})
|
||||
self.c.call('POST','/api/v1/users',400,body={**valid,'unexpected':'x'})
|
||||
self.c.call('POST','/api/v1/users',415,raw=b'{}',headers={'Content-Type':'text/plain'})
|
||||
self.c.call('POST','/api/v1/users',413,raw=b'x'*65537,headers={'Content-Type':'application/json'})
|
||||
raw=json.dumps({**valid,'display_name':'\ud800'}).encode()
|
||||
self.c.call('POST','/api/v1/users',400,raw=raw,headers={'Content-Type':'application/json'})
|
||||
|
||||
def test_empty_message_unicode_and_sender(self):
|
||||
for body in ({'text':''},{'text':'\t\n\u2003'},{'text':None},{'text':123},{'text':'🐍'*4001},{'text':'x','sender_id':self.eve['id']}):
|
||||
self.c.call('POST',self.path+'/messages',400,body=body,actor=self.alice)
|
||||
message=self.c.message(self.alice,self.chat,'🐍'*4000)['json']
|
||||
self.assertEqual(message['sender_id'],self.alice['id'])
|
||||
self.assertEqual(message['text'],'🐍'*4000)
|
||||
|
||||
def test_authentication_before_access_and_foreign_chat(self):
|
||||
for suffix in ('','/messages'):
|
||||
self.c.call('GET',self.path+suffix,404,actor=self.eve)
|
||||
self.c.call('POST',self.path+'/messages',404,body={'text':'x'},actor=self.eve)
|
||||
self.c.call('GET','/api/v1/chats/not-a-uuid?limit=0',401)
|
||||
self.c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':self.alice['id']})
|
||||
me=self.c.call('GET','/api/v1/users/me',actor=self.alice,headers={'X-User-Id':self.eve['id']},schema='User')['json']
|
||||
self.assertEqual(me,self.alice['user'])
|
||||
|
||||
def test_bad_password_unknown_username_and_basic_only_for_login(self):
|
||||
known=self.alice['registration']
|
||||
for authorization in ('Basic not-base64','Bearer '+self.alice['token'],basic(known['username'],'Wrong-password-123'),basic('unknown_'+uuid.uuid4().hex[:10],'Wrong-password-123')):
|
||||
response=self.c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':authorization})
|
||||
self.assertEqual(response['headers']['WWW-Authenticate'],'Basic realm="messenger", charset="UTF-8"')
|
||||
self.assertEqual(response['json']['error']['message'],'Неверные или отсутствующие учётные данные')
|
||||
self.c.call('GET','/api/v1/users/me',401,headers={'Authorization':basic(known['username'],known['password'])})
|
||||
self.c.call('POST','/api/v1/auth/sessions',400,body={},headers={'Authorization':basic(known['username'],known['password'])})
|
||||
|
||||
def test_unicode_password_128_codepoints_and_colon(self):
|
||||
username='unicode_'+uuid.uuid4().hex[:12]
|
||||
password='😀'*126+':я'
|
||||
user=self.c.call('POST','/api/v1/users',201,body={'username':username,'display_name':'🐍'*100,'password':password},schema='User')['json']
|
||||
session=self.c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':basic(username,password)},schema='Session')['json']
|
||||
self.assertEqual(session['user'],user)
|
||||
self.assertNotIn('password',user)
|
||||
self.assertNotIn('password_hash',user)
|
||||
self.assertGreaterEqual(len(base64.urlsafe_b64decode(session['token']+'=')),32)
|
||||
|
||||
def test_logout_revokes_only_current_session(self):
|
||||
credentials=self.alice['registration']
|
||||
session=self.c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':basic(credentials['username'],credentials['password'])},schema='Session')['json']
|
||||
other={'id':self.alice['id'],'token':session['token']}
|
||||
self.c.call('DELETE','/api/v1/auth/sessions/current',204,actor=self.alice)
|
||||
self.c.call('GET','/api/v1/users/me',401,actor=self.alice)
|
||||
self.c.call('DELETE','/api/v1/auth/sessions/current',401,actor=self.alice)
|
||||
self.c.call('GET','/api/v1/users/me',actor=other,schema='User')
|
||||
|
||||
def test_chat_rollback_and_membership_validation(self):
|
||||
before=self.c.call('GET','/api/v1/chats',actor=self.alice,schema='ChatPage')['json']
|
||||
for members in ([],[self.alice['id'],self.alice['id']],[self.bob['id']],[self.alice['id'],self.bob['id'],str(uuid.uuid4())],None,[self.alice['id'],1]):
|
||||
self.c.call('POST','/api/v1/chats',400,body={'title':'ROLLBACK','member_ids':members},actor=self.alice)
|
||||
self.assertEqual(before,self.c.call('GET','/api/v1/chats',actor=self.alice,schema='ChatPage')['json'])
|
||||
|
||||
def test_multiple_pages_bad_limits_and_cross_resource_cursor(self):
|
||||
expected=[self.c.message(self.alice,self.chat,str(i))['json'] for i in range(13)]
|
||||
found=[]
|
||||
cursor=saved=None
|
||||
while True:
|
||||
path=self.path+'/messages?limit='+('2' if cursor is None else '3')
|
||||
if cursor:
|
||||
path+='&cursor='+quote(cursor,safe='')
|
||||
page=self.c.call('GET',path,actor=self.bob,schema='MessagePage')['json']
|
||||
found.extend(page['items'])
|
||||
cursor=page['next_cursor']
|
||||
saved=saved or cursor
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(found,expected)
|
||||
other=self.c.call('POST','/api/v1/chats',201,body={'title':'Other','member_ids':[self.alice['id']]},actor=self.alice,schema='Chat')['json']
|
||||
self.c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+quote(saved,safe=''),400,actor=self.alice)
|
||||
for query in ('limit=0','limit=101','limit=1.5','limit=true','limit=-1','limit=1&limit=2','cursor=','cursor=bad'):
|
||||
self.c.call('GET',self.path+'/messages?'+query,400,actor=self.alice)
|
||||
|
||||
def test_read_after_write_during_pagination(self):
|
||||
expected=[self.c.message(self.alice,self.chat,str(i))['json'] for i in range(3)]
|
||||
first=self.c.call('GET',self.path+'/messages?limit=2',actor=self.alice,schema='MessagePage')['json']
|
||||
late=self.c.message(self.bob,self.chat,'late')['json']
|
||||
rest=self.c.call('GET',self.path+'/messages?cursor='+quote(first['next_cursor'],safe=''),actor=self.alice,schema='MessagePage')['json']
|
||||
self.assertEqual(first['items']+rest['items'],expected+[late])
|
||||
|
||||
def test_100_messages_10_clients(self):
|
||||
actors=[self.alice,self.bob]+[self.c.user('writer') for _ in range(8)]
|
||||
chat=self.c.call('POST','/api/v1/chats',201,body={'title':'Concurrency','member_ids':[a['id'] for a in actors]},actor=self.alice,schema='Chat')['json']
|
||||
barrier=threading.Barrier(10)
|
||||
def worker(index):
|
||||
local=Client(self.base)
|
||||
barrier.wait()
|
||||
return [local.message(actors[index],chat,f'{index}:{i}')['json'] for i in range(10)]
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
sent=[m for values in pool.map(worker,range(10)) for m in values]
|
||||
page=self.c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=100',actor=self.alice,schema='MessagePage')['json']
|
||||
self.assertEqual(len(page['items']),100)
|
||||
self.assertEqual(len({m['id'] for m in page['items']}),100)
|
||||
self.assertEqual({m['id'] for m in sent},{m['id'] for m in page['items']})
|
||||
self.assertIsNone(page['next_cursor'])
|
||||
|
||||
def test_racing_registration(self):
|
||||
username='race_'+uuid.uuid4().hex[:12]
|
||||
barrier=threading.Barrier(10)
|
||||
def register(_):
|
||||
local=Client(self.base)
|
||||
barrier.wait()
|
||||
return local.call('POST','/api/v1/users',[201,409],body={'username':username,'display_name':'Concurrent','password':'Long-password-123'},schema='User')['status']
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
statuses=list(pool.map(register,range(10)))
|
||||
self.assertEqual(statuses.count(201),1)
|
||||
self.assertEqual(statuses.count(409),9)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user