|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Exercise migration freeze with synthetic application content over HTTP.""" |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import os |
| 6 | +import shutil |
| 7 | +import socket |
| 8 | +import sqlite3 |
| 9 | +import subprocess |
| 10 | +import tempfile |
| 11 | +import time |
| 12 | +from pathlib import Path |
| 13 | +import urllib.error |
| 14 | +import urllib.request |
| 15 | + |
| 16 | +from integration import ROOT, server |
| 17 | + |
| 18 | + |
| 19 | +def frozen_restart(binary, request, admin, token, frozen): |
| 20 | + """A fresh process preserves a frozen snapshot despite changed deploy settings.""" |
| 21 | + with tempfile.TemporaryDirectory(prefix='taskcontext-frozen-restart-') as tmp: |
| 22 | + data = Path(tmp) / 'pb_data' |
| 23 | + data.mkdir() |
| 24 | + for source in request.data_dir.glob('*.db'): |
| 25 | + with sqlite3.connect(source.as_uri() + '?mode=ro', uri=True) as read: |
| 26 | + with sqlite3.connect(data / source.name) as write: |
| 27 | + read.backup(write) |
| 28 | + shutil.copy2(request.data_dir / 'maintenance.json', data / 'maintenance.json') |
| 29 | + if (request.data_dir / 'storage').exists(): |
| 30 | + shutil.copytree(request.data_dir / 'storage', data / 'storage') |
| 31 | + def config_rows(path): |
| 32 | + with sqlite3.connect(path.as_uri() + '?mode=ro', uri=True) as db: |
| 33 | + return (db.execute('SELECT * FROM _params ORDER BY id').fetchall(), |
| 34 | + db.execute('SELECT * FROM _collections ORDER BY id').fetchall(), |
| 35 | + db.execute('SELECT * FROM users ORDER BY id').fetchall(), |
| 36 | + db.execute('SELECT * FROM _superusers ORDER BY id').fetchall()) |
| 37 | + stored = config_rows(data / 'data.db') |
| 38 | + with socket.socket() as sock: |
| 39 | + sock.bind(('127.0.0.1', 0)) |
| 40 | + port = sock.getsockname()[1] |
| 41 | + env = dict(os.environ, BASE_URL='https://must-not-apply.example.test', |
| 42 | + TASKCONTEXT_GOOGLE_CLIENT_ID='synthetic-changed-client', |
| 43 | + TASKCONTEXT_GOOGLE_CLIENT_SECRET='synthetic-changed-secret', |
| 44 | + TASKCONTEXT_REQUIRED_USERS='[{"email":"must-not-create@example.test","name":"Must not create"}]') |
| 45 | + common = [str(Path(binary).resolve()), '--dir', str(data), |
| 46 | + '--migrationsDir', str(ROOT / 'pb_migrations'), '--hooksDir', str(ROOT / 'pb_hooks')] |
| 47 | + # New application migrations must not silently change a frozen snapshot. |
| 48 | + pending = Path(tmp) / 'pending_migrations' |
| 49 | + shutil.copytree(ROOT / 'pb_migrations', pending) |
| 50 | + (pending / '9999999999_frozen_pending.js').write_text( |
| 51 | + 'migrate((app) => { app.db().newQuery("CREATE TABLE forbidden_frozen_write (id TEXT)").execute(); }, () => {});') |
| 52 | + rejected = subprocess.run([str(Path(binary).resolve()), '--dir', str(data), |
| 53 | + '--migrationsDir', str(pending), '--hooksDir', str(ROOT / 'pb_hooks'), |
| 54 | + 'serve', '--http', f'127.0.0.1:{port}'], cwd=ROOT, env=env, |
| 55 | + capture_output=True, text=True, timeout=20) |
| 56 | + assert rejected.returncode != 0, 'pending migration started during freeze' |
| 57 | + assert config_rows(data / 'data.db') == stored, 'pending migration changed stored settings' |
| 58 | + def call(method, path, body=None, identity=admin): |
| 59 | + req = urllib.request.Request(f'http://127.0.0.1:{port}' + path, |
| 60 | + data=None if body is None else json.dumps(body).encode(), |
| 61 | + headers={'Content-Type': 'application/json', 'Authorization': identity}, method=method) |
| 62 | + with urllib.request.urlopen(req, timeout=10) as response: |
| 63 | + return json.loads(response.read()) |
| 64 | + with (Path(tmp) / 'server.log').open('w+') as log: |
| 65 | + process = subprocess.Popen(common + ['serve', '--http', f'127.0.0.1:{port}'], |
| 66 | + cwd=ROOT, env=env, stdout=log, stderr=log) |
| 67 | + try: |
| 68 | + for _ in range(150): |
| 69 | + if process.poll() is not None: |
| 70 | + log.seek(0) |
| 71 | + raise AssertionError(log.read()) |
| 72 | + try: |
| 73 | + state = call('GET', '/api/context/maintenance') |
| 74 | + break |
| 75 | + except (OSError, ValueError): |
| 76 | + time.sleep(.1) |
| 77 | + else: |
| 78 | + raise AssertionError('frozen restart timed out') |
| 79 | + assert state['state'] == 'read_only' and state['generation'] == frozen['generation'], state |
| 80 | + assert config_rows(data / 'data.db') == stored, 'frozen bootstrap changed configuration' |
| 81 | + assert call('POST', '/api/context/query', {'sql': 'SELECT id FROM projects'}, token)['rows'] |
| 82 | + # Existing operator tokens can thaw after a full process restart. |
| 83 | + state = call('PUT', '/api/context/maintenance', { |
| 84 | + 'readOnly': False, 'expectedGeneration': frozen['generation']}) |
| 85 | + assert state['state'] == 'writable', state |
| 86 | + finally: |
| 87 | + process.terminate() |
| 88 | + process.wait(timeout=15) |
| 89 | + |
| 90 | + |
| 91 | +def main(): |
| 92 | + parser = argparse.ArgumentParser() |
| 93 | + parser.add_argument('--binary', required=True) |
| 94 | + args = parser.parse_args() |
| 95 | + with server(args.binary) as request: |
| 96 | + records = '/api/collections/' |
| 97 | + admin = request('POST', records + '_superusers/auth-with-password', { |
| 98 | + 'identity':'admin@example.com', 'password':'SyntheticAdminPassword123!'})['token'] |
| 99 | + def account(email): |
| 100 | + user = request('POST', records + 'users/records', { |
| 101 | + 'email':email, 'name':'Synthetic', 'verified':True, |
| 102 | + 'password':'SyntheticPassword123!', 'passwordConfirm':'SyntheticPassword123!'}, admin) |
| 103 | + token = request('POST', records + 'users/auth-with-password', { |
| 104 | + 'identity':email, 'password':'SyntheticPassword123!'})['token'] |
| 105 | + return user, token |
| 106 | + user, token = account('reader@example.test') |
| 107 | + outsider, other = account('outsider@example.test') |
| 108 | + payload = {'key':'FREEZE','name':'Synthetic freeze'} |
| 109 | + row = request('POST', records + 'projects/records', payload, token) |
| 110 | + issue = request('POST', records + 'issues/records', {'project':row['id'],'title':'Before freeze'}, token) |
| 111 | + assert issue['key'] == 'FREEZE-1' |
| 112 | + query_sql = 'SELECT id FROM projects' |
| 113 | + write_table = 'projects' |
| 114 | + status = request('GET','/api/context/maintenance',token=admin) |
| 115 | + for identity in (None,token): |
| 116 | + request('GET','/api/context/maintenance',token=identity,expected=(401,403)) |
| 117 | + request('PUT','/api/context/maintenance',{'readOnly':True,'expectedGeneration':status['generation']},identity,(401,403)) |
| 118 | + frozen = request('PUT','/api/context/maintenance',{'readOnly':True,'expectedGeneration':status['generation']},admin) |
| 119 | + assert frozen['state'] == 'read_only' |
| 120 | + assert request('POST','/api/context/query',{'sql':query_sql},token)['rows'] == [[row['id']]] |
| 121 | + request('POST', records + 'users/auth-refresh', {}, token) |
| 122 | + for identity in (token,admin): |
| 123 | + request('POST',records + write_table + '/records',payload,identity,503) |
| 124 | + request('PATCH',records + write_table + '/records/' + row['id'],{'expected_revision':1},identity,503) |
| 125 | + request('POST','/api/batch',{'requests':[{'method':'POST','url':records + write_table + '/records','body':payload}]},identity,503) |
| 126 | + request('POST', records + 'issues/records', {'project':row['id'],'title':'Blocked'}, token,503) |
| 127 | + frozen_restart(args.binary, request, admin, token, frozen) |
| 128 | + request('PUT','/api/context/maintenance',{'readOnly':False,'expectedGeneration':status['generation']},admin,409) |
| 129 | + thawed = request('PUT','/api/context/maintenance',{'readOnly':False,'expectedGeneration':frozen['generation']},admin) |
| 130 | + assert thawed['state'] == 'writable' |
| 131 | + issue = request('POST', records + 'issues/records', {'project':row['id'],'title':'After thaw'}, token) |
| 132 | + assert issue['key'] == 'FREEZE-2' |
| 133 | + print('PASS: maintenance authorization, mutation rejection, read access, frozen restart and thaw') |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == '__main__': |
| 137 | + main() |
0 commit comments