From 2d9afd4a35334ac8a7a8e88721567dedb3df56fa Mon Sep 17 00:00:00 2001 From: "John Paul E. Balandan, CPA" Date: Mon, 9 Nov 2026 18:28:42 +0800 Subject: [PATCH 1/2] chore: cleanup phpstan tooling --- .editorconfig | 2 +- .gitattributes | 2 +- .github/workflows/mutation.yml | 4 ++-- .github/workflows/phpstan.yml | 11 ++++++---- composer.json | 5 +++-- phpstan.dist.neon | 40 ++++++++++++++++++++++++++++++++++ phpstan.neon.dist | 40 ---------------------------------- rector.php | 2 +- 8 files changed, 55 insertions(+), 51 deletions(-) create mode 100644 phpstan.dist.neon delete mode 100644 phpstan.neon.dist diff --git a/.editorconfig b/.editorconfig index 7382bb8eb..99dc2ff61 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,5 +11,5 @@ end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true -[*.{yml,yaml}] +[*.{neon,yml,yaml}] indent_size = 2 diff --git a/.gitattributes b/.gitattributes index 95f18d8ed..96cbc5a3a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -11,7 +11,7 @@ /infection.json5 export-ignore /mkdocs.yml export-ignore /phpstan-baseline.php export-ignore -/phpstan.neon.dist export-ignore +/phpstan.dist.neon export-ignore /phpunit.dist.xml export-ignore /pyrameter.php export-ignore /psalm_autoload.php export-ignore diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 0425207c2..89b2197ba 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -10,7 +10,7 @@ on: - 'composer.json' - 'infection.json5' - 'phpunit.dist.xml' - - 'phpstan.neon.dist' + - 'phpstan.dist.neon' - '.github/workflows/mutation.yml' push: branches: @@ -21,7 +21,7 @@ on: - 'composer.json' - 'infection.json5' - 'phpunit.dist.xml' - - 'phpstan.neon.dist' + - 'phpstan.dist.neon' - '.github/workflows/mutation.yml' permissions: diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index fd8c9a15d..249ea7329 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -6,18 +6,21 @@ on: - develop paths: - '**.php' - - 'composer.*' - - 'phpstan*' + - 'composer.json' + - 'phpstan.dist.neon' - '.github/workflows/phpstan.yml' push: branches: - develop paths: - '**.php' - - 'composer.*' - - 'phpstan*' + - 'composer.json' + - 'phpstan.dist.neon' - '.github/workflows/phpstan.yml' +permissions: + contents: read + jobs: phpstan: uses: codeigniter4/.github/.github/workflows/phpstan.yml@CI47 diff --git a/composer.json b/composer.json index 6a6e3665e..f5fc60483 100644 --- a/composer.json +++ b/composer.json @@ -74,7 +74,7 @@ }, "scripts": { "analyze": [ - "phpstan analyze", + "@phpstan:check", "psalm", "rector process --dry-run" ], @@ -100,7 +100,8 @@ "@putenv PYRAMETER_DISABLED=1", "bin/mutation-filter" ], - "sa": "@analyze", + "phpstan:baseline": "@phpstan:check --generate-baseline=phpstan-baseline.php", + "phpstan:check": "phpstan analyse --ansi --verbose", "style": "@cs-fix", "test": "phpunit" } diff --git a/phpstan.dist.neon b/phpstan.dist.neon new file mode 100644 index 000000000..0362f5adc --- /dev/null +++ b/phpstan.dist.neon @@ -0,0 +1,40 @@ +includes: + - phpstan-baseline.php + - phar://vendor/phpstan/phpstan/phpstan.phar/conf/bleedingEdge.neon + +parameters: + tmpDir: build/phpstan + level: 5 + paths: + - src/ + - tests/ + bootstrapFiles: + - vendor/codeigniter4/framework/system/Test/bootstrap.php + excludePaths: + - src/Views/* + universalObjectCratesClasses: + - Faker\Generator + scanDirectories: + - vendor/codeigniter4/framework/system/Helpers + - vendor/codeigniter4/settings/src/Helpers + dynamicConstantNames: + - CodeIgniter\CodeIgniter::CI_VERSION + codeigniter: + additionalConfigNamespaces: + - CodeIgniter\Settings\Config + - CodeIgniter\Shield\Config + additionalServices: + - CodeIgniter\Shield\Config\Services + strictRules: + allRules: false + disallowedLooseComparison: true + booleansInConditions: true + disallowedBacktick: true + disallowedEmpty: true + disallowedImplicitArrayCreation: true + disallowedShortTernary: true + matchingInheritedMethodNames: true + ignoreErrors: + - identifier: function.internal + - identifier: return.internalClass + - identifier: staticMethod.internal diff --git a/phpstan.neon.dist b/phpstan.neon.dist deleted file mode 100644 index c29c48cbc..000000000 --- a/phpstan.neon.dist +++ /dev/null @@ -1,40 +0,0 @@ -includes: - - phpstan-baseline.php - - phar://vendor/phpstan/phpstan/phpstan.phar/conf/bleedingEdge.neon - -parameters: - tmpDir: build/phpstan - level: 5 - paths: - - src/ - - tests/ - bootstrapFiles: - - vendor/codeigniter4/framework/system/Test/bootstrap.php - excludePaths: - - src/Views/* - universalObjectCratesClasses: - - Faker\Generator - scanDirectories: - - vendor/codeigniter4/framework/system/Helpers - - vendor/codeigniter4/settings/src/Helpers - dynamicConstantNames: - - CodeIgniter\CodeIgniter::CI_VERSION - codeigniter: - additionalConfigNamespaces: - - CodeIgniter\Settings\Config - - CodeIgniter\Shield\Config - additionalServices: - - CodeIgniter\Shield\Config\Services - strictRules: - allRules: false - disallowedLooseComparison: true - booleansInConditions: true - disallowedBacktick: true - disallowedEmpty: true - disallowedImplicitArrayCreation: true - disallowedShortTernary: true - matchingInheritedMethodNames: true - ignoreErrors: - - identifier: function.internal - - identifier: return.internalClass - - identifier: staticMethod.internal diff --git a/rector.php b/rector.php index 4a56721c3..c612238d3 100644 --- a/rector.php +++ b/rector.php @@ -75,7 +75,7 @@ ]); $rectorConfig->phpstanConfigs([ - __DIR__ . '/phpstan.neon.dist', + __DIR__ . '/phpstan.dist.neon', __DIR__ . '/vendor/codeigniter/phpstan-codeigniter/extension.neon', __DIR__ . '/vendor/phpstan/phpstan-strict-rules/rules.neon', ]); From cb736c0530561946bef80911cf67b42a90edfedf Mon Sep 17 00:00:00 2001 From: "John Paul E. Balandan, CPA" Date: Mon, 9 Nov 2026 18:32:14 +0800 Subject: [PATCH 2/2] refactor: fix mechanical phpstan errors --- phpstan-baseline.php | 126 ------------------ src/Authentication/Actions/Email2FA.php | 2 +- src/Authentication/Authentication.php | 2 +- .../Authenticators/AccessTokens.php | 6 +- src/Authentication/Authenticators/Session.php | 8 +- .../Passwords/NothingPersonalValidator.php | 8 +- .../Passwords/ValidationRules.php | 2 +- src/Authorization/Groups.php | 6 +- src/Entities/User.php | 2 +- src/Filters/AbstractAuthFilter.php | 2 +- src/Filters/TokenAuth.php | 2 +- src/Models/UserModel.php | 4 +- .../AccessTokenAuthenticatorTest.php | 12 ++ .../Authenticators/JWTAuthenticatorTest.php | 4 - .../SessionAuthenticatorTest.php | 42 ++++-- .../Authentication/ForcePasswordResetTest.php | 2 + tests/Authentication/HasAccessTokensTest.php | 1 - .../Language/AbstractTranslationTestCase.php | 4 +- .../Authentication/JWT/JWTManagerTest.php | 10 -- tests/Unit/NothingPersonalValidatorTest.php | 59 ++++++++ tests/Unit/UserTest.php | 12 +- tests/Unit/ValidationRulesTest.php | 60 +++++++++ 22 files changed, 201 insertions(+), 175 deletions(-) create mode 100644 tests/Unit/ValidationRulesTest.php diff --git a/phpstan-baseline.php b/phpstan-baseline.php index 1cf96992f..b4085bf9c 100644 --- a/phpstan-baseline.php +++ b/phpstan-baseline.php @@ -1,30 +1,6 @@ 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 1, - 'path' => __DIR__ . '/src/Authentication/Actions/Email2FA.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 1, - 'path' => __DIR__ . '/src/Authentication/Authentication.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 2, - 'path' => __DIR__ . '/src/Authentication/Authenticators/AccessTokens.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Only booleans are allowed in &&, CodeIgniter\\I18n\\Time|null given on the left side.', - 'identifier' => 'booleanAnd.leftNotBoolean', - 'count' => 1, - 'path' => __DIR__ . '/src/Authentication/Authenticators/AccessTokens.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Parameter #1 $credentials (array{token?: string}) of method CodeIgniter\\Shield\\Authentication\\Authenticators\\JWT::attempt() should be contravariant with parameter $credentials (array) of method CodeIgniter\\Shield\\Authentication\\AuthenticatorInterface::attempt()', 'identifier' => 'method.childParameterType', @@ -37,18 +13,6 @@ 'count' => 1, 'path' => __DIR__ . '/src/Authentication/Authenticators/JWT.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 1, - 'path' => __DIR__ . '/src/Authentication/Authenticators/Session.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Only booleans are allowed in an if condition, int|string|null given.', - 'identifier' => 'if.condNotBoolean', - 'count' => 3, - 'path' => __DIR__ . '/src/Authentication/Authenticators/Session.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Parameter #1 $credentials (array{email?: string, username?: string, password?: string, ...}) of method CodeIgniter\\Shield\\Authentication\\Authenticators\\Session::attempt() should be contravariant with parameter $credentials (array) of method CodeIgniter\\Shield\\Authentication\\AuthenticatorInterface::attempt()', 'identifier' => 'method.childParameterType', @@ -61,24 +25,6 @@ 'count' => 1, 'path' => __DIR__ . '/src/Authentication/Authenticators/Session.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 4, - 'path' => __DIR__ . '/src/Authentication/Passwords/NothingPersonalValidator.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Only booleans are allowed in &&, CodeIgniter\\Shield\\Entities\\User|null given on the right side.', - 'identifier' => 'booleanAnd.rightNotBoolean', - 'count' => 1, - 'path' => __DIR__ . '/src/Authentication/Passwords/ValidationRules.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 3, - 'path' => __DIR__ . '/src/Authorization/Groups.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Return type (int|string|null) of method CodeIgniter\\Shield\\Collectors\\Auth::getBadgeValue() should be covariant with return type (int|null) of method CodeIgniter\\Debug\\Toolbar\\Collectors\\BaseCollector::getBadgeValue()', 'identifier' => 'method.childReturnType', @@ -133,18 +79,6 @@ 'count' => 1, 'path' => __DIR__ . '/src/Database/Migrations/2020-12-28-223112_create_auth_tables.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Only booleans are allowed in a ternary operator condition, int<0, max> given.', - 'identifier' => 'ternary.condNotBoolean', - 'count' => 1, - 'path' => __DIR__ . '/src/Entities/User.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 1, - 'path' => __DIR__ . '/src/Filters/AbstractAuthFilter.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Return type (CodeIgniter\\HTTP\\RedirectResponse|void) of method CodeIgniter\\Shield\\Filters\\AbstractAuthFilter::before() should be covariant with return type (CodeIgniter\\HTTP\\RequestInterface|CodeIgniter\\HTTP\\ResponseInterface|string|null) of method CodeIgniter\\Filters\\FilterInterface::before()', 'identifier' => 'method.childReturnType', @@ -229,12 +163,6 @@ 'count' => 1, 'path' => __DIR__ . '/src/Filters/SessionAuth.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 1, - 'path' => __DIR__ . '/src/Filters/TokenAuth.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Method CodeIgniter\\Shield\\Filters\\TokenAuth::before() should return CodeIgniter\\HTTP\\RedirectResponse|void but returns CodeIgniter\\HTTP\\ResponseInterface.', 'identifier' => 'return.type', @@ -253,12 +181,6 @@ 'count' => 1, 'path' => __DIR__ . '/src/Filters/TokenAuth.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Construct empty() is not allowed. Use more strict comparison.', - 'identifier' => 'empty.notAllowed', - 'count' => 2, - 'path' => __DIR__ . '/src/Models/UserModel.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Parameter #1 $row (array|CodeIgniter\\Shield\\Entities\\User) of method CodeIgniter\\Shield\\Models\\UserModel::insert() should be contravariant with parameter $row (array|object|null) of method CodeIgniter\\Model::insert()', 'identifier' => 'method.childParameterType', @@ -283,42 +205,12 @@ 'count' => 1, 'path' => __DIR__ . '/src/Models/UserModel.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Call to method PHPUnit\\Framework\\Assert::assertInstanceOf() with \'CodeIgniter\\\\Shield\\\\Result\' and CodeIgniter\\Shield\\Result will always evaluate to true.', - 'identifier' => 'method.alreadyNarrowedType', - 'count' => 3, - 'path' => __DIR__ . '/tests/Authentication/Authenticators/JWTAuthenticatorTest.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Call to method PHPUnit\\Framework\\Assert::assertInstanceOf() with \'CodeIgniter\\\\Shield\\\\Result\' and CodeIgniter\\Shield\\Result will always evaluate to true.', - 'identifier' => 'method.alreadyNarrowedType', - 'count' => 8, - 'path' => __DIR__ . '/tests/Authentication/Authenticators/SessionAuthenticatorTest.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Call to method setCookie() of internal class CodeIgniter\\Superglobals from outside its root namespace CodeIgniter.', 'identifier' => 'method.internalClass', 'count' => 2, 'path' => __DIR__ . '/tests/Authentication/Authenticators/SessionAuthenticatorTest.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Implicit array creation is not allowed - variable $users might not exist.', - 'identifier' => 'variable.implicitArray', - 'count' => 1, - 'path' => __DIR__ . '/tests/Authentication/ForcePasswordResetTest.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Variable $users might not be defined.', - 'identifier' => 'variable.undefined', - 'count' => 1, - 'path' => __DIR__ . '/tests/Authentication/ForcePasswordResetTest.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Call to method PHPUnit\\Framework\\Assert::assertInstanceOf() with \'CodeIgniter\\\\Shield\\\\Entities\\\\AccessToken\' and CodeIgniter\\Shield\\Entities\\AccessToken will always evaluate to true.', - 'identifier' => 'method.alreadyNarrowedType', - 'count' => 1, - 'path' => __DIR__ . '/tests/Authentication/HasAccessTokensTest.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Call to method setServer() of internal class CodeIgniter\\Superglobals from outside its root namespace CodeIgniter.', 'identifier' => 'method.internalClass', @@ -349,18 +241,6 @@ 'count' => 1, 'path' => __DIR__ . '/tests/Controllers/MagicLinkTest.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Only booleans are allowed in a ternary operator condition, string|null given.', - 'identifier' => 'ternary.condNotBoolean', - 'count' => 2, - 'path' => __DIR__ . '/tests/Language/AbstractTranslationTestCase.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Call to method PHPUnit\\Framework\\Assert::assertIsString() with string will always evaluate to true.', - 'identifier' => 'method.alreadyNarrowedType', - 'count' => 6, - 'path' => __DIR__ . '/tests/Unit/Authentication/JWT/JWTManagerTest.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Call to deprecated method __construct() of class CodeIgniter\\HTTP\\Response: 4.5.0 The param $config is no longer used.', @@ -374,12 +254,6 @@ 'count' => 9, 'path' => __DIR__ . '/tests/Unit/UserTest.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Call to method PHPUnit\\Framework\\Assert::assertInstanceOf() with \'CodeIgniter\\\\Shield\\\\Entities\\\\UserIdentity\' and CodeIgniter\\Shield\\Entities\\UserIdentity will always evaluate to true.', - 'identifier' => 'method.alreadyNarrowedType', - 'count' => 1, - 'path' => __DIR__ . '/tests/Unit/UserTest.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Offset 1 does not exist on array{CodeIgniter\\Shield\\Entities\\User}.', 'identifier' => 'offsetAccess.notFound', diff --git a/src/Authentication/Actions/Email2FA.php b/src/Authentication/Actions/Email2FA.php index 4d438a633..bfce96d15 100644 --- a/src/Authentication/Actions/Email2FA.php +++ b/src/Authentication/Actions/Email2FA.php @@ -72,7 +72,7 @@ public function handle(IncomingRequest $request) throw new RuntimeException('Cannot get the pending login User.'); } - if (empty($email) || $email !== $user->email) { + if ($email !== $user->email) { return redirect()->route('auth-action-show')->with('error', lang('Auth.invalidEmail', [$email])); } diff --git a/src/Authentication/Authentication.php b/src/Authentication/Authentication.php index 0a3d7e358..bd2c7f294 100644 --- a/src/Authentication/Authentication.php +++ b/src/Authentication/Authentication.php @@ -49,7 +49,7 @@ public function factory(?string $alias = null): AuthenticatorInterface $alias ??= $this->config->defaultAuthenticator; // Return the cached instance if we have it - if (! empty($this->instances[$alias])) { + if (isset($this->instances[$alias])) { return $this->instances[$alias]; } diff --git a/src/Authentication/Authenticators/AccessTokens.php b/src/Authentication/Authenticators/AccessTokens.php index 30b6975a4..a76e4d77e 100644 --- a/src/Authentication/Authenticators/AccessTokens.php +++ b/src/Authentication/Authenticators/AccessTokens.php @@ -126,7 +126,7 @@ public function attempt(array $credentials): Result */ public function check(array $credentials): Result { - if (! array_key_exists('token', $credentials) || empty($credentials['token'])) { + if (($credentials['token'] ?? '') === '') { return new Result([ 'success' => false, 'reason' => lang( @@ -166,7 +166,7 @@ public function check(array $credentials): Result // Hasn't been used in a long time if ( - $token->last_used_at + $token->last_used_at !== null && $token->last_used_at->isBefore( Time::now()->subSeconds(config('AuthToken')->unusedTokenLifetime), ) @@ -270,7 +270,7 @@ public function getBearerToken(): ?string $header = $request->getHeaderLine(config('AuthToken')->authenticatorHeader['tokens']); - if (empty($header)) { + if ($header === '') { return null; } diff --git a/src/Authentication/Authenticators/Session.php b/src/Authentication/Authenticators/Session.php index 147db31a3..a9c1ba424 100644 --- a/src/Authentication/Authenticators/Session.php +++ b/src/Authentication/Authenticators/Session.php @@ -350,7 +350,7 @@ private function recordLoginAttempt( public function check(array $credentials): Result { // Can't validate without a password. - if (empty($credentials['password']) || count($credentials) < 2) { + if (($credentials['password'] ?? '') === '' || count($credentials) < 2) { return new Result([ 'success' => false, 'reason' => lang('Auth.badAttempt'), @@ -440,7 +440,7 @@ private function checkUserState(): void } // If having `auth_action`, it is pending. - if ($this->getSessionUserKey('auth_action')) { + if ($this->getSessionUserKey('auth_action') !== null) { $this->userState = self::STATE_PENDING; return; @@ -489,7 +489,7 @@ public function hasAction($userId = null): bool } // Check the Session - if ($this->getSessionUserKey('auth_action')) { + if ($this->getSessionUserKey('auth_action') !== null) { return true; } @@ -805,7 +805,7 @@ public function login(User $user): void ); } // Check auth_action in Session - if ($this->getSessionUserKey('auth_action')) { + if ($this->getSessionUserKey('auth_action') !== null) { throw new LogicException( 'The user has auth action in session, so cannot complete login.' . ' If you want to start to login with auth action, use startLogin() instead.' diff --git a/src/Authentication/Passwords/NothingPersonalValidator.php b/src/Authentication/Passwords/NothingPersonalValidator.php index bf5398fce..62fb69df2 100644 --- a/src/Authentication/Passwords/NothingPersonalValidator.php +++ b/src/Authentication/Passwords/NothingPersonalValidator.php @@ -94,7 +94,7 @@ protected function isNotPersonal(string $password, ?User $user): bool $personalFields = $this->config->personalFields; foreach ($personalFields as $value) { - if (! empty($user->{$value})) { + if (($user->{$value} ?? '') !== '') { $needles[] = strtolower($user->{$value}); } } @@ -121,12 +121,12 @@ protected function isNotPersonal(string $password, ?User $user): bool $haystacks = $this->strip_explode($password); foreach ($haystacks as $haystack) { - if (empty($haystack) || in_array($haystack, $trivial, true) || mb_strlen($haystack, 'UTF-8') < 3) { + if (in_array($haystack, $trivial, true) || mb_strlen($haystack, 'UTF-8') < 3) { continue; // ignore trivial words } foreach ($needles as $needle) { - if (empty($needle) || in_array($needle, $trivial, true) || mb_strlen($needle, 'UTF-8') < 3) { + if (in_array($needle, $trivial, true) || mb_strlen($needle, 'UTF-8') < 3) { continue; } @@ -172,7 +172,7 @@ protected function isNotSimilar(string $password, ?User $user): bool $maxSimilarity = 100; } - if (! empty($maxSimilarity)) { + if ($maxSimilarity > 0) { $userName = strtolower($user->username); similar_text($password, $userName, $similarity); diff --git a/src/Authentication/Passwords/ValidationRules.php b/src/Authentication/Passwords/ValidationRules.php index e37b9f62a..a1583268b 100644 --- a/src/Authentication/Passwords/ValidationRules.php +++ b/src/Authentication/Passwords/ValidationRules.php @@ -45,7 +45,7 @@ public function strong_password(string $value, ?string &$error1 = null, array $d /** @var Passwords $checker */ $checker = service('passwords'); - if (function_exists('auth') && auth()->user()) { + if (function_exists('auth') && auth()->user() !== null) { $user = auth()->user(); } else { /** @phpstan-ignore-next-line */ diff --git a/src/Authorization/Groups.php b/src/Authorization/Groups.php index eb76920c9..fbd2dde10 100644 --- a/src/Authorization/Groups.php +++ b/src/Authorization/Groups.php @@ -29,7 +29,7 @@ public function info(string $group): ?Group { $info = setting('AuthGroups.groups')[strtolower($group)] ?? null; - if (empty($info)) { + if ($info === null || $info === []) { return null; } @@ -43,7 +43,7 @@ public function info(string $group): ?Group */ public function save(Group $group): void { - if (empty($group->title)) { + if (($group->title ?? '') === '') { throw new RuntimeException(lang('Auth.missingTitle')); } @@ -51,7 +51,7 @@ public function save(Group $group): void $alias = $group->alias; - if (empty($alias)) { + if (($alias ?? '') === '') { $alias = strtolower(url_title($group->title)); } diff --git a/src/Entities/User.php b/src/Entities/User.php index f4a6ef8ad..d86e15d91 100644 --- a/src/Entities/User.php +++ b/src/Entities/User.php @@ -83,7 +83,7 @@ public function getIdentity(string $type): ?UserIdentity { $identities = $this->getIdentities($type); - return count($identities) ? array_shift($identities) : null; + return $identities !== [] ? array_shift($identities) : null; } /** diff --git a/src/Filters/AbstractAuthFilter.php b/src/Filters/AbstractAuthFilter.php index 652d8940b..c2d96395f 100644 --- a/src/Filters/AbstractAuthFilter.php +++ b/src/Filters/AbstractAuthFilter.php @@ -33,7 +33,7 @@ abstract class AbstractAuthFilter implements FilterInterface */ public function before(RequestInterface $request, $arguments = null) { - if (empty($arguments)) { + if (($arguments ?? []) === []) { return; } diff --git a/src/Filters/TokenAuth.php b/src/Filters/TokenAuth.php index 473d5cc8d..a433a1a20 100644 --- a/src/Filters/TokenAuth.php +++ b/src/Filters/TokenAuth.php @@ -55,7 +55,7 @@ public function before(RequestInterface $request, $arguments = null) 'token' => $request->getHeaderLine(setting('AuthToken.authenticatorHeader')['tokens'] ?? 'Authorization'), ]); - if (! $result->isOK() || (! empty($arguments) && $result->extraInfo()->tokenCant($arguments[0]))) { + if (! $result->isOK() || (($arguments ?? []) !== [] && $result->extraInfo()->tokenCant($arguments[0]))) { return service('response') ->setStatusCode(Response::HTTP_UNAUTHORIZED) ->setJSON(['message' => lang('Auth.badToken')]); diff --git a/src/Models/UserModel.php b/src/Models/UserModel.php index 9ba28709a..7acb01258 100644 --- a/src/Models/UserModel.php +++ b/src/Models/UserModel.php @@ -130,7 +130,7 @@ protected function fetchIdentities(array $data): array // Get our identities for all users $identities = $identityModel->getIdentitiesByUserIds($userIds); - if (empty($identities)) { + if ($identities === []) { return $data; } @@ -297,7 +297,7 @@ public function addToDefaultGroup(User $user): void $groupModel = model(GroupModel::class); - if (empty($defaultGroup) || ! $groupModel->isValidGroup($defaultGroup)) { + if ($defaultGroup === null || $defaultGroup === '' || ! $groupModel->isValidGroup($defaultGroup)) { throw new InvalidArgumentException(lang('Auth.unknownGroup', [$defaultGroup ?? '--not found--'])); } diff --git a/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php b/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php index bb365a1d6..6a1edf922 100644 --- a/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php @@ -48,6 +48,18 @@ protected function setUp(): void Services::injectMock('events', new MockEvents()); } + public function testGetBearerToken(): void + { + service('request')->setHeader('Authorization', 'Bearer abc123'); + + $this->assertSame('abc123', $this->auth->getBearerToken()); + } + + public function testGetBearerTokenWithoutHeader(): void + { + $this->assertNull($this->auth->getBearerToken()); + } + public function testLogin(): void { $user = fake(UserModel::class); diff --git a/tests/Authentication/Authenticators/JWTAuthenticatorTest.php b/tests/Authentication/Authenticators/JWTAuthenticatorTest.php index fc28d0cf1..2fd6ba685 100644 --- a/tests/Authentication/Authenticators/JWTAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/JWTAuthenticatorTest.php @@ -22,7 +22,6 @@ use CodeIgniter\Shield\Config\AuthJWT; use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Models\UserModel; -use CodeIgniter\Shield\Result; use CodeIgniter\Test\Mock\MockEvents; use Config\Services; use Firebase\JWT\JWT as FirebaseJWT; @@ -197,7 +196,6 @@ public function testAttemptBadSignatureToken(): void 'token' => self::BAD_JWT, ]); - $this->assertInstanceOf(Result::class, $result); $this->assertFalse($result->isOK()); $this->assertSame(lang('Auth.invalidJWT'), $result->reason()); @@ -219,7 +217,6 @@ public function testAttemptBannedUser(): void 'token' => $token, ]); - $this->assertInstanceOf(Result::class, $result); $this->assertFalse($result->isOK()); $this->assertSame(lang('Auth.bannedUser'), $result->reason()); @@ -245,7 +242,6 @@ public function testAttemptSuccess(): void 'token' => $token, ]); - $this->assertInstanceOf(Result::class, $result); $this->assertTrue($result->isOK()); $foundUser = $result->extraInfo(); diff --git a/tests/Authentication/Authenticators/SessionAuthenticatorTest.php b/tests/Authentication/Authenticators/SessionAuthenticatorTest.php index 88ab88bcb..3e4bffa36 100644 --- a/tests/Authentication/Authenticators/SessionAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/SessionAuthenticatorTest.php @@ -23,9 +23,9 @@ use CodeIgniter\Shield\Exceptions\LogicException; use CodeIgniter\Shield\Models\RememberModel; use CodeIgniter\Shield\Models\UserModel; -use CodeIgniter\Shield\Result; use CodeIgniter\Test\Mock\MockEvents; use Config\Services; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\Support\DatabaseTestCase; use Tests\Support\FakeUser; @@ -256,11 +256,42 @@ public function testCheckNoPassword(): void 'email' => 'johnsmith@example.com', ]); - $this->assertInstanceOf(Result::class, $result); $this->assertFalse($result->isOK()); $this->assertSame(lang('Auth.badAttempt'), $result->reason()); } + /** + * @param array $credentials + */ + #[DataProvider('provideCheckWithoutUsablePasswordDoesNotVerify')] + public function testCheckWithoutUsablePasswordDoesNotVerify(array $credentials): void + { + $passwords = new class (new Auth()) extends Passwords { + public array $checks = []; + + public function verify(string $password, string $hash): bool + { + $this->checks[] = [$password, $hash]; + + return false; + } + }; + Services::injectMock('passwords', $passwords); + + $result = $this->auth->check($credentials); + + $this->assertFalse($result->isOK()); + $this->assertSame(lang('Auth.badAttempt'), $result->reason()); + $this->assertSame([], $passwords->checks); + } + + public static function provideCheckWithoutUsablePasswordDoesNotVerify(): iterable + { + yield 'empty password' => [['email' => 'johnsmith@example.com', 'password' => '']]; + + yield 'password only' => [['password' => 'secret']]; + } + public function testCheckCannotFindUser(): void { $result = $this->auth->check([ @@ -268,7 +299,6 @@ public function testCheckCannotFindUser(): void 'password' => 'secret', ]); - $this->assertInstanceOf(Result::class, $result); $this->assertFalse($result->isOK()); $this->assertSame(lang('Auth.badAttempt'), $result->reason()); } @@ -308,7 +338,6 @@ public function testCheckBadPassword(): void 'password' => 'secret', ]); - $this->assertInstanceOf(Result::class, $result); $this->assertFalse($result->isOK()); $this->assertSame(lang('Auth.badAttempt'), $result->reason()); } @@ -325,7 +354,6 @@ public function testCheckSuccess(): void 'password' => 'secret123', ]); - $this->assertInstanceOf(Result::class, $result); $this->assertTrue($result->isOK()); $foundUser = $result->extraInfo(); @@ -339,7 +367,6 @@ public function testAttemptCannotFindUser(): void 'password' => 'secret', ]); - $this->assertInstanceOf(Result::class, $result); $this->assertFalse($result->isOK()); $this->assertSame(lang('Auth.badAttempt'), $result->reason()); @@ -364,7 +391,6 @@ public function testAttemptSuccess(): void 'password' => 'secret123', ]); - $this->assertInstanceOf(Result::class, $result); $this->assertTrue($result->isOK()); $foundUser = $result->extraInfo(); @@ -414,7 +440,6 @@ public function testAttemptCaseInsensitive(): void 'password' => 'secret123', ]); - $this->assertInstanceOf(Result::class, $result); $this->assertTrue($result->isOK()); $foundUser = $result->extraInfo(); @@ -451,7 +476,6 @@ public function testAttemptUsernameOnly(): void 'password' => 'secret123', ]); - $this->assertInstanceOf(Result::class, $result); $this->assertTrue($result->isOK()); $foundUser = $result->extraInfo(); diff --git a/tests/Authentication/ForcePasswordResetTest.php b/tests/Authentication/ForcePasswordResetTest.php index 527230e32..22df88e6f 100644 --- a/tests/Authentication/ForcePasswordResetTest.php +++ b/tests/Authentication/ForcePasswordResetTest.php @@ -96,6 +96,8 @@ public function testRequiresPasswordResetRedirect(): void public function testForceGlobalPasswordReset(): void { + $users = []; + for ($i = 0; $i < 3; $i++) { $user = fake(UserModel::class); $user->createEmailIdentity([ diff --git a/tests/Authentication/HasAccessTokensTest.php b/tests/Authentication/HasAccessTokensTest.php index 0ca609f70..56ce55a60 100644 --- a/tests/Authentication/HasAccessTokensTest.php +++ b/tests/Authentication/HasAccessTokensTest.php @@ -47,7 +47,6 @@ public function testGenerateToken(): void { $token = $this->user->generateAccessToken('foo'); - $this->assertInstanceOf(AccessToken::class, $token); $this->assertSame('foo', $token->name); $this->assertNull($token->expires); diff --git a/tests/Language/AbstractTranslationTestCase.php b/tests/Language/AbstractTranslationTestCase.php index 733611bca..c7173f446 100644 --- a/tests/Language/AbstractTranslationTestCase.php +++ b/tests/Language/AbstractTranslationTestCase.php @@ -427,7 +427,7 @@ final public function foundSets(string $locale): array */ final public function loadFile(string $file, ?string $locale = null): array { - $folder = $locale + $folder = $locale !== null ? getcwd() . self::LANGUAGE_DIR . "{$locale}/" : getcwd() . self::MAIN_LANGUAGE_REPO; @@ -445,7 +445,7 @@ private function translationSets(?string $locale = null): array { helper('filesystem'); - $location = $locale + $location = $locale !== null ? getcwd() . self::LANGUAGE_DIR . "{$locale}/" : getcwd() . self::MAIN_LANGUAGE_REPO; diff --git a/tests/Unit/Authentication/JWT/JWTManagerTest.php b/tests/Unit/Authentication/JWT/JWTManagerTest.php index cd32ef077..f0f7f32af 100644 --- a/tests/Unit/Authentication/JWT/JWTManagerTest.php +++ b/tests/Unit/Authentication/JWT/JWTManagerTest.php @@ -47,7 +47,6 @@ public function testGenerateToken(): array // Reset the current time. Time::setTestNow(); - $this->assertIsString($token); $this->assertStringStartsWith('eyJ', $token); return [$token, $currentTime]; @@ -83,8 +82,6 @@ public function testGenerateTokenAddClaims(): void ]; $token = $manager->generateToken($user, $claims); - $this->assertIsString($token); - $payload = $this->decodeJWT($token, 'payload'); $this->assertStringStartsWith('1', $payload['sub']); @@ -111,7 +108,6 @@ public function testIssue(): array // Reset the current time. Time::setTestNow(); - $this->assertIsString($token); $this->assertStringStartsWith('eyJ', $token); return [$token, $currentTime]; @@ -151,8 +147,6 @@ public function testIssueSetKid(): void ]; $token = $manager->issue($payload, DAY); - $this->assertIsString($token); - $headers = $this->decodeJWT($token, 'header'); $this->assertSame([ 'typ' => 'JWT', @@ -173,8 +167,6 @@ public function testIssueAddHeader(): void ]; $token = $manager->issue($payload, DAY, 'default', $headers); - $this->assertIsString($token); - $headers = $this->decodeJWT($token, 'header'); $this->assertEqualsCanonicalizing([ 'typ' => 'JWT', @@ -228,8 +220,6 @@ public function testIssueWithAsymmetricKey(): void ]; $token = $manager->issue($payload, DAY); - $this->assertIsString($token); - $headers = $this->decodeJWT($token, 'header'); $this->assertSame([ 'typ' => 'JWT', diff --git a/tests/Unit/NothingPersonalValidatorTest.php b/tests/Unit/NothingPersonalValidatorTest.php index 8d4499dcf..207a05503 100644 --- a/tests/Unit/NothingPersonalValidatorTest.php +++ b/tests/Unit/NothingPersonalValidatorTest.php @@ -136,6 +136,65 @@ public function testTrueForAllowedTooSmallMatch(): void $this->assertTrue($result->isOK()); } + public function testFalseWhenPasswordPartIsExactlyThreeCharactersLong(): void + { + $user = new User([ + 'email' => 'zzzz@example.com', + 'username' => 'bobby', + ]); + + $result = $this->validator->check('bob!qzxwv7', $user); + + $this->assertFalse($result->isOK()); + } + + public function testTrueWhenPasswordIsTwoMultibyteCharacters(): void + { + $user = new User([ + 'email' => 'éé1@example.com', + 'username' => null, + ]); + + $result = $this->validator->check('éé', $user); + + $this->assertTrue($result->isOK()); + } + + public function testTrueWhenPersonalNeedleIsTwoMultibyteCharacters(): void + { + $user = new User([ + 'email' => 'éé@example.com', + 'username' => null, + ]); + + $result = $this->validator->check('éé1', $user); + + $this->assertTrue($result->isOK()); + } + + public function testChecksAreOverridableByExtendingClasses(): void + { + $validator = new class (new Auth()) extends NothingPersonalValidator { + public function personal(string $password, ?User $user): bool + { + return $this->isNotPersonal($password, $user); + } + + public function similar(string $password, ?User $user): bool + { + return $this->isNotSimilar($password, $user); + } + }; + + $user = new User([ + 'email' => 'zzzz@example.com', + 'username' => 'bobby', + ]); + + $this->assertTrue($validator->personal('opensesame', $user)); + $this->assertTrue($validator->similar('opensesame', $user)); + } + public function testFalseForSensibleMatch(): void { $user = new User([ diff --git a/tests/Unit/UserTest.php b/tests/Unit/UserTest.php index 52c500f11..c2e3d6a7e 100644 --- a/tests/Unit/UserTest.php +++ b/tests/Unit/UserTest.php @@ -60,11 +60,21 @@ public function testGetIdentitiesByType(): void $identities = $this->user->getIdentities('access_token'); $this->assertCount(1, $identities); - $this->assertInstanceOf(UserIdentity::class, $identities[0]); $this->assertSame('access_token', $identities[0]->type); $this->assertSame([], $this->user->getIdentities('foo')); } + public function testGetIdentity(): void + { + fake(UserIdentityModel::class, ['user_id' => $this->user->id, 'type' => 'access_token']); + + $identity = $this->user->getIdentity('access_token'); + + $this->assertInstanceOf(UserIdentity::class, $identity); + $this->assertSame('access_token', $identity->type); + $this->assertNull($this->user->getIdentity('foo')); + } + public function testSetIdentitiesNullReloadsIdentities(): void { fake(UserIdentityModel::class, ['user_id' => $this->user->id, 'type' => 'password']); diff --git a/tests/Unit/ValidationRulesTest.php b/tests/Unit/ValidationRulesTest.php new file mode 100644 index 000000000..fd030a7b6 --- /dev/null +++ b/tests/Unit/ValidationRulesTest.php @@ -0,0 +1,60 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Tests\Unit; + +use CodeIgniter\Shield\Authentication\Passwords\ValidationRules; +use Tests\Support\DatabaseTestCase; +use Tests\Support\FakeUser; + +/** + * @internal + */ +final class ValidationRulesTest extends DatabaseTestCase +{ + use FakeUser; + + protected $namespace; + protected $refresh = true; + + public function testStrongPasswordUsesLoggedInUser(): void + { + $this->user->createEmailIdentity([ + 'email' => 'jane.doe@example.com', + 'password' => 'secret123', + ]); + auth()->login($this->user); + + $error = null; + + $this->assertFalse((new ValidationRules())->strong_password('jane.doe@example.com', $error)); + $this->assertSame(lang('Auth.errorPasswordPersonal'), $error); + } + + public function testStrongPasswordUsesAssignedDataWithoutLoggedInUser(): void + { + $error1 = null; + $error2 = null; + + $result = (new ValidationRules())->strong_password( + 'jane.doe@example.com', + $error1, + ['email' => 'jane.doe@example.com'], + $error2, + ); + + $this->assertFalse($result); + $this->assertNull($error1); + $this->assertSame(lang('Auth.errorPasswordPersonal'), $error2); + } +}