Skip to content

A free open source IT asset/license management system

Fixed FD-57214 - tighter gating on company/location import

snipe834e55513fe0
diff --git a/app/Exceptions/ImportRowRejected.php b/app/Exceptions/ImportRowRejected.php
new file mode 100644
index 0000000000..cf86e24af6
--- /dev/null
+++ b/app/Exceptions/ImportRowRejected.php
@@ -0,0 +1,23 @@
+<?php
+
+namespace App\Exceptions;
+
+use Exception;
+
+/**
+ * Thrown from within an importer's row-handler when a row cannot be
+ * processed as submitted (typically because the resolved company or
+ * location fails the FMCS membership check). The base Importer's
+ * import() loop catches this, records the row as errored, surfaces
+ * the message to the wizard's error table, and continues with the
+ * next row.
+ */
+class ImportRowRejected extends Exception
+{
+ public function __construct(
+ public readonly string $field,
+ string $message,
+ ) {
+ parent::__construct($message);
+ }
+}
diff --git a/app/Importer/Importer.php b/app/Importer/Importer.php
index f6d5a4bb4e..83cc17dd10 100644
--- a/app/Importer/Importer.php
+++ b/app/Importer/Importer.php
@@ -393,7 +393,14 @@ abstract class Importer
// Lowercase header values to ensure we're comparing values properly.
$row = array_change_key_case($row, CASE_LOWER);
- $this->handle($row);
+ try {
+ $this->handle($row);
+ } catch (\App\Exceptions\ImportRowRejected $e) {
+ $this->recordErrored();
+ $this->log('Row rejected: '.$e->getMessage());
+ $rowLabel = $row['asset tag'] ?? $row['item name'] ?? $row['name'] ?? 'Row #'.($importedItemsCount + 1);
+ $this->addErrorToBag((object) ['name' => $rowLabel], $e->field, $e->getMessage());
+ }
$importedItemsCount++;
$processedInSlice++;
diff --git a/app/Importer/ItemImporter.php b/app/Importer/ItemImporter.php
index c0fdaf31e5..f684db8b8e 100644
--- a/app/Importer/ItemImporter.php
+++ b/app/Importer/ItemImporter.php
@@ -2,12 +2,14 @@
namespace App\Importer;
+use App\Exceptions\ImportRowRejected;
use App\Models\AssetModel;
use App\Models\Category;
use App\Models\Company;
use App\Models\CompanyableScope;
use App\Models\Location;
use App\Models\Manufacturer;
+use App\Models\Setting;
use App\Models\Statuslabel;
use App\Models\Supplier;
use App\Models\User;
@@ -16,9 +18,12 @@ class ItemImporter extends Importer
{
protected $item;
+ protected Setting $settings;
+
public function __construct($filename)
{
parent::__construct($filename);
+ $this->settings = Setting::getSettings();
}
protected function handle($row)
@@ -533,28 +538,46 @@ class ItemImporter extends Importer
/**
* Fetch an existing company, or create new if it doesn't exist
*
+ * @param $asset_company_name string
+ * @return int|null id of company created/found, or null when FMCS rejects the importing user's access to it
+ *
* @author Daniel Melzter
*
* @since 3.0
- *
- * @param $asset_company_name string
- * @return int id of company created/found
*/
public function createOrFetchCompany($asset_company_name)
{
// Bypass CompanyableScope so the lookup can see companies the
- // importer's user isn't FMCS-allowed to see — otherwise the
- // SELECT misses an existing row, the code falls through to the
- // INSERT path, and the unique index on companies.name rejects
- // it (which is what the customer's stack trace shows).
+ // importer's user isn't FMCS-allowed to see. Without this, a
+ // scoped user hits the create path against a name that already
+ // exists in another tenant, and Watson ValidatingTrait rejects
+ // the save because company.name has to be globally unique.
$company = Company::withoutGlobalScope(CompanyableScope::class)
->where('name', $asset_company_name)
->first();
+
+ $importing_user = auth()->user() ?? ($this->created_by ? User::find($this->created_by) : null);
+ $fmcs = (bool) $this->settings->full_multiple_companies_support;
+
if ($company) {
+ if ($fmcs && $importing_user !== null && ! $importing_user->isSuperUser()) {
+ $userCompanyIds = $importing_user->companies()->pluck('companies.id')->all();
+ // Empty pivot under floater mode is a trusted global-access actor.
+ $isFloater = empty($userCompanyIds) && (bool) $this->settings->null_company_is_floater;
+
+ if (! $isFloater && ! in_array($company->id, $userCompanyIds, true)) {
+ throw new ImportRowRejected(
+ 'company',
+ 'User is not a member of company "'.$asset_company_name.'". Row rejected.',
+ );
+ }
+ }
+
$this->log('A matching Company '.$asset_company_name.' already exists');
return $company->id;
}
+
$company = new Company;
$company->created_by = $this->created_by;
$company->name = $asset_company_name;
@@ -703,19 +726,42 @@ class ItemImporter extends Importer
}
// Bypass CompanyableScope so the lookup can see locations the
- // importer's user isn't FMCS-allowed to see — same shape as the
- // Company fix in createOrFetchCompany(). Without this, a hidden
- // existing location forces the INSERT path and trips the unique
- // index on locations.name.
+ // importer's user isn't FMCS-allowed to see. Falling through
+ // to the create path when a matching row already exists would
+ // just produce a second row with the same name.
$location = Location::withoutGlobalScope(CompanyableScope::class)
->where('name', $asset_location)
->first();
+ $importing_user = auth()->user() ?? ($this->created_by ? User::find($this->created_by) : null);
+ $fmcs = (bool) $this->settings->full_multiple_companies_support;
+ $locationsFmcs = (bool) $this->settings->scope_locations_fmcs;
+
if ($location) {
+ // Only enforced when scope_locations_fmcs is on. Otherwise
+ // locations are global and every user can see all of them.
+ if ($fmcs
+ && $locationsFmcs
+ && $importing_user !== null
+ && ! $importing_user->isSuperUser()
+ && $location->company_id
+ ) {
+ $userCompanyIds = $importing_user->companies()->pluck('companies.id')->all();
+ $isFloater = empty($userCompanyIds) && (bool) $this->settings->null_company_is_floater;
+
+ if (! $isFloater && ! in_array($location->company_id, $userCompanyIds, true)) {
+ throw new ImportRowRejected(
+ 'location',
+ 'User does not have access to location "'.$asset_location.'". Row rejected.',
+ );
+ }
+ }
+
$this->log('Location '.$asset_location.' already exists');
return $location->id;
}
+
// No matching locations in the collection, create a new one.
$location = new Location;
$location->name = $asset_location;
diff --git a/app/Livewire/Importer.php b/app/Livewire/Importer.php
index 2f1dd79dc6..a0031aadac 100644
--- a/app/Livewire/Importer.php
+++ b/app/Livewire/Importer.php
@@ -14,6 +14,7 @@ use App\Models\Import;
use App\Models\License;
use App\Models\Location;
use App\Models\Manufacturer;
+use App\Models\Setting;
use App\Models\Supplier;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
@@ -1336,6 +1337,27 @@ class Importer extends Component
return false;
}
+ /**
+ * True when the current user's FMCS memberships restrict what they
+ * can import into. Superusers, and empty-pivot floater actors skip this.
+ */
+ #[Computed]
+ public function showFmcsRestrictionNotice(): bool
+ {
+ if (auth()->user()->isSuperUser()) {
+ return false;
+ }
+
+ $settings = Setting::getSettings();
+ if (! $settings->full_multiple_companies_support) {
+ return false;
+ }
+
+ $userCompanyIds = auth()->user()->companies()->pluck('companies.id')->all();
+
+ return ! (empty($userCompanyIds) && $settings->null_company_is_floater);
+ }
+
#[Computed]
public function files()
{
diff --git a/resources/lang/en-US/general.php b/resources/lang/en-US/general.php
index 2133da7c41..6ca44cdff5 100644
--- a/resources/lang/en-US/general.php
+++ b/resources/lang/en-US/general.php
@@ -646,6 +646,7 @@ return [
'fmcs_location_select_note' => 'Full Multiple Company Support with location scoping is enabled. Only locations belonging to your company will appear in this list.',
'fmcs_company_select_note' => 'Full Multiple Company Support is enabled. You can only assign companies you belong to.',
'fmcs_company_select_superadmin_note' => 'Full Multiple Company Support is enabled. The company assigned here may affect visibility for non-superadmin users.',
+ 'fmcs_import_restriction_note' => 'Full Multiple Company Support is enabled. CSV rows that reference companies or scoped locations outside your assigned companies will be rejected. Records outside your assigned companies cannot be updated.',
'error_user_company' => 'Checkout target company and asset company do not match',
'error_user_company_multiple' => 'One or more of the checkout target company and asset company do not match',
'error_user_company_accept_view' => 'An Asset assigned to you belongs to a different company so you can\'t accept nor deny it, please check with your manager',
diff --git a/resources/views/livewire/importer.blade.php b/resources/views/livewire/importer.blade.php
index 8273b05acd..24a8d10e0f 100644
--- a/resources/views/livewire/importer.blade.php
+++ b/resources/views/livewire/importer.blade.php
@@ -20,6 +20,14 @@
</div>
@endif
+@if($this->showFmcsRestrictionNotice)
+ <div class="col-md-12">
+ <x-alert type="info" icon="tip">
+ {{ trans('general.fmcs_import_restriction_note') }}
+ </x-alert>
+ </div>
+@endif
+
@if($import_errors)
<div class="col-md-12">
<div class="box box-default">
diff --git a/tests/Feature/Importing/Api/ImportAssetsFmcsIsolationTest.php b/tests/Feature/Importing/Api/ImportAssetsFmcsIsolationTest.php
new file mode 100644
index 0000000000..ff0efc5d3a
--- /dev/null
+++ b/tests/Feature/Importing/Api/ImportAssetsFmcsIsolationTest.php
@@ -0,0 +1,198 @@
+<?php
+
+namespace Tests\Feature\Importing\Api;
+
+use App\Models\Asset;
+use App\Models\Company;
+use App\Models\Import;
+use App\Models\Location;
+use App\Models\User;
+use Illuminate\Testing\TestResponse;
+use PHPUnit\Framework\Attributes\Test;
+use Tests\Support\Importing\AssetsImportFileBuilder as ImportFileBuilder;
+use Tests\Support\Importing\CleansUpImportFiles;
+
+class ImportAssetsFmcsIsolationTest extends ImportDataTestCase
+{
+ use CleansUpImportFiles;
+
+ protected function importFileResponse(array $parameters = []): TestResponse
+ {
+ if (! array_key_exists('import-type', $parameters)) {
+ $parameters['import-type'] = 'asset';
+ }
+
+ return parent::importFileResponse($parameters);
+ }
+
+ #[Test]
+ public function scoped_importer_cannot_inject_asset_into_another_tenants_company(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$attackerCo, $victimCo] = Company::factory()->count(2)->create();
+ $attacker = User::factory()->canImport()->forCompany($attackerCo)->create();
+
+ $builder = ImportFileBuilder::new(['companyName' => $victimCo->name]);
+ $import = Import::factory()->asset()->create([
+ 'file_path' => $builder->saveToImportsDirectory(),
+ 'created_by' => $attacker->id,
+ ]);
+
+ $this->actingAsForApi($attacker);
+ $this->importFileResponse(['import' => $import->id]);
+
+ $this->assertDatabaseMissing('assets', [
+ 'serial' => $builder->firstRow()['serialNumber'],
+ ]);
+ }
+
+ #[Test]
+ public function importer_pinning_to_their_own_company_still_works(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $ownCompany = Company::factory()->create();
+ $user = User::factory()->canImport()->forCompany($ownCompany)->create();
+
+ $builder = ImportFileBuilder::new(['companyName' => $ownCompany->name]);
+ $import = Import::factory()->asset()->create([
+ 'file_path' => $builder->saveToImportsDirectory(),
+ 'created_by' => $user->id,
+ ]);
+
+ $this->actingAsForApi($user);
+ $this->importFileResponse(['import' => $import->id]);
+
+ $asset = Asset::query()->where('serial', $builder->firstRow()['serialNumber'])->first();
+
+ $this->assertNotNull($asset, 'Legit same-tenant import should still succeed.');
+ $this->assertSame($ownCompany->id, $asset->company_id);
+ }
+
+ #[Test]
+ public function empty_pivot_user_gets_floater_pass_when_floater_mode_is_on(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport()->enableFloaterMode();
+
+ $existingCo = Company::factory()->create();
+ $floater = User::factory()->canImport()->withoutCompany()->create();
+
+ $builder = ImportFileBuilder::new(['companyName' => $existingCo->name]);
+ $import = Import::factory()->asset()->create([
+ 'file_path' => $builder->saveToImportsDirectory(),
+ 'created_by' => $floater->id,
+ ]);
+
+ $this->actingAsForApi($floater);
+ $this->importFileResponse(['import' => $import->id]);
+
+ $asset = Asset::query()->where('serial', $builder->firstRow()['serialNumber'])->first();
+
+ $this->assertNotNull($asset, 'Empty-pivot floater should be able to import.');
+ $this->assertSame($existingCo->id, $asset->company_id, 'Floater should be able to pin to any company.');
+ }
+
+ #[Test]
+ public function empty_pivot_user_is_rejected_when_floater_mode_is_off(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport()->disableFloaterMode();
+
+ $existingCo = Company::factory()->create();
+ $attacker = User::factory()->canImport()->withoutCompany()->create();
+
+ $builder = ImportFileBuilder::new(['companyName' => $existingCo->name]);
+ $import = Import::factory()->asset()->create([
+ 'file_path' => $builder->saveToImportsDirectory(),
+ 'created_by' => $attacker->id,
+ ]);
+
+ $this->actingAsForApi($attacker);
+ $this->importFileResponse(['import' => $import->id]);
+
+ $this->assertDatabaseMissing('assets', [
+ 'serial' => $builder->firstRow()['serialNumber'],
+ ]);
+ }
+
+ #[Test]
+ public function superuser_can_still_pin_to_any_company_and_auto_create(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $existingCo = Company::factory()->create();
+ $superuser = User::factory()->superuser()->create();
+
+ $builder = ImportFileBuilder::new(['companyName' => $existingCo->name]);
+ $import = Import::factory()->asset()->create([
+ 'file_path' => $builder->saveToImportsDirectory(),
+ 'created_by' => $superuser->id,
+ ]);
+
+ $this->actingAsForApi($superuser);
+ $this->importFileResponse(['import' => $import->id]);
+
+ $asset = Asset::query()->where('serial', $builder->firstRow()['serialNumber'])->firstOrFail();
+ $this->assertSame($existingCo->id, $asset->company_id);
+ }
+
+ #[Test]
+ public function scoped_importer_cannot_update_another_tenants_asset_by_id(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$attackerCo, $victimCo] = Company::factory()->count(2)->create();
+ $attacker = User::factory()->canImport()->forCompany($attackerCo)->create();
+
+ $victimAsset = Asset::factory()->create([
+ 'company_id' => $victimCo->id,
+ 'name' => 'ORIGINAL_VICTIM_NAME',
+ ]);
+
+ $csv = "ID,Asset Tag,item Name\n";
+ $csv .= "{$victimAsset->id},{$victimAsset->asset_tag},HIJACKED_BY_ATTACKER\n";
+ $filename = 'attack-'.uniqid().'.csv';
+ file_put_contents(config('app.private_uploads')."/imports/{$filename}", $csv);
+
+ $import = Import::factory()->asset()->create([
+ 'file_path' => $filename,
+ 'created_by' => $attacker->id,
+ ]);
+
+ $this->actingAsForApi($attacker);
+ $this->importFileResponse(['import' => $import->id]);
+
+ $this->assertSame(
+ 'ORIGINAL_VICTIM_NAME',
+ $victimAsset->fresh()->name,
+ 'Attacker must not update another tenants asset by id.',
+ );
+ }
+
+ #[Test]
+ public function scoped_importer_cannot_pin_asset_to_foreign_company_location_when_locations_are_fmcs_scoped(): void
+ {
+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();
+
+ [$attackerCo, $victimCo] = Company::factory()->count(2)->create();
+ $attacker = User::factory()->canImport()->forCompany($attackerCo)->create();
+
+ $victimLocation = Location::factory()->create(['company_id' => $victimCo->id]);
+
+ $builder = ImportFileBuilder::new([
+ 'companyName' => $attackerCo->name,
+ 'location' => $victimLocation->name,
+ ]);
+ $import = Import::factory()->asset()->create([
+ 'file_path' => $builder->saveToImportsDirectory(),
+ 'created_by' => $attacker->id,
+ ]);
+
+ $this->actingAsForApi($attacker);
+ $this->importFileResponse(['import' => $import->id]);
+
+ $this->assertDatabaseMissing('assets', [
+ 'serial' => $builder->firstRow()['serialNumber'],
+ ]);
+ }
+}