Add device-bound robot notifications and automatic OAuth cards
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from relay import work_client
|
||||
from relay.crypto import pem_private, verified, canonical
|
||||
from relay.notification_client import push, register_notification_tool
|
||||
from relay.work_client import WorkClient, WorkError
|
||||
from test_notifications import channel
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_auto_authorization_card_once(channel, tmp_path, monkeypatch):
|
||||
# DPAPI is separately implemented; keep the test independent of OS account keys.
|
||||
monkeypatch.setattr(work_client,'protect',lambda b:b)
|
||||
monkeypatch.setattr(work_client,'unprotect',lambda b:b)
|
||||
(tmp_path/'device.json').write_text(json.dumps({'host_id':'a'*32,'owner':'ou_a'}))
|
||||
(tmp_path/'device.key').write_bytes(pem_private(channel['keys']['a'*32]))
|
||||
(tmp_path/'server.pem').write_bytes(channel['settings'].ca_cert.read_bytes())
|
||||
calls=[]
|
||||
def handler(request):
|
||||
payload=json.loads(request.content)
|
||||
calls.append((request.url.path,payload))
|
||||
if request.url.path=='/oauth/start':
|
||||
return httpx.Response(201,json={'state':'fake-state','claim_secret':'fake-claim-secret',
|
||||
'authorization_url':'https://work.example.test/authorize?state=fake-state','expires_in':600})
|
||||
plain={k:v for k,v in payload.items() if k not in {'host_id','proof'}}
|
||||
signed=verified(payload['proof'],channel['keys']['a'*32].public_key())
|
||||
assert signed['payload_hash']==hashlib.sha256(canonical(plain)).hexdigest()
|
||||
assert 'fake-claim-secret' not in json.dumps(payload)
|
||||
return httpx.Response(200,json={'status':'sent','message_id':'om_test'})
|
||||
client=WorkClient(tmp_path,'https://relay.example.test',transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
url=client.authorize()
|
||||
assert client.authorize()==url
|
||||
assert [c[0] for c in calls]==['/oauth/start','/device/notifications']
|
||||
assert client.read(client.pending)['notification_status']=='sent'
|
||||
finally:client.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_old_ecs_failure_keeps_local_authorization(channel,tmp_path,monkeypatch):
|
||||
monkeypatch.setattr(work_client,'protect',lambda b:b)
|
||||
monkeypatch.setattr(work_client,'unprotect',lambda b:b)
|
||||
(tmp_path/'device.json').write_text(json.dumps({'host_id':'a'*32,'owner':'ou_a'}))
|
||||
(tmp_path/'device.key').write_bytes(pem_private(channel['keys']['a'*32]))
|
||||
(tmp_path/'server.pem').write_bytes(channel['settings'].ca_cert.read_bytes())
|
||||
attempts=[]
|
||||
def handler(request):
|
||||
if request.url.path=='/oauth/start':
|
||||
return httpx.Response(201,json={'state':'fake-state','claim_secret':'private-claim',
|
||||
'authorization_url':'https://work.example.test/authorize','expires_in':600})
|
||||
attempts.append(1)
|
||||
return httpx.Response(404)
|
||||
client=WorkClient(tmp_path,'https://relay.example.test',transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
assert client.authorize()=='https://work.example.test/authorize'
|
||||
assert client.authorize()=='https://work.example.test/authorize'
|
||||
assert len(attempts)==1
|
||||
assert client.read(client.pending)['notification_status']=='unconfirmed'
|
||||
finally:client.close()
|
||||
|
||||
|
||||
def test_native_notification_tool_has_no_recipient(monkeypatch):
|
||||
found={}
|
||||
registry=types.SimpleNamespace(register=lambda **kw:found.update(kw))
|
||||
monkeypatch.setitem(sys.modules,'tools',types.ModuleType('tools'))
|
||||
monkeypatch.setitem(sys.modules,'tools.registry',types.SimpleNamespace(registry=registry))
|
||||
toolsets=types.SimpleNamespace(TOOLSETS={'hainuo_work':{'tools':[]}},_HERMES_CORE_TOOLS=[])
|
||||
monkeypatch.setitem(sys.modules,'toolsets',toolsets)
|
||||
register_notification_tool('not-used')
|
||||
assert found['name']=='work_notification'
|
||||
assert set(found['schema']['parameters']['properties'])=={'request_id','kind','text','title'}
|
||||
result=json.loads(found['handler']({'request_id':'request_0001','text':'hi','receive_id':'ou_b'}))
|
||||
assert result['status']=='unconfirmed'
|
||||
assert 'work_notification' in toolsets._HERMES_CORE_TOOLS
|
||||
@@ -0,0 +1,28 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('notification_installer',ROOT/'scripts/apply_notification_client.py')
|
||||
installer=importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(installer)
|
||||
|
||||
|
||||
def test_client_patch_preserves_other_fixes_and_is_repeatable(tmp_path):
|
||||
baseline=ROOT.parent/'host-code/relay'
|
||||
marker='\n# Existing TLS and cloud-document fixes must stay.\n'
|
||||
for name in ['work_client.py','work_tools.py']:
|
||||
(tmp_path/name).write_text((baseline/name).read_text(encoding='utf-8')+marker,encoding='utf-8')
|
||||
updates=installer.prepare(tmp_path)
|
||||
assert all(marker in updates[name] for name in ['work_client.py','work_tools.py'])
|
||||
installer.apply(tmp_path)
|
||||
assert (tmp_path/'work_client.py').read_text(encoding='utf-8').count('notify_authorization(self, data)')==2
|
||||
assert (tmp_path/'work_tools.py').read_text(encoding='utf-8').count('register_notification_tool(directory)')==1
|
||||
again=installer.prepare(tmp_path)
|
||||
assert again['work_client.py']==(tmp_path/'work_client.py').read_text(encoding='utf-8')
|
||||
|
||||
|
||||
def test_unknown_client_version_is_not_modified(tmp_path):
|
||||
for name in ['work_client.py','work_tools.py']:(tmp_path/name).write_text('# unknown version\n')
|
||||
with pytest.raises(ValueError):installer.prepare(tmp_path)
|
||||
assert (tmp_path/'work_client.py').read_text()=='# unknown version\n'
|
||||
@@ -0,0 +1,249 @@
|
||||
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'}
|
||||
Reference in New Issue
Block a user