-
Notifications
You must be signed in to change notification settings - Fork 91
Switch to proxy URL to handle API requests to demo, #PG-5029 #876
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| <?php | ||
| /** | ||
| * Piwik - Open source web analytics | ||
| * | ||
| * @link http://piwik.org | ||
| * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later | ||
| */ | ||
|
|
||
| namespace helpers; | ||
|
|
||
| /** | ||
| * Proxy for demo.matomo.cloud, allows us to make single origin requests by doing them through this class | ||
| */ | ||
| class DemoProxy | ||
| { | ||
|
|
||
| public const MATOMO_SWAGGER_PROXY_TARGET = 'https://demo.matomo.cloud'; | ||
|
|
||
| /** | ||
| * Fetches a demo API GET response and returns the body and status code. | ||
| * | ||
| * @param string $url Demo API URL to request. | ||
| * @param string $authorizationHeader Optional Authorization header value to forward. | ||
| * @return array{body: string, statusCode: int} | ||
| */ | ||
| public static function get(string $url, string $authorizationHeader = ''): array | ||
| { | ||
| $context = self::createContext($authorizationHeader); | ||
| $proxiedResponse = self::fetchResponse($url, $context); | ||
| $statusCode = self::parseStatusCode($proxiedResponse['responseHeaders']); | ||
|
|
||
| return [ | ||
| 'body' => $proxiedResponse['body'], | ||
| 'statusCode' => $statusCode, | ||
| ]; | ||
| } | ||
|
|
||
| private static function createContext(string $authorizationHeader) | ||
| { | ||
| return stream_context_create([ | ||
| 'http' => [ | ||
| 'method' => 'GET', | ||
| 'header' => self::buildHeaders($authorizationHeader), | ||
| 'ignore_errors' => true, | ||
| 'timeout' => 30, | ||
| ], | ||
| ]); | ||
| } | ||
|
|
||
| private static function buildHeaders(string $authorizationHeader): string | ||
| { | ||
| if ($authorizationHeader === '') { | ||
| return ''; | ||
| } | ||
|
|
||
| return 'Authorization: ' . $authorizationHeader; | ||
| } | ||
|
|
||
| /** | ||
| * @return array{body: string, responseHeaders: array} | ||
| */ | ||
| private static function fetchResponse(string $url, $context): array | ||
| { | ||
| $body = @file_get_contents($url, false, $context); | ||
| if ($body === false) { | ||
| throw new \RuntimeException('Could not proxy HTTP request'); | ||
| } | ||
|
|
||
| return [ | ||
| 'body' => $body, | ||
| 'responseHeaders' => $http_response_header ?? [], | ||
| ]; | ||
| } | ||
|
|
||
| private static function parseStatusCode(array $responseHeaders): int | ||
| { | ||
| $statusLine = $responseHeaders[0] ?? ''; | ||
|
|
||
| if (preg_match('#^HTTP/\S+\s+(\d{3})#', $statusLine, $matches)) { | ||
| return (int) $matches[1]; | ||
| } | ||
|
|
||
| return 200; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,6 +20,7 @@ | |
| use helpers\Content\Category\TracTicketArchiveCategory; | ||
| use helpers\Content\Guide; | ||
| use helpers\Content\PhpDoc; | ||
| use helpers\DemoProxy; | ||
| use helpers\DocumentNotExistException; | ||
| use helpers\Environment; | ||
| use helpers\OpenApiSpecRegistry; | ||
|
|
@@ -31,6 +32,7 @@ | |
| use Slim\Exception\HttpNotFoundException; | ||
|
|
||
|
|
||
|
|
||
| function renderGuide(Slim\Views\Twig $view, Response $response, Psr\Http\Message\UriInterface $uri, Guide $guide, Category $category, string $template = 'guide.twig') | ||
| { | ||
| return $view->render($response, $template, [ | ||
|
|
@@ -265,6 +267,20 @@ function renderGuide(Slim\Views\Twig $view, Response $response, Psr\Http\Message | |
| ->withStatus(200); | ||
| }); | ||
|
|
||
| $app->get('/demo-proxy/{path:.*}', function (Request $request, Response $response, $args) { | ||
| $path = ltrim($args['path'] ?? '', '/'); | ||
| $targetUrl = rtrim(DemoProxy::MATOMO_SWAGGER_PROXY_TARGET, '/') . '/' . $path; | ||
| $query = $request->getUri()->getQuery(); | ||
| if ($query !== '') { | ||
| $targetUrl .= '?' . $query; | ||
| } | ||
|
|
||
| $proxiedResponse = DemoProxy::get($targetUrl, $request->getHeaderLine('Authorization')); | ||
|
|
||
| $response->getBody()->write($proxiedResponse['body']); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should add a try/catch here
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done, I also realised we return errors with a 200 OK? At the moment it doesn't break anything in Swagger, technically we could catch in the proxy and throw something else |
||
| return $response->withStatus($proxiedResponse['statusCode']); | ||
| }); | ||
|
|
||
| $app->post('/receive-commit-hook', function (Request $request, Response $response, $args) { | ||
| $params = $request->getQueryParams(); | ||
| if (empty($params["token"]) || !password_verify($params["token"], WEBHOOK_TOKEN)) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -19,7 +19,8 @@ | |||||
| <script src="/vendor/swagger-ui/swagger-ui-bundle.js?{{ revision|e('html_attr') }}"></script> | ||||||
| <script type="text/javascript"> | ||||||
| window.onload = function () { | ||||||
| let pluginSpec = {{ pluginSpecJson|raw }}; | ||||||
| let pluginSpecJson = {{ pluginSpecJson|raw }}; | ||||||
| let proxyBaseUrl = window.location.origin + '/demo-proxy'; | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||||||
| let summaryPrefix = '/index.php?module=API&method='; | ||||||
|
|
||||||
| function clonePluginSpec(spec) { | ||||||
|
|
@@ -50,10 +51,15 @@ | |||||
| } | ||||||
|
|
||||||
| if (typeof SwaggerUIBundle === 'function') { | ||||||
| let pluginSpec = clonePluginSpec(pluginSpecJson); | ||||||
|
|
||||||
| // CORs on demo not allowing authorization: Bearer anonymous in preflight, so we need a proxy into demo | ||||||
| pluginSpec.servers = [{ url: proxyBaseUrl }]; | ||||||
|
|
||||||
| SwaggerUIBundle({ | ||||||
| dom_id: '#swagger-ui', | ||||||
| url: null, | ||||||
| spec: clonePluginSpec(pluginSpec), | ||||||
| spec: pluginSpec, | ||||||
| docExpansion: 'list', | ||||||
| tagsSorter: 'alpha', | ||||||
| presets: [ | ||||||
|
|
||||||

There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
main concern is that it now becomes a proxy to query
demo.matomo.cloudwithout any CORS errorWe can add a check that requestURL path should be index.php and Module should be API along with CSRF token.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Have added some URL validation so only the API can be queried.
Demo is a public instance, are we exposing anything that isn't already available with this proxy? For the CSRF token, we don't have a session on developer docs, so not sure where we can store that