summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAlex Pott2016-08-01 16:35:53 (GMT)
committerAlex Pott2016-08-01 16:35:53 (GMT)
commit2ec23349fc186045cec82433a1b845fef99ff106 (patch)
treecccd7391835bef14ab29fb39aed192be408ad5e7
parent23ed767a23b96415d73d164e6ceea43a90374eed (diff)
Issue #2664780 by Wim Leers, tedbow, dawehner, klausi: Remove REST's resource- and verb-specific permissions for EntityResource, but provide BC and document why it's necessary for other resources
-rw-r--r--core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php4
-rw-r--r--core/modules/page_cache/src/Tests/PageCacheTest.php5
-rw-r--r--core/modules/rest/config/install/rest.settings.yml8
-rw-r--r--core/modules/rest/config/schema/rest.schema.yml3
-rw-r--r--core/modules/rest/rest.install10
-rw-r--r--core/modules/rest/src/Plugin/ResourceBase.php47
-rw-r--r--core/modules/rest/src/Plugin/ResourceInterface.php4
-rw-r--r--core/modules/rest/src/Plugin/rest/resource/EntityResource.php31
-rw-r--r--core/modules/rest/src/RequestHandler.php13
-rw-r--r--core/modules/rest/src/Tests/AuthTest.php1
-rw-r--r--core/modules/rest/src/Tests/CreateTest.php23
-rw-r--r--core/modules/rest/src/Tests/CsrfTest.php1
-rw-r--r--core/modules/rest/src/Tests/DeleteTest.php1
-rw-r--r--core/modules/rest/src/Tests/NodeTest.php1
-rw-r--r--core/modules/rest/src/Tests/PageCacheTest.php4
-rw-r--r--core/modules/rest/src/Tests/ReadTest.php8
-rw-r--r--core/modules/rest/src/Tests/Update/EntityResourcePermissionsUpdateTest.php56
-rw-r--r--core/modules/rest/src/Tests/UpdateTest.php23
-rw-r--r--core/modules/rest/tests/fixtures/update/drupal-8.rest-rest_update_8203.php63
-rw-r--r--core/modules/system/src/Tests/System/ResponseGeneratorTest.php1
20 files changed, 242 insertions, 65 deletions
diff --git a/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php b/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php
index 1dd1f11..279d202 100644
--- a/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php
+++ b/core/modules/dblog/src/Tests/Rest/DbLogResourceTest.php
@@ -53,13 +53,13 @@ class DbLogResourceTest extends RESTTestBase {
$response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => 9999, '_format' => $this->defaultFormat]), 'GET');
$this->assertResponse(404);
$decoded = Json::decode($response);
- $this->assertEqual($decoded['error'], 'Log entry with ID 9999 was not found', 'Response message is correct.');
+ $this->assertEqual($decoded['message'], 'Log entry with ID 9999 was not found', 'Response message is correct.');
// Make a bad request (a true malformed request would never be a route match).
$response = $this->httpRequest(Url::fromRoute('rest.dblog.GET.' . $this->defaultFormat, ['id' => 0, '_format' => $this->defaultFormat]), 'GET');
$this->assertResponse(400);
$decoded = Json::decode($response);
- $this->assertEqual($decoded['error'], 'No log entry ID was provided', 'Response message is correct.');
+ $this->assertEqual($decoded['message'], 'No log entry ID was provided', 'Response message is correct.');
}
}
diff --git a/core/modules/page_cache/src/Tests/PageCacheTest.php b/core/modules/page_cache/src/Tests/PageCacheTest.php
index 64e4ee9..22b8b51 100644
--- a/core/modules/page_cache/src/Tests/PageCacheTest.php
+++ b/core/modules/page_cache/src/Tests/PageCacheTest.php
@@ -8,7 +8,6 @@ use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\simpletest\WebTestBase;
use Drupal\Core\Cache\Cache;
-use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
/**
@@ -136,10 +135,6 @@ class PageCacheTest extends WebTestBase {
$node = $this->drupalCreateNode(['type' => 'article']);
$node_uri = $node->urlInfo();
$node_url_with_hal_json_format = $node->urlInfo('canonical')->setRouteParameter('_format', 'hal_json');
- /** @var \Drupal\user\RoleInterface $role */
- $role = Role::load('anonymous');
- $role->grantPermission('restful get entity:node');
- $role->save();
$this->drupalGet($node_uri);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
diff --git a/core/modules/rest/config/install/rest.settings.yml b/core/modules/rest/config/install/rest.settings.yml
index 2d8185e..eb3da2d 100644
--- a/core/modules/rest/config/install/rest.settings.yml
+++ b/core/modules/rest/config/install/rest.settings.yml
@@ -1,3 +1,11 @@
# Set the domain for REST type and relation links.
# If left blank, the site's domain will be used.
link_domain: ~
+
+# Before Drupal 8.2, EntityResource used permissions as well as the entity
+# access system for access checking. This was confusing, and it only did this
+# for historical reasons. New Drupal installations opt out from this by default
+# (hence this is set to false), existing installations opt in to it.
+# @see rest_update_8203()
+# @see https://www.drupal.org/node/2664780
+bc_entity_resource_permissions: false
diff --git a/core/modules/rest/config/schema/rest.schema.yml b/core/modules/rest/config/schema/rest.schema.yml
index 04f88a6..2c255ab 100644
--- a/core/modules/rest/config/schema/rest.schema.yml
+++ b/core/modules/rest/config/schema/rest.schema.yml
@@ -6,6 +6,9 @@ rest.settings:
link_domain:
type: string
label: 'Domain of the relation'
+ bc_entity_resource_permissions:
+ type: boolean
+ label: 'Whether the pre Drupal 8.2.x behavior of having permissions for EntityResource is enabled or not.'
# Method-level granularity of REST resource configuration.
rest_resource.method:
diff --git a/core/modules/rest/rest.install b/core/modules/rest/rest.install
index 4cfaa11..90f4ec9 100644
--- a/core/modules/rest/rest.install
+++ b/core/modules/rest/rest.install
@@ -66,5 +66,15 @@ function rest_update_8202() {
}
/**
+ * Enable BC for EntityResource: continue to use permissions.
+ */
+function rest_update_8203() {
+ $config_factory = \Drupal::configFactory();
+ $rest_settings = $config_factory->getEditable('rest.settings');
+ $rest_settings->set('bc_entity_resource_permissions', TRUE)
+ ->save(TRUE);
+}
+
+/**
* @} End of "defgroup updates-8.1.x-to-8.2.x".
*/
diff --git a/core/modules/rest/src/Plugin/ResourceBase.php b/core/modules/rest/src/Plugin/ResourceBase.php
index 549ac54..93684db 100644
--- a/core/modules/rest/src/Plugin/ResourceBase.php
+++ b/core/modules/rest/src/Plugin/ResourceBase.php
@@ -12,6 +12,11 @@ use Symfony\Component\Routing\RouteCollection;
/**
* Common base class for resource plugins.
*
+ * Note that this base class' implementation of the permissions() method
+ * generates a permission for every method for a resource. If your resource
+ * already has its own access control mechanism, you should opt out from this
+ * default permissions() method by overriding it.
+ *
* @see \Drupal\rest\Annotation\RestResource
* @see \Drupal\rest\Plugin\Type\ResourcePluginManager
* @see \Drupal\rest\Plugin\ResourceInterface
@@ -179,7 +184,7 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
}
/**
- * Setups the base route for all HTTP methods.
+ * Gets the base route for a particular method.
*
* @param string $canonical_path
* The canonical path for the resource.
@@ -190,20 +195,48 @@ abstract class ResourceBase extends PluginBase implements ContainerFactoryPlugin
* The created base route.
*/
protected function getBaseRoute($canonical_path, $method) {
- $lower_method = strtolower($method);
-
- $route = new Route($canonical_path, array(
+ return new Route($canonical_path, array(
'_controller' => 'Drupal\rest\RequestHandler::handle',
- ), array(
- '_permission' => "restful $lower_method $this->pluginId",
),
+ $this->getBaseRouteRequirements($method),
array(),
'',
array(),
// The HTTP method is a requirement for this route.
array($method)
);
- return $route;
+ }
+
+ /**
+ * Gets the base route requirements for a particular method.
+ *
+ * @param $method
+ * The HTTP method to be used for the route.
+ *
+ * @return array
+ * An array of requirements for parameters.
+ */
+ protected function getBaseRouteRequirements($method) {
+ $lower_method = strtolower($method);
+ // Every route MUST have requirements that result in the access manager
+ // having access checks to check. If it does not, the route is made
+ // inaccessible. So, we default to granting access to everyone. If a
+ // permission exists, then we add that below. The access manager requires
+ // that ALL access checks must grant access, so this still results in
+ // correct behavior.
+ $requirements = [
+ '_access' => 'TRUE',
+ ];
+
+ // Only specify route requirements if the default permission exists. For any
+ // more advanced route definition, resource plugins extending this base
+ // class must override this method.
+ $permission = "restful $lower_method $this->pluginId";
+ if (isset($this->permissions()[$permission])) {
+ $requirements['_permission'] = $permission;
+ }
+
+ return $requirements;
}
}
diff --git a/core/modules/rest/src/Plugin/ResourceInterface.php b/core/modules/rest/src/Plugin/ResourceInterface.php
index 0bc2bfb..7e92c57 100644
--- a/core/modules/rest/src/Plugin/ResourceInterface.php
+++ b/core/modules/rest/src/Plugin/ResourceInterface.php
@@ -33,6 +33,10 @@ interface ResourceInterface extends PluginInspectionInterface {
* A resource plugin can define a set of user permissions that are used on the
* routes for this resource or for other purposes.
*
+ * It is not required for a resource plugin to specify permissions: if they
+ * have their own access control mechanism, they can use that, and return the
+ * empty array.
+ *
* @return array
* The permission array.
*/
diff --git a/core/modules/rest/src/Plugin/rest/resource/EntityResource.php b/core/modules/rest/src/Plugin/rest/resource/EntityResource.php
index 8b96940..5cf42dd 100644
--- a/core/modules/rest/src/Plugin/rest/resource/EntityResource.php
+++ b/core/modules/rest/src/Plugin/rest/resource/EntityResource.php
@@ -6,6 +6,7 @@ use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
+use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\rest\Plugin\ResourceBase;
@@ -43,6 +44,13 @@ class EntityResource extends ResourceBase implements DependentPluginInterface {
protected $entityType;
/**
+ * The config factory.
+ *
+ * @var \Drupal\Core\Config\ConfigFactoryInterface
+ */
+ protected $configFactory;
+
+ /**
* Constructs a Drupal\rest\Plugin\rest\resource\EntityResource object.
*
* @param array $configuration
@@ -57,10 +65,13 @@ class EntityResource extends ResourceBase implements DependentPluginInterface {
* The available serialization formats.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
+ * @param \Drupal\Core\Config\ConfigFactoryInterface
+ * The config factory.
*/
- public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, $serializer_formats, LoggerInterface $logger) {
+ public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, $serializer_formats, LoggerInterface $logger, ConfigFactoryInterface $config_factory) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->entityType = $entity_type_manager->getDefinition($plugin_definition['entity_type']);
+ $this->configFactory = $config_factory;
}
/**
@@ -73,7 +84,8 @@ class EntityResource extends ResourceBase implements DependentPluginInterface {
$plugin_definition,
$container->get('entity_type.manager'),
$container->getParameter('serializer.formats'),
- $container->get('logger.factory')->get('rest')
+ $container->get('logger.factory')->get('rest'),
+ $container->get('config.factory')
);
}
@@ -300,6 +312,21 @@ class EntityResource extends ResourceBase implements DependentPluginInterface {
/**
* {@inheritdoc}
*/
+ public function permissions() {
+ // @see https://www.drupal.org/node/2664780
+ if ($this->configFactory->get('rest.settings')->get('bc_entity_resource_permissions')) {
+ // The default Drupal 8.0.x and 8.1.x behavior.
+ return parent::permissions();
+ }
+ else {
+ // The default Drupal 8.2.x behavior.
+ return [];
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
protected function getBaseRoute($canonical_path, $method) {
$route = parent::getBaseRoute($canonical_path, $method);
$definition = $this->getPluginDefinition();
diff --git a/core/modules/rest/src/RequestHandler.php b/core/modules/rest/src/RequestHandler.php
index d75cfbb..088dca2 100644
--- a/core/modules/rest/src/RequestHandler.php
+++ b/core/modules/rest/src/RequestHandler.php
@@ -12,7 +12,6 @@ use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\SerializerInterface;
@@ -131,17 +130,7 @@ class RequestHandler implements ContainerAwareInterface, ContainerInjectionInter
// Invoke the operation on the resource plugin.
$format = $this->getResponseFormat($route_match, $request);
- try {
- $response = call_user_func_array(array($resource, $method), array_merge($parameters, array($unserialized, $request)));
- }
- catch (HttpException $e) {
- $error['error'] = $e->getMessage();
- $content = $serializer->serialize($error, $format);
- // Add the default content type, but only if the headers from the
- // exception have not specified it already.
- $headers = $e->getHeaders() + array('Content-Type' => $request->getMimeType($format));
- return new Response($content, $e->getStatusCode(), $headers);
- }
+ $response = call_user_func_array(array($resource, $method), array_merge($parameters, array($unserialized, $request)));
return $response instanceof ResourceResponseInterface ?
$this->renderResponse($request, $response, $serializer, $format, $resource_config) :
diff --git a/core/modules/rest/src/Tests/AuthTest.php b/core/modules/rest/src/Tests/AuthTest.php
index e9fb7d7..9f4224f 100644
--- a/core/modules/rest/src/Tests/AuthTest.php
+++ b/core/modules/rest/src/Tests/AuthTest.php
@@ -43,7 +43,6 @@ class AuthTest extends RESTTestBase {
// resources via the REST API, but the request is authenticated
// with session cookies.
$permissions = $this->entityPermissions($entity_type, 'view');
- $permissions[] = 'restful get entity:' . $entity_type;
$account = $this->drupalCreateUser($permissions);
$this->drupalLogin($account);
diff --git a/core/modules/rest/src/Tests/CreateTest.php b/core/modules/rest/src/Tests/CreateTest.php
index d71b9e4..8c7db07 100644
--- a/core/modules/rest/src/Tests/CreateTest.php
+++ b/core/modules/rest/src/Tests/CreateTest.php
@@ -5,6 +5,7 @@ namespace Drupal\rest\Tests;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityInterface;
+use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
@@ -49,8 +50,6 @@ class CreateTest extends RESTTestBase {
// Get the necessary user permissions to create the current entity type.
$permissions = $this->entityPermissions($entity_type, 'create');
- // POST method must be allowed for the current entity type.
- $permissions[] = 'restful post entity:' . $entity_type;
// Create the user.
$account = $this->drupalCreateUser($permissions);
@@ -77,7 +76,11 @@ class CreateTest extends RESTTestBase {
/**
* Ensure that an entity cannot be created without the restful permission.
*/
- public function testCreateWithoutPermission() {
+ public function testCreateWithoutPermissionIfBcFlagIsOn() {
+ $rest_settings = $this->config('rest.settings');
+ $rest_settings->set('bc_entity_resource_permissions', TRUE)
+ ->save(TRUE);
+
$entity_type = 'entity_test';
// Enables the REST service for 'entity_test' entity type.
$this->enableService('entity:' . $entity_type, 'POST');
@@ -96,6 +99,14 @@ class CreateTest extends RESTTestBase {
$this->httpRequest('entity/' . $entity_type, 'POST', $serialized, $this->defaultMimeType);
$this->assertResponse(403);
$this->assertFalse(EntityTest::loadMultiple(), 'No entity has been created in the database.');
+
+ // Create a user with the 'restful post entity:entity_test permission and
+ // try again. This time, we should be able to create an entity.
+ $permissions[] = 'restful post entity:' . $entity_type;
+ $account = $this->drupalCreateUser($permissions);
+ $this->drupalLogin($account);
+ $this->httpRequest('entity/' . $entity_type, 'POST', $serialized, $this->defaultMimeType);
+ $this->assertResponse(201);
}
/**
@@ -331,8 +342,6 @@ class CreateTest extends RESTTestBase {
$accounts = array();
// Get the necessary user permissions for the current $entity_type creation.
$permissions = $this->entityPermissions($entity_type, 'create');
- // POST method must be allowed for the current entity type.
- $permissions[] = 'restful post entity:' . $entity_type;
// Create user without administrative permissions.
$accounts[] = $this->drupalCreateUser($permissions);
// Add administrative permissions for nodes and users.
@@ -440,14 +449,14 @@ class CreateTest extends RESTTestBase {
$entity->set('uuid', $this->randomMachineName(129));
$invalid_serialized = $this->serializer->serialize($entity, $this->defaultFormat, $context);
- $response = $this->httpRequest('entity/' . $entity_type, 'POST', $invalid_serialized, $this->defaultMimeType);
+ $response = $this->httpRequest(Url::fromRoute("rest.entity.$entity_type.POST")->setRouteParameter('_format', $this->defaultFormat), 'POST', $invalid_serialized, $this->defaultMimeType);
// Unprocessable Entity as response.
$this->assertResponse(422);
// Verify that the text of the response is correct.
$error = Json::decode($response);
- $this->assertEqual($error['error'], "Unprocessable Entity: validation failed.\nuuid.0.value: <em class=\"placeholder\">UUID</em>: may not be longer than 128 characters.\n");
+ $this->assertEqual($error['message'], "Unprocessable Entity: validation failed.\nuuid.0.value: <em class=\"placeholder\">UUID</em>: may not be longer than 128 characters.\n");
}
/**
diff --git a/core/modules/rest/src/Tests/CsrfTest.php b/core/modules/rest/src/Tests/CsrfTest.php
index b23e23d..f1c41a6 100644
--- a/core/modules/rest/src/Tests/CsrfTest.php
+++ b/core/modules/rest/src/Tests/CsrfTest.php
@@ -43,7 +43,6 @@ class CsrfTest extends RESTTestBase {
// Create a user account that has the required permissions to create
// resources via the REST API.
$permissions = $this->entityPermissions($this->testEntityType, 'create');
- $permissions[] = 'restful post entity:' . $this->testEntityType;
$this->account = $this->drupalCreateUser($permissions);
// Serialize an entity to a string to use in the content body of the POST
diff --git a/core/modules/rest/src/Tests/DeleteTest.php b/core/modules/rest/src/Tests/DeleteTest.php
index 7de3fb4..60302bc 100644
--- a/core/modules/rest/src/Tests/DeleteTest.php
+++ b/core/modules/rest/src/Tests/DeleteTest.php
@@ -31,7 +31,6 @@ class DeleteTest extends RESTTestBase {
// Create a user account that has the required permissions to delete
// resources via the REST API.
$permissions = $this->entityPermissions($entity_type, 'delete');
- $permissions[] = 'restful delete entity:' . $entity_type;
$account = $this->drupalCreateUser($permissions);
$this->drupalLogin($account);
diff --git a/core/modules/rest/src/Tests/NodeTest.php b/core/modules/rest/src/Tests/NodeTest.php
index dbdeaec..95dc475 100644
--- a/core/modules/rest/src/Tests/NodeTest.php
+++ b/core/modules/rest/src/Tests/NodeTest.php
@@ -32,7 +32,6 @@ class NodeTest extends RESTTestBase {
protected function enableNodeConfiguration($method, $operation) {
$this->enableService('entity:node', $method);
$permissions = $this->entityPermissions('node', $operation);
- $permissions[] = 'restful ' . strtolower($method) . ' entity:node';
$account = $this->drupalCreateUser($permissions);
$this->drupalLogin($account);
}
diff --git a/core/modules/rest/src/Tests/PageCacheTest.php b/core/modules/rest/src/Tests/PageCacheTest.php
index d4b09e9..66e57f5 100644
--- a/core/modules/rest/src/Tests/PageCacheTest.php
+++ b/core/modules/rest/src/Tests/PageCacheTest.php
@@ -48,10 +48,6 @@ class PageCacheTest extends RESTTestBase {
$this->enableService('entity:entity_test', 'POST');
$permissions = [
'administer entity_test content',
- 'restful post entity:entity_test',
- 'restful get entity:entity_test',
- 'restful patch entity:entity_test',
- 'restful delete entity:entity_test',
];
$account = $this->drupalCreateUser($permissions);
diff --git a/core/modules/rest/src/Tests/ReadTest.php b/core/modules/rest/src/Tests/ReadTest.php
index 99ebbaa..dc6f574 100644
--- a/core/modules/rest/src/Tests/ReadTest.php
+++ b/core/modules/rest/src/Tests/ReadTest.php
@@ -48,7 +48,6 @@ class ReadTest extends RESTTestBase {
// Create a user account that has the required permissions to read
// resources via the REST API.
$permissions = $this->entityPermissions($entity_type, 'view');
- $permissions[] = 'restful get entity:' . $entity_type;
$account = $this->drupalCreateUser($permissions);
$this->drupalLogin($account);
@@ -123,12 +122,6 @@ class ReadTest extends RESTTestBase {
$data = Json::decode($response);
$this->assertFalse(isset($data['field_test_text']), 'Field access protected field is not visible in the response.');
}
-
- // Try to read an entity without proper permissions.
- $this->drupalLogout();
- $response = $this->httpRequest($this->getReadUrl($entity), 'GET');
- $this->assertResponse(403);
- $this->assertIdentical('{"message":""}', $response);
}
// Try to read a resource, the user entity, which is not REST API enabled.
$account = $this->drupalCreateUser();
@@ -155,7 +148,6 @@ class ReadTest extends RESTTestBase {
// Create a user account that has the required permissions to read
// resources via the REST API.
$permissions = $this->entityPermissions('node', 'view');
- $permissions[] = 'restful get entity:node';
$account = $this->drupalCreateUser($permissions);
$this->drupalLogin($account);
diff --git a/core/modules/rest/src/Tests/Update/EntityResourcePermissionsUpdateTest.php b/core/modules/rest/src/Tests/Update/EntityResourcePermissionsUpdateTest.php
new file mode 100644
index 0000000..989159e
--- /dev/null
+++ b/core/modules/rest/src/Tests/Update/EntityResourcePermissionsUpdateTest.php
@@ -0,0 +1,56 @@
+<?php
+
+namespace Drupal\rest\Tests\Update;
+
+use Drupal\system\Tests\Update\UpdatePathTestBase;
+
+/**
+ * Tests that existing sites continue to use permissions for EntityResource.
+ *
+ * @see https://www.drupal.org/node/2664780
+ *
+ * @group rest
+ */
+class EntityResourcePermissionsUpdateTest extends UpdatePathTestBase {
+
+ /**
+ * {@inheritdoc}
+ */
+ protected static $modules = ['rest', 'serialization'];
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setDatabaseDumpFiles() {
+ $this->databaseDumpFiles = [
+ __DIR__ . '/../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
+ __DIR__ . '/../../../../rest/tests/fixtures/update/drupal-8.rest-rest_update_8203.php',
+ ];
+ }
+
+ /**
+ * Tests rest_update_8203().
+ */
+ public function testBcEntityResourcePermissionSettingAdded() {
+ $permission_handler = $this->container->get('user.permissions');
+
+ $is_rest_resource_permission = function ($permission) {
+ return $permission['provider'] === 'rest' && (string) $permission['title'] !== 'Administer REST resource configuration';
+ };
+
+ // Make sure we have the expected values before the update.
+ $rest_settings = $this->config('rest.settings');
+ $this->assertFalse(array_key_exists('bc_entity_resource_permissions', $rest_settings->getRawData()));
+ $this->assertEqual([], array_filter($permission_handler->getPermissions(), $is_rest_resource_permission));
+
+ $this->runUpdates();
+
+ // Make sure we have the expected values after the update.
+ $rest_settings = $this->config('rest.settings');
+ $this->assertTrue(array_key_exists('bc_entity_resource_permissions', $rest_settings->getRawData()));
+ $this->assertTrue($rest_settings->get('bc_entity_resource_permissions'));
+ $rest_permissions = array_keys(array_filter($permission_handler->getPermissions(), $is_rest_resource_permission));
+ $this->assertEqual(['restful delete entity:node', 'restful get entity:node', 'restful patch entity:node', 'restful post entity:node'], $rest_permissions);
+ }
+
+}
diff --git a/core/modules/rest/src/Tests/UpdateTest.php b/core/modules/rest/src/Tests/UpdateTest.php
index dcab1ff..2f80304 100644
--- a/core/modules/rest/src/Tests/UpdateTest.php
+++ b/core/modules/rest/src/Tests/UpdateTest.php
@@ -46,7 +46,6 @@ class UpdateTest extends RESTTestBase {
// Create a user account that has the required permissions to create
// resources via the REST API.
$permissions = $this->entityPermissions($entity_type, 'update');
- $permissions[] = 'restful patch entity:' . $entity_type;
$account = $this->drupalCreateUser($permissions);
$this->drupalLogin($account);
@@ -176,10 +175,10 @@ class UpdateTest extends RESTTestBase {
// Send a UUID that is too long.
$entity->set('uuid', $this->randomMachineName(129));
$invalid_serialized = $serializer->serialize($entity, $this->defaultFormat, $context);
- $response = $this->httpRequest($entity->urlInfo(), 'PATCH', $invalid_serialized, $this->defaultMimeType);
+ $response = $this->httpRequest($entity->toUrl()->setRouteParameter('_format', $this->defaultFormat), 'PATCH', $invalid_serialized, $this->defaultMimeType);
$this->assertResponse(422);
$error = Json::decode($response);
- $this->assertEqual($error['error'], "Unprocessable Entity: validation failed.\nuuid.0.value: <em class=\"placeholder\">UUID</em>: may not be longer than 128 characters.\n");
+ $this->assertEqual($error['message'], "Unprocessable Entity: validation failed.\nuuid.0.value: <em class=\"placeholder\">UUID</em>: may not be longer than 128 characters.\n");
// Try to update an entity without proper permissions.
$this->drupalLogout();
@@ -202,7 +201,6 @@ class UpdateTest extends RESTTestBase {
// Enables the REST service for 'user' entity type.
$this->enableService('entity:' . $entity_type, 'PATCH');
$permissions = $this->entityPermissions($entity_type, 'update');
- $permissions[] = 'restful patch entity:' . $entity_type;
$account = $this->drupalCreateUser($permissions);
$account->set('mail', 'old-email@example.com');
$this->drupalLogin($account);
@@ -216,18 +214,18 @@ class UpdateTest extends RESTTestBase {
$context = ['account' => $account];
$normalized = $serializer->normalize($account, $this->defaultFormat, $context);
$serialized = $serializer->serialize($normalized, $this->defaultFormat, $context);
- $response = $this->httpRequest($account->urlInfo(), 'PATCH', $serialized, $this->defaultMimeType);
+ $response = $this->httpRequest($account->toUrl()->setRouteParameter('_format', $this->defaultFormat), 'PATCH', $serialized, $this->defaultMimeType);
$this->assertResponse(422);
$error = Json::decode($response);
- $this->assertEqual($error['error'], "Unprocessable Entity: validation failed.\nmail: Your current password is missing or incorrect; it's required to change the <em class=\"placeholder\">Email</em>.\n");
+ $this->assertEqual($error['message'], "Unprocessable Entity: validation failed.\nmail: Your current password is missing or incorrect; it's required to change the <em class=\"placeholder\">Email</em>.\n");
// Try and send the new email with a password.
$normalized['pass'][0]['existing'] = 'wrong';
$serialized = $serializer->serialize($normalized, $this->defaultFormat, $context);
- $response = $this->httpRequest($account->urlInfo(), 'PATCH', $serialized, $this->defaultMimeType);
+ $response = $this->httpRequest($account->toUrl()->setRouteParameter('_format', $this->defaultFormat), 'PATCH', $serialized, $this->defaultMimeType);
$this->assertResponse(422);
$error = Json::decode($response);
- $this->assertEqual($error['error'], "Unprocessable Entity: validation failed.\nmail: Your current password is missing or incorrect; it's required to change the <em class=\"placeholder\">Email</em>.\n");
+ $this->assertEqual($error['message'], "Unprocessable Entity: validation failed.\nmail: Your current password is missing or incorrect; it's required to change the <em class=\"placeholder\">Email</em>.\n");
// Try again with the password.
$normalized['pass'][0]['existing'] = $account->pass_raw;
@@ -240,10 +238,10 @@ class UpdateTest extends RESTTestBase {
$normalized = $serializer->normalize($account, $this->defaultFormat, $context);
$normalized['pass'][0]['value'] = $new_password;
$serialized = $serializer->serialize($normalized, $this->defaultFormat, $context);
- $response = $this->httpRequest($account->urlInfo(), 'PATCH', $serialized, $this->defaultMimeType);
+ $response = $this->httpRequest($account->toUrl()->setRouteParameter('_format', $this->defaultFormat), 'PATCH', $serialized, $this->defaultMimeType);
$this->assertResponse(422);
$error = Json::decode($response);
- $this->assertEqual($error['error'], "Unprocessable Entity: validation failed.\npass: Your current password is missing or incorrect; it's required to change the <em class=\"placeholder\">Password</em>.\n");
+ $this->assertEqual($error['message'], "Unprocessable Entity: validation failed.\npass: Your current password is missing or incorrect; it's required to change the <em class=\"placeholder\">Password</em>.\n");
// Try again with the password.
$normalized['pass'][0]['existing'] = $account->pass_raw;
@@ -264,7 +262,6 @@ class UpdateTest extends RESTTestBase {
// Enables the REST service for 'comment' entity type.
$this->enableService('entity:' . $entity_type, 'PATCH', ['hal_json', 'json']);
$permissions = $this->entityPermissions($entity_type, 'update');
- $permissions[] = 'restful patch entity:' . $entity_type;
$account = $this->drupalCreateUser($permissions);
$account->set('mail', 'old-email@example.com');
$this->drupalLogin($account);
@@ -336,7 +333,7 @@ class UpdateTest extends RESTTestBase {
protected function patchEntity(EntityInterface $entity, array $read_only_fields, AccountInterface $account, $format, $mime_type) {
$serializer = $this->container->get('serializer');
- $url = $entity->toUrl();
+ $url = $entity->toUrl()->setRouteParameter('_format', $this->defaultFormat);
$context = ['account' => $account];
// Certain fields are always read-only, others this user simply is not
// allowed to modify. For all of them, ensure they are not serialized, else
@@ -359,7 +356,7 @@ class UpdateTest extends RESTTestBase {
$this->httpRequest($url, 'PATCH', $serialized, $mime_type);
$this->assertResponse(403);
- $this->assertResponseBody('{"error":"Access denied on updating field \'' . $field . '\'."}');
+ $this->assertResponseBody('{"message":"Access denied on updating field \\u0027' . $field . '\\u0027."}');
if ($format === 'hal_json') {
// We've just tried with this read-only field, now unset it.
diff --git a/core/modules/rest/tests/fixtures/update/drupal-8.rest-rest_update_8203.php b/core/modules/rest/tests/fixtures/update/drupal-8.rest-rest_update_8203.php
new file mode 100644
index 0000000..3ce8b6a
--- /dev/null
+++ b/core/modules/rest/tests/fixtures/update/drupal-8.rest-rest_update_8203.php
@@ -0,0 +1,63 @@
+<?php
+
+/**
+ * @file
+ * Contains database additions to drupal-8.bare.standard.php.gz for testing the
+ * upgrade path of rest_update_8203().
+ */
+
+use Drupal\Core\Database\Database;
+
+$connection = Database::getConnection();
+
+// Set the schema version.
+$connection->insert('key_value')
+ ->fields([
+ 'collection' => 'system.schema',
+ 'name' => 'rest',
+ 'value' => 'i:8000;',
+ ])
+ ->fields([
+ 'collection' => 'system.schema',
+ 'name' => 'serialization',
+ 'value' => 'i:8000;',
+ ])
+ ->execute();
+
+// Update core.extension.
+$extensions = $connection->select('config')
+ ->fields('config', ['data'])
+ ->condition('collection', '')
+ ->condition('name', 'core.extension')
+ ->execute()
+ ->fetchField();
+$extensions = unserialize($extensions);
+$extensions['module']['rest'] = 8000;
+$extensions['module']['serialization'] = 8000;
+$connection->update('config')
+ ->fields([
+ 'data' => serialize($extensions),
+ ])
+ ->condition('collection', '')
+ ->condition('name', 'core.extension')
+ ->execute();
+
+// Install the rest configuration.
+$config = [
+ 'resources' => [
+ 'entity:node' => [
+ 'GET' => [
+ 'supported_formats' => ['json'],
+ 'supported_auth' => ['basic_auth'],
+ ],
+ ],
+ ],
+ 'link_domain' => '~',
+];
+$data = $connection->insert('config')
+ ->fields([
+ 'name' => 'rest.settings',
+ 'data' => serialize($config),
+ 'collection' => ''
+ ])
+ ->execute();
diff --git a/core/modules/system/src/Tests/System/ResponseGeneratorTest.php b/core/modules/system/src/Tests/System/ResponseGeneratorTest.php
index d2f8f5f..f54c651 100644
--- a/core/modules/system/src/Tests/System/ResponseGeneratorTest.php
+++ b/core/modules/system/src/Tests/System/ResponseGeneratorTest.php
@@ -26,7 +26,6 @@ class ResponseGeneratorTest extends RESTTestBase {
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
$permissions = $this->entityPermissions('node', 'view');
- $permissions[] = 'restful get entity:node';
$account = $this->drupalCreateUser($permissions);
$this->drupalLogin($account);
}