Skip to content
Merged
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
18 changes: 0 additions & 18 deletions phpstan-baseline.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,24 +85,6 @@
'count' => 1,
'path' => __DIR__ . '/src/Collectors/Auth.php',
];
$ignoreErrors[] = [
'rawMessage' => 'Cannot access property $expires on array<string, string>|object.',
'identifier' => 'property.nonObject',
'count' => 3,
'path' => __DIR__ . '/src/Commands/Hmac.php',
];
$ignoreErrors[] = [
'rawMessage' => 'Cannot access property $id on array<string, string>|object.',
'identifier' => 'property.nonObject',
'count' => 9,
'path' => __DIR__ . '/src/Commands/Hmac.php',
];
$ignoreErrors[] = [
'rawMessage' => 'Cannot access property $secret2 on array<string, string>|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',
Expand Down
105 changes: 46 additions & 59 deletions src/Commands/Hmac.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@
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;
use ReflectionException;

class Hmac extends BaseCommand
{
private const CHUNK_SIZE = 100;

/**
* The Command's name
*
Expand Down Expand Up @@ -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
*
Expand All @@ -88,15 +96,15 @@ public function run(array $params): int
$action = $params[0] ?? null;

$this->encrypter = new HmacEncrypter();
$this->saver = new UserIdentityModel();

try {
match ($action) {
'encrypt' => $this->encrypt(),
'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');
Expand All @@ -112,30 +120,24 @@ public function run(array $params): int
*
* @throws ReflectionException
*/
public function encrypt(): void
private 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()));
}
},
);
Expand All @@ -146,27 +148,21 @@ static function ($identity) use ($uIdModelSub, $encrypter, $that): void {
*
* @throws ReflectionException
*/
public function decrypt(): void
private 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));
},
);
}
Expand All @@ -177,55 +173,46 @@ static function ($identity) use ($uIdModelSub, $encrypter, $that): void {
*
* @throws ReflectionException
*/
public function reEncrypt(): void
private 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));
},
);
}

/**
* Invalidates all HMAC Keys/Tokens for every user.
*/
public function invalidateAll(): void
private 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));
},
);
}
Expand Down
58 changes: 58 additions & 0 deletions tests/Commands/HmacTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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();
Expand All @@ -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();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}

/**
Expand Down
Loading