Files
xieyi-weixin-/test_native_evidence.py
T
2026-09-21 10:56:48 +08:00

137 lines
8.0 KiB
Python

"""Only confirmed manual evidence can enable a pending adapter; never flags alone."""
from dataclasses import replace
import hashlib
import json
from pathlib import Path
import sqlite3
import tempfile
from types import SimpleNamespace
import unittest
from unittest import mock
from wecom_native_builds import build_for_version
from wecom_native_evidence import TEST_TEXT, local_send_receipt, send_authorized
from wecom_native_sender import NativeClient, NativeUnavailable
from reply_transport import protocol_ready
class EvidenceTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name); self.path = self.root / 'protocol_sends.sqlite3'
self.profile = build_for_version('5.0.11.6018')
self.request = f'manual-verification:1.4.15:{self.profile.version}:100:S:100_200'
self.receipt = dict(status='confirmed', nativeCallback='success', clientVersion=self.profile.version,
clientSha256=self.profile.sha256, adapterRevision=self.profile.adapter_revision,
accountId='100', conversationId='S:100_200', messageId=1, serverId=2,
senderVerified=True, textVerified=True)
self.enterContext(mock.patch('wecom_native_evidence.application_data_dir', return_value=self.root))
def save(self, *, receipt=None, status='confirmed', request=None, text=TEST_TEXT):
connection = sqlite3.connect(self.path)
connection.execute('CREATE TABLE IF NOT EXISTS sends(request_id TEXT PRIMARY KEY,fingerprint TEXT,status TEXT,result TEXT,created REAL)')
connection.execute('DELETE FROM sends')
fingerprint = hashlib.sha256(json.dumps(['100', 'S:100_200', text], ensure_ascii=False).encode()).hexdigest()
connection.execute('INSERT INTO sends VALUES(?,?,?,?,?)',
(request or self.request, fingerprint, status, json.dumps(self.receipt if receipt is None else receipt), 1))
connection.commit(); connection.close()
def test_no_evidence_does_not_create_database_or_enable_sending(self):
self.assertFalse(send_authorized(self.profile, '100'))
self.assertFalse(self.path.exists())
self.assertTrue(send_authorized(build_for_version('5.0.10.6023'), '100'))
def test_confirmed_evidence_is_account_build_and_revision_bound(self):
self.save()
self.assertEqual(local_send_receipt(self.profile, '100'), self.receipt)
self.assertTrue(send_authorized(self.profile, '100'))
self.assertFalse(send_authorized(self.profile, '101'))
self.assertFalse(send_authorized(replace(self.profile, sha256='0' * 64), '100'))
self.assertFalse(send_authorized(replace(self.profile, adapter_revision='next'), '100'))
def test_failed_incomplete_or_wrong_receipt_cannot_enable(self):
changes = [{'nativeCallback':'error'}, {'senderVerified':False}, {'textVerified':False},
{'messageId':0}, {'serverId':True}, {'status':'unknown'}, {'accountId':'101'},
{'clientVersion':'5.0.10.6023'}, {'conversationId':'S:100_201'},
{'clientSha256':'0' * 64}, {'adapterRevision':'unknown'}]
for change in changes:
with self.subTest(change=change):
self.save(receipt={**self.receipt, **change})
self.assertFalse(send_authorized(self.profile, '100'))
for status in ('failed', 'unknown'):
self.save(status=status); self.assertFalse(send_authorized(self.profile, '100'))
def test_only_fixed_manual_test_with_matching_fingerprint_counts(self):
self.save(request='automatic:5.0.11.6018:100:S:100_200')
self.assertFalse(send_authorized(self.profile, '100'))
self.save(text='another message')
self.assertFalse(send_authorized(self.profile, '100'))
self.path.write_bytes(b'not sqlite')
self.assertFalse(send_authorized(self.profile, '100'))
def test_report_flags_and_exported_json_do_not_enable_without_journal(self):
report = dict(status='native_ready', nativeAdapter=self.profile.adapter_id, clientSha256=self.profile.sha256,
nativeAccount='100', canSend=True, loginVerified=True, adapterInstalled=True,
sendVerified=True, receiptVerified=True, databaseReady=True, localSendVerified=True)
(self.root / 'report.json').write_text(json.dumps(self.receipt))
self.assertFalse(protocol_ready(report))
self.save(); self.assertTrue(protocol_ready(report))
self.assertFalse(protocol_ready({**report, 'nativeAccount':'101'}))
self.assertFalse(protocol_ready({**report, 'clientSha256':'0' * 64}))
self.assertFalse(protocol_ready({**report, 'databaseReady':False}))
def test_probe_moves_to_ready_only_after_confirmed_journal(self):
import wxwork_protocol_probe as probe
live = dict(pid=1, accountId='100', clientVersion=self.profile.version, clientSha256=self.profile.sha256)
client = dict(pid=1, path=r'E:\企业 微信\WXWork.exe', version=self.profile.version, architecture='x86')
with mock.patch.object(probe, 'running_clients', return_value=[client]), \
mock.patch.object(probe, 'inspect_binary', return_value={}), \
mock.patch.object(probe, 'bundled_agent_info', return_value={}), \
mock.patch('wecom_native_sender.discover', return_value=live), \
mock.patch('wecom_environment.protocol_database_status', return_value={'ready':True}):
before = probe.probe_installed_client()
self.assertTrue(before['needsSendValidation']); self.assertFalse(protocol_ready(before))
self.save()
after = probe.probe_installed_client()
self.assertTrue(after['localSendVerified']); self.assertTrue(protocol_ready(after))
self.assertFalse(after['needsSendValidation'])
self.assertEqual(after['verificationScope'], 'current_account')
class ClientGateTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / 'WXWork.exe'; self.path.write_bytes(b'fixture')
self.profile = build_for_version('5.0.11.6018')
self.k = mock.Mock()
self.k.CreateToolhelp32Snapshot.return_value = 1
def first(snapshot, pointer):
module = pointer._obj; module.szModule = 'WXWork.exe'
module.szExePath = str(self.path); module.modBaseAddr = 0x400000
return True
self.k.Module32FirstW.side_effect = first
self.k.OpenProcess.side_effect = [10, 20]
self.enterContext(mock.patch('wecom_native_sender.kernel', return_value=self.k))
self.enterContext(mock.patch('wecom_native_sender._client_file_digest', return_value=self.profile.sha256))
self.validate = self.enterContext(mock.patch.object(NativeClient, 'validate', return_value='100'))
self.authorized = self.enterContext(mock.patch('wecom_native_sender.send_authorized', return_value=False))
def test_pending_build_cannot_even_acquire_write_handle_without_evidence(self):
with self.assertRaisesRegex(NativeUnavailable, '首次发送'):
NativeClient(1, write=True)
self.k.OpenProcess.assert_called_once_with(0x410, False, 1)
def test_confirmed_evidence_allows_write_after_readonly_identity_check(self):
self.authorized.return_value = True
with NativeClient(1, write=True):
self.assertEqual(self.k.OpenProcess.call_args_list, [mock.call(0x410,False,1), mock.call(0x43a,False,1)])
self.authorized.assert_called_once_with(self.profile, '100')
self.assertEqual(self.validate.call_count, 2)
def test_account_change_while_opening_write_handle_cancels(self):
self.authorized.return_value = True; self.validate.side_effect = ['100', '101']
with self.assertRaisesRegex(NativeUnavailable, '账号已变化'):
NativeClient(1, write=True)
if __name__ == '__main__': unittest.main()