forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL и постоянные сессии — Гавриленко БПИ2303, на 3
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
"""Additional checks against a running lab2 server."""
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Additional validation checks')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a, b, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
c.call('POST', '/api/v1/users', 400, body={'username': 'BAD', 'display_name': 'X'})
|
||||
c.call('POST', '/api/v1/users', 400, body={'username': 'valid_name', 'display_name': ' '})
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(a['registration'], extra=True))
|
||||
c.call('POST', path, 400, actor=a, body={'text': ' '})
|
||||
c.call('POST', path, 400, actor=a, body={'text': 'ok', 'sender_id': b['id']})
|
||||
c.call('GET', path, 404, actor=eve)
|
||||
c.call('GET', path + '?cursor=bad', 400, actor=a)
|
||||
c.call('GET', path + '?limit=1.5', 400, actor=a)
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': str(uuid.uuid4())})
|
||||
for i in range(5):
|
||||
c.message(a, chat, 'Юникод 👋 ' + str(i))
|
||||
p = c.call('GET', path + '?limit=2', actor=b, schema='MessagePage')['json']
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=a, body={'title': 'other', 'member_ids': [a['id']]}, schema='Chat')['json']
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + p['next_cursor'], 400, actor=a)
|
||||
items = p['items']
|
||||
while p['next_cursor']:
|
||||
p = c.call('GET', path + '?limit=2&cursor=' + p['next_cursor'], actor=b, schema='MessagePage')['json']
|
||||
items += p['items']
|
||||
assert len(items) == len({x['id'] for x in items}) == 5
|
||||
print('PASS: validation, access, Unicode, pagination and cursor scope')
|
||||
c.call('POST', '/api/v1/users', 400, raw=b'{', headers={'Content-Type': 'application/json'})
|
||||
c.call('POST', '/api/v1/users', 409, body=a['registration'])
|
||||
print('PASS: malformed JSON and duplicate username')
|
||||
import base64
|
||||
# All 128 Unicode code points, including colon, must survive KDF without truncation.
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:12], 'display_name': 'Unicode', 'password': ':' + '🔐' * 127}
|
||||
u = c.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
|
||||
credential = base64.b64encode((u['username'] + ':' + registration['password']).encode()).decode()
|
||||
session = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
assert session['user'] == u
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(registration, password='a' * 11))
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(registration, password='a' * 129))
|
||||
# Creating a chat with a missing participant must leave no visible chat behind.
|
||||
before = c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json']
|
||||
for members in ([a['id'], str(uuid.uuid4())], [a['id'], a['id']], [b['id']]):
|
||||
c.call('POST', '/api/v1/chats', 400, actor=a, body={'title': 'invalid', 'member_ids': members})
|
||||
assert c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json'] == before
|
||||
print('PASS: Unicode/colon passwords, length boundaries, invalid chat creation')
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Run inside API container: migrations, constraints, rollback and password storage."""
|
||||
import sys
|
||||
import uuid
|
||||
sys.path.insert(0, '/app/src')
|
||||
import psycopg
|
||||
from db import connect, migrate
|
||||
|
||||
|
||||
def counts():
|
||||
with connect() as db:
|
||||
return {name: db.execute('SELECT count(*) AS n FROM ' + name).fetchone()['n']
|
||||
for name in ('users', 'chats', 'chat_members', 'messages', 'sessions', 'schema_migrations')}
|
||||
|
||||
|
||||
before = counts()
|
||||
migrate()
|
||||
migrate()
|
||||
assert counts() == before
|
||||
with connect() as db:
|
||||
assert db.execute('SELECT count(*) AS n FROM users').fetchone()['n'] > 0
|
||||
assert db.execute('SELECT 1 FROM users WHERE octet_length(password_salt) != 16 OR octet_length(password_hash) != 64').fetchone() is None
|
||||
assert db.execute('SELECT 1 FROM sessions WHERE octet_length(token_hash) != 32').fetchone() is None
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
with connect() as db:
|
||||
db.execute('INSERT INTO chats (id,title) VALUES (%s,%s)', (chat_id, 'rollback check'))
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat_id, uuid.uuid4()))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Foreign key did not reject missing member')
|
||||
with connect() as db:
|
||||
assert db.execute('SELECT 1 FROM chats WHERE id=%s', (chat_id,)).fetchone() is None
|
||||
assert counts() == before
|
||||
print('PASS: repeated migrations preserve row counts; scrypt/token digests; FK and transaction rollback')
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Run against an API started with SESSION_TTL_SECONDS=2; tokens never printed."""
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Short-TTL session expiry')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a = c.user('expiry')
|
||||
c.call('GET', '/api/v1/users/me', actor=a, schema='User')
|
||||
time.sleep(3)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=a)
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=a)
|
||||
print('PASS: session expires with TTL=2; expired token cannot read or logout')
|
||||
Reference in New Issue
Block a user