Files
ecs-relay-service/deployable/relay/notifications.py
ex_tianzy d1ab834ecb feat(lifecycle): add stage 4 authoritative unbind and durable task routing
Unify broker-mode binding changes in database transactions: advance device
generation, invalidate pending authorizations/tasks and prior pairing-code
epochs, and persist audit plus invalidation outbox. Add authenticated device
unbind alongside robot/admin paths. Pairing codes are hashed, generation-
fenced and consumed atomically with binding.

Replay Redis invalidation effects without undoing committed unbind. Guard
online cleanup and delayed kill events by generation. Introduce a separate
router admission credential with no platform-event injection authority.
Router verifies signed nonce-bound internal admission on handshake, task
traffic and periodic checks; reject stale sessions and control-plane outages.

Persist task owner/device/generation/session/worker and original message
mapping. Sign routing metadata, verify late results, claim replies once and
mark ambiguous/crashed tasks unknown instead of replaying writes. Fence
notifications across same-user rebind. Release in-memory slots/waiters even
when database or Redis cleanup fails.

Validation: 213 passed, 3 skipped (real PostgreSQL not configured), 30 existing
uvicorn/websockets deprecation warnings. New lifecycle coverage: 28 tests,
including real loopback WebSocket isolation, reverse completion, missed kill,
periodic unbind checks, outbox recovery, transaction rollback and cleanup
failures. Syntax, docs and staged diff checks pass.

Default legacy mode remains unchanged. Broker mode now requires coordinated
router admission configuration and a v2 client handshake. No production ECS
configuration, real credentials or client installer was changed. PostgreSQL,
real Redis multi-node, ARM64 and actual Work/client rollout remain stage 5.
2026-11-04 11:43:53 +08:00

142 lines
7.8 KiB
Python

