A free open source IT asset/license management system
Fixed #19762 - enforce model constraints on sync adapters, importer
snipe32284c84cec0
diff --git a/app/Models/Asset.php b/app/Models/Asset.phpindex f538b149c3..48f54980e5 100644--- a/app/Models/Asset.php+++ b/app/Models/Asset.php@@ -353,6 +353,13 @@ class Asset extends Depreciable{$this->rules += $this->customFieldValidationRules();+ if ($this->model_id && $this->model && (string) $this->model->require_serial === '1') {+ $this->rules['serial'] = array_merge(+ array_filter($this->rules['serial'] ?? [], fn($r) => $r !== 'nullable'),+ ['required'],+ );+ }+return parent::save($params);}diff --git a/app/SyncAdapters/SyncsHostFromRecord.php b/app/SyncAdapters/SyncsHostFromRecord.phpindex e2ac7310aa..155f8214af 100644--- a/app/SyncAdapters/SyncsHostFromRecord.php+++ b/app/SyncAdapters/SyncsHostFromRecord.php@@ -166,6 +166,26 @@ trait SyncsHostFromRecordreturn null;}+ // UX layer on top of the authoritative require_serial check+ // in Asset::save().+ if ($record->hardwareSerial === null || $record->hardwareSerial === '') {+ $modelName = self::resolveModelSourceValue($record, $mapping);+ if ($modelName !== null && $modelName !== '') {+ $existingModel = AssetModel::where('name', $modelName)->first();+ if ($existingModel !== null && (string) $existingModel->require_serial === '1') {+ Log::channel('sync-adapters')->warning(sprintf(+ '%s sync: skipped %s record %s (no serial, and asset model "%s" requires one)',+ $adapter?->name() ?? $record->sourceKey,+ $record->sourceKey,+ $record->sourceId,+ $existingModel->name,+ ));++ return null;+ }+ }+ }+$asset = self::createShellAsset($record, $instance, $mapping);// Identity row created empty of inventory columns. thediff --git a/tests/Feature/Assets/Api/StoreAssetTest.php b/tests/Feature/Assets/Api/StoreAssetTest.phpindex fb19eee810..742c437913 100644--- a/tests/Feature/Assets/Api/StoreAssetTest.php+++ b/tests/Feature/Assets/Api/StoreAssetTest.php@@ -902,4 +902,37 @@ class StoreAssetTest extends TestCase// $this->assertEquals('3d67fb99a0b6926e350f7b71397525d7a6b936c1', sha1($image_data)); //this doesn't work because the image gets resized - use the resized hash instead$this->assertEquals('db2e13ba04318c99058ca429d67777322f48566b', sha1($image_data));}++ public function test_api_rejects_asset_create_without_serial_when_model_requires_serial(): void+ {+ $model = AssetModel::factory()->create(['require_serial' => 1]);+ $status = Statuslabel::factory()->create();++ $this->actingAsForApi(User::factory()->superuser()->create())+ ->postJson(route('api.assets.store'), [+ 'model_id' => $model->id,+ 'status_id' => $status->id,+ 'asset_tag' => 'NEEDS-SERIAL-1',+ // 'serial' intentionally omitted+ ])+ ->assertStatusMessageIs('error');++ $this->assertDatabaseMissing('assets', ['asset_tag' => 'NEEDS-SERIAL-1']);+ }++ public function test_api_accepts_asset_create_without_serial_when_model_does_not_require_serial(): void+ {+ $model = AssetModel::factory()->create(['require_serial' => 0]);+ $status = Statuslabel::factory()->create();++ $this->actingAsForApi(User::factory()->superuser()->create())+ ->postJson(route('api.assets.store'), [+ 'model_id' => $model->id,+ 'status_id' => $status->id,+ 'asset_tag' => 'OPTIONAL-SERIAL-1',+ ])+ ->assertStatusMessageIs('success');++ $this->assertDatabaseHas('assets', ['asset_tag' => 'OPTIONAL-SERIAL-1']);+ }}diff --git a/tests/Feature/Importing/Api/ImportAssetsTest.php b/tests/Feature/Importing/Api/ImportAssetsTest.phpindex e8af835d08..d03cde41c1 100644--- a/tests/Feature/Importing/Api/ImportAssetsTest.php+++ b/tests/Feature/Importing/Api/ImportAssetsTest.php@@ -4,6 +4,7 @@ namespace Tests\Feature\Importing\Api;use App\Models\Actionlog as ActionLog;use App\Models\Asset;+use App\Models\AssetModel;use App\Models\Company;use App\Models\CustomField;use App\Models\Import;@@ -139,6 +140,72 @@ class ImportAssetsTest extends ImportDataTestCase implements TestsPermissionsReq}+ #[Test]+ public function csv_import_rejects_asset_row_without_serial_when_model_requires_serial(): void+ {+ $modelName = 'RequireSerialModel-' . Str::random(6);+ $modelNumber = 'MN-' . Str::random(6);+ AssetModel::factory()->create([+ 'name' => $modelName,+ 'model_number' => $modelNumber,+ 'require_serial' => 1,+ ]);++ $importFileBuilder = ImportFileBuilder::new([+ 'model' => $modelName,+ 'modelNumber' => $modelNumber,+ 'serialNumber' => '',+ ]);+ $import = Import::factory()->asset()->create([+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),+ ]);++ $this->actingAsForApi(User::factory()->superuser()->create());++ // The importer returns a 500 when every row errored (status+ // import-errors), with the tally still on the payload.+ $this->importFileResponse(['import' => $import->id])+ ->assertStatus(500)+ ->assertJsonPath('payload.tally.created', 0)+ ->assertJsonPath('payload.tally.errored', 1);++ $this->assertDatabaseMissing('assets', [+ 'asset_tag' => $importFileBuilder->firstRow()['tag'],+ ]);+ }++ #[Test]+ public function csv_import_accepts_asset_row_without_serial_when_model_does_not_require_serial(): void+ {+ $modelName = 'OptionalSerialModel-' . Str::random(6);+ $modelNumber = 'MN-' . Str::random(6);+ AssetModel::factory()->create([+ 'name' => $modelName,+ 'model_number' => $modelNumber,+ 'require_serial' => 0,+ ]);++ $importFileBuilder = ImportFileBuilder::new([+ 'model' => $modelName,+ 'modelNumber' => $modelNumber,+ 'serialNumber' => '',+ ]);+ $import = Import::factory()->asset()->create([+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),+ ]);++ $this->actingAsForApi(User::factory()->superuser()->create());++ $this->importFileResponse(['import' => $import->id])+ ->assertOk()+ ->assertJsonPath('payload.tally.created', 1)+ ->assertJsonPath('payload.tally.errored', 0);++ $this->assertDatabaseHas('assets', [+ 'asset_tag' => $importFileBuilder->firstRow()['tag'],+ ]);+ }+#[Test]public function will_ignore_unknown_columns_when_file_contains_unknown_columns(): void{diff --git a/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php b/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.phpindex 5e794f09cb..798d2b530e 100644--- a/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php+++ b/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php@@ -2,6 +2,8 @@namespace Tests\Feature\SyncAdapters\Intune;+use App\Models\Asset;+use App\Models\AssetModel;use App\Models\Statuslabel;use App\Models\SyncAdapterConfig;use App\Models\SyncAdapterInstance;@@ -141,4 +143,65 @@ class IntuneAdapterTest extends TestCase'model' => 'Generic Model',];}++ public function test_vendor_record_without_serial_is_skipped_when_model_requires_serial()+ {+ AssetModel::factory()->create([+ 'name' => 'Generic Model',+ 'require_serial' => 1,+ ]);++ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([+ 'value' => [+ [+ 'id' => 'guid-no-serial',+ 'deviceName' => 'defender-onboarded-host',+ 'serialNumber' => '',+ 'model' => 'Generic Model',+ ],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseMissing('asset_external_sources', ['source' => 'intune', 'external_id' => 'guid-no-serial']);+ $this->assertSame(0, Asset::query()->count(), 'No asset should be created when the model requires a serial and the vendor record has none.');+ }++ public function test_vendor_record_without_serial_still_creates_when_model_does_not_require_serial()+ {+ AssetModel::factory()->create([+ 'name' => 'Generic Model',+ 'require_serial' => 0,+ ]);++ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([+ 'value' => [+ [+ 'id' => 'guid-no-serial-ok',+ 'deviceName' => 'serial-less-but-ok',+ 'serialNumber' => '',+ 'model' => 'Generic Model',+ ],+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseHas('asset_external_sources', ['source' => 'intune', 'external_id' => 'guid-no-serial-ok']);+ }}