Skip to content

A free open source IT asset/license management system

Sync Adapters: Fixed #19726 - a failed asset save during sync is counted as success

snipedc417f573b02
diff --git a/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapter.php b/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapter.php
index 0f6364112e..ce35a26f3a 100644
--- a/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapter.php
+++ b/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapter.php
@@ -301,7 +301,7 @@ class GoogleWorkspaceAdapter extends SyncAdapter implements PushableAdapter
return false;
}
- $payload = $this->buildPushPayload($asset);
+ $payload = $this->buildOutgoingPayload($asset);
$this->applyComposedNotesToPayload($asset, $payload);
if ($payload === []) {
@@ -337,9 +337,15 @@ class GoogleWorkspaceAdapter extends SyncAdapter implements PushableAdapter
* direction UI appear here. This is the base payload before
* composed notes are spliced in.
*
+ * Named distinct from the SyncAdapter base's buildPushPayload()
+ * template hook because that hook returns a `[payload, touched]`
+ * for adapters that route through pushViaSinglePayload().
+ * This adapter's push() dispatches directly and only needs the
+ * payload half, so the shape and name stay separate.
+ *
* @return array<string, mixed>
*/
- protected function buildPushPayload(Asset $asset): array
+ private function buildOutgoingPayload(Asset $asset): array
{
$payload = [];
diff --git a/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceClient.php b/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceClient.php
index bf3baa6079..b3ae378424 100644
--- a/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceClient.php
+++ b/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceClient.php
@@ -69,7 +69,7 @@ class GoogleWorkspaceClient
'projection' => 'FULL',
'maxResults' => $pageSize,
];
- if (is_string($pageToken) && $pageToken !== '') {
+ if (is_string($pageToken)) {
$params['pageToken'] = $pageToken;
}
diff --git a/app/SyncAdapters/SyncsHostFromRecord.php b/app/SyncAdapters/SyncsHostFromRecord.php
index e455a73057..0af71a8d0d 100644
--- a/app/SyncAdapters/SyncsHostFromRecord.php
+++ b/app/SyncAdapters/SyncsHostFromRecord.php
@@ -57,7 +57,22 @@ trait SyncsHostFromRecord
throw new RuntimeException('Failed to save asset during heartbeat-only sync.');
}
} else {
- $asset->saveOrFail();
+ // Asset::save() augments $this->rules with the model's
+ // fieldset validation rules INSIDE the save call, so
+ // Watson's saveOrFail() upfront isInvalid() check runs
+ // before the augmentation and passes. It then delegates
+ // to Eloquent's saveOrFail() which wraps save() in a
+ // transaction WITHOUT re-checking the return value, so
+ // when the ValidatingObserver aborts the save (returns
+ // false) the whole chain silently returns false and the
+ // sync counts the record as processed. Calling save()
+ // directly and checking the boolean mirrors
+ // createShellAsset()'s existing guard and surfaces the
+ // real validation error to the pull loop's catch.
+ if (! $asset->save()) {
+ $errors = implode('; ', $asset->getErrors()->all()) ?: 'unknown validation failure';
+ throw new RuntimeException("could not update asset for {$record->sourceKey} record {$record->sourceId}: {$errors}");
+ }
}
// External-source column writes gather during the mapping
@@ -1261,7 +1276,14 @@ trait SyncsHostFromRecord
if ($user->location_id !== null) {
$asset->location_id = $user->location_id;
}
- $asset->saveOrFail();
+ // See #19726 note above the primary write site. saveOrFail()
+ // returns false rather than throwing when Asset's fieldset
+ // validation aborts the save, so we check save()'s return
+ // and raise for the pull loop's catch to log.
+ if (! $asset->save()) {
+ $errors = implode('; ', $asset->getErrors()->all()) ?: 'unknown validation failure';
+ throw new RuntimeException("could not persist sync-driven checkout on asset {$asset->id}: {$errors}");
+ }
$log = new Actionlog;
$log->item_id = $asset->id;
@@ -1289,7 +1311,11 @@ trait SyncsHostFromRecord
$asset->assigned_to = null;
$asset->assigned_type = null;
$asset->last_checkin = now();
- $asset->saveOrFail();
+ // See #19726 note above the primary write site.
+ if (! $asset->save()) {
+ $errors = implode('; ', $asset->getErrors()->all()) ?: 'unknown validation failure';
+ throw new RuntimeException("could not persist sync-driven checkin on asset {$asset->id}: {$errors}");
+ }
$log = new Actionlog;
$log->item_id = $asset->id;
diff --git a/tests/Feature/SyncAdapters/SilentSaveFailureTest.php b/tests/Feature/SyncAdapters/SilentSaveFailureTest.php
new file mode 100644
index 0000000000..8d0c296c3b
--- /dev/null
+++ b/tests/Feature/SyncAdapters/SilentSaveFailureTest.php
@@ -0,0 +1,134 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters;
+
+use App\Models\Asset;
+use App\Models\AssetExternalSource;
+use App\Models\AssetModel;
+use App\Models\CustomField;
+use App\Models\CustomFieldset;
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\SyncAdapters\HostInventoryRecord;
+use App\SyncAdapters\SyncAdapter;
+use Illuminate\Support\Facades\Crypt;
+use Tests\TestCase;
+
+
+class SilentSaveFailureTest extends TestCase
+{
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ Statuslabel::factory()->rtd()->create();
+ }
+
+ public function test_update_path_throws_when_extra_mapping_fails_fieldset_validation(): void
+ {
+ // Build a fieldset with a MAC-format text custom field, attach
+ // it to the AssetModel the sync will resolve, and pre-create
+ // the asset + external_source row so the sync hits the UPDATE
+ // branch (not the create-shell branch, which already has its
+ // own guard).
+ $macField = CustomField::factory()->create([
+ 'element' => 'text',
+ 'name' => 'Fleet MAC',
+ 'format' => 'MAC',
+ ]);
+ $fieldset = CustomFieldset::factory()->create();
+ $fieldset->fields()->attach($macField->id, ['required' => 0, 'order' => 1]);
+
+ $model = AssetModel::factory()->create([
+ 'name' => 'Generic Laptop',
+ 'fieldset_id' => $fieldset->id,
+ ]);
+ $asset = Asset::factory()->create([
+ 'name' => 'existing-host',
+ 'model_id' => $model->id,
+ ]);
+
+ $instance = $this->configuredFleetInstance();
+ SyncAdapterConfig::put($instance->id, 'mapping.fleet_uuid', 'custom:'.$macField->id);
+
+ AssetExternalSource::create([
+ 'asset_id' => $asset->id,
+ 'source' => 'fleet',
+ 'external_id' => 'fleet-update-record',
+ ]);
+
+ // Sync a record whose uuid extra will land on the MAC-format
+ // custom field. The MAC format validation rejects
+ // "not-a-mac-address", the ValidatingObserver aborts the
+ // save with return false, and pre-fix the whole thing was
+ // swallowed.
+ $record = new HostInventoryRecord(
+ sourceKey: 'fleet',
+ sourceId: 'fleet-update-record',
+ hostname: 'existing-host',
+ hardwareSerial: 'SN-EXIST',
+ hardwareModel: 'Generic Laptop',
+ extra: ['fleet_uuid' => 'not-a-mac-address'],
+ );
+
+ $thrown = null;
+ try {
+ SyncAdapter::syncFromRecord($record);
+ } catch (\Throwable $e) {
+ $thrown = $e;
+ }
+
+ $this->assertNotNull($thrown, 'syncFromRecord must surface a save-failure on the update path so the pull loop counts it as an error rather than silently succeeding.');
+ // The RuntimeException wraps the underlying validation
+ // failure so the pull loop's log line names the offending
+ // record and the reason. Prior to the fix, no exception
+ // reached this point.
+ $this->assertStringContainsString('could not update asset for fleet record fleet-update-record', $thrown->getMessage());
+
+ // Invalid value must not have made it into the DB.
+ $asset->refresh();
+ $this->assertNotSame('not-a-mac-address', $asset->{$macField->db_column});
+ }
+
+ public function test_valid_update_path_still_persists(): void
+ {
+ // Sanity check that the guard did not turn valid updates into
+ // errors. A record that would pass validation completes the
+ // update and lands its mapped values.
+ $model = AssetModel::factory()->create(['name' => 'Generic Laptop']);
+ $asset = Asset::factory()->create([
+ 'name' => 'pre-existing-clean',
+ 'model_id' => $model->id,
+ ]);
+
+ $this->configuredFleetInstance();
+ AssetExternalSource::create([
+ 'asset_id' => $asset->id,
+ 'source' => 'fleet',
+ 'external_id' => 'fleet-clean-update',
+ ]);
+
+ $record = new HostInventoryRecord(
+ sourceKey: 'fleet',
+ sourceId: 'fleet-clean-update',
+ hostname: 'now-renamed',
+ hardwareSerial: 'SN-EXIST',
+ hardwareModel: 'Generic Laptop',
+ );
+
+ SyncAdapter::syncFromRecord($record);
+
+ $asset->refresh();
+ $this->assertSame('now-renamed', $asset->name);
+ }
+
+ private function configuredFleetInstance(): SyncAdapterInstance
+ {
+ $instance = SyncAdapterInstance::where('slug', 'fleet')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'url', 'https://example.com/fleet');
+ SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-token'));
+
+ return $instance->fresh();
+ }
+}