200 lines
18 KiB
PHP
200 lines
18 KiB
PHP
<?php
|
|
namespace Tests\Feature\PaymentHealth;
|
|
|
|
use Tests\TestCase;
|
|
use App\Models\Payment;
|
|
use App\Services\PaymentHealth\{Monitor,EpayProbe,HttpsTransport,QrEvidence,TeleHubReporter,StateStore};
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
use Illuminate\Foundation\Bootstrap\RegisterProviders;
|
|
use Illuminate\Support\Facades\{Schema,Cache,Http,DB};
|
|
use Carbon\CarbonImmutable;
|
|
use Illuminate\Http\Request;
|
|
|
|
class FakeProbe extends EpayProbe
|
|
{
|
|
public array $calls=[];
|
|
public array $outcomes=[];
|
|
public function __construct() {}
|
|
public function probe(Payment $p,string $tradeNo):array{$this->calls[]=$p->id;return array_shift($this->outcomes)??['status'=>'healthy','reason'=>'fresh_cashier_qr'];}
|
|
}
|
|
class FakeReporter extends TeleHubReporter
|
|
{
|
|
public array $sent=[];
|
|
public function deliver(array $event):array{$this->sent[]=$event;return ['status'=>'sent','receipt_id'=>'00000000-0000-0000-0000-000000000001'];}
|
|
}
|
|
class QueueTransport extends HttpsTransport
|
|
{
|
|
public array $calls=[];public array $responses=[];
|
|
protected function publicAddress(string $host):string{return '93.184.216.34';}
|
|
public function request(string $method,string $url,array $fields=[],bool $downstream=false):array{
|
|
$this->calls[]=[$method,$url,$fields];
|
|
$this->endpoint($url,$downstream);
|
|
$r=array_shift($this->responses);return ['status'=>$r[0],'body'=>$r[1],'location'=>$r[2]??'','host'=>parse_url($url,PHP_URL_HOST),'sha256'=>hash('sha256',$r[1])];
|
|
}
|
|
}
|
|
class TestEpayProbe extends EpayProbe
|
|
{
|
|
protected function paymentUrl(Payment $p,string $tradeNo,int $cents):string{return 'https://pay.airspay.top/submit.php?'.http_build_query(['out_trade_no'=>$tradeNo,'money'=>$cents/100,'sign'=>str_repeat('a',32),'type'=>$p->config['type']]);}
|
|
}
|
|
class PaymentHealthTest extends TestCase
|
|
{
|
|
private string $dir;private FakeProbe $probe;private FakeReporter $reporter;
|
|
public function createApplication(){
|
|
$app=require dirname(__DIR__,3).'/bootstrap/app.php';
|
|
$app->beforeBootstrapping(RegisterProviders::class,function($app){$app['config']->set(['database.default'=>'sqlite','database.connections.sqlite.database'=>':memory:','cache.default'=>'array','cache.stores.redis'=>['driver'=>'array'],'queue.default'=>'sync','app.key'=>'base64:'.base64_encode(str_repeat('x',32)),'app.url'=>'https://site.example.invalid']);});
|
|
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();return $app;
|
|
}
|
|
protected function setUp():void{
|
|
parent::setUp();$this->dir=sys_get_temp_dir().'/xb-health-'.bin2hex(random_bytes(5));mkdir($this->dir,0700);
|
|
config(['payment_health.state_path'=>$this->dir.'/state.json']);
|
|
Schema::create('v2_plugins',fn(Blueprint $t)=>[$t->id(),$t->boolean('is_enabled')->default(false)]);
|
|
Schema::create('v2_settings',fn(Blueprint $t)=>[$t->id(),$t->string('name'),$t->text('value')->nullable(),$t->timestamps()]);
|
|
Schema::create('v2_payment',function(Blueprint $t){$t->id();$t->string('uuid');$t->string('payment');$t->string('name');$t->text('config');$t->boolean('enable');$t->string('notify_domain')->nullable();$t->timestamps();});
|
|
Cache::store('redis')->flush();$this->app->forgetInstance(\App\Support\Setting::class);Http::preventStrayRequests();
|
|
CarbonImmutable::setTestNow('2026-10-30 00:10:00 Asia/Shanghai');
|
|
Payment::create(['id'=>1,'uuid'=>'channel1','payment'=>'EPay','name'=>'微信','enable'=>true,'config'=>['type'=>'wxpay','url'=>'https://pay.airspay.top','pid'=>'merchant','key'=>'never-log-this-secret']]);
|
|
$this->probe=new FakeProbe;$this->reporter=new FakeReporter;
|
|
}
|
|
protected function tearDown():void{CarbonImmutable::setTestNow();foreach(glob($this->dir.'/*')?:[]as$p)unlink($p);rmdir($this->dir);parent::tearDown();}
|
|
private function runMonitor():array{return (new Monitor($this->probe,$this->reporter))->run();}
|
|
private function state():array{return json_decode(file_get_contents($this->dir.'/state.json'),true);}
|
|
private function nextSlot():void{CarbonImmutable::setTestNow(CarbonImmutable::now()->addHours(6));}
|
|
public function test_defaults_and_six_hour_schedule():void{
|
|
$this->assertTrue(config('payment_health.enabled'));$this->assertTrue(config('payment_health.auto_toggle'));
|
|
$schedules=app(\Illuminate\Console\Scheduling\Schedule::class)->events();$match=array_values(array_filter($schedules,fn($e)=>str_contains($e->command??'','payment:health-check')));
|
|
$this->assertCount(1,$match);$this->assertSame('0 */6 * * *',$match[0]->expression);$this->assertSame('Asia/Shanghai',$match[0]->timezone);
|
|
}
|
|
public function test_hard_failure_disables_and_healthy_recovers_only_owned_channel():void{
|
|
$this->probe->outcomes=[['status'=>'hard_failure','reason'=>'cashier_not_found']];$this->runMonitor();$this->assertFalse(Payment::find(1)->enable);$this->assertCount(1,$this->reporter->sent);
|
|
$this->nextSlot();$this->runMonitor();$this->assertTrue(Payment::find(1)->enable);$this->assertSame('notification',$this->reporter->sent[1]['bot']);$this->assertCount(2,$this->probe->calls);
|
|
}
|
|
public function test_same_slot_is_not_repeated_and_no_secret_is_persisted():void{
|
|
$this->runMonitor();$this->runMonitor();$this->assertCount(1,$this->probe->calls);
|
|
$raw=file_get_contents($this->dir.'/state.json');$this->assertStringNotContainsString('never-log-this-secret',$raw);$this->assertStringNotContainsString('PH2026',$raw);$this->assertSame(0600,fileperms($this->dir.'/state.json')&0777);
|
|
}
|
|
public function test_manual_off_is_respected_and_manual_edit_releases_ownership():void{
|
|
Payment::find(1)->update(['enable'=>false]);$this->runMonitor();$this->assertCount(0,$this->probe->calls);
|
|
Payment::find(1)->update(['enable'=>true]);$this->probe->outcomes=[['status'=>'hard_failure','reason'=>'cashier_not_found']];$this->runMonitor();$this->assertFalse(Payment::find(1)->enable);
|
|
$this->nextSlot();Payment::find(1)->update(['name'=>'operator edited']);$this->runMonitor();$this->assertCount(1,$this->probe->calls);$this->assertFalse(Payment::find(1)->enable);
|
|
}
|
|
public function test_network_requires_two_slots_and_success_resets_streak():void{
|
|
$soft=['status'=>'soft_failure','reason'=>'network_timeout'];$this->probe->outcomes=[$soft,$soft];$this->runMonitor();$this->assertTrue(Payment::find(1)->enable);
|
|
$this->nextSlot();$this->runMonitor();$this->assertFalse(Payment::find(1)->enable);
|
|
}
|
|
public function test_review_required_does_not_toggle_or_keep_creating_orders():void{
|
|
$this->probe->outcomes=[['status'=>'review_required','reason'=>'unapproved_host']];$this->runMonitor();$this->nextSlot();$this->runMonitor();$this->assertTrue(Payment::find(1)->enable);$this->assertCount(1,$this->probe->calls);
|
|
}
|
|
public function test_unsupported_and_daily_budget_are_safe():void{
|
|
Payment::find(1)->update(['payment'=>'OtherProvider']);$this->runMonitor();$this->assertCount(0,$this->probe->calls);$this->assertTrue(Payment::find(1)->enable);
|
|
Payment::find(1)->update(['payment'=>'EPay']);config(['payment_health.daily_probe_limit'=>1]);$this->runMonitor();$this->nextSlot();$this->runMonitor();$this->assertCount(1,$this->probe->calls);
|
|
}
|
|
public function test_claimed_crash_slot_corrupt_state_and_lock_never_resubmit():void{
|
|
$this->runMonitor();$s=$this->state();$s['channels']['channel1']['phase']='claimed';file_put_contents($this->dir.'/state.json',json_encode($s));$this->runMonitor();$this->assertCount(1,$this->probe->calls);
|
|
$lock=fopen($this->dir.'/state.json.lock','c+');flock($lock,LOCK_EX);$this->assertSame('locked',$this->runMonitor()['status']);fclose($lock);
|
|
file_put_contents($this->dir.'/state.json','invalid');try{$this->runMonitor();$this->fail('Corrupt state ignored');}catch(\JsonException $e){$this->assertCount(1,$this->probe->calls);}
|
|
}
|
|
public function test_epay_gateway_200_followed_by_downstream_404_is_failure():void{
|
|
$t=new QueueTransport;$t->responses=[[200,'<form action="https://api.shangri-la.vc/submit.php" method="POST"><input name="money" value="32.00"></form>'],[404,'Not Found']];
|
|
$r=(new TestEpayProbe($t,new QrEvidence))->probe(Payment::find(1),'probe-123');$this->assertSame('hard_failure',$r['status']);$this->assertSame('cashier_not_found',$r['reason']);$this->assertCount(2,$t->calls);$this->assertSame('POST',$t->calls[0][0]);$this->assertStringNotContainsString('sign=',$t->calls[0][1]);
|
|
}
|
|
public function test_strict_opt_out_stops_new_handoff_and_generic_200_is_not_healthy():void{
|
|
config(['payment_health.dynamic_handoffs'=>false]);
|
|
$t=new QueueTransport;$t->responses=[[200,'<form action="https://new.example.invalid/pay" method="POST"></form>']];$r=(new TestEpayProbe($t,new QrEvidence))->probe(Payment::find(1),'probe-123');$this->assertSame('review_required',$r['status']);
|
|
$t=new QueueTransport;$t->responses=[[200,'二维码 32.00 微信 正在跳转']];$r=(new TestEpayProbe($t,new QrEvidence))->probe(Payment::find(1),'probe-123');$this->assertSame('indeterminate',$r['status']);
|
|
}
|
|
public function test_dynamic_handoff_and_redirect_are_followed_but_new_entry_is_rejected():void
|
|
{
|
|
$this->assertTrue(config('payment_health.dynamic_handoffs'));
|
|
$t=new QueueTransport;$t->responses=[[200,'<form action="https://cashier.example.invalid/pay" method="POST"><input name="money" value="32.00"></form>'],[302,'','https://other.example.invalid/qr'],[200,'32.00 <div id="qr"></div><script>new QRCode(document.getElementById("qr"),"weixin://wxpay/bizpayurl?pr=fixture")</script>']];
|
|
$r=(new TestEpayProbe($t,new QrEvidence))->probe(Payment::find(1),'probe-123');$this->assertSame('healthy',$r['status']);$this->assertCount(3,$t->calls);
|
|
try{$t->request('POST','https://cashier.example.invalid/pay');$this->fail('Untrusted entry accepted');}catch(\RuntimeException $e){$this->assertSame('unapproved_host',$e->getMessage());}
|
|
}
|
|
public function test_dynamic_handoffs_still_reject_unsafe_destinations():void
|
|
{
|
|
foreach(['http://cashier.example.invalid/pay','https://127.0.0.1/pay','https://[::1]/pay','https://user:[email protected]/pay','https://cashier.example.invalid:8443/pay','file:///etc/passwd']as$url){
|
|
$t=new QueueTransport;$t->responses=[[302,'',$url]];$r=(new TestEpayProbe($t,new QrEvidence))->probe(Payment::find(1),'probe-123');$this->assertSame('review_required',$r['status'],$url);$this->assertCount(2,$t->calls);
|
|
}
|
|
$t=new class extends HttpsTransport {public function check(string $url):array{return $this->endpoint($url,true);}protected function records(string $host):array{return [['ip'=>'127.0.0.1']];}};
|
|
try{$t->check('https://cashier.example.invalid/pay');$this->fail('Private DNS allowed');}catch(\RuntimeException $e){$this->assertSame('nonpublic_dns',$e->getMessage());}
|
|
}
|
|
public function test_dns_shared_and_multicast_ranges_are_not_public_cashiers():void
|
|
{
|
|
$t=new class extends HttpsTransport {public array $answers=[];public function check():array{return $this->endpoint('https://cashier.example.invalid/pay',true);}protected function records(string $host):array{return $this->answers;}};
|
|
foreach(['100.64.0.1','224.0.0.1','169.254.169.254','ff02::1','::ffff:127.0.0.1'] as $ip){
|
|
$t->answers=[[str_contains($ip,':')?'ipv6':'ip'=>$ip]];try{$t->check();$this->fail('Nonpublic destination allowed');}catch(\RuntimeException $e){$this->assertSame('nonpublic_dns',$e->getMessage());}
|
|
}
|
|
$t->answers=[['ip'=>'93.184.216.34']];$this->assertSame(['cashier.example.invalid','93.184.216.34'],$t->check());
|
|
}
|
|
public function test_policy_upgrade_unlocks_next_slot_without_duplicate_same_slot_probe():void
|
|
{
|
|
$this->probe->outcomes=[['status'=>'review_required','reason'=>'unapproved_host']];$this->runMonitor();$s=$this->state();$s['channels']['channel1']['policy']=hash('sha256',json_encode(config('payment_health.allowed_hosts')));file_put_contents($this->dir.'/state.json',json_encode($s));
|
|
$this->runMonitor();$this->assertCount(1,$this->probe->calls);$this->nextSlot();$this->runMonitor();$this->assertCount(2,$this->probe->calls);$this->assertSame('healthy',$this->state()['channels']['channel1']['status']);
|
|
}
|
|
public function test_qr_requires_amount_payment_uri_and_rendering():void{
|
|
$q=new QrEvidence;$body='<p>32.00</p><div id="qr"></div><script>new QRCode(document.getElementById("qr"),"weixin://wxpay/bizpayurl?pr=fixture-only")</script>';
|
|
$this->assertTrue($q->valid($body,'wxpay',3200));$this->assertFalse($q->valid(str_replace('32.00','16.00',$body),'wxpay',3200));$this->assertFalse($q->valid('32.00 微信二维码','wxpay',3200));
|
|
}
|
|
private function callbackFixture():array
|
|
{
|
|
Schema::create('v2_order',function(Blueprint $t){$t->id();$t->string('trade_no');$t->integer('payment_id');$t->integer('total_amount');$t->integer('handling_amount')->nullable();$t->integer('status');$t->string('callback_no')->nullable();$t->integer('paid_at')->nullable();$t->integer('created_at')->nullable();$t->integer('updated_at')->nullable();});
|
|
\App\Models\Order::create(['trade_no'=>'existing-real-order','payment_id'=>1,'total_amount'=>3200,'handling_amount'=>0,'status'=>0,'created_at'=>time()-60]);
|
|
require_once base_path('plugins-core/Epay/Plugin.php');
|
|
$plugin=new \Plugin\Epay\Plugin('epay');$plugin->boot();
|
|
$manager=\Mockery::mock(\App\Services\Plugin\PluginManager::class);$manager->shouldReceive('getEnabledPaymentPlugins')->andReturn([$plugin]);$this->app->instance(\App\Services\Plugin\PluginManager::class,$manager);
|
|
\Illuminate\Support\Facades\Bus::fake([\App\Jobs\OrderHandleJob::class]);
|
|
return ['pid'=>'merchant','type'=>'wxpay','money'=>'32.00','trade_status'=>'TRADE_SUCCESS','out_trade_no'=>'existing-real-order','trade_no'=>'provider-reference'];
|
|
}
|
|
private function notify(array $params):mixed
|
|
{
|
|
ksort($params,SORT_STRING);$parts=[];foreach($params as$key=>$value)if($value!==''&&$value!==null)$parts[]=$key.'='.$value;
|
|
$params['sign']=md5(implode('&',$parts).'never-log-this-secret');$params['sign_type']='MD5';
|
|
return (new \App\Http\Controllers\V1\Guest\PaymentController)->notify('EPay','channel1',Request::create('/callback','GET',$params));
|
|
}
|
|
public function test_monitor_off_preserves_valid_existing_order_callback_and_idempotence():void
|
|
{
|
|
$params=$this->callbackFixture();$this->probe->outcomes=[['status'=>'hard_failure','reason'=>'cashier_not_found']];$this->runMonitor();
|
|
$this->assertFalse(Payment::find(1)->enable);$this->assertSame('success',$this->notify($params));$this->assertSame('success',$this->notify($params));
|
|
$this->assertSame(1,(int)\App\Models\Order::first()->status);\Illuminate\Support\Facades\Bus::assertDispatchedSync(\App\Jobs\OrderHandleJob::class,1);
|
|
}
|
|
public function test_disabled_callback_still_rejects_forgery_wrong_amount_and_new_order():void
|
|
{
|
|
$params=$this->callbackFixture();$this->probe->outcomes=[['status'=>'hard_failure','reason'=>'cashier_not_found']];$this->runMonitor();
|
|
foreach([['money'=>'16.00'],['pid'=>'wrong'],['type'=>'alipay']]as$change)$this->assertNotSame('success',$this->notify(array_replace($params,$change)));
|
|
$this->assertNotSame('success',(new \App\Http\Controllers\V1\Guest\PaymentController)->notify('EPay','channel1',Request::create('/callback','GET',$params+['sign'=>'forged'])));
|
|
\App\Models\Order::where('id',1)->update(['created_at'=>time()+60]);$this->assertNotSame('success',$this->notify($params));\Illuminate\Support\Facades\Bus::assertNothingDispatched();
|
|
}
|
|
public function test_manual_disabled_callback_is_rejected():void
|
|
{
|
|
$params=$this->callbackFixture();Payment::find(1)->update(['enable'=>false]);$this->assertNotSame('success',$this->notify($params));\Illuminate\Support\Facades\Bus::assertNothingDispatched();
|
|
}
|
|
public function test_database_ownership_recovers_crash_after_disable_without_new_order_in_same_slot():void
|
|
{
|
|
$this->probe->outcomes=[['status'=>'hard_failure','reason'=>'cashier_not_found']];$this->runMonitor();$s=$this->state();$s['channels']['channel1']['phase']='toggle_pending';$s['channels']['channel1']['managed_disabled']=false;unset($s['channels']['channel1']['expected_updated_at']);file_put_contents($this->dir.'/state.json',json_encode($s));
|
|
$this->runMonitor();$this->assertCount(1,$this->probe->calls);$this->nextSlot();$this->runMonitor();$this->assertTrue(Payment::find(1)->enable);
|
|
}
|
|
public function test_telehub_uses_stable_event_key_then_reads_receipt_without_duplicate_send():void
|
|
{
|
|
config(['payment_health.telehub_key'=>'telehub_'.str_repeat('a',64)]);
|
|
Http::fake(['*/api/v1/messages'=>Http::response(['data'=>['id'=>'00000000-0000-0000-0000-000000000001','status'=>'queued']],202),'*/api/v1/messages/*'=>Http::response(['data'=>['id'=>'00000000-0000-0000-0000-000000000001','status'=>'sent']],200)]);
|
|
$reporter=new TeleHubReporter;$event=['key'=>'xb.payment-health.fixture.1','bot'=>'error','text'=>'【XB - 支付通道异常】'];$first=$reporter->deliver($event);$second=$reporter->deliver($event+$first);
|
|
$this->assertSame('queued',$first['status']);$this->assertSame('sent',$second['status']);Http::assertSentCount(2);
|
|
Http::assertSent(fn($r)=>$r->method()==='POST'&&$r->header('Idempotency-Key')[0]===$event['key']&&array_keys($r->data())===['bot','target','text']);
|
|
}
|
|
|
|
public function test_same_second_manual_toggle_clears_lease_and_callback_permission():void
|
|
{
|
|
$params=$this->callbackFixture();$this->probe->outcomes=[['status'=>'hard_failure','reason'=>'cashier_not_found']];$this->runMonitor();
|
|
$this->assertNotNull(\App\Services\PaymentHealth\Ownership::lease(Payment::find(1)));
|
|
Payment::find(1)->update(['enable'=>true]);Payment::find(1)->update(['enable'=>false]);
|
|
$this->assertNull(\App\Services\PaymentHealth\Ownership::lease(Payment::find(1)));$this->assertNotSame('success',$this->notify($params));
|
|
$this->nextSlot();$this->runMonitor();$this->assertFalse(Payment::find(1)->enable);$this->assertCount(1,$this->probe->calls);
|
|
}
|
|
|
|
public function test_config_change_and_policy_change_cannot_create_second_probe_in_same_slot():void
|
|
{
|
|
$this->runMonitor();$p=Payment::find(1);$p->config=array_replace($p->config,['pid'=>'new-merchant']);$p->save();$this->runMonitor();$this->assertCount(1,$this->probe->calls);
|
|
$this->nextSlot();$this->runMonitor();$this->assertCount(2,$this->probe->calls);
|
|
}
|
|
|
|
}
|