230 lines
14 KiB
PHP
230 lines
14 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
// Isolated adapter tests: no ThinkPHP bootstrap, credentials, database or network.
|
|
require_once dirname(__DIR__) . '/app/common/service/esign/EsignClient.php';
|
|
|
|
use app\common\service\esign\EsignClient;
|
|
use app\common\service\esign\EsignOutcomeUnknownException;
|
|
use app\common\service\esign\EsignProviderException;
|
|
|
|
$checks = 0;
|
|
function esignExpect(bool $condition, string $label): void
|
|
{
|
|
global $checks;
|
|
++$checks;
|
|
if (!$condition) {
|
|
throw new RuntimeException('FAIL: ' . $label);
|
|
}
|
|
}
|
|
|
|
function esignThrows(callable $call, string $class, string $code): EsignProviderException
|
|
{
|
|
try {
|
|
$call();
|
|
} catch (EsignProviderException $exception) {
|
|
esignExpect(get_class($exception) === $class, 'exception type ' . $code);
|
|
esignExpect($exception->providerCode === $code, 'exception code ' . $code);
|
|
esignExpect($exception->getPrevious() === null, 'no sensitive previous exception');
|
|
return $exception;
|
|
}
|
|
throw new RuntimeException('Expected exception: ' . $code);
|
|
}
|
|
|
|
function esignConfig(array $overrides = []): array
|
|
{
|
|
return array_replace([
|
|
'enabled' => true, 'environment' => 'sandbox', 'app_id' => 'test-app', 'app_secret' => 'test-secret',
|
|
'sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service', 'timeout' => 45,
|
|
], $overrides);
|
|
}
|
|
|
|
function esignResponse(array $data, int $status = 200): array
|
|
{
|
|
return ['status' => $status, 'body' => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
|
|
}
|
|
|
|
/** @return array<string,array{headers:string,body:string}> */
|
|
function esignMultipartParts(array $request): array
|
|
{
|
|
$contentType = $request['headers']['Content-Type'];
|
|
esignExpect(str_starts_with($contentType, 'multipart/form-data; boundary='), 'multipart envelope');
|
|
$boundary = substr($contentType, strlen('multipart/form-data; boundary='));
|
|
$parts = [];
|
|
foreach (explode('--' . $boundary, $request['body']) as $part) {
|
|
if (!str_contains($part, "\r\n\r\n")) {
|
|
continue;
|
|
}
|
|
[$headers, $body] = explode("\r\n\r\n", ltrim($part, "\r\n"), 2);
|
|
preg_match('/name="([^"]+)"/', $headers, $matches);
|
|
$parts[$matches[1]] = ['headers' => $headers, 'body' => substr($body, 0, -2)];
|
|
}
|
|
return $parts;
|
|
}
|
|
|
|
$requests = [];
|
|
$responses = [];
|
|
$transport = static function (array $request) use (&$requests, &$responses): array {
|
|
$requests[] = $request;
|
|
if ($responses === []) {
|
|
throw new RuntimeException('No fake response');
|
|
}
|
|
return array_shift($responses);
|
|
};
|
|
$clock = static fn (): int => 1800000000000;
|
|
$client = new EsignClient(esignConfig(), $transport, $clock);
|
|
esignExpect($client->isEnabled() && $client->environment() === 'sandbox', 'configured environment');
|
|
$client->assertConfigured();
|
|
|
|
foreach ([
|
|
[['enabled' => 'false'], 'DISABLED'],
|
|
[['environment' => 'prod'], 'ENVIRONMENT_INVALID'],
|
|
[['app_secret' => ''], 'CREDENTIALS_MISSING'],
|
|
[['app_id' => "app\r\nInjected:yes"], 'CREDENTIALS_MISSING'],
|
|
[['timeout' => 0], 'TIMEOUT_INVALID'],
|
|
[['timeout' => 301], 'TIMEOUT_INVALID'],
|
|
[['sdk_url' => 'http://example.com/paas-sdk-service'], 'SDK_HTTP_REQUIRES_PRIVATE_HOST'],
|
|
[['sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service?x=1'], 'SDK_URL_INVALID'],
|
|
[['sdk_url' => 'https://user:pass@example.com/paas-sdk-service'], 'SDK_URL_INVALID'],
|
|
[['sdk_url' => 'file:///tmp/paas-sdk-service'], 'SDK_URL_INVALID'],
|
|
] as [$config, $code]) {
|
|
esignThrows(fn () => (new EsignClient(esignConfig($config), $transport, $clock))->assertConfigured(), EsignProviderException::class, $code);
|
|
}
|
|
esignExpect($requests === [], 'configuration failures issue no request');
|
|
|
|
$responses[] = esignResponse(['errCode' => 0]);
|
|
$client->initialize();
|
|
$init = json_decode($requests[0]['body'], true);
|
|
esignExpect($requests[0]['url'] === 'http://127.0.0.1:8091/paas-sdk-service/timevale/init', 'SDK init endpoint');
|
|
esignExpect($init['projectConfig'] === [
|
|
'projectId' => 'test-app', 'projectSecret' => 'test-secret',
|
|
'itsmApiUrl' => 'https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2',
|
|
], 'sandbox initialization parameters');
|
|
esignExpect($init['httpConfig'] === ['httpType' => 'HTTPS', 'retry' => 0], 'SDK internal retry disabled');
|
|
esignExpect($init['signConfig']['algorithm'] === 'HMACSHA256', 'SDK algorithm');
|
|
|
|
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'shortLink' => 'https://smlt.esign.cn/identity7']]);
|
|
$identity = $client->startIdentity('张医生', 'rx-7', 'sdk-account-1');
|
|
$request = $requests[count($requests) - 1];
|
|
$body = json_decode($request['body'], true);
|
|
esignExpect($identity === ['flow_id' => 'flow-7', 'auth_url' => 'https://smlt.esign.cn/identity7'], 'identity result');
|
|
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl', 'independent v2 identity API');
|
|
esignExpect($body['indivInfo']['sdkAccountId'] === 'sdk-account-1' && !isset($body['sdkAccountId']), 'SDK account nested in indivInfo');
|
|
esignExpect($body['configParams']['indivUneditableInfo'] === ['name', 'certType'], 'doctor name locked');
|
|
// Fixed vectors independently calculated with Python hashlib/hmac; UTF-8 bytes must match exactly.
|
|
esignExpect($request['headers']['Content-MD5'] === 'M2hjK+7n9RSpPC8C09vWVQ==', 'POST content MD5 vector');
|
|
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'i2dGU5UsRuMb6has/RBZN5BAsECYV4ziEDF17YHaL0g=', 'POST HMACSHA256 vector');
|
|
esignExpect($request['headers']['X-Tsign-Open-Ca-Timestamp'] === '1800000000000', 'timestamp in milliseconds');
|
|
esignExpect($request['headers']['X-Tsign-Open-Auth-Mode'] === 'Signature', 'signature auth mode');
|
|
|
|
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'status' => 'SUCCESS']]);
|
|
esignExpect($client->identityDetail('flow-7')['status'] === 'SUCCESS', 'identity official data returned');
|
|
$request = $requests[count($requests) - 1];
|
|
esignExpect($request['method'] === 'GET' && $request['body'] === '' && !isset($request['headers']['Content-MD5']), 'GET no body MD5');
|
|
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'wPILAWFFD+SOKXrMxguRUqiG1Iwl+k/X9O9Fukf7hes=', 'GET HMACSHA256 vector');
|
|
|
|
$valid = ['errCode' => 0, 'status' => 1, 'remainingTimes' => 1, 'expireAt' => $clock() + 1000];
|
|
$responses[] = esignResponse($valid);
|
|
$client->checkWillingness('flow-7');
|
|
esignExpect(str_ends_with($requests[count($requests) - 1]['url'], '/timevale/auth/queryWillingnessValidity'), 'willingness endpoint');
|
|
foreach ([['status' => 0], ['remainingTimes' => 0], ['expireAt' => $clock()], ['status' => '1'], ['expireAt' => 'not-a-date']] as $invalid) {
|
|
$responses[] = esignResponse(array_replace($valid, $invalid));
|
|
esignThrows(fn () => $client->checkWillingness('flow-7'), EsignProviderException::class, 'WILLINGNESS_INVALID');
|
|
}
|
|
|
|
$responses[] = esignResponse(['errCode' => 0, 'accountId' => 'person-7']);
|
|
esignExpect($client->createPerson('张医生', 'TEST-IDENTITY', 'flow-7') === 'person-7', 'created SDK account');
|
|
$request = $requests[count($requests) - 1];
|
|
esignExpect(str_ends_with($request['url'], '/timevale/account/addPerson'), 'account SDK endpoint');
|
|
esignExpect(json_decode($request['body'], true) === ['name' => '张医生', 'idNo' => 'TEST-IDENTITY', 'idNoType' => 'MAINLAND', 'identityAuthId' => 'flow-7'], 'identity bound to SDK account');
|
|
|
|
$responses[] = esignResponse(['errCode' => 0, 'sealData' => base64_encode('seal-image')]);
|
|
esignExpect($client->createSeal('person-7') === base64_encode('seal-image'), 'seal result');
|
|
$sealBody = json_decode($requests[count($requests) - 1]['body'], true);
|
|
esignExpect($sealBody === ['accountId' => 'person-7', 'type' => 'BORDERLESS', 'color' => 'BLACK', 'stampRule' => 'SEAL_NONE'], 'seal from account identity');
|
|
|
|
$pdf = "%PDF-1.7\n\x00\x01binary-pdf\r\n%%EOF";
|
|
$signedPdf = "%PDF-1.7\nsigned\x00binary\n%%EOF";
|
|
$responses[] = esignResponse(['errCode' => 0, 'signServiceId' => 'service-7', 'stream' => base64_encode($signedPdf)]);
|
|
esignExpect($client->signPdf('person-7', 'flow-7', base64_encode('seal-image'), $pdf, 'rx-7.pdf') === ['sign_service_id' => 'service-7', 'pdf' => $signedPdf], 'decoded signed PDF bytes');
|
|
$request = $requests[count($requests) - 1];
|
|
esignExpect(str_ends_with($request['url'], '/timevale/user/sign/personSign'), 'SDK person sign endpoint');
|
|
$parts = esignMultipartParts($request);
|
|
esignExpect(array_keys($parts) === ['personSignParam', 'streamFile'], 'multipart field names');
|
|
esignExpect(str_contains($parts['personSignParam']['headers'], 'Content-Type: application/json; charset=UTF-8'), 'JSON part media type');
|
|
esignExpect(str_contains($parts['streamFile']['headers'], 'Content-Type: application/octet-stream'), 'file part media type');
|
|
esignExpect($parts['streamFile']['body'] === $pdf, 'multipart preserves arbitrary binary bytes');
|
|
$parameters = json_decode($parts['personSignParam']['body'], true);
|
|
esignExpect($parameters['fileBean'] === ['fileName' => 'rx-7.pdf'] && !isset($parameters['fileBean']['dstPdfFile']), 'stream response requested');
|
|
esignExpect($parameters['signType'] === 'Single' && $parameters['posBeans'] === [['posPage' => '1', 'posX' => 420, 'posY' => 70, 'width' => 100]], 'fixed prescription signature location');
|
|
esignExpect($parameters['willingnessId'] === 'flow-7' && $parameters['accountId'] === 'person-7', 'signature identity binding');
|
|
|
|
$signatures = [['signature' => ['validate' => true], 'cert' => ['cn' => '张医生']], ['signature' => ['validate' => true]]];
|
|
$responses[] = esignResponse(['errCode' => 0, 'signatures' => $signatures]);
|
|
esignExpect($client->verifyPdf($signedPdf) === ['signatures' => $signatures], 'all signatures verified');
|
|
$parts = esignMultipartParts($requests[count($requests) - 1]);
|
|
esignExpect(isset($parts['verifyPdfParam']) && $parts['streamFile']['body'] === $signedPdf, 'verify multipart');
|
|
foreach ([[], [['signature' => ['validate' => true]], ['signature' => ['validate' => false]]], [['signature' => ['validate' => 1]]], [['cert' => []]]] as $invalid) {
|
|
$responses[] = esignResponse(['errCode' => 0, 'signatures' => $invalid]);
|
|
esignThrows(fn () => $client->verifyPdf($signedPdf), EsignProviderException::class, $invalid === [] ? 'NO_SIGNATURES' : 'SIGNATURE_INVALID');
|
|
}
|
|
|
|
foreach ([
|
|
[['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'],
|
|
[['status' => 200, 'body' => '<html>secret identity data</html>'], 'INVALID_JSON'],
|
|
[esignResponse(['msg' => 'private identity']), 'RESPONSE_INVALID'],
|
|
[esignResponse(['errCode' => 42, 'msg' => 'private name/id/secret']), 'PROVIDER_42'],
|
|
[['status' => 302, 'body' => 'Location: https://attacker.invalid'], 'HTTP_302'],
|
|
[['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'],
|
|
] as [$response, $code]) {
|
|
$responses[] = $response;
|
|
$before = count($requests);
|
|
$exception = esignThrows(fn () => $client->createSeal('person-7'), EsignProviderException::class, $code);
|
|
esignExpect(count($requests) === $before + 1, 'no retry ' . $code);
|
|
esignExpect(!str_contains($exception->getMessage(), 'private') && !str_contains($exception->getMessage(), 'secret') && !str_contains($exception->getMessage(), 'attacker'), 'sanitized error ' . $code);
|
|
}
|
|
|
|
foreach ([
|
|
[['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'],
|
|
[['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'],
|
|
[['status' => 502, 'body' => 'private server exception'], 'HTTP_502'],
|
|
[esignResponse(['errCode' => 0, 'signServiceId' => 'already-signed']), 'SIGNED_FILE_UNAVAILABLE'],
|
|
] as [$response, $code]) {
|
|
$responses[] = $response;
|
|
$before = count($requests);
|
|
$exception = esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, $code);
|
|
esignExpect(count($requests) === $before + 1, 'unknown signing outcome is never retried');
|
|
if ($code === 'SIGNED_FILE_UNAVAILABLE') {
|
|
esignExpect($exception->signServiceId === 'already-signed', 'known sign reference retained');
|
|
}
|
|
}
|
|
$responses[] = esignResponse(['errCode' => 55, 'msg' => 'secret rejected identity']);
|
|
esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_55');
|
|
$throwing = new EsignClient(esignConfig(), static function (): array { throw new RuntimeException('https://secret:password/private'); }, $clock);
|
|
esignThrows(fn () => $throwing->createSeal('person-7'), EsignProviderException::class, 'TRANSPORT_ERROR');
|
|
esignThrows(fn () => $throwing->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, 'TRANSPORT_ERROR');
|
|
|
|
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://attacker.invalid/identity']]);
|
|
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
|
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://t.esign.cn/identity']]);
|
|
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
|
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => 'https://smlfront.esign.cn:8890/identity/login']]);
|
|
esignExpect($client->startIdentity('医生', 'rx')['auth_url'] === 'https://smlfront.esign.cn:8890/identity/login', 'official sandbox long URL port');
|
|
foreach (['https://smlfront.esign.cn:444/x', 'https://smlt.esign.cn:8890/x', 'https://smlt.esign.cn/a\\b'] as $invalidUrl) {
|
|
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => $invalidUrl]]);
|
|
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
|
}
|
|
|
|
$production = new EsignClient(esignConfig(['environment' => 'production']), $transport, $clock);
|
|
$responses[] = esignResponse(['errCode' => 0]);
|
|
$production->initialize();
|
|
$init = json_decode($requests[count($requests) - 1]['body'], true);
|
|
esignExpect($init['projectConfig']['itsmApiUrl'] === 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2', 'production init endpoint');
|
|
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => '', 'url' => 'https://idverify.esign.cn/identity']]);
|
|
$production->startIdentity('医生', 'rx');
|
|
esignExpect(str_starts_with($requests[count($requests) - 1]['url'], 'https://openapi.esign.cn/v2/identity/'), 'production identity endpoint');
|
|
|
|
esignExpect($responses === [], 'all expected transport responses consumed');
|
|
echo 'EsignClient: ' . $checks . " checks passed (offline)\n";
|