Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 14 additions & 15 deletions src/Authentication/Passwords/NothingPersonalValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
*/
public function check(string $password, ?User $user = null): Result
{
$password = strtolower($password);
$password = mb_strtolower($password);
Comment thread
neznaika0 marked this conversation as resolved.
Resolved

if ($valid = $this->isNotPersonal($password, $user)) {
$valid = $this->isNotSimilar($password, $user);
Expand All @@ -46,8 +46,6 @@
}

/**
* isNotPersonal()
*
* Looks for personal information in a password. The personal info used
* comes from CodeIgniter\Shield\Entities\User properties username and email.
*
Expand All @@ -59,13 +57,12 @@
*
* public $personalFields = ['firstname', 'lastname'];
*
* isNotPersonal() returns true if no personal information can be found, or false
* if such info is found.
* @return bool `true` if no personal information can be found, or `false` if such info is found.
*/
protected function isNotPersonal(string $password, ?User $user): bool
{
$userName = strtolower($user->username ?? '');
$email = strtolower($user->email);
$userName = mb_strtolower($user->username ?? '');
$email = mb_strtolower($user->email ?? '');
$valid = true;

// The most obvious transgressions
Expand Down Expand Up @@ -134,12 +131,12 @@
$haystacks = $this->strip_explode($password);

foreach ($haystacks as $haystack) {
if (in_array($haystack, $trivial, true) || mb_strlen($haystack, 'UTF-8') < 3) {
if (in_array($haystack, $trivial, true) || mb_strlen($haystack) < 3) {
continue; // ignore trivial words
}

foreach ($needles as $needle) {
if (in_array($needle, $trivial, true) || mb_strlen($needle, 'UTF-8') < 3) {
if (in_array($needle, $trivial, true) || mb_strlen($needle) < 3) {
continue;
}

Expand All @@ -152,6 +149,7 @@
}
}
}

if ($valid) {
return true;
}
Expand All @@ -163,17 +161,19 @@
}

/**
* notSimilar() uses $password and $userName to calculate a similarity value.
* Method uses password and username to calculate a similarity value.
* Similarity values equal to, or greater than CodeIgniter\Shield\Config::maxSimilarity
* are rejected for being too much alike and false is returned.
* Otherwise, true is returned,
*
* A $maxSimilarity value of 0 (zero) returns true without making a comparison.
* In other words, 0 (zero) turns off similarity testing.
*
* @return bool `true` if a similarity is found, or `false` if such info is found.
*/
protected function isNotSimilar(string $password, ?User $user): bool
{
if ($user->username === null) {
if (! $user instanceof User || $user->username === null) {
return true;
}

Expand All @@ -186,9 +186,10 @@
}

if ($maxSimilarity > 0) {
$userName = strtolower($user->username);
$userName = mb_strtolower($user->username);

similar_text($password, $userName, $similarity);

if ($similarity >= $maxSimilarity) {
$this->error = lang('Auth.errorPasswordTooSimilar');
$this->suggestion = lang('Auth.suggestPasswordTooSimilar');
Expand All @@ -201,16 +202,14 @@
}

/**
* strip_explode($str)
*
* Replaces all non-word characters and underscores in $str with a space.
* Then it explodes that result using the space for a delimiter.
*
* @return array<int, string>
*/
protected function strip_explode(string $str): array

Check warning on line 210 in src/Authentication/Passwords/NothingPersonalValidator.php

View workflow job for this annotation

GitHub Actions / Infection

Escaped Mutant for Mutator "ProtectedVisibility": @@ @@ * * @return array<int, string> */ - protected function strip_explode(string $str): array + private function strip_explode(string $str): array { $stripped = preg_replace('/[\W_]+/u', ' ', $str); $parts = explode(' ', trim((string) $stripped));
{
$stripped = preg_replace('/[\W_]+/', ' ', $str);
$stripped = preg_replace('/[\W_]+/u', ' ', $str);
$parts = explode(' ', trim((string) $stripped));

// If it's not already there put the untouched input at the top of the array
Expand Down
263 changes: 263 additions & 0 deletions tests/Unit/NothingPersonalValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -376,4 +376,267 @@ public static function provideCheckPasswordWithBadEmail(): iterable
],
];
}

#[DataProvider('provideIsolatedMethodIsNotPersonal')]
public function testIsolatedMethodIsNotPersonal(mixed ...$input): void
{
$user = null;
$fields = [];
// Password removes spaces inside `check()`, so we’ll duplicate it here
$password = mb_strtolower($input[0]);

if (is_array($input[1])) {
$user = new User($input[1]);
$fields = array_keys($input[1]);
}

$config = new Auth();
$config->personalFields = array_filter($fields, static fn ($val): bool => $val !== 'email' && $val !== 'username');
$validator = new NothingPersonalValidator($config);

$isNotPersonal = self::getPrivateMethodInvoker($validator, 'isNotPersonal');

/** @var bool */
$result = $isNotPersonal($password, $user);

$this->assertSame($input[2], $result);
}

#[DataProvider('provideIsolatedMethodIsNotPersonal')]
public function testCheckMultibyteMethodIsNotPersonal(mixed ...$input): void
{
$user = null;
$fields = [];

if (is_array($input[1])) {
$user = new User($input[1]);
$fields = array_keys($input[1]);
}

$config = new Auth();
$config->personalFields = array_filter($fields, static fn ($val): bool => $val !== 'email' && $val !== 'username');
$validator = new NothingPersonalValidator($config);

$result = $validator->check($input[0], $user);

$this->assertSame($input[2], $result->isOK());
}

public static function provideIsolatedMethodIsNotPersonal(): iterable
{
// @todo: strrev() doesn’t work with Unicode
// yield 'Password is equal to reversed username' => [
// 'ПеТьКа',
// [
// 'email' => 'аДмИн@СаЙт.Ру',
// 'username' => 'аКьТеП'
// ],
// false
// ];

yield 'Repeated words in the personal data' => [
'Никола',
[
'email' => 'Никола@никола.ру',
'username' => 'Никола Никола',
'lastname' => 'Никола Никола',
],
false,
];

yield 'Password is equal to username' => [
'ПаРоЛь',
[
'email' => 'админ@сайт.ру',
'username' => 'пАрОлЬ',
],
false,
];

yield 'Password is equal to email' => [
'аДмИн@СаЙт.Ру',
[
'email' => 'АдМиН@сАйТ.рУ',
'username' => 'Петя',
],
false,
];

yield 'Password contains the username' => [
'ПеТя-9000',
[
'email' => 'админ@сайт.ру',
'username' => 'пЕтЯ',
],
false,
];

yield 'Password contains the email' => [
'ПеТя-9000',
[
'email' => 'админ@петя.ру',
'username' => 'Пётр',
],
false,
];

yield 'Password contains the personal data' => [
'_ПеТр_9000',
[
'email' => 'админ@caйт.ру',
'username' => 'Пётр',
'lastname' => 'Петров',
],
false,
];

yield 'Empty password' => [
'',
[
'email' => 'админ@сайт.ру',
'username' => 'Петя',
],
true,
];

yield 'Only spaces in password' => [
' ',
[
'email' => 'админ@сайт.ру',
'username' => 'Петя',
],
true,
];

yield 'Password without user' => [
'_ПеТр_9000',
null,
true,
];
}

#[DataProvider('provideIsolatedMethodIsNotSimilar')]
public function testIsolatedMethodIsNotSimilar(mixed ...$input): void
{
$user = null;
// Password removes spaces inside `check()`, so we’ll duplicate it here
$password = mb_strtolower($input[0]);

if (is_array($input[1])) {
$user = new User($input[1]);
}

$config = new Auth();
$config->maxSimilarity = $input[2];
$validator = new NothingPersonalValidator($config);

$isNotSimilar = self::getPrivateMethodInvoker($validator, 'isNotSimilar');

/** @var bool */
$result = $isNotSimilar($password, $user);

$this->assertSame($input[3], $result);
}

public static function provideIsolatedMethodIsNotSimilar(): iterable
{
yield 'Same password and username (similar > 1%)' => [
'ПёТр',
[
'email' => 'петя@caйт.ру',
'username' => 'ПёТр',
],
1,
false,
];

yield 'Same password and username (similar > 100%)' => [
'ПёТр',
[
'email' => 'петя@caйт.ру',
'username' => 'ПёТр',
],
150,
false,
];

yield 'Empty password and username (similar < 1%)' => [
'',
[
'email' => 'петя@caйт.ру',
'username' => '',
],
0,
true,
];

yield 'Empty password and username (similar > 1%)' => [
'',
[
'email' => 'петя@caйт.ру',
'username' => '',
],
1,
true,
];

yield 'Empty password and specified username (similar > 1%)' => [
'',
[
'email' => 'петя@caйт.ру',
'username' => 'ПёТр',
],
1,
true,
];

yield 'Empty username and specified password (similar > 1%)' => [
'ПаРоЛь',
[
'email' => 'петя@caйт.ру',
'username' => '',
],
1,
true,
];

yield 'Empty User and specified password (similar > 1%)' => [
'ПаРоЛь',
null,
1,
true,
];
}

public function testIsNotPersonalAcceptsWrongData(): void
{
$config = new Auth();
$config->personalFields = ['altName', 'job'];
$validator = new NothingPersonalValidator($config);

$isNotPersonal = self::getPrivateMethodInvoker($validator, 'isNotPersonal');

/** @var bool */
$result = $isNotPersonal(
'Pa55w0rd',
new User([
'email' => 'user@email.local',
'username' => 'John',
]),
);

$this->assertTrue($result);

$result = $isNotPersonal(
'Pa55w0rd',
new User([
'email' => 'user@email.local',
'username' => 'John',
'altName' => [],
'job' => new Auth(),
]),
);

$this->assertTrue($result);
}
}
Loading