Files
zyt/server/tests/DoctorEsignIdentityTest.php
T
2026-11-26 15:46:20 +08:00

376 lines
25 KiB
PHP

<?php
declare(strict_types=1);
namespace app\common\service\esign {
class EsignProviderException extends \RuntimeException
{
public function __construct(public string $operation, public string $providerCode) {}
}
final class EsignClient
{
public const NAME = '测试医师';
public const DOCUMENT = '110101199001011237';
public static array $identity = ['status' => 'INIT'];
public static int $starts = 0;
public static int $creates = 0;
public static string $newAccountId = 'bound-account';
public static string $requestedName = '';
public static ?string $mobile = null;
public static bool $expired = false;
public static ?\Closure $checkCertificate = null;
public static ?\Closure $duringStart = null;
public static ?\Closure $duringRecipientLookup = null;
public static ?string $account = null;
public static int $quickStarts = 0;
public static int $willingnessChecks = 0;
public static int $willingnessExpiry = 0;
public static bool $willingnessValid = true;
public static ?\Closure $duringWillingnessCheck = null;
public function startDoctorIdentity(string $name, string $contextId, string $mobile, ?string $accountId): array
{
++self::$starts;
self::$account = $accountId;
self::$requestedName = $name;
if (self::$duringStart) {
(self::$duringStart)();
}
return ['flow_id' => 'flow-' . self::$starts, 'auth_url' => 'https://smlt.esign.cn/example/' . self::$starts];
}
public function identityDetail(string $flowId): array
{
return self::$identity + ['flowId' => $flowId, 'appId' => 'fixture', 'objectType' => 'INDIVIDUAL'];
}
public function startDoctorQuickAuthorization(string $name, string $document, string $contextId, string $accountId): array
{
if ($name !== self::NAME || $document !== self::DOCUMENT || $accountId !== 'bound-account'
|| !str_starts_with($contextId, 'doctor-quicksign-')) {
throw new \RuntimeException('Wrong quick-sign authorization subject or context');
}
++self::$quickStarts;
if (self::$duringStart) {
(self::$duringStart)();
}
return ['flow_id' => 'quick-proof-' . self::$quickStarts, 'auth_url' => 'https://smlt.esign.cn/quick/' . self::$quickStarts];
}
public function willingnessValidity(string $flowId): array
{
++self::$willingnessChecks;
if (self::$duringWillingnessCheck) {
(self::$duringWillingnessCheck)();
}
if ($flowId !== 'quick-proof-' . self::$quickStarts || !self::$willingnessValid) {
return ['state' => 'exhausted', 'expires_at' => 0, 'remaining_times' => 0];
}
return ['state' => 'valid', 'expires_at' => self::$willingnessExpiry, 'remaining_times' => 2];
}
public function createPerson(string $name, string $document, string $flowId): string
{
if ($name !== self::NAME || $document !== self::DOCUMENT || $flowId !== 'flow-' . self::$starts) {
throw new \RuntimeException('Identity proof mismatch');
}
++self::$creates;
return self::$newAccountId;
}
public function signingAccount(string $accountId): array
{
return ['accountId' => $accountId, 'name' => self::NAME, 'idNo' => self::DOCUMENT,
'accountType' => 'PERSON', 'idNoType' => 'MAINLAND'];
}
public function certificateValidity(string $accountId): array
{
if (self::$checkCertificate) {
return (self::$checkCertificate)($accountId);
}
return ['startDate' => '2024-01-01 08:00:00',
'endDate' => self::$expired ? '2024-02-01 08:00:00' : '2099-01-01 08:00:00'];
}
public function authorizedMobile(string $name, string $document): ?string
{
if ($name !== self::NAME || $document !== self::DOCUMENT) {
throw new \RuntimeException('Wrong provider subject');
}
if (self::$duringRecipientLookup) {
(self::$duringRecipientLookup)();
}
return self::$mobile;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\common\service\esign\DoctorEsignIdentityRequired;
use app\common\service\esign\DoctorEsignAuthorizationRequired;
use app\common\service\esign\DoctorEsignIdentityService as Enrollment;
use app\common\service\esign\EsignClient as Provider;
use app\common\service\esign\EsignProviderException;
use think\facade\Db;
use think\Container;
$app = new think\App();
$app->instance('log', new Psr\Log\NullLogger());
$manager = new think\DbManager();
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
$config = new think\Config();
$settings = ['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture', 'app_secret' => 'fixture-secret'];
$config->set($settings, 'esign');
Container::getInstance()->instance('config', $config);
foreach (['identity', 'quicksign'] as $migration) {
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_doctor_esign_' . $migration . '.sql');
$sql = preg_replace('/\) ENGINE=.*;/u', ');', $sql);
Db::execute($sql);
Db::execute($sql);
}
Db::execute('CREATE TABLE zyt_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,disable INTEGER DEFAULT 0,delete_time INTEGER,root INTEGER DEFAULT 0)');
Db::execute('CREATE TABLE zyt_admin_role (admin_id INTEGER,role_id INTEGER)');
Db::execute('CREATE TABLE zyt_doctor_esign_account (doctor_id INTEGER,environment TEXT,app_id TEXT,account_id TEXT,
doctor_name TEXT,create_time INTEGER,UNIQUE(doctor_id,environment,app_id))');
Db::name('admin')->insertAll([['id' => 1, 'name' => Provider::NAME], ['id' => 2, 'name' => '另一位医师'], ['id' => 3, 'name' => '客服']]);
Db::name('admin_role')->insertAll([['admin_id' => 1, 'role_id' => 1], ['admin_id' => 2, 'role_id' => 1], ['admin_id' => 3, 'role_id' => 2]]);
$checks = 0;
$assert = static function (bool $condition, string $message) use (&$checks): void {
if (!$condition) {
throw new RuntimeException($message);
}
++$checks;
};
$throws = static function (callable $operation, string $expected, string $message) use ($assert): void {
try {
$operation();
} catch (Throwable $error) {
$assert(is_a($error, $expected), $message);
return;
}
$assert(false, $message);
};
$phone = '13800000000';
$assert(Enrollment::status(1)['enabled'] === false, 'SMS enrollment defaults off');
$config->set(['doctor_sms_enabled' => true], 'esign');
$unbound = Enrollment::status(1);
$assert($unbound['status'] === 'unbound' && !isset($unbound['certificate_state']), 'doctor starts unbound');
$throws(static fn () => Enrollment::status(3), DomainException::class, 'non-physician denied');
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, ''), DoctorEsignIdentityRequired::class, 'setup-required reason distinguishes an unbound doctor');
Provider::$duringStart = static function () use ($assert, $phone): void {
$duplicate = Enrollment::start(1, $phone);
$assert($duplicate['status'] === 'authenticating' && !isset($duplicate['auth_url']), 'concurrent start is held by the operation lease');
};
$first = Enrollment::start(1, $phone);
Provider::$duringStart = null;
$assert($first['status'] === 'authenticating' && Enrollment::start(1, $phone) === $first && Provider::$starts === 1,
'explicit repeat resumes the hosted flow');
$assert(Enrollment::status(2)['status'] === 'unbound', 'another physician cannot see this URL');
$config->set(['app_id' => 'other-app'], 'esign');
$assert(Enrollment::status(1)['status'] === 'unbound', 'another eSign application cannot see this URL');
$config->set(['app_id' => 'fixture'], 'esign');
$assert(!str_contains(json_encode(Db::name('doctor_esign_identity')->find()), $phone), 'mobile stored only as a keyed digest');
$assert(Enrollment::complete(1)['status'] === 'authenticating' && Provider::$creates === 0, 'unfinished H5 does not bind');
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => ['name' => Provider::NAME,
'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => '1101**********123X']];
$pending = Enrollment::status(1);
$assert($pending['status'] === 'binding_required' && $pending['identity_details_required'] && !isset($pending['auth_url'])
&& Provider::$creates === 0, 'successful polling exposes only safe metadata and accepts masked identity as supplemental');
$assert(Enrollment::complete(1, 'bad-input')['identity_details_required'] && Provider::$creates === 0, 'invalid supplemental number never reaches SDK');
$withoutMobile = Enrollment::complete(1, Provider::DOCUMENT);
$assert($withoutMobile['status'] === 'needs_mobile' && $withoutMobile['certificate_state'] === 'valid' && Provider::$creates === 1,
'successful provider proof binds without signing, but an absent provider authorization is not ready');
$assert(Db::name('doctor_esign_identity')->count() === 0 && !str_contains(json_encode(Db::name('doctor_esign_account')->find()), Provider::DOCUMENT),
'completed enrollment clears hosted URL and does not persist identity number');
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class, 'willingness requires a current authorized mobile');
$boundAccount = Db::name('doctor_esign_account')->where('doctor_id', 1)->find();
Provider::$checkCertificate = static function (string $accountId) use ($assert): array {
$assert($accountId === 'bound-account', 'certificate query uses the current signing account');
return ['startDate' => '2098-01-01 08:00:00', 'endDate' => '2099-01-01 08:00:00'];
};
$futureCertificate = Enrollment::status(1);
$assert($futureCertificate['status'] === 'renewal_required' && $futureCertificate['certificate_state'] === 'renewal_required',
'certificate validity must have already started');
Provider::$checkCertificate = static fn () => ['startDate' => '2024-01-01 08:00:00', 'endDate' => '2024-01-01 08:00:00'];
$assert(Enrollment::status(1)['certificate_state'] === 'renewal_required', 'an empty validity period cannot authorize signing');
Provider::$checkCertificate = static fn () => ['startDate' => '2024-02-30 08:00:00', 'endDate' => '2099-01-01 08:00:00'];
$badCertificate = Enrollment::status(1);
$assert($badCertificate['status'] === 'renewal_required' && $badCertificate['certificate_state'] === 'unconfirmed'
&& $badCertificate['cert_expires_at'] === 0, 'unparseable dates cannot establish certificate validity');
$throws(static fn () => Enrollment::start(1, $phone), DomainException::class, 'malformed dates cannot begin renewal');
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'TIMEOUT');
$timeout = Enrollment::status(1);
$assert($timeout['certificate_state'] === 'unconfirmed' && $timeout['cert_expires_at'] === 0 && !isset($timeout['auth_url'])
&& !str_contains(json_encode($timeout), 'TIMEOUT'), 'a transient query failure reports uncertainty without provider data');
$throws(static fn () => Enrollment::start(1, $phone), EsignProviderException::class, 'a transient failure preserves the retry path');
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'PROVIDER_123');
$providerRejection = Enrollment::status(1);
$assert($providerRejection['certificate_state'] === 'unconfirmed' && $providerRejection['cert_expires_at'] === 0
&& !str_contains(json_encode($providerRejection), 'PROVIDER_123') && Provider::$starts === 1
&& Db::name('doctor_esign_account')->where('doctor_id', 1)->find() === $boundAccount
&& Db::name('doctor_esign_identity')->count() === 0, 'recheck does not initiate or mutate enrollment on provider rejection');
Provider::$checkCertificate = null;
$assert(Enrollment::status(1)['certificate_state'] === 'valid', 'a later recheck can confirm the existing certificate');
Provider::$expired = true;
$expired = Enrollment::status(1);
$assert($expired['status'] === 'renewal_required' && $expired['certificate_state'] === 'renewal_required',
'expired provider certificate requires renewal');
Provider::$identity = ['status' => 'INIT'];
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account', 'renewal reuses canonical account');
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
Provider::$mobile = $phone;
Provider::$expired = false;
$assert(Enrollment::status(1)['identity_details_required'] === false, 'a bound account needs no supplemental input');
$ready = Enrollment::complete(1);
$assert($ready['status'] === 'ready' && $ready['certificate_state'] === 'valid'
&& $ready['cert_expires_at'] === strtotime('2099-01-01T00:00:00Z') && Provider::$creates === 1,
'same account becomes ready with certificate date in configured SDK timezone');
$assert(!str_contains(json_encode($ready), $phone) && !str_contains(json_encode($ready), Provider::DOCUMENT), 'status never returns provider identity');
$recipient = Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account');
$assert($recipient === ['name' => Provider::NAME, 'idNo' => Provider::DOCUMENT, 'mobile' => $phone], 'recipient includes only verified transient provider fields');
Provider::$duringRecipientLookup = static fn () => Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'changed']);
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DomainException::class, 'mid-flight account change cannot authorize willingness');
Provider::$duringRecipientLookup = null;
Provider::$mobile = null;
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
Provider::$identity = ['status' => 'INIT'];
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'PROVIDER_123');
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account',
'explicit renewal on provider rejection reuses the canonical account');
Provider::$checkCertificate = null;
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
$assert(Enrollment::complete(1)['certificate_state'] === 'valid' && Provider::$creates === 1,
'successful same-account recheck does not create another account');
$assert(!Enrollment::quickEnabled(), 'quick-sign is disabled by default');
$config->set(['doctor_sms_enabled' => false, 'doctor_quicksign_enabled' => true], 'esign');
$quickReady = Enrollment::status(1);
$assert($quickReady['status'] === 'ready' && $quickReady['quicksign_enabled'] && $quickReady['quicksign_expires_at'] === 0,
'a bound current certificate can enter quick-sign without SMS or previous authorization');
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
'an established signing account and historical identity are insufficient to sign');
$assert(Enrollment::start(2, '')['status'] === 'unbound' && Provider::$quickStarts === 0, 'an unbound physician cannot start a quick-sign grant');
Provider::$identity = ['status' => 'INIT'];
Provider::$duringStart = static function () use ($assert): void {
$processing = Enrollment::status(1);
$assert($processing['status'] === 'authenticating' && $processing['quicksign_authorizing'] && !isset($processing['auth_url']),
'quick-sign grant initiation is serialized');
};
$quick = Enrollment::start(1, '');
Provider::$duringStart = null;
$assert($quick['quicksign_authorizing'] && $quick['status'] === 'authenticating' && $quick['quicksign_expires_at'] === 0
&& isset($quick['auth_url']) && Enrollment::start(1, '') === $quick && Provider::$quickStarts === 1,
'empty mobile starts or resumes a distinct provider grant');
$assert(Enrollment::complete(1) === $quick && Provider::$willingnessChecks === 0, 'incomplete face authentication cannot grant signing');
$now = time();
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null, 'endTime' => $now * 1000];
Provider::$willingnessExpiry = ($now + 3 * 86400) * 1000;
$quickPending = Enrollment::status(1);
$assert($quickPending['status'] === 'binding_required' && $quickPending['quicksign_authorizing']
&& !$quickPending['identity_details_required'] && $quickPending['quicksign_expires_at'] === 0 && !isset($quickPending['auth_url']),
'provider success waits for explicit physician confirmation without another identity prompt');
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
'provider face verification alone does not activate grant');
$quickGranted = Enrollment::complete(1);
$assert($quickGranted['status'] === 'ready' && !$quickGranted['quicksign_authorizing']
&& $quickGranted['quicksign_expires_at'] === $now + 3 * 86400 && $quickGranted['quicksign_remaining_times'] === 2
&& !str_contains(json_encode($quickGranted), 'quick-proof') && !str_contains(json_encode($quickGranted), Provider::DOCUMENT),
'confirmed provider proof follows provider expiry and remains server-only');
$quickRow = Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->find();
$assert($quickRow['flow_id'] === 'quick-proof-1' && $quickRow['auth_url'] === null
&& Db::name('doctor_esign_identity')->count() === 0 && Provider::$creates === 1, 'grant clears its hosted link and keeps enrollment untouched');
$checksBeforeReuse = Provider::$willingnessChecks;
Provider::$willingnessExpiry = ($now + 120) * 1000 + 123;
$assert(Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account') === 'quick-proof-1'
&& Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account') === 'quick-proof-1'
&& Provider::$willingnessChecks === $checksBeforeReuse + 2,
'the same independent proof can be reused with a fresh provider check each time');
$assert(Enrollment::status(1)['quicksign_expires_at'] === $now + 120, 'reported validity honors a shorter provider expiry');
$assert(Enrollment::start(1, '')['quicksign_expires_at'] === $now + 120 && Provider::$quickStarts === 1, 'a current grant is never replaced by a casual repeat');
$throws(static fn () => Enrollment::quickAuthorization(2, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
'another physician cannot use this proof');
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'other-account'), DomainException::class,
'signatures must match the authorized SDK account');
$config->set(['app_id' => 'other-app'], 'esign');
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
'another eSign application cannot use this proof');
$config->set(['app_id' => 'fixture'], 'esign');
Provider::$duringWillingnessCheck = static fn () => Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'changed']);
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DomainException::class,
'a mid-flight account change invalidates the checked result');
Provider::$duringWillingnessCheck = null;
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
Provider::$willingnessValid = false;
$spent = Enrollment::status(1);
$assert($spent['quicksign_expires_at'] === 0 && $spent['quicksign_remaining_times'] === 0
&& $spent['quicksign_unavailable_reason'] === 'exhausted' && $spent['status'] === 'ready' && $spent['certificate_state'] === 'valid',
'provider exhaustion leaves certificate enrollment valid and reports the spent grant');
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
'provider cancellation/exhaustion blocks dispatch');
Provider::$willingnessValid = true;
Provider::$expired = true;
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
'expired identity certificate is distinct from an unavailable signing grant');
Provider::$expired = false;
$checksBeforeExpiry = Provider::$willingnessChecks;
Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->update(['expires_at' => time() - 1]);
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
'locally expired grant remains invalid even if the provider still accepts the flow');
$assert(Provider::$willingnessChecks === $checksBeforeExpiry && Enrollment::status(1)['status'] === 'ready'
&& Enrollment::status(1)['quicksign_expires_at'] === 0, 'expired grant leaves the current signing account enrolled');
Provider::$identity = ['status' => 'INIT'];
$assert(Enrollment::start(1, '')['quicksign_authorizing'] && Provider::$quickStarts === 2, 'expired grant permits a new standalone grant');
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
$assert(Enrollment::complete(1)['quicksign_expires_at'] === $now + 120, 'provider validity is preserved when shorter than the local bound');
$config->set(['review_enabled' => true], 'esign');
Db::name('admin')->insert(['id' => 4, 'name' => 'admin', 'root' => 1]);
Provider::$identity = ['status' => 'INIT'];
Provider::$newAccountId = 'reviewer-account';
$startsBeforeReview = Provider::$starts;
$assert(Enrollment::status(4)['can_edit_signer_name'] === true, 'an unbound reviewer can supply a separate legal name');
$throws(static fn () => Enrollment::start(2, $phone, Provider::NAME), DomainException::class,
'the reviewer-only input does not override a physician roster name');
$throws(static fn () => Enrollment::start(4, $phone, '<姓名>'), DomainException::class,
'invalid names are rejected before contacting eSign');
$oldReview = Enrollment::start(4, $phone);
$newReview = Enrollment::start(4, $phone, Provider::NAME);
$assert($newReview['auth_url'] !== $oldReview['auth_url'] && Provider::$requestedName === Provider::NAME
&& Enrollment::status(4)['can_edit_signer_name'] && Provider::$starts === $startsBeforeReview + 2,
'correcting an unfinished reviewer name requests a new provider URL');
$assert(Enrollment::start(4, $phone, Provider::NAME) === $newReview && Provider::$starts === $startsBeforeReview + 2,
'resubmitting the same name and number restores the pending flow');
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => ['name' => Provider::NAME,
'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => Provider::DOCUMENT]];
$assert(Enrollment::start(4, $phone, '错误姓名')['status'] === 'binding_required' && Provider::$starts === $startsBeforeReview + 2,
'an already verified identity cannot be replaced on retry');
$assert(Enrollment::complete(4)['status'] === 'ready'
&& Db::name('doctor_esign_account')->where('doctor_id', 4)->value('doctor_name') === Provider::NAME
&& Db::name('admin')->where('id', 4)->value('name') === 'admin',
'verified legal name is saved only to the reviewer signing account');
$throws(static fn () => Enrollment::start(4, $phone, '不同姓名'), DomainException::class,
'a verified signing account cannot be renamed through enrollment');
echo "Doctor eSign enrollment: $checks checks passed (SQLite and provider doubles)\n";
}