A free open source IT asset/license management system
Added validators
snipe93cfbc590fa1
diff --git a/app/Rules/AssetTagPatternRule.php b/app/Rules/AssetTagPatternRule.phpnew file mode 100644index 0000000000..7684e749fc--- /dev/null+++ b/app/Rules/AssetTagPatternRule.php@@ -0,0 +1,38 @@+<?php++namespace App\Rules;++use App\SyncAdapters\SyncHostFromAdapter;+use Closure;+use Illuminate\Contracts\Validation\ValidationRule;++/**+ * Non-empty asset_tag_pattern must contain at least one recognized+ * placeholder (e.g. {external_id}, {serial}). Without a placeholder+ * the pattern renders to the same literal string for every record+ * and the first save wins on asset_tag uniqueness while every+ * subsequent record collides.+ *+ * Empty / null values are allowed. The pattern is optional, and its+ * absence falls back to Snipe-IT's auto-increment or a+ * source-slug + external-id composite.+ */+class AssetTagPatternRule implements ValidationRule+{+ public function validate(string $attribute, mixed $value, Closure $fail): void+ {+ if (!is_string($value) || $value === '') {+ return;+ }++ foreach (SyncHostFromAdapter::ASSET_TAG_PATTERN_PLACEHOLDERS as $placeholder) {+ if (str_contains($value, $placeholder)) {+ return;+ }+ }++ $fail(trans('validation.asset_tag_pattern_placeholder', [+ 'placeholders' => implode(', ', SyncHostFromAdapter::ASSET_TAG_PATTERN_PLACEHOLDERS),+ ]));+ }+}diff --git a/app/Rules/CustomHttpExtrasJsonRule.php b/app/Rules/CustomHttpExtrasJsonRule.phpnew file mode 100644index 0000000000..a57d3e6ef9--- /dev/null+++ b/app/Rules/CustomHttpExtrasJsonRule.php@@ -0,0 +1,61 @@+<?php++namespace App\Rules;++use Closure;+use Illuminate\Contracts\Validation\ValidationRule;++/**+ * Validate the Custom HTTP adapter's Custom Extras JSON blob. Blank+ * is fine (no extras configured). Otherwise the value must parse as+ * a JSON array whose entries are objects containing at least the+ * required `key` and `path` string keys.+ */+class CustomHttpExtrasJsonRule implements ValidationRule+{+ public function validate(string $attribute, mixed $value, Closure $fail): void+ {+ if ($value === null || $value === '' || (is_string($value) && trim($value) === '')) {+ return;+ }++ if (!is_string($value)) {+ $fail(trans('validation.custom_http_extras_json.not_json'));++ return;+ }++ $decoded = json_decode($value, true);+ if (json_last_error() !== JSON_ERROR_NONE) {+ $fail(trans('validation.custom_http_extras_json.not_json', [+ 'error' => json_last_error_msg(),+ ]));++ return;+ }++ if (!is_array($decoded)) {+ $fail(trans('validation.custom_http_extras_json.not_array'));++ return;+ }++ foreach ($decoded as $index => $entry) {+ if (!is_array($entry)) {+ $fail(trans('validation.custom_http_extras_json.entry_not_object', ['index' => $index]));++ return;+ }+ foreach (['key', 'path'] as $requiredKey) {+ if (!array_key_exists($requiredKey, $entry) || !is_string($entry[$requiredKey]) || trim($entry[$requiredKey]) === '') {+ $fail(trans('validation.custom_http_extras_json.missing_field', [+ 'index' => $index,+ 'field' => $requiredKey,+ ]));++ return;+ }+ }+ }+ }+}diff --git a/resources/lang/en-US/validation.php b/resources/lang/en-US/validation.phpindex 9d172a7ec2..92bd7731b1 100644--- a/resources/lang/en-US/validation.php+++ b/resources/lang/en-US/validation.php@@ -174,6 +174,13 @@ return ['uppercase' => 'The :attribute field must be uppercase.','url' => 'The :attribute field must be a valid URL.','external_url' => 'The :attribute field must be a valid external URL (http:// or https://) that does not point at a private or local address.',+ 'asset_tag_pattern_placeholder' => 'The asset tag pattern must include at least one placeholder from :placeholders, otherwise every synced asset would receive the same tag and only the first would save.',+ 'custom_http_extras_json' => [+ 'not_json' => 'Custom Extras must be valid JSON. Parser error: :error',+ 'not_array' => 'Custom Extras must be a JSON array (starting with [ and ending with ]).',+ 'entry_not_object' => 'Custom Extras entry #:index must be a JSON object with key, label, and path fields.',+ 'missing_field' => 'Custom Extras entry #:index is missing the required ":field" field.',+ ],'ulid' => 'The :attribute field must be a valid ULID.','uuid' => 'The :attribute field must be a valid UUID.','valid_css_color' => 'The :attribute field must be a valid CSS color (hex, rgb, rgba, hsl, or hsla).',diff --git a/tests/Unit/Rules/AssetTagPatternRuleTest.php b/tests/Unit/Rules/AssetTagPatternRuleTest.phpnew file mode 100644index 0000000000..c06c705a9b--- /dev/null+++ b/tests/Unit/Rules/AssetTagPatternRuleTest.php@@ -0,0 +1,81 @@+<?php++namespace Tests\Unit\Rules;++use App\Rules\AssetTagPatternRule;+use Illuminate\Support\Facades\Validator;+use Tests\TestCase;++/**+ * Rule catches literal-prefix asset-tag patterns like "DEMO-" or+ * "PROD-" that will render to the same tag for every synced record+ * and collide on uniqueness after the first save. Empty / null+ * patterns are allowed because the framework has a documented+ * fall-through (autoincrement, then source-slug + external-id).+ */+class AssetTagPatternRuleTest extends TestCase+{+ public function test_pattern_with_external_id_placeholder_passes()+ {+ $this->assertTrue($this->validate('SNIPEYHEAD-{external_id}'));+ }++ public function test_pattern_with_serial_placeholder_passes()+ {+ $this->assertTrue($this->validate('{serial}'));+ }++ public function test_pattern_with_hostname_placeholder_passes()+ {+ $this->assertTrue($this->validate('inv-{hostname}-2026'));+ }++ public function test_pattern_with_model_placeholder_passes()+ {+ $this->assertTrue($this->validate('{model}-{external_id}'));+ }++ public function test_pattern_with_source_placeholder_passes()+ {+ $this->assertTrue($this->validate('{source}-{external_id}'));+ }++ public function test_empty_pattern_passes()+ {+ $this->assertTrue($this->validate(''));+ }++ public function test_null_pattern_passes()+ {+ $this->assertTrue($this->validate(null));+ }++ public function test_literal_prefix_without_placeholder_fails()+ {+ // The exact case that bit real users: a "prefix + dash"+ // pattern with no placeholder. Every record renders to+ // "SNIPEYHEAD-" and only the first saves.+ $this->assertFalse($this->validate('SNIPEYHEAD-'));+ }++ public function test_unrelated_curly_braces_do_not_count_as_placeholders()+ {+ // Regression guard: a naive is-there-a-brace check would let+ // "DEMO-{unknown}" through, even though {unknown} isn't in+ // the substitution list and renders literally.+ $this->assertFalse($this->validate('DEMO-{unknown}'));+ }++ public function test_pattern_with_placeholder_and_trailing_characters_passes()+ {+ $this->assertTrue($this->validate('{external_id}-v2'));+ }++ private function validate(?string $value): bool+ {+ return Validator::make(+ ['pattern' => $value],+ ['pattern' => ['nullable', new AssetTagPatternRule]],+ )->passes();+ }+}diff --git a/tests/Unit/Rules/CustomHttpExtrasJsonRuleTest.php b/tests/Unit/Rules/CustomHttpExtrasJsonRuleTest.phpnew file mode 100644index 0000000000..dead9f5639--- /dev/null+++ b/tests/Unit/Rules/CustomHttpExtrasJsonRuleTest.php@@ -0,0 +1,90 @@+<?php++namespace Tests\Unit\Rules;++use App\Rules\CustomHttpExtrasJsonRule;+use Illuminate\Support\Facades\Validator;+use Tests\TestCase;+++class CustomHttpExtrasJsonRuleTest extends TestCase+{+ public function test_empty_string_passes()+ {+ $this->assertTrue($this->validate(''));+ }++ public function test_null_passes()+ {+ $this->assertTrue($this->validate(null));+ }++ public function test_whitespace_only_passes()+ {+ $this->assertTrue($this->validate(" \n "));+ }++ public function test_valid_json_array_of_complete_entries_passes()+ {+ $this->assertTrue($this->validate(json_encode([+ ['key' => 'vendor_tag', 'label' => 'Vendor Tag', 'path' => 'tags.asset_tag'],+ ['key' => 'vendor_room', 'label' => 'Vendor Room', 'path' => 'location.room'],+ ])));+ }++ public function test_entry_without_label_passes_since_label_is_optional()+ {+ // key and path are required, but label falls back to key at read time.+ $this->assertTrue($this->validate(json_encode([+ ['key' => 'vendor_tag', 'path' => 'tags.asset_tag'],+ ])));+ }++ public function test_malformed_json_fails()+ {+ // Exactly what bit the user: object followed by a bare number+ // with no comma. json_decode returns null with a syntax error.+ $this->assertFalse($this->validate(+ '[{"key": "vendor_field", "label": "Human Label", "path": "dot.path.to.value"} 90]'+ ));+ }++ public function test_not_an_array_fails()+ {+ $this->assertFalse($this->validate('{"key": "one"}'));+ }++ public function test_entry_not_an_object_fails()+ {+ $this->assertFalse($this->validate(json_encode(['just a string', 'another'])));+ }++ public function test_entry_missing_key_fails()+ {+ $this->assertFalse($this->validate(json_encode([+ ['label' => 'Missing Key', 'path' => 'tags.a'],+ ])));+ }++ public function test_entry_missing_path_fails()+ {+ $this->assertFalse($this->validate(json_encode([+ ['key' => 'vendor_tag', 'label' => 'Missing Path'],+ ])));+ }++ public function test_entry_with_blank_key_fails()+ {+ $this->assertFalse($this->validate(json_encode([+ ['key' => ' ', 'path' => 'tags.a'],+ ])));+ }++ private function validate(?string $value): bool+ {+ return Validator::make(+ ['blob' => $value],+ ['blob' => ['nullable', new CustomHttpExtrasJsonRule]],+ )->passes();+ }+}