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

zat.dev/zds

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

0
0
856 lines · 58.3 KB Raw History
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
"""Exercise space policies and access using the disposable smoke server/accounts."""
import base64
import hashlib
import hmac
import http.server
import json
import os
import sqlite3
import subprocess
import threading
import time
import urllib.error
import urllib.parse
import urllib.request

base = os.environ['SMOKE_BASE']
owner = os.environ['SMOKE_TOKEN']
member = os.environ['SMOKE_BOB_TOKEN']
member_did = 'did:plc:spacesmokebob'
db = os.environ['SMOKE_DB']
member_policy = {'$type': 'com.atproto.memberspace.policy'}
public_policy = {'$type': 'com.atproto.memberspace.policy', 'publicRead': True}


def normalized(**fields):
    return {'$type': 'com.atproto.memberspace.policy', 'publicRead': False, 'publicWrite': False,
            **fields, 'publishPolicy': fields.get('publishPolicy', False), 'publishMembers': fields.get('publishMembers', False)}


def writers(space):
    with sqlite3.connect(db) as connection:
        return {row[0] for row in connection.execute('select repo_did from permissioned_space_writers where space = ? and removed_at is null', (space,))}


def removed(space):
    with sqlite3.connect(db) as connection:
        return {row[0] for row in connection.execute('select repo_did from permissioned_space_writers where space = ? and removed_at is not null', (space,))}


def call(method, body=None, token=owner, params=None, headers=None):
    url = base + '/xrpc/' + method
    if params:
        url += '?' + urllib.parse.urlencode(params)
    auth = {'authorization': 'Bearer ' + token} if token else {}
    request = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
                                    headers={**auth, 'content-type': 'application/json', **(headers or {})})
    try:
        response = urllib.request.urlopen(request, timeout=10)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        return response.status, json.load(response)


def expect(method, expected, **kwargs):
    status, body = call(method, **kwargs)
    assert status == expected, f'{method}: expected {expected}, got {status} ({body.get("error")})'
    return body


credential_kid = subprocess.check_output(['./zig-out/bin/zds-space-signature', 'kid'], text=True, stderr=subprocess.STDOUT).strip()


def request_credential(space, delegation, expected):
    body = {'space': space, 'credentialKey': credential_kid}
    if delegation:
        body['delegationToken'] = delegation
    return expect('com.atproto.space.authorizeSpaceSync', expected, token=None, body=body)


create = {'spaceType': 'test.access.space', 'skey': 'self', 'policy': member_policy}
space = expect('com.atproto.space.createSpace', 200, body=create)['space']
# The authority's own spaces exist only through createSpace.
unknown = space.replace('/self', '/missing')
assert expect('com.atproto.space.createRecord', 400, body={'space': unknown, 'repo': 'did:plc:permissionsmoke', 'collection': 'test.access.record',
              'record': {'$type': 'test.access.record', 'text': 'no space'}})['error'] == 'SpaceNotFound'
# Space records are bounded at 1 MiB of DRISL, separately from the public limit.
sized = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.sized'})['space']
for size, status in ((1024 * 1024 - 64, 200), (1024 * 1024 + 1, 400)):
    expect('com.atproto.space.putRecord', status, body={'space': sized, 'repo': 'did:plc:permissionsmoke', 'collection': 'test.access.record',
           'rkey': f'size-{status}', 'record': {'$type': 'test.access.record', 'text': 'x' * size}})
# The simplespace shapes and routes are gone.
simple = {'spaceType': 'test.access.obsolete', 'readPolicy': {'$type': 'com.atproto.simplespace.defs#memberListPolicy'},
          'writePolicy': {'$type': 'com.atproto.simplespace.defs#memberListPolicy'}, 'appAccess': {'$type': 'com.atproto.simplespace.defs#open'}}
assert expect('com.atproto.space.createSpace', 400, body=simple)['error'] == 'InvalidRequest'
assert expect('com.atproto.space.createSpace', 400, body={**simple, 'policy': simple['readPolicy']})['error'] == 'UnsupportedPolicy'
for method in ('createSpace', 'putMember', 'listMembers', 'checkUserAccess'):
    assert call('com.atproto.simplespace.' + method, body=simple)[0] == 404
for bad in ({'$type': 'com.atproto.managedspace.policy', 'managingApp': 'https://plyr.fm'}, {'$type': 'com.atproto.managedspace.policy', 'managingApp': 'did:web:plyr.fm'}, {'$type': 'com.atproto.memberspace.policy', 'publicRead': 'yes'}):
    assert expect('com.atproto.space.createSpace', 400, body={**create, 'skey': 'bad', 'policy': bad})['error'] == 'InvalidRequest'
assert expect('com.atproto.space.updateSpace', 400, body={'space': space})['error'] == 'InvalidRequest'
# allowedApps holds client IDs, which are URIs.
assert expect('com.atproto.space.createSpace', 400, body={**create, 'skey': 'bad', 'policy': {**member_policy, 'allowedApps': ['not a uri']}})['error'] == 'InvalidRequest'
# A cursor these lists did not hand out is refused.
for method, params in (('com.atproto.space.listSpaces', {}), ('com.atproto.memberspace.listMembers', {'space': space}),
                       ('com.atproto.space.listRecords', {'space': space, 'repo': 'did:plc:permissionsmoke'})):
    assert expect(method, 400, params={**params, 'cursor': 'not a cursor'})['error'] == 'InvalidCursor', method
for fields in ({'read': True}, {'read': 'true', 'write': True}, {'read': True, 'write': None}):
    expect('com.atproto.memberspace.putMembers', 400, body={'space': space, 'members': [{'did': member_did, **fields}]})
assert expect('com.atproto.memberspace.putMembers', 400, token=member, body={'space': space, 'members': [{'did': member_did, 'read': True, 'write': True}]})['error'] == 'NotAuthorized'
assert expect('com.atproto.memberspace.listMembers', 400, token=member, params={'space': space})['error'] == 'NotAuthorized'

for index, (read, write) in enumerate(((True, False), (False, True), (False, False), (True, True))):
    expect('com.atproto.memberspace.putMembers', 200, body={'space': space, 'members': [{'did': member_did, 'read': read, 'write': write}]})
    members = expect('com.atproto.memberspace.listMembers', 200, params={'space': space})['members']
    assert members == [{'did': member_did, 'read': read, 'write': write}], members
    expect('com.atproto.space.createRecord', 200, token=member,
           body={'space': space, 'repo': member_did, 'collection': 'test.access.record',
                 'rkey': f'case-{index}', 'record': {'$type': 'test.access.record', 'text': 'disposable'}})
    assert (member_did in writers(space)) == write
    delegation = expect('com.atproto.space.getDelegationToken', 200, token=member, params={'space': space})['token']
    outcome = request_credential(space, delegation, 200 if read else 400)
    assert read or outcome['error'] == 'SpaceNotFound'

