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

zat.dev/zds

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

0
0
252 lines · 9.6 KB Raw History
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = ["moto[server]==5.2.5", "boto3==1.44.9"]
# ///
"""Run zds against a local S3 stand-in that checks SigV4 signatures (moto
with IAM auth on) and check the blob mirror end to end: backfill of blobs
that predate the mirror, mirroring of new uploads, fetching a blob back when
its file is gone, refusing bucket bytes that do not hash to the CID, and
removing the bucket's copies when the account is deleted.

Run after `zig build`; `just smoke-blob-mirror` does both."""
import json
import os
import socket
import sqlite3
import subprocess
import sys
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

import boto3
import botocore

root = Path(__file__).resolve().parent.parent
zds_bin = root / 'zig-out/bin/zds'
work = Path(tempfile.mkdtemp(prefix='zds-smoke-blob-mirror.'))
db = work / 'zds.sqlite3'
blob_root = work / 'blobs'
bucket = 'zds-smoke-mirror'
prefix = 'blobs/'
admin = 'smoke-admin-token'
children = []


def free_port():
    with socket.socket() as s:
        s.bind(('127.0.0.1', 0))
        return s.getsockname()[1]


def wait_for(what, check, timeout=60):
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if check():
            return
        time.sleep(0.25)
    raise AssertionError(f'timed out waiting for {what}')


# moto checks signatures only once IAM auth is on, which it turns on after
# this many unauthenticated calls: the ones that make the user and its key.
s3_port = free_port()
s3_url = f'http://127.0.0.1:{s3_port}'
children.append(subprocess.Popen(
    [sys.executable, '-m', 'moto.server', '-H', '127.0.0.1', '-p', str(s3_port)],
    env={**os.environ, 'INITIAL_NO_AUTH_ACTION_COUNT': '3'},
    stdout=open(work / 's3.log', 'w'), stderr=subprocess.STDOUT))


def s3_up():
    try:
        urlopen(s3_url + '/moto-api/', timeout=1)
        return True
    except Exception:
        return False


wait_for('the S3 stand-in', s3_up)
boot = dict(endpoint_url=s3_url, region_name='us-east-1', aws_access_key_id='boot', aws_secret_access_key='boot')
iam = boto3.client('iam', **boot)
iam.create_user(UserName='zds')
iam.put_user_policy(UserName='zds', PolicyName='all', PolicyDocument=json.dumps(
    {'Version': '2012-10-17', 'Statement': [{'Effect': 'Allow', 'Action': '*', 'Resource': '*'}]}))
key = iam.create_access_key(UserName='zds')['AccessKey']
s3 = boto3.client('s3', endpoint_url=s3_url, region_name='us-east-1',
                  aws_access_key_id=key['AccessKeyId'], aws_secret_access_key=key['SecretAccessKey'])
s3.create_bucket(Bucket=bucket)
wrong = boto3.client('s3', endpoint_url=s3_url, region_name='us-east-1',
                     aws_access_key_id=key['AccessKeyId'], aws_secret_access_key='not-' + key['SecretAccessKey'])
try:
    wrong.list_objects_v2(Bucket=bucket)
    raise AssertionError('the S3 stand-in accepted a bad signature, so it would not check zds')
except botocore.exceptions.ClientError as exc:
    assert exc.response['Error']['Code'] == 'SignatureDoesNotMatch', exc.response


class Plc(BaseHTTPRequestHandler):
    """Accepts every genesis operation, which is all createAccount needs."""

    def do_POST(self):
        self.rfile.read(int(self.headers.get('content-length', 0)))
        self.send_response(200)
        self.end_headers()

    def do_GET(self):
        self.send_response(404)
        self.end_headers()

    def log_message(self, *args):
        pass


plc = HTTPServer(('127.0.0.1', 0), Plc)
threading.Thread(target=plc.serve_forever, daemon=True).start()

zds_port = free_port()
base = f'http://127.0.0.1:{zds_port}'
zds_log = open(work / 'zds.log', 'w')
zds = None


def start_zds(mirror):
    global zds
    env = {k: v for k, v in os.environ.items() if not k.startswith('AWS_') and not k.startswith('ZDS_')}
    env.update({
        'ZDS_HOST': '127.0.0.1', 'ZDS_PORT': str(zds_port), 'ZDS_PUBLIC_URL': base,
        'ZDS_SERVER_DID': 'did:web:localhost', 'ZDS_DB': str(db), 'ZDS_BLOBSTORE_PATH': str(blob_root),
        'ZDS_JWT_SECRET': 'smoke-jwt-secret', 'ZDS_ADMIN_TOKEN': admin, 'ZDS_HANDLE_DOMAINS': '.test',
        'ZDS_CRAWLERS': '', 'ZDS_MAIL_PROVIDER': 'outbox', 'ZDS_ALLOW_PRIVATE_FETCH': 'true',
        'ZDS_PLC_DIRECTORY': f'http://127.0.0.1:{plc.server_port}',
        'ZDS_PLC_ROTATION_KEY': '1' * 64,
    })
    if mirror:
        env.update({
            'ZDS_BLOB_MIRROR_BUCKET': bucket, 'ZDS_BLOB_MIRROR_PATH_STYLE': 'true',
            'AWS_ENDPOINT_URL_S3': s3_url, 'AWS_REGION': 'us-east-1',
            'AWS_ACCESS_KEY_ID': key['AccessKeyId'], 'AWS_SECRET_ACCESS_KEY': key['SecretAccessKey'],
        })
    zds = subprocess.Popen([str(zds_bin)], env=env, stdout=zds_log, stderr=subprocess.STDOUT)
    children.append(zds)

    def up():
        assert zds.poll() is None, f'zds exited; log: {work / "zds.log"}'
        try:
            urlopen(base + '/xrpc/_health', timeout=1)
            return True
        except Exception:
            return False

    wait_for('zds', up)


