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,'
'],[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,'']];$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,''],[302,'','https://other.example.invalid/qr'],[200,'32.00 ']]; $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:pass@cashier.example.invalid/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='32.00
'; $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)); } public function test_cashier_requests_explicitly_accept_html_with_the_original_agent():void { Http::fake(['https://pay.airspay.top/*'=>Http::response('cashier',200)]); $transport=new class extends HttpsTransport {protected function publicAddress(string $host):string{return '93.184.216.34';}}; $transport->request('POST','https://pay.airspay.top/submit.php',['money'=>'32.00']); Http::assertSent(fn($r)=>$r->hasHeader('Accept','text/html')&&$r->hasHeader('User-Agent','XB-PaymentHealth/1.0')&&$r['money']==='32.00'); Http::assertSentCount(1); } public function test_wechat_https_qr_still_requires_exact_host_amount_and_rendering():void { $q=new QrEvidence; $body='32.00
'; $this->assertTrue($q->valid($body,'wxpay',3200)); $this->assertFalse($q->valid($body,'wxpay',1600)); $this->assertFalse($q->valid($body,'alipay',3200)); $this->assertFalse($q->valid('32.00 https://wxmpurl.cn/fixture-only','wxpay',3200)); foreach(['http://wxmpurl.cn/fixture','https://wxmpurl.cn.evil.invalid/fixture','https://sub.wxmpurl.cn/fixture', 'https://wxmpurlXcn/fixture','https://wxmpurl.cn@evil.invalid/fixture','https://user@wxmpurl.cn/fixture', 'https://wxmpurl.cn:8443/fixture','https://evil.invalid/https://wxmpurl.cn/fixture', 'https://evil.invalid/?next=https://wxmpurl.cn/fixture','https://wxmpurl.cn/','https://wxmpurl.cn/fixture#fragment']as$url){ $this->assertFalse($q->valid(str_replace('https://wxmpurl.cn/fixture-only',$url,$body),'wxpay',3200),$url); } } public function test_wechat_https_cashier_is_healthy_without_following_the_qr_url():void { $body='32.00
'; $t=new QueueTransport;$t->responses=[[200,$body]]; $out=(new TestEpayProbe($t,new QrEvidence))->probe(Payment::find(1),'fixture-trade'); $this->assertSame('healthy',$out['status']);$this->assertSame('fresh_cashier_qr',$out['reason']);$this->assertCount(1,$t->calls); } private function qrPng(int $pixels):string { $matrix=\BaconQrCode\Encoder\Encoder::encode('alipays://platformapi/startapp?appId=fixture-only',\BaconQrCode\Common\ErrorCorrectionLevel::M())->getMatrix(); $n=$matrix->getWidth();$src=imagecreatetruecolor($n+8,$n+8);$white=imagecolorallocate($src,255,255,255);$black=imagecolorallocate($src,0,0,0);imagefill($src,0,0,$white); for($y=0;$y<$n;$y++)for($x=0;$x<$n;$x++)if($matrix->get($x,$y)===1)imagesetpixel($src,$x+4,$y+4,$black); $out=imagecreatetruecolor($pixels,$pixels);imagecopyresized($out,$src,0,0,0,0,$pixels,$pixels,$n+8,$n+8);ob_start();imagepng($out);$png=ob_get_clean();imagedestroy($src);imagedestroy($out);return $png; } public function test_large_real_qr_is_normalized_without_weakening_amount_or_uri_checks():void { $q=new QrEvidence;$png=$this->qrPng(650); $html='32.00 支付