42 lines
2.7 KiB
PHP
42 lines
2.7 KiB
PHP
<?php
|
|
namespace App\Services\PaymentHealth;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use RuntimeException;
|
|
|
|
class HttpsTransport
|
|
{
|
|
public function request(string $method,string $url,array $fields=[],bool $downstream=false): array
|
|
{
|
|
[$host,$ip]=$this->endpoint($url,$downstream);
|
|
$client=Http::withoutRedirecting()->connectTimeout(10)->timeout(25)->withUserAgent('XB-PaymentHealth/1.0')->accept('text/html')
|
|
->withOptions(['verify'=>true,'curl'=>[CURLOPT_RESOLVE=>[$host.':443:'.(str_contains($ip,':')?'['.$ip.']':$ip)]]]);
|
|
$response=$method==='POST'?$client->asForm()->post($url,$fields):$client->get($url);
|
|
$body=$response->body();if(strlen($body)>2097152)throw new RuntimeException('oversized_cashier_response');
|
|
return ['status'=>$response->status(),'body'=>$body,'location'=>$response->header('Location'),'host'=>$host,'sha256'=>hash('sha256',$body)];
|
|
}
|
|
protected function endpoint(string $url,bool $downstream):array
|
|
{
|
|
$parts=parse_url($url);$host=strtolower($parts['host']??'');
|
|
if (($parts['scheme']??'')!=='https'||!$host||isset($parts['user'])||isset($parts['pass'])||isset($parts['fragment'])||($parts['port']??443)!==443) throw new RuntimeException('unsafe_url');
|
|
if(filter_var(trim($host,'[]'),FILTER_VALIDATE_IP))throw new RuntimeException('ip_literal_not_allowed');
|
|
if(!preg_match('/\A(?=.{1,253}\z)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\z/D',$host))throw new RuntimeException('unsafe_url');
|
|
// Only EpayProbe may mark a URL as a handoff after a validated gateway response.
|
|
if(!in_array($host,config('payment_health.allowed_hosts',[]),true)&&!($downstream&&config('payment_health.dynamic_handoffs',true)))throw new RuntimeException('unapproved_host');
|
|
return [$host,$this->publicAddress($host)];
|
|
}
|
|
protected function records(string $host):array
|
|
{return dns_get_record($host,DNS_A|DNS_AAAA)?:[];}
|
|
protected function publicAddress(string $host): string
|
|
{
|
|
if(filter_var($host,FILTER_VALIDATE_IP)) throw new RuntimeException('ip_literal_not_allowed');
|
|
$records=$this->records($host);$ips=[];
|
|
foreach($records?:[] as $r){$ip=$r['ip']??$r['ipv6']??null;if(!$ip)continue;
|
|
if(str_starts_with(strtolower($ip),'::ffff:'))throw new RuntimeException('nonpublic_dns');
|
|
$packed=@inet_pton($ip);$multicast=$packed!==false&&((strlen($packed)===4&&ord($packed[0])>=224)||(strlen($packed)===16&&ord($packed[0])===255));
|
|
if(!filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_GLOBAL_RANGE)||$multicast)throw new RuntimeException('nonpublic_dns');$ips[]=$ip;}
|
|
if(!$ips)throw new RuntimeException('dns_unavailable');
|
|
return $ips[0];
|
|
}
|
|
}
|