Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / user / tests / src / Kernel / UserValidationTest.php
1 <?php
2
3 namespace Drupal\Tests\user\Kernel;
4
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Language\Language;
7 use Drupal\Core\Render\Element\Email;
8 use Drupal\KernelTests\KernelTestBase;
9 use Drupal\user\Entity\Role;
10 use Drupal\user\Entity\User;
11
12 /**
13  * Verify that user validity checks behave as designed.
14  *
15  * @group user
16  */
17 class UserValidationTest extends KernelTestBase {
18
19   /**
20    * Modules to enable.
21    *
22    * @var array
23    */
24   public static $modules = ['field', 'user', 'system'];
25
26   /**
27    * {@inheritdoc}
28    */
29   protected function setUp() {
30     parent::setUp();
31     $this->installEntitySchema('user');
32     $this->installSchema('system', ['sequences']);
33
34     // Make sure that the default roles exist.
35     $this->installConfig(['user']);
36
37   }
38
39   /**
40    * Tests user name validation.
41    */
42   public function testUsernames() {
43     $test_cases = [
44       // '<username>' => ['<description>', 'assert<testName>'].
45       'foo'                    => ['Valid username', 'assertNull'],
46       'FOO'                    => ['Valid username', 'assertNull'],
47       'Foo O\'Bar'             => ['Valid username', 'assertNull'],
48       'foo@bar'                => ['Valid username', 'assertNull'],
49       'foo@example.com'        => ['Valid username', 'assertNull'],
50       // invalid domains are allowed in usernames.
51       'foo@-example.com'       => ['Valid username', 'assertNull'],
52       'þòøÇߪř€'               => ['Valid username', 'assertNull'],
53       // '+' symbol is allowed.
54       'foo+bar'                => ['Valid username', 'assertNull'],
55       // runes.
56       'ᚠᛇᚻ᛫ᛒᛦᚦ'                => ['Valid UTF8 username', 'assertNull'],
57       ' foo'                   => ['Invalid username that starts with a space', 'assertNotNull'],
58       'foo '                   => ['Invalid username that ends with a space', 'assertNotNull'],
59       'foo  bar'               => ['Invalid username that contains 2 spaces \'&nbsp;&nbsp;\'', 'assertNotNull'],
60       ''                       => ['Invalid empty username', 'assertNotNull'],
61       'foo/'                   => ['Invalid username containing invalid chars', 'assertNotNull'],
62       // NULL.
63       'foo' . chr(0) . 'bar'   => ['Invalid username containing chr(0)', 'assertNotNull'],
64       // CR.
65       'foo' . chr(13) . 'bar'  => ['Invalid username containing chr(13)', 'assertNotNull'],
66       str_repeat('x', USERNAME_MAX_LENGTH + 1) => ['Invalid excessively long username', 'assertNotNull'],
67     ];
68     foreach ($test_cases as $name => $test_case) {
69       list($description, $test) = $test_case;
70       $result = user_validate_name($name);
71       $this->$test($result, $description . ' (' . $name . ')');
72     }
73   }
74
75   /**
76    * Runs entity validation checks.
77    */
78   public function testValidation() {
79     $user = User::create([
80       'name' => 'test',
81       'mail' => 'test@example.com',
82     ]);
83     $violations = $user->validate();
84     $this->assertEqual(count($violations), 0, 'No violations when validating a default user.');
85
86     // Only test one example invalid name here, the rest is already covered in
87     // the testUsernames() method in this class.
88     $name = $this->randomMachineName(61);
89     $user->set('name', $name);
90     $violations = $user->validate();
91     $this->assertEqual(count($violations), 1, 'Violation found when name is too long.');
92     $this->assertEqual($violations[0]->getPropertyPath(), 'name');
93     $this->assertEqual($violations[0]->getMessage(), t('The username %name is too long: it must be %max characters or less.', ['%name' => $name, '%max' => 60]));
94
95     // Create a second test user to provoke a name collision.
96     $user2 = User::create([
97       'name' => 'existing',
98       'mail' => 'existing@example.com',
99     ]);
100     $user2->save();
101     $user->set('name', 'existing');
102     $violations = $user->validate();
103     $this->assertEqual(count($violations), 1, 'Violation found on name collision.');
104     $this->assertEqual($violations[0]->getPropertyPath(), 'name');
105     $this->assertEqual($violations[0]->getMessage(), t('The username %name is already taken.', ['%name' => 'existing']));
106
107     // Make the name valid.
108     $user->set('name', $this->randomMachineName());
109
110     $user->set('mail', 'invalid');
111     $violations = $user->validate();
112     $this->assertEqual(count($violations), 1, 'Violation found when email is invalid');
113     $this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value');
114     $this->assertEqual($violations[0]->getMessage(), t('This value is not a valid email address.'));
115
116     $mail = $this->randomMachineName(Email::EMAIL_MAX_LENGTH - 11) . '@example.com';
117     $user->set('mail', $mail);
118     $violations = $user->validate();
119     // @todo There are two violations because EmailItem::getConstraints()
120     //   overlaps with the implicit constraint of the 'email' property type used
121     //   in EmailItem::propertyDefinitions(). Resolve this in
122     //   https://www.drupal.org/node/2023465.
123     $this->assertEqual(count($violations), 2, 'Violations found when email is too long');
124     $this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value');
125     $this->assertEqual($violations[0]->getMessage(), t('%name: the email address can not be longer than @max characters.', ['%name' => $user->get('mail')->getFieldDefinition()->getLabel(), '@max' => Email::EMAIL_MAX_LENGTH]));
126     $this->assertEqual($violations[1]->getPropertyPath(), 'mail.0.value');
127     $this->assertEqual($violations[1]->getMessage(), t('This value is not a valid email address.'));
128
129     // Provoke an email collision with an existing user.
130     $user->set('mail', 'existing@example.com');
131     $violations = $user->validate();
132     $this->assertEqual(count($violations), 1, 'Violation found when email already exists.');
133     $this->assertEqual($violations[0]->getPropertyPath(), 'mail');
134     $this->assertEqual($violations[0]->getMessage(), t('The email address %mail is already taken.', ['%mail' => 'existing@example.com']));
135     $user->set('mail', NULL);
136     $violations = $user->validate();
137     $this->assertEqual(count($violations), 1, 'Email addresses may not be removed');
138     $this->assertEqual($violations[0]->getPropertyPath(), 'mail');
139     $this->assertEqual($violations[0]->getMessage(), t('@name field is required.', ['@name' => $user->getFieldDefinition('mail')->getLabel()]));
140     $user->set('mail', 'someone@example.com');
141
142     $user->set('timezone', $this->randomString(33));
143     $this->assertLengthViolation($user, 'timezone', 32, 2, 1);
144     $user->set('timezone', 'invalid zone');
145     $this->assertAllowedValuesViolation($user, 'timezone');
146     $user->set('timezone', NULL);
147
148     $user->set('init', 'invalid');
149     $violations = $user->validate();
150     $this->assertEqual(count($violations), 1, 'Violation found when init email is invalid');
151     $user->set('init', NULL);
152
153     $user->set('langcode', 'invalid');
154     $this->assertAllowedValuesViolation($user, 'langcode');
155     $user->set('langcode', NULL);
156
157     // Only configurable langcodes are allowed for preferred languages.
158     $user->set('preferred_langcode', Language::LANGCODE_NOT_SPECIFIED);
159     $this->assertAllowedValuesViolation($user, 'preferred_langcode');
160     $user->set('preferred_langcode', NULL);
161
162     $user->set('preferred_admin_langcode', Language::LANGCODE_NOT_SPECIFIED);
163     $this->assertAllowedValuesViolation($user, 'preferred_admin_langcode');
164     $user->set('preferred_admin_langcode', NULL);
165
166     Role::create(['id' => 'role1'])->save();
167     Role::create(['id' => 'role2'])->save();
168
169     // Test cardinality of user roles.
170     $user = User::create([
171       'name' => 'role_test',
172       'mail' => 'test@example.com',
173       'roles' => ['role1', 'role2'],
174     ]);
175     $violations = $user->validate();
176     $this->assertEqual(count($violations), 0);
177
178     $user->roles[1]->target_id = 'unknown_role';
179     $violations = $user->validate();
180     $this->assertEqual(count($violations), 1);
181     $this->assertEqual($violations[0]->getPropertyPath(), 'roles.1.target_id');
182     $this->assertEqual($violations[0]->getMessage(), t('The referenced entity (%entity_type: %name) does not exist.', ['%entity_type' => 'user_role', '%name' => 'unknown_role']));
183   }
184
185   /**
186    * Verifies that a length violation exists for the given field.
187    *
188    * @param \Drupal\core\Entity\EntityInterface $entity
189    *   The entity object to validate.
190    * @param string $field_name
191    *   The field that violates the maximum length.
192    * @param int $length
193    *   Number of characters that was exceeded.
194    * @param int $count
195    *   (optional) The number of expected violations. Defaults to 1.
196    * @param int $expected_index
197    *   (optional) The index at which to expect the violation. Defaults to 0.
198    */
199   protected function assertLengthViolation(EntityInterface $entity, $field_name, $length, $count = 1, $expected_index = 0) {
200     $violations = $entity->validate();
201     $this->assertEqual(count($violations), $count, "Violation found when $field_name is too long.");
202     $this->assertEqual($violations[$expected_index]->getPropertyPath(), "$field_name.0.value");
203     $field_label = $entity->get($field_name)->getFieldDefinition()->getLabel();
204     $this->assertEqual($violations[$expected_index]->getMessage(), t('%name: may not be longer than @max characters.', ['%name' => $field_label, '@max' => $length]));
205   }
206
207   /**
208    * Verifies that a AllowedValues violation exists for the given field.
209    *
210    * @param \Drupal\core\Entity\EntityInterface $entity
211    *   The entity object to validate.
212    * @param string $field_name
213    *   The name of the field to verify.
214    */
215   protected function assertAllowedValuesViolation(EntityInterface $entity, $field_name) {
216     $violations = $entity->validate();
217     $this->assertEqual(count($violations), 1, "Allowed values violation for $field_name found.");
218     $this->assertEqual($violations[0]->getPropertyPath(), "$field_name.0.value");
219     $this->assertEqual($violations[0]->getMessage(), t('The value you selected is not a valid choice.'));
220   }
221
222 }