-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathController.php
411 lines (361 loc) · 13.6 KB
/
Controller.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
<?php
namespace SilverStripe\GraphQL;
use Exception;
use GraphQL\Language\Parser;
use GraphQL\Language\Source;
use InvalidArgumentException;
use LogicException;
use SilverStripe\Control\Controller as BaseController;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\EventDispatcher\Dispatch\Dispatcher;
use SilverStripe\EventDispatcher\Symfony\Event;
use SilverStripe\GraphQL\Auth\Handler;
use SilverStripe\GraphQL\PersistedQuery\RequestProcessor;
use SilverStripe\GraphQL\QueryHandler\QueryHandler;
use SilverStripe\GraphQL\QueryHandler\QueryHandlerInterface;
use SilverStripe\GraphQL\QueryHandler\QueryStateProvider;
use SilverStripe\GraphQL\Schema\Exception\SchemaBuilderException;
use SilverStripe\GraphQL\QueryHandler\RequestContextProvider;
use SilverStripe\GraphQL\QueryHandler\SchemaConfigProvider;
use SilverStripe\GraphQL\QueryHandler\TokenContextProvider;
use SilverStripe\GraphQL\QueryHandler\UserContextProvider;
use SilverStripe\GraphQL\Schema\SchemaBuilder;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Versioned\Versioned;
use BadMethodCallException;
use SilverStripe\Dev\Backtrace;
/**
* Top level controller for handling graphql requests.
*/
class Controller extends BaseController
{
/**
* Cors default config
*
* @config
*/
private static array $cors = [
'Enabled' => false, // Off by default
'Allow-Origin' => [], // List of all allowed origins; Deny by default
'Allow-Headers' => 'Authorization, Content-Type',
'Allow-Methods' => 'GET, POST, OPTIONS',
'Allow-Credentials' => '',
'Max-Age' => 86400, // 86,400 seconds = 1 day.
];
private string $schemaKey;
private QueryHandlerInterface $queryHandler;
/**
* Override the default cors config per instance
*/
protected array $corsConfig = [];
protected bool $autobuildSchema = true;
public function __construct(
?string $schemaKey = null,
?QueryHandlerInterface $queryHandler = null
) {
parent::__construct();
$this->setSchemaKey($schemaKey);
$handler = $queryHandler ?: Injector::inst()->create(QueryHandlerInterface::class);
$this->setQueryHandler($handler);
}
/**
* Handles requests to the index action (e.g. /graphql)
*
* @throws InvalidArgumentException
*/
public function index(HTTPRequest $request): HTTPResponse
{
if (!$this->schemaKey) {
throw new BadMethodCallException('Cannot query the controller without a schema key defined');
}
if (class_exists(Versioned::class) && $stage = $request->param('Stage')) {
Versioned::set_stage($stage);
}
// Check for a possible CORS preflight request and handle if necessary
if ($request->httpMethod() === 'OPTIONS') {
return $this->handleOptions($request);
}
// Main query handling
try {
list($query, $variables) = $this->getRequestQueryVariables($request);
if (!$query) {
$this->httpError(400, 'This endpoint requires a "query" parameter');
}
$builder = SchemaBuilder::singleton();
$graphqlSchema = $builder->getSchema($this->getSchemaKey());
if (!$graphqlSchema && $this->autobuildEnabled()) {
// clear the cache on autobuilds until we trust it more. Maybe
// make this configurable.
$clear = true;
$graphqlSchema = $builder->buildByName($this->getSchemaKey(), $clear);
} elseif (!$graphqlSchema) {
throw new SchemaBuilderException(sprintf(
'Schema %s has not been built.',
$this->getSchemaKey()
));
}
$handler = $this->getQueryHandler();
$this->applyContext($handler);
$queryDocument = Parser::parse(new Source($query));
$ctx = $handler->getContext();
$result = $handler->query($graphqlSchema, $query, $variables);
// Fire an eventYou
$eventContext = [
'schema' => $graphqlSchema,
'schemaKey' => $this->getSchemaKey(),
'query' => $query,
'context' => $ctx,
'variables' => $variables,
'result' => $result,
];
$event = QueryHandler::isMutation($query) ? 'graphqlMutation' : 'graphqlQuery';
$operationName = QueryHandler::getOperationName($queryDocument);
Dispatcher::singleton()->trigger($event, Event::create($operationName, $eventContext));
} catch (Exception $exception) {
$error = ['message' => $exception->getMessage()];
if (Director::isDev()) {
$error['code'] = $exception->getCode();
$error['file'] = $exception->getFile();
$error['line'] = $exception->getLine();
$error['trace'] = $this->prepareBacktrace($exception->getTrace());
}
$result = [
'errors' => [$error]
];
}
$response = $this->addCorsHeaders($request, new HTTPResponse(json_encode($result)));
return $response->addHeader('Content-Type', 'application/json');
}
private function prepareBacktrace(array $trace): array
{
$argCharLimit = 10000;
$trace = Backtrace::filter_backtrace($trace);
foreach ($trace as &$item) {
// This mimics how Backtrace::full_func_name() treats arguments
if (isset($item['args'])) {
$args = [];
foreach ($item['args'] as $arg) {
if (!is_object($arg) || method_exists($arg, '__toString')) {
$sarg = is_array($arg) ? 'Array' : strval($arg);
$args[] = (strlen($sarg ?? '') > $argCharLimit) ? substr($sarg, 0, $argCharLimit) . '...' : $sarg;
} else {
$args[] = get_class($arg);
}
}
$item['args'] = $args;
}
}
return $trace;
}
public function autobuildEnabled(): bool
{
return $this->autobuildSchema;
}
public function setAutobuildSchema(bool $autobuildSchema): Controller
{
$this->autobuildSchema = $autobuildSchema;
return $this;
}
/**
* Get an instance of the authorization Handler to manage any authentication requirements
*/
public function getAuthHandler(): Handler
{
return new Handler;
}
public function getToken(): ?string
{
return $this->getRequest()->getHeader('X-CSRF-TOKEN');
}
/**
* Process the CORS config options and add the appropriate headers to the response.
*/
public function addCorsHeaders(HTTPRequest $request, HTTPResponse $response): HTTPResponse
{
$corsConfig = $this->getMergedCorsConfig();
// If CORS is disabled don't add the extra headers. Simply return the response untouched.
if (empty($corsConfig['Enabled'])) {
return $response;
}
// Calculate origin
$origin = $this->getRequestOrigin($request);
// Check if valid
$allowedOrigins = (array)$corsConfig['Allow-Origin'];
$originAuthorised = $this->validateOrigin($origin, $allowedOrigins);
if (!$originAuthorised) {
$this->httpError(403, "Access Forbidden");
}
$response->addHeader('Access-Control-Allow-Origin', $origin);
$response->addHeader('Access-Control-Allow-Headers', $corsConfig['Allow-Headers']);
$response->addHeader('Access-Control-Allow-Methods', $corsConfig['Allow-Methods']);
$response->addHeader('Access-Control-Max-Age', $corsConfig['Max-Age']);
if (isset($corsConfig['Allow-Credentials'])) {
$response->addHeader('Access-Control-Allow-Credentials', $corsConfig['Allow-Credentials']);
}
return $response;
}
public function getCorsConfig(): array
{
return $this->corsConfig;
}
public function getMergedCorsConfig(): array
{
$defaults = Config::inst()->get(static::class, 'cors');
$override = $this->corsConfig;
return array_merge($defaults, $override);
}
public function setCorsConfig(array $config): self
{
$this->corsConfig = array_merge($this->corsConfig, $config);
return $this;
}
/**
* Validate an origin matches a set of allowed origins
*/
protected function validateOrigin(?string $origin, array $allowedOrigins): bool
{
if (empty($allowedOrigins) || empty($origin)) {
return false;
}
foreach ($allowedOrigins as $allowedOrigin) {
if ($allowedOrigin === '*') {
return true;
}
if (strcasecmp($allowedOrigin ?? '', $origin ?? '') === 0) {
return true;
}
}
return false;
}
/**
* @throws Exception
*/
protected function applyContext(QueryHandlerInterface $handler): void
{
$request = $this->getRequest();
$user = $this->getRequestUser($request);
$token = $this->getToken();
$handler->addContextProvider(UserContextProvider::create($user))
->addContextProvider(TokenContextProvider::create($token ?: ''))
->addContextProvider(RequestContextProvider::create($request));
$schemaContext = SchemaBuilder::singleton()->getConfig($this->getSchemaKey());
if ($schemaContext) {
$handler->addContextProvider(SchemaConfigProvider::create($schemaContext));
}
$handler->addContextProvider(QueryStateProvider::create());
}
/**
* Get (or infer) value of Origin header
*/
protected function getRequestOrigin(HTTPRequest $request): ?string
{
// Prefer Origin header
$origin = $request->getHeader('Origin');
if ($origin) {
return $origin;
}
// Check referer
$referer = $request->getHeader('Referer');
if ($referer) {
// Extract protocol, hostname, and port
$refererParts = parse_url($referer ?? '');
if (!$refererParts) {
return null;
}
// Rebuild
$origin = $refererParts['scheme'] . '://' . $refererParts['host'];
if (isset($refererParts['port'])) {
$origin .= ':' . $refererParts['port'];
}
return $origin;
}
return null;
}
/**
* Response for HTTP OPTIONS request
*/
protected function handleOptions(HTTPRequest $request): HTTPResponse
{
$response = HTTPResponse::create();
$corsConfig = Config::inst()->get(self::class, 'cors');
if ($corsConfig['Enabled']) {
// CORS config is enabled and the request is an OPTIONS pre-flight.
// Process the CORS config and add appropriate headers.
$this->addCorsHeaders($request, $response);
} else {
// CORS is disabled but we have received an OPTIONS request. This is not a valid request method in this
// situation. Return a 405 Method Not Allowed response.
$this->httpError(405, "Method Not Allowed");
}
return $response;
}
/**
* Parse query and variables from the given request
*
* @throws LogicException
*/
protected function getRequestQueryVariables(HTTPRequest $request): array
{
$contentType = $request->getHeader('content-type');
$isJson = preg_match('#^application/json\b#', $contentType ?? '');
if ($isJson) {
$rawBody = $request->getBody();
$data = json_decode($rawBody ?: '', true);
$query = isset($data['query']) ? $data['query'] : null;
$variables = isset($data['variables']) ? (array)$data['variables'] : null;
} else {
/** @var RequestProcessor $persistedProcessor */
$persistedProcessor = Injector::inst()->get(RequestProcessor::class);
list($query, $variables) = $persistedProcessor->getRequestQueryVariables($request);
}
return [$query, $variables];
}
/**
* Get user and validate for this request
*
* @throws Exception
*/
protected function getRequestUser(HTTPRequest $request): ?Member
{
// Check authentication
$member = $this->getAuthHandler()->requireAuthentication($request) ?: null;
// Check authorisation
$permissions = $request->param('Permissions');
if (!$permissions) {
return $member;
}
// If permissions requested require authentication
if (!$member) {
throw new Exception("Authentication required");
}
// Check authorisation for this member
$allowed = Permission::checkMember($member, $permissions);
if (!$allowed) {
throw new Exception("Not authorised");
}
return $member;
}
public function setSchemaKey(string $schemaKey): self
{
$this->schemaKey = $schemaKey;
return $this;
}
public function getSchemaKey(): ?string
{
return $this->schemaKey;
}
public function getQueryHandler(): QueryHandlerInterface
{
return $this->queryHandler;
}
public function setQueryHandler(QueryHandlerInterface $queryHandler): self
{
$this->queryHandler = $queryHandler;
return $this;
}
}