From 74bf1fc9d230b80fad916f969a2971fad78554cc Mon Sep 17 00:00:00 2001 From: "John Paul E. Balandan, CPA" Date: Mon, 9 Nov 2026 20:26:22 +0800 Subject: [PATCH 1/2] refactor: cleanup `Hmac` command --- phpstan-baseline.php | 18 ------- src/Commands/Hmac.php | 97 ++++++++++++++++--------------------- tests/Commands/HmacTest.php | 58 ++++++++++++++++++++++ 3 files changed, 100 insertions(+), 73 deletions(-) diff --git a/phpstan-baseline.php b/phpstan-baseline.php index 1cf96992f..f6027c948 100644 --- a/phpstan-baseline.php +++ b/phpstan-baseline.php @@ -85,24 +85,6 @@ 'count' => 1, 'path' => __DIR__ . '/src/Collectors/Auth.php', ]; -$ignoreErrors[] = [ - 'rawMessage' => 'Cannot access property $expires on array|object.', - 'identifier' => 'property.nonObject', - 'count' => 3, - 'path' => __DIR__ . '/src/Commands/Hmac.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Cannot access property $id on array|object.', - 'identifier' => 'property.nonObject', - 'count' => 9, - 'path' => __DIR__ . '/src/Commands/Hmac.php', -]; -$ignoreErrors[] = [ - 'rawMessage' => 'Cannot access property $secret2 on array|object.', - 'identifier' => 'property.nonObject', - 'count' => 11, - 'path' => __DIR__ . '/src/Commands/Hmac.php', -]; $ignoreErrors[] = [ 'rawMessage' => 'Call to function assert() with false and \'Config Auth…\' will always evaluate to false.', 'identifier' => 'function.impossibleType', diff --git a/src/Commands/Hmac.php b/src/Commands/Hmac.php index 38421cb67..78b416ba5 100644 --- a/src/Commands/Hmac.php +++ b/src/Commands/Hmac.php @@ -16,6 +16,7 @@ use CodeIgniter\I18n\Time; use CodeIgniter\Shield\Authentication\HMAC\HmacEncrypter; use CodeIgniter\Shield\Commands\Exceptions\BadInputException; +use CodeIgniter\Shield\Entities\UserIdentity; use CodeIgniter\Shield\Exceptions\RuntimeException; use CodeIgniter\Shield\Models\UserIdentityModel; use Exception; @@ -23,6 +24,8 @@ class Hmac extends BaseCommand { + private const CHUNK_SIZE = 100; + /** * The Command's name * @@ -73,6 +76,11 @@ class Hmac extends BaseCommand */ private HmacEncrypter $encrypter; + /** + * Persists identities while chunk() iterates through another model. + */ + private UserIdentityModel $saver; + /** * the Command's Options * @@ -88,6 +96,7 @@ public function run(array $params): int $action = $params[0] ?? null; $this->encrypter = new HmacEncrypter(); + $this->saver = new UserIdentityModel(); try { match ($action) { @@ -95,8 +104,7 @@ public function run(array $params): int 'decrypt' => $this->decrypt(), 'reencrypt' => $this->reEncrypt(), 'invalidateAll' => $this->invalidateAll(), - - default => throw new BadInputException('Unrecognized Command'), + default => throw new BadInputException('Unrecognized Command'), }; } catch (Exception $e) { $this->write($e->getMessage(), 'red'); @@ -114,28 +122,22 @@ public function run(array $params): int */ public function encrypt(): void { - $uIdModel = new UserIdentityModel(); - $uIdModelSub = new UserIdentityModel(); // For saving. - $encrypter = $this->encrypter; - - $that = $this; - - $uIdModel->where('type', 'hmac_sha256')->orderBy('id')->chunk( - 100, - static function ($identity) use ($uIdModelSub, $encrypter, $that): void { - if ($encrypter->isEncrypted($identity->secret2)) { - $that->write('id: ' . $identity->id . ', already encrypted, skipped.'); + (new UserIdentityModel())->where('type', 'hmac_sha256')->orderBy('id')->chunk( + self::CHUNK_SIZE, + function (UserIdentity $identity): void { + if ($this->encrypter->isEncrypted($identity->secret2)) { + $this->write(sprintf('id: %s, already encrypted, skipped.', $identity->id)); return; } try { - $identity->secret2 = $encrypter->encrypt($identity->secret2); - $uIdModelSub->save($identity); + $identity->secret2 = $this->encrypter->encrypt($identity->secret2); + $this->saver->save($identity); - $that->write('id: ' . $identity->id . ', encrypted.'); + $this->write(sprintf('id: %s, encrypted.', $identity->id)); } catch (RuntimeException $e) { - $that->error('id: ' . $identity->id . ', ' . $e->getMessage()); + $this->error(sprintf('id: %s, %s', $identity->id, $e->getMessage())); } }, ); @@ -148,25 +150,19 @@ static function ($identity) use ($uIdModelSub, $encrypter, $that): void { */ public function decrypt(): void { - $uIdModel = new UserIdentityModel(); - $uIdModelSub = new UserIdentityModel(); // For saving. - $encrypter = $this->encrypter; - - $that = $this; - - $uIdModel->where('type', 'hmac_sha256')->orderBy('id')->chunk( - 100, - static function ($identity) use ($uIdModelSub, $encrypter, $that): void { - if (! $encrypter->isEncrypted($identity->secret2)) { - $that->write('id: ' . $identity->id . ', not encrypted, skipped.'); + (new UserIdentityModel())->where('type', 'hmac_sha256')->orderBy('id')->chunk( + self::CHUNK_SIZE, + function (UserIdentity $identity): void { + if (! $this->encrypter->isEncrypted($identity->secret2)) { + $this->write(sprintf('id: %s, not encrypted, skipped.', $identity->id)); return; } - $identity->secret2 = $encrypter->decrypt($identity->secret2); - $uIdModelSub->save($identity); + $identity->secret2 = $this->encrypter->decrypt($identity->secret2); + $this->saver->save($identity); - $that->write('id: ' . $identity->id . ', decrypted.'); + $this->write(sprintf('id: %s, decrypted.', $identity->id)); }, ); } @@ -179,26 +175,20 @@ static function ($identity) use ($uIdModelSub, $encrypter, $that): void { */ public function reEncrypt(): void { - $uIdModel = new UserIdentityModel(); - $uIdModelSub = new UserIdentityModel(); // For saving. - $encrypter = $this->encrypter; - - $that = $this; - - $uIdModel->where('type', 'hmac_sha256')->orderBy('id')->chunk( - 100, - static function ($identity) use ($uIdModelSub, $encrypter, $that): void { - if ($encrypter->isEncryptedWithCurrentKey($identity->secret2)) { - $that->write('id: ' . $identity->id . ', already encrypted with current key, skipped.'); + (new UserIdentityModel())->where('type', 'hmac_sha256')->orderBy('id')->chunk( + self::CHUNK_SIZE, + function (UserIdentity $identity): void { + if ($this->encrypter->isEncryptedWithCurrentKey($identity->secret2)) { + $this->write(sprintf('id: %s, already encrypted with current key, skipped.', $identity->id)); return; } - $identity->secret2 = $encrypter->decrypt($identity->secret2); - $identity->secret2 = $encrypter->encrypt($identity->secret2); - $uIdModelSub->save($identity); + $identity->secret2 = $this->encrypter->decrypt($identity->secret2); + $identity->secret2 = $this->encrypter->encrypt($identity->secret2); + $this->saver->save($identity); - $that->write('id: ' . $identity->id . ', Re-encrypted.'); + $this->write(sprintf('id: %s, Re-encrypted.', $identity->id)); }, ); } @@ -208,24 +198,21 @@ static function ($identity) use ($uIdModelSub, $encrypter, $that): void { */ public function invalidateAll(): void { - $uIdModel = new UserIdentityModel(); - $uIdModelSub = new UserIdentityModel(); - - $uIdModel->where('type', 'hmac_sha256')->orderBy('id')->chunk( - 100, - function ($identity) use ($uIdModelSub): void { + (new UserIdentityModel())->where('type', 'hmac_sha256')->orderBy('id')->chunk( + self::CHUNK_SIZE, + function (UserIdentity $identity): void { $timeNow = Time::now(); if (null !== $identity->expires && $identity->expires->isBefore($timeNow)) { - $this->write('HMAC Token ID: ' . $identity->id . ', already expired, skipped.'); + $this->write(sprintf('HMAC Token ID: %s, already expired, skipped.', $identity->id)); return; } $identity->expires = $timeNow; - $uIdModelSub->save($identity); + $this->saver->save($identity); - $this->write('HMAC Token ID: ' . $identity->id . ', set as expired.'); + $this->write(sprintf('HMAC Token ID: %s, set as expired.', $identity->id)); }, ); } diff --git a/tests/Commands/HmacTest.php b/tests/Commands/HmacTest.php index 405fbcaae..34f91ccfc 100644 --- a/tests/Commands/HmacTest.php +++ b/tests/Commands/HmacTest.php @@ -21,6 +21,7 @@ use CodeIgniter\Shield\Models\UserIdentityModel; use CodeIgniter\Shield\Models\UserModel; use CodeIgniter\Shield\Test\MockInputOutput; +use Config\Services; use Tests\Support\DatabaseTestCase; /** @@ -49,6 +50,8 @@ public function testEncrypt(): void $this->setMockIo([]); $this->assertNotFalse(command('shield:hmac encrypt')); + $this->assertSame('id: 1, encrypted.', trim($this->io->getOutputs())); + $tokenCheck = $idModel->find($token->id); $encrypter = new HmacEncrypter(); @@ -64,6 +67,56 @@ public function testEncrypt(): void $this->assertSame('id: 1, already encrypted, skipped.', $resultsString); } + public function testEncryptReportsKeysThatAreTooLong(): void + { + $idModel = new UserIdentityModel(); + + /** @var User $user */ + $user = fake(UserModel::class); + $token = $user->generateHmacToken('foo'); + + $rawSecretKey = $token->rawSecretKey; + $token->secret2 = $rawSecretKey; + $idModel->save($token); + + config('AuthToken')->secret2StorageLimit = 10; + + $this->setMockIo([]); + $this->assertNotFalse(command('shield:hmac encrypt')); + + $this->assertStringContainsString( + 'id: 1, Encrypted key too long. Unable to store value.', + $this->io->getOutputs(), + ); + $this->assertSame($rawSecretKey, $idModel->find($token->id)->secret2); + } + + public function testDecryptRestoresRawSecretKey(): void + { + $idModel = new UserIdentityModel(); + + /** @var User $user */ + $user = fake(UserModel::class); + $token = $user->generateHmacToken('foo'); + + $this->assertTrue((new HmacEncrypter())->isEncrypted($idModel->find($token->id)->secret2)); + + $this->setMockIo([]); + $this->assertNotFalse(command('shield:hmac decrypt')); + + $this->assertSame('id: 1, decrypted.', trim($this->io->getOutputs())); + $this->assertSame($token->rawSecretKey, $idModel->find($token->id)->secret2); + } + + public function testRunReturnsExitCodes(): void + { + $this->setMockIo([]); + $command = new Hmac(Services::logger(), Services::commands()); + + $this->assertSame(EXIT_ERROR, $command->run(['badcommand'])); + $this->assertSame(EXIT_SUCCESS, $command->run(['encrypt'])); + } + public function testDecrypt(): void { $idModel = new UserIdentityModel(); @@ -126,6 +179,7 @@ public function testReEncrypt(): void $tokenCheck1 = $idModel->find($token1->id); $descryptSecretKey1 = $encrypter->decrypt($tokenCheck1->secret2); $this->assertSame($token1->rawSecretKey, $descryptSecretKey1); + $this->assertTrue($encrypter->isEncryptedWithCurrentKey($tokenCheck1->secret2)); $tokenCheck2 = $idModel->find($token2->id); $descryptSecretKey2 = $encrypter->decrypt($tokenCheck2->secret2); @@ -162,6 +216,10 @@ public function testExpireAll(): void $this->assertCount(2, $results); $this->assertSame('HMAC Token ID: 1, already expired, skipped.', trim($results[0])); $this->assertSame('HMAC Token ID: 2, set as expired.', trim($results[1])); + + $idModel = new UserIdentityModel(); + $this->assertSame('2024-11-03 12:00:00', $idModel->find(1)->expires->format('Y-m-d H:i:s')); + $this->assertNotNull($idModel->find(2)->expires); } /** From 03c9e3d467f23969da29e5f546f49451160ed687 Mon Sep 17 00:00:00 2001 From: "John Paul E. Balandan, CPA" Date: Mon, 9 Nov 2026 20:45:18 +0800 Subject: [PATCH 2/2] refactor: reduce visibility on Hmac's actions --- src/Commands/Hmac.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Commands/Hmac.php b/src/Commands/Hmac.php index 78b416ba5..cb9fbf1df 100644 --- a/src/Commands/Hmac.php +++ b/src/Commands/Hmac.php @@ -120,7 +120,7 @@ public function run(array $params): int * * @throws ReflectionException */ - public function encrypt(): void + private function encrypt(): void { (new UserIdentityModel())->where('type', 'hmac_sha256')->orderBy('id')->chunk( self::CHUNK_SIZE, @@ -148,7 +148,7 @@ function (UserIdentity $identity): void { * * @throws ReflectionException */ - public function decrypt(): void + private function decrypt(): void { (new UserIdentityModel())->where('type', 'hmac_sha256')->orderBy('id')->chunk( self::CHUNK_SIZE, @@ -173,7 +173,7 @@ function (UserIdentity $identity): void { * * @throws ReflectionException */ - public function reEncrypt(): void + private function reEncrypt(): void { (new UserIdentityModel())->where('type', 'hmac_sha256')->orderBy('id')->chunk( self::CHUNK_SIZE, @@ -196,7 +196,7 @@ function (UserIdentity $identity): void { /** * Invalidates all HMAC Keys/Tokens for every user. */ - public function invalidateAll(): void + private function invalidateAll(): void { (new UserIdentityModel())->where('type', 'hmac_sha256')->orderBy('id')->chunk( self::CHUNK_SIZE,