import asyncio import hashlib import json import secrets import sys import time from pathlib import Path import fakeredis.aioredis import httpx import pytest import pytest_asyncio from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 from fastapi import FastAPI sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from relay.config import Settings from relay.crypto import canonical, issue_ca, issue_device, sign from relay.notifications import router from relay.oauth import OAuth from relay.platform import Feishu from relay.store import Store class Platform: def __init__(self): self.sent = [] self.fail = False self.before_token = None async def tenant_token(self): if self.before_token: await self.before_token() return 'fake-tenant-token' async def send(self, owner, kind, content, delivery_id, *, token): self.sent.append((owner, kind, content, delivery_id)) if self.fail: raise httpx.ReadTimeout('ambiguous') return {'message_id': 'om_' + delivery_id} async def exchange(self, code): return {'user_access_token': 'fake-user-token', 'expires_in': 3600} async def user_info(self, token): return {'open_id': 'ou_b'} @pytest_asyncio.fixture async def channel(tmp_path): ca_key, ca = issue_ca() cert_path = tmp_path/'ca.pem' cert_path.write_bytes(ca.public_bytes(serialization.Encoding.PEM)) settings = Settings(environment='test', admin_secret='a'*40, internal_secret='b'*40, ca_cert=cert_path, data_dir=tmp_path, feishu_enabled=True, feishu_app_id='cli_test', feishu_app_secret='fake-secret', public_url='https://relay.example.test', feishu_api_base='https://work.example.test', feishu_authorize_url='https://work.example.test/authorize') store = Store(tmp_path/'metadata.sqlite') redis = fakeredis.aioredis.FakeRedis(decode_responses=True) platform = Platform() oauth = OAuth(settings, redis, platform) oauth.store = store keys = {} for host, owner in [('a'*32,'ou_a'),('b'*32,'ou_b')]: key = ed25519.Ed25519PrivateKey.generate() cert = issue_device(ca_key, ca, host, key.public_key()).public_bytes(serialization.Encoding.PEM).decode() from relay.crypto import fingerprint store.add_device(host, cert, fingerprint(cert)) store.bind(host, owner) keys[host] = key app = FastAPI() app.include_router(oauth.router) app.include_router(router(settings, redis, store, platform, oauth)) async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url='https://relay.example.test') as client: yield {'client':client, 'store':store, 'platform':platform, 'oauth':oauth, 'keys':keys, 'settings':settings, 'redis':redis, 'app':app} await redis.aclose() store.close() def proof(env, host, purpose, payload, **override): return sign({'host_id':host, 'purpose':purpose, 'ts':int(time.time()), 'nonce':secrets.token_hex(16), 'payload_hash':hashlib.sha256(canonical(payload)).hexdigest(), **override}, env['keys'][host]) def wire(env, host='a'*32, request_id='request_0001', **fields): payload={'request_id':request_id,'kind':'text','text':'hello','title':'','oauth_state':'', 'binding_owner':'ou_a' if host=='a'*32 else 'ou_b',**fields} return {**payload, 'host_id':host, 'proof':proof(env,host,'work-notify-v1',payload)} @pytest.mark.asyncio async def test_two_devices_route_to_own_users(channel): for host,owner in [('a'*32,'ou_a'),('b'*32,'ou_b')]: response=await channel['client'].post('/device/notifications',json=wire(channel,host)) assert response.json()['status']=='sent' assert channel['platform'].sent[-1][0]==owner @pytest.mark.asyncio async def test_recipient_and_arbitrary_url_are_rejected(channel): for field in ['receive_id','owner','url','card']: response=await channel['client'].post('/device/notifications',json={**wire(channel),field:'ou_b'}) assert response.status_code==422 assert not channel['platform'].sent @pytest.mark.asyncio async def test_tampering_wrong_device_and_expired_proof(channel): for variant in ['content','host','expired']: data=wire(channel) if variant=='content':data['text']='tampered' if variant=='host':data['host_id']='b'*32 if variant=='expired': payload={k:v for k,v in data.items() if k not in {'host_id','proof'}} data['proof']=proof(channel,'a'*32,'work-notify-v1',payload,ts=int(time.time())-200) assert (await channel['client'].post('/device/notifications',json=data)).status_code==403 assert not channel['platform'].sent @pytest.mark.asyncio async def test_proof_replay_and_idempotent_payload(channel): data=wire(channel) assert (await channel['client'].post('/device/notifications',json=data)).json()['status']=='sent' assert (await channel['client'].post('/device/notifications',json=data)).status_code==409 result=await channel['client'].post('/device/notifications',json=wire(channel)) assert result.json()['previous_status']=='sent' changed=await channel['client'].post('/device/notifications',json=wire(channel,text='different')) assert changed.status_code==409 assert len(channel['platform'].sent)==1 @pytest.mark.asyncio async def test_dedupe_survives_new_router(channel): await channel['client'].post('/device/notifications',json=wire(channel)) app=FastAPI() app.include_router(router(channel['settings'],channel['redis'],channel['store'],channel['platform'],channel['oauth'])) async with httpx.AsyncClient(transport=httpx.ASGITransport(app),base_url='https://relay.example.test') as client: assert (await client.post('/device/notifications',json=wire(channel))).json()['status']=='duplicate' assert len(channel['platform'].sent)==1 @pytest.mark.asyncio async def test_revoked_and_unbound_rejected(channel): channel['store'].revoke('a'*32) channel['store'].unbind('ou_b') for host in ['a'*32,'b'*32]: assert (await channel['client'].post('/device/notifications',json=wire(channel,host))).status_code==403 @pytest.mark.asyncio async def test_binding_rechecked_after_token_acquisition(channel): async def change():channel['store'].unbind('ou_a') channel['platform'].before_token=change result=await channel['client'].post('/device/notifications',json=wire(channel)) assert result.json()['status']=='binding_changed' assert not channel['platform'].sent @pytest.mark.asyncio async def test_request_id_cannot_migrate_to_rebound_owner(channel): await channel['client'].post('/device/notifications',json=wire(channel)) channel['store'].unbind('ou_a') channel['store'].bind('a'*32,'ou_new') assert (await channel['client'].post('/device/notifications',json=wire(channel))).status_code==403 assert (await channel['client'].post('/device/notifications',json=wire(channel,binding_owner='ou_new'))).status_code==409 assert len(channel['platform'].sent)==1 @pytest.mark.asyncio async def test_unknown_delivery_is_not_retried(channel): channel['platform'].fail=True assert (await channel['client'].post('/device/notifications',json=wire(channel))).json()['status']=='unknown' again=await channel['client'].post('/device/notifications',json=wire(channel)) assert again.json()['previous_status']=='unknown' assert len(channel['platform'].sent)==1 @pytest.mark.asyncio async def test_concurrent_same_request_delivered_once(channel): entered,release=asyncio.Event(),asyncio.Event() async def pause():entered.set();await release.wait() channel['platform'].before_token=pause task=asyncio.create_task(channel['client'].post('/device/notifications',json=wire(channel))) await entered.wait() second=await channel['client'].post('/device/notifications',json=wire(channel)) assert second.json()['previous_status']=='inflight' release.set() assert (await task).json()['status']=='sent' assert len(channel['platform'].sent)==1 @pytest.mark.asyncio async def test_rate_limit(channel): for i in range(10): assert (await channel['client'].post('/device/notifications',json=wire(channel,request_id=f'request_{i:04d}'))).status_code==200 assert (await channel['client'].post('/device/notifications',json=wire(channel,request_id='request_extra'))).status_code==429 assert len(channel['platform'].sent)==10 async def start_oauth(channel,host='a'*32): response=await channel['client'].post('/oauth/start',json={'host_id':host,'proof':proof(channel,host,'work-oauth-v1',{})}) assert response.status_code==201 return response.json() @pytest.mark.asyncio async def test_authorization_card_server_owned_and_no_claim_secret(channel): data=await start_oauth(channel) result=await channel['client'].post('/device/notifications',json=wire(channel,kind='authorization',text='',oauth_state=data['state'])) assert result.json()['status']=='sent' owner,kind,card,_=channel['platform'].sent[-1] assert owner=='ou_a' and kind=='interactive' assert card['elements'][1]['actions'][0]['url']==data['authorization_url'] assert data['claim_secret'] not in json.dumps(card) assert 'user_access_token' not in json.dumps(card) # Wrong Work user completing this OAuth transaction is rejected by existing callback validation. response=await channel['client'].get('/oauth/cb',params={'state':data['state'],'code':'fake-code'}) assert response.status_code==502 @pytest.mark.asyncio async def test_cross_user_and_expired_oauth_cards_rejected(channel): data=await start_oauth(channel,'b'*32) response=await channel['client'].post('/device/notifications',json=wire(channel,kind='authorization',text='',oauth_state=data['state'])) assert response.status_code==403 channel['oauth'].pending[data['state']].expires=0 response=await channel['client'].post('/device/notifications',json=wire(channel,'b'*32,kind='authorization',text='',oauth_state=data['state'])) assert response.status_code==403 assert not channel['platform'].sent @pytest.mark.asyncio async def test_platform_send_wire_format(channel): captured=[] def handler(request): captured.append(request) return httpx.Response(200,json={'code':0,'data':{'message_id':'om_real'}}) api=Feishu(channel['settings'],transport=httpx.MockTransport(handler)) try: assert (await api.send('ou_a','text',{'text':'hello'},'stable-id',token='fake-token'))['message_id']=='om_real' finally:await api.close() request=captured[0] assert str(request.url)=='https://work.example.test/open-apis/im/v1/messages?receive_id_type=open_id' assert json.loads(request.content)=={'receive_id':'ou_a','msg_type':'text','content':'{"text": "hello"}','uuid':'stable-id'}