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

zat.dev/zds

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

0
0
210 lines · 12.0 KB Raw History
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
import base64
import hashlib
import json
import os
import sqlite3
import sys
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen


def request(base, method, nsid, token=None, body=None, params=None, error=None, code=None, basic=None):
    headers = {}
    if token:
        headers['authorization'] = 'Bearer ' + token
    if basic:
        headers['authorization'] = 'Basic ' + base64.b64encode(basic.encode()).decode()
    if isinstance(body, bytes):
        headers['content-type'] = 'application/vnd.ipld.car'
    elif body is not None:
        headers['content-type'] = 'application/json'
        body = json.dumps(body).encode()
    url = base + '/xrpc/' + nsid
    if params:
        url += '?' + urlencode(params)
    try:
        with urlopen(Request(url, data=body, headers=headers, method=method), timeout=30) as res:
            data = res.read()
            result = json.loads(data) if 'json' in res.headers.get('content-type', '') else data
    except HTTPError as exc:
        result = json.loads(exc.read())
        assert error and result.get('error') == error, (nsid, exc.code, result)
        assert code is None or exc.code == code, (nsid, exc.code, result)
        return result
    assert error is None, (nsid, 'unexpected success', error)
    return result


def varint(n):
    out = bytearray()
    while n >= 0x80:
        out.append(n & 0x7F | 0x80)
        n >>= 7
    out.append(n)
    return bytes(out)


def pad_car(car, count):
    # Appends `count` unreferenced DAG-CBOR blocks: a whole-repo CAR past
    # the 10,000-block firehose-frame limit, with the commit left intact.
    sections = bytearray(car)
    for i in range(count):
        data = b'\x58\x08' + i.to_bytes(8, 'big')
        cid = b'\x01\x71\x12\x20' + hashlib.sha256(data).digest()
        sections += varint(len(cid) + len(data)) + cid + data
    return bytes(sections)


