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->base = rtrim($base, '/'); $this->key = hex2bin($keyHex); $this->transport = $transport === null ? null : \Closure::fromCallable($transport); $this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock); } public function options(string $gid, int $sourceId, int $companyId): array { return $this->request('/group/access-options', $this->identity($gid, $sourceId, $companyId)); } public function update(string $gid, int $sourceId, int $companyId, int $actorId, string $revision, string $roleCode, ?array $permissions): array { self::validateChange($revision, $roleCode, $permissions); if ($actorId < 1) { throw new ApiError(422, '操作人无效'); } return $this->request('/group/access-update', $this->identity($gid, $sourceId, $companyId) + [ 'actor_source_admin_id'=>$actorId, 'request_id'=>bin2hex(random_bytes(16)), 'expected_revision'=>$revision, 'role_code'=>$roleCode, 'permissions'=>$permissions, ]); } public static function validateChange(mixed $revision, mixed $roleCode, mixed $permissions): void { if (!is_string($revision) || !preg_match('/^[a-f0-9]{64}$/D', $revision) || !self::text($roleCode, 80, false) || ($permissions !== null && !self::codes($permissions))) { throw new ApiError(422, '客服角色或权限参数无效'); } } private function identity(string $gid, int $sourceId, int $companyId): array { if (!preg_match('/^gid_[a-f0-9]{32}$/D', $gid) || $sourceId < 1 || $companyId < 2) { throw new ApiError(422, '客服身份参数无效'); } return ['client_id'=>'kefu','gid'=>$gid,'source_admin_id'=>$sourceId,'company_id'=>$companyId]; } private function request(string $path, array $request): array { $body = json_encode($request, JSON_THROW_ON_ERROR); if (strlen($body) > self::MAX_REQUEST) { throw new ApiError(422, '客服授权请求过大'); } $now = ($this->clock)(); $nonce = bin2hex(random_bytes(16)); $signature = hash_hmac('sha256', "POST\n$path\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->base.$path, $headers, $body) : $this->curl($path, $headers, $body); $raw = $response['body'] ?? null; $mac = null; $macCount = 0; $status = $response['status'] ?? null; foreach (($response['headers'] ?? []) as $name=>$value) { if (strtolower((string)$name) === 'x-group-response-signature') { $mac = $value; $macCount++; } } if (!is_int($status) || !is_string($raw) || strlen($raw) > self::MAX_RESPONSE || $macCount !== 1 || !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(); } // Validate objects before associative decoding, so {} cannot impersonate []. $value = json_decode($raw, false, 32, JSON_THROW_ON_ERROR); if ($status === 200) { $this->validateSuccess($value, $request, $now); } else { if (!in_array($status, [403,404,409,422,429,503], true) || !self::keys($value, ['version','client_id','generated_at','error']) || !$this->envelope($value, $now) || !self::keys($value->error, ['code','message']) || $value->error->code !== $status || !self::text($value->error->message, 200, false)) { throw new \RuntimeException(); } } $decoded = json_decode($raw, true, 32, JSON_THROW_ON_ERROR); } catch (\Throwable $error) { throw new ApiError(503, '客服授权暂时不可用,请刷新核对后重试'); } // Only authenticated, strictly validated error messages cross this boundary. if ($status !== 200) { throw new ApiError($status, $decoded['error']['message']); } return $decoded; } private static function keys(mixed $value, array $expected): bool { if (!$value instanceof \stdClass) { return false; } $keys = array_keys(get_object_vars($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 $value): bool { return is_string($value) && strlen($value) <= 80 && (bool)preg_match('/^[a-z][a-z0-9-]*(?::[a-z0-9-]+)+$/D', $value); } private static function codes(mixed $values): bool { if (!is_array($values) || !array_is_list($values) || count($values) > 2000) { return false; } $seen = []; foreach ($values as $value) { if (!self::code($value) || isset($seen[$value])) { return false; } $seen[$value] = true; } return true; } private function envelope(\stdClass $value, int $now): bool { return $value->version === 1 && $value->client_id === 'kefu' && is_int($value->generated_at) && abs($value->generated_at-$now) <= 90; } private function validateSuccess(mixed $value, array $request, int $now): void { if (!self::keys($value, ['version','client_id','generated_at','subject','revision','roles','catalog']) || !$this->envelope($value, $now) || !is_string($value->revision) || !preg_match('/^[a-f0-9]{64}$/D', $value->revision) || !is_array($value->roles) || !array_is_list($value->roles) || count($value->roles) > 2000 || !self::keys($value->catalog, ['permissions']) || !is_array($value->catalog->permissions) || !array_is_list($value->catalog->permissions) || count($value->catalog->permissions) > 2000) { throw new \RuntimeException(); } $subject = $value->subject; if (!self::keys($subject, ['gid','found','source_admin_id','company_id','user']) || $subject->found !== true || $subject->gid !== $request['gid'] || $subject->source_admin_id !== $request['source_admin_id'] || $subject->company_id !== $request['company_id']) { 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) || !self::codes($user->permissions) || (!$user->active && $user->permissions !== [])) { throw new \RuntimeException(); } $catalog = []; foreach ($value->catalog->permissions as $row) { if (!self::keys($row,['code','name','group','page','kind','source','enabled','sort']) || !self::code($row->code) || isset($catalog[$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(); } $catalog[$row->code] = true; } $roles = []; $assigned = null; foreach ($value->roles as $role) { if (!self::keys($role,['code','name','permissions']) || !self::text($role->code,80,false) || isset($roles[$role->code]) || !self::text($role->name,200) || !self::codes($role->permissions)) { throw new \RuntimeException(); } foreach ($role->permissions as $code) { if (!isset($catalog[$code])) { throw new \RuntimeException(); } } $roles[$role->code] = true; if ($role->code === $user->role->code) { if ($role->name !== $user->role->name) { throw new \RuntimeException(); } $assigned = $role->permissions; } } if ($assigned === null || ($user->active && !self::sameCodes($assigned, $user->permissions))) { throw new \RuntimeException(); } if (isset($request['expected_revision'])) { if ($request['permissions'] === null ? $user->role->code !== $request['role_code'] : !self::sameCodes($assigned, $request['permissions'])) { throw new \RuntimeException(); } } } private static function sameCodes(array $left, array $right): bool { sort($left); sort($right); return $left === $right; } private function curl(string $path, array $headers, string $body): array { if (!function_exists('curl_init')) { throw new \RuntimeException(); } $handle = curl_init($this->base.$path); $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=>5,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); } } }