You are here

public function UserTest::testPatchSecurityOtherUser in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/jsonapi/tests/src/Functional/UserTest.php \Drupal\Tests\jsonapi\Functional\UserTest::testPatchSecurityOtherUser()

Tests PATCHing security-sensitive base fields to change other users.

File

core/modules/jsonapi/tests/src/Functional/UserTest.php, line 323

Class

UserTest
JSON:API integration test for the "User" content entity type.

Namespace

Drupal\Tests\jsonapi\Functional

Code

public function testPatchSecurityOtherUser() {

  // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.
  $url = Url::fromRoute(sprintf('jsonapi.user--user.individual'), [
    'entity' => $this->account
      ->uuid(),
  ]);

  /* $url = $this->account->toUrl('jsonapi'); */
  $original_normalization = $this
    ->normalize($this->account, $url);

  // Since this test must be performed by the user that is being modified,
  // we must use $this->account, not $this->entity.
  $request_options = [];
  $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
  $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
  $request_options = NestedArray::mergeDeep($request_options, $this
    ->getAuthenticationRequestOptions());
  $normalization = $original_normalization;
  $normalization['data']['attributes']['mail'] = 'new-email@example.com';
  $request_options[RequestOptions::BODY] = Json::encode($normalization);

  // DX: 405 when read-only mode is enabled.
  $response = $this
    ->request('PATCH', $url, $request_options);
  $this
    ->assertResourceErrorResponse(405, sprintf("JSON:API is configured to accept only read operations. Site administrators can configure this at %s.", Url::fromUri('base:/admin/config/services/jsonapi')
    ->setAbsolute()
    ->toString(TRUE)
    ->getGeneratedUrl()), $url, $response);
  $this
    ->assertSame([
    'GET',
  ], $response
    ->getHeader('Allow'));
  $this
    ->config('jsonapi.settings')
    ->set('read_only', FALSE)
    ->save(TRUE);

  // Try changing user 1's email.
  $user1 = $original_normalization;
  $user1['data']['attributes']['mail'] = 'another_email_address@example.com';
  $user1['data']['attributes']['uid'] = 1;
  $user1['data']['attributes']['name'] = 'another_user_name';
  $user1['data']['attributes']['pass']['existing'] = $this->account->passRaw;
  $request_options[RequestOptions::BODY] = Json::encode($user1);
  $response = $this
    ->request('PATCH', $url, $request_options);

  // Ensure the email address has not changed.
  $this
    ->assertEquals('admin@example.com', $this->entityStorage
    ->loadUnchanged(1)
    ->getEmail());
  $this
    ->assertResourceErrorResponse(403, 'The current user is not allowed to PATCH the selected field (uid). The entity ID cannot be changed.', $url, $response, '/data/attributes/uid');
}