Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
JaZo committed Mar 4, 2024
1 parent 9e04f36 commit d82e2d3
Show file tree
Hide file tree
Showing 6 changed files with 254 additions and 6 deletions.
39 changes: 39 additions & 0 deletions MIGRATING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Migrating swisnl/laravel-encrypted-data

## To Laravel Encrypted Casting
The main difference between this package and [Laravel Encrypted Casting](https://laravel.com/docs/10.x/eloquent-mutators#encrypted-casting) is that this package serializes the data before encrypting it, while Laravel Encrypted Casting encrypts the data directly. This means that the data is not compatible between the two packages. In order to migrate from this package to Laravel Encrypted Casting, you will need to decrypt the data and then re-encrypt it using Laravel Encrypted Casting. Here is a step-by-step guide on how to do this:

[//]: # (TODO: What to do when you need serialized data?)

1. Set up Encrypted Casting, but keep extending `EncryptedModel` from this package:
```diff
- protected $encrypted = [
- 'secret',
- ];
+ protected $casts = [
+ 'secret' => 'encrypted',
+ ];
```
2. Set up our custom model encrypter in your `AppServiceProvider`:
```php
public function boot(): void
{
$modelEncrypter = new \Swis\Laravel\Encrypted\ModelEncrypter();
YourEncryptedModel::encryptUsing($modelEncrypter);
// ... all your other models that extend \Swis\Laravel\Encrypted\EncryptedModel
}
```
3. Run our re-encryption command:
```bash
php artisan encrypted-data:re-encrypt:models --quietly --no-touch
```
N.B. Use `--help` to see all available options and modify as needed!
4. Remove the `Swis\Laravel\Encrypted\EncryptedModel` from your models and replace it with `Illuminate\Database\Eloquent\Model`:
```diff
- use Swis\Laravel\Encrypted\EncryptedModel
+ use Illuminate\Database\Eloquent\Model

- class YourEncryptedModel extends EncryptedModel
+ class YourEncryptedModel extends Model
```
5. Remove our custom model encrypter from your `AppServiceProvider` (step 2).
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ This package contains several Laravel utilities to work with encrypted data.

Via Composer

``` bash
$ composer require swisnl/laravel-encrypted-data
```bash
composer require swisnl/laravel-encrypted-data
```

N.B. Using Laravel 6-8? Please use version [1.x](https://github.com/swisnl/laravel-encrypted-data/tree/1.x) of this package.
Expand All @@ -33,7 +33,7 @@ N.B. Using Laravel 6-8? Please use version [1.x](https://github.com/swisnl/larav
Extend `\Swis\Laravel\Encrypted\EncryptedModel` in your model and define the encrypted fields. Make sure your database columns are long enough, so your data isn't truncated!

``` php
```php
protected $encrypted = [
'secret',
];
Expand All @@ -45,7 +45,7 @@ You can now simply use the model properties as usual and everything will be encr

Configure the storage driver in `config/filesystems.php`.

``` php
```php
'disks' => [
'local' => [
'driver' => 'local-encrypted',
Expand Down Expand Up @@ -78,8 +78,8 @@ Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed re

## Testing

``` bash
$ composer test
```bash
composer test
```

## Contributing
Expand Down
132 changes: 132 additions & 0 deletions src/Commands/ReEncryptModels.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace Swis\Laravel\Encrypted\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Symfony\Component\Finder\Finder;

class ReEncryptModels extends Command
{
protected $signature = 'encrypted-data:re-encrypt:models
{--model=* : Class names of the models to be re-encrypted}
{--except=* : Class names of the models to be excluded from re-encryption}
{--path=* : Absolute path(s) to directories where models are located}
{--chunk=1000 : The number of models to retrieve per chunk of models to be re-encrypted}
{--quietly : Re-encrypt the models without raising any events}
{--no-touch : Re-encrypt the models without updating timestamps}
{--with-trashed : Re-encrypt trashed models}';

protected $description = 'Re-encrypt models';

public function handle(): int
{
$models = $this->models();

if ($models->isEmpty()) {
$this->warn('No models found.');

return 1;
}

$models->each(function (string $model) {
$this->line("Re-encrypting {$model}...");
$this->reEncryptModels($model);
});

$this->info('Re-encrypting done!');

return 0;
}

/**
* @param class-string<\Illuminate\Database\Eloquent\Model> $modelClass
*/
protected function reEncryptModels(string $modelClass): void
{
$modelClass::unguarded(function () use ($modelClass) {
$modelClass::query()
->when($this->option('with-trashed') && in_array(SoftDeletes::class, class_uses_recursive($modelClass), true), function ($query) {
$query->withTrashed();
})
->eachById(
function (Model $model) {
if ($this->option('no-touch')) {
$model->timestamps = false;
}

// Set each encrypted attribute to trigger re-encryption
collect($model->getCasts())
->keys()
->filter(fn ($key) => $model->hasCast($key, ['encrypted', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object']))
->each(fn ($key) => $model->setAttribute($key, $model->getAttribute($key)));

if ($this->option('quietly')) {
$model->saveQuietly();
} else {
$model->save();
}
},
$this->option('chunk')
);
});
}

/**
* Determine the models that should be re-encrypted.
*
* @return \Illuminate\Support\Collection<int, class-string<\Illuminate\Database\Eloquent\Model>>
*/
protected function models(): Collection
{
if (!empty($models = $this->option('model'))) {
return collect($models)->filter(function ($model) {
return class_exists($model);
})->values();
}

$except = $this->option('except');

if (!empty($models) && !empty($except)) {
throw new \InvalidArgumentException('The --models and --except options cannot be combined.');
}

return collect(Finder::create()->in($this->getPath())->files()->name('*.php'))
->map(function ($model) {
$namespace = $this->laravel->getNamespace();

return $namespace.str_replace(
['/', '.php'],
['\\', ''],
Str::after($model->getRealPath(), realpath(app_path()).DIRECTORY_SEPARATOR)
);
})->when(!empty($except), function ($models) use ($except) {
return $models->reject(function ($model) use ($except) {
return in_array($model, $except, true);
});
})->filter(function ($model) {
return class_exists($model);
})->filter(function ($model) {
return is_a($model, Model::class, true);
})->values();
}

/**
* Get the path where models are located.
*
* @return string[]|string
*/
protected function getPath(): string|array
{
if (!empty($path = $this->option('path'))) {
return collect($path)->map(function ($path) {
return base_path($path);
})->all();
}

return app_path('Models');
}
}
7 changes: 7 additions & 0 deletions src/EncryptedDataServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use League\Flysystem\UnixVisibility\PortableVisibilityConverter;
use League\Flysystem\Visibility;
use Swis\Flysystem\Encrypted\EncryptedFilesystemAdapter;
use Swis\Laravel\Encrypted\Commands\ReEncryptModels;

class EncryptedDataServiceProvider extends ServiceProvider
{
Expand All @@ -28,6 +29,12 @@ protected function registerEncrypter(): void
public function boot(): void
{
$this->setupStorageDriver();

if ($this->app->runningInConsole()) {
$this->commands([
ReEncryptModels::class,
]);
}
}

protected function setupStorageDriver(): void
Expand Down
20 changes: 20 additions & 0 deletions src/EncryptedModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

/**
* @deprecated use Laravel's built-in encrypted casting instead, this class will be removed in a future version
* @see ../MIGRATING.md for a step-by-step guide on how to migrate
*/
class EncryptedModel extends Model
{
/**
Expand All @@ -28,6 +32,22 @@ public function setRawAttributes(array $attributes, $sync = false)
return parent::setRawAttributes($this->decryptAttributes($attributes), $sync);
}

/**
* {@inheritdoc}
*
* @param string $key
*
* @return bool
*/
public function originalIsEquivalent($key)
{
if (static::$encrypter instanceof ModelEncrypter && $this->isEncryptedCastable($key)) {
return false;
}

return parent::originalIsEquivalent($key);
}

/**
* {@inheritdoc}
*
Expand Down
50 changes: 50 additions & 0 deletions src/ModelEncrypter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace Swis\Laravel\Encrypted;

use Illuminate\Contracts\Encryption\Encrypter;

/**
* @deprecated only use this when migrating from this package to Laravel's built-in encrypted casting
*/
class ModelEncrypter implements Encrypter
{
private ?Encrypter $encrypter;

public function __construct()
{
$this->encrypter = app('encrypted-data.encrypter');
}

public function encrypt($value, $serialize = true)
{
return $this->encrypter->encrypt($value, $serialize);
}

public function decrypt($payload, $unserialize = true)
{
$decrypted = $this->encrypter->decrypt($payload, false);

$unserialized = @unserialize($decrypted);
if ($unserialized === false && $decrypted !== 'b:0;') {
return $decrypted;
}

return $unserialized;
}

public function getKey()
{
return $this->encrypter->getKey();
}

public function getAllKeys()
{
return $this->encrypter->getAllKeys();
}

public function getPreviousKeys()
{
return $this->encrypter->getPreviousKeys();
}
}

0 comments on commit d82e2d3

Please sign in to comment.