Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions app/helpers/DemoProxy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?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
{

private const MATOMO_SWAGGER_PROXY_TARGET = 'https://demo.matomo.cloud';
private const DEMO_AUTHORIZATION_HEADER = 'Bearer anonymous';

/**
* Fetches a demo API GET response and returns the body and status code.
*
* @param string $url Demo API URL to request.
* @return array{body: string, statusCode: int}
*/
public static function get(string $url): array
{
$context = self::createContext();
$proxiedResponse = self::fetchResponse($url, $context);
$statusCode = self::parseStatusCode($proxiedResponse['responseHeaders']);

return [
'body' => $proxiedResponse['body'],
'statusCode' => $statusCode,
];
}

/**
* Builds a validated demo API URL for proxying.
*
* @param string $path Relative request path.
* @param array $queryParams Query parameters to append to the URL.
* @return string The validated absolute demo API URL.
* @throws \InvalidArgumentException If the path is not index.php.
* @throws \InvalidArgumentException If the module query parameter is not API.
*/
public static function buildValidatedApiUrl(string $path, array $queryParams): string
{
$normalizedPath = trim($path, '/');
if ($normalizedPath !== 'index.php') {
throw new \InvalidArgumentException('Path must be index.php');
}

if (($queryParams['module'] ?? null) !== 'API') {
throw new \InvalidArgumentException('Module must be API');
}

$targetUrl = rtrim(self::MATOMO_SWAGGER_PROXY_TARGET, '/') . '/' . $normalizedPath;
$query = http_build_query($queryParams);

if ($query !== '') {
$targetUrl .= '?' . $query;
}

return $targetUrl;
}

private static function createContext()
{
return stream_context_create([
'http' => [
'method' => 'GET',
'header' => self::buildHeaders(),
'ignore_errors' => true,
'timeout' => 30,
],
]);
}

private static function buildHeaders(): string
{
return 'Authorization: ' . self::DEMO_AUTHORIZATION_HEADER;
}

/**
* @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;
}
}
23 changes: 23 additions & 0 deletions app/routes/page.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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, [
Expand Down Expand Up @@ -265,6 +267,27 @@ function renderGuide(Slim\Views\Twig $view, Response $response, Psr\Http\Message
->withStatus(200);
});

$app->get('/demo/{path:.*}', function (Request $request, Response $response, $args) {
$path = $args['path'] ?? '';

try {
$targetUrl = DemoProxy::buildValidatedApiUrl($path, $request->getQueryParams());
} catch (\InvalidArgumentException $e) {
$response->getBody()->write($e->getMessage());
return $response->withStatus(400);
}

try {
$proxiedResponse = DemoProxy::get($targetUrl);
} catch (\RuntimeException $e) {
$response->getBody()->write('Could not proxy demo request');
return $response->withStatus(502);
}

$response->getBody()->write($proxiedResponse['body']);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should add a try/catch here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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)) {
Expand Down
10 changes: 8 additions & 2 deletions app/templates/api-swagger.twig
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '/demo';
let summaryPrefix = '/index.php?module=API&method=';

function clonePluginSpec(spec) {
Expand Down Expand Up @@ -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: [
Expand Down