-
Notifications
You must be signed in to change notification settings - Fork 611
/
GraphqlController.php
787 lines (659 loc) · 24.2 KB
/
GraphqlController.php
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\controllers;
use Craft;
use craft\errors\GqlException;
use craft\errors\MissingComponentException;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Gql as GqlHelper;
use craft\helpers\Json;
use craft\helpers\UrlHelper;
use craft\models\GqlSchema;
use craft\models\GqlToken;
use craft\models\Site;
use craft\services\Gql as GqlService;
use craft\web\assets\graphiql\GraphiqlAsset;
use craft\web\Controller;
use craft\web\ErrorHandler;
use Throwable;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\base\InvalidValueException;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
/**
* The GqlController class is a controller that handles various GraphQL related tasks.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.3.0
*/
class GraphqlController extends Controller
{
/**
* @inheritdoc
*/
protected array|bool|int $allowAnonymous = ['api'];
/**
* @inheritdoc
*/
public $defaultAction = 'api';
/**
* @inheritdoc
* @throws NotFoundHttpException
*/
public function beforeAction($action): bool
{
if (!Craft::$app->getConfig()->getGeneral()->enableGql) {
throw new NotFoundHttpException(Craft::t('yii', 'Page not found.'));
}
if ($action->id === 'api') {
$this->enableCsrfValidation = false;
}
if (!parent::beforeAction($action)) {
return false;
}
return true;
}
/**
* Performs a GraphQL query.
*
* @return Response
* @throws BadRequestHttpException
* @throws GqlException
* @throws ForbiddenHttpException
*/
public function actionApi(): Response
{
// Add CORS headers
$headers = $this->response->getHeaders();
$headers->setDefault('Access-Control-Allow-Credentials', 'true');
$headers->setDefault('Access-Control-Allow-Headers', 'Authorization, Content-Type, X-Craft-Authorization, X-Craft-Token');
$generalConfig = Craft::$app->getConfig()->getGeneral();
if (is_array($generalConfig->allowedGraphqlOrigins)) {
if (($origins = $this->request->getOrigin()) !== null) {
$origins = ArrayHelper::filterEmptyStringsFromArray(array_map('trim', explode(',', $origins)));
foreach ($origins as $origin) {
if (in_array($origin, $generalConfig->allowedGraphqlOrigins)) {
$headers->setDefault('Access-Control-Allow-Origin', $origin);
break;
}
}
}
} elseif ($generalConfig->allowedGraphqlOrigins !== false) {
$headers->setDefault('Access-Control-Allow-Origin', '*');
}
if ($this->request->getIsOptions()) {
// This is just a preflight request, no need to run the actual query yet
$this->response->format = Response::FORMAT_RAW;
$this->response->data = '';
return $this->response;
}
$this->response->format = Response::FORMAT_JSON;
$gqlService = Craft::$app->getGql();
$schema = $this->_schema($gqlService);
$this->_enforceSiteAccess($schema);
$query = $operationName = $variables = null;
// Check the body if it's a POST request
if ($this->request->getIsPost()) {
// If it's an application/graphql request, the whole body is the query
if ($this->request->getIsGraphql()) {
$query = $this->request->getRawBody();
} else {
$query = $this->request->getBodyParam('query');
$operationName = $this->request->getBodyParam('operationName');
$variables = $this->request->getBodyParam('variables');
}
}
// query/variables/operationName GET params supersede BODY params
if (($qQuery = $this->request->getQueryParam('query')) !== null) {
$query = $qQuery;
}
if (($qVariables = $this->request->getQueryParam('variables')) !== null) {
// Must be valid JSON
try {
$variables = Json::decode($qVariables);
} catch (InvalidArgumentException $e) {
throw new BadRequestHttpException('The variables param must be valid JSON', 0, $e);
}
}
if (($qOperationName = $this->request->getQueryParam('operationName')) !== null) {
$operationName = $qOperationName;
}
$queries = [];
if ($singleQuery = ($query !== null)) {
$queries[] = [$query, $variables, $operationName];
} else {
if ($this->request->getIsJson()) {
// Check if there are any queries defined in the JSON body
foreach ($this->request->getBodyParams() as $key => $param) {
$queries[$key] = [$param['query'] ?? null, $param['variables'] ?? null, $param['operationName'] ?? null];
}
}
if (empty($queries)) {
$singleQuery = true;
$queries[] = [null, null, null];
}
}
if ($generalConfig->maxGraphqlBatchSize && count($queries) > $generalConfig->maxGraphqlBatchSize) {
throw new BadRequestHttpException(sprintf(
'No more than %s GraphQL %s can be executed in a single batch.',
$generalConfig->maxGraphqlBatchSize,
$generalConfig->maxGraphqlBatchSize === 1 ? 'query' : 'queries'
));
}
// Generate all transforms immediately
$generalConfig->generateTransformsBeforePageLoad = true;
// Check for the cache-bust header
$noCache = $this->request->getHeaders()->get('x-craft-gql-cache', null, true) === 'no-cache';
if ($noCache) {
$cacheSetting = $generalConfig->enableGraphqlCaching;
$generalConfig->enableGraphqlCaching = false;
}
$result = [];
foreach ($queries as $key => [$query, $variables, $operationName]) {
try {
if (empty($query)) {
throw new InvalidValueException('No GraphQL query was supplied');
}
$result[$key] = $gqlService->executeQuery($schema, $query, $variables, $operationName, App::devMode());
} catch (InvalidValueException $e) {
$result[$key] = [
'errors' => [
[
'message' => $e->getMessage(),
],
],
];
} catch (Throwable $e) {
/** @var ErrorHandler $errorHandler */
$errorHandler = Craft::$app->getErrorHandler();
$errorHandler->logException($e);
$result[$key] = [
'errors' => [
$errorHandler->showExceptionDetails()
? $errorHandler->exceptionAsArray($e)
: ['message' => Craft::t('app', 'Something went wrong when processing the GraphQL query.')],
],
];
}
}
if ($noCache) {
$generalConfig->enableGraphqlCaching = $cacheSetting;
}
return $this->asJson($singleQuery ? reset($result) : $result);
}
/**
* Returns the requested GraphQL schema
*
* @param GqlService $gqlService
* @return GqlSchema
* @throws ForbiddenHttpException
* @throws BadRequestHttpException
*/
private function _schema(GqlService $gqlService): GqlSchema
{
$requestHeaders = $this->request->getHeaders();
// Admins can access schemas directly with a X-Craft-Gql-Schema header
if ($requestHeaders->has('x-craft-gql-schema')) {
$this->requireAdmin(false);
$schemaUid = $requestHeaders->get('x-craft-gql-schema');
if ($schemaUid === '*') {
return GqlHelper::createFullAccessSchema();
}
$schema = $gqlService->getSchemaByUid($schemaUid);
if (!$schema) {
throw new BadRequestHttpException('Invalid X-Craft-Gql-Schema header');
}
return $schema;
}
$token = $this->_token($gqlService);
// If we couldn't find a token, then return the active schema if there is one, otherwise bail
if (!$token) {
try {
return $gqlService->getActiveSchema();
} catch (GqlException) {
throw new BadRequestHttpException('Missing Authorization header');
}
}
// Update the lastUsed timestamp
$token->lastUsed = DateTimeHelper::currentUTCDateTime();
$gqlService->saveToken($token);
return $token->getSchema();
}
private function _token(GqlService $gqlService): ?GqlToken
{
$bearerToken = $this->request->getBearerToken();
if ($bearerToken) {
try {
$token = $gqlService->getTokenByAccessToken($bearerToken);
if (!$token->getIsValid()) {
throw new BadRequestHttpException('Invalid Authorization header');
}
return $token;
} catch (InvalidArgumentException) {
}
}
// Get the public schema, if it exists & is valid
return $this->_publicToken($gqlService);
}
/**
* Returns the public token, if it exists and is valid.
*
* @param GqlService $gqlService
* @return GqlToken|null
*/
private function _publicToken(GqlService $gqlService): ?GqlToken
{
try {
$token = $gqlService->getPublicToken();
} catch (Throwable $e) {
Craft::warning('Could not obtain the public token: ' . $e->getMessage());
Craft::$app->getErrorHandler()->logException($e);
return null;
}
return $token->getIsValid() ? $token : null;
}
/**
* Enforce site access based on used schema.
*
* @param GqlSchema $schema
* @return void
* @throws ForbiddenHttpException
* @throws \craft\errors\SiteNotFoundException
*/
private function _enforceSiteAccess(GqlSchema $schema): void
{
$sitesService = Craft::$app->getSites();
$allowedSites = GqlHelper::getAllowedSites($schema);
$allowedSiteIds = array_flip(array_map(fn(Site $site) => $site->id, $allowedSites));
// check if schema has access to the current site
$currentSite = $sitesService->getCurrentSite();
if (isset($allowedSiteIds[$currentSite->id])) {
return;
}
// if not, check if it has access to the primary site (if different from the current site)
$primarySite = $sitesService->getPrimarySite();
if ($currentSite->id !== $primarySite->id && isset($allowedSiteIds[$primarySite->id])) {
$sitesService->setCurrentSite($primarySite);
return;
}
// otherwise, loop through all sites until we find one that the token has access to
foreach ($sitesService->getAllSites() as $site) {
if (isset($allowedSiteIds[$site->id])) {
$sitesService->setCurrentSite($site);
return;
}
}
// no allowed sites could be found, so throw a ForbiddenHttpException
throw new ForbiddenHttpException(sprintf('Schema doesn’t have access to the “%s” site.', $currentSite->getName()));
}
/**
* @return Response
* @throws ForbiddenHttpException
* @throws InvalidConfigException
* @throws BadRequestHttpException
*/
public function actionGraphiql(): Response
{
$this->requireAdmin(false);
$this->getView()->registerAssetBundle(GraphiqlAsset::class);
$schemaUid = $this->request->getQueryParam('schemaUid');
$gqlService = Craft::$app->getGql();
// Ensure the public schema is created.
Craft::$app->getGql()->getPublicSchema();
if ($schemaUid && $schemaUid !== '*') {
try {
$selectedSchema = $gqlService->getSchemaByUid($schemaUid);
} catch (InvalidArgumentException) {
throw new BadRequestHttpException('Invalid token UID.');
}
Craft::$app->getSession()->authorize("graphql-schema:$schemaUid");
} else {
$selectedSchema = GqlHelper::createFullAccessSchema();
}
$schemas = [
Craft::t('app', 'Full Schema') => '*',
];
foreach ($gqlService->getSchemas() as $schema) {
$name = $schema->name;
$schemas[$name] = $schema->uid;
}
return $this->renderTemplate('graphql/graphiql.twig', [
'url' => UrlHelper::actionUrl('graphql/api'),
'schemas' => $schemas,
'selectedSchema' => $selectedSchema,
]);
}
/**
* Redirects to the GraphQL Schemas/Tokens page in the control panel.
*
* @return Response
* @throws NotFoundHttpException if this isn't a control panel request
* @throws ForbiddenHttpException if the logged-in user isn't an admin
* @since 3.5.0
*/
public function actionCpIndex(): Response
{
$generalConfig = Craft::$app->getConfig()->getGeneral();
if (!$this->request->getIsCpRequest() || !$generalConfig->enableGql) {
throw new NotFoundHttpException();
}
$this->requireAdmin(false);
if ($generalConfig->allowAdminChanges) {
return $this->redirect('graphql/schemas');
}
return $this->redirect('graphql/tokens');
}
/**
* @return Response
* @throws ForbiddenHttpException
* @since 3.4.0
*/
public function actionViewSchemas(): Response
{
$this->requireAdmin();
// Ensure the public schema is created.
Craft::$app->getGql()->getPublicSchema();
return $this->renderTemplate('graphql/schemas/_index.twig');
}
/**
* @param int|null $tokenId
* @param GqlToken|null $token
* @return Response
* @throws ForbiddenHttpException
* @throws NotFoundHttpException
* @since 3.4.0
*/
public function actionEditToken(?int $tokenId = null, ?GqlToken $token = null): Response
{
$this->requireAdmin(false);
$gqlService = Craft::$app->getGql();
$accessToken = null;
if ($token || $tokenId) {
if (!$token) {
$token = $gqlService->getTokenById($tokenId);
}
if (!$token || $token->getIsPublic()) {
throw new NotFoundHttpException('Token not found');
}
$title = trim($token->name) ?: Craft::t('app', 'Edit GraphQL Token');
} else {
$token = new GqlToken();
$accessToken = $this->_generateToken();
$title = trim($token->name) ?: Craft::t('app', 'Create a new GraphQL token');
}
$schemas = $gqlService->getSchemas();
$schemaOptions = [];
$publicSchema = $gqlService->getPublicSchema();
foreach ($schemas as $schema) {
if (!$publicSchema || $schema->id !== $publicSchema->id) {
$schemaOptions[] = [
'label' => $schema->name,
'value' => $schema->id,
];
}
}
if ($token->id && !$token->schemaId && !empty($schemaOptions)) {
// Add a blank option to the top so it's clear no schema is currently selected
array_unshift($schemaOptions, [
'label' => '',
'value' => '',
]);
}
return $this->renderTemplate('graphql/tokens/_edit.twig', compact(
'token',
'title',
'accessToken',
'schemaOptions'
));
}
/**
* @return Response|null
* @throws BadRequestHttpException
* @throws ForbiddenHttpException
* @throws NotFoundHttpException
* @throws MissingComponentException
* @throws Exception
* @since 3.4.0
*/
public function actionSaveToken(): ?Response
{
$this->requirePostRequest();
$this->requireAdmin(false);
$this->requireElevatedSession();
$gqlService = Craft::$app->getGql();
$tokenId = $this->request->getBodyParam('tokenId');
if ($tokenId) {
$token = $gqlService->getTokenById($tokenId);
if (!$token) {
throw new NotFoundHttpException('Token not found');
}
} else {
$token = new GqlToken();
}
$token->name = $this->request->getBodyParam('name') ?? $token->name;
$token->accessToken = $this->request->getBodyParam('accessToken') ?? $token->accessToken;
$token->enabled = (bool)$this->request->getRequiredBodyParam('enabled');
$token->schemaId = $this->request->getBodyParam('schema');
if (($expiryDate = $this->request->getBodyParam('expiryDate')) !== null) {
$token->expiryDate = DateTimeHelper::toDateTime($expiryDate) ?: null;
}
if (!$gqlService->saveToken($token)) {
return $this->asFailure(
Craft::t('app', 'Couldn’t save token.'),
routeParams: [
'token' => $token,
]
);
}
return $this->asSuccess(Craft::t('app', 'Schema saved.'));
}
/**
* @return Response
* @throws BadRequestHttpException
* @since 3.4.0
*/
public function actionDeleteToken(): Response
{
$this->requirePostRequest();
$this->requireAcceptsJson();
$this->requireAdmin(false);
$schemaId = $this->request->getRequiredBodyParam('id');
Craft::$app->getGql()->deleteTokenById($schemaId);
return $this->asSuccess();
}
/**
* @return Response
* @throws ForbiddenHttpException
* @since 3.4.0
*/
public function actionViewTokens(): Response
{
$this->requireAdmin(false);
return $this->renderTemplate('graphql/tokens/_index.twig');
}
/**
* @param int|null $schemaId
* @param GqlSchema|null $schema
* @return Response
* @throws ForbiddenHttpException
* @throws NotFoundHttpException
* @since 3.4.0
*/
public function actionEditSchema(?int $schemaId = null, ?GqlSchema $schema = null): Response
{
$this->requireAdmin();
$gqlService = Craft::$app->getGql();
if ($schema || $schemaId) {
if (!$schema) {
$schema = $gqlService->getSchemaById($schemaId);
}
if (!$schema) {
throw new NotFoundHttpException('Schema not found');
}
$title = trim($schema->name) ?: Craft::t('app', 'Edit GraphQL Schema');
} else {
$schema = new GqlSchema();
$title = trim($schema->name) ?: Craft::t('app', 'Create a new GraphQL Schema');
}
return $this->renderTemplate('graphql/schemas/_edit.twig', compact(
'schema',
'title'
));
}
/**
* @param GqlSchema|null $schema
* @return Response
* @throws ForbiddenHttpException
* @throws NotFoundHttpException
* @since 3.4.0
*/
public function actionEditPublicSchema(?GqlSchema $schema = null): Response
{
$this->requireAdmin();
$gqlService = Craft::$app->getGql();
if (!$schema) {
$schema = $gqlService->getPublicSchema();
}
$token = $gqlService->getPublicToken();
$title = Craft::t('app', 'Edit the public GraphQL schema');
return $this->renderTemplate('graphql/schemas/_edit.twig', compact(
'schema',
'token',
'title'
));
}
/**
* @return Response|null
* @throws ForbiddenHttpException
* @throws NotFoundHttpException
* @since 3.4.0
*/
public function actionSavePublicSchema(): ?Response
{
$this->requirePostRequest();
$this->requireAdmin();
$this->requireElevatedSession();
$gqlService = Craft::$app->getGql();
$schema = $gqlService->getPublicSchema();
$schema->scope = $this->request->getBodyParam('permissions') ?? [];
if (!$gqlService->saveSchema($schema)) {
$this->setFailFlash(Craft::t('app', 'Couldn’t save schema.'));
// Send the schema back to the template
Craft::$app->getUrlManager()->setRouteParams([
'schema' => $schema,
]);
return null;
}
$token = $gqlService->getPublicToken();
$token->enabled = (bool)$this->request->getRequiredBodyParam('enabled');
if (($expiryDate = $this->request->getBodyParam('expiryDate')) !== null) {
$token->expiryDate = DateTimeHelper::toDateTime($expiryDate) ?: null;
}
if (!$gqlService->saveToken($token)) {
$this->setFailFlash(Craft::t('app', 'Couldn’t save public schema settings.'));
return null;
}
$this->setSuccessFlash(Craft::t('app', 'Schema saved.'));
return $this->redirectToPostedUrl();
}
/**
* @return Response|null
* @throws BadRequestHttpException
* @throws ForbiddenHttpException
* @throws NotFoundHttpException
* @throws MissingComponentException
* @throws Exception
* @since 3.4.0
*/
public function actionSaveSchema(): ?Response
{
$this->requirePostRequest();
$this->requireAdmin();
$this->requireElevatedSession();
$gqlService = Craft::$app->getGql();
$schemaId = $this->request->getBodyParam('schemaId');
if ($schemaId) {
$schema = $gqlService->getSchemaById($schemaId);
if (!$schema) {
throw new NotFoundHttpException('Schema not found');
}
} else {
$schema = new GqlSchema();
}
$schema->name = $this->request->getBodyParam('name') ?? $schema->name;
$schema->scope = $this->request->getBodyParam('permissions') ?? [];
if (!$gqlService->saveSchema($schema)) {
$this->setFailFlash(Craft::t('app', 'Couldn’t save schema.'));
// Send the schema back to the template
Craft::$app->getUrlManager()->setRouteParams([
'schema' => $schema,
]);
return null;
}
$this->setSuccessFlash(Craft::t('app', 'Schema saved.'));
return $this->redirectToPostedUrl();
}
/**
* @return Response
* @throws BadRequestHttpException
* @since 3.4.0
*/
public function actionDeleteSchema(): Response
{
$this->requirePostRequest();
$this->requireAcceptsJson();
$this->requireAdmin();
$schemaId = $this->request->getRequiredBodyParam('id');
Craft::$app->getGql()->deleteSchemaById($schemaId);
return $this->asSuccess();
}
/**
* @return Response
* @throws BadRequestHttpException
*/
public function actionFetchToken(): Response
{
$this->requirePostRequest();
$this->requireAcceptsJson();
$this->requireAdmin(false);
$this->requireElevatedSession();
$tokenUid = $this->request->getRequiredBodyParam('tokenUid');
try {
$schema = Craft::$app->getGql()->getTokenByUid($tokenUid);
} catch (InvalidArgumentException) {
throw new BadRequestHttpException('Invalid schema UID.');
}
return $this->asJson([
'accessToken' => $schema->accessToken,
]);
}
/**
* @return Response
*/
public function actionGenerateToken(): Response
{
$this->requirePostRequest();
$this->requireAcceptsJson();
$this->requireAdmin(false);
return $this->asJson([
'accessToken' => $this->_generateToken(),
]);
}
/**
* @return string
*/
private function _generateToken(): string
{
return Craft::$app->getSecurity()->generateRandomString(32);
}
}