Replace with helper

This commit is contained in:
Lance Pioch 2024-03-19 05:11:41 -04:00
parent d9cfb62a12
commit d58496a355
20 changed files with 28 additions and 125 deletions

View File

@ -3,7 +3,6 @@
namespace App\Extensions;
use App\Models\DatabaseHost;
use Illuminate\Contracts\Encryption\Encrypter;
class DynamicDatabaseConnection
{
@ -11,14 +10,6 @@ class DynamicDatabaseConnection
public const DB_COLLATION = 'utf8_unicode_ci';
public const DB_DRIVER = 'mysql';
/**
* DynamicDatabaseConnection constructor.
*/
public function __construct(
protected Encrypter $encrypter,
) {
}
/**
* Adds a dynamic database connection entry to the runtime config.
*/
@ -34,7 +25,7 @@ class DynamicDatabaseConnection
'port' => $host->port,
'database' => $database,
'username' => $host->username,
'password' => $this->encrypter->decrypt($host->password),
'password' => decrypt($host->password),
'charset' => self::DB_CHARSET,
'collation' => self::DB_COLLATION,
]);

View File

@ -7,7 +7,6 @@ use App\Models\Node;
use App\Models\ApiKey;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Services\Api\KeyCreationService;
class NodeAutoDeployController extends Controller
@ -16,7 +15,6 @@ class NodeAutoDeployController extends Controller
* NodeAutoDeployController constructor.
*/
public function __construct(
private Encrypter $encrypter,
private KeyCreationService $keyCreationService
) {
}
@ -58,7 +56,7 @@ class NodeAutoDeployController extends Controller
return new JsonResponse([
'node' => $node->id,
'token' => $key->identifier . $this->encrypter->decrypt($key->token),
'token' => $key->identifier . decrypt($key->token),
]);
}
}

View File

