~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
123 lines · 6.2 KB Raw History
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
"""Exercise migration with a new disposable PLC account; deactivate it on exit."""
import argparse
import json
import os
import secrets
import sqlite3
import time
from urllib.request import Request, urlopen

import runpy
from pathlib import Path

request = runpy.run_path(str(Path(__file__).with_name('smoke-migration.py')))['request']


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source', required=True)
    parser.add_argument('--target', required=True)
    parser.add_argument('--target-db')
    args = parser.parse_args()
    source, target = args.source.rstrip('/'), args.target.rstrip('/')
    password = secrets.token_urlsafe(32)
    name = 'mig-' + secrets.token_hex(5)
    accounts = []

    def call(base, method, nsid, **kw):
        start = time.monotonic()
        result = request(base, method, 'com.atproto.' + nsid, **kw)
        outcome = 'rejected ' + kw['error'] if kw.get('error') else 'ok'
        print(f'{base} {nsid}: {outcome} ({(time.monotonic() - start) * 1000:.0f} ms)', flush=True)
        return result

    def create(base, admin, did=None, service_token=None):
        desc = call(base, 'GET', 'server.describeServer')
        body = {'handle': name + desc['availableUserDomains'][0],
                'email': name + '@example.invalid', 'password': password}
        if desc.get('inviteCodeRequired'):
            body['inviteCode'] = call(base, 'POST', 'server.createInviteCode', token=admin,
                                      body={'useCount': 1})['code']
        if did:
            body['did'] = did
        account = call(base, 'POST', 'server.createAccount', token=service_token, body=body)
        accounts.append((base, account['accessJwt']))
        return account

    def upload(base, token, data):
        req = Request(base + '/xrpc/com.atproto.repo.uploadBlob', data=data, method='POST',
                      headers={'authorization': 'Bearer ' + token, 'content-type': 'text/plain'})
        with urlopen(req, timeout=30) as res:
            return json.load(res)['blob']

    try:
        old = create(source, os.environ.get('ZDS_ADMIN_TOKEN'))
        did, old_token = old['did'], old['accessJwt']
        print('throwaway DID:', did, flush=True)
        payload = ('ZDS migration verification ' + name).encode()
        blob = upload(source, old_token, payload)
        cid = blob['ref']['$link']
        record = {'$type': 'dev.zds.migration.check', 'text': name, 'blob': blob}
        created = call(source, 'POST', 'repo.createRecord', token=old_token,
                       body={'repo': did, 'collection': record['$type'], 'rkey': 'check',
                             'validate': False, 'record': record})
        car = call(source, 'GET', 'sync.getRepo', params={'did': did})
        if source == target:
            new = old
            call(target, 'POST', 'server.deactivateAccount', token=old_token, body={})
        else:
            desc = call(target, 'GET', 'server.describeServer')
            auth = call(source, 'GET', 'server.getServiceAuth', token=old_token,
                        params={'aud': desc['did'], 'lxm': 'com.atproto.server.createAccount'})
            new = create(target, os.environ.get('ZDS_TARGET_ADMIN_TOKEN'), did, auth['token'])
        token = new['accessJwt']
        session = call(target, 'POST', 'server.createSession', body={'identifier': did, 'password': password})
        assert session['active'] is False
        token = session['accessJwt']
        initial = call(target, 'GET', 'server.checkAccountStatus', token=token)
        if source != target:
            assert initial['indexedRecords'] == 0 and initial['activated'] is False, initial
            local_car = call(target, 'GET', 'sync.getRepo', token=token, params={'did': did})
            call(target, 'POST', 'repo.importRepo', token=token, body=local_car, error='InvalidRequest')

        def events():
            if args.target_db:
                with sqlite3.connect(args.target_db) as conn:
                    return conn.execute('SELECT count(*) FROM seq_events WHERE did = ?', (did,)).fetchone()[0]

        before_events = events()
        call(target, 'POST', 'repo.importRepo', token=token, body=car)
        call(target, 'POST', 'repo.importRepo', token=token, body=car)
        assert events() == before_events, 'inactive import published sync events'
        after = call(target, 'GET', 'server.checkAccountStatus', token=token)
        assert after['activated'] is False and after['indexedRecords'] == 1, after
        missing = call(target, 'GET', 'repo.listMissingBlobs', token=token)['blobs']
        if source != target:
            assert [b['cid'] for b in missing] == [cid], missing
        assert upload(target, token, payload)['ref']['$link'] == cid
        assert call(target, 'GET', 'repo.listMissingBlobs', token=token)['blobs'] == []
        call(target, 'POST', 'repo.importRepo', token=token, body=car[:-1], error='InvalidRequest')
        call(target, 'POST', 'repo.createRecord', token=token, body={}, error='RepoDeactivated')
        call(target, 'GET', 'sync.getRepo', params={'did': did}, error='RepoDeactivated')
        assert call(target, 'GET', 'sync.getBlob', token=token, params={'did': did, 'cid': cid}) == payload
        call(target, 'GET', 'sync.getRepo', token=token, params={'did': did})
        call(target, 'POST', 'server.activateAccount', token=token, body={})
        result = call(target, 'GET', 'repo.getRecord',
                      params={'repo': did, 'collection': record['$type'], 'rkey': 'check'})
        assert result['cid'] == created['cid'] and result['value'] == record, result
        assert call(target, 'GET', 'sync.getBlob', params={'did': did, 'cid': cid}) == payload
        print('PASS: signed CAR import/retry, blob transfer, inactive privacy, activation and exact record/blob reads', flush=True)
        print('Identity remains on the source PDS; this probe does not submit a PLC migration operation.', flush=True)
    finally:
        for base, token in reversed(accounts):
            call(base, 'POST', 'server.deactivateAccount', token=token, body={})
        print('Throwaway accounts deactivated.', flush=True)


if __name__ == '__main__':
    main()