"""C2 callback verifier; HTTP registration is opt-in in approval_api. Only the SDK worker's authenticated internal channel or a signed platform webhook may enter here. action.value is a reference, never actor identity. """ import base64 import hashlib import hmac import json import re import time from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from .approval_store import ApprovalError, VerifiedDecision from .crypto import canonical class CallbackError(ApprovalError): pass def _pairs(pairs): result = {} for key, value in pairs: if key in result: raise CallbackError('ambiguous_callback') result[key] = value return result def _json(raw): if not isinstance(raw, bytes) or not 0 < len(raw) <= 65536: raise CallbackError('invalid_callback_budget') try: data = json.loads(raw, object_pairs_hook=_pairs, parse_constant=lambda _: (_ for _ in ()).throw(ValueError())) if not isinstance(data, dict): raise ValueError() return data except (ValueError, RecursionError, UnicodeError): raise CallbackError('invalid_callback_json') from None def _text(value, pattern=r'[A-Za-z0-9_-]{1,128}'): if not isinstance(value, str) or not re.fullmatch(pattern, value): raise CallbackError('invalid_callback_field') return value def _equal_secret(actual, expected): return (isinstance(actual, str) and isinstance(expected, str) and bool(expected) and hmac.compare_digest(actual.encode(), expected.encode())) class ApprovalCallbackVerifier: def __init__(self, *, environment, app_id, tenant_key, verification_token, internal_secret='', encrypt_key='', clock=time.time): self.environment = _text(environment) self.app_id = _text(app_id) self.tenant_key = _text(tenant_key) if not isinstance(verification_token, str) or not verification_token: raise CallbackError('callback_verifier_not_configured') self.verification_token = verification_token self.internal_secret = internal_secret self.encrypt_key = encrypt_key self.clock = clock def from_sdk_channel(self, raw, supplied_secret): """Future internal handler only; never expose as an unauthenticated API. Caller must enforce selected event source, a bounded body and the private network boundary. The secret is not read from callback JSON. """ if len(self.internal_secret) < 32 or not _equal_secret(supplied_secret, self.internal_secret): raise CallbackError('unauthenticated_callback_channel') return self._decision(_json(raw)) def from_webhook(self, raw, *, timestamp, nonce, signature): """Verify the original bytes before decrypting. No token-only fallback.""" if not self.encrypt_key: raise CallbackError('callback_verifier_not_configured') _text(timestamp, r'[0-9]{1,12}') _text(nonce) _text(signature, r'[a-f0-9]{64}') if abs(self.clock() - int(timestamp)) > 300: raise CallbackError('stale_callback') if not isinstance(raw, bytes) or not 0 < len(raw) <= 65536: raise CallbackError('invalid_callback_budget') expected = hashlib.sha256((timestamp + nonce + self.encrypt_key).encode() + raw).hexdigest() if not hmac.compare_digest(expected, signature): raise CallbackError('unauthenticated_callback_channel') envelope = _json(raw) try: if set(envelope) != {'encrypt'} or not isinstance(envelope['encrypt'], str): raise ValueError() ciphertext = base64.b64decode(envelope['encrypt'], validate=True) if len(ciphertext) < 32 or len(ciphertext) % 16: raise ValueError() decryptor = Cipher(algorithms.AES(hashlib.sha256(self.encrypt_key.encode()).digest()), modes.CBC(ciphertext[:16])).decryptor() padded = decryptor.update(ciphertext[16:]) + decryptor.finalize() unpadder = padding.PKCS7(128).unpadder() plaintext = unpadder.update(padded) + unpadder.finalize() except (ValueError, TypeError): raise CallbackError('invalid_callback_ciphertext') from None return self._decision(_json(plaintext)) def _decision(self, data): header, event = data.get('header'), data.get('event') if data.get('schema') != '2.0' or not isinstance(header, dict) or not isinstance(event, dict): raise CallbackError('unsupported_callback') if (header.get('event_type') != 'card.action.trigger' or header.get('app_id') != self.app_id or header.get('tenant_key') != self.tenant_key or not _equal_secret(header.get('token'), self.verification_token)): raise CallbackError('callback_application_conflict') event_id = _text(header.get('event_id')) created = _text(header.get('create_time'), r'[0-9]{1,20}') if abs(self.clock() - int(created) / 1000000) > 300: raise CallbackError('stale_callback') operator, context, action = event.get('operator'), event.get('context'), event.get('action') if not all(isinstance(item, dict) for item in (operator, context, action)): raise CallbackError('invalid_callback_context') if (event.get('host') != 'im_message' or action.get('tag') != 'button' or operator.get('tenant_key') != self.tenant_key): raise CallbackError('unsupported_callback_context') value = action.get('value') if isinstance(value, str): value = _json(value.encode()) if not isinstance(value, dict) or set(value) != {'kind', 'approval_id', 'nonce', 'choice'}: raise CallbackError('invalid_approval_reference') if value['kind'] != 'hainuo.approval.v1' or value['choice'] not in ('allow', 'deny'): raise CallbackError('invalid_approval_choice') fields = dict(environment=self.environment, app_id=self.app_id, actor_open_id=_text(operator.get('open_id'), r'ou_[A-Za-z0-9_-]{1,120}'), chat_id=_text(context.get('open_chat_id'), r'oc_[A-Za-z0-9_-]{1,120}'), card_message_id=_text(context.get('open_message_id'), r'om_[A-Za-z0-9_-]{1,120}'), approval_id=_text(value['approval_id'], r'apr_[a-f0-9]{64}'), nonce=_text(value['nonce'], r'[A-Za-z0-9_-]{43}'), choice=value['choice']) # No token, raw callback or user text is persisted in the receipt. digest = hashlib.sha256(canonical(fields)).hexdigest() return VerifiedDecision(**fields, event_id=event_id, event_digest=digest) def decision_toast(status): """Bounded platform response; never starts a task or executes an action.""" state = status.get('state') if isinstance(status, dict) else None messages = {'approved': '已允许本次操作,等待客户端继续。', 'rejected': '已拒绝本次操作。', 'expired': '确认已过期,请重新发起。', 'consumed': '本次确认已使用,请勿重复操作。', 'cancelled': '本次操作已取消。'} return {'toast': {'type': 'info', 'content': messages.get(state, '确认未完成,请核对任务状态。')}}