执行带证书的请求

@param $request
@param $certPemPath
@param $keyPemPath
@return array|mixed
490069
protected function executeRequestWithPem($request, $certPemPath, $keyPemPath)
    {
        // 请求微信服务器
        $result = $this->request->curlPostWithCert($request->getRequestUrl(), $request->params(), $certPemPath, $keyPemPath);

        $result = (array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);

        return $result;
    }
665397
private function _compatFPM(Request $request)
    {
        // Override php globals array
        // Store $_GET, $_POST ....
        $_GET    = $request->get ?? [];
        $_POST   = $request->post ?? [];
        $_COOKIE = $request->cookie ?? [];
        $_FILES  = $request->files ?? [];
        // $_REQUEST  = array_merge($_COOKIE, $_GET, $_POST);

        // 注入全局变量
        $GLOBALS['__$request']  = $request;
        $GLOBALS['__$DB_QUERY_COUNT'] = 0;

        // 兼容php-fpm的$_SERVER
        $_SERVER = [];
        foreach ($request->server as $key => $value) {
            $key = strtoupper($key);
            $_SERVER[$key] = $value;

            // FIXED: swoole REQUEST_URI don't contains QUERY_STRING
            if ($key === 'REQUEST_URI' && isset($_SERVER['QUERY_STRING'])) {
                $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
            }
        }

        // 兼容php-fpm的header传值
        foreach ($request->header as $key => $value) {
            $key = strtoupper(str_replace('-', '_', $key));
            if ($key === 'CONTENT_TYPE' || $key === 'CONTENT_LENGTH') {
                $_SERVER[$key] = $value;
            } else {
                $_SERVER['HTTP_' . $key] = $value;
            }
        }
    }
981880
public function match($path, RouteRequest $request = null)
    {
        $requestMethod = null;

        if ($request) {

            $requestMethod = self::convertRequestMethodConstant($request->getRequestMethod());

        } else if (isset($_SERVER['REQUEST_METHOD'])) {

            $requestMethod = self::convertRequestMethodConstant($_SERVER['REQUEST_METHOD']);

        }

        foreach ($this->routes as $route) {
            // If the route is using pcre pattern marching...
            if ($route[0]) {
                if (!preg_match($route[1], $path, $matches)) {
                    continue;
                }
                $route[3]['vars'] = $matches;

                // validate request method
                if (isset($route[3]['method']) && $route[3]['method'] != $requestMethod) {
                    continue;
                }
                if (isset($route[3]['domain']) && $route[3]['domain'] != $_SERVER['HTTP_HOST']) {
                    continue;
                }
                if (isset($route[3]['secure']) && $route[3]['secure'] && $_SERVER['HTTPS']) {
                    continue;
                }

                return $route;
            } else {
                // prefix match is used when expanding is not enabled.
                if ((
                        (is_int($route[2]) || $route[2] instanceof self || $route[2] instanceof \PHPSGI\App)
                        && strncmp($route[1], $path, strlen($route[1])) === 0
                    ) || $route[1] == $path) {
                    // validate request method
                    if (isset($route[3]['method']) && $route[3]['method'] != $requestMethod) {
                        continue;
                    }
                    if (isset($route[3]['domain']) && $route[3]['domain'] != $_SERVER['HTTP_HOST']) {
                        continue;
                    }
                    if (isset($route[3]['secure']) && $route[3]['secure'] && $_SERVER['HTTPS']) {
                        continue;
                    }

                    return $route;
                }
                continue;
            }
        }
    }
50203
private function validateCertContent(array $cert, string $localCertPath)
    {
        // validate cert subject
        if (false === isset($cert['extensions']['subjectAltName']) ||
            false === stristr($cert['extensions']['subjectAltName'], 'echo-api.amazon.com')
        ) {
            throw new RequestInvalidSignatureException('Cert subject error.');
        }

        // validate cert validTo time
        if (false === isset($cert['validTo_time_t']) || time() > $cert['validTo_time_t'] || false === isset($cert['validFrom_time_t']) || time() < $cert['validFrom_time_t']) {
            if (file_exists($localCertPath)) {
                @unlink($localCertPath);
            }
            throw new OutdatedCertExceptionException('Cert is outdated.');
        }
    }
1319058
public function nextQuestionAction(Request $request)
    {
        $questionInteract = $this->get('qcm_core.question.interact');
        $formType = $this->get('qcm_core.form.type.reply');
        $form = $this->createForm($formType);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $questionInteract->saveStep($form);
            $configuration = $questionInteract->getUserConfiguration();

            if (!is_null($configuration->getTimeout()) && $configuration->getQuestions()->count() - $configuration->getAnswers()->count() == 0 ||
                false === $questionInteract->getNextQuestion()
            ) {
                $url = 'qcm_public_question_summary';

                if (!is_null($configuration->getTimePerQuestion())) {
                    $url = 'qcm_public_question_end';
                }

                return $this->redirect($this->generateUrl($url));
            }
        }

        return $this->redirect($this->generateUrl('qcm_public_question_reply'));
    }
