Skip to content

A free open source IT asset/license management system

tests added, regex validation working

spencerrlongg8a40d7e35c7e
diff --git a/app/Models/CustomFieldset.php b/app/Models/CustomFieldset.php
index 86c5d44e67..f27b838647 100644
--- a/app/Models/CustomFieldset.php
+++ b/app/Models/CustomFieldset.php
@@ -11,12 +11,11 @@ use App\Rules\IPv4Encrypted;
use App\Rules\IPv6Encrypted;
use App\Rules\MacEncrypted;
use App\Rules\NumericEncrypted;
+use App\Rules\RegexEncrypted;
use App\Rules\UrlEncrypted;
use Gate;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
-use Illuminate\Support\Facades\Log;
-use Illuminate\Validation\Rule;
use Watson\Validating\ValidatingTrait;
class CustomFieldset extends Model
@@ -141,75 +140,54 @@ class CustomFieldset extends Model
$ipv6Key = array_search('ipv6', $rules[$field->db_column_name()]);
$macKey = array_search('regex:/^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$/', $rules[$field->db_column_name()]);
$booleanKey = array_search('boolean', $rules[$field->db_column_name()]);
- match ($field->format) {
- 'NUMERIC' => $rules[$field->db_column_name()][$numericKey] = new NumericEncrypted,
- 'ALPHA' => $rules[$field->db_column_name()][$alphaKey] = new AlphaEncrypted,
- 'EMAIL' => $rules[$field->db_column_name()][$emailKey] = new EmailEncrypted,
- 'DATE' => $rules[$field->db_column_name()][$dateKey] = new DateEncrypted,
- 'URL' => $rules[$field->db_column_name()][$urlKey] = new UrlEncrypted,
- 'IP' => $rules[$field->db_column_name()][$ipKey] = new IPEncrypted,
- 'IPV4' => $rules[$field->db_column_name()][$ipv4Key] = new IPv4Encrypted,
- 'IPV6' => $rules[$field->db_column_name()][$ipv6Key] = new IPv6Encrypted,
- 'MAC' => $rules[$field->db_column_name()][$macKey] = new MacEncrypted,
- 'BOOLEAN' => $rules[$field->db_column_name()][$booleanKey] = new BooleanEncrypted,
- default => null,
- };
+ // find objects in array that start with "regex:"
+ // collect because i couldn't figure how to do this
+ // with array filter and get keys out of it
+ $regexCollect = collect($rules[$field->db_column_name()]);
+ $regexKeys = $regexCollect->filter(function ($value, $key) {
+ return starts_with($value, 'regex:');
+ })->keys()->values()->toArray();
+
+ switch ($field->format) {
+ case 'NUMERIC':
+ $rules[$field->db_column_name()][$numericKey] = new NumericEncrypted;
+ break;
+ case 'ALPHA':
+ $rules[$field->db_column_name()][$alphaKey] = new AlphaEncrypted;
+ break;
+ case 'EMAIL':
+ $rules[$field->db_column_name()][$emailKey] = new EmailEncrypted;
+ break;
+ case 'DATE':
+ $rules[$field->db_column_name()][$dateKey] = new DateEncrypted;
+ break;
+ case 'URL':
+ $rules[$field->db_column_name()][$urlKey] = new UrlEncrypted;
+ break;
+ case 'IP':
+ $rules[$field->db_column_name()][$ipKey] = new IPEncrypted;
+ break;
+ case 'IPV4':
+ $rules[$field->db_column_name()][$ipv4Key] = new IPv4Encrypted;
+ break;
+ case 'IPV6':
+ $rules[$field->db_column_name()][$ipv6Key] = new IPv6Encrypted;
+ break;
+ case 'MAC':
+ $rules[$field->db_column_name()][$macKey] = new MacEncrypted;
+ break;
+ case 'BOOLEAN':
+ $rules[$field->db_column_name()][$booleanKey] = new BooleanEncrypted;
+ break;
+ case starts_with($field->format, 'regex'):
+ foreach ($regexKeys as $regexKey) {
+ $rules[$field->db_column_name()][$regexKey] = new RegexEncrypted;
+ }
+ break;
+ }
}
- // these are to replace the standard 'numeric' and 'alpha' rules if the custom field is also encrypted.
- // the values need to be decrypted first, because encrypted strings are alphanumeric
- //if ($field->format === 'NUMERIC' && $field->field_encrypted) {
- // $numericKey = array_search('numeric', $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$numericKey] = new NumericEncrypted;
- //}
- //
- //if ($field->format === 'ALPHA' && $field->field_encrypted) {
- // $alphaKey = array_search('alpha', $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$alphaKey] = new AlphaEncrypted;
- //}
- //
- //if ($field->format === 'EMAIL' && $field->field_encrypted) {
- // $emailKey = array_search('email', $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$emailKey] = new EmailEncrypted;
- //}
- //
- //if ($field->format === 'DATE' && $field->field_encrypted) {
- // $dateKey = array_search('date', $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$dateKey] = new DateEncrypted;
- //}
- //
- //if ($field->format === 'URL' && $field->field_encrypted) {
- // $urlKey = array_search('url', $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$urlKey] = new UrlEncrypted;
- //}
- //
- //if ($field->format === 'IP' && $field->field_encrypted) {
- // $ipKey = array_search('ip', $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$ipKey] = new IpEncrypted;
- //}
- //
- //if ($field->format === 'IPV4' && $field->field_encrypted) {
- // $ipKey = array_search('ipv4', $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$ipKey] = new IPv4Encrypted;
- //}
- //
- //if ($field->format === 'IPV6' && $field->field_encrypted) {
- // $ipKey = array_search('ipv6', $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$ipKey] = new IPv6Encrypted;
- //}
-
- // hm, the 'format' on these is just the regex string, so gonna have to figure out how to filter to get it...
- // hrmph, the string doesn't work. maybe a generic RegexEncrypted rule that takes the regex input and feeds it into
- // laravel's regex validation rule? yeah, maybe.
- // hm, dumping $field->format says that the format actually is 'MAC', which doesn't make sense because it's not that in the DB...
- //if ($field->format == 'MAC' && $field->field_encrypted) {
- // //dd($rules);
- // $macKey = array_search(CustomField::PREDEFINED_FORMATS['MAC'], $rules[$field->db_column_name()]);
- // $rules[$field->db_column_name()][$macKey] = new MacEncrypted;
- //}
-
-
// add not_array to rules for all fields but checkboxes
if ($field->element != 'checkbox') {
$rules[$field->db_column_name()][] = 'not_array';
diff --git a/app/Rules/RegexEncrypted.php b/app/Rules/RegexEncrypted.php
new file mode 100644
index 0000000000..9a573f4b53
--- /dev/null
+++ b/app/Rules/RegexEncrypted.php
@@ -0,0 +1,36 @@
+<?php
+
+namespace App\Rules;
+
+use App\Models\CustomField;
+use Closure;
+use Illuminate\Contracts\Validation\ValidationRule;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Validation\Concerns\ValidatesAttributes;
+
+class RegexEncrypted implements ValidationRule
+{
+ use ValidatesAttributes;
+
+ /**
+ * Run the validation rule.
+ *
+ * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
+ */
+ public function validate(string $attribute, mixed $value, Closure $fail): void
+ {
+ $field = CustomField::where('db_column', $attribute)->first();
+ $regex = $field->format;
+ $regex = str_replace('regex:', '', $regex);
+ try {
+ $attributeName = trim(preg_replace('/_+|snipeit|\d+/', ' ', $attribute));
+ $decrypted = Crypt::decrypt($value);
+ if (!$this->validateRegex($attributeName, $decrypted, [$regex]) && !is_null($decrypted)) {
+ $fail(trans('validation.regex', ['attribute' => $attributeName]));
+ }
+ } catch (\Exception $e) {
+ report($e->getMessage());
+ $fail(trans('general.something_went_wrong'));
+ }
+ }
+}
diff --git a/database/factories/CustomFieldFactory.php b/database/factories/CustomFieldFactory.php
index 44ab0707e0..b0d44b242f 100644
--- a/database/factories/CustomFieldFactory.php
+++ b/database/factories/CustomFieldFactory.php
@@ -93,6 +93,54 @@ class CustomFieldFactory extends Factory
});
}
+ public function encrypt()
+ {
+ return $this->state(function () {
+ return [
+ 'field_encrypted' => '1',
+ ];
+ });
+ }
+
+ public function alpha()
+ {
+ return $this->state(function () {
+ return [
+ 'format' => 'alpha',
+ ];
+ });
+ }
+
+ public function numeric()
+ {
+ return $this->state(function () {
+ return [
+ 'format' => 'numeric',
+ ];
+ });
+ }
+
+ public function email()
+ {
+ return $this->state(function () {
+ return [
+ 'format' => 'email',
+ ];
+ });
+ }
+
+ //public function testEncryptedAlpha()
+ //{
+ // return $this->state(function () {
+ // return [
+ // 'name' => 'Test Encrypted',
+ // 'field_encrypted' => '1',
+ // 'help_text' => 'This is a sample encrypted field.',
+ // 'format' => 'alpha'
+ // ];
+ // });
+ //}
+
public function testCheckbox()
{
return $this->state(function () {
diff --git a/tests/Feature/Assets/Api/StoreAssetTest.php b/tests/Feature/Assets/Api/StoreAssetTest.php
index 1af3569f75..f04a93991d 100644
--- a/tests/Feature/Assets/Api/StoreAssetTest.php
+++ b/tests/Feature/Assets/Api/StoreAssetTest.php
@@ -723,6 +723,65 @@ class StoreAssetTest extends TestCase
$this->assertEquals('This is encrypted field', Crypt::decrypt($asset->{$field->db_column_name()}));
}
+ public function test_encrypted_custom_field_validation_passes()
+ {
+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');
+
+ $status = Statuslabel::factory()->readyToDeploy()->create();
+ $alphaField = CustomField::factory()->encrypt()->alpha()->create();
+ $numericField = CustomField::factory()->encrypt()->numeric()->create();
+ $emailField = CustomField::factory()->encrypt()->email()->create();
+ $fields = [$alphaField, $numericField, $emailField];
+ $superuser = User::factory()->superuser()->create();
+ $assetData = Asset::factory()->hasMultipleCustomFields($fields)->make();
+
+ $response = $this->actingAsForApi($superuser)
+ ->postJson(route('api.assets.store'), [
+ $alphaField->db_column_name() => 'Thisisencryptedfield',
+ $numericField->db_column_name() => '1234567890',
+ $emailField->db_column_name() => '[email protected]',
+ 'model_id' => $assetData->model->id,
+ 'status_id' => $status->id,
+ 'asset_tag' => '1234',
+ ])
+ ->assertStatusMessageIs('success')
+ ->assertOk()
+ ->json();
+
+ $asset = Asset::findOrFail($response['payload']['id']);
+ $this->assertEquals('Thisisencryptedfield', Crypt::decrypt($asset->{$alphaField->db_column_name()}));
+ $this->assertEquals('1234567890', Crypt::decrypt($asset->{$numericField->db_column_name()}));
+ $this->assertEquals('[email protected]', Crypt::decrypt($asset->{$emailField->db_column_name()}));
+ }
+
+ public function test_encrypted_custom_field_validation_fails()
+ {
+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');
+
+ $status = Statuslabel::factory()->readyToDeploy()->create();
+ $alphaField = CustomField::factory()->encrypt()->alpha()->create();
+ $numericField = CustomField::factory()->encrypt()->numeric()->create();
+ $emailField = CustomField::factory()->encrypt()->email()->create();
+ $fields = [$alphaField, $numericField, $emailField];
+ $superuser = User::factory()->superuser()->create();
+ $assetData = Asset::factory()->hasMultipleCustomFields($fields)->make();
+ $cleaned_name = trim(preg_replace('/_+|snipeit|\d+/', ' ', $alphaField->db_column_name()));
+
+ $response = $this->actingAsForApi($superuser)
+ ->postJson(route('api.assets.store'), [
+ $alphaField->db_column_name() => 'Thisisencryptedfield123',
+ 'model_id' => $assetData->model->id,
+ 'status_id' => $status->id,
+ 'asset_tag' => '1234',
+ ])
+ ->dump()
+ ->assertStatusMessageIs('error')
+ ->assertJsonPath('messages.'.$alphaField->db_column_name(), [trans('validation.alpha', ['attribute' => $cleaned_name])])
+ ->assertOk()
+ ->json();
+ }
+
+
public function testPermissionNeededToStoreEncryptedField()
{
// @todo: