147 lines
10 KiB
PHP
147 lines
10 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace app\service\group;
|
|
|
|
use app\exception\ApiError;
|
|
use app\service\Settings;
|
|
|
|
/** Server-only, authenticated metadata reads. No human sessions cross this boundary. */
|
|
final class KefuMetadataClient
|
|
{
|
|
private const MAX_RESPONSE = 4194304;
|
|
private string $url;
|
|
private string $key;
|
|
private ?\Closure $transport;
|
|
private \Closure $clock;
|
|
|
|
/** Synthetic transport: (url, headers, rawBody) => status/body/headers. */
|
|
public function __construct(?string $base = null, ?string $keyHex = null, ?callable $transport = null, ?callable $clock = null)
|
|
{
|
|
$base ??= Settings::get('IAM_KEFU_METADATA_API_URL');
|
|
$parts = parse_url($base);
|
|
if (!$parts || !in_array($parts['scheme'] ?? '', ['https', 'http'], true) || empty($parts['host'])
|
|
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])
|
|
|| preg_match('/[\x00-\x20\x7f\\\\%]/', $base)
|
|
|| !preg_match('~^(?:/[A-Za-z0-9_-]+)*/?$~D', $parts['path'] ?? '')
|
|
|| ($parts['scheme'] === 'http' && !KefuClient::isHttpOriginAllowed($base))) {
|
|
throw new ApiError(503, '客服授权信息服务尚未正确配置');
|
|
}
|
|
if ($keyHex === null) {
|
|
$path = Settings::get('IAM_KEFU_METADATA_KEY_FILE');
|
|
$keyHex = $path !== '' && is_file($path) && !is_link($path) ? @file_get_contents($path, false, null, 0, 65) : false;
|
|
}
|
|
if (!is_string($keyHex) || !preg_match('/^[a-fA-F0-9]{64}$/D', $keyHex)) {
|
|
throw new ApiError(503, '客服授权信息服务尚未正确配置');
|
|
}
|
|
$this->url = rtrim($base, '/') . '/group/access-snapshot';
|
|
$this->key = hex2bin($keyHex);
|
|
$this->transport = $transport === null ? null : \Closure::fromCallable($transport);
|
|
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
|
|
}
|
|
|
|
public static function configured(): bool
|
|
{
|
|
return Settings::get('IAM_KEFU_METADATA_API_URL') !== '' && Settings::get('IAM_KEFU_METADATA_KEY_FILE') !== '';
|
|
}
|
|
|
|
public function snapshot(array $gids, bool $includeCatalog): array
|
|
{
|
|
if (!array_is_list($gids) || count($gids) > 100 || count(array_unique($gids)) !== count($gids)) { throw new ApiError(422, '身份参数无效'); }
|
|
foreach ($gids as $gid) if (!is_string($gid) || !preg_match('/^gid_[a-f0-9]{32}$/D', $gid)) { throw new ApiError(422, '身份参数无效'); }
|
|
$body = json_encode(['client_id'=>'kefu','gids'=>$gids,'include_catalog'=>$includeCatalog], JSON_THROW_ON_ERROR);
|
|
$now = ($this->clock)(); $nonce = bin2hex(random_bytes(16));
|
|
$signature = hash_hmac('sha256', "POST\n/group/access-snapshot\n$now\n$nonce\n" . hash('sha256', $body), $this->key);
|
|
$headers = ['Accept: application/json','Content-Type: application/json','X-Group-Timestamp: ' . $now,
|
|
'X-Group-Nonce: ' . $nonce,'X-Group-Signature: ' . $signature];
|
|
try {
|
|
$response = $this->transport ? ($this->transport)($this->url, $headers, $body) : $this->curl($headers, $body);
|
|
$raw = $response['body'] ?? null; $mac = null;
|
|
foreach (($response['headers'] ?? []) as $name => $value) if (strtolower((string) $name) === 'x-group-response-signature') { $mac = $value; }
|
|
if (($response['status'] ?? null) !== 200 || !is_string($raw) || strlen($raw) > self::MAX_RESPONSE
|
|
|| !is_string($mac) || !preg_match('/^[a-f0-9]{64}$/D', $mac)
|
|
|| !hash_equals(hash_hmac('sha256', "response\n$nonce\n" . hash('sha256', $raw), $this->key), $mac)) { throw new \RuntimeException(); }
|
|
// Keep JSON object/array distinctions that associative decoding otherwise loses.
|
|
$shape = json_decode($raw, false, 32, JSON_THROW_ON_ERROR);
|
|
if (!$shape instanceof \stdClass || !is_array($shape->subjects ?? null)) { throw new \RuntimeException(); }
|
|
foreach ($shape->subjects as $subject) {
|
|
if (!$subject instanceof \stdClass || (isset($subject->user) && (!$subject->user instanceof \stdClass
|
|
|| !($subject->user->role ?? null) instanceof \stdClass || !is_array($subject->user->permissions ?? null)))) { throw new \RuntimeException(); }
|
|
}
|
|
if ($includeCatalog && (!($shape->catalog ?? null) instanceof \stdClass || !is_array($shape->catalog->permissions ?? null))) { throw new \RuntimeException(); }
|
|
$value = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
|
|
$this->validate($value, $gids, $includeCatalog, $now);
|
|
return $value;
|
|
} catch (\Throwable $error) { throw new ApiError(503, '客服授权信息暂时不可用,请稍后重试'); }
|
|
}
|
|
|
|
private static function keys(mixed $value, array $expected): bool
|
|
{
|
|
if (!is_array($value)) { return false; } $keys = array_keys($value); sort($keys); sort($expected); return $keys === $expected;
|
|
}
|
|
|
|
private static function text(mixed $value, int $max, bool $empty = true): bool
|
|
{
|
|
return is_string($value) && ($empty || trim($value) !== '') && mb_strlen($value) <= $max && !preg_match('/[\x00-\x1f\x7f]/', $value);
|
|
}
|
|
|
|
private static function code(mixed $code): bool { return is_string($code) && (bool) preg_match('/^[a-z][a-z0-9-]*(?::[a-z0-9-]+)+$/D', $code) && strlen($code) <= 80; }
|
|
|
|
private function validate(mixed $value, array $gids, bool $catalog, int $now): void
|
|
{
|
|
if (!self::keys($value, ['version','client_id','generated_at','subjects','catalog']) || $value['version'] !== 1
|
|
|| $value['client_id'] !== 'kefu' || !is_int($value['generated_at']) || abs($value['generated_at'] - $now) > 90
|
|
|| !is_array($value['subjects']) || !array_is_list($value['subjects']) || count($value['subjects']) !== count($gids)) { throw new \RuntimeException(); }
|
|
$seen = [];
|
|
foreach ($value['subjects'] as $subject) {
|
|
if (!is_array($subject) || !is_string($subject['gid'] ?? null) || !in_array($subject['gid'], $gids, true)
|
|
|| isset($seen[$subject['gid']]) || !is_bool($subject['found'] ?? null)) { throw new \RuntimeException(); }
|
|
$seen[$subject['gid']] = true;
|
|
if (!$subject['found']) { if (!self::keys($subject, ['gid','found'])) { throw new \RuntimeException(); } continue; }
|
|
if (!self::keys($subject, ['gid','found','source_admin_id','company_id','user']) || !is_int($subject['source_admin_id']) || $subject['source_admin_id'] < 1
|
|
|| !is_int($subject['company_id']) || $subject['company_id'] < 2) { throw new \RuntimeException(); }
|
|
$user = $subject['user'];
|
|
if (!self::keys($user, ['id','username','source_account','source_name','active','role','permissions']) || !is_int($user['id']) || $user['id'] < 1
|
|
|| !self::text($user['username'],200,false) || !self::text($user['source_account'],200) || !self::text($user['source_name'],200)
|
|
|| !is_bool($user['active']) || !self::keys($user['role'],['code','name']) || !self::text($user['role']['code'],80,false)
|
|
|| !self::text($user['role']['name'],200) || !is_array($user['permissions']) || !array_is_list($user['permissions'])
|
|
|| count($user['permissions']) > 2000 || count(array_unique($user['permissions'])) !== count($user['permissions'])
|
|
|| (!$user['active'] && $user['permissions'] !== [])) { throw new \RuntimeException(); }
|
|
foreach ($user['permissions'] as $code) if (!self::code($code)) { throw new \RuntimeException(); }
|
|
}
|
|
if (!$catalog) { if ($value['catalog'] !== null) { throw new \RuntimeException(); } return; }
|
|
if (!self::keys($value['catalog'], ['permissions']) || !is_array($value['catalog']['permissions'])
|
|
|| !array_is_list($value['catalog']['permissions']) || count($value['catalog']['permissions']) > 2000) { throw new \RuntimeException(); }
|
|
$seen = [];
|
|
foreach ($value['catalog']['permissions'] as $row) {
|
|
if (!self::keys($row,['code','name','group','page','kind','source','enabled','sort']) || !self::code($row['code']) || isset($seen[$row['code']])
|
|
|| !self::text($row['name'],64,false) || !self::text($row['group'],64,false) || !self::text($row['page'],64)
|
|
|| !in_array($row['kind'],['page','action'],true) || !in_array($row['source'],['builtin','custom','discovered'],true)
|
|
|| !is_bool($row['enabled']) || !is_int($row['sort']) || $row['sort'] < 0 || $row['sort'] > 100000) { throw new \RuntimeException(); }
|
|
$seen[$row['code']] = true;
|
|
}
|
|
}
|
|
|
|
private function curl(array $headers, string $body): array
|
|
{
|
|
if (!function_exists('curl_init')) { throw new \RuntimeException(); }
|
|
$handle = curl_init($this->url); $raw = ''; $responseHeaders = []; $headerBytes = 0;
|
|
curl_setopt_array($handle, [CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$body,CURLOPT_HTTPHEADER=>$headers,
|
|
CURLOPT_FOLLOWLOCATION=>false,CURLOPT_MAXREDIRS=>0,CURLOPT_PROXY=>'',CURLOPT_NOPROXY=>'*',
|
|
CURLOPT_CONNECTTIMEOUT=>1,CURLOPT_TIMEOUT=>3,CURLOPT_SSL_VERIFYPEER=>true,CURLOPT_SSL_VERIFYHOST=>2,
|
|
CURLOPT_PROTOCOLS=>CURLPROTO_HTTP|CURLPROTO_HTTPS,
|
|
CURLOPT_HEADERFUNCTION=>static function ($handle, string $line) use (&$responseHeaders, &$headerBytes): int {
|
|
$headerBytes += strlen($line); if ($headerBytes > 16384) { return 0; }
|
|
if (str_starts_with($line, 'HTTP/')) { $responseHeaders = []; }
|
|
elseif (str_contains($line, ':')) { [$name,$value] = explode(':',$line,2); $name = strtolower(trim($name));
|
|
if (isset($responseHeaders[$name])) { return 0; } $responseHeaders[$name] = trim($value); }
|
|
return strlen($line);
|
|
},
|
|
CURLOPT_WRITEFUNCTION=>static function ($handle, string $chunk) use (&$raw): int {
|
|
if (strlen($raw)+strlen($chunk)>self::MAX_RESPONSE) { return 0; } $raw.=$chunk; return strlen($chunk);
|
|
}]);
|
|
try { if (curl_exec($handle) === false) { throw new \RuntimeException(); }
|
|
return ['status'=>(int)curl_getinfo($handle,CURLINFO_RESPONSE_CODE),'body'=>$raw,'headers'=>$responseHeaders];
|
|
} finally { curl_close($handle); }
|
|
}
|
|
}
|