replace encrypt/ decrypt with encrypted casting

This commit is contained in:
Boy132 2024-05-28 15:24:20 +02:00
parent 15caac51fb
commit 82fd547484
40 changed files with 45 additions and 79 deletions

View File

@ -25,7 +25,7 @@ class DynamicDatabaseConnection
'port' => $host->port,
'database' => $database,
'username' => $host->username,
'password' => decrypt($host->password),
'password' => $host->password,
'charset' => self::DB_CHARSET,
'collation' => self::DB_COLLATION,
]);

View File

@ -19,7 +19,7 @@ class CreateApiKey extends CreateRecord
return $form
->schema([
Forms\Components\Hidden::make('identifier')->default(ApiKey::generateTokenIdentifier(ApiKey::TYPE_APPLICATION)),
Forms\Components\Hidden::make('token')->default(encrypt(str_random(ApiKey::KEY_LENGTH))),
Forms\Components\Hidden::make('token')->default(str_random(ApiKey::KEY_LENGTH)),
Forms\Components\Hidden::make('user_id')
->default(auth()->user()->id)

View File

@ -28,7 +28,7 @@ class ListApiKeys extends ListRecords
Tables\Columns\TextColumn::make('key')
->copyable()
->icon('tabler-clipboard-text')
->state(fn (ApiKey $key) => $key->identifier . decrypt($key->token)),
->state(fn (ApiKey $key) => $key->identifier . $key->token),
Tables\Columns\TextColumn::make('memo')
->label('Description')

View File

@ -74,15 +74,6 @@ class CreateDatabaseHost extends CreateRecord
]);
}
protected function mutateFormDataBeforeCreate(array $data): array
{
if (isset($data['password'])) {
$data['password'] = encrypt($data['password']);
}
return $data;
}
protected function getHeaderActions(): array
{
return [

View File

@ -76,15 +76,6 @@ class EditDatabaseHost extends EditRecord
];
}
protected function mutateFormDataBeforeSave(array $data): array
{
if (isset($data['password'])) {
$data['password'] = encrypt($data['password']);
}
return $data;
}
protected function getFormActions(): array
{
return [];

View File

@ -28,13 +28,13 @@ class DatabasesRelationManager extends RelationManager
->requiresConfirmation()
->action(fn (DatabasePasswordService $service, Database $database, $set, $get) => $this->rotatePassword($service, $database, $set, $get))
)
->formatStateUsing(fn (Database $database) => decrypt($database->password)),
->formatStateUsing(fn (Database $database) => $database->password),
Forms\Components\TextInput::make('remote')->label('Connections From'),
Forms\Components\TextInput::make('max_connections'),
Forms\Components\TextInput::make('JDBC')
->label('JDBC Connection String')
->columnSpanFull()
->formatStateUsing(fn (Forms\Get $get, Database $database) => 'jdbc:mysql://' . $get('username') . ':' . urlencode(decrypt($database->password)) . '@' . $database->host->host . ':' . $database->host->port . '/' . $get('database')),
->formatStateUsing(fn (Forms\Get $get, Database $database) => 'jdbc:mysql://' . $get('username') . ':' . urlencode($database->password) . '@' . $database->host->host . ':' . $database->host->port . '/' . $get('database')),
]);
}
public function table(Table $table): Table

View File

@ -56,7 +56,7 @@ class NodeAutoDeployController extends Controller
return new JsonResponse([
'node' => $node->id,
'token' => $key->identifier . decrypt($key->token),
'token' => $key->identifier . $key->token,
]);
}
}

View File

