diff --git a/.github/workflows/application.yml b/.github/workflows/application.yml new file mode 100644 index 00000000..40962420 --- /dev/null +++ b/.github/workflows/application.yml @@ -0,0 +1,28 @@ +name: Application +on: [push, pull_request] +permissions: + contents: read +jobs: + postgres-compose: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: python scripts/init_local.py + - run: docker compose config --quiet + - run: docker compose up -d --build --wait --wait-timeout 120 + - run: make check test + - run: docker compose exec -T api python -m messenger.migrate + - run: | + docker compose cp student-tests api:/app/student-tests + docker compose exec -T api python -m unittest discover -s student-tests -v + - run: chmod +x scripts/restart.sh && make test-persistence ACTION_SCRIPT=scripts/restart.sh + - uses: actions/upload-artifact@v4 + if: always() + with: + name: restart-evidence + path: evidence/restart-*.txt + - if: always() + run: docker compose down diff --git a/scripts/start.sh b/scripts/start.sh new file mode 100644 index 00000000..6d9e6f43 --- /dev/null +++ b/scripts/start.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +python -m messenger.migrate +exec python -m messenger diff --git a/student-tests/test_api.py b/student-tests/test_api.py new file mode 100644 index 00000000..8bcae7d1 --- /dev/null +++ b/student-tests/test_api.py @@ -0,0 +1,123 @@ +"""Integration tests. DATABASE_URL[_FILE] must point to a disposable PostgreSQL DB.""" +import base64 +import time +import unittest +from dataclasses import replace +from uuid import uuid4 +from messenger.api import create_app +from messenger.config import Settings +from messenger.database import Database +from messenger.migrate import migrate + + +class ApiTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.settings = Settings.from_env() + cls.db = Database(cls.settings.database_url) + migrate(cls.db) + cls.app = create_app(settings=cls.settings) + + def setUp(self): + self.c = self.app.test_client() + self.password = 'Учебный:пароль-12345' + self.name = 'u_' + uuid4().hex[:16] + self.registration = {'username': self.name, 'display_name': 'Имя 👋', 'password': self.password} + r = self.c.post('/api/v1/users', json=self.registration) + self.assertEqual(r.status_code, 201) + self.user = r.json + self.basic = {'Authorization': 'Basic ' + base64.b64encode((self.name + ':' + self.password).encode()).decode()} + r = self.c.post('/api/v1/auth/sessions', headers=self.basic) + self.assertEqual(r.status_code, 201) + self.session = r.json + self.headers = {'Authorization': 'Bearer ' + self.session['token']} + self.chat = self.c.post('/api/v1/chats', headers=self.headers, json={ + 'title': 'Учебный чат', 'member_ids': [self.user['id']]}).json + self.path = '/api/v1/chats/' + self.chat['id'] + '/messages' + + def error(self, response, status): + self.assertEqual(response.status_code, status) + self.assertEqual(response.json['error']['request_id'], response.headers['X-Request-Id']) + + def test_authentication_and_logout(self): + for headers in [{}, self.basic, {'X-User-Id': self.user['id']}, {'Authorization': 'Bearer bad'}]: + r = self.c.get('/api/v1/users/me', headers=headers) + self.error(r, 401) + self.assertEqual(r.headers['WWW-Authenticate'], 'Bearer realm="messenger"') + for auth in ['Basic bad', 'Bearer bad', 'Basic ' + base64.b64encode((self.name + ':wrong-password').encode()).decode()]: + r = self.c.post('/api/v1/auth/sessions', headers={'Authorization': auth}) + self.error(r, 401) + self.assertEqual(r.headers['WWW-Authenticate'], 'Basic realm="messenger", charset="UTF-8"') + r = self.c.get('/api/v1/users/me', headers=dict(self.headers, **{'X-User-Id': str(uuid4())})) + self.assertEqual(r.json, self.user) + self.error(self.c.post('/api/v1/auth/sessions', headers=self.basic, json={}), 400) + r = self.c.delete('/api/v1/auth/sessions/current', headers=self.headers) + self.assertEqual((r.status_code, r.data), (204, b'')) + self.error(self.c.get('/api/v1/users/me', headers=self.headers), 401) + self.error(self.c.delete('/api/v1/auth/sessions/current', headers=self.headers), 401) + + def test_expiry_and_restart_app(self): + short = create_app(settings=replace(self.settings, session_ttl=2)).test_client() + r = short.post('/api/v1/auth/sessions', headers=self.basic) + self.assertEqual(r.status_code, 201) + headers = {'Authorization': 'Bearer ' + r.json['token']} + self.assertEqual(short.get('/api/v1/users/me', headers=headers).status_code, 200) + # New app instance must respect the stored original expiry, not renew it. + restarted = create_app(settings=replace(self.settings, session_ttl=3600)).test_client() + self.assertEqual(restarted.get('/api/v1/users/me', headers=headers).status_code, 200) + time.sleep(2.1) + self.error(restarted.get('/api/v1/users/me', headers=headers), 401) + + def test_strict_validation_and_private_chat(self): + self.error(self.c.post('/api/v1/users', data='{', content_type='application/json'), 400) + self.error(self.c.post('/api/v1/users', json=self.registration), 409) + for patch in [{'password': 'short'}, {'password': 42}, {'display_name': ' '}, {'extra': 1}]: + self.error(self.c.post('/api/v1/users', json=dict(self.registration, **patch)), 400) + self.error(self.c.post(self.path, headers=self.headers, json={'text': ' \n'}), 400) + self.error(self.c.post(self.path, headers=self.headers, json={'text': 'x', 'sender_id': self.user['id']}), 400) + self.error(self.c.get('/api/v1/chats/' + str(uuid4()), headers=self.headers), 404) + outsider = 'u_' + uuid4().hex[:16] + self.c.post('/api/v1/users', json=dict(self.registration, username=outsider)) + basic = {'Authorization': 'Basic ' + base64.b64encode((outsider + ':' + self.password).encode()).decode()} + token = self.c.post('/api/v1/auth/sessions', headers=basic).json['token'] + self.error(self.c.get(self.path, headers={'Authorization': 'Bearer ' + token}), 404) + + def test_pagination_survives_new_app(self): + expected = [self.c.post(self.path, headers=self.headers, json={'text': str(i)}).json for i in range(5)] + first = self.c.get(self.path + '?limit=2', headers=self.headers).json + cursor = first['next_cursor'] + new_client = create_app(settings=self.settings).test_client() + second = new_client.get(self.path, query_string={'limit': 1, 'cursor': cursor}, headers=self.headers).json + third = new_client.get(self.path, query_string={'limit': 100, 'cursor': second['next_cursor']}, headers=self.headers).json + self.assertEqual(first['items'] + second['items'] + third['items'], expected) + self.assertIsNone(third['next_cursor']) + self.error(self.c.get('/api/v1/chats', query_string={'cursor': cursor}, headers=self.headers), 400) + other = self.c.post('/api/v1/chats', headers=self.headers, json={'title': 'Other', 'member_ids': [self.user['id']]}).json + self.error(self.c.get('/api/v1/chats/' + other['id'] + '/messages', query_string={'cursor': cursor}, headers=self.headers), 400) + for limit in ['0', '101', '1.5', 'true']: + self.error(self.c.get(self.path, query_string={'limit': limit}, headers=self.headers), 400) + self.error(self.c.get(self.path, query_string={'cursor': 'invalid'}, headers=self.headers), 400) + page = self.c.get('/api/v1/chats?limit=1', headers=self.headers).json + last = self.c.get('/api/v1/chats', query_string={'cursor': page['next_cursor']}, headers=self.headers).json + self.assertEqual(len(page['items'] + last['items']), 2) + + def test_atomic_chat_and_migration_repeat(self): + with self.db.transaction() as conn: + before = conn.execute('SELECT count(*) AS n FROM chats').fetchone()['n'] + for members in [[self.user['id'], str(uuid4())], [self.user['id'], self.user['id']], []]: + self.error(self.c.post('/api/v1/chats', headers=self.headers, + json={'title': 'Invalid', 'member_ids': members}), 400) + migrate(self.db) + migrate(self.db) + with self.db.transaction() as conn: + self.assertEqual(conn.execute('SELECT count(*) AS n FROM chats').fetchone()['n'], before) + self.assertEqual(conn.execute('SELECT count(*) AS n FROM schema_migrations').fetchone()['n'], 1) + row = conn.execute('SELECT password_hash FROM users WHERE id=%s', (self.user['id'],)).fetchone() + self.assertTrue(row['password_hash'].startswith('$argon2id$')) + hashes = [r['token_hash'] for r in conn.execute('SELECT token_hash FROM sessions WHERE user_id=%s', (self.user['id'],))] + self.assertNotIn(self.session['token'], hashes) + self.assertEqual(self.c.get('/api/v1/users/me', headers=self.headers).json, self.user) + + +if __name__ == '__main__': + unittest.main()