"""Device-authenticated outbound messages. Recipient and OAuth links are server-owned."""
import hashlib
import json
import time
import uuid
from urllib.parse import urlencode
from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from .common import no_cache, rate_limit
from .crypto import canonical
from .store import INTEGRITY_ERRORS
from .device_auth import device_owner
class Notification(BaseModel):
model_config = ConfigDict(extra='forbid')
host_id: str = Field(pattern=r'^[a-f0-9]{32}$')
proof: dict
request_id: str = Field(pattern=r'^[A-Za-z0-9_-]{8,100}$')
binding_owner: str = Field(min_length=1, max_length=128)
binding_generation: int | None = Field(default=None,strict=True,ge=0)
kind: str = Field(pattern=r'^(text|notice|authorization)$')
title: str = Field(default='', max_length=80)
text: str = Field(default='', max_length=2000)
oauth_state: str = Field(default='', max_length=100)
def router(settings, redis, store, platform, oauth):
routes = APIRouter()
store.db.execute('''CREATE TABLE IF NOT EXISTS notifications(
host_id TEXT NOT NULL, request_id TEXT NOT NULL, owner TEXT NOT NULL,
request_hash TEXT NOT NULL, status TEXT NOT NULL, message_id TEXT NOT NULL,
created DOUBLE PRECISION NOT NULL, PRIMARY KEY(host_id,request_id))''')
if not settings.database_url:
store.db.commit()
@routes.post('/device/notifications')
async def notify(body: Notification):
if not settings.feishu_enabled:
raise HTTPException(503, 'platform disabled')
payload = body.model_dump(exclude={'host_id', 'proof'})
if body.binding_generation is None:
payload.pop('binding_generation') # Preserve exact legacy proof contract.
owner = await device_owner(settings, redis, store, body.host_id, body.proof,
'work-notify-v1', payload)
if body.binding_owner != owner:
raise HTTPException(403, 'local binding is stale; pair the client again')
if settings.credential_mode == 'broker':
current = store.device(body.host_id)
if body.binding_generation is None or current['binding_generation'] != body.binding_generation:
raise HTTPException(403,'stale_binding')
digest = hashlib.sha256(canonical(payload)).hexdigest()
previous = store.db.execute('SELECT * FROM notifications WHERE host_id=? AND request_id=?',
(body.host_id, body.request_id)).fetchone()
if previous:
return duplicate(dict(previous), owner, digest)
await rate_limit(redis, 'notify-device:' + body.host_id, 10)
await rate_limit(redis, 'notify-owner:' + owner, 10)
if body.kind == 'authorization':
if body.text or body.title or not body.oauth_state:
raise HTTPException(422, 'authorization requires only a pending OAuth state')
if hasattr(oauth, 'authorization_url_for_notification'):
url = oauth.authorization_url_for_notification(owner, body.host_id, body.oauth_state)
else:
oauth.prune()
item = oauth.pending.get(body.oauth_state)
if (not settings.oauth_enabled or not item or item.status != 'waiting'
or item.owner != owner or item.host_id != body.host_id):
raise HTTPException(403, 'active device-owned authorization required')
params = {'app_id': settings.feishu_app_id,
'redirect_uri': settings.public_url.rstrip('/') + '/oauth/cb',
'state': body.oauth_state}
if settings.feishu_oauth_scopes:
params['scope'] = settings.feishu_oauth_scopes
url = settings.feishu_authorize_url + '?' + urlencode(params)
if not url.startswith('https://'):
raise HTTPException(503, 'HTTPS authorization URL required')
content = {'config': {'wide_screen_mode': True},
'header': {'title': {'tag': 'plain_text', 'content': '海能Work 用户授权'}},
'elements': [
{'tag': 'div', 'text': {'tag': 'plain_text', 'content': '本机海诺需要本人授权。请使用与电脑绑定一致的账号完成授权;链接短时有效,过期请重新发起。'}},
{'tag': 'action', 'actions': [{'tag': 'button', 'type': 'primary',
'text': {'tag': 'plain_text', 'content': '前往授权'}, 'url': url}]}]}
msg_type = 'interactive'
else:
if body.oauth_state or not body.text.strip():
raise HTTPException(422, 'notification text required; OAuth state is not allowed')
if body.kind == 'text':
if body.title:
raise HTTPException(422, 'text messages do not accept title')
msg_type, content = 'text', {'text': body.text}
else:
msg_type = 'interactive'
content = {'header': {'title': {'tag': 'plain_text', 'content': body.title or '海诺通知'}},
'elements': [{'tag': 'div', 'text': {'tag': 'plain_text', 'content': body.text}}]}
try:
with store.db:
store.db.execute('INSERT INTO notifications VALUES(?,?,?,?,?,?,?)',
(body.host_id, body.request_id, owner, digest, 'inflight', '', time.time()))
except INTEGRITY_ERRORS:
row = store.db.execute('SELECT * FROM notifications WHERE host_id=? AND request_id=?',
(body.host_id, body.request_id)).fetchone()
return duplicate(dict(row), owner, digest)
status, message_id = 'unknown', ''
try:
# Complete credential acquisition before the last synchronous binding check.
token = await platform.tenant_token()
if body.kind == 'authorization' and hasattr(oauth, 'authorization_url_for_notification'):
# Recheck the transaction and generation after waiting on app credentials.
oauth.authorization_url_for_notification(owner, body.host_id, body.oauth_state)
device = store.device(body.host_id)
if (not device or device['revoked'] or device['owner'] != owner
or (settings.credential_mode == 'broker' and device['binding_generation'] != body.binding_generation)):
status = 'binding_changed'
else:
delivery_id = uuid.uuid5(uuid.NAMESPACE_URL, body.host_id + ':' + body.request_id).hex
result = await platform.send(owner, msg_type, content, delivery_id, token=token)
message_id = result.get('message_id', '')
status = 'sent' if message_id else 'unknown'
except Exception:
# A timeout may follow successful delivery. Do not retry or expose upstream secrets.
status = 'unknown'
with store.db:
store.db.execute('UPDATE notifications SET status=?,message_id=? WHERE host_id=? AND request_id=?',
(status, message_id, body.host_id, body.request_id))
store.audit(owner, 'device_notification', body.request_id, status)
return no_cache(JSONResponse({'status': status, 'request_id': body.request_id,
'message_id': message_id}))
return routes
def duplicate(row, owner, digest):
if row['owner'] != owner or row['request_hash'] != digest:
raise HTTPException(409, 'request_id reused across owner or content')
return no_cache(JSONResponse({'status': 'duplicate', 'previous_status': row['status'],
'request_id': row['request_id'], 'message_id': row['message_id']}))