985209
public function searchAction(Request $request)
    {
        $this->denyAccessIfProfilerDisabled();

        $ip = preg_replace('/[^:\d\.]/', '', $request->query->get('ip'));
        $method = $request->query->get('method');
        $statusCode = $request->query->get('status_code');
        $url = $request->query->get('url');
        $start = $request->query->get('start', null);
        $end = $request->query->get('end', null);
        $limit = $request->query->get('limit');
        $token = $request->query->get('token');

        if ($request->hasSession()) {
            $session = $request->getSession();

            $session->set('_profiler_search_ip', $ip);
            $session->set('_profiler_search_method', $method);
            $session->set('_profiler_search_status_code', $statusCode);
            $session->set('_profiler_search_url', $url);
            $session->set('_profiler_search_start', $start);
            $session->set('_profiler_search_end', $end);
            $session->set('_profiler_search_limit', $limit);
            $session->set('_profiler_search_token', $token);
        }

        if (!empty($token)) {
            return new RedirectResponse($this->generator->generate('_profiler', ['token' => $token]), 302, ['Content-Type' => 'text/html']);
        }

        $tokens = $this->profiler->find($ip, $url, $limit, $method, $start, $end, $statusCode);

        return new RedirectResponse($this->generator->generate('_profiler_search_results', [
            'token' => $tokens ? $tokens[0]['token'] : 'empty',
            'ip' => $ip,
            'method' => $method,
            'status_code' => $statusCode,
            'url' => $url,
            'start' => $start,
            'end' => $end,
            'limit' => $limit,
        ]), 302, ['Content-Type' => 'text/html']);
    }
585050
public function signature ( $request, $base_string, $consumer_secret, $token_secret )
	{
		// Fetch the private key cert based on the request
		$cert = $this->fetch_private_cert($request);
		
		// Pull the private key ID from the certificate
		$privatekeyid = openssl_get_privatekey($cert);
		
		// Sign using the key
		$sig = false;
		$ok  = openssl_sign($base_string, $sig, $privatekeyid);   
		
		// Release the key resource
		openssl_free_key($privatekeyid);
		  
		return $request->urlencode(base64_encode($sig));
	}
177170
private function formatKey($certData)
    {
        return X509Certificate::PEM_HEADER .
            PHP_EOL .
            // Chunk it in 64 character bytes
            chunk_split($certData, 64, PHP_EOL) .
            X509Certificate::PEM_FOOTER .
            PHP_EOL;
    }
125674
function parseRequest($request)
    {
        $url_info = parse_url($request->meta['uri']);
        $request->meta['path'] = $url_info['path'];
        if (isset($url_info['fragment'])) $request->meta['fragment'] = $url_info['fragment'];
        if (isset($url_info['query']))
        {
            parse_str($url_info['query'], $request->get);
        }
        //POST请求,有http body
        if ($request->meta['method'] === 'POST')
        {
            $this->parser->parseBody($request);
        }
        //解析Cookies
        if (!empty($request->header['Cookie']))
        {
            $this->parser->parseCookie($request);
        }
    }
150224
public function setSSLCert($certPath, $passPhrase = null)
    {
        $this->curlOptions[CURLOPT_SSLCERT] = realpath($certPath);
        if (isset($passPhrase) && trim($passPhrase) != "") {
            $this->curlOptions[CURLOPT_SSLCERTPASSWD] = $passPhrase;
        }
    }
135294
public function send(\Psr\Http\Message\RequestInterface $request)
    {
        if($this->credentials instanceof Container) {
            if ($this->needsKeypairAuthentication($request)) {
                $request = $request->withHeader('Authorization', 'Bearer ' . $this->credentials->get(Keypair::class)->generateJwt());
            } else {
                $request = self::authRequest($request, $this->credentials->get(Basic::class));
            }
        } elseif($this->credentials instanceof Keypair){
            $request = $request->withHeader('Authorization', 'Bearer ' . $this->credentials->generateJwt());
        } elseif($this->credentials instanceof SignatureSecret){
            $request = self::signRequest($request, $this->credentials);
        } elseif($this->credentials instanceof Basic){
            $request = self::authRequest($request, $this->credentials);
        }

        //todo: add oauth support

        //allow any part of the URI to be replaced with a simple search
        if(isset($this->options['url'])){
            foreach($this->options['url'] as $search => $replace){
                $uri = (string) $request->getUri();

                $new = str_replace($search, $replace, $uri);
                if($uri !== $new){
                    $request = $request->withUri(new Uri($new));
                }
            }
        }

        // The user agent must be in the following format:
        // LIBRARY-NAME/LIBRARY-VERSION LANGUAGE-NAME/LANGUAGE-VERSION [APP-NAME/APP-VERSION]
        // See https://github.com/Nexmo/client-library-specification/blob/master/SPECIFICATION.md#reporting
        $userAgent = [];

        // Library name
        $userAgent[] = 'nexmo-php/'.self::VERSION;

        // Language name
        $userAgent[] = 'php/'.PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;

        // If we have an app set, add that to the UA
        if (isset($this->options['app'])) {
            $app = $this->options['app'];
            $userAgent[] = $app['name'].'/'.$app['version'];
        }

        // Set the header. Build by joining all the parts we have with a space
        $request = $request->withHeader('User-Agent', implode(" ", $userAgent));

        $response = $this->client->sendRequest($request);
        return $response;
    }
