A free open source IT asset/license management system
Fixed FD-56673 - added custom field helper with gate
snipe42a98fc355b1
diff --git a/app/Helpers/Helper.php b/app/Helpers/Helper.phpindex 2c2818b9ac..53eb3ab47b 100644--- a/app/Helpers/Helper.php+++ b/app/Helpers/Helper.php@@ -20,6 +20,7 @@ use Illuminate\Http\RedirectResponse;use Illuminate\Pagination\LengthAwarePaginator;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Gate;use Illuminate\Support\Facades\Log;use Illuminate\Support\Str;use Intervention\Image\ImageManagerStatic as Image;@@ -1261,6 +1262,31 @@ class Helperreturn $string;}+ /**+ * Resolves the value to render in a custom-field form input for the current+ * request. Encapsulates the "encrypted + no view.encrypted_custom_fields+ * gate" branch so every element type in custom_fields_form.blade.php+ * consults the same rule, and any future form template can call one method+ * rather than reconstructing the ternary inline.+ *+ * Returns the shared masked-value string when the field is encrypted and+ * the caller cannot view encrypted custom fields. Otherwise returns the+ * decrypted stored value for the given $item, or the model-scoped default+ * value when no $item is present (create form path).+ */+ public static function customFieldFormValue(CustomField $field, $item, $model)+ {+ if ($field->field_encrypted && ! Gate::allows('assets.view.encrypted_custom_fields')) {+ return strtoupper(trans('admin/custom_fields/general.encrypted'));+ }++ if (isset($item)) {+ return self::gracefulDecrypt($field, $item->{$field->db_column_name()});+ }++ return $field->defaultValue($model->id);+ }+public static function formatStandardApiResponse($status, $payload = null, $messages = null){$array['status'] = $status;diff --git a/resources/views/models/custom_fields_form.blade.php b/resources/views/models/custom_fields_form.blade.phpindex 8050e5508e..72d1ff37d0 100644--- a/resources/views/models/custom_fields_form.blade.php+++ b/resources/views/models/custom_fields_form.blade.php@@ -34,18 +34,18 @@<x-input.select:name="$field->db_column_name()":options="$field->formatFieldValuesAsArray()"- :selected="old($field->db_column_name(), (isset($item) ? Helper::gracefulDecrypt($field, $item->{$field->db_column_name()}) : $field->defaultValue($model->id)))"+ :selected="old($field->db_column_name(), Helper::customFieldFormValue($field, $item ?? null, $model))":required="$field->pivot->required == '1'"class="format form-control"/>@elseif ($field->element=='textarea')<!-- Textarea -->- <textarea rows="6" class="col-md-6 form-control" id="{{ $field->db_column_name() }}" name="{{ $field->db_column_name() }}"{{ ($field->pivot->required=='1') ? ' required' : '' }}>{{ old($field->db_column_name(),(isset($item) ? Helper::gracefulDecrypt($field, $item->{$field->db_column_name()}) : $field->defaultValue($model->id))) }}</textarea>+ <textarea rows="6" class="col-md-6 form-control" id="{{ $field->db_column_name() }}" name="{{ $field->db_column_name() }}"{{ ($field->pivot->required=='1') ? ' required' : '' }}>{{ old($field->db_column_name(), Helper::customFieldFormValue($field, $item ?? null, $model)) }}</textarea>@elseif ($field->element=='markdown-textarea')<!-- Markdown Textarea -->- <textarea rows="6" class="col-md-6 form-control" id="{{ $field->db_column_name() }}" name="{{ $field->db_column_name() }}"{{ ($field->pivot->required=='1') ? ' required' : '' }}>{{ old($field->db_column_name(),(isset($item) ? Helper::gracefulDecrypt($field, $item->{$field->db_column_name()}) : $field->defaultValue($model->id))) }}</textarea>+ <textarea rows="6" class="col-md-6 form-control" id="{{ $field->db_column_name() }}" name="{{ $field->db_column_name() }}"{{ ($field->pivot->required=='1') ? ' required' : '' }}>{{ old($field->db_column_name(), Helper::customFieldFormValue($field, $item ?? null, $model)) }}</textarea><p class="help-block"><i class="fab fa-markdown" aria-hidden="true"></i> {{ trans('general.markdown') }}</p>@@ -80,7 +80,7 @@<x-input.datepickerid="{{ $field->db_column_name() }}"name="{{ $field->db_column_name() }}"- :value="old($field->db_column_name(), isset($item) ? Helper::gracefulDecrypt($field, $item->{$field->db_column_name()}) : $field->defaultValue($model->id))"+ :value="old($field->db_column_name(), Helper::customFieldFormValue($field, $item ?? null, $model))"required="{{ ($field->pivot->required=='1') ? '1' : '' }}"/></div>@@ -93,7 +93,7 @@<x-input.datetimepickerid="{{ $field->db_column_name() }}"name="{{ $field->db_column_name() }}"- :value="old($field->db_column_name(), isset($item) ? Helper::gracefulDecrypt($field, $item->{$field->db_column_name()}) : $field->defaultValue($model->id))"+ :value="old($field->db_column_name(), Helper::customFieldFormValue($field, $item ?? null, $model))"required="{{ ($field->pivot->required=='1') ? '1' : '' }}":default_now="false"/>@@ -109,7 +109,7 @@<x-input.datepickerid="{{ $field->db_column_name() }}"name="{{ $field->db_column_name() }}"- :value="old($field->db_column_name(), isset($item) ? Helper::gracefulDecrypt($field, $item->{$field->db_column_name()}) : $field->defaultValue($model->id))"+ :value="old($field->db_column_name(), Helper::customFieldFormValue($field, $item ?? null, $model))"required="{{ ($field->pivot->required=='1') ? '1' : '' }}"/></div>@@ -126,7 +126,7 @@<x-input.datetimepickerid="{{ $field->db_column_name() }}"name="{{ $field->db_column_name() }}"- :value="old($field->db_column_name(), isset($item) ? Helper::gracefulDecrypt($field, $item->{$field->db_column_name()}) : $field->defaultValue($model->id))"+ :value="old($field->db_column_name(), Helper::customFieldFormValue($field, $item ?? null, $model))"required="{{ ($field->pivot->required=='1') ? '1' : '' }}":default_now="false"/>@@ -172,7 +172,7 @@$errormessage = $errors->first($field->db_column_name());if ($errormessage) {$errormessage = preg_replace('/ snipeit /', '', $errormessage);- print('<span class="alert-msg" role="alert" aria-live="assertive">'.$errormessage.'</span>');+ echo '<span class="alert-msg" role="alert" aria-live="assertive">'.$errormessage.'</span>';}?></div>diff --git a/tests/Feature/Assets/Ui/EncryptedCustomFieldFormDisclosureTest.php b/tests/Feature/Assets/Ui/EncryptedCustomFieldFormDisclosureTest.phpnew file mode 100644index 0000000000..075919506a--- /dev/null+++ b/tests/Feature/Assets/Ui/EncryptedCustomFieldFormDisclosureTest.php@@ -0,0 +1,195 @@+<?php++namespace Tests\Feature\Assets\Ui;++use App\Models\Asset;+use App\Models\AssetModel;+use App\Models\CustomField;+use App\Models\CustomFieldset;+use App\Models\User;+use Illuminate\Support\Facades\Crypt;+use Tests\TestCase;++/**+ * FD-56675 regression coverage. Asserts that every element-type branch in+ * resources/views/models/custom_fields_form.blade.php honors the+ * assets.view.encrypted_custom_fields gate, and that the fix is picked up+ * on each of the four form contexts that include the template+ * (edit, checkin, checkout, audit).+ *+ * The pre-fix template unconditionally called Helper::gracefulDecrypt on+ * the listbox, textarea, markdown-textarea, date_picker, datetime_picker,+ * DATE-format, and DATETIME-format branches, leaking plaintext to any+ * assets.edit / assets.checkin / assets.checkout / assets.audit user.+ */+class EncryptedCustomFieldFormDisclosureTest extends TestCase+{+ /**+ * @dataProvider elementTypeProvider+ */+ public function test_edit_form_masks_encrypted_custom_field_for_user_without_view_encrypted(array $fieldAttributes, string $secret): void+ {+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');++ [$asset, $field] = $this->assetWithEncryptedField($fieldAttributes, $secret);++ $actor = User::factory()->editAssets()->create();++ $response = $this->actingAs($actor)->get(route('hardware.edit', $asset))->assertOk();++ $response->assertDontSee($secret, false);+ $response->assertSee(strtoupper(trans('admin/custom_fields/general.encrypted')), false);+ }++ /**+ * @dataProvider elementTypeProvider+ */+ public function test_edit_form_shows_encrypted_custom_field_plaintext_for_superuser(array $fieldAttributes, string $secret): void+ {+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');++ [$asset] = $this->assetWithEncryptedField($fieldAttributes, $secret);++ $actor = User::factory()->superuser()->create();++ $this->actingAs($actor)+ ->get(route('hardware.edit', $asset))+ ->assertOk()+ ->assertSee($secret, false);+ }++ public function test_checkin_form_masks_encrypted_custom_field_for_user_without_view_encrypted(): void+ {+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');++ // Checkin flow requires the asset to be checked out first, otherwise the+ // controller redirects to hardware.index with "already checked in".+ [$asset] = $this->assetWithEncryptedField(+ ['element' => 'textarea', 'display_checkin' => 1],+ 'CHECKIN-SECRET-SHOULD-NOT-LEAK',+ fn ($factory) => $factory->assignedToUser()+ );++ $actor = User::factory()->checkinAssets()->create();++ $response = $this->actingAs($actor)->get(route('hardware.checkin.create', $asset))->assertOk();++ $response->assertDontSee('CHECKIN-SECRET-SHOULD-NOT-LEAK', false);+ $response->assertSee(strtoupper(trans('admin/custom_fields/general.encrypted')), false);+ }++ public function test_checkout_form_masks_encrypted_custom_field_for_user_without_view_encrypted(): void+ {+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');++ [$asset] = $this->assetWithEncryptedField(+ ['element' => 'textarea', 'display_checkout' => 1],+ 'CHECKOUT-SECRET-SHOULD-NOT-LEAK'+ );++ $actor = User::factory()->checkoutAssets()->create();++ $response = $this->actingAs($actor)->get(route('hardware.checkout.create', $asset))->assertOk();++ $response->assertDontSee('CHECKOUT-SECRET-SHOULD-NOT-LEAK', false);+ $response->assertSee(strtoupper(trans('admin/custom_fields/general.encrypted')), false);+ }++ public function test_audit_form_masks_encrypted_custom_field_for_user_without_view_encrypted(): void+ {+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');++ [$asset] = $this->assetWithEncryptedField(+ ['element' => 'textarea', 'display_audit' => 1],+ 'AUDIT-SECRET-SHOULD-NOT-LEAK'+ );++ $actor = User::factory()->auditAssets()->create();++ $response = $this->actingAs($actor)->get(route('asset.audit.create', $asset))->assertOk();++ $response->assertDontSee('AUDIT-SECRET-SHOULD-NOT-LEAK', false);+ $response->assertSee(strtoupper(trans('admin/custom_fields/general.encrypted')), false);+ }++ /**+ * Each row exercises one of the seven Blade branches that used to leak+ * plaintext when the caller lacked view.encrypted_custom_fields.+ */+ public static function elementTypeProvider(): array+ {+ return [+ // Note: element='listbox' is intentionally excluded from this+ // feature-level provider. The <x-input.select> component only+ // renders options that appear in field_values, so both the+ // plaintext (pre-fix) and the mask (post-fix) collapse into+ // "no option marked selected" when they do not match one of+ // the configured options. There is no substring assertion that+ // cleanly distinguishes the two states without regex parsing.+ // The listbox branch calls Helper::customFieldFormValue verbatim+ // (identical to the four branches below), and HelperTest covers+ // the helper's return values directly.+ 'textarea' => [+ ['element' => 'textarea'],+ 'SECRET-INSIDE-TEXTAREA',+ ],+ 'markdown-textarea' => [+ ['element' => 'markdown-textarea'],+ 'SECRET-INSIDE-MARKDOWN-TEXTAREA',+ ],+ 'date_picker' => [+ ['element' => 'date_picker'],+ '2026-07-29',+ ],+ 'datetime_picker' => [+ ['element' => 'datetime_picker'],+ '2026-07-29 13:37:00',+ ],+ // Note: element='text' with format='DATE' or 'DATETIME' also render+ // decrypt chains in the template, but CustomField::canEncryptFor()+ // rejects field_encrypted='1' for those formats at validation time+ // (native date columns can't hold ciphertext), so those branches+ // can never actually render an encrypted value. Not vulnerable.+ ];+ }++ /**+ * Build an asset whose model uses a fieldset containing a single encrypted+ * custom field with the given attributes and stored plaintext $secret.+ *+ * Custom fields materialize their `db_column` and add a real database+ * column via an afterCreating observer, so we always re-fetch the field+ * from the DB after the factory returns rather than trusting the in-memory+ * factory instance (which will not know its own db_column yet).+ *+ * Optionally accepts a $factoryState closure to layer additional Asset+ * factory states (e.g. assignedToUser() for the checkin test).+ */+ private function assetWithEncryptedField(array $fieldAttributes, string $secret, ?callable $factoryState = null): array+ {+ $uniqueName = 'Encrypted Field '.uniqid();++ CustomField::factory()->create(array_merge([+ 'name' => $uniqueName,+ 'field_encrypted' => '1',+ ], $fieldAttributes));++ $field = CustomField::where('name', $uniqueName)->firstOrFail();++ $fieldset = CustomFieldset::factory()->create();+ $fieldset->fields()->attach($field, ['order' => '1', 'required' => false]);++ $model = AssetModel::factory()->create(['fieldset_id' => $fieldset->id]);++ $assetFactory = Asset::factory()->state([+ 'model_id' => $model->id,+ $field->db_column => Crypt::encrypt($secret),+ ]);++ if ($factoryState) {+ $assetFactory = $factoryState($assetFactory);+ }++ return [$assetFactory->create(), $field];+ }+}diff --git a/tests/Unit/Helpers/HelperTest.php b/tests/Unit/Helpers/HelperTest.phpindex 433981fcb6..53990bb47a 100644--- a/tests/Unit/Helpers/HelperTest.php+++ b/tests/Unit/Helpers/HelperTest.php@@ -340,4 +340,97 @@ class HelperTest extends TestCase// current scheme and points at evil.com. Must be rejected.$this->assertNull(Helper::sameOriginUrl('//evil.example.com/steal-session'));}++ /**+ * FD-56675 regression coverage: customFieldFormValue collapses the+ * gate + decrypt + default fallback that every branch of+ * custom_fields_form.blade.php used to hand-roll (and got wrong on+ * seven of them). These unit tests pin the four possible states of+ * the helper without needing to boot a full HTTP request.+ */+ public function test_custom_field_form_value_masks_encrypted_field_when_gate_denies(): void+ {+ \App\Models\CustomField::factory()->testEncrypted()->create();+ $field = \App\Models\CustomField::where('name', 'Test Encrypted')->first();++ // Set the column value via magic-setter rather than mass assignment+ // because CustomField columns are added at runtime and are not in+ // Asset's $fillable, so `new Asset([...])` would silently drop them.+ $asset = new \App\Models\Asset;+ $asset->{$field->db_column} = \Illuminate\Support\Facades\Crypt::encrypt('very-secret-value');++ $model = \App\Models\AssetModel::factory()->make();++ $this->actingAs(\App\Models\User::factory()->editAssets()->create());++ $this->assertSame(+ strtoupper(trans('admin/custom_fields/general.encrypted')),+ Helper::customFieldFormValue($field, $asset, $model)+ );+ }++ public function test_custom_field_form_value_returns_decrypted_value_when_gate_allows(): void+ {+ \App\Models\CustomField::factory()->testEncrypted()->create();+ $field = \App\Models\CustomField::where('name', 'Test Encrypted')->first();++ $asset = new \App\Models\Asset;+ $asset->{$field->db_column} = \Illuminate\Support\Facades\Crypt::encrypt('very-secret-value');++ $model = \App\Models\AssetModel::factory()->make();++ $this->actingAs(\App\Models\User::factory()->superuser()->create());++ $this->assertSame(+ 'very-secret-value',+ Helper::customFieldFormValue($field, $asset, $model)+ );+ }++ public function test_custom_field_form_value_returns_raw_value_for_non_encrypted_field(): void+ {+ // Non-encrypted fields short-circuit before the gate check, so the caller+ // permission is irrelevant. Verified with an unauthenticated actor to make+ // the "gate does not gate this" behavior explicit.+ \App\Models\CustomField::factory()->ram()->create();+ $field = \App\Models\CustomField::where('name', 'RAM')->first();++ $asset = new \App\Models\Asset;+ $asset->{$field->db_column} = '16';++ $model = \App\Models\AssetModel::factory()->make();++ $this->assertSame('16', Helper::customFieldFormValue($field, $asset, $model));+ }++ public function test_custom_field_form_value_returns_default_when_item_is_null(): void+ {+ // Create-form path: no bound $item yet, so the helper returns the+ // model-scoped default value for the field.+ \App\Models\CustomField::factory()->ram()->create();+ $field = \App\Models\CustomField::where('name', 'RAM')->first();+ $model = \App\Models\AssetModel::factory()->create();++ $this->assertSame(+ $field->defaultValue($model->id),+ Helper::customFieldFormValue($field, null, $model)+ );+ }++ public function test_custom_field_form_value_masks_default_when_encrypted_field_has_no_item_and_gate_denies(): void+ {+ // Create-form path AND encrypted field AND caller can't view keys.+ // The gate check runs first regardless of whether $item is present,+ // so the mask should win over the default-value fallback.+ \App\Models\CustomField::factory()->testEncrypted()->create();+ $field = \App\Models\CustomField::where('name', 'Test Encrypted')->first();+ $model = \App\Models\AssetModel::factory()->create();++ $this->actingAs(\App\Models\User::factory()->editAssets()->create());++ $this->assertSame(+ strtoupper(trans('admin/custom_fields/general.encrypted')),+ Helper::customFieldFormValue($field, null, $model)+ );+ }}