Compare commits

..

No commits in common. "9193ff649a5355f2334ecb3f2d7eefa75721d467" and "cff6336828e82b0d2278718ee57af4befaae93a9" have entirely different histories.

13 changed files with 576 additions and 1533 deletions

View File

@ -20,7 +20,7 @@
}
},
"require": {
"php": "^7.2.5|^8.0",
"php": "^7.2.5",
"illuminate/config": "^7.0|^8.0",
"illuminate/support": "^7.0|^8.0",
"illuminate/database": "^7.0|^8.0",

1635
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,22 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd" backupGlobals="false" backupStaticAttributes="false" bootstrap="vendor/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false">
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./src</directory>
</include>
</coverage>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
</testsuites>
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="MAIL_DRIVER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="file"/>
<server name="DB_CONNECTION" value="testing"/>
</php>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="MAIL_DRIVER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="file"/>
<server name="DB_CONNECTION" value="testing"/>
</php>
</phpunit>

View File

@ -1,14 +1,12 @@
# CipherSweet for Laravel
A Laravel implementation of [Paragon Initiative Enterprises CipherSweet](https://ciphersweet.paragonie.com) searchable
field level encryption.
A Laravel implementation of [Paragon Initiative Enterprises CipherSweet](https://ciphersweet.paragonie.com) searchable field level encryption.
Make sure you have some basic understanding of CipherSweet before continuing.
## Installation
Install the package using composer:
```
composer require bjorn-voesten/ciphersweet-for-laravel
```
@ -18,13 +16,10 @@ The package will then automatically register itself.
#### Encryption key
In your `.env` file you should add:
```dotenv
CIPHERSWEET_KEY=
```
And then generate an encryption key:
```
php artisan ciphersweet:key
```
@ -32,7 +27,6 @@ php artisan ciphersweet:key
#### Config file
Publish the config file:
```
php artisan vendor:publish --tag=ciphersweet-config
```
@ -41,9 +35,8 @@ php artisan vendor:publish --tag=ciphersweet-config
### Define encryption
Add the `BjornVoesten\CipherSweet\Concerns\WithAttributeEncryption` trait to your model <br>
Add the `BjornVoesten\CipherSweet\Concerns\WithAttributeEncryption` trait to your model <br>
and add the `BjornVoesten\CipherSweet\Casts\Encrypted` cast to the attributes you want to encrypt.
```php
<?php
@ -106,42 +99,29 @@ class User extends Model
Attributes will be automatically encrypted and decrypted when filling and retrieving attribute values.
**Note** Because the package uses Laravel casts it is not possible to combine the `Encrypted` cast and
accessors/mutators.
**Note** Because the package uses Laravel casts it is not possible to combine the `Encrypted` cast and accessors/mutators.
### Searching
**Note** When searching with the `equal to` operator models will be returned when the value is found in one of all
available or defined indexes. When searching with the `not equal to` operator all models where the value is not found in
any of the available or the defined indexes are returned.
**Note** When searching with the `equal to` operator models will be returned when the value is found in one of all available or defined indexes. When searching with the `not equal to` operator all models where the value is not found in any of the available or the defined indexes are returned.
**Note**
Because of the limited search possibilities in CipherSweet only the `=` and `!=` operators are available when searching
encrypted attributes.
Because of the limited search possibilities in CipherSweet only the `=` and `!=` operators are available when searching encrypted attributes.
<br/>
#### `whereEncrypted`, `orWhereEncrypted`
#### `whereEncrypted`
```php
User::query()
->whereEncrypted('social_security_number', '=', '123-456-789')
->orWhereEncrypted('social_security_number', '=', '123-456-789')
->get();
```
<br/>
#### `whereInEncrypted`, `orWhereInEncrypted`
#### `orWhereEncrypted`
```php
User::query()
->whereInEncrypted('social_security_number', [
'123-456-789',
])
->orWhereInEncrypted('social_security_number', [
'456-123-789',
])
->whereEncrypted('social_security_number', '=', '123-456-789')
->orWhereEncrypted('social_security_number', '=', '456-123-789')
->get();
```
@ -151,8 +131,7 @@ Please see [contributing.md](contributing.md) for details and a todolist.
## Security
If you discover any security related issues, please email [security@bjornvoesten.com](mailto:security@bjornvoesten.com)
instead of using the issue tracker.
If you discover any security related issues, please email [security@bjornvoesten.com](mailto:security@bjornvoesten.com) instead of using the issue tracker.
## Testing

View File

@ -13,10 +13,10 @@ class Encrypted implements CastsAttributes
* @param string $key
* @param mixed $value
* @param array $attributes
* @return string|null
* @return string
* @throws \Exception
*/
public function get($model, string $key, $value, array $attributes): ?string
public function get($model, string $key, $value, array $attributes)
{
return $model->decrypt($key);
}

View File

@ -108,23 +108,23 @@ class CipherSweetService
$field = new EncryptedField(
$this->engine,
$table = $model->getTable(),
$attribute->column
$attribute->column,
);
// Map and add the indexes to the encrypted
// field instance.
collect($attribute->indexes)
->map(static function (Index $index) {
return new BlindIndex(
->map(function (Index $index) {
return $index = new BlindIndex(
$index->column,
$index->transformers,
$index->bits,
$index->fast
$index->fast,
);
})
->each(static function ($index) use ($field) {
return $field->addBlindIndex($index);
});
->each(
fn($index) => $field->addBlindIndex($index)
);
return $field;
}
@ -134,24 +134,18 @@ class CipherSweetService
*
* @param \Illuminate\Database\Eloquent\Model|\BjornVoesten\CipherSweet\Concerns\WithAttributeEncryption $model
* @param string $attribute
* @param string|int|boolean|null $value
* @param string|int|boolean $value
* @return array
* @throws \ParagonIE\CipherSweet\Exception\BlindIndexNameCollisionException
* @throws \ParagonIE\CipherSweet\Exception\BlindIndexNotFoundException
* @throws \ParagonIE\CipherSweet\Exception\CryptoOperationException
* @throws \SodiumException
*/
public function encrypt(Model $model, string $attribute, $value): array
public function encrypt(Model $model, string $attribute, $value)
{
$field = $this->field($model, $attribute);
if (is_null($value)) {
return [null, array_map(static function () {
return null;
}, $field->getAllBlindIndexes(''))];
}
return $field->prepareForStorage($value);
return $this
->field($model, $attribute)
->prepareForStorage($value);
}
/**
@ -164,12 +158,8 @@ class CipherSweetService
* @throws \ParagonIE\CipherSweet\Exception\BlindIndexNameCollisionException
* @throws \ParagonIE\CipherSweet\Exception\CryptoOperationException
*/
public function decrypt(Model $model, string $attribute, $value): ?string
public function decrypt(Model $model, string $attribute, $value)
{
if (is_null($value)) {
return null;
}
return $this
->field($model, $attribute)
->decryptValue($value);

View File

@ -36,7 +36,7 @@ class CipherSweetServiceProvider extends ServiceProvider
{
// Config
$this->publishes([
__DIR__ . '/../config/ciphersweet.php' => config_path('ciphersweet.php')
__DIR__ . '/../config/ciphersweet.php',
], 'ciphersweet-config');
$this->mergeConfigFrom(

View File

@ -3,6 +3,7 @@
namespace BjornVoesten\CipherSweet\Concerns;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
/**
* @mixin \Illuminate\Database\Eloquent\Model
@ -15,8 +16,9 @@ trait WithAttributeEncryption
* @param string $attribute
* @param string|int|boolean $value
* @return array
* @throws \Exception
*/
public function encrypt(string $attribute, $value): array
public function encrypt(string $attribute, $value)
{
[$ciphertext, $indexes] = $result = app('ciphersweet')->encrypt(
$this, $attribute, $value
@ -35,12 +37,12 @@ trait WithAttributeEncryption
* Encrypt the attribute.
*
* @param string $attribute
* @return string|null
* @return $this
*/
public function decrypt(string $attribute): ?string
public function decrypt(string $attribute)
{
return app('ciphersweet')->decrypt(
$this, $attribute, $this->attributes[$attribute] ?? null
$this, $attribute, $this->attributes[$attribute]
);
}
@ -52,25 +54,27 @@ trait WithAttributeEncryption
* @param $operator
* @param $value
* @param array $indexes
* @param string $boolean
* @return void
* @throws \Exception
*/
public function scopeWhereEncrypted(Builder $query, string $column, $operator, $value, array $indexes = [], $boolean = 'and'): void
public function scopeWhereEncrypted(Builder $query, string $column, $operator, $value, array $indexes = []): void
{
/** @var array $available */
$available = $this->encrypt($column, $value)[1];
$available = Arr::last(
$this->encrypt($column, $value)
);
$indexes = empty($indexes) ? array_keys($available) : $indexes;
$indexes = empty($indexes)
? array_keys($available)
: $indexes;
$method = $boolean === 'or'
? 'orWhere'
: 'where';
$first = true;
foreach ($indexes as $index) {
$first
? $query->where($index, $operator, $available[$index])
: $query->orWhere($index, $operator, $available[$index]);
$query->{$method}(function (Builder $query) use ($available, $operator, $indexes) {
foreach ($indexes as $key => $index) {
$query->where($index, $operator, $available[$index]);
}
});
$first = false;
}
}
/**
@ -79,76 +83,23 @@ trait WithAttributeEncryption
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $column
* @param string $operator
* @param mixed $value
* @param $value
* @param array $indexes
* @param string $boolean
* @return void
*/
public function scopeOrWhereEncrypted(
Builder $query, string $column, string $operator, $value,
array $indexes = [], $boolean = 'or'
): void
{
$this->scopeWhereEncrypted(
$query, $column, $operator, $value, $indexes, $boolean
);
}
/**
* Add a where in clause to the query for an encrypted column.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $column
* @param array $values
* @param array $indexes
* @param string $boolean
* @return void
* @throws \Exception
*/
public function scopeWhereInEncrypted(
Builder $query, string $column, array $values, array $indexes = [],
$boolean = 'and'
): void
public function scopeOrWhereEncrypted(Builder $query, string $column, string $operator, $value, array $indexes = []): void
{
$values = array_map(function (string $value) use ($column) {
return $this->encrypt($column, $value)[1];
}, $values);
$available = array_keys($values[0]);
$indexes = empty($indexes) ? $available : $indexes;
$method = $boolean === 'or'
? 'orWhere'
: 'where';
$query->{$method}(function (Builder $query) use ($values, $indexes) {
foreach ($indexes as $key => $index) {
(bool) $key
? $query->orWhereIn($index, $values)
: $query->whereIn($index, $values);
}
});
}
/**
* Add a or where in clause to the query for an encrypted column.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $column
* @param array $values
* @param array $indexes
* @param string $boolean
* @return void
* @throws \Exception
*/
public function scopeOrWhereInEncrypted(
Builder $query, string $column, array $values, array $indexes = [],
$boolean = 'or'
): void
{
$this->scopeWhereInEncrypted(
$query, $column, $values, $indexes, $boolean
$available = Arr::last(
$this->encrypt($column, $value)
);
$indexes = empty($indexes)
? array_keys($available)
: $indexes;
foreach ($indexes as $index) {
$query->orWhere($index, $operator, $available[$index]);
}
}
}

View File

@ -11,7 +11,7 @@ class Blueprint
{
public function encrypted(): Closure
{
return function (string $name, ?array $indexes = null, ?string $after = null, bool $nullable = false): void {
return function (string $name, ?array $indexes = null): void {
$columns = empty($indexes)
? [
$name,
@ -23,13 +23,7 @@ class Blueprint
);
foreach ($columns as $column) {
$addedColumn = $this->string($column)->nullable($nullable);
if($after) {
$addedColumn->after($after);
$after = $column;
}
$this->string($column);
}
$this->index($columns);
@ -38,8 +32,22 @@ class Blueprint
public function nullableEncrypted(): Closure
{
return function (string $name, ?array $indexes = null, ?string $after = null): void {
$this->encrypted($name, $indexes, $after, true);
return function (string $name, ?array $indexes = null): void {
$columns = empty($indexes)
? [
$name,
"{$name}_index",
]
: array_merge(
[$name],
$indexes
);
foreach ($columns as $column) {
$this->string($column)->nullable();
}
$this->index($columns);
};
}
}

View File

@ -10,8 +10,8 @@ trait CreateUsersTable
protected function createUsersTable(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('social_security_number')->nullable();
$table->id('id');
$table->string('social_security_number');
$table->string('social_security_number_index')->nullable();
$table->string('custom_index')->nullable();
$table->timestamps();

View File

@ -9,10 +9,10 @@ trait CreatesUsers
/**
* Create a new user instance.
*
* @param string|null $socialSecurityNumber
* @param string $socialSecurityNumber
* @return \Tests\Mocks\User|\Illuminate\Database\Eloquent\Model
*/
protected function user(?string $socialSecurityNumber): User
protected function user(string $socialSecurityNumber): User
{
return User::query()->create([
'social_security_number' => $socialSecurityNumber,

View File

@ -27,12 +27,12 @@ class EncryptionTest extends TestCase
'social_security_number' => '123-456-789',
]);
static::assertSame(
$this->assertSame(
'123-456-789',
$user->social_security_number
);
static::assertNotEmpty(
$this->assertNotEmpty(
$user->social_security_number_index
);
}
@ -41,12 +41,12 @@ class EncryptionTest extends TestCase
{
$user = $this->user('123-456-789');
static::assertNotSame(
$this->assertNotSame(
'123-456-789',
$user->getRawOriginal('social_security_number')
);
static::assertNotEmpty(
$this->assertNotEmpty(
$user->social_security_number_index
);
@ -78,12 +78,12 @@ class EncryptionTest extends TestCase
])
->save();
static::assertNotSame(
$this->assertNotSame(
'123-456-789',
$user->getRawOriginal('social_security_number')
);
static::assertNotEmpty(
$this->assertNotEmpty(
$user->getAttribute('custom_index')
);
@ -100,29 +100,9 @@ class EncryptionTest extends TestCase
{
$user = $this->user('123-456-789');
static::assertSame(
$this->assertSame(
'123-456-789',
$user->getAttribute('social_security_number')
);
}
public function testAttributesCanBeMadeNull(): void
{
$user = $this->user('123-456-789');
static::assertSame(
'123-456-789',
$user->social_security_number
);
$user->social_security_number = null;
static::assertNull(
$user->social_security_number
);
static::assertNull(
$user->social_security_number_index
);
}
}

View File

@ -32,8 +32,8 @@ class QueryTest extends TestCase
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertNotContains($userTwo->id, $keys);
$this->assertContains($userOne->id, $keys);
$this->assertNotContains($userTwo->id, $keys);
// Assert success using provided index.
/** @var \Illuminate\Database\Eloquent\Collection $keys */
@ -44,8 +44,8 @@ class QueryTest extends TestCase
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertNotContains($userTwo->id, $keys);
$this->assertContains($userOne->id, $keys);
$this->assertNotContains($userTwo->id, $keys);
// Assert undefined index exception.
$this->expectException(Exception::class);
@ -57,22 +57,6 @@ class QueryTest extends TestCase
->get();
}
public function testCanQueryNullableAttributes(): void
{
$userOne = $this->user('123-456-789');
$userTwo = $this->user(null);
// Assert success.
/** @var \Illuminate\Database\Eloquent\Collection $keys */
$keys = User::query()
->whereEncrypted('social_security_number', '=', '123-456-789')
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertNotContains($userTwo->id, $keys);
}
public function testCanQueryEncryptedAttributeWithOrWhereClause(): void
{
$userOne = $this->user('123-456-789');
@ -87,9 +71,9 @@ class QueryTest extends TestCase
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertNotContains($userTwo->id, $keys);
static::assertContains($userThree->id, $keys);
$this->assertContains($userOne->id, $keys);
$this->assertNotContains($userTwo->id, $keys);
$this->assertContains($userThree->id, $keys);
// Assert success using provided index.
/** @var \Illuminate\Database\Eloquent\Collection $keys */
@ -101,9 +85,9 @@ class QueryTest extends TestCase
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertNotContains($userTwo->id, $keys);
static::assertContains($userThree->id, $keys);
$this->assertContains($userOne->id, $keys);
$this->assertNotContains($userTwo->id, $keys);
$this->assertContains($userThree->id, $keys);
// Assert undefined index exception.
$this->expectException(Exception::class);
@ -114,118 +98,4 @@ class QueryTest extends TestCase
])
->get();
}
public function testCanQueryEncryptedAttributeWithWhereInClause(): void
{
$userOne = $this->user('123-456-789');
$userTwo = $this->user('789-456-123');
$userThree = $this->user('456-789-123');
// Assert success.
/** @var \Illuminate\Database\Eloquent\Collection $keys */
$keys = User::query()
->whereInEncrypted(
'social_security_number',
[
'123-456-789',
'789-456-123',
]
)
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertContains($userTwo->id, $keys);
static::assertNotContains($userThree->id, $keys);
// Assert success using provided index.
/** @var \Illuminate\Database\Eloquent\Collection $keys */
$keys = User::query()
->whereInEncrypted(
'social_security_number',
[
'123-456-789',
'789-456-123',
],
['social_security_number_index']
)
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertContains($userTwo->id, $keys);
static::assertNotContains($userThree->id, $keys);
$keys = User::query()
->whereInEncrypted(
'social_security_number',
['789-456-123'],
['non_existing_index']
)
->get()
->modelKeys();
static::assertEmpty($keys);
}
public function testCanQueryEncryptedAttributeWithOrWhereInClause(): void
{
$userOne = $this->user('123-456-789');
$userTwo = $this->user('789-456-123');
$userThree = $this->user('456-789-123');
// Assert success.
/** @var \Illuminate\Database\Eloquent\Collection $keys */
$keys = User::query()
->whereInEncrypted(
'social_security_number',
['123-456-789']
)
->orWhereInEncrypted(
'social_security_number',
['789-456-123']
)
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertContains($userTwo->id, $keys);
static::assertNotContains($userThree->id, $keys);
// Assert success using provided index.
/** @var \Illuminate\Database\Eloquent\Collection $keys */
$keys = User::query()
->whereInEncrypted(
'social_security_number',
['123-456-789'],
['social_security_number_index']
)
->orWhereInEncrypted(
'social_security_number',
['789-456-123'],
['social_security_number_index']
)
->get()
->modelKeys();
static::assertContains($userOne->id, $keys);
static::assertContains($userTwo->id, $keys);
static::assertNotContains($userThree->id, $keys);
$keys = User::query()
->whereInEncrypted(
'social_security_number',
['789-456-123'],
['non_existing_index']
)
->orWhereInEncrypted(
'social_security_number',
['789-456-123'],
['non_existing_index']
)
->get()
->modelKeys();
static::assertEmpty($keys);
}
}