# Revoking write removes the writer, kept as removed, and the next authorized
# write re-tracks it.
expect('com.atproto.memberspace.putMembers', 200, body={'space': space, 'members': [{'did': member_did, 'read': True, 'write': False}]})
assert member_did not in writers(space) and member_did in removed(space)
expect('com.atproto.memberspace.putMembers', 200, body={'space': space, 'members': [{'did': member_did, 'read': True, 'write': True}]})
expect('com.atproto.space.putRecord', 200, token=member, body={'space': space, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'case-3', 'record': {'$type': 'test.access.record', 'text': 'tracked again'}})
assert member_did in writers(space)
assert expect('com.atproto.space.removeWriter', 400, token=member, body={'space': space, 'repo': member_did})['error'] == 'NotAuthorized'
assert expect('com.atproto.space.removeWriter', 400, body={'space': unknown, 'repo': member_did})['error'] == 'SpaceNotFound'
for _ in range(2):
    expect('com.atproto.space.removeWriter', 200, body={'space': space, 'repo': member_did})
assert member_did not in writers(space) and member_did in removed(space)
expect('com.atproto.space.putRecord', 200, token=member, body={'space': space, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'case-3', 'record': {'$type': 'test.access.record', 'text': 'tracked once more'}})
assert member_did in writers(space)
# listSpaces shows each caller its own repo state in the space, and the authority
# the space's latest revision.
def listed(token):
    spaces = expect('com.atproto.space.listSpaces', 200, token=token, params={'spaceDid': 'did:plc:permissionsmoke', 'spaceType': 'test.access.space'})['spaces']
    return next(entry for entry in spaces if entry['space'] == space)
as_member, as_owner = listed(member), listed(owner)
assert as_member['repoRev'] and as_member['data']['$bytes'] and 'spaceRev' not in as_member, as_member
assert len(as_owner['spaceRev']) == 13, as_owner

# getSpace is the owner's, read wholesale; a personalspace admits only the owner.
assert expect('com.atproto.space.getSpace', 200, params={'space': space}) == {'space': space, 'policy': normalized()}
assert expect('com.atproto.space.getSpace', 400, token=member, params={'space': space})['error'] == 'NotAuthorized'
personal = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.personal',
                  'policy': {'$type': 'com.atproto.personalspace.policy', 'publicRead': True}})['space']
assert expect('com.atproto.space.getSpace', 200, params={'space': personal})['policy'] == {'$type': 'com.atproto.personalspace.policy'}
assert expect('com.atproto.memberspace.putMembers', 400, body={'space': personal, 'members': [{'did': member_did, 'read': True, 'write': True}]})['error'] == 'PolicyMismatch'
personal_delegation = expect('com.atproto.space.getDelegationToken', 200, token=member, params={'space': personal})['token']
assert request_credential(personal, personal_delegation, 400)['error'] == 'SpaceNotFound'
assert request_credential(personal, None, 400)['error'] == 'SpaceNotFound'
owner_delegation = expect('com.atproto.space.getDelegationToken', 200, params={'space': personal})['token']
request_credential(personal, owner_delegation, 200)

# allowedApps is judged after the user: a refused user learns nothing, an
# admitted one without an attested app is told the app is not allowed.
gated = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.gated',
               'policy': {**public_policy, 'allowedApps': ['https://app.test/client.json']}})['space']
assert request_credential(gated, None, 400)['error'] == 'AppNotAuthorized'
expect('com.atproto.space.updateSpace', 200, body={'space': gated, 'policy': {**member_policy, 'allowedApps': ['https://app.test/client.json']}})
gated_delegation = expect('com.atproto.space.getDelegationToken', 200, token=member, params={'space': gated})['token']
assert request_credential(gated, gated_delegation, 400)['error'] == 'SpaceNotFound'
expect('com.atproto.memberspace.putMembers', 200, body={'space': gated, 'members': [{'did': member_did, 'read': True, 'write': False}]})
gated_delegation = expect('com.atproto.space.getDelegationToken', 200, token=member, params={'space': gated})['token']
assert request_credential(gated, gated_delegation, 400)['error'] == 'AppNotAuthorized'

# putMembers and removeMembers change up to 100 members in one commit; a DID
# listed twice takes its last entry, and removing a non-member is a no-op.
batch = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.batch'})['space']
expect('com.atproto.memberspace.putMembers', 200, body={'space': batch, 'members': [
    {'did': member_did, 'read': True, 'write': True}, {'did': 'did:plc:spacesmokecarol', 'read': True, 'write': False},
    {'did': member_did, 'read': True, 'write': False}]})
assert {m['did']: m['write'] for m in expect('com.atproto.memberspace.listMembers', 200, params={'space': batch})['members']} == {member_did: False, 'did:plc:spacesmokecarol': False}
assert expect('com.atproto.memberspace.putMembers', 400, body={'space': batch, 'members': [{'did': member_did, 'read': True, 'write': True}] * 101})['error'] == 'InvalidRequest'
assert expect('com.atproto.memberspace.putMembers', 400, token=member, body={'space': batch, 'members': []})['error'] == 'NotAuthorized'
expect('com.atproto.memberspace.removeMembers', 200, body={'space': batch, 'dids': ['did:plc:spacesmokecarol', 'did:plc:spacesmokenobody']})
assert [m['did'] for m in expect('com.atproto.memberspace.listMembers', 200, params={'space': batch})['members']] == [member_did]
assert expect('com.atproto.memberspace.removeMembers', 400, body={'space': personal, 'dids': [member_did]})['error'] == 'PolicyMismatch'

# Published configuration lives in the authority's repo and follows the policy.
published = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.published',
                   'policy': {**member_policy, 'publishPolicy': True, 'publishMembers': True}})['space']


def published_record(collection, rkey, expected=200):
    return expect('com.atproto.space.getRecord', expected, params={'space': published, 'repo': 'did:plc:permissionsmoke', 'collection': collection, 'rkey': rkey})


policy_record = published_record('com.atproto.space.policy', 'self')['value']
assert policy_record == {'$type': 'com.atproto.space.policy', 'policy': normalized(publishPolicy=True, publishMembers=True)}, policy_record
expect('com.atproto.memberspace.putMembers', 200, body={'space': published, 'members': [{'did': member_did, 'read': True, 'write': True}]})
assert published_record('com.atproto.memberspace.member', member_did)['value'] == {'$type': 'com.atproto.memberspace.member', 'read': True, 'write': True}
expect('com.atproto.memberspace.putMembers', 200, body={'space': published, 'members': [{'did': member_did, 'read': True, 'write': False}]})
assert published_record('com.atproto.memberspace.member', member_did)['value'] == {'$type': 'com.atproto.memberspace.member', 'read': True, 'write': False}
expect('com.atproto.space.updateSpace', 200, body={'space': published, 'policy': {**member_policy, 'publishMembers': True}})
published_record('com.atproto.space.policy', 'self', 404)
published_record('com.atproto.memberspace.member', member_did)
expect('com.atproto.memberspace.removeMembers', 200, body={'space': published, 'dids': [member_did]})
published_record('com.atproto.memberspace.member', member_did, 404)
expect('com.atproto.space.updateSpace', 200, body={'space': published, 'policy': {**member_policy, 'publishPolicy': True}})
for collection, rkey in (('com.atproto.space.policy', 'self'), ('com.atproto.memberspace.member', member_did)):
    record = {'$type': collection, 'read': True, 'write': True}
    for token, repo in ((owner, 'did:plc:permissionsmoke'), (member, member_did)):
        target = {'space': published, 'repo': repo, 'collection': collection, 'rkey': rkey}
        expect('com.atproto.space.createRecord', 400, token=token, body={**target, 'record': record})
        expect('com.atproto.space.putRecord', 400, token=token, body={**target, 'record': record})
        expect('com.atproto.space.deleteRecord', 400, token=token, body=target)
        expect('com.atproto.space.applyWrites', 400, token=token, body={'space': published, 'repo': repo, 'writes': [
            {'$type': 'com.atproto.space.applyWrites#create', 'collection': collection, 'rkey': rkey, 'value': record}]})