def main():
    base, db, did, cid = sys.argv[1:]
    token = os.environ['ZDS_SMOKE_TOKEN']
    other = os.environ['ZDS_SMOKE_OTHER_TOKEN']
    admin = 'smoke-admin-token'
    call = lambda method, nsid, **kw: request(base, method, nsid, **kw)
    records = call('GET', 'com.atproto.repo.listRecords', params={'repo': did, 'collection': 'app.bsky.feed.post'})['records']
    rkey = records[0]['uri'].rsplit('/', 1)[1]
    other_did = call('GET', 'com.atproto.server.getSession', token=other)['did']
    other_car = call('GET', 'com.atproto.sync.getRepo', params={'did': other_did})
    call('POST', 'com.atproto.server.deactivateAccount', token=token, body={})
    session = call('POST', 'com.atproto.server.createSession',
                   body={'identifier': did, 'password': 'password'})
    assert session['active'] is False
    token = session['accessJwt']
    call('GET', 'com.atproto.server.checkAccountStatus', token=token)
    call('GET', 'com.atproto.repo.listMissingBlobs', token=token)
    call('POST', 'com.atproto.repo.uploadBlob', token=token, body=b'migration smoke')
    call('POST', 'com.atproto.repo.importRepo', token=token, body=b'invalid CAR', error='InvalidRequest')
    call('POST', 'com.atproto.repo.importRepo', token=token, body=other_car, error='InvalidRequest')
    own_car = call('GET', 'com.atproto.sync.getRepo', token=token, params={'did': did})
    big = request(base, 'POST', 'com.atproto.repo.importRepo', token=token, body=pad_car(own_car, 10_001), error='DidResolutionFailed')
    assert big['message'] != 'invalid repo CAR', big
    exports = [
        ('getRepo', {'did': did}),
        ('getBlob', {'did': did, 'cid': cid}),
        ('getLatestCommit', {'did': did}),
        ('listBlobs', {'did': did}),
        ('getRecord', {'did': did, 'collection': 'app.bsky.feed.post', 'rkey': rkey}),
    ]
    for method, params in exports:
        nsid = 'com.atproto.sync.' + method
        call('GET', nsid, token=token, params=params)
        call('GET', nsid, params=params, error='RepoDeactivated')
        call('GET', nsid, token=other, params=params, error='RepoDeactivated')
    blob_url = base + '/xrpc/com.atproto.sync.getBlob?' + urlencode({'did': did, 'cid': cid})
    with urlopen(Request(blob_url, headers={'authorization': 'Bearer ' + token}), timeout=30) as response:
        assert response.headers['cache-control'] == 'private, no-store'
        blob_len = len(response.read())
    # HEAD reports the blob's real size and sends no body.
    with urlopen(Request(blob_url, method='HEAD', headers={'authorization': 'Bearer ' + token}), timeout=30) as response:
        assert int(response.headers['content-length']) == blob_len > 0, (response.headers['content-length'], blob_len)
        assert response.read() == b''
    for method, params in exports:
        call('GET', 'com.atproto.sync.' + method, token=admin, params=params)
        call('GET', 'com.atproto.sync.' + method, basic='admin:smoke-admin-token', params=params)
    for method in ('createRecord', 'putRecord', 'deleteRecord', 'applyWrites'):
        call('POST', 'com.atproto.repo.' + method, token=token, body={}, error='AccountDeactivated', code=401)
    call('POST', 'com.atproto.server.activateAccount', token=token, body={})
    try:
        for status, error, account_error, account_code in [('takendown', 'RepoTakendown', 'AccountTakedown', 401),
                                                           ('suspended', 'RepoSuspended', 'AccountSuspended', 401),
                                                           ('deleted', 'RepoNotFound', 'AccountNotFound', 403)]:
            with sqlite3.connect(db) as conn:
                conn.execute('UPDATE accounts SET account_status = ? WHERE did = ?', (status, did))
            for method, body in [('importRepo', b'invalid'), ('uploadBlob', b'blob')]:
                call('POST', 'com.atproto.repo.' + method, token=token, body=body, error=account_error, code=account_code)
            call('GET', 'com.atproto.repo.listMissingBlobs', token=token)
            for method, params in exports:
                nsid = 'com.atproto.sync.' + method
                if status == 'deleted':
                    call('GET', nsid, token=admin, params=params, error=error)
                else:
                    call('GET', nsid, token=admin, params=params)
                if status == 'takendown':
                    # The account can still export its own repo to move away.
                    call('GET', nsid, token=token, params=params)
                    call('GET', nsid, params=params, error=error)
                    call('GET', nsid, token=other, params=params, error=error)
                else:
                    call('GET', nsid, token=token, params=params, error=error)
    finally:
        with sqlite3.connect(db) as conn:
            conn.execute("UPDATE accounts SET account_status = 'active' WHERE did = ?", (did,))
    call('POST', 'com.atproto.admin.updateSubjectStatus', token=admin,
         body={'subject': {'$type': 'com.atproto.admin.defs#repoRef', 'did': did},
               'takedown': {'applied': True}})
    # A takedown ends refresh tokens only: an existing access token learns why.
    call('POST', 'com.atproto.repo.createRecord', token=token, body={}, error='AccountTakedown', code=401)
    call('GET', 'com.atproto.server.getSession', token=token)
    call('GET', 'com.atproto.sync.getRepo', params={'did': did}, error='RepoTakendown')
    # A taken-down account signs in with allowTakendown to a session that can
    # export its data and move its identity, and nothing else.
    credentials = {'identifier': did, 'password': 'password'}
    call('POST', 'com.atproto.server.createSession', body=credentials, error='AccountTakedown')
    call('POST', 'com.atproto.server.createSession', body={'identifier': did, 'password': 'wrong'}, error='AuthenticationRequired')
    limited = call('POST', 'com.atproto.server.createSession', body={**credentials, 'allowTakendown': True})
    assert limited['active'] is False and limited['status'] == 'takendown', limited
    taken = limited['accessJwt']
    for method in ('getRepo', 'getBlob', 'listBlobs'):
        call('GET', 'com.atproto.sync.' + method, token=taken, params=dict(exports)[method])
    for method in ('getLatestCommit', 'getRecord'):
        call('GET', 'com.atproto.sync.' + method, token=taken, params=dict(exports)[method], error='InvalidToken')
    call('GET', 'app.bsky.actor.getPreferences', token=taken)
    call('POST', 'com.atproto.identity.requestPlcOperationSignature', token=taken, body={})
    service = {'aud': 'did:web:new-host.example'}
    call('GET', 'com.atproto.server.getServiceAuth', token=taken, params={**service, 'lxm': 'com.atproto.server.createAccount'})
    call('GET', 'com.atproto.server.getServiceAuth', token=taken, params=service, error='InvalidToken')
    call('GET', 'com.atproto.server.getServiceAuth', token=taken, params={**service, 'lxm': 'app.bsky.feed.getTimeline'}, error='InvalidToken')
    call('POST', 'com.atproto.repo.createRecord', token=taken, body={}, error='InvalidToken', code=400)
    call('GET', 'com.atproto.repo.listMissingBlobs', token=taken, error='InvalidToken', code=400)
    call('POST', 'com.atproto.server.createAppPassword', token=taken, body={'name': 'escape'}, error='InvalidToken', code=400)
    # The takedown session reaches the appeal path, createReport, and no other
    # proxied method.
    def proxied(nsid, verb, body=None):
        headers = {'authorization': 'Bearer ' + taken, 'atproto-proxy': 'did:web:api.bsky.app#bsky_appview'}
        if body is not None:
            headers['content-type'] = 'application/json'
            body = json.dumps(body).encode()
        try:
            with urlopen(Request(base + '/xrpc/' + nsid, data=body, headers=headers, method=verb), timeout=30) as res:
                return res.status, res.read()
        except HTTPError as exc:
            return exc.code, exc.read()
    status, raw = proxied('app.bsky.feed.getTimeline', 'GET')
    assert status == 400 and json.loads(raw)['error'] == 'InvalidToken', (status, raw)
    status, raw = proxied('com.atproto.moderation.createReport', 'POST',
                          {'reasonType': 'com.atproto.moderation.defs#reasonAppeal',
                           'subject': {'$type': 'com.atproto.admin.defs#repoRef', 'did': did}})
    assert b'InvalidToken' not in raw and b'AuthenticationRequired' not in raw, (status, raw)
    refreshed = call('POST', 'com.atproto.server.refreshSession', token=limited['refreshJwt'])
    call('GET', 'com.atproto.sync.getRepo', token=refreshed['accessJwt'], params={'did': did})
    call('POST', 'com.atproto.repo.createRecord', token=refreshed['accessJwt'], body={}, error='InvalidToken')
    # Deactivating beneath a takedown keeps the takedown and outlasts it.
    call('POST', 'com.atproto.server.deactivateAccount', token=refreshed['accessJwt'], body={})
    call('GET', 'com.atproto.sync.getRepo', params={'did': did}, error='RepoTakendown')
    call('POST', 'com.atproto.admin.updateSubjectStatus', token=admin,
         body={'subject': {'$type': 'com.atproto.admin.defs#repoRef', 'did': did},
               'takedown': {'applied': False}})
    call('GET', 'com.atproto.sync.getRepo', params={'did': did}, error='RepoDeactivated')
    print('migration account-state smoke ok')
    call('POST', 'com.atproto.admin.deleteAccount', token=token, body={'did': did}, error='AdminRequired')
    call('POST', 'com.atproto.admin.deleteAccount', token=admin, body={'did': did})
    call('GET', 'com.atproto.sync.getRepo', params={'did': did}, error='RepoNotFound')
    call('GET', 'com.atproto.sync.getBlob', params={'did': did, 'cid': cid}, error='RepoNotFound')
    repos = call('GET', 'com.atproto.sync.listRepos')['repos']
    assert did not in [repo['did'] for repo in repos], repos
    assert other_did in [repo['did'] for repo in repos], repos
    call('POST', 'com.atproto.admin.deleteAccount', token=admin, body={'did': did}, error='AccountNotFound')
    with sqlite3.connect(db) as conn:
        events = conn.execute('SELECT COUNT(*) FROM seq_events WHERE did = ?', (did,)).fetchone()[0]
    assert events == 1, events
    print('admin account deletion smoke ok')


if __name__ == '__main__':
    main()