@ -65,9 +65,7 @@ class LoginCheckpointController extends AbstractLoginController
return $this->sendLoginResponse($user, $request);
}
} else {
$decrypted = decrypt($user->totp_secret);
if ($this->google2FA->verifyKey($decrypted, (string) $request->input('authentication_code'), config('panel.auth.2fa.window'))) {
if ($this->google2FA->verifyKey($user->totp_secret, (string) $request->input('authentication_code'), config('panel.auth.2fa.window'))) {
Event::dispatch(new ProvidedAuthenticationToken($user));
return $this->sendLoginResponse($user, $request);

View File

@ -41,7 +41,7 @@ class DaemonAuthenticate
/** @var Node $node */
$node = Node::query()->where('daemon_token_id', $parts[0])->firstOrFail();
if (hash_equals((string) decrypt($node->daemon_token), $parts[1])) {
if (hash_equals((string) $node->daemon_token, $parts[1])) {
$request->attributes->set('node', $node);
return $next($request);

View File

@ -149,6 +149,7 @@ class ApiKey extends Model
'user_id' => 'int',
'last_used_at' => 'datetime',
'expires_at' => 'datetime',
'token' => 'encrypted',
self::CREATED_AT => 'datetime',
self::UPDATED_AT => 'datetime',
'r_' . AdminAcl::RESOURCE_USERS => 'int',
@ -188,7 +189,7 @@ class ApiKey extends Model
$identifier = substr($token, 0, self::IDENTIFIER_LENGTH);
$model = static::where('identifier', $identifier)->first();
if (!is_null($model) && decrypt($model->token) === substr($token, strlen($identifier))) {
if (!is_null($model) && $model->token === substr($token, strlen($identifier))) {
return $model;
}

View File

@ -64,6 +64,7 @@ class Database extends Model
'server_id' => 'integer',
'database_host_id' => 'integer',
'max_connections' => 'integer',
'password' => 'encrypted'
];
}

View File

@ -60,6 +60,7 @@ class DatabaseHost extends Model
'id' => 'integer',
'max_databases' => 'integer',
'node_id' => 'integer',
'password' => 'encrypted',
'created_at' => 'immutable_datetime',
'updated_at' => 'immutable_datetime',
];

View File

@ -127,6 +127,7 @@ class Node extends Model
'cpu' => 'integer',
'daemon_listen' => 'integer',
'daemon_sftp' => 'integer',
'daemon_token' => 'encrypted',
'behind_proxy' => 'boolean',
'public' => 'boolean',
'maintenance_mode' => 'boolean',
@ -143,7 +144,7 @@ class Node extends Model
{
static::creating(function (self $node) {
$node->uuid = Str::uuid();
$node->daemon_token = encrypt(Str::random(self::DAEMON_TOKEN_LENGTH));
$node->daemon_token = Str::random(self::DAEMON_TOKEN_LENGTH);
$node->daemon_token_id = Str::random(self::DAEMON_TOKEN_ID_LENGTH);
return true;
@ -171,7 +172,7 @@ class Node extends Model
'debug' => false,
'uuid' => $this->uuid,
'token_id' => $this->daemon_token_id,
'token' => decrypt($this->daemon_token),
'token' => $this->daemon_token,
'api' => [
'host' => '0.0.0.0',
'port' => $this->daemon_listen,
@ -209,16 +210,6 @@ class Node extends Model
return json_encode($this->getConfiguration(), $pretty ? JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT : JSON_UNESCAPED_SLASHES);
}
/**
* Helper function to return the decrypted key for a node.
*/
public function getDecryptedKey(): string
{
return (string) decrypt(
$this->daemon_token
);
}
public function isUnderMaintenance(): bool
{
return $this->maintenance_mode;

View File

@ -31,7 +31,7 @@ trait HasAccessTokens
'user_id' => $this->id,
'key_type' => ApiKey::TYPE_ACCOUNT,
'identifier' => ApiKey::generateTokenIdentifier(ApiKey::TYPE_ACCOUNT),
'token' => encrypt($plain = Str::random(ApiKey::KEY_LENGTH)),
'token' => $plain = Str::random(ApiKey::KEY_LENGTH),
'memo' => $memo ?? '',
'allowed_ips' => $ips ?? [],
]);

View File

@ -171,6 +171,7 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac
'use_totp' => 'boolean',
'gravatar' => 'boolean',
'totp_authenticated_at' => 'datetime',
'totp_secret' => 'encrypted',
];
}

View File

@ -60,7 +60,7 @@ class AppServiceProvider extends ServiceProvider
'daemon',
fn (Node $node, array $headers = []) => Http::acceptJson()
->asJson()
->withToken($node->getDecryptedKey())
->withToken($node->daemon_token)
->withHeaders($headers)
->withOptions(['verify' => (bool) app()->environment('production')])
->timeout(config('panel.guzzle.timeout'))

View File

@ -31,7 +31,7 @@ class KeyCreationService
$data = array_merge($data, [
'key_type' => $this->keyType,
'identifier' => ApiKey::generateTokenIdentifier($this->keyType),
'token' => encrypt(str_random(ApiKey::KEY_LENGTH)),
'token' => str_random(ApiKey::KEY_LENGTH),
]);
if ($this->keyType === ApiKey::TYPE_APPLICATION) {

View File

@ -86,9 +86,7 @@ class DatabaseManagementService
$data = array_merge($data, [
'server_id' => $server->id,
'username' => sprintf('u%d_%s', $server->id, str_random(10)),
'password' => encrypt(
Utilities::randomStringWithSpecialCharacters(24)
),
'password' => Utilities::randomStringWithSpecialCharacters(24),
]);
return $this->connection->transaction(function () use ($data, &$database) {
@ -100,7 +98,7 @@ class DatabaseManagementService
$database->createUser(
$database->username,
$database->remote,
decrypt($database->password),
$database->password,
$database->max_connections
);
$database->assignUserToDatabase($database->database, $database->username, $database->remote);

View File

@ -33,7 +33,7 @@ class DatabasePasswordService
$this->dynamic->set('dynamic', $database->database_host_id);
$database->update([
'password' => encrypt($password),
'password' => $password,
]);
$database->dropUser($database->username, $database->remote);

View File

@ -28,7 +28,7 @@ class HostCreationService
{
return $this->connection->transaction(function () use ($data) {
$host = DatabaseHost::query()->create([
'password' => encrypt(array_get($data, 'password')),
'password' => array_get($data, 'password'),
'name' => array_get($data, 'name'),
'host' => array_get($data, 'host'),
'port' => array_get($data, 'port'),

View File

@ -26,9 +26,7 @@ class HostUpdateService
*/
public function handle(int $hostId, array $data): DatabaseHost
{
if (!empty(array_get($data, 'password'))) {
$data['password'] = encrypt($data['password']);
} else {
if (empty(array_get($data, 'password'))) {
unset($data['password']);
}

View File

@ -16,7 +16,7 @@ class NodeCreationService
public function handle(array $data): Node
{
$data['uuid'] = Uuid::uuid4()->toString();
$data['daemon_token'] = encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH));
$data['daemon_token'] = Str::random(Node::DAEMON_TOKEN_LENGTH);
$data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH);
return Node::query()->create($data);

View File

@ -63,7 +63,7 @@ class NodeJWTService
public function handle(Node $node, ?string $identifiedBy, string $algo = 'md5'): Plain
{
$identifier = hash($algo, $identifiedBy);
$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText($node->getDecryptedKey()));
$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText($node->daemon_token));
$builder = $config->builder(new TimestampDates())
->issuedBy(config('app.url'))

View File

@ -28,7 +28,7 @@ class NodeUpdateService
public function handle(Node $node, array $data, bool $resetToken = false): Node
{
if ($resetToken) {
$data['daemon_token'] = encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH));
$data['daemon_token'] = Str::random(Node::DAEMON_TOKEN_LENGTH);
$data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH);
}

View File

@ -32,9 +32,7 @@ class ToggleTwoFactorService
*/
public function handle(User $user, string $token, bool $toggleState = null): array
{
$secret = decrypt($user->totp_secret);
$isValidToken = $this->google2FA->verifyKey($secret, $token, config()->get('panel.auth.2fa.window'));
$isValidToken = $this->google2FA->verifyKey($user->totp_secret, $token, config()->get('panel.auth.2fa.window'));
if (!$isValidToken) {
throw new TwoFactorAuthenticationTokenInvalid();

View File

@ -26,7 +26,7 @@ class TwoFactorSetupService
throw new \RuntimeException($exception->getMessage(), 0, $exception);
}
$user->totp_secret = encrypt($secret);
$user->totp_secret = $secret;
$user->save();
$company = urlencode(preg_replace('/\s/', '', config('app.name')));

View File

@ -45,7 +45,7 @@ class ServerDatabaseTransformer extends BaseTransformer
{
return $this->item($model, function (Database $model) {
return [
'password' => decrypt($model->password),
'password' => $model->password,
];
}, 'database_password');
}

View File

@ -55,7 +55,7 @@ class DatabaseTransformer extends BaseClientTransformer
return $this->item($database, function (Database $model) {
return [
'password' => decrypt($model->password),
'password' => $model->password,
];
}, 'database_password');
}

View File

@ -26,7 +26,7 @@ class ApiKeyFactory extends Factory
return [
'key_type' => ApiKey::TYPE_APPLICATION,
'identifier' => ApiKey::generateTokenIdentifier(ApiKey::TYPE_APPLICATION),
'token' => $token ?: $token = encrypt(Str::random(ApiKey::KEY_LENGTH)),
'token' => $token ?: $token = Str::random(ApiKey::KEY_LENGTH),
'allowed_ips' => null,
'memo' => 'Test Function Key',
'created_at' => Carbon::now(),

View File

@ -27,7 +27,7 @@ class DatabaseFactory extends Factory
'database' => Str::random(10),
'username' => Str::random(10),
'remote' => '%',
'password' => $password ?: encrypt('test123'),
'password' => $password ?: 'test123',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
];

View File

@ -3,7 +3,6 @@
namespace Database\Factories;
use App\Models\DatabaseHost;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Factories\Factory;
class DatabaseHostFactory extends Factory
@ -25,7 +24,7 @@ class DatabaseHostFactory extends Factory
'host' => $this->faker->unique()->ipv4(),
'port' => 3306,
'username' => $this->faker->colorName(),
'password' => Crypt::encrypt($this->faker->word()),
'password' => $this->faker->word(),
];
}
}

View File

@ -5,7 +5,6 @@ namespace Database\Factories;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Str;
use App\Models\Node;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Factories\Factory;
class NodeFactory extends Factory
@ -37,7 +36,7 @@ class NodeFactory extends Factory
'cpu_overallocate' => 0,
'upload_size' => 100,
'daemon_token_id' => Str::random(Node::DAEMON_TOKEN_ID_LENGTH),
'daemon_token' => Crypt::encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH)),
'daemon_token' => Str::random(Node::DAEMON_TOKEN_LENGTH),
'daemon_listen' => 8080,
'daemon_sftp' => 2022,
'daemon_base' => '/var/lib/panel/volumes',

View File

@ -33,7 +33,7 @@
</tr>
@foreach($keys as $key)
<tr>
<td><code>{{ $key->identifier }}{{ decrypt($key->token) }}</code></td>
<td><code>{{ $key->identifier }}{{ $key->token }}</code></td>
<td>{{ $key->memo }}</td>
<td>
@if(!is_null($key->last_used_at))

View File

@ -49,7 +49,7 @@
</tr>
@foreach ($nodes as $node)
<tr>
<td class="text-center text-muted left-icon" data-action="ping" data-secret="{{ $node->getDecryptedKey() }}" data-location="{{ $node->scheme }}://{{ $node->fqdn }}:{{ $node->daemon_listen }}/api/system"><i class="fa fa-fw fa-refresh fa-spin"></i></td>
<td class="text-center text-muted left-icon" data-action="ping" data-secret="{{ $node->daemon_token }}" data-location="{{ $node->scheme }}://{{ $node->fqdn }}:{{ $node->daemon_listen }}/api/system"><i class="fa fa-fw fa-refresh fa-spin"></i></td>
<td>{!! $node->maintenance_mode ? '<span class="label label-warning"><i class="fa fa-wrench"></i></span> ' : '' !!}<a href="{{ route('admin.nodes.view', $node->id) }}">{{ $node->name }}</a></td>
<td>{{ $node->memory }} MiB</td>
<td>{{ $node->disk }} MiB</td>

View File

@ -37,7 +37,7 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
$this
->withHeader('Accept', 'application/vnd.panel.v1+json')
->withHeader('Authorization', 'Bearer ' . $this->key->identifier . decrypt($this->key->token));
->withHeader('Authorization', 'Bearer ' . $this->key->identifier . $this->key->token);
}
public function getApiUser(): User
@ -57,7 +57,7 @@ abstract class ApplicationApiIntegrationTestCase extends IntegrationTestCase
{
$this->key = $this->createApiKey($user, $permissions);
$this->withHeader('Authorization', 'Bearer ' . $this->key->identifier . decrypt($this->key->token));
$this->withHeader('Authorization', 'Bearer ' . $this->key->identifier . $this->key->token);
return $this->key;
}

View File

@ -71,7 +71,7 @@ class ApiKeyControllerTest extends ClientApiIntegrationTestCase
$key = ApiKey::query()->where('identifier', $response->json('attributes.identifier'))->firstOrFail();
$this->assertJsonTransformedWith($response->json('attributes'), $key);
$response->assertJsonPath('meta.secret_token', decrypt($key->token));
$response->assertJsonPath('meta.secret_token', $key->token);
$this->assertActivityFor('user:api-key.create', $user, [$key, $user]);
}

View File

@ -62,7 +62,7 @@ class WebsocketControllerTest extends ClientApiIntegrationTestCase
$this->assertStringStartsWith('wss://', $connection, 'Failed asserting that websocket connection address has expected "wss://" prefix.');
$this->assertStringEndsWith("/api/servers/$server->uuid/ws", $connection, 'Failed asserting that websocket connection address uses expected Daemon endpoint.');
$config = Configuration::forSymmetricSigner(new Sha256(), $key = InMemory::plainText($server->node->getDecryptedKey()));
$config = Configuration::forSymmetricSigner(new Sha256(), $key = InMemory::plainText($server->node->daemon_token));
$config->setValidationConstraints(new SignedWith(new Sha256(), $key));
/** @var \Lcobucci\JWT\Token\Plain $token */
$token = $config->parser()->parse($response->json('data.token'));
@ -107,7 +107,7 @@ class WebsocketControllerTest extends ClientApiIntegrationTestCase
$response->assertOk();
$response->assertJsonStructure(['data' => ['token', 'socket']]);
$config = Configuration::forSymmetricSigner(new Sha256(), $key = InMemory::plainText($server->node->getDecryptedKey()));
$config = Configuration::forSymmetricSigner(new Sha256(), $key = InMemory::plainText($server->node->daemon_token));
$config->setValidationConstraints(new SignedWith(new Sha256(), $key));
/** @var \Lcobucci\JWT\Token\Plain $token */
$token = $config->parser()->parse($response->json('data.token'));

View File

@ -85,8 +85,7 @@ class TwoFactorControllerTest extends ClientApiIntegrationTestCase
/** @var \PragmaRX\Google2FA\Google2FA $service */
$service = $this->app->make(Google2FA::class);
$secret = decrypt($user->totp_secret);
$token = $service->getCurrentOtp($secret);
$token = $service->getCurrentOtp($user->totp_secret);
$response = $this->actingAs($user)->postJson('/api/client/account/two-factor', [
'code' => $token,

View File

@ -94,7 +94,7 @@ class DaemonAuthenticateTest extends MiddlewareTestCase
public function testSuccessfulMiddlewareProcess(): void
{
$node = Node::factory()->create();
$node->daemon_token = encrypt('the_same');
$node->daemon_token = 'the_same';
$node->save();
$this->request->expects('route->getName')->withNoArgs()->andReturn('random.route');

View File

@ -229,6 +229,6 @@ class SftpAuthenticationControllerTest extends IntegrationTestCase
{
$node = $node ?? $this->server->node;
$this->withHeader('Authorization', 'Bearer ' . $node->daemon_token_id . '.' . decrypt($node->daemon_token));
$this->withHeader('Authorization', 'Bearer ' . $node->daemon_token_id . '.' . $node->daemon_token);
}
}