8283bef260010b79991644347312b690023e3af7
[yaffs-website] / web / core / modules / rest / tests / src / Functional / ResourceTestBase.php
1 <?php
2
3 namespace Drupal\Tests\rest\Functional;
4
5 use Behat\Mink\Driver\BrowserKitDriver;
6 use Drupal\Core\Url;
7 use Drupal\rest\RestResourceConfigInterface;
8 use Drupal\Tests\BrowserTestBase;
9 use Drupal\user\Entity\Role;
10 use Drupal\user\RoleInterface;
11 use GuzzleHttp\RequestOptions;
12 use Psr\Http\Message\ResponseInterface;
13
14 /**
15  * Subclass this for every REST resource, every format and every auth provider.
16  *
17  * For more guidance see
18  * \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase
19  * which has recommendations for testing the
20  * \Drupal\rest\Plugin\rest\resource\EntityResource REST resource for every
21  * format and every auth provider. It's a special case (because that single REST
22  * resource generates supports not just one thing, but many things — multiple
23  * entity types), but the same principles apply.
24  */
25 abstract class ResourceTestBase extends BrowserTestBase {
26
27   /**
28    * The format to use in this test.
29    *
30    * A format is the combination of a certain normalizer and a certain
31    * serializer.
32    *
33    * @see https://www.drupal.org/developing/api/8/serialization
34    *
35    * (The default is 'json' because that doesn't depend on any module.)
36    *
37    * @var string
38    */
39   protected static $format = 'json';
40
41   /**
42    * The MIME type that corresponds to $format.
43    *
44    * (Sadly this cannot be computed automatically yet.)
45    *
46    * @var string
47    */
48   protected static $mimeType = 'application/json';
49
50   /**
51    * The authentication mechanism to use in this test.
52    *
53    * (The default is 'cookie' because that doesn't depend on any module.)
54    *
55    * @var string
56    */
57   protected static $auth = FALSE;
58
59   /**
60    * The REST Resource Config entity ID under test (i.e. a resource type).
61    *
62    * The REST Resource plugin ID can be calculated from this.
63    *
64    * @var string
65    *
66    * @see \Drupal\rest\Entity\RestResourceConfig::__construct()
67    */
68   protected static $resourceConfigId = NULL;
69
70   /**
71    * The account to use for authentication, if any.
72    *
73    * @var null|\Drupal\Core\Session\AccountInterface
74    */
75   protected $account = NULL;
76
77   /**
78    * The REST resource config entity storage.
79    *
80    * @var \Drupal\Core\Entity\EntityStorageInterface
81    */
82   protected $resourceConfigStorage;
83
84   /**
85    * The serializer service.
86    *
87    * @var \Symfony\Component\Serializer\Serializer
88    */
89   protected $serializer;
90
91   /**
92    * Modules to install.
93    *
94    * @var array
95    */
96   public static $modules = ['rest'];
97
98   /**
99    * {@inheritdoc}
100    */
101   public function setUp() {
102     parent::setUp();
103
104     $this->serializer = $this->container->get('serializer');
105
106     // Ensure the anonymous user role has no permissions at all.
107     $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
108     foreach ($user_role->getPermissions() as $permission) {
109       $user_role->revokePermission($permission);
110     }
111     $user_role->save();
112     assert([] === $user_role->getPermissions(), 'The anonymous user role has no permissions at all.');
113
114     if (static::$auth !== FALSE) {
115       // Ensure the authenticated user role has no permissions at all.
116       $user_role = Role::load(RoleInterface::AUTHENTICATED_ID);
117       foreach ($user_role->getPermissions() as $permission) {
118         $user_role->revokePermission($permission);
119       }
120       $user_role->save();
121       assert([] === $user_role->getPermissions(), 'The authenticated user role has no permissions at all.');
122
123       // Create an account.
124       $this->account = $this->createUser();
125     }
126     else {
127       // Otherwise, also create an account, so that any test involving User
128       // entities will have the same user IDs regardless of authentication.
129       $this->createUser();
130     }
131
132     $this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
133
134     // Ensure there's a clean slate: delete all REST resource config entities.
135     $this->resourceConfigStorage->delete($this->resourceConfigStorage->loadMultiple());
136     $this->refreshTestStateAfterRestConfigChange();
137   }
138
139   /**
140    * Provisions the REST resource under test.
141    *
142    * @param string[] $formats
143    *   The allowed formats for this resource.
144    * @param string[] $authentication
145    *   The allowed authentication providers for this resource.
146    */
147   protected function provisionResource($formats = [], $authentication = []) {
148     $this->resourceConfigStorage->create([
149       'id' => static::$resourceConfigId,
150       'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
151       'configuration' => [
152         'methods' => ['GET', 'POST', 'PATCH', 'DELETE'],
153         'formats' => $formats,
154         'authentication' => $authentication,
155       ],
156       'status' => TRUE,
157     ])->save();
158     $this->refreshTestStateAfterRestConfigChange();
159   }
160
161   /**
162    * Refreshes the state of the tester to be in sync with the testee.
163    *
164    * Should be called after every change made to:
165    * - RestResourceConfig entities
166    * - the 'rest.settings' simple configuration
167    */
168   protected function refreshTestStateAfterRestConfigChange() {
169     // Ensure that the cache tags invalidator has its internal values reset.
170     // Otherwise the http_response cache tag invalidation won't work.
171     $this->refreshVariables();
172
173     // Tests using this base class may trigger route rebuilds due to changes to
174     // RestResourceConfig entities or 'rest.settings'. Ensure the test generates
175     // routes using an up-to-date router.
176     \Drupal::service('router.builder')->rebuildIfNeeded();
177   }
178
179   /**
180    * Return the expected error message.
181    *
182    * @param string $method
183    *   The HTTP method (GET, POST, PATCH, DELETE).
184    *
185    * @return string
186    *   The error string.
187    */
188   protected function getExpectedUnauthorizedAccessMessage($method) {
189     $resource_plugin_id = str_replace('.', ':', static::$resourceConfigId);
190     $permission = 'restful ' . strtolower($method) . ' ' . $resource_plugin_id;
191     return "The '$permission' permission is required.";
192   }
193
194   /**
195    * Sets up the necessary authorization.
196    *
197    * In case of a test verifying publicly accessible REST resources: grant
198    * permissions to the anonymous user role.
199    *
200    * In case of a test verifying behavior when using a particular authentication
201    * provider: create a user with a particular set of permissions.
202    *
203    * Because of the $method parameter, it's possible to first set up
204    * authentication for only GET, then add POST, et cetera. This then also
205    * allows for verifying a 403 in case of missing authorization.
206    *
207    * @param string $method
208    *   The HTTP method for which to set up authentication.
209    *
210    * @see ::grantPermissionsToAnonymousRole()
211    * @see ::grantPermissionsToAuthenticatedRole()
212    */
213   abstract protected function setUpAuthorization($method);
214
215   /**
216    * Verifies the error response in case of missing authentication.
217    *
218    * @param string $method
219    *   HTTP method.
220    * @param \Psr\Http\Message\ResponseInterface $response
221    *   The response to assert.
222    */
223   abstract protected function assertResponseWhenMissingAuthentication($method, ResponseInterface $response);
224
225   /**
226    * Asserts normalization-specific edge cases.
227    *
228    * (Should be called before sending a well-formed request.)
229    *
230    * @see \GuzzleHttp\ClientInterface::request()
231    *
232    * @param string $method
233    *   HTTP method.
234    * @param \Drupal\Core\Url $url
235    *   URL to request.
236    * @param array $request_options
237    *   Request options to apply.
238    */
239   abstract protected function assertNormalizationEdgeCases($method, Url $url, array $request_options);
240
241   /**
242    * Asserts authentication provider-specific edge cases.
243    *
244    * (Should be called before sending a well-formed request.)
245    *
246    * @see \GuzzleHttp\ClientInterface::request()
247    *
248    * @param string $method
249    *   HTTP method.
250    * @param \Drupal\Core\Url $url
251    *   URL to request.
252    * @param array $request_options
253    *   Request options to apply.
254    */
255   abstract protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options);
256
257   /**
258    * Returns the expected cacheability of an unauthorized access response.
259    *
260    * @return \Drupal\Core\Cache\RefinableCacheableDependencyInterface
261    *   The expected cacheability.
262    */
263   abstract protected function getExpectedUnauthorizedAccessCacheability();
264
265   /**
266    * Initializes authentication.
267    *
268    * E.g. for cookie authentication, we first need to get a cookie.
269    */
270   protected function initAuthentication() {}
271
272   /**
273    * Returns Guzzle request options for authentication.
274    *
275    * @param string $method
276    *   The HTTP method for this authenticated request.
277    *
278    * @return array
279    *   Guzzle request options to use for authentication.
280    *
281    * @see \GuzzleHttp\ClientInterface::request()
282    */
283   protected function getAuthenticationRequestOptions($method) {
284     return [];
285   }
286
287   /**
288    * Grants permissions to the anonymous role.
289    *
290    * @param string[] $permissions
291    *   Permissions to grant.
292    */
293   protected function grantPermissionsToAnonymousRole(array $permissions) {
294     $this->grantPermissions(Role::load(RoleInterface::ANONYMOUS_ID), $permissions);
295   }
296
297   /**
298    * Grants permissions to the authenticated role.
299    *
300    * @param string[] $permissions
301    *   Permissions to grant.
302    */
303   protected function grantPermissionsToAuthenticatedRole(array $permissions) {
304     $this->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), $permissions);
305   }
306
307   /**
308    * Grants permissions to the tested role: anonymous or authenticated.
309    *
310    * @param string[] $permissions
311    *   Permissions to grant.
312    *
313    * @see ::grantPermissionsToAuthenticatedRole()
314    * @see ::grantPermissionsToAnonymousRole()
315    */
316   protected function grantPermissionsToTestedRole(array $permissions) {
317     if (static::$auth) {
318       $this->grantPermissionsToAuthenticatedRole($permissions);
319     }
320     else {
321       $this->grantPermissionsToAnonymousRole($permissions);
322     }
323   }
324
325   /**
326    * Performs a HTTP request. Wraps the Guzzle HTTP client.
327    *
328    * Why wrap the Guzzle HTTP client? Because we want to keep the actual test
329    * code as simple as possible, and hence not require them to specify the
330    * 'http_errors = FALSE' request option, nor do we want them to have to
331    * convert Drupal Url objects to strings.
332    *
333    * We also don't want to follow redirects automatically, to ensure these tests
334    * are able to detect when redirects are added or removed.
335    *
336    * @see \GuzzleHttp\ClientInterface::request()
337    *
338    * @param string $method
339    *   HTTP method.
340    * @param \Drupal\Core\Url $url
341    *   URL to request.
342    * @param array $request_options
343    *   Request options to apply.
344    *
345    * @return \Psr\Http\Message\ResponseInterface
346    */
347   protected function request($method, Url $url, array $request_options) {
348     $request_options[RequestOptions::HTTP_ERRORS] = FALSE;
349     $request_options[RequestOptions::ALLOW_REDIRECTS] = FALSE;
350     $request_options = $this->decorateWithXdebugCookie($request_options);
351     $client = $this->getSession()->getDriver()->getClient()->getClient();
352     return $client->request($method, $url->setAbsolute(TRUE)->toString(), $request_options);
353   }
354
355   /**
356    * Asserts that a resource response has the given status code and body.
357    *
358    * @param int $expected_status_code
359    *   The expected response status.
360    * @param string|false $expected_body
361    *   The expected response body. FALSE in case this should not be asserted.
362    * @param \Psr\Http\Message\ResponseInterface $response
363    *   The response to assert.
364    * @param string[]|false $expected_cache_tags
365    *   (optional) The expected cache tags in the X-Drupal-Cache-Tags response
366    *   header, or FALSE if that header should be absent. Defaults to FALSE.
367    * @param string[]|false $expected_cache_contexts
368    *   (optional) The expected cache contexts in the X-Drupal-Cache-Contexts
369    *   response header, or FALSE if that header should be absent. Defaults to
370    *   FALSE.
371    * @param string|false $expected_page_cache_header_value
372    *   (optional) The expected X-Drupal-Cache response header value, or FALSE if
373    *   that header should be absent. Possible strings: 'MISS', 'HIT'. Defaults
374    *   to FALSE.
375    * @param string|false $expected_dynamic_page_cache_header_value
376    *   (optional) The expected X-Drupal-Dynamic-Cache response header value, or
377    *   FALSE if that header should be absent. Possible strings: 'MISS', 'HIT'.
378    *   Defaults to FALSE.
379    */
380   protected function assertResourceResponse($expected_status_code, $expected_body, ResponseInterface $response, $expected_cache_tags = FALSE, $expected_cache_contexts = FALSE, $expected_page_cache_header_value = FALSE, $expected_dynamic_page_cache_header_value = FALSE) {
381     $this->assertSame($expected_status_code, $response->getStatusCode());
382     if ($expected_status_code === 204) {
383       // DELETE responses should not include a Content-Type header. But Apache
384       // sets it to 'text/html' by default. We also cannot detect the presence
385       // of Apache either here in the CLI. For now having this documented here
386       // is all we can do.
387       // $this->assertSame(FALSE, $response->hasHeader('Content-Type'));
388       $this->assertSame('', (string) $response->getBody());
389     }
390     else {
391       $this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
392       if ($expected_body !== FALSE) {
393         $this->assertSame($expected_body, (string) $response->getBody());
394       }
395     }
396
397     // Expected cache tags: X-Drupal-Cache-Tags header.
398     $this->assertSame($expected_cache_tags !== FALSE, $response->hasHeader('X-Drupal-Cache-Tags'));
399     if (is_array($expected_cache_tags)) {
400       $this->assertSame($expected_cache_tags, explode(' ', $response->getHeader('X-Drupal-Cache-Tags')[0]));
401     }
402
403     // Expected cache contexts: X-Drupal-Cache-Contexts header.
404     $this->assertSame($expected_cache_contexts !== FALSE, $response->hasHeader('X-Drupal-Cache-Contexts'));
405     if (is_array($expected_cache_contexts)) {
406       $this->assertSame($expected_cache_contexts, explode(' ', $response->getHeader('X-Drupal-Cache-Contexts')[0]));
407     }
408
409     // Expected Page Cache header value: X-Drupal-Cache header.
410     if ($expected_page_cache_header_value !== FALSE) {
411       $this->assertTrue($response->hasHeader('X-Drupal-Cache'));
412       $this->assertSame($expected_page_cache_header_value, $response->getHeader('X-Drupal-Cache')[0]);
413     }
414     else {
415       $this->assertFalse($response->hasHeader('X-Drupal-Cache'));
416     }
417
418     // Expected Dynamic Page Cache header value: X-Drupal-Dynamic-Cache header.
419     if ($expected_dynamic_page_cache_header_value !== FALSE) {
420       $this->assertTrue($response->hasHeader('X-Drupal-Dynamic-Cache'));
421       $this->assertSame($expected_dynamic_page_cache_header_value, $response->getHeader('X-Drupal-Dynamic-Cache')[0]);
422     }
423     else {
424       $this->assertFalse($response->hasHeader('X-Drupal-Dynamic-Cache'));
425     }
426   }
427
428   /**
429    * Asserts that a resource error response has the given message.
430    *
431    * @param int $expected_status_code
432    *   The expected response status.
433    * @param string $expected_message
434    *   The expected error message.
435    * @param \Psr\Http\Message\ResponseInterface $response
436    *   The error response to assert.
437    * @param string[]|false $expected_cache_tags
438    *   (optional) The expected cache tags in the X-Drupal-Cache-Tags response
439    *   header, or FALSE if that header should be absent. Defaults to FALSE.
440    * @param string[]|false $expected_cache_contexts
441    *   (optional) The expected cache contexts in the X-Drupal-Cache-Contexts
442    *   response header, or FALSE if that header should be absent. Defaults to
443    *   FALSE.
444    * @param string|false $expected_page_cache_header_value
445    *   (optional) The expected X-Drupal-Cache response header value, or FALSE if
446    *   that header should be absent. Possible strings: 'MISS', 'HIT'. Defaults
447    *   to FALSE.
448    * @param string|false $expected_dynamic_page_cache_header_value
449    *   (optional) The expected X-Drupal-Dynamic-Cache response header value, or
450    *   FALSE if that header should be absent. Possible strings: 'MISS', 'HIT'.
451    *   Defaults to FALSE.
452    */
453   protected function assertResourceErrorResponse($expected_status_code, $expected_message, ResponseInterface $response, $expected_cache_tags = FALSE, $expected_cache_contexts = FALSE, $expected_page_cache_header_value = FALSE, $expected_dynamic_page_cache_header_value = FALSE) {
454     $expected_body = ($expected_message !== FALSE) ? $this->serializer->encode(['message' => $expected_message], static::$format) : FALSE;
455     $this->assertResourceResponse($expected_status_code, $expected_body, $response, $expected_cache_tags, $expected_cache_contexts, $expected_page_cache_header_value, $expected_dynamic_page_cache_header_value);
456   }
457
458   /**
459    * Adds the Xdebug cookie to the request options.
460    *
461    * @param array $request_options
462    *   The request options.
463    *
464    * @return array
465    *   Request options updated with the Xdebug cookie if present.
466    */
467   protected function decorateWithXdebugCookie(array $request_options) {
468     $session = $this->getSession();
469     $driver = $session->getDriver();
470     if ($driver instanceof BrowserKitDriver) {
471       $client = $driver->getClient();
472       foreach ($client->getCookieJar()->all() as $cookie) {
473         if (isset($request_options[RequestOptions::HEADERS]['Cookie'])) {
474           $request_options[RequestOptions::HEADERS]['Cookie'] .= '; ' . $cookie->getName() . '=' . $cookie->getValue();
475         }
476         else {
477           $request_options[RequestOptions::HEADERS]['Cookie'] = $cookie->getName() . '=' . $cookie->getValue();
478         }
479       }
480     }
481     return $request_options;
482   }
483
484 }