@ -11,7 +11,6 @@ use App\Notifications\MailTested;
use Illuminate\Support\Facades\Notification;
use App\Exceptions\DisplayException;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Providers\SettingsServiceProvider;
use App\Http\Requests\Admin\Settings\MailSettingsFormRequest;
@ -21,7 +20,6 @@ class MailController extends Controller
* MailController constructor.
*/
public function __construct(
private Encrypter $encrypter,
private Kernel $kernel,
) {
}
@ -56,7 +54,7 @@ class MailController extends Controller
foreach ($values as $key => $value) {
if (in_array($key, SettingsServiceProvider::getEncryptedKeys()) && !empty($value)) {
$value = $this->encrypter->encrypt($value);
$value = encrypt($value);
}
Setting::set('settings::' . $key, $value);

View File

@ -8,7 +8,6 @@ use App\Models\User;
use Illuminate\Http\JsonResponse;
use PragmaRX\Google2FA\Google2FA;
use Illuminate\Support\Facades\Event;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Events\Auth\ProvidedAuthenticationToken;
use App\Http\Requests\Auth\LoginCheckpointRequest;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
@ -21,7 +20,6 @@ class LoginCheckpointController extends AbstractLoginController
* LoginCheckpointController constructor.
*/
public function __construct(
private Encrypter $encrypter,
private Google2FA $google2FA,
private ValidationFactory $validation
) {
@ -67,7 +65,7 @@ class LoginCheckpointController extends AbstractLoginController
return $this->sendLoginResponse($user, $request);
}
} else {
$decrypted = $this->encrypter->decrypt($user->totp_secret);
$decrypted = decrypt($user->totp_secret);
if ($this->google2FA->verifyKey($decrypted, (string) $request->input('authentication_code'), config('panel.auth.2fa.window'))) {
Event::dispatch(new ProvidedAuthenticationToken($user));

View File

@ -4,7 +4,6 @@ namespace App\Http\Middleware\Api\Daemon;
use App\Models\Node;
use Illuminate\Http\Request;
use Illuminate\Contracts\Encryption\Encrypter;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@ -18,13 +17,6 @@ class DaemonAuthenticate
'daemon.configuration',
];
/**
* DaemonAuthenticate constructor.
*/
public function __construct(private Encrypter $encrypter)
{
}
/**
* Check if a request from the daemon can be properly attributed back to a single node instance.
*
@ -49,7 +41,7 @@ class DaemonAuthenticate
/** @var Node $node */
$node = Node::query()->where('daemon_token_id', $parts[0])->firstOrFail();
if (hash_equals((string) $this->encrypter->decrypt($node->daemon_token), $parts[1])) {
if (hash_equals((string) decrypt($node->daemon_token), $parts[1])) {
$request->attributes->set('node', $node);
return $next($request);

View File

@ -4,9 +4,7 @@ namespace App\Models;
use Illuminate\Support\Str;
use Symfony\Component\Yaml\Yaml;
use Illuminate\Container\Container;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
@ -136,7 +134,7 @@ class Node extends Model
'debug' => false,
'uuid' => $this->uuid,
'token_id' => $this->daemon_token_id,
'token' => Container::getInstance()->make(Encrypter::class)->decrypt($this->daemon_token),
'token' => decrypt($this->daemon_token),
'api' => [
'host' => '0.0.0.0',
'port' => $this->daemonListen,
@ -179,7 +177,7 @@ class Node extends Model
*/
public function getDecryptedKey(): string
{
return (string) Container::getInstance()->make(Encrypter::class)->decrypt(
return (string) decrypt(
$this->daemon_token
);
}

View File

@ -3,11 +3,10 @@
namespace App\Providers;
use App\Models\Setting;
use Exception;
use Psr\Log\LoggerInterface as Log;
use Illuminate\Database\QueryException;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Contracts\Encryption\DecryptException;
class SettingsServiceProvider extends ServiceProvider
{
@ -56,7 +55,7 @@ class SettingsServiceProvider extends ServiceProvider
/**
* Boot the service provider.
*/
public function boot(Encrypter $encrypter, Log $log): void
public function boot(Log $log): void
{
// Only set the email driver settings from the database if we
// are configured using SMTP as the driver.
@ -78,8 +77,9 @@ class SettingsServiceProvider extends ServiceProvider
$value = array_get($values, 'settings::' . $key, config(str_replace(':', '.', $key)));
if (in_array($key, self::$encrypted)) {
try {
$value = $encrypter->decrypt($value);
} catch (DecryptException $exception) {
$value = decrypt($value);
} catch (Exception) {
// ignore
}
}

View File

@ -3,19 +3,11 @@
namespace App\Services\Api;
use App\Models\ApiKey;
use Illuminate\Contracts\Encryption\Encrypter;
class KeyCreationService
{
private int $keyType = ApiKey::TYPE_NONE;
/**
* ApiKeyService constructor.
*/
public function __construct(private Encrypter $encrypter)
{
}
/**
* Set the type of key that should be created. By default, an orphaned key will be
* created. These keys cannot be used for anything, and will not render in the UI.
@ -39,7 +31,7 @@ class KeyCreationService
$data = array_merge($data, [
'key_type' => $this->keyType,
'identifier' => ApiKey::generateTokenIdentifier($this->keyType),
'token' => $this->encrypter->encrypt(str_random(ApiKey::KEY_LENGTH)),
'token' => encrypt(str_random(ApiKey::KEY_LENGTH)),
]);
if ($this->keyType === ApiKey::TYPE_APPLICATION) {

View File

@ -2,12 +2,10 @@
namespace App\Services\Databases;
use Exception;
use App\Models\Server;
use App\Models\Database;
use App\Helpers\Utilities;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Extensions\DynamicDatabaseConnection;
use App\Exceptions\Repository\DuplicateDatabaseNameException;
use App\Exceptions\Service\Database\TooManyDatabasesException;
@ -34,7 +32,6 @@ class DatabaseManagementService
public function __construct(
protected ConnectionInterface $connection,
protected DynamicDatabaseConnection $dynamic,
protected Encrypter $encrypter,
) {
}
@ -89,7 +86,7 @@ class DatabaseManagementService
$data = array_merge($data, [
'server_id' => $server->id,
'username' => sprintf('u%d_%s', $server->id, str_random(10)),
'password' => $this->encrypter->encrypt(
'password' => encrypt(
Utilities::randomStringWithSpecialCharacters(24)
),
]);
@ -103,7 +100,7 @@ class DatabaseManagementService
$database->createUser(
$database->username,
$database->remote,
$this->encrypter->decrypt($database->password),
decrypt($database->password),
$database->max_connections
);
$database->assignUserToDatabase($database->database, $database->username, $database->remote);

View File

@ -5,7 +5,6 @@ namespace App\Services\Databases;
use App\Models\Database;
use App\Helpers\Utilities;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Extensions\DynamicDatabaseConnection;
class DatabasePasswordService
@ -16,7 +15,6 @@ class DatabasePasswordService
public function __construct(
private ConnectionInterface $connection,
private DynamicDatabaseConnection $dynamic,
private Encrypter $encrypter,
) {
}
@ -35,7 +33,7 @@ class DatabasePasswordService
$this->dynamic->set('dynamic', $database->database_host_id);
$database->update([
'password' => $this->encrypter->encrypt($password),
'password' => encrypt($password),
]);
$database->dropUser($database->username, $database->remote);

View File

@ -5,7 +5,6 @@ namespace App\Services\Databases\Hosts;
use App\Models\DatabaseHost;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Extensions\DynamicDatabaseConnection;
class HostCreationService
@ -17,7 +16,6 @@ class HostCreationService
private ConnectionInterface $connection,
private DatabaseManager $databaseManager,
private DynamicDatabaseConnection $dynamic,
private Encrypter $encrypter,
) {
}
@ -30,7 +28,7 @@ class HostCreationService
{
return $this->connection->transaction(function () use ($data) {
$host = DatabaseHost::query()->create([
'password' => $this->encrypter->encrypt(array_get($data, 'password')),
'password' => encrypt(array_get($data, 'password')),
'name' => array_get($data, 'name'),
'host' => array_get($data, 'host'),
'port' => array_get($data, 'port'),

View File

@ -5,7 +5,6 @@ namespace App\Services\Databases\Hosts;
use App\Models\DatabaseHost;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Extensions\DynamicDatabaseConnection;
class HostUpdateService
@ -17,7 +16,6 @@ class HostUpdateService
private ConnectionInterface $connection,
private DatabaseManager $databaseManager,
private DynamicDatabaseConnection $dynamic,
private Encrypter $encrypter,
) {
}
@ -29,7 +27,7 @@ class HostUpdateService
public function handle(int $hostId, array $data): DatabaseHost
{
if (!empty(array_get($data, 'password'))) {
$data['password'] = $this->encrypter->encrypt($data['password']);
$data['password'] = encrypt($data['password']);
} else {
unset($data['password']);
}

View File

@ -5,7 +5,6 @@ namespace App\Services\Nodes;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Str;
use App\Models\Node;
use Illuminate\Contracts\Encryption\Encrypter;
class NodeCreationService
{
@ -17,7 +16,7 @@ class NodeCreationService
public function handle(array $data): Node
{
$data['uuid'] = Uuid::uuid4()->toString();
$data['daemon_token'] = app(Encrypter::class)->encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH));
$data['daemon_token'] = encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH));
$data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH);
return Node::query()->create($data);

View File

@ -5,7 +5,6 @@ namespace App\Services\Nodes;
use Illuminate\Support\Str;
use App\Models\Node;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Repositories\Daemon\DaemonConfigurationRepository;
use App\Exceptions\Http\Connection\DaemonConnectionException;
use App\Exceptions\Service\Node\ConfigurationNotPersistedException;
@ -18,7 +17,6 @@ class NodeUpdateService
public function __construct(
private ConnectionInterface $connection,
private DaemonConfigurationRepository $configurationRepository,
private Encrypter $encrypter,
) {
}
@ -30,7 +28,7 @@ class NodeUpdateService
public function handle(Node $node, array $data, bool $resetToken = false): Node
{
if ($resetToken) {
$data['daemon_token'] = $this->encrypter->encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH));
$data['daemon_token'] = encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH));
$data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH);
}

View File

@ -8,7 +8,6 @@ use Illuminate\Support\Str;
use App\Models\User;
use PragmaRX\Google2FA\Google2FA;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Exceptions\Service\User\TwoFactorAuthenticationTokenInvalid;
class ToggleTwoFactorService
@ -18,7 +17,6 @@ class ToggleTwoFactorService
*/
public function __construct(
private ConnectionInterface $connection,
private Encrypter $encrypter,
private Google2FA $google2FA,
) {
}
@ -34,7 +32,7 @@ class ToggleTwoFactorService
*/
public function handle(User $user, string $token, bool $toggleState = null): array
{
$secret = $this->encrypter->decrypt($user->totp_secret);
$secret = decrypt($user->totp_secret);
$isValidToken = $this->google2FA->verifyKey($secret, $token, config()->get('panel.auth.2fa.window'));

View File

@ -3,20 +3,11 @@
namespace App\Services\Users;
use App\Models\User;
use Illuminate\Contracts\Encryption\Encrypter;
class TwoFactorSetupService
{
public const VALID_BASE32_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
/**
* TwoFactorSetupService constructor.
*/
public function __construct(
private Encrypter $encrypter,
) {
}
/**
* Generate a 2FA token and store it in the database before returning the
* QR code URL. This URL will need to be attached to a QR generating service in
@ -35,7 +26,7 @@ class TwoFactorSetupService
throw new \RuntimeException($exception->getMessage(), 0, $exception);
}
$user->totp_secret = $this->encrypter->encrypt($secret);
$user->totp_secret = encrypt($secret);
$user->save();
$company = urlencode(preg_replace('/\s/', '', config('app.name')));

View File

@ -7,22 +7,11 @@ use League\Fractal\Resource\Item;
use App\Models\DatabaseHost;
use League\Fractal\Resource\NullResource;
use App\Services\Acl\Api\AdminAcl;
use Illuminate\Contracts\Encryption\Encrypter;
class ServerDatabaseTransformer extends BaseTransformer
{
protected array $availableIncludes = ['password', 'host'];
private Encrypter $encrypter;
/**
* Perform dependency injection.
*/
public function handle(Encrypter $encrypter)
{
$this->encrypter = $encrypter;
}
/**
* Return the resource name for the JSONAPI output.
*/
@ -56,7 +45,7 @@ class ServerDatabaseTransformer extends BaseTransformer
{
return $this->item($model, function (Database $model) {
return [
'password' => $this->encrypter->decrypt($model->password),
'password' => decrypt($model->password),
];
}, 'database_password');
}

View File

@ -6,23 +6,19 @@ use App\Models\Database;
use League\Fractal\Resource\Item;
use App\Models\Permission;
use League\Fractal\Resource\NullResource;
use Illuminate\Contracts\Encryption\Encrypter;
use App\Contracts\Extensions\HashidsInterface;
class DatabaseTransformer extends BaseClientTransformer
{
protected array $availableIncludes = ['password'];
private Encrypter $encrypter;
private HashidsInterface $hashids;
/**
* Handle dependency injection.
*/
public function handle(Encrypter $encrypter, HashidsInterface $hashids)
public function handle(HashidsInterface $hashids)
{
$this->encrypter = $encrypter;
$this->hashids = $hashids;
}
@ -59,7 +55,7 @@ class DatabaseTransformer extends BaseClientTransformer
return $this->item($database, function (Database $model) {
return [
'password' => $this->encrypter->decrypt($model->password),
'password' => decrypt($model->password),
];
}, 'database_password');
}

View File

@ -2,11 +2,9 @@
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\DB;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Contracts\Encryption\Encrypter;
class StoreNodeTokensAsEncryptedValue extends Migration
{
@ -33,14 +31,11 @@ class StoreNodeTokensAsEncryptedValue extends Migration
$table->text('daemon_token')->change();
});
/** @var \Illuminate\Contracts\Encryption\Encrypter $encrypter */
$encrypter = Container::getInstance()->make(Encrypter::class);
foreach (DB::select('SELECT id, daemon_token FROM nodes') as $datum) {
DB::update('UPDATE nodes SET uuid = ?, daemon_token_id = ?, daemon_token = ? WHERE id = ?', [
Uuid::uuid4()->toString(),
substr($datum->daemon_token, 0, 16),
$encrypter->encrypt(substr($datum->daemon_token, 16)),
encrypt(substr($datum->daemon_token, 16)),
$datum->id,
]);
}
@ -59,12 +54,9 @@ class StoreNodeTokensAsEncryptedValue extends Migration
public function down()
{
DB::transaction(function () {
/** @var \Illuminate\Contracts\Encryption\Encrypter $encrypter */
$encrypter = Container::getInstance()->make(Encrypter::class);
foreach (DB::select('SELECT id, daemon_token_id, daemon_token FROM nodes') as $datum) {
DB::update('UPDATE nodes SET daemon_token = ? WHERE id = ?', [
$datum->daemon_token_id . $encrypter->decrypt($datum->daemon_token),
$datum->daemon_token_id . decrypt($datum->daemon_token),
$datum->id,
]);
}

View File

@ -5,28 +5,13 @@ namespace App\Tests\Integration\Api\Daemon;
use App\Http\Middleware\Api\Daemon\DaemonAuthenticate;
use App\Models\Node;
use App\Tests\Unit\Http\Middleware\MiddlewareTestCase;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Mockery as m;
use Mockery\MockInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class DaemonAuthenticateTest extends MiddlewareTestCase
{
private MockInterface $encrypter;
/**
* Setup tests.
*/
public function setUp(): void
{
parent::setUp();
$this->encrypter = m::mock(Encrypter::class);
}
/**
* Test that if we are accessing the daemon configuration route this middleware is not
* applied in order to allow an unauthenticated request to use a token to grab data.
@ -86,8 +71,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($node->daemon_token_id . '.random_string_123');
$this->encrypter->expects('decrypt')->with($node->daemon_token)->andReturns(decrypt($node->daemon_token));
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
}
@ -116,7 +99,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');
$this->request->expects('bearerToken')->withNoArgs()->andReturn($node->daemon_token_id . '.the_same');
$this->encrypter->expects('decrypt')->with($node->daemon_token)->andReturns(decrypt($node->daemon_token));
$this->getMiddleware()->handle($this->request, $this->getClosureAssertions());
$this->assertRequestHasAttribute('node');
@ -147,6 +129,6 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
*/
private function getMiddleware(): DaemonAuthenticate
{
return new DaemonAuthenticate($this->encrypter);
return new DaemonAuthenticate();
}
}