def stop_zds():
    zds.terminate()
    zds.wait(timeout=20)


def call(method, body=None, token=None, mime='application/json', status=200, params=None):
    headers = {}
    if token:
        headers['authorization'] = 'Bearer ' + token
    if mime is not None and body is not None:
        headers['content-type'] = mime
    if isinstance(body, dict):
        body = json.dumps(body).encode()
    url = base + '/xrpc/' + method + ('?' + urlencode(params) if params else '')
    try:
        with urlopen(Request(url, data=body, headers=headers), timeout=30) as response:
            code, data, content_type = response.status, response.read(), response.headers.get('content-type', '')
    except HTTPError as exc:
        code, data, content_type = exc.code, exc.read(), exc.headers.get('content-type', '')
    assert code == status, (method, code, data)
    return json.loads(data) if 'json' in content_type else data


def storage(did, cid):
    with sqlite3.connect(db) as connection:
        row = connection.execute('select storage from blobs where did = ? and cid = ?', (did, cid)).fetchone()
    return row[0] if row else None


def object_bytes(did, cid):
    try:
        return s3.get_object(Bucket=bucket, Key=f'{prefix}{did}/{cid}')['Body'].read()
    except s3.exceptions.NoSuchKey:
        return None


def upload(token, data, mime='application/octet-stream'):
    return call('com.atproto.repo.uploadBlob', data, token, mime)['blob']


try:
    # 1. blobs uploaded before the mirror existed are backfilled.
    start_zds(mirror=False)
    account = call('com.atproto.server.createAccount', {
        'handle': 'mirror.test', 'email': 'mirror@test.com', 'password': 'mirror-password'})
    did, token = account['did'], account['accessJwt']
    before = [os.urandom(n) for n in (1, 70 * 1024, 2 * 1024 * 1024)]
    old = [upload(token, data) for data in before]
    for blob in old:
        call('com.atproto.repo.createRecord', {'repo': did, 'collection': 'test.mirror.record',
                                               'record': {'$type': 'test.mirror.record', 'file': blob}}, token)
    assert all(storage(did, b['ref']['$link']) == 'disk' for b in old)
    stop_zds()

    start_zds(mirror=True)
    wait_for('the backfill', lambda: all(storage(did, b['ref']['$link']) == 's3' for b in old))
    for blob, data in zip(old, before):
        assert object_bytes(did, blob['ref']['$link']) == data
    print('ok   blobs from before the mirror are copied to the bucket, signed')

    # 2. a new upload follows within a round.
    data = os.urandom(300 * 1024)
    new = upload(token, data)
    call('com.atproto.repo.createRecord', {'repo': did, 'collection': 'test.mirror.record',
                                           'record': {'$type': 'test.mirror.record', 'file': new}}, token)
    wait_for('the new upload to be mirrored', lambda: storage(did, new['ref']['$link']) == 's3', timeout=90)
    assert object_bytes(did, new['ref']['$link']) == data
    print('ok   a new upload is copied to the bucket')

    # 3. a blob whose file is gone is fetched back from the bucket.
    cid = old[2]['ref']['$link']
    (blob_root / did / cid).unlink()
    assert call('com.atproto.sync.getBlob', params={'did': did, 'cid': cid}) == before[2]
    assert (blob_root / did / cid).read_bytes() == before[2]
    print('ok   a missing file is fetched back from the bucket and kept')

    # 4. bucket bytes that do not hash to the CID are refused.
    cid = old[1]['ref']['$link']
    s3.put_object(Bucket=bucket, Key=f'{prefix}{did}/{cid}', Body=b'not the blob')
    (blob_root / did / cid).unlink()
    call('com.atproto.sync.getBlob', params={'did': did, 'cid': cid}, status=404)
    assert not (blob_root / did / cid).exists()
    assert 'reason=digest_mismatch' in (work / 'zds.log').read_text()
    print('ok   bucket bytes that do not match the CID are refused')

    # 5. deleting the account removes its copies from the bucket.
    call('com.atproto.admin.deleteAccount', {'did': did}, admin)
    wait_for('the bucket copies to go', lambda: s3.list_objects_v2(Bucket=bucket, Prefix=f'{prefix}{did}/')['KeyCount'] == 0, timeout=90)
    assert not list((blob_root / '.mirror-deletes').iterdir())
    print('ok   deleting the account deletes its bucket copies')
    stop_zds()
    print('blob mirror smoke passed')
except BaseException:
    print(f'blob mirror smoke failed; diagnostic files: {work}', file=sys.stderr)
    raise
else:
    import shutil
    shutil.rmtree(work)
finally:
    for child in children:
        if child.poll() is None:
            child.terminate()
            child.wait(timeout=20)