assert published_record('com.atproto.space.policy', 'self')['value']['policy'] == normalized(publishPolicy=True)

# A managing-app space asks the app over service auth before granting anyone
# but the authority. The stub is both the PLC directory that resolves the app's
# DID and the app itself.
stub_port = int(os.environ['SMOKE_STUB_PORT'])
managing_app = 'did:plc:spacesmokeapp#smoke_app'
checks = []
answer = {'status': 200, 'body': {'read': True, 'write': True}}
# The stub is also a syncer: it confirms registrations for the tokens it
# issued, and records each notifySpaceUpdate with the authorization it carried.
issued_tokens = set()
confirmations = []
space_updates = []
# (token, update $type) pairs the syncer rejects, and how many times it fails a
# delivery before accepting it.
rejected_updates = set()
failures_left = {}


class ManagingApp(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        url = urllib.parse.urlsplit(self.path)
        if url.path == '/did:plc:spacesmokeapp':
            status, body = 200, {'id': 'did:plc:spacesmokeapp', 'service': [
                {'id': '#smoke_app', 'type': 'SmokeManagingApp', 'serviceEndpoint': f'http://127.0.0.1:{stub_port}'}]}
        elif url.path == '/xrpc/com.atproto.managedspace.checkAccess':
            token = self.headers.get('authorization', '').removeprefix('Bearer ')
            claims = json.loads(base64.urlsafe_b64decode(token.split('.')[1] + '==='))
            checks.append((dict(urllib.parse.parse_qsl(url.query)), claims))
            status, body = answer['status'], answer['body']
        else:
            status, body = 404, {'message': 'not found'}
        payload = json.dumps(body).encode()
        self.send_response(status)
        self.send_header('content-type', 'application/json')
        self.send_header('content-length', str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers['content-length'])))
        if self.path == '/xrpc/com.atproto.space.confirmRegistration':
            confirmations.append(body)
            known = (body['space'], body['token']) in issued_tokens
            self.reply(200 if known else 400, {'challenge': body['challenge']} if known else {'error': 'InvalidRequest'})
        elif self.path == '/xrpc/com.atproto.space.notifySpaceUpdate':
            space_updates.append((body, self.headers.get('authorization')))
            kind = (body['token'], body['update']['$type'])
            if kind in rejected_updates:
                self.reply(400, {'error': 'InvalidRequest'})
            elif failures_left.get(kind, 0) > 0:
                failures_left[kind] -= 1
                self.reply(503, {'error': 'Unavailable'})
            else:
                self.reply(200, {})
        else:
            self.reply(404, {'message': 'not found'})

    def reply(self, status, body):
        payload = json.dumps(body).encode()
        self.send_response(status)
        self.send_header('content-type', 'application/json')
        self.send_header('content-length', str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def log_message(self, *args):
        pass


stub = http.server.ThreadingHTTPServer(('127.0.0.1', stub_port), ManagingApp)
threading.Thread(target=stub.serve_forever, daemon=True).start()
app_policy = {'$type': 'com.atproto.managedspace.policy', 'managingApp': managing_app}
managed = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.managed', 'policy': app_policy})['space']
assert expect('com.atproto.memberspace.listMembers', 400, params={'space': managed})['error'] == 'PolicyMismatch'


def managed_credential(expected):
    token = expect('com.atproto.space.getDelegationToken', 200, token=member, params={'space': managed})['token']
    return request_credential(managed, token, expected)


# Without a delegation token the app is asked about an anonymous reader, with no repo.
answer.update(status=200, body={'read': False, 'write': False})
assert request_credential(managed, None, 400)['error'] == 'SpaceNotFound'
assert checks[-1][0] == {'space': managed}, checks[-1]
answer.update(status=200, body={'read': True, 'write': True})
managed_credential(200)
params, claims = checks[-1]
assert params == {'space': managed, 'repo': member_did}, params
assert (claims['iss'], claims['aud'], claims['lxm']) == (
    'did:plc:permissionsmoke', managing_app, 'com.atproto.managedspace.checkAccess'), claims
# Writes are asked about too, without a client identity.
expect('com.atproto.space.createRecord', 200, token=member, body={'space': managed, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'managed-write', 'record': {'$type': 'test.access.record', 'text': 'managed'}})
assert checks[-1][0] == {'space': managed, 'repo': member_did}, checks[-1]
assert member_did in writers(managed)
# An answer of false is a refusal; an app that fails to answer is an upstream
# failure, not a refusal. Exactly one access check per credential request.
for reply, status, error in (({'status': 200, 'body': {'read': False, 'write': True}}, 400, 'SpaceNotFound'),
                             ({'status': 200, 'body': {}}, 502, 'UpstreamFailure'),
                             ({'status': 200, 'body': {'read': 'yes', 'write': True}}, 502, 'UpstreamFailure'),
                             ({'status': 401, 'body': {'error': 'AuthenticationRequired'}}, 502, 'UpstreamFailure'),
                             ({'status': 500, 'body': {}}, 502, 'UpstreamFailure')):
    answer.update(reply)
    asked = len(checks)
    refusal = managed_credential(status)
    assert refusal['error'] == error, (reply, refusal)
    assert len(checks) == asked + 1, (reply, [params for params, _ in checks[asked:]])
# A write the app can't vouch for is answered UpstreamFailure, so the repo host retries.
writer_check = expect('com.atproto.server.getServiceAuth', 200, token=member,
                      params={'aud': 'did:plc:permissionsmoke#atproto_pds', 'lxm': 'com.atproto.space.notifyRepoUpdate'})['token']
managed_state = expect('com.atproto.space.getLatestCommit', 200, token=member, params={'space': managed, 'repo': member_did})['commit']
assert expect('com.atproto.space.notifyRepoUpdate', 502, token=writer_check, body={'space': managed, 'repo': member_did,
              'repoRev': managed_state['rev'], 'data': managed_state['data']})['error'] == 'UpstreamFailure'
# Nor does it withdraw a syncer's registration.
issued_tokens.add((managed, 'managed'))
answer.update(status=200, body={'read': True, 'write': True})
managed_notify = {'endpoint': f'http://127.0.0.1:{stub_port}', 'token': 'managed'}
expect('com.atproto.space.authorizeSpaceSync', 200, token=None, body={'space': managed, 'credentialKey': credential_kid, 'notify': managed_notify})
answer.update(status=500, body={})
assert expect('com.atproto.space.authorizeSpaceSync', 502, token=None,
              body={'space': managed, 'credentialKey': credential_kid, 'notify': managed_notify})['error'] == 'UpstreamFailure'
with sqlite3.connect(db) as connection:
    assert connection.execute('select count(*) from permissioned_space_notify_registrations where space = ?', (managed,)).fetchone()[0] == 1
answer.update(status=200, body={'read': False, 'write': False})
assert expect('com.atproto.space.authorizeSpaceSync', 400, token=None,
              body={'space': managed, 'credentialKey': credential_kid, 'notify': managed_notify})['error'] == 'SpaceNotFound'
with sqlite3.connect(db) as connection:
    assert connection.execute('select count(*) from permissioned_space_notify_registrations where space = ?', (managed,)).fetchone()[0] == 0
# The authority is never sent to the managing app.
asked = len(checks)
owner_managed = expect('com.atproto.space.getDelegationToken', 200, params={'space': managed})['token']
request_credential(managed, owner_managed, 200)
assert len(checks) == asked
# An app that allows anonymous reads gets the reader a credential.
answer.update(status=200, body={'read': True, 'write': False})
assert request_credential(managed, None, 200)['credential']

# Syncers register for notifications by authorizing with `notify`. Only the
# endpoint's origin is called.
synced = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.synced', 'policy': public_policy})['space']
fresh = request_credential(synced, None, 200)
# A space with no update yet has no revision to report.
assert 'spaceRev' not in fresh, fresh
endpoint = f'http://127.0.0.1:{stub_port}/ignored'


def authorize(token, expected, notify=None, space=synced):
    body = {'space': space, 'credentialKey': credential_kid, 'notify': notify or {'endpoint': endpoint, 'token': token}}
    return expect('com.atproto.space.authorizeSpaceSync', expected, token=None, body=body)


def registered(space=synced):
    with sqlite3.connect(db) as connection:
        return {row[0]: (row[1], row[2]) for row in connection.execute(
            'select token, expires_at, expiry_notified from permissioned_space_notify_registrations where space = ?', (space,))}


def lapse(token, space=synced):
    with sqlite3.connect(db) as connection:
        connection.execute('update permissioned_space_notify_registrations set expires_at = 1 where space = ? and token = ?', (space, token))


def updates_for(token, count, timeout=20):
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        seen = [(body, auth) for body, auth in space_updates if body['token'] == token]
        if len(seen) >= count:
            return seen
        time.sleep(0.1)
    raise AssertionError(f'{token}: expected {count} notifications, got {[b for b, _ in space_updates if b["token"] == token]}')


for bad in ({'endpoint': endpoint}, {'endpoint': 'not a uri', 'token': 't'}, {'endpoint': endpoint, 'token': 'x' * 513}, {'endpoint': endpoint, 'token': 7}):
    assert authorize(None, 400, notify=bad)['error'] == 'InvalidRequest', bad
# A new registration is confirmed first, and only for a token the syncer issued.
assert authorize('unknown', 400)['error'] == 'RegistrationNotConfirmed'
assert confirmations[-1]['space'] == synced and confirmations[-1]['token'] == 'unknown' and len(confirmations[-1]['challenge']) >= 16
assert 'unknown' not in registered()
issued_tokens.update({(synced, 'kept'), (synced, 'rejecting')})
authorized = authorize('kept', 200)
claims = json.loads(base64.urlsafe_b64decode(authorized['credential'].split('.')[1] + '==='))
assert registered()['kept'] == (claims['exp'], 0), registered()
confirmed = len(confirmations)
# Each authorization renews it without confirming again.
authorize('kept', 200)
authorize('rejecting', 200)
assert len(confirmations) == confirmed + 1 and set(registered()) == {'kept', 'rejecting'}

# Registered syncers hear of each write and each removal from the writer set,
# in space revision order, with their token and no service auth.
expect('com.atproto.memberspace.putMembers', 200, body={'space': synced, 'members': [{'did': member_did, 'read': True, 'write': True}]})
expect('com.atproto.space.putRecord', 200, token=member, body={'space': synced, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'synced', 'record': {'$type': 'test.access.record', 'text': 'synced'}})
expect('com.atproto.memberspace.removeMembers', 200, body={'space': synced, 'dids': [member_did]})
(wrote, wrote_auth), (left, left_auth) = updates_for('kept', 2)[-2:]
assert wrote_auth is None and left_auth is None
assert wrote['space'] == synced and set(wrote) == {'space', 'token', 'update'}, wrote
write = wrote['update']
assert write['$type'] == 'com.atproto.space.defs#repoWrite' and write['repo'] == member_did and write['repoRev'] and write['data']['$bytes'], write
assert 'prevSpaceRev' not in write, write
removal = left['update']
assert removal == {'$type': 'com.atproto.space.defs#repoRemoved', 'repo': member_did, 'spaceRev': removal['spaceRev'], 'prevSpaceRev': write['spaceRev']}, removal
assert write['spaceRev'] < removal['spaceRev']
assert authorize('kept', 200)['spaceRev'] == removal['spaceRev']
updates_for('rejecting', 2)

# A lapsed registration gets one expiry notice in place of the next update,
# then nothing until it reauthorizes. A syncer that rejects the notice is
# unregistered.
rejected_updates.add(('rejecting', 'com.atproto.space.notifySpaceUpdate#registrationExpired'))
for token in ('kept', 'rejecting'):
    lapse(token)
heard = len(space_updates)
expect('com.atproto.memberspace.putMembers', 200, body={'space': synced, 'members': [{'did': member_did, 'read': True, 'write': True}]})
expect('com.atproto.space.putRecord', 200, token=member, body={'space': synced, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'lapsed', 'record': {'$type': 'test.access.record', 'text': 'after the lapse'}})
expired = updates_for('kept', 3)[-1][0]['update']
assert expired['$type'] == 'com.atproto.space.notifySpaceUpdate#registrationExpired' and len(expired['spaceRev']) == 13, expired
deadline = time.monotonic() + 20
while 'rejecting' in registered() and time.monotonic() < deadline:
    time.sleep(0.1)
assert set(registered()) == {'kept'} and registered()['kept'][1] == 1, registered()
expect('com.atproto.space.putRecord', 200, token=member, body={'space': synced, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'lapsed', 'record': {'$type': 'test.access.record', 'text': 'still lapsed'}})
time.sleep(1.5)
assert [body['update']['$type'] for body, _ in space_updates[heard:]] == ['com.atproto.space.notifySpaceUpdate#registrationExpired'] * 2, space_updates[heard:]
# Reauthorizing renews it without a new confirmation.
confirmed = len(confirmations)
authorize('kept', 200)
assert len(confirmations) == confirmed and registered()['kept'][1] == 0
expect('com.atproto.space.putRecord', 200, token=member, body={'space': synced, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'lapsed', 'record': {'$type': 'test.access.record', 'text': 'renewed'}})
assert updates_for('kept', 4)[-1][0]['update']['$type'] == 'com.atproto.space.defs#repoWrite'

# A syncer refused the space when reauthorizing loses its registration.
expect('com.atproto.space.updateSpace', 200, body={'space': synced, 'policy': member_policy})
assert authorize('kept', 400)['error'] == 'SpaceNotFound'
assert registered() == {}
expect('com.atproto.space.updateSpace', 200, body={'space': synced, 'policy': public_policy})
authorize('kept', 200)
authorize('rejecting', 200)
lapse('rejecting')

# Every registration hears of the space's deletion, lapsed ones too, and the
# notice is retried until the syncer accepts it.
failures_left[('kept', 'com.atproto.space.notifySpaceUpdate#spaceDeleted')] = 1
expect('com.atproto.space.deleteSpace', 200, body={'space': synced})
updates_for('kept', 5)
# Once the failure is rescheduled, bring the retry forward.
with sqlite3.connect(db) as connection:
    deadline = time.monotonic() + 10
    while not connection.execute("select count(*) from permissioned_space_syncer_outbox where space = ? and token = 'kept' and retry_at > cast(strftime('%s', 'now') as integer)", (synced,)).fetchone()[0]:
        assert time.monotonic() < deadline, 'deletion notice was not rescheduled'
        time.sleep(0.1)
    connection.execute('update permissioned_space_syncer_outbox set retry_at = 0 where space = ?', (synced,))
for token, count in (('kept', 6), ('rejecting', 4)):
    deleted = updates_for(token, count)[-1][0]
    assert deleted == {'space': synced, 'token': token, 'update': {'$type': 'com.atproto.space.notifySpaceUpdate#spaceDeleted'}}, deleted
with sqlite3.connect(db) as connection:
    deadline = time.monotonic() + 5
    while connection.execute('select count(*) from permissioned_space_syncer_outbox where space = ?', (synced,)).fetchone()[0] and time.monotonic() < deadline:
        time.sleep(0.1)
    assert connection.execute('select count(*) from permissioned_space_syncer_outbox where space = ?', (synced,)).fetchone()[0] == 0
assert registered() == {}
# A deleted space says so with or without a delegation token, so a public
# space's syncer drops its copy too.
assert request_credential(synced, None, 400)['error'] == 'SpaceDeleted'
deleted_delegation = expect('com.atproto.space.getDelegationToken', 200, params={'space': synced})['token']
assert request_credential(synced, deleted_delegation, 400)['error'] == 'SpaceDeleted'
# before the request's authorization is looked at
assert request_credential(synced, 'not-a-delegation-token', 400)['error'] == 'SpaceDeleted'
stub.shutdown()


# updateSpace replaces the policy wholesale; omitted fields reset to defaults.
expect('com.atproto.space.updateSpace', 200, body={'space': space, 'policy': {**member_policy, 'publicWrite': True}})
assert expect('com.atproto.space.getSpace', 200, params={'space': space})['policy'] == normalized(publicWrite=True)
expect('com.atproto.space.updateSpace', 200, body={'space': space, 'policy': {**public_policy, 'publicWrite': True, 'ignored': 1}})
assert expect('com.atproto.space.getSpace', 200, params={'space': space})['policy'] == normalized(publicRead=True, publicWrite=True)
expect('com.atproto.memberspace.removeMembers', 200, body={'space': space, 'dids': [member_did]})
assert member_did not in writers(space)
# A public-write space tracks any writer again on its next write.
expect('com.atproto.space.putRecord', 200, token=member, body={'space': space, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'public-write', 'record': {'$type': 'test.access.record', 'text': 'anyone'}})
assert member_did in writers(space)
delegation = expect('com.atproto.space.getDelegationToken', 200, params={'space': space})['token']
def signed_headers(authorization, audience):
    output = subprocess.check_output(['./zig-out/bin/zds-space-signature', authorization, audience], text=True, stderr=subprocess.STDOUT)
    return dict(line.split(': ', 1) for line in output.strip().splitlines())

credential = request_credential(space, delegation, 200)['credential']
assert request_credential(space, delegation, 400)['error'] == 'InvalidDelegationToken'
claims = json.loads(base64.urlsafe_b64decode(credential.split('.')[1] + '==='))
assert claims['exp'] - claims['iat'] == 600 and claims['cnf']['kid'] == credential_kid
# A public-read space hands an anonymous caller a credential with no delegation.
anonymous = request_credential(space, None, 200)['credential']
assert json.loads(base64.urlsafe_b64decode(anonymous.split('.')[1] + '==='))['sub'] == space
authority = 'did:plc:permissionsmoke'
authorization = 'Atproto-Space-Credential ' + credential
headers = {'authorization': authorization, **signed_headers(authorization, authority)}
for _ in range(2):
    expect('com.atproto.space.listWriters', 200, params={'space': space}, headers=headers)
# A space credential does not reach the owner's configuration.
assert call('com.atproto.space.getSpace', token=None, params={'space': space}, headers=headers)[0] == 401
wrong = {'authorization': authorization, **signed_headers(authorization, member_did)}
assert expect('com.atproto.space.listWriters', 401, params={'space': space}, headers=wrong)['error'] == 'BadSpaceAudience'
repos = expect('com.atproto.space.listWriters', 200, params={'space': space, 'limit': 1}, headers=headers)
assert len(repos['repos']) == 1 and repos['cursor'] == repos['repos'][0]['spaceRev']
writer = repos['repos'][0]
assert set(writer) == {'$type', 'repo', 'repoRev', 'data', 'spaceRev'}, writer
assert writer['$type'] == 'com.atproto.space.defs#repoWrite' and writer['repoRev'] and writer['data']['$bytes'], writer
checkpoint = repos['cursor']
assert expect('com.atproto.space.listWriters', 200, params={'space': space, 'cursor': checkpoint}, headers=headers) == {'repos': []}
writer_auth = expect('com.atproto.server.getServiceAuth', 200, token=member,
                     params={'aud': authority + '#atproto_pds', 'lxm': 'com.atproto.space.notifyRepoUpdate'})['token']
# A repo host reports {space, repo, repoRev, data}, nothing of the space's sequence.
body = {'space': space, 'repo': member_did, 'repoRev': writer['repoRev'], 'data': writer['data']}
expect('com.atproto.space.notifyRepoUpdate', 200, token=writer_auth, body=body)
assert expect('com.atproto.space.listWriters', 200, params={'space': space}, headers=headers)['cursor'] == checkpoint
for bad in ({'data': None}, {'repoRev': 'not-a-tid'}, {'repoRev': None}, {'data': {'$bytes': 'AAEC'}}):
    assert expect('com.atproto.space.notifyRepoUpdate', 400, token=writer_auth, body={**body, **bad})['error'] == 'InvalidRequest', bad
assert expect('com.atproto.space.notifyRepoUpdate', 400, token=writer_auth, body={'space': space, 'repo': member_did})['error'] == 'InvalidRequest'
# The November 5 shape carries no repoRev.
latest = {'$type': 'com.atproto.space.defs#repoWrite', 'rev': writer['repoRev'], 'data': writer['data']}
assert expect('com.atproto.space.notifyRepoUpdate', 400, token=writer_auth, body={'space': space, 'repo': member_did, 'latest': latest})['error'] == 'InvalidRequest'
assert expect('com.atproto.space.notifyRepoUpdate', 400, token=writer_auth, body={**body, 'repoRev': '7zzzzzzzzzzzz'})['error'] == 'FutureRev'
assert expect('com.atproto.space.notifyRepoUpdate', 403, token=writer_auth, body={**body, 'repo': authority})['error'] == 'Forbidden'
# A removal is listed at the next space revision until the repo writes again.
expect('com.atproto.space.removeWriter', 200, body={'space': space, 'repo': member_did})
after = expect('com.atproto.space.listWriters', 200, params={'space': space, 'cursor': checkpoint}, headers=headers)['repos']
assert after == [{'$type': 'com.atproto.space.defs#repoRemoved', 'repo': member_did, 'spaceRev': after[0]['spaceRev']}], after
assert after[0]['spaceRev'] > checkpoint
expect('com.atproto.space.putRecord', 200, token=member, body={'space': space, 'repo': member_did, 'collection': 'test.access.record',
       'rkey': 'case-3', 'record': {'$type': 'test.access.record', 'text': 'tracked after removal'}})
rejoined = expect('com.atproto.space.listWriters', 200, params={'space': space, 'cursor': after[0]['spaceRev']}, headers=headers)['repos']
assert [(r['repo'], r['$type']) for r in rejoined] == [(member_did, 'com.atproto.space.defs#repoWrite')], rejoined
import http.client
connection = http.client.HTTPConnection(urllib.parse.urlparse(base).netloc)
connection.putrequest('GET', '/xrpc/com.atproto.space.listWriters?' + urllib.parse.urlencode({'space': space}))
for name, value in headers.items():
    connection.putheader(name, value)
connection.putheader('authorization', authorization)
connection.endheaders()
response = connection.getresponse()
assert response.status == 401
response.read()
connection.close()

# Commit and record reads with a space credential must ask for a MAC, keyed by a
# shared secret derived against the author's #atproto_kem key.
def raw_get(method, params, headers, token=None):
    request = urllib.request.Request(base + '/xrpc/' + method + '?' + urllib.parse.urlencode(params),
                                     headers={**({'authorization': 'Bearer ' + token} if token else {}), **headers})
    try:
        response = urllib.request.urlopen(request, timeout=10)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        return response.status, response.headers, response.read()


def session_key(token, fragment):
    doc = expect('com.atproto.server.getSession', 200, token=token)['didDoc']
    return 'did:key:' + next(m for m in doc['verificationMethod'] if m['id'] == fragment)['publicKeyMultibase']


def accept_signature(kind, kem_key):
    output = subprocess.check_output(['./zig-out/bin/zds-space-signature', 'accept-signature', kind, kem_key], text=True, stderr=subprocess.STDOUT)
    fields = dict(line.split(': ', 1) for line in output.strip().splitlines())
    return fields['accept-signature'], bytes.fromhex(fields['shared-secret'])


def mac_matches(headers, covered_name, secret):
    """Recompute the RFC 9421 hmac-sha256 MAC over the covered header."""
    assert covered_name in headers['access-control-expose-headers'], headers['access-control-expose-headers']
    label, params = headers['signature-input'].split('=', 1)
    signature = headers['signature']
    assert signature.startswith(label + '=:') and signature.endswith(':'), signature
    mac = base64.b64decode(signature[len(label) + 2:-1])
    base = f'"{covered_name}";sf: {headers[covered_name]}\n"@signature-params": {params}'
    return hmac.compare_digest(mac, hmac.new(secret, base.encode(), hashlib.sha256).digest())


def json_bytes(value):
    return base64.b64decode(value["$bytes"] + "=" * (-len(value["$bytes"]) % 4))


def commit_header(commit):
    data = base64.b64encode(json_bytes(commit["data"])).decode()
    return (f'ver={commit["ver"]}, repo="{commit["repo"]}", space="{commit["space"]}", '
            f'rev="{commit["rev"]}", data=:{data}:')


def commit_mac_ok(headers, secret, commit):
    return headers['atproto-space-commit'] == commit_header(commit) and mac_matches(headers, 'atproto-space-commit', secret)


bob_kem = session_key(member, '#atproto_kem')
assert bob_kem.startswith('did:key:zDnae'), bob_kem
repo_headers = {'authorization': authorization, **signed_headers(authorization, member_did)}
repo_params = {'space': space, 'repo': member_did}
assert expect('com.atproto.space.listRepoOps', 400, token=member, params={**repo_params, 'cursor': 'nope'})['error'] == 'InvalidCursor'
good_commit_request, _ = accept_signature('commit', bob_kem)
bad_requests = [
    None,
    '???',
    good_commit_request.replace('tag="atproto-space-commit"', 'tag="atproto-space-record"'),
    good_commit_request.replace(';sf', ''),
    good_commit_request + ';created=1',
    good_commit_request + ';alg="ecdsa-p256-sha256"',
    'mac=("atproto-space-commit";sf);tag="atproto-space-commit"',
    f'mac=("atproto-space-commit";sf);keyid="{session_key(owner, "#atproto")}";tag="atproto-space-commit"',
]
for method in ('com.atproto.space.getLatestCommit', 'com.atproto.space.listRepoOps', 'com.atproto.space.getRepo'):
    for bad in bad_requests:
        status, response_headers, body = raw_get(method, repo_params, {**repo_headers, **({'accept-signature': bad} if bad else {})})
        assert status == 400 and json.loads(body)['error'] == 'InvalidSpaceMac', (method, bad, status, body)
        assert 'accept-signature' in response_headers['vary']
record_params = {**repo_params, 'collection': 'test.access.record', 'rkey': 'case-0'}
assert json.loads(raw_get('com.atproto.space.getRecord', record_params, repo_headers)[2])['error'] == 'InvalidSpaceMac'
assert json.loads(raw_get('com.atproto.space.getRecord', record_params, {**repo_headers, 'accept-signature': good_commit_request})[2])['error'] == 'InvalidSpaceMac'

want, secret = accept_signature('commit', bob_kem)
status, response_headers, body = raw_get('com.atproto.space.getLatestCommit', repo_params, {**repo_headers, 'accept-signature': want})
assert status == 200, body
latest = json.loads(body)['commit']
assert set(latest) == {'ver', 'repo', 'space', 'rev', 'data'} and latest['ver'] == 1, latest
assert (latest['repo'], latest['space']) == (member_did, space)
assert response_headers['signature-input'] == want, response_headers['signature-input']
assert commit_mac_ok(response_headers, secret, latest)
assert not commit_mac_ok(response_headers, accept_signature('commit', bob_kem)[1], latest)
# found by its tag, and answered under the label the syncer asked for
want, secret = accept_signature('commit', bob_kem)
relabeled = 'other=("content-digest");tag="other", sync' + want[len('mac'):]
status, response_headers, body = raw_get('com.atproto.space.getLatestCommit', repo_params, {**repo_headers, 'accept-signature': relabeled})
assert status == 200 and response_headers['signature-input'].startswith('sync=('), response_headers['signature-input']
assert commit_mac_ok(response_headers, secret, json.loads(body)['commit'])

want, secret = accept_signature('commit', bob_kem)
status, response_headers, body = raw_get('com.atproto.space.listRepoOps', repo_params, {**repo_headers, 'accept-signature': want})
ops = json.loads(body)
assert status == 200 and ops['commit'] == latest and 'cursor' not in ops
assert commit_mac_ok(response_headers, secret, ops['commit'])
# Every page carries the current commit, MAC'd, beside its cursor.
want, secret = accept_signature('commit', bob_kem)
status, response_headers, body = raw_get('com.atproto.space.listRepoOps', {**repo_params, 'limit': 1}, {**repo_headers, 'accept-signature': want})
page = json.loads(body)
assert status == 200 and page['cursor'] and page['commit'] == latest, page
assert commit_mac_ok(response_headers, secret, page['commit'])

want, secret = accept_signature('commit', bob_kem)
status, response_headers, body = raw_get('com.atproto.space.getRepo', repo_params, {**repo_headers, 'accept-signature': want})
assert status == 200 and body[:4] == b'*l\x01\x00'
assert commit_mac_ok(response_headers, secret, latest)

want, secret = accept_signature('record', bob_kem)
status, response_headers, body = raw_get('com.atproto.space.getRecord', record_params, {**repo_headers, 'accept-signature': want})
record = json.loads(body)
assert status == 200 and record['uri'] == f'{space}/{member_did}/test.access.record/case-0', record
assert response_headers['atproto-space-record'] == f'uri="{record["uri"]}", cid="{record["cid"]}"', response_headers['atproto-space-record']
assert mac_matches(response_headers, 'atproto-space-record', secret)

# Reads that carry no commit or record need no MAC.
status, _, body = raw_get('com.atproto.space.listRecords', {**repo_params, 'collection': 'test.access.record'}, repo_headers)
assert status == 200 and json.loads(body)['records'], body
# An account reading its own repo may skip the MAC, or ask for one.
status, response_headers, body = raw_get('com.atproto.space.getLatestCommit', repo_params, {}, token=member)
assert status == 200 and 'atproto-space-commit' not in response_headers and 'accept-signature' in response_headers['vary']
want, secret = accept_signature('commit', bob_kem)
status, response_headers, body = raw_get('com.atproto.space.getLatestCommit', repo_params, {'accept-signature': want}, token=member)
assert status == 200 and commit_mac_ok(response_headers, secret, json.loads(body)['commit'])
status, _, body = raw_get('com.atproto.space.getLatestCommit', repo_params, {'accept-signature': '???'}, token=member)
assert status == 400 and json.loads(body)['error'] == 'InvalidSpaceMac'
attacker = expect('com.atproto.server.getServiceAuth', 200, token=member,
                  params={'aud': authority, 'lxm': 'com.atproto.space.notifyCredentialsRevoked'})['token']
assert expect('com.atproto.space.notifyCredentialsRevoked', 403, token=attacker,
              body={'space': space, 'credentials': [claims['jti']]})['error'] == 'Forbidden'
wrong_method = expect('com.atproto.server.getServiceAuth', 200,
                      params={'aud': authority, 'lxm': 'com.atproto.space.notifyRepoUpdate'})['token']
assert expect('com.atproto.space.notifyCredentialsRevoked', 401, token=wrong_method,
              body={'space': space, 'credentials': [claims['jti']]})['error'] == 'BadJwtLexiconMethod'
service = expect('com.atproto.server.getServiceAuth', 200,
                 params={'aud': authority, 'lxm': 'com.atproto.space.notifyCredentialsRevoked'})['token']
for _ in range(2):
    expect('com.atproto.space.notifyCredentialsRevoked', 200, token=service,
           body={'space': space, 'credentials': [claims['jti'], claims['jti']]})
assert expect('com.atproto.space.listWriters', 401, params={'space': space}, headers=headers)['error'] == 'CredentialRevoked'
# The removed notification methods are not served.
for method in ('registerNotify', 'unregisterNotify', 'notifySpaceStatus', 'getSpaceCredential'):
    assert call('com.atproto.space.' + method, token=None, body={'space': space})[0] == 404, method
assert expect('com.atproto.space.getLatestCommit', 200, token=member, params=repo_params)['commit']
for ids in ([], [''], [claims['jti']] * 101):
    expect('com.atproto.space.notifyCredentialsRevoked', 400, token=service,
           body={'space': space, 'credentials': ids})

# clearRecords empties the caller's repo at a new rev with the empty digest.
before = expect('com.atproto.space.getLatestCommit', 200, token=member, params=repo_params)['commit']
assert expect('com.atproto.space.clearRecords', 403, token=member, body={'space': space, 'repo': authority})['error'] == 'InvalidRepo'
expect('com.atproto.space.clearRecords', 200, token=member, body={'space': space, 'repo': member_did})
cleared = expect('com.atproto.space.getLatestCommit', 200, token=member, params=repo_params)['commit']
assert cleared['rev'] > before['rev']
assert json_bytes(cleared["data"]).hex() == 'e5a00aa9991ac8a5ee3109844d84a55583bd20572ad3ffcd42792f3c36b183ad'
assert not cleared["data"]["$bytes"].endswith("="), cleared
assert expect('com.atproto.space.listRecords', 200, token=member, params=repo_params)['records'] == []
# Another account's repo answers as an absent one would.
assert expect('com.atproto.space.listRecords', 404, params=repo_params)['error'] == 'RepoNotFound'
assert expect('com.atproto.space.listRepoOps', 200, token=member, params=repo_params)['ops'] == []
assert expect('com.atproto.space.listRepoOps', 400, token=member, params={**repo_params, 'since': 'not-a-tid'})['error'] == 'InvalidRequest'
assert member_did in writers(space)
expect('com.atproto.space.clearRecords', 200, token=member, body={'space': space, 'repo': member_did})
assert expect('com.atproto.space.getLatestCommit', 200, token=member, params=repo_params)['commit'] == cleared
# The authority keeps its published policy through a clear.
expect('com.atproto.space.createRecord', 200, body={'space': published, 'repo': authority, 'collection': 'test.access.record',
       'rkey': 'authority-note', 'record': {'$type': 'test.access.record', 'text': 'goes'}})
expect('com.atproto.space.clearRecords', 200, body={'space': published, 'repo': authority})
assert [r['collection'] for r in expect('com.atproto.space.listRecords', 200, params={'space': published, 'repo': authority})['records']] == ['com.atproto.space.policy']

# Imports replace a whole space or repo: an app password can't, nor can another account.
def post_octets(method, token, body, content_type='application/vnd.dasl.star'):
    request = urllib.request.Request(base + '/xrpc/' + method, data=body, method='POST',
                                     headers={'authorization': 'Bearer ' + token, 'content-type': content_type})
    try:
        response = urllib.request.urlopen(request, timeout=10)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        return response.status, json.load(response)


status, export_headers, exported = raw_get('com.atproto.space.exportSpaceMeta', {'space': space}, {}, token=owner)
assert status == 200 and exported[:4] == b'*l\x01\x00', status
assert export_headers['content-type'] == 'application/vnd.dasl.star', export_headers['content-type']
assert raw_get('com.atproto.space.exportSpaceMeta', {'space': space}, {}, token=member)[0] == 400
app_password = expect('com.atproto.server.createAppPassword', 200, body={'name': 'space-import-smoke'})['password']
app_token = expect('com.atproto.server.createSession', 200, token=None,
                   body={'identifier': 'permissioned-smoke.test', 'password': app_password})['accessJwt']
status, refused = post_octets('com.atproto.space.importSpaceMeta', app_token, exported)
assert status == 401 and refused['error'] == 'InvalidToken', (status, refused)
assert post_octets('com.atproto.space.importSpaceMeta', member, exported)[1]['error'] == 'NotAuthorized'
for method in ('com.atproto.space.importSpaceMeta', 'com.atproto.space.importRepo'):
    assert post_octets(method, owner, exported, 'application/octet-stream') == (400, {'error': 'InvalidRequest',
           'message': 'Wrong request encoding (Content-Type): expected application/vnd.dasl.star'}), method
assert post_octets('com.atproto.space.importSpaceMeta', owner, exported) == (200, {})
status, _, member_repo = raw_get('com.atproto.space.getRepo', repo_params, {}, token=member)
assert status == 200
assert post_octets('com.atproto.space.importRepo', owner, member_repo)[1]['error'] == 'RepoMismatch'
assert post_octets('com.atproto.space.importRepo', member, member_repo) == (200, {})
assert post_octets('com.atproto.space.importRepo', member, b'not a star')[1]['error'] == 'InvalidRepoFile'
assert post_octets('com.atproto.space.importSpaceMeta', owner, b'not a star')[1]['error'] == 'InvalidSpaceMeta'
expect('com.atproto.space.deleteSpace', 200, body={'space': space})

# Account status follows the reference PDS: a deactivated account can neither
# manage spaces nor write in them (401 AccountDeactivated) but still reads its
# own repo, and a deactivated authority issues no credentials and lists no repos.
def raw_post_status(method, token):
    request = urllib.request.Request(base + '/xrpc/' + method, data=b'{}', method='POST',
                                     headers={'authorization': 'Bearer ' + token, 'content-type': 'application/json'})
    try:
        response = urllib.request.urlopen(request, timeout=10)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        return response.status


lapsed = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.lapsed', 'policy': public_policy})['space']
expect('com.atproto.memberspace.putMembers', 200, body={'space': lapsed, 'members': [{'did': member_did, 'read': True, 'write': True}]})
lapsed_record = {'space': lapsed, 'repo': member_did, 'collection': 'test.access.record', 'record': {'$type': 'test.access.record', 'text': 'kept'}}
expect('com.atproto.space.createRecord', 200, token=member, body={**lapsed_record, 'rkey': 'before'})
lapsed_authorized = request_credential(lapsed, None, 200)
lapsed_authorization = 'Atproto-Space-Credential ' + lapsed_authorized['credential']
lapsed_headers = {'authorization': lapsed_authorization, **signed_headers(lapsed_authorization, authority)}
lapsed_writers = expect('com.atproto.space.listWriters', 200, token=None, params={'space': lapsed}, headers=lapsed_headers)
assert member_did in [r['repo'] for r in lapsed_writers['repos']]
# The space's current revision is the writer set's latest.
assert lapsed_authorized['spaceRev'] == lapsed_writers['cursor'], (lapsed_authorized, lapsed_writers)

expect('com.atproto.server.deactivateAccount', 200, token=member, body={})
assert expect('com.atproto.space.createRecord', 401, token=member, body={**lapsed_record, 'rkey': 'after'})['error'] == 'AccountDeactivated'
assert expect('com.atproto.space.clearRecords', 401, token=member, body={'space': lapsed, 'repo': member_did})['error'] == 'AccountDeactivated'
assert expect('com.atproto.space.createSpace', 401, token=member, body={**create, 'spaceType': 'test.access.lapsed-member'})['error'] == 'AccountDeactivated'
lapsed_params = {'space': lapsed, 'repo': member_did, 'collection': 'test.access.record'}
assert [r['rkey'] for r in expect('com.atproto.space.listRecords', 200, token=member, params=lapsed_params)['records']] == ['before']
assert raw_get('com.atproto.space.getRepo', {'space': lapsed, 'repo': member_did}, {}, token=member)[0] == 200
# The harness creates both smoke accounts without a public repo; activating
# one creates it.
assert raw_post_status('com.atproto.server.activateAccount', member) == 200

expect('com.atproto.server.deactivateAccount', 200, body={})
assert request_credential(lapsed, None, 400)['error'] == 'RepoDeactivated'
assert expect('com.atproto.space.listWriters', 400, token=None, params={'space': lapsed}, headers=lapsed_headers)['error'] == 'RepoDeactivated'
for method, body in (('com.atproto.memberspace.putMembers', {'space': lapsed, 'members': [{'did': member_did, 'read': True, 'write': False}]}),
                     ('com.atproto.memberspace.removeMembers', {'space': lapsed, 'dids': [member_did]}),
                     ('com.atproto.space.updateSpace', {'space': lapsed, 'policy': member_policy}),
                     ('com.atproto.space.removeWriter', {'space': lapsed, 'repo': member_did}),
                     ('com.atproto.space.deleteSpace', {'space': lapsed})):
    assert expect(method, 401, body=body)['error'] == 'AccountDeactivated', method
assert raw_post_status('com.atproto.server.activateAccount', owner) == 200
assert request_credential(lapsed, None, 200)['credential']
expect('com.atproto.space.deleteSpace', 200, body={'space': lapsed})
# A taken-down account moves its spaces with the session createSession grants
# under allowTakendown: listSpaces, exportSpaceMeta, and its repo's getRepo and
# listBlobs, and nothing else.
admin_headers = {'authorization': 'Bearer permissioned-smoke-admin-token'}


def takedown(did, applied):
    expect('com.atproto.admin.updateSubjectStatus', 200, token=None, headers=admin_headers,
           body={'subject': {'$type': 'com.atproto.admin.defs#repoRef', 'did': did}, 'takedown': {'applied': applied}})


exported = expect('com.atproto.space.createSpace', 200, body={**create, 'spaceType': 'test.access.exported'})['space']
expect('com.atproto.memberspace.putMembers', 200, body={'space': exported, 'members': [{'did': member_did, 'read': True, 'write': True}]})
exported_record = {'space': exported, 'repo': member_did, 'collection': 'test.access.record', 'rkey': 'moved',
                   'record': {'$type': 'test.access.record', 'text': 'moves with its account'}}
expect('com.atproto.space.createRecord', 200, token=member, body=exported_record)
takedown(member_did, True)
takedown(authority, True)
sessions = {}
for name, handle in (('member', 'space-smoke-bob.test'), ('owner', 'permissioned-smoke.test')):
    login = {'identifier': handle, 'password': 'password'}
    assert expect('com.atproto.server.createSession', 401, token=None, body=login)['error'] == 'AccountTakedown'
    sessions[name] = expect('com.atproto.server.createSession', 200, token=None, body={**login, 'allowTakendown': True})['accessJwt']
exported_repo = {'space': exported, 'repo': member_did}
assert raw_get('com.atproto.space.getRepo', exported_repo, {}, token=sessions['member'])[0] == 200
expect('com.atproto.space.listBlobs', 200, token=sessions['member'], params=exported_repo)
assert exported in [entry['space'] for entry in expect('com.atproto.space.listSpaces', 200, token=sessions['member'])['spaces']]
assert raw_get('com.atproto.space.exportSpaceMeta', {'space': exported}, {}, token=sessions['owner'])[0] == 200
# Outside its grant the takedown session gets the reference PDS's scope
# rejection, and an admin token still reads the taken-down repo.
assert expect('com.atproto.space.listRecords', 400, token=sessions['member'],
              params={**exported_repo, 'collection': 'test.access.record'})['error'] == 'InvalidToken'
assert expect('com.atproto.space.createRecord', 400, token=sessions['member'], body={**exported_record, 'rkey': 'after'})['error'] == 'InvalidToken'
assert expect('com.atproto.space.createSpace', 400, token=sessions['owner'], body={**create, 'spaceType': 'test.access.escaped'})['error'] == 'InvalidToken'
assert [r['rkey'] for r in expect('com.atproto.space.listRecords', 200, token=None, headers=admin_headers,
                                  params={**exported_repo, 'collection': 'test.access.record'})['records']] == ['moved']
assert raw_get('com.atproto.space.getRepo', exported_repo, admin_headers)[0] == 200
takedown(member_did, False)
takedown(authority, False)

print('space access: baseline policies, member upserts, writer set, published records, managing app, credentials, syncer registrations and notices, clears, migration imports, account status, takedown exports, and space MACs passed')