91 lines
5.0 KiB
Python
91 lines
5.0 KiB
Python
"""C2 approval presentation and delivery through the dedicated DB worker."""
|
|
import asyncio
|
|
import hashlib
|
|
import math
|
|
import re
|
|
import time
|
|
|
|
from .approval_store import ApprovalError, _public_text
|
|
|
|
|
|
def approval_card(material, clock=time.time):
|
|
reference, nonce = material.get('approval_id'), material.get('nonce')
|
|
if (not isinstance(reference, str) or not re.fullmatch(r'apr_[a-f0-9]{64}', reference)
|
|
or not isinstance(nonce, str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}', nonce)):
|
|
raise ApprovalError('invalid_approval_reference')
|
|
summary = _public_text(material.get('summary'), 200)
|
|
impact = _public_text(material.get('impact'), 500)
|
|
expiry = material.get('expires_at')
|
|
if type(expiry) not in (int, float) or not math.isfinite(expiry) or expiry <= clock():
|
|
raise ApprovalError('approval_task_expired')
|
|
seconds = min(600, max(1, math.ceil(expiry - clock())))
|
|
buttons = []
|
|
for choice, label, style in (('allow', '允许本次', 'primary'), ('deny', '拒绝', 'default')):
|
|
buttons.append({'tag': 'button', 'text': {'tag': 'plain_text', 'content': label},
|
|
'type': style, 'value': {'kind': 'hainuo.approval.v1', 'approval_id': reference,
|
|
'nonce': nonce, 'choice': choice}})
|
|
return {'config': {'wide_screen_mode': True, 'enable_forward': False, 'update_multi': True},
|
|
'header': {'template': 'orange', 'title': {'tag': 'plain_text', 'content': '海诺操作确认'}},
|
|
'elements': [
|
|
{'tag': 'div', 'text': {'tag': 'plain_text', 'content': '准备做什么:' + summary}},
|
|
{'tag': 'div', 'text': {'tag': 'plain_text', 'content': '可能的影响:' + impact}},
|
|
{'tag': 'div', 'text': {'tag': 'plain_text', 'content': '仅允许本次操作;约' + str(seconds) + '秒后失效。'}},
|
|
{'tag': 'action', 'actions': buttons}]}
|
|
|
|
|
|
class ApprovalCardSender:
|
|
def __init__(self, approvals, platform):
|
|
self.approvals, self.platform = approvals, platform
|
|
|
|
async def send(self, approval_id):
|
|
material = await self.approvals.call('card_material',approval_id)
|
|
# Prepare before claiming: invalid presentation must not consume an intent.
|
|
card = approval_card(material, self.approvals.clock)
|
|
token = await self.platform.tenant_token()
|
|
if not await self.approvals.call('claim_card',approval_id):
|
|
return {'state': 'already_sent_or_unconfirmed'}
|
|
delivery_id = hashlib.sha256(('approval-card-v1\0' + approval_id).encode()).hexdigest()[:32]
|
|
try:
|
|
# Receipt is the actual reply card ID, never the source user message.
|
|
message_id = await asyncio.wait_for(self.platform.reply_task_card(
|
|
material['source_message_id'], card, delivery_id, token=token), timeout=10)
|
|
await self.approvals.call('bind_card',approval_id, message_id)
|
|
except BaseException:
|
|
# Cancellation/timeout can occur after platform acceptance. Never
|
|
# infer "not sent" and automatically issue another confirmation.
|
|
await self.approvals.call('card_send_unknown',approval_id)
|
|
raise
|
|
return {'state': 'sent'}
|
|
|
|
async def update_closed(self,approval_id,refresh=False):
|
|
receipt=await self.approvals.call('closed_card_receipt',approval_id,refresh)
|
|
if not receipt:return {'state':'no_closed_card'}
|
|
card=closed_approval_card(receipt['state'])
|
|
token=await self.platform.tenant_token()
|
|
# Updating the known original message is retryable; sending a new
|
|
# confirmation card after a lost create receipt is not.
|
|
await asyncio.wait_for(self.platform.update_task_card(
|
|
receipt['message_id'],card,token=token),timeout=5)
|
|
await self.approvals.call('mark_card_closed',approval_id,receipt['state'])
|
|
return {'state':'updated'}
|
|
|
|
|
|
def closed_approval_card(state):
|
|
messages={'rejected':'你已拒绝本次操作。',
|
|
'expired':'本次确认已过期,未获得新的执行许可;需要时请重新发起任务。',
|
|
'cancelled':'本次确认已取消,不能再通过这张卡片批准。',
|
|
'consumed':'本次许可已交给客户端;是否执行及执行结果请查看任务进度。'}
|
|
if state not in messages:raise ApprovalError('approval_not_closed')
|
|
return {'config':{'wide_screen_mode':True,'enable_forward':False,'update_multi':True},
|
|
'header':{'template':'grey','title':{'tag':'plain_text','content':'海诺操作确认已结束'}},
|
|
'elements':[{'tag':'div','text':{'tag':'plain_text','content':messages[state]}}]}
|
|
|
|
|
|
def decision_response_card(state):
|
|
if state=='approved':
|
|
return {'config':{'wide_screen_mode':True,'enable_forward':False,'update_multi':True},
|
|
'header':{'template':'blue','title':{'tag':'plain_text','content':'海诺操作已允许'}},
|
|
'elements':[{'tag':'div','text':{'tag':'plain_text',
|
|
'content':'你已允许本次操作,等待客户端继续。执行结果请查看任务进度。'}}]}
|
|
return closed_approval_card(state)
|