Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / rest / src / Tests / RESTTestBase.php
1 <?php
2
3 namespace Drupal\rest\Tests;
4
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Config\Entity\ConfigEntityType;
7 use Drupal\node\NodeInterface;
8 use Drupal\rest\RestResourceConfigInterface;
9 use Drupal\simpletest\WebTestBase;
10 use GuzzleHttp\Cookie\FileCookieJar;
11 use GuzzleHttp\Cookie\SetCookie;
12
13 /**
14  * Test helper class that provides a REST client method to send HTTP requests.
15  *
16  * @deprecated in Drupal 8.3.x-dev and will be removed before Drupal 9.0.0. Use \Drupal\Tests\rest\Functional\ResourceTestBase and \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase instead. Only retained for contributed module tests that may be using this base class.
17  */
18 abstract class RESTTestBase extends WebTestBase {
19
20   /**
21    * The REST resource config storage.
22    *
23    * @var \Drupal\Core\Entity\EntityStorageInterface
24    */
25   protected $resourceConfigStorage;
26
27   /**
28    * The default serialization format to use for testing REST operations.
29    *
30    * @var string
31    */
32   protected $defaultFormat;
33
34   /**
35    * The default MIME type to use for testing REST operations.
36    *
37    * @var string
38    */
39   protected $defaultMimeType;
40
41   /**
42    * The entity type to use for testing.
43    *
44    * @var string
45    */
46   protected $testEntityType = 'entity_test';
47
48   /**
49    * The default authentication provider to use for testing REST operations.
50    *
51    * @var array
52    */
53   protected $defaultAuth;
54
55
56   /**
57    * The raw response body from http request operations.
58    *
59    * @var array
60    */
61   protected $responseBody;
62
63   /**
64    * Modules to install.
65    *
66    * @var array
67    */
68   public static $modules = ['rest', 'entity_test'];
69
70   /**
71    * The last response.
72    *
73    * @var \Psr\Http\Message\ResponseInterface
74    */
75   protected $response;
76
77   protected function setUp() {
78     parent::setUp();
79     $this->defaultFormat = 'hal_json';
80     $this->defaultMimeType = 'application/hal+json';
81     $this->defaultAuth = ['cookie'];
82     $this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
83     // Create a test content type for node testing.
84     if (in_array('node', static::$modules)) {
85       $this->drupalCreateContentType(['name' => 'resttest', 'type' => 'resttest']);
86     }
87
88     $this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
89   }
90
91   /**
92    * Calculates cookies used by guzzle later.
93    *
94    * @return \GuzzleHttp\Cookie\CookieJarInterface
95    *   The used CURL options in guzzle.
96    */
97   protected function cookies() {
98     $cookies = [];
99
100     foreach ($this->cookies as $key => $cookie) {
101       $cookies[$key][] = $cookie['value'];
102     }
103
104     $request = \Drupal::request();
105     $cookies = NestedArray::mergeDeep($cookies, $this->extractCookiesFromRequest($request));
106
107     $cookie_jar = new FileCookieJar($this->cookieFile);
108     foreach ($cookies as $key => $cookie_values) {
109       foreach ($cookie_values as $cookie_value) {
110         // setcookie() sets the value of a cookie to be deleted, when its gonna
111         // be removed.
112         if ($cookie_value !== 'deleted') {
113           $cookie_jar->setCookie(new SetCookie(['Name' => $key, 'Value' => $cookie_value, 'Domain' => $request->getHost()]));
114         }
115       }
116     }
117
118     return $cookie_jar;
119   }
120
121   /**
122    * Helper function to issue a HTTP request with simpletest's cURL.
123    *
124    * @param string|\Drupal\Core\Url $url
125    *   A Url object or system path.
126    * @param string $method
127    *   HTTP method, one of GET, POST, PUT or DELETE.
128    * @param string $body
129    *   The body for POST and PUT.
130    * @param string $mime_type
131    *   The MIME type of the transmitted content.
132    * @param bool $csrf_token
133    *   If NULL, a CSRF token will be retrieved and used. If FALSE, omit the
134    *   X-CSRF-Token request header (to simulate developer error). Otherwise, the
135    *   passed in value will be used as the value for the X-CSRF-Token request
136    *   header (to simulate developer error, by sending an invalid CSRF token).
137    *
138    * @return string
139    *   The content returned from the request.
140    */
141   protected function httpRequest($url, $method, $body = NULL, $mime_type = NULL, $csrf_token = NULL) {
142     if (!isset($mime_type)) {
143       $mime_type = $this->defaultMimeType;
144     }
145     if (!in_array($method, ['GET', 'HEAD', 'OPTIONS', 'TRACE'])) {
146       // GET the CSRF token first for writing requests.
147       $requested_token = $this->drupalGet('session/token');
148     }
149
150     $client = \Drupal::httpClient();
151     $url = $this->buildUrl($url);
152
153     $options = [
154       'http_errors' => FALSE,
155       'cookies' => $this->cookies(),
156       'curl' => [
157         CURLOPT_HEADERFUNCTION => [&$this, 'curlHeaderCallback'],
158       ],
159     ];
160     switch ($method) {
161       case 'GET':
162         $options += [
163           'headers' => [
164             'Accept' => $mime_type,
165           ],
166         ];
167         $response = $client->get($url, $options);
168         break;
169
170       case 'HEAD':
171         $response = $client->head($url, $options);
172         break;
173
174       case 'POST':
175         $options += [
176           'headers' => $csrf_token !== FALSE ? [
177             'Content-Type' => $mime_type,
178             'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
179           ] : [
180             'Content-Type' => $mime_type,
181           ],
182           'body' => $body,
183         ];
184         $response = $client->post($url, $options);
185         break;
186
187       case 'PUT':
188         $options += [
189           'headers' => $csrf_token !== FALSE ? [
190             'Content-Type' => $mime_type,
191             'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
192           ] : [
193             'Content-Type' => $mime_type,
194           ],
195           'body' => $body,
196         ];
197         $response = $client->put($url, $options);
198         break;
199
200       case 'PATCH':
201         $options += [
202           'headers' => $csrf_token !== FALSE ? [
203             'Content-Type' => $mime_type,
204             'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
205           ] : [
206             'Content-Type' => $mime_type,
207           ],
208           'body' => $body,
209         ];
210         $response = $client->patch($url, $options);
211         break;
212
213       case 'DELETE':
214         $options += [
215           'headers' => $csrf_token !== FALSE ? [
216             'Content-Type' => $mime_type,
217             'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
218           ] : [],
219         ];
220         $response = $client->delete($url, $options);
221         break;
222     }
223
224     $this->response = $response;
225     $this->responseBody = (string) $response->getBody();
226     $this->setRawContent($this->responseBody);
227
228     // Ensure that any changes to variables in the other thread are picked up.
229     $this->refreshVariables();
230
231     $this->verbose($method . ' request to: ' . $url .
232       '<hr />Code: ' . $this->response->getStatusCode() .
233       (isset($options['headers']) ? '<hr />Request headers: ' . nl2br(print_r($options['headers'], TRUE)) : '') .
234       (isset($options['body']) ? '<hr />Request body: ' . nl2br(print_r($options['body'], TRUE)) : '') .
235       '<hr />Response headers: ' . nl2br(print_r($response->getHeaders(), TRUE)) .
236       '<hr />Response body: ' . $this->responseBody);
237
238     return $this->responseBody;
239   }
240
241   /**
242    * {@inheritdoc}
243    */
244   protected function assertResponse($code, $message = '', $group = 'Browser') {
245     if (!isset($this->response)) {
246       return parent::assertResponse($code, $message, $group);
247     }
248     return $this->assertEqual($code, $this->response->getStatusCode(), $message ? $message : "HTTP response expected $code, actual {$this->response->getStatusCode()}", $group);
249   }
250
251   /**
252    * {@inheritdoc}
253    */
254   protected function drupalGetHeaders($all_requests = FALSE) {
255     if (!isset($this->response)) {
256       return parent::drupalGetHeaders($all_requests);
257     }
258     $lowercased_keys = array_map('strtolower', array_keys($this->response->getHeaders()));
259     return array_map(function (array $header) {
260       return implode(', ', $header);
261     }, array_combine($lowercased_keys, array_values($this->response->getHeaders())));
262   }
263
264   /**
265    * {@inheritdoc}
266    */
267   protected function drupalGetHeader($name, $all_requests = FALSE) {
268     if (!isset($this->response)) {
269       return parent::drupalGetHeader($name, $all_requests);
270     }
271     if ($header = $this->response->getHeader($name)) {
272       return implode(', ', $header);
273     }
274   }
275
276   /**
277    * Creates entity objects based on their types.
278    *
279    * @param string $entity_type
280    *   The type of the entity that should be created.
281    *
282    * @return \Drupal\Core\Entity\EntityInterface
283    *   The new entity object.
284    */
285   protected function entityCreate($entity_type) {
286     return $this->container->get('entity_type.manager')
287       ->getStorage($entity_type)
288       ->create($this->entityValues($entity_type));
289   }
290
291   /**
292    * Provides an array of suitable property values for an entity type.
293    *
294    * Required properties differ from entity type to entity type, so we keep a
295    * minimum mapping here.
296    *
297    * @param string $entity_type_id
298    *   The ID of the type of entity that should be created.
299    *
300    * @return array
301    *   An array of values keyed by property name.
302    */
303   protected function entityValues($entity_type_id) {
304     switch ($entity_type_id) {
305       case 'entity_test':
306         return [
307           'name' => $this->randomMachineName(),
308           'user_id' => 1,
309           'field_test_text' => [0 => [
310             'value' => $this->randomString(),
311             'format' => 'plain_text',
312           ]],
313         ];
314       case 'config_test':
315         return [
316           'id' => $this->randomMachineName(),
317           'label' => 'Test label',
318         ];
319       case 'node':
320         return ['title' => $this->randomString(), 'type' => 'resttest'];
321       case 'node_type':
322         return [
323           'type' => 'article',
324           'name' => $this->randomMachineName(),
325         ];
326       case 'user':
327         return ['name' => $this->randomMachineName()];
328
329       case 'comment':
330         return [
331           'subject' => $this->randomMachineName(),
332           'entity_type' => 'node',
333           'comment_type' => 'comment',
334           'comment_body' => $this->randomString(),
335           'entity_id' => 'invalid',
336           'field_name' => 'comment',
337         ];
338       case 'taxonomy_vocabulary':
339         return [
340           'vid' => 'tags',
341           'name' => $this->randomMachineName(),
342         ];
343       case 'block':
344         // Block placements depend on themes, ensure Bartik is installed.
345         $this->container->get('theme_installer')->install(['bartik']);
346         return [
347           'id' => strtolower($this->randomMachineName(8)),
348           'plugin' => 'system_powered_by_block',
349           'theme' => 'bartik',
350           'region' => 'header',
351         ];
352       default:
353         if ($this->isConfigEntity($entity_type_id)) {
354           return $this->configEntityValues($entity_type_id);
355         }
356         return [];
357     }
358   }
359
360   /**
361    * Enables the REST service interface for a specific entity type.
362    *
363    * @param string|false $resource_type
364    *   The resource type that should get REST API enabled or FALSE to disable all
365    *   resource types.
366    * @param string $method
367    *   The HTTP method to enable, e.g. GET, POST etc.
368    * @param string|array $format
369    *   (Optional) The serialization format, e.g. hal_json, or a list of formats.
370    * @param array $auth
371    *   (Optional) The list of valid authentication methods.
372    */
373   protected function enableService($resource_type, $method = 'GET', $format = NULL, array $auth = []) {
374     if ($resource_type) {
375       // Enable REST API for this entity type.
376       $resource_config_id = str_replace(':', '.', $resource_type);
377       // get entity by id
378       /** @var \Drupal\rest\RestResourceConfigInterface $resource_config */
379       $resource_config = $this->resourceConfigStorage->load($resource_config_id);
380       if (!$resource_config) {
381         $resource_config = $this->resourceConfigStorage->create([
382           'id' => $resource_config_id,
383           'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
384           'configuration' => []
385         ]);
386       }
387       $configuration = $resource_config->get('configuration');
388
389       if (is_array($format)) {
390         for ($i = 0; $i < count($format); $i++) {
391           $configuration[$method]['supported_formats'][] = $format[$i];
392         }
393       }
394       else {
395         if ($format == NULL) {
396           $format = $this->defaultFormat;
397         }
398         $configuration[$method]['supported_formats'][] = $format;
399       }
400
401       if (!is_array($auth) || empty($auth)) {
402         $auth = $this->defaultAuth;
403       }
404       foreach ($auth as $auth_provider) {
405         $configuration[$method]['supported_auth'][] = $auth_provider;
406       }
407
408       $resource_config->set('configuration', $configuration);
409       $resource_config->save();
410     }
411     else {
412       foreach ($this->resourceConfigStorage->loadMultiple() as $resource_config) {
413         $resource_config->delete();
414       }
415     }
416     $this->rebuildCache();
417   }
418
419   /**
420    * Rebuilds routing caches.
421    */
422   protected function rebuildCache() {
423     $this->container->get('router.builder')->rebuildIfNeeded();
424   }
425
426   /**
427    * {@inheritdoc}
428    *
429    * This method is overridden to deal with a cURL quirk: the usage of
430    * CURLOPT_CUSTOMREQUEST cannot be unset on the cURL handle, so we need to
431    * override it every time it is omitted.
432    */
433   protected function curlExec($curl_options, $redirect = FALSE) {
434     unset($this->response);
435
436     if (!isset($curl_options[CURLOPT_CUSTOMREQUEST])) {
437       if (!empty($curl_options[CURLOPT_HTTPGET])) {
438         $curl_options[CURLOPT_CUSTOMREQUEST] = 'GET';
439       }
440       if (!empty($curl_options[CURLOPT_POST])) {
441         $curl_options[CURLOPT_CUSTOMREQUEST] = 'POST';
442       }
443     }
444     return parent::curlExec($curl_options, $redirect);
445   }
446
447   /**
448    * Provides the necessary user permissions for entity operations.
449    *
450    * @param string $entity_type_id
451    *   The entity type.
452    * @param string $operation
453    *   The operation, one of 'view', 'create', 'update' or 'delete'.
454    *
455    * @return array
456    *   The set of user permission strings.
457    */
458   protected function entityPermissions($entity_type_id, $operation) {
459     switch ($entity_type_id) {
460       case 'entity_test':
461         switch ($operation) {
462           case 'view':
463             return ['view test entity'];
464           case 'create':
465           case 'update':
466           case 'delete':
467             return ['administer entity_test content'];
468         }
469       case 'node':
470         switch ($operation) {
471           case 'view':
472             return ['access content'];
473           case 'create':
474             return ['create resttest content'];
475           case 'update':
476             return ['edit any resttest content'];
477           case 'delete':
478             return ['delete any resttest content'];
479         }
480
481       case 'comment':
482         switch ($operation) {
483           case 'view':
484             return ['access comments'];
485
486           case 'create':
487             return ['post comments', 'skip comment approval'];
488
489           case 'update':
490             return ['edit own comments'];
491
492           case 'delete':
493             return ['administer comments'];
494         }
495         break;
496
497       case 'user':
498         switch ($operation) {
499           case 'view':
500             return ['access user profiles'];
501
502           default:
503             return ['administer users'];
504         }
505
506       default:
507         if ($this->isConfigEntity($entity_type_id)) {
508           $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
509           if ($admin_permission = $entity_type->getAdminPermission()) {
510             return [$admin_permission];
511           }
512         }
513     }
514     return [];
515   }
516
517   /**
518    * Loads an entity based on the location URL returned in the location header.
519    *
520    * @param string $location_url
521    *   The URL returned in the Location header.
522    *
523    * @return \Drupal\Core\Entity\Entity|false
524    *   The entity or FALSE if there is no matching entity.
525    */
526   protected function loadEntityFromLocationHeader($location_url) {
527     $url_parts = explode('/', $location_url);
528     $id = end($url_parts);
529     return $this->container->get('entity_type.manager')
530       ->getStorage($this->testEntityType)->load($id);
531   }
532
533   /**
534    * Remove node fields that can only be written by an admin user.
535    *
536    * @param \Drupal\node\NodeInterface $node
537    *   The node to remove fields where non-administrative users cannot write.
538    *
539    * @return \Drupal\node\NodeInterface
540    *   The node with removed fields.
541    */
542   protected function removeNodeFieldsForNonAdminUsers(NodeInterface $node) {
543     $node->set('status', NULL);
544     $node->set('created', NULL);
545     $node->set('changed', NULL);
546     $node->set('promote', NULL);
547     $node->set('sticky', NULL);
548     $node->set('revision_timestamp', NULL);
549     $node->set('revision_log', NULL);
550     $node->set('uid', NULL);
551
552     return $node;
553   }
554
555   /**
556    * Check to see if the HTTP request response body is identical to the expected
557    * value.
558    *
559    * @param $expected
560    *   The first value to check.
561    * @param $message
562    *   (optional) A message to display with the assertion. Do not translate
563    *   messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
564    *   variables in the message text, not t(). If left blank, a default message
565    *   will be displayed.
566    * @param $group
567    *   (optional) The group this message is in, which is displayed in a column
568    *   in test output. Use 'Debug' to indicate this is debugging output. Do not
569    *   translate this string. Defaults to 'Other'; most tests do not override
570    *   this default.
571    *
572    * @return bool
573    *   TRUE if the assertion succeeded, FALSE otherwise.
574    */
575   protected function assertResponseBody($expected, $message = '', $group = 'REST Response') {
576     return $this->assertIdentical($expected, $this->responseBody, $message ? $message : strtr('Response body @expected (expected) is equal to @response (actual).', ['@expected' => var_export($expected, TRUE), '@response' => var_export($this->responseBody, TRUE)]), $group);
577   }
578
579   /**
580    * Checks if an entity type id is for a Config Entity.
581    *
582    * @param string $entity_type_id
583    *   The entity type ID to check.
584    *
585    * @return bool
586    *   TRUE if the entity is a Config Entity, FALSE otherwise.
587    */
588   protected function isConfigEntity($entity_type_id) {
589     return \Drupal::entityTypeManager()->getDefinition($entity_type_id) instanceof ConfigEntityType;
590   }
591
592   /**
593    * Provides an array of suitable property values for a config entity type.
594    *
595    * Config entities have some common keys that need to be created. Required
596    * properties differ among config entity types, so we keep a minimum mapping
597    * here.
598    *
599    * @param string $entity_type_id
600    *   The ID of the type of entity that should be created.
601    *
602    * @return array
603    *   An array of values keyed by property name.
604    */
605   protected function configEntityValues($entity_type_id) {
606     $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
607     $keys = $entity_type->getKeys();
608     $values = [];
609     // Fill out known key values that are shared across entity types.
610     foreach ($keys as $key) {
611       if ($key === 'id' || $key === 'label') {
612         $values[$key] = $this->randomMachineName();
613       }
614     }
615     // Add extra values for particular entity types.
616     switch ($entity_type_id) {
617       case 'block':
618         $values['plugin'] = 'system_powered_by_block';
619         break;
620     }
621     return $values;
622   }
623
624 }