Upgraded drupal core with security updates
[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   protected static $resourceConfigId = NULL;
67
68   /**
69    * The account to use for authentication, if any.
70    *
71    * @var null|\Drupal\Core\Session\AccountInterface
72    */
73   protected $account = NULL;
74
75   /**
76    * The REST resource config entity storage.
77    *
78    * @var \Drupal\Core\Entity\EntityStorageInterface
79    */
80   protected $resourceConfigStorage;
81
82   /**
83    * The serializer service.
84    *
85    * @var \Symfony\Component\Serializer\Serializer
86    */
87   protected $serializer;
88
89   /**
90    * Modules to install.
91    *
92    * @var array
93    */
94   public static $modules = ['rest'];
95
96   /**
97    * {@inheritdoc}
98    */
99   public function setUp() {
100     parent::setUp();
101
102     // Ensure the anonymous user role has no permissions at all.
103     $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
104     foreach ($user_role->getPermissions() as $permission) {
105       $user_role->revokePermission($permission);
106     }
107     $user_role->save();
108     assert('[] === $user_role->getPermissions()', 'The anonymous user role has no permissions at all.');
109
110     if (static::$auth !== FALSE) {
111       // Ensure the authenticated user role has no permissions at all.
112       $user_role = Role::load(RoleInterface::AUTHENTICATED_ID);
113       foreach ($user_role->getPermissions() as $permission) {
114         $user_role->revokePermission($permission);
115       }
116       $user_role->save();
117       assert('[] === $user_role->getPermissions()', 'The authenticated user role has no permissions at all.');
118
119       // Create an account.
120       $this->account = $this->createUser();
121     }
122     else {
123       // Otherwise, also create an account, so that any test involving User
124       // entities will have the same user IDs regardless of authentication.
125       $this->createUser();
126     }
127
128     $this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
129
130     // Ensure there's a clean slate: delete all REST resource config entities.
131     $this->resourceConfigStorage->delete($this->resourceConfigStorage->loadMultiple());
132     $this->refreshTestStateAfterRestConfigChange();
133   }
134
135   /**
136    * Provisions the REST resource under test.
137    *
138    * @param string[] $formats
139    *   The allowed formats for this resource.
140    * @param string[] $authentication
141    *   The allowed authentication providers for this resource.
142    */
143   protected function provisionResource($formats = [], $authentication = []) {
144     $this->resourceConfigStorage->create([
145       'id' => static::$resourceConfigId,
146       'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
147       'configuration' => [
148         'methods' => ['GET', 'POST', 'PATCH', 'DELETE'],
149         'formats' => $formats,
150         'authentication' => $authentication,
151       ],
152       'status' => TRUE,
153     ])->save();
154     $this->refreshTestStateAfterRestConfigChange();
155   }
156
157   /**
158    * Refreshes the state of the tester to be in sync with the testee.
159    *
160    * Should be called after every change made to:
161    * - RestResourceConfig entities
162    * - the 'rest.settings' simple configuration
163    */
164   protected function refreshTestStateAfterRestConfigChange() {
165     // Ensure that the cache tags invalidator has its internal values reset.
166     // Otherwise the http_response cache tag invalidation won't work.
167     $this->refreshVariables();
168
169     // Tests using this base class may trigger route rebuilds due to changes to
170     // RestResourceConfig entities or 'rest.settings'. Ensure the test generates
171     // routes using an up-to-date router.
172     \Drupal::service('router.builder')->rebuildIfNeeded();
173   }
174
175   /**
176    * Sets up the necessary authorization.
177    *
178    * In case of a test verifying publicly accessible REST resources: grant
179    * permissions to the anonymous user role.
180    *
181    * In case of a test verifying behavior when using a particular authentication
182    * provider: create a user with a particular set of permissions.
183    *
184    * Because of the $method parameter, it's possible to first set up
185    * authentication for only GET, then add POST, et cetera. This then also
186    * allows for verifying a 403 in case of missing authorization.
187    *
188    * @param string $method
189    *   The HTTP method for which to set up authentication.
190    *
191    * @see ::grantPermissionsToAnonymousRole()
192    * @see ::grantPermissionsToAuthenticatedRole()
193    */
194   abstract protected function setUpAuthorization($method);
195
196   /**
197    * Verifies the error response in case of missing authentication.
198    */
199   abstract protected function assertResponseWhenMissingAuthentication(ResponseInterface $response);
200
201   /**
202    * Asserts normalization-specific edge cases.
203    *
204    * (Should be called before sending a well-formed request.)
205    *
206    * @see \GuzzleHttp\ClientInterface::request()
207    *
208    * @param string $method
209    *   HTTP method.
210    * @param \Drupal\Core\Url $url
211    *   URL to request.
212    * @param array $request_options
213    *   Request options to apply.
214    */
215   abstract protected function assertNormalizationEdgeCases($method, Url $url, array $request_options);
216
217   /**
218    * Asserts authentication provider-specific edge cases.
219    *
220    * (Should be called before sending a well-formed request.)
221    *
222    * @see \GuzzleHttp\ClientInterface::request()
223    *
224    * @param string $method
225    *   HTTP method.
226    * @param \Drupal\Core\Url $url
227    *   URL to request.
228    * @param array $request_options
229    *   Request options to apply.
230    */
231   abstract protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options);
232
233   /**
234    * Return the expected error message.
235    *
236    * @param string $method
237    *   The HTTP method (GET, POST, PATCH, DELETE).
238    *
239    * @return string
240    *    The error string.
241    */
242   abstract protected function getExpectedUnauthorizedAccessMessage($method);
243
244   /**
245    * Return the default expected error message if the
246    * bc_entity_resource_permissions is true.
247    *
248    * @param string $method
249    *   The HTTP method (GET, POST, PATCH, DELETE).
250    *
251    * @return string
252    *   The error string.
253    */
254   abstract protected function getExpectedBcUnauthorizedAccessMessage($method);
255
256   /**
257    * Initializes authentication.
258    *
259    * E.g. for cookie authentication, we first need to get a cookie.
260    */
261   protected function initAuthentication() {}
262
263   /**
264    * Returns Guzzle request options for authentication.
265    *
266    * @param string $method
267    *   The HTTP method for this authenticated request.
268    *
269    * @return array
270    *   Guzzle request options to use for authentication.
271    *
272    * @see \GuzzleHttp\ClientInterface::request()
273    */
274   protected function getAuthenticationRequestOptions($method) {
275     return [];
276   }
277
278   /**
279    * Grants permissions to the anonymous role.
280    *
281    * @param string[] $permissions
282    *   Permissions to grant.
283    */
284   protected function grantPermissionsToAnonymousRole(array $permissions) {
285     $this->grantPermissions(Role::load(RoleInterface::ANONYMOUS_ID), $permissions);
286   }
287
288   /**
289    * Grants permissions to the authenticated role.
290    *
291    * @param string[] $permissions
292    *   Permissions to grant.
293    */
294   protected function grantPermissionsToAuthenticatedRole(array $permissions) {
295     $this->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), $permissions);
296   }
297
298   /**
299    * Grants permissions to the tested role: anonymous or authenticated.
300    *
301    * @param string[] $permissions
302    *   Permissions to grant.
303    *
304    * @see ::grantPermissionsToAuthenticatedRole()
305    * @see ::grantPermissionsToAnonymousRole()
306    */
307   protected function grantPermissionsToTestedRole(array $permissions) {
308     if (static::$auth) {
309       $this->grantPermissionsToAuthenticatedRole($permissions);
310     }
311     else {
312       $this->grantPermissionsToAnonymousRole($permissions);
313     }
314   }
315
316   /**
317    * Performs a HTTP request. Wraps the Guzzle HTTP client.
318    *
319    * Why wrap the Guzzle HTTP client? Because we want to keep the actual test
320    * code as simple as possible, and hence not require them to specify the
321    * 'http_errors = FALSE' request option, nor do we want them to have to
322    * convert Drupal Url objects to strings.
323    *
324    * @see \GuzzleHttp\ClientInterface::request()
325    *
326    * @param string $method
327    *   HTTP method.
328    * @param \Drupal\Core\Url $url
329    *   URL to request.
330    * @param array $request_options
331    *   Request options to apply.
332    *
333    * @return \Psr\Http\Message\ResponseInterface
334    */
335   protected function request($method, Url $url, array $request_options) {
336     $request_options[RequestOptions::HTTP_ERRORS] = FALSE;
337     $request_options = $this->decorateWithXdebugCookie($request_options);
338     $client = $this->getSession()->getDriver()->getClient()->getClient();
339     return $client->request($method, $url->setAbsolute(TRUE)->toString(), $request_options);
340   }
341
342   /**
343    * Asserts that a resource response has the given status code and body.
344    *
345    * @param int $expected_status_code
346    *   The expected response status.
347    * @param string|false $expected_body
348    *   The expected response body. FALSE in case this should not be asserted.
349    * @param \Psr\Http\Message\ResponseInterface $response
350    *   The response to assert.
351    */
352   protected function assertResourceResponse($expected_status_code, $expected_body, ResponseInterface $response) {
353     $this->assertSame($expected_status_code, $response->getStatusCode());
354     if ($expected_status_code < 400) {
355       $this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
356     }
357     else {
358       $this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
359     }
360     if ($expected_body !== FALSE) {
361       $this->assertSame($expected_body, (string) $response->getBody());
362     }
363   }
364
365   /**
366    * Asserts that a resource error response has the given message.
367    *
368    * @param int $expected_status_code
369    *   The expected response status.
370    * @param string $expected_message
371    *   The expected error message.
372    * @param \Psr\Http\Message\ResponseInterface $response
373    *   The error response to assert.
374    */
375   protected function assertResourceErrorResponse($expected_status_code, $expected_message, ResponseInterface $response) {
376     $expected_body = ($expected_message !== FALSE) ? $this->serializer->encode(['message' => $expected_message], static::$format) : FALSE;
377     $this->assertResourceResponse($expected_status_code, $expected_body, $response);
378   }
379
380   /**
381    * Adds the Xdebug cookie to the request options.
382    *
383    * @param array $request_options
384    *   The request options.
385    *
386    * @return array
387    *   Request options updated with the Xdebug cookie if present.
388    */
389   protected function decorateWithXdebugCookie(array $request_options) {
390     $session = $this->getSession();
391     $driver = $session->getDriver();
392     if ($driver instanceof BrowserKitDriver) {
393       $client = $driver->getClient();
394       foreach ($client->getCookieJar()->all() as $cookie) {
395         if (isset($request_options[RequestOptions::HEADERS]['Cookie'])) {
396           $request_options[RequestOptions::HEADERS]['Cookie'] .= '; ' . $cookie->getName() . '=' . $cookie->getValue();
397         }
398         else {
399           $request_options[RequestOptions::HEADERS]['Cookie'] = $cookie->getName() . '=' . $cookie->getValue();
400         }
401       }
402     }
403     return $request_options;
404   }
405
406 }