740330
public function setCert(Http $http) {
        //两个文件合成一个.pem文件
        if (!empty($this->privateKeyFile)) {
            return $http->setOption(CURLOPT_SSLCERT, (string)$this->privateKeyFile);
        }
        //cert 与 key 分别属于两个.pem文件
        return $http->setOption([
            CURLOPT_SSLCERTTYPE => 'PEM',
            CURLOPT_SSLCERT => (string)$this->get('certFile'),
            CURLOPT_SSLCERTPASSWD => $this->get('mch_id'),
            CURLOPT_SSLKEYTYPE => 'PEM',
            CURLOPT_SSLKEY => (string)$this->get('keyFile'),
            CURLOPT_SSLKEYPASSWD => $this->get('mch_id'),
        ]);
    }
273173
public function process(&$request)
    {
        $authorize = $this->deny;
        assert('is_array($request)');
        assert('array_key_exists("Attributes", $request)');

        $attributes =& $request['Attributes'];

        foreach ($this->valid_attribute_values as $name => $patterns) {
            if (array_key_exists($name, $attributes)) {
                foreach ($patterns as $pattern) {
                    $values = $attributes[$name];
                    if (!is_array($values)) {
                        $values = array($values);
                    }
                    foreach ($values as $value) {
                        if ($this->regex) {
                            $matched = preg_match($pattern, $value);
                        } else {
                            $matched = ($value == $pattern);
                        }
                        if ($matched) {
                            $authorize = ($this->deny ? false : true);
                            break 3;
                        }
                    }
                }
            }
        }
        if (!$authorize) {
            $this->unauthorized($request);
        }
    }
528218
private function _exec($request, $params = null): ?string
  {
    if ( is_string($request) && bbn\str::is_json($request) ){
      $request = json_decode($request, true);
    }
    if ( is_array($request) ){
      return $this->_exec_array($request);
    }
    return $this->_exec_string($request, $params);
  }
658924
public function cpatchAction(Request $request)
    {
        try {
            $tags = [];

            $i = 0;
            while ($item = $request->get($i)) {
                if (isset($item['id'])) {
                    $tags[] = $this->getManager()->save($item, $item['id']);
                } else {
                    $tags[] = $this->getManager()->save($item);
                }
                ++$i;
            }
            $this->getDoctrine()->getManager()->flush();

            $context = new Context();
            $context->setGroups(['partialTag']);
            $view = $this->view($tags)->setContext($context);
        } catch (TagAlreadyExistsException $exc) {
            $cvExistsException = new ConstraintViolationException(
                'A tag with the name "' . $exc->getName() . '"already exists!',
                'name',
                ConstraintViolationException::EXCEPTION_CODE_NON_UNIQUE_NAME
            );
            $view = $this->view($cvExistsException->toArray(), 400);
        }

        return $this->handleView($view);
    }
425106
protected function signRequest(HttpRequest $request, $username, $timestamp, $secretKey)
    {
        $message = $username
                 . $timestamp
                 . $this->getRequestMessage($request)
        ;

        return $this->algorithm->sign($message, $secretKey);
    }
1215284
public function buildRequestBody(BaseRequest &$request)
    {
        $params = $request->getParameters();
        $params['SecretId'] = $this->secretId;
        $params['Nonce'] = rand(1, 65535);
        $params['Timestamp'] = time();
        $params['SignatureMethod'] = $this->signatureMethod;
        $host = str_replace(['http://', 'https://'], '', $this->endPoint);
        $plainText = $this->makeSignPlainText($params, $this->requestMethod, $host, $this->requestPath);
        //签名
        if ($this->signatureMethod == self::SIGNATURE_METHOD_HMAC_SHA256) {
            $params['Signature'] = base64_encode(hash_hmac('sha256', $plainText, $this->secretKey, true));
        } elseif ($this->signatureMethod == self::SIGNATURE_METHOD_HMAC_SHA1) {
            $params['Signature'] = base64_encode(hash_hmac('sha1', $plainText, $this->secretKey, true));
        }
        //var_dump($params);exit;
        return $params;
    }