-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathController.php
More file actions
446 lines (382 loc) · 17.3 KB
/
Copy pathController.php
File metadata and controls
446 lines (382 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\OAuth2;
use Matomo\Dependencies\OAuth2\Nyholm\Psr7\Factory\Psr17Factory;
use Matomo\Dependencies\OAuth2\Nyholm\Psr7\Response;
use Matomo\Dependencies\OAuth2\Nyholm\Psr7Server\ServerRequestCreator;
use Piwik\Common;
use Piwik\Log;
use Piwik\Nonce;
use Piwik\Piwik;
use Piwik\Plugin\ControllerAdmin;
use Piwik\Plugin\Manager;
use Piwik\Plugins\OAuth2\Entities\ClientEntity;
use Piwik\Plugins\OAuth2\Entities\UserEntity;
use Piwik\Plugins\OAuth2\Model\ClientModel;
use Piwik\Plugins\OAuth2\Repositories\ScopeRepository;
use Piwik\Plugins\OAuth2\Service\AuthorizationServerMetadata;
use Piwik\Plugins\OAuth2\Service\ServerFactory;
use Piwik\Plugins\UsersManager\Model as UserModel;
use Piwik\Request;
use Piwik\Url;
use Matomo\Dependencies\OAuth2\Psr\Http\Message\ResponseInterface;
use Matomo\Dependencies\OAuth2\League\OAuth2\Server\Entities\ClientEntityInterface;
use Matomo\Dependencies\OAuth2\League\OAuth2\Server\Exception\OAuthServerException;
class Controller extends ControllerAdmin
{
public function __construct(
private ClientModel $clientModel,
private ScopeRepository $scopeRepository,
private ServerFactory $serverFactory,
private SystemSettings $settings,
private UserModel $userModel,
private AuthorizationServerMetadata $authorizationServerMetadata
) {
parent::__construct();
}
public function index()
{
Piwik::checkUserHasSuperUserAccess();
$baseUrl = Url::getCurrentUrlWithoutFileName();
$viewData = [
'clients' => array_map(static function (array $client) {
unset($client['secret_hash']);
return $client;
}, $this->clientModel->all()),
'scopes' => $this->scopeRepository->describeScopes(),
'authorizeUrl' => $baseUrl . 'index.php?module=OAuth2&action=authorize',
'tokenUrl' => $baseUrl . 'index.php?module=OAuth2&action=token',
];
return $this->renderTemplate('index', $viewData);
}
public function authorize()
{
if (!$this->settings->enableAuthorizationCode->getValue()) {
return $this->renderUnauthorized(Piwik::translate('OAuth2_AuthorizationCodeGrantDisabled'));
}
if (Piwik::isUserIsAnonymous()) {
Piwik::checkUserIsNotAnonymous();
}
$psrRequest = $this->createServerRequest();
$authServer = $this->serverFactory->makeAuthorizationServer();
try {
$authRequest = $authServer->validateAuthorizationRequest($psrRequest);
} catch (OAuthServerException $e) {
$this->logOAuthRequestFailure('authorize', $e);
return $this->emitResponse($e->generateHttpResponse(new Response()));
} catch (\Throwable $e) {
$this->logOAuthRequestFailure('authorize', $e);
return $this->renderUnauthorized(Piwik::translate('OAuth2_InvalidAuthorizationRequest'));
}
$login = Piwik::getCurrentUserLogin();
$userEntity = new UserEntity();
$userEntity->setIdentifier($login);
$authRequest->setUser($userEntity);
$scopes = array_map(function ($scope) {
return $scope->getIdentifier();
}, $authRequest->getScopes());
$requestedClientScopes = $this->getScopesAllowedForClient(array_values($scopes), $authRequest->getClient());
if (empty($requestedClientScopes)) {
return $this->renderUnauthorized(Piwik::translate('OAuth2_InvalidClientScope'));
}
$selectableScopes = $this->getScopesUserCanGrant($requestedClientScopes);
if (empty($selectableScopes)) {
return $this->renderUnauthorized(Piwik::translate(
'OAuth2_NoAccessForRequestedScopes',
implode(', ', $requestedClientScopes)
));
}
if ($this->isPostRequest()) {
// the consent form is submitted as POST, and Request::fromRequest() lets a query string
// parameter of the same name win, so the decision must be read from the POST body only
$post = Request::fromPost();
$decision = $post->getStringParameter('decision', '');
$nonce = $post->getStringParameter('nonce', '');
if (!Nonce::verifyNonce('Oauth2.authorize', $nonce)) {
return $this->renderUnauthorized(Piwik::translate('OAuth2_InvalidAuthorizationRequest'));
}
if (!in_array($decision, ['allow', 'deny'], true)) {
return $this->renderUnauthorized(Piwik::translate('OAuth2_InvalidAuthorizationRequest'));
}
$selectedScope = $post->getStringParameter('selected_scope', '');
if (!in_array($selectedScope, $selectableScopes, true)) {
return $this->renderUnauthorized(Piwik::translate('OAuth2_InvalidScopeValue'));
}
$this->checkDoesUserHasAccessAsPerScope($selectedScope);
$authRequest->setScopes([$this->scopeRepository->getScopeEntityByIdentifier($selectedScope)]);
$isApproved = $decision === 'allow';
$authRequest->setAuthorizationApproved($isApproved);
/**
* Triggered after a user allowed or denied an OAuth 2.0 authorization request on the
* consent screen, before the authorization code is issued.
*
* Used by the plugin itself to record the decision in the activity log, and available
* to other plugins that need to audit or react to granted and denied access.
*
* @param array $activityData Details of the decision:
*
* - `version`: the payload version, currently `v1`.
* - `client`: the OAuth client, with `id` and `name`, plus
* `type` and `active` for clients of this plugin.
* - `userLogin`: the login of the user who decided.
* - `scopes`: the scopes that were granted. The user grants
* exactly one, so this holds a single scope, and it is
* empty when the request was denied.
* - `requestedScopes`: everything the client asked for. An
* authorize request may name several scopes even though
* only one of them can be granted.
* - `decision`: either `allowed` or `denied`.
*/
Piwik::postEvent('OAuth2.authorize.decision.end', [
$this->buildAuthorizationActivityData(
$authRequest->getClient(),
$login,
array_values($scopes),
$selectedScope,
$isApproved
),
]);
try {
$response = $authServer->completeAuthorizationRequest($authRequest, new Response());
} catch (OAuthServerException $e) {
$this->logOAuthRequestFailure('authorize', $e);
$response = $e->generateHttpResponse(new Response());
} catch (\Throwable $e) {
$this->logOAuthRequestFailure('authorize', $e);
$response = (new Response())->withStatus(500)->withBody((new Psr17Factory())->createStream(Piwik::translate('OAuth2_ServerError')));
}
return $this->emitResponse($response);
}
$client = $authRequest->getClient();
$user = $this->userModel->getUser($login);
$termsAndConditionUrl = '';
$privacyPolicyUrl = '';
if (Manager::getInstance()->isPluginActivated('PrivacyManager')) {
$coreSettings = new \Piwik\Plugins\PrivacyManager\SystemSettings();
$termsAndConditionUrl = $coreSettings->termsAndConditionUrl->getValue();
$privacyPolicyUrl = $coreSettings->privacyPolicyUrl->getValue();
}
return $this->renderTemplate('authorize', [
'clientName' => $client->getName(),
'clientId' => $client->getIdentifier(),
'userLogin' => $login,
'userEmail' => $user['email'] ?? '',
'scopes' => $selectableScopes,
'scopeDescriptions' => $this->scopeRepository->describeScopes(),
'nonce' => Nonce::getNonce('Oauth2.authorize'),
'termsAndCondition' => $termsAndConditionUrl,
'privacyPolicyUrl' => $privacyPolicyUrl,
]);
}
public function token()
{
if (!$this->isPostRequest()) {
$response = (new Response())
->withStatus(405, 'Method Not Allowed')
->withHeader('Allow', 'POST')
->withBody((new Psr17Factory())->createStream(Piwik::translate('OAuth2_TokenEndpointException')));
return $this->emitResponse($response);
}
$psrRequest = $this->createServerRequest();
$authServer = $this->serverFactory->makeAuthorizationServer();
$response = new Response();
try {
$response = $authServer->respondToAccessTokenRequest($psrRequest, $response);
} catch (OAuthServerException $e) {
$this->logOAuthRequestFailure('token', $e);
$response = $e->generateHttpResponse($response);
} catch (\Throwable $e) {
$this->logOAuthRequestFailure('token', $e);
$response = $response->withStatus(500)->withBody((new Psr17Factory())->createStream(Piwik::translate('OAuth2_ServerError')));
}
return $this->emitResponse($response);
}
/**
* Serves the OAuth 2.0 Authorization Server Metadata document (RFC 8414).
*
* This is a public endpoint. The web server is expected to forward
* `/.well-known/oauth-authorization-server` to this action; see the plugin README.
*/
public function metadata()
{
// This is a public, cacheable document. Matomo's normal dispatch starts a session,
// which queues a session cookie and PHP's session cache-limiter headers
// (Expires/Pragma: no-cache). Strip those so the response is cookie-free and cleanly
// cacheable; the Cache-Control header sent below replaces the session's one.
if (!headers_sent()) {
header_remove('Set-Cookie');
header_remove('Expires');
header_remove('Pragma');
}
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
$psr17Factory = new Psr17Factory();
if ($method !== 'GET' && $method !== 'HEAD') {
$response = (new Response())
->withStatus(405, 'Method Not Allowed')
->withHeader('Allow', 'GET, HEAD')
->withHeader('Content-Type', 'application/json; charset=utf-8')
->withBody($psr17Factory->createStream((string) json_encode(['error' => 'Method not allowed.'])));
return $this->emitResponse($response);
}
$metadata = $this->authorizationServerMetadata->build();
$body = $method === 'HEAD' ? '' : (string) json_encode($metadata);
$response = (new Response())
->withStatus(200)
->withHeader('Content-Type', 'application/json; charset=utf-8')
->withHeader('Cache-Control', 'public, max-age=3600')
->withBody($psr17Factory->createStream($body));
return $this->emitResponse($response);
}
private function createServerRequest()
{
$psr17Factory = new Psr17Factory();
$creator = new ServerRequestCreator($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
return $creator->fromGlobals();
}
private function emitResponse(ResponseInterface $response)
{
$this->sendResponseCode($response->getStatusCode(), $response->getReasonPhrase());
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
Common::sendHeader($name . ': ' . $value);
}
}
echo (string) $response->getBody();
return null;
}
private function isPostRequest(): bool
{
return !empty($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD']) === 'POST';
}
private function renderUnauthorized(string $message)
{
$this->sendResponseCode(400);
return $message;
}
private function sendResponseCode(int $statusCode, string $reasonPhrase = ''): void
{
try {
Common::sendResponseCode($statusCode);
return;
} catch (\Exception $e) {
// Common::sendResponseCode() only knows a fixed set of status codes and rejects the
// others, such as the 405 the token and metadata endpoints send for a wrong method.
}
Common::sendHeader(rtrim($this->getStatusHeaderPrefix() . ' ' . $statusCode . ' ' . $reasonPhrase));
}
/**
* Same prefix Common::sendResponseCode() uses, as FastCGI needs a Status header instead of a
* status line and the response should keep the protocol the request was made with.
*/
private function getStatusHeaderPrefix(): string
{
if (strpos(PHP_SAPI, '-fcgi') !== false) {
return 'Status:';
}
$protocol = $_SERVER['SERVER_PROTOCOL'] ?? '';
if (strlen($protocol) > 1 && strlen($protocol) < 15) {
return $protocol;
}
return 'HTTP/1.1';
}
private function buildAuthorizationActivityData(
$client,
string $login,
array $requestedScopes,
string $selectedScope,
bool $isApproved
): array {
$clientData = [
'id' => method_exists($client, 'getIdentifier') ? $client->getIdentifier() : null,
'name' => method_exists($client, 'getName') ? $client->getName() : null,
];
if ($client instanceof ClientEntity) {
$clientData['type'] = $client->type;
$clientData['active'] = $client->active;
}
return [
'version' => 'v1',
'client' => $clientData,
'userLogin' => $login,
// keeps reporting the effective permission, which is nothing at all when denied, so a
// listener reading only this field can never read more access than was granted
'scopes' => $isApproved ? [$selectedScope] : [],
'requestedScopes' => array_values($requestedScopes),
'decision' => $isApproved ? 'allowed' : 'denied',
];
}
private function logOAuthRequestFailure(string $endpoint, \Throwable $exception): void
{
Log::warning(
'OAuth 2.0 %s request failed: %s (%s)',
$endpoint,
get_class($exception),
(string) $exception->getCode()
);
}
private function checkDoesUserHasAccessAsPerScope(string $scope): void
{
switch ($scope) {
case 'matomo:read':
Piwik::checkUserHasSomeViewAccess();
break;
case 'matomo:write':
Piwik::checkUserHasSomeWriteAccess();
break;
case 'matomo:admin':
Piwik::checkUserHasSomeAdminAccess();
break;
case 'matomo:superuser':
Piwik::checkUserHasSuperUserAccess();
break;
default:
// never reached, the scope is validated against the selectable scopes beforehand
throw new \Exception(Piwik::translate('OAuth2_InvalidScopeValue'));
}
}
/**
* Returns the requested scopes the client is allowed to use, in ascending privilege order
* (read < write < admin < superuser).
*/
private function getScopesAllowedForClient(array $requestedScopes, ClientEntityInterface $client): array
{
$allowed = $this->scopeRepository->getAllowedScopeIds();
if ($client instanceof ClientEntity && !empty($client->getAllowedScopes())) {
// an empty client scope list means no client specific restriction, as in ScopeRepository::finalizeScopes()
$allowed = array_values(array_intersect(
$allowed,
ScopeRepository::expandScopes($client->getAllowedScopes())
));
}
return array_values(array_intersect($allowed, $requestedScopes));
}
/**
* Returns the scopes the current user has a high enough access level to grant.
*/
private function getScopesUserCanGrant(array $scopes): array
{
return array_values(array_filter($scopes, function (string $scope) {
return $this->canUserGrantScope($scope);
}));
}
private function canUserGrantScope(string $scope): bool
{
switch ($scope) {
case 'matomo:read':
return Piwik::isUserHasSomeViewAccess();
case 'matomo:write':
return Piwik::isUserHasSomeWriteAccess();
case 'matomo:admin':
return Piwik::isUserHasSomeAdminAccess();
case 'matomo:superuser':
return Piwik::hasUserSuperUserAccess();
default:
return false;
}
}
}