A free open source IT asset/license management system
Added Mosyle Business endpoint
snipe9307b060515d
diff --git a/app/SyncAdapters/MosyleBusiness/MosyleBusinessAdapter.php b/app/SyncAdapters/MosyleBusiness/MosyleBusinessAdapter.phpnew file mode 100644index 0000000000..eef3689ca6--- /dev/null+++ b/app/SyncAdapters/MosyleBusiness/MosyleBusinessAdapter.php@@ -0,0 +1,319 @@+<?php++namespace App\SyncAdapters\MosyleBusiness;++use App\Models\Asset;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableAdapter;+use App\SyncAdapters\SyncAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * Mosyle Business adapter. Pulls device inventory from a Mosyle+ * Business v1 tenant and normalizes it into HostInventoryRecord+ * objects. Also pushes Snipe-IT-authoritative asset_tag and composed+ * notes back via Mosyle's dispatcher-style /devices endpoint.+ *+ * Sibling to MosyleAdapter (Manager v2). The two share almost all of+ * their device-field names, so normalize() is nearly identical, but+ * the auth model, endpoint URL, response wrapping, OS enum, and push+ * payload shape differ enough that they live in separate adapter ++ * client pairs. See the MosyleBusinessClient docblock for the full+ * compare.+ *+ * Key difference admins care about: Business exposes a `notes` push+ * field. This adapter wires that up through the composed-notes+ * framework.+ */+class MosyleBusinessAdapter extends SyncAdapter implements PushableAdapter+{+ public static function typeLabel(): string+ {+ return 'Mosyle Business';+ }++ public static function typeSlug(): string+ {+ return 'mosyle_business';+ }++ public static function docsUrl(): ?string+ {+ return 'https://school.mosyle.com/solutions/macos/privilege-management';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://businessapi.mosyle.com/v1';+ }++ public function settingsSchema(): array+ {+ return [+ [+ 'key' => 'access_token',+ 'label' => trans('admin/settings/sync_adapters.label_access_token'),+ 'secret' => true,+ 'help' => trans('admin/settings/sync_adapters.mosyle_business_access_token_help'),+ ],+ [+ 'key' => 'email',+ 'label' => trans('general.email'),+ 'help' => trans('admin/settings/sync_adapters.mosyle_business_email_help'),+ ],+ [+ 'key' => 'password',+ 'label' => trans('general.password'),+ 'secret' => true,+ 'help' => trans('admin/settings/sync_adapters.mosyle_business_password_help'),+ ],+ ];+ }++ /**+ * Business and Manager return almost identical device fields, so+ * the same extras set applies to both. Lang keys are reused from+ * the Manager adapter's mosyle_extra_* namespace to keep the+ * translator community from carrying 60 duplicate strings.+ */+ public function extraFields(): array+ {+ return [+ // Hardware / inventory+ 'mosyle_battery' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_battery'],+ 'mosyle_total_disk' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_total_disk'],+ 'mosyle_available_disk' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_available_disk'],+ 'mosyle_bluetooth_mac' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_bluetooth_mac'],+ 'mosyle_ethernet_mac' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_ethernet_mac'],+ 'mosyle_device_type' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_device_type'],+ 'mosyle_build_version' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_build_version'],+ // Cellular+ 'mosyle_carrier' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_carrier'],+ 'mosyle_imei' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_imei'],+ 'mosyle_meid' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_meid'],+ // Security / posture+ 'mosyle_activation_lock_enabled' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_activation_lock_enabled', 'type' => 'boolean'],+ 'mosyle_device_locator_enabled' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_device_locator_enabled', 'type' => 'boolean'],+ 'mosyle_cloud_backup_enabled' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_cloud_backup_enabled', 'type' => 'boolean'],+ 'mosyle_last_cloud_backup_date' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_last_cloud_backup_date'],+ 'mosyle_sip_enabled' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_sip_enabled', 'type' => 'boolean'],+ 'mosyle_device_attestation_status' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_device_attestation_status'],+ // MDM / lifecycle+ 'mosyle_enrollment_type' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_enrollment_type'],+ 'mosyle_status' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_status'],+ 'mosyle_management_status' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_management_status'],+ 'mosyle_os_update_status' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_os_update_status'],+ 'mosyle_date_last_beat' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_date_last_beat'],+ 'mosyle_date_last_push' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_date_last_push'],+ 'mosyle_user_id' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_user_id'],+ 'mosyle_supervised' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_supervised', 'type' => 'boolean'],+ // User / scoping+ 'mosyle_user_type' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_user_type'],+ 'mosyle_location' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_location'],+ 'mosyle_tags' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_tags'],+ // Network+ 'mosyle_last_ssid' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_last_ssid'],+ // Lost-mode fields (only populated when device is in lost mode)+ 'mosyle_lost_mode_status' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_lost_mode_status'],+ 'mosyle_latitude' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_latitude'],+ 'mosyle_longitude' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_longitude'],+ 'mosyle_altitude' => ['label_key' => 'admin/settings/sync_adapters.mosyle_extra_altitude'],+ ];+ }++ public function pull(): iterable+ {+ $client = $this->makeClient();++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert a Mosyle Business device payload into the normalized+ * record shape. Field names match the Business v1 /devices list+ * response. `username` not `usename`, `last_lan_ip` for the+ * device IP, same as Manager v2.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'deviceudid'),+ hostname: Arr::get($device, 'device_name'),+ hardwareSerial: Arr::get($device, 'serial_number'),+ hardwareModel: Arr::get($device, 'device_model_name') ?? Arr::get($device, 'device_model'),+ manufacturer: 'Apple',+ primaryMac: Arr::get($device, 'wifi_mac_address'),+ primaryIp: Arr::get($device, 'last_lan_ip'),+ os: Arr::get($device, 'os'),+ osVersion: Arr::get($device, 'osversion'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'date_info')),+ assetTag: Arr::get($device, 'asset_tag'),+ assignedUserEmail: Arr::get($device, 'useremail'),+ assignedUserName: Arr::get($device, 'username'),+ extra: [+ // Hardware / inventory+ 'mosyle_battery' => Arr::get($device, 'battery'),+ 'mosyle_total_disk' => Arr::get($device, 'total_disk'),+ 'mosyle_available_disk' => Arr::get($device, 'available_disk'),+ 'mosyle_bluetooth_mac' => Arr::get($device, 'bluetooth_mac_address'),+ 'mosyle_ethernet_mac' => Arr::get($device, 'ethernet_mac_address'),+ 'mosyle_device_type' => Arr::get($device, 'device_type'),+ 'mosyle_build_version' => Arr::get($device, 'BuildVersion'),+ // Cellular+ 'mosyle_carrier' => Arr::get($device, 'carrier'),+ 'mosyle_imei' => Arr::get($device, 'imei'),+ 'mosyle_meid' => Arr::get($device, 'meid'),+ // Security / posture+ 'mosyle_activation_lock_enabled' => Arr::get($device, 'isActivationLockEnabled'),+ 'mosyle_device_locator_enabled' => Arr::get($device, 'isDeviceLocatorServiceEnabled'),+ 'mosyle_cloud_backup_enabled' => Arr::get($device, 'isCloudBackupEnabled'),+ 'mosyle_last_cloud_backup_date' => Arr::get($device, 'LastCloudBackupDate'),+ 'mosyle_sip_enabled' => Arr::get($device, 'SystemIntegrityProtectionEnabled'),+ 'mosyle_device_attestation_status' => Arr::get($device, 'DeviceAttestationStatus'),+ // MDM / lifecycle+ 'mosyle_enrollment_type' => Arr::get($device, 'enrollment_type'),+ 'mosyle_status' => Arr::get($device, 'status'),+ 'mosyle_management_status' => Arr::get($device, 'ManagementStatus'),+ 'mosyle_os_update_status' => Arr::get($device, 'OSUpdateStatus'),+ 'mosyle_date_last_beat' => Arr::get($device, 'date_last_beat'),+ 'mosyle_date_last_push' => Arr::get($device, 'date_last_push'),+ 'mosyle_user_id' => Arr::get($device, 'userid'),+ 'mosyle_supervised' => Arr::get($device, 'is_supervised'),+ // User / scoping+ 'mosyle_user_type' => Arr::get($device, 'usertype'),+ 'mosyle_location' => Arr::get($device, 'location'),+ 'mosyle_tags' => Arr::get($device, 'tags'),+ // Network+ 'mosyle_last_ssid' => Arr::get($device, 'last_ssid'),+ // Lost-mode+ 'mosyle_lost_mode_status' => Arr::get($device, 'lostmode_status'),+ 'mosyle_latitude' => Arr::get($device, 'latitude'),+ 'mosyle_longitude' => Arr::get($device, 'longitude'),+ 'mosyle_altitude' => Arr::get($device, 'altitude'),+ ],+ );+ }++ /**+ * Mosyle Business returns timestamps as Unix epoch seconds (same+ * as Manager v2). Numeric values in the plausible Unix-time range+ * get routed through createFromTimestamp. ISO strings fall back+ * to Carbon::parse. Any failure logs and returns null rather than+ * aborting a sync run on one bad device.+ */+ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ try {+ if (is_numeric($value) && $value >= 1_000_000_000 && $value <= 100_000_000_000) {+ return Carbon::createFromTimestampUTC((int) $value);+ }++ return Carbon::parse($value);+ } catch (\Throwable $e) {+ Log::channel('sync-adapters')->warning(+ $this->name().': skipped unparseable Mosyle Business timestamp ('.var_export($value, true).'): '.$e->getMessage()+ );++ return null;+ }+ }++ /**+ * Business writes use the same credential set as reads. No tier+ * / license gate, so canPush is always true for a configured+ * instance.+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * Business DOES support a notes push field (Manager does not).+ * The dispatcher endpoint accepts notes as a top-level string+ * on operation=update_device.+ */+ public function notesFieldTarget(): ?string+ {+ return 'notes';+ }++ /**+ * Push Snipe-IT asset_tag (and optionally composed notes) back+ * to Mosyle Business. Both land in a single update_device call+ * because the dispatcher accepts multiple writable fields in one+ * payload.+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): bool+ {+ $externalSource = $this->pushPrologue($asset, $changedFields);+ if ($externalSource === null) {+ return false;+ }++ $serial = $asset->serial;+ if ($serial === null || $serial === '') {+ $serial = $externalSource->external_id;+ }++ $fields = [];+ $pushedLabels = [];++ if (in_array('asset_tag', $this->pushDirectedFields(), true)) {+ $value = $this->assetValueForSourceField($asset, 'asset_tag');+ if ($value !== null && $value !== '') {+ $fields['asset_tag'] = (string) $value;+ $pushedLabels[] = 'asset_tag';+ }+ }++ $composedNotes = $this->composeNotesForPush($asset);+ if ($composedNotes !== null) {+ $fields[$composedNotes['target']] = $composedNotes['value'];+ $pushedLabels[] = 'notes';+ }++ if ($fields === []) {+ return false;+ }++ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(+ $this->name().' push [dry-run]: would update Mosyle Business device serial='.$serial.' fields ['.implode(', ', $pushedLabels).']'+ );++ return true;+ }++ $this->makeClient()->updateDeviceBySerial($serial, $fields);++ Log::channel('sync-adapters')->info(+ $this->name().' push: updated Mosyle Business device serial='.$serial.' fields ['.implode(', ', $pushedLabels).']'+ );++ return true;+ }++ private function makeClient(): MosyleBusinessClient+ {+ return new MosyleBusinessClient(+ baseUrl: $this->url(),+ accessToken: $this->credential('access_token'),+ email: $this->credential('email'),+ password: $this->credential('password'),+ );+ }+}diff --git a/app/SyncAdapters/MosyleBusiness/MosyleBusinessClient.php b/app/SyncAdapters/MosyleBusiness/MosyleBusinessClient.phpnew file mode 100644index 0000000000..f39c08dd42--- /dev/null+++ b/app/SyncAdapters/MosyleBusiness/MosyleBusinessClient.php@@ -0,0 +1,184 @@+<?php++namespace App\SyncAdapters\MosyleBusiness;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Mosyle Business v1 API. Owns auth ++ * pagination for the endpoints the sync adapter uses. Yields raw+ * decoded JSON, no normalization (that's the adapter's job).+ *+ * Auth model (Mosyle Business v1):+ * 1. POST /login with the accessToken in the request HEADER and+ * { email, password } in the body. Response carries a JWT bearer+ * token in the Authorization response header, valid 24h.+ * 2. Every subsequent request carries BOTH the accessToken in the+ * request header AND the JWT in the Authorization: Bearer header.+ * Business keeps the accessToken header-only. Manager keeps the+ * accessToken body-only. Do not confuse the two.+ *+ * Device endpoint shape is also different from Manager v2: Business+ * uses a dispatcher pattern on POST /devices keyed by the `operation`+ * field (list / update_device / shutdown_devices / wipe_devices /+ * assign_devices / etc.). The response is wrapped in an array+ * (`response[0].devices`) rather than Manager's object form+ * (`response.devices`). The OS enum uses `mac` where Manager uses+ * `macos`.+ *+ * Business adds a real `notes` push field, which Manager does not+ * expose. The adapter uses that to opt into composed-notes push.+ *+ * JWT is cached on this instance for the life of the sync run. No+ * cross-run persistence. One sync spawns one client so one login+ * services every /devices page call.+ */+class MosyleBusinessClient+{+ // Mosyle Business splits devices by OS, which is a required option+ // on /devices list. A full-tenant pull iterates each OS. Note that+ // Business uses `mac` not `macos` (Manager uses `macos`).+ private const DEVICE_OSES = [+ 'mac',+ 'ios',+ 'tvos',+ 'visionos',+ ];++ private ?string $jwt = null;++ public function __construct(+ private readonly string $baseUrl,+ private readonly string $accessToken,+ private readonly string $email,+ private readonly string $password,+ ) {}++ /**+ * Iterate every managed device in the Mosyle Business tenant+ * across every supported OS, one page at a time. Returns a+ * generator so callers stream through large fleets without+ * holding the whole list in memory.+ *+ * @return iterable<array<string, mixed>>+ */+ public function devices(int $pageSize = 200): iterable+ {+ foreach (self::DEVICE_OSES as $os) {+ yield from $this->devicesForOs($os, $pageSize);+ }+ }++ /**+ * Paginate /devices list for a single OS. Terminates when a page+ * comes back shorter than page_size.+ *+ * @return iterable<array<string, mixed>>+ */+ private function devicesForOs(string $os, int $pageSize): iterable+ {+ $page = 1;++ do {+ $response = $this->request()+ ->post('/devices', [+ 'operation' => 'list',+ 'options' => [+ 'os' => $os,+ 'page_size' => $pageSize,+ 'page' => $page,+ ],+ ])+ ->throw()+ ->json();++ // Business wraps the response in an array:+ // `response[0].devices`. Manager keeps it as an object:+ // `response.devices`. Preserve the array unwrap carefully.+ $rows = $response['response'][0]['devices'] ?? [];++ foreach ($rows as $device) {+ yield $device;+ }++ $done = count($rows) < $pageSize;+ $page++;+ } while (! $done);+ }++ /**+ * Update writable per-device metadata by serial number. Business+ * uses the dispatcher pattern: POST /devices with+ * operation=update_device and the serialnumber + updatable fields+ * at the top level of the body (no `elements` array like Manager).+ *+ * Fields the caller doesn't include stay untouched. Business+ * exposes asset_tag, device_name, tags, lockmessage, and notes.+ * The adapter uses asset_tag and notes.+ *+ * @param array<string, scalar|null> $fields+ */+ public function updateDeviceBySerial(string $serial, array $fields): void+ {+ $payload = array_merge(+ [+ 'operation' => 'update_device',+ 'serialnumber' => $serial,+ ],+ $fields,+ );++ $this->request()+ ->post('/devices', $payload)+ ->throw();+ }++ /**+ * Fetch (or reuse) the JWT bearer token. First call POSTs to+ * /login with accessToken in the HEADER and email/password in+ * the body. Subsequent calls reuse the cached JWT for the life+ * of this client instance.+ *+ * Mosyle returns the JWT in the Authorization response header,+ * not the body.+ */+ private function bearer(): string+ {+ if ($this->jwt !== null) {+ return $this->jwt;+ }++ $response = Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withOptions(['allow_redirects' => false])+ ->withHeaders(['accessToken' => $this->accessToken])+ ->acceptJson()+ ->asJson()+ ->timeout(30)+ ->post('/login', [+ 'email' => $this->email,+ 'password' => $this->password,+ ])+ ->throw();++ $header = $response->header('Authorization');+ if ($header === '' || ! str_starts_with($header, 'Bearer ')) {+ throw new \RuntimeException('Mosyle Business /login did not return a Bearer token in the Authorization response header. Check the access token, email, and password.');+ }++ return $this->jwt = substr($header, 7);+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withOptions(['allow_redirects' => false])+ ->withHeaders([+ 'accessToken' => $this->accessToken,+ 'Authorization' => 'Bearer '.$this->bearer(),+ ])+ ->acceptJson()+ ->asJson()+ ->timeout(30);+ }+}diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 73a132587e..9413d3d768 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -165,6 +165,9 @@ return ['mosyle_access_token_help' => 'Generate under Account -> API in your Mosyle Manager admin console. Needs read access to Devices (and write access if you plan to push asset tags back to Mosyle).','mosyle_email_help' => 'Email address of the Mosyle admin account used to log in. Pairs with the access token and password to obtain a 24-hour JWT.','mosyle_password_help' => 'Password for the Mosyle admin account above. We recommend creating a dedicated service account with the narrowest permissions needed for sync, rather than reusing a human admin\'s login.',+ 'mosyle_business_access_token_help' => 'Generate under Organization -> API Integration in your Mosyle Business admin console. Needs read access to Devices (and write access if you plan to push asset tags or notes back to Mosyle).',+ 'mosyle_business_email_help' => 'Email address of the Mosyle Business admin account used to log in. Pairs with the access token and password to obtain a 24-hour JWT.',+ 'mosyle_business_password_help' => 'Password for the Mosyle Business admin account above. We recommend creating a dedicated service account with the narrowest permissions needed for sync, rather than reusing a human admin\'s login. The password is stored encrypted at rest but is reversible by design (we need to send it to Mosyle on each login).',// Mosyle Manager v2 extra fields. One label per Manager v2 device// attribute surfaced for custom-field mapping. Dual-SIM cellular// (imeiOne/Two, PhoneNumberOne/Two, etc.) is intentionally omitted.diff --git a/tests/Feature/SyncAdapters/MosyleBusiness/MosyleBusinessAdapterTest.php b/tests/Feature/SyncAdapters/MosyleBusiness/MosyleBusinessAdapterTest.phpnew file mode 100644index 0000000000..8e30319717--- /dev/null+++ b/tests/Feature/SyncAdapters/MosyleBusiness/MosyleBusinessAdapterTest.php@@ -0,0 +1,299 @@+<?php++namespace Tests\Feature\SyncAdapters\MosyleBusiness;++use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\MosyleBusiness\MosyleBusinessAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * End-to-end coverage for the Mosyle Business adapter. Mocks the+ * Business v1 response shapes: JWT returned in the Authorization+ * header on /login, /devices dispatcher POST with+ * operation=list, accessToken required in the request HEADER (not+ * body) on every call, and the array-wrapped response at+ * response[0].devices.+ */+class MosyleBusinessAdapterTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ }++ public function test_pulls_devices_from_mosyle_business_and_creates_assets(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::sequence()+ // First mac page returns two devices.+ ->push($this->devicesResponse([+ $this->businessDevice(udid: 'biz-mac-1', name: 'biz-mbp-01', model: 'MacBook Pro'),+ $this->businessDevice(udid: 'biz-mac-2', name: 'biz-mbp-02', model: 'MacBook Air'),+ ]))+ // Terminator for mac + empty responses for ios / tvos / visionos+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([])),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 2);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'mosyle_business', 'external_id' => 'biz-mac-1']);+ $this->assertDatabaseHas('assets', ['name' => 'biz-mbp-01']);+ }++ public function test_devices_request_carries_access_token_in_header_not_body(): void+ {+ // Business keeps accessToken header-only. Manager keeps it+ // body-only. Both patterns coexist in the codebase, so+ // asserting the header position catches a Business-to-Manager+ // regression where the adapter accidentally moves the token+ // into the body.+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::response($this->devicesResponse([])),+ ]);++ iterator_to_array($adapter->pull());++ Http::assertSent(function ($request) {+ if (! str_ends_with($request->url(), '/devices')) {+ return true;+ }+ $body = $request->data();++ return $request->method() === 'POST'+ && ($request->header('accessToken')[0] ?? null) === 'fake-access-token'+ && ($request->header('Authorization')[0] ?? null) === 'Bearer fake-jwt'+ && ! array_key_exists('accessToken', $body)+ && ($body['operation'] ?? null) === 'list';+ });+ }++ public function test_devices_request_iterates_each_business_os(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::response($this->devicesResponse([])),+ ]);++ iterator_to_array($adapter->pull());++ $osesRequested = [];+ Http::assertSent(function ($request) use (&$osesRequested) {+ if (str_ends_with($request->url(), '/devices')) {+ $osesRequested[] = $request->data()['options']['os'] ?? null;+ }++ return true;+ });++ // Business uses 'mac', not Manager's 'macos'.+ $this->assertSame(['mac', 'ios', 'tvos', 'visionos'], $osesRequested);+ }++ public function test_login_posts_access_token_as_header_and_credentials_as_body(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::response($this->devicesResponse([])),+ ]);++ iterator_to_array($adapter->pull());++ Http::assertSent(function ($request) {+ if (! str_ends_with($request->url(), '/login')) {+ return true;+ }+ $body = $request->data();++ return $request->method() === 'POST'+ && ($request->header('accessToken')[0] ?? null) === 'fake-access-token'+ && ($body['email'] ?? null) === '[email protected]'+ && ($body['password'] ?? null) === 'fake-password'+ && ! array_key_exists('accessToken', $body);+ });+ }++ public function test_response_is_unwrapped_from_the_array_wrapper(): void+ {+ // Business returns response[0].devices. Manager returns+ // response.devices. The adapter must unwrap the array form.+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::sequence()+ ->push($this->devicesResponse([+ $this->businessDevice(udid: 'wrap-1', name: 'wrapped'),+ ]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([])),+ ]);++ $records = iterator_to_array($adapter->pull());++ $this->assertCount(1, $records);+ $this->assertSame('wrap-1', $records[0]->sourceId);+ }++ public function test_normalized_record_populates_business_specific_field_names(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::sequence()+ ->push($this->devicesResponse([[+ 'deviceudid' => 'biz-full',+ 'serial_number' => 'C02-BIZ',+ 'device_name' => 'biz-full-device',+ 'device_model' => 'iPad12,1',+ 'device_model_name' => 'iPad',+ 'os' => 'ios',+ 'osversion' => '16.6.1',+ 'wifi_mac_address' => '60:99:ab:1a:a6:c9',+ 'last_lan_ip' => '192.168.1.42',+ 'username' => 'ada',+ 'useremail' => '[email protected]',+ 'date_info' => '1694210840',+ 'battery' => '0.81',+ 'is_supervised' => '1',+ 'enrollment_type' => 'GENERAL',+ 'status' => 'IN',+ ]]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([])),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertCount(1, $records);++ $record = $records[0];+ $this->assertSame('mosyle_business', $record->sourceKey);+ $this->assertSame('biz-full', $record->sourceId);+ $this->assertSame('biz-full-device', $record->hostname);+ $this->assertSame('iPad', $record->hardwareModel);+ $this->assertSame('C02-BIZ', $record->hardwareSerial);+ $this->assertSame('Apple', $record->manufacturer);+ $this->assertSame('192.168.1.42', $record->primaryIp);+ $this->assertSame('ada', $record->assignedUserName);+ $this->assertSame('[email protected]', $record->assignedUserEmail);+ $this->assertSame('0.81', $record->extra['mosyle_battery']);+ $this->assertSame('GENERAL', $record->extra['mosyle_enrollment_type']);+ $this->assertNotNull($record->lastSeen);+ $this->assertSame(1694210840, $record->lastSeen->getTimestamp());+ }++ public function test_falls_back_to_device_model_when_device_model_name_is_absent(): void+ {+ // Business response in the real API returns `device_model`+ // (e.g. 'iPad12,1') but may omit `device_model_name` on some+ // devices. Manager v2 returns both. Normalize prefers+ // device_model_name but falls back to device_model so no+ // record lands without a model.+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::sequence()+ ->push($this->devicesResponse([[+ 'deviceudid' => 'fallback',+ 'serial_number' => 'XZ',+ 'device_model' => 'iPad12,1',+ 'os' => 'ios',+ ]]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([]))+ ->push($this->devicesResponse([])),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertSame('iPad12,1', $records[0]->hardwareModel);+ }++ public function test_login_missing_authorization_header_throws(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/login' => Http::response(['status' => 'OK'], 200),+ '*/devices' => Http::response($this->devicesResponse([])),+ ]);++ $this->expectExceptionMessage('Mosyle Business /login did not return a Bearer token');++ iterator_to_array($adapter->pull());+ }++ /**+ * @return array<string, mixed>+ */+ private function devicesResponse(array $devices): array+ {+ // Business response shape: `response` is an ARRAY wrapper.+ return [+ 'status' => 'OK',+ 'response' => [[+ 'devices' => $devices,+ 'rows' => count($devices),+ 'page' => 1,+ 'page_size' => 200,+ ]],+ ];+ }++ private function configuredAdapter(): MosyleBusinessAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'mosyle_business')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://businessapi.mosyle.com/v1');+ SyncAdapterConfig::put($instance->id, 'access_token', Crypt::encrypt('fake-access-token'));+ SyncAdapterConfig::put($instance->id, 'email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'password', Crypt::encrypt('fake-password'));++ return new MosyleBusinessAdapter($instance->fresh());+ }++ /**+ * @return array<string, mixed>+ */+ private function businessDevice(+ string $udid,+ string $name = 'device',+ string $model = 'iPad',+ ?string $serial = null,+ ?string $os = 'ios',+ ): array {+ return [+ 'deviceudid' => $udid,+ 'device_name' => $name,+ 'device_model_name' => $model,+ 'serial_number' => $serial,+ 'os' => $os,+ ];+ }+}diff --git a/tests/Feature/SyncAdapters/MosyleBusiness/MosyleBusinessPushTest.php b/tests/Feature/SyncAdapters/MosyleBusiness/MosyleBusinessPushTest.phpnew file mode 100644index 0000000000..9b31dfbb60--- /dev/null+++ b/tests/Feature/SyncAdapters/MosyleBusiness/MosyleBusinessPushTest.php@@ -0,0 +1,127 @@+<?php++namespace Tests\Feature\SyncAdapters\MosyleBusiness;++use App\Models\Asset;+use App\Models\AssetExternalSource;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\MosyleBusiness\MosyleBusinessAdapter;+use App\SyncAdapters\PushableAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * Push-path coverage for the Mosyle Business adapter. Business uses+ * a dispatcher pattern on POST /devices with operation=update_device,+ * carrying serialnumber + updatable fields at the top level of the+ * body. Business DOES support a notes push field, unlike Manager v2.+ */+class MosyleBusinessPushTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ }++ public function test_adapter_implements_pushable_interface(): void+ {+ $this->assertInstanceOf(PushableAdapter::class, $this->configured());+ }++ public function test_push_asset_tag_sends_update_device_operation_at_top_level(): void+ {+ $adapter = $this->configured();+ $instance = SyncAdapterInstance::where('slug', 'mosyle_business')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'direction.asset_tag', 'push');++ $asset = Asset::factory()->create([+ 'asset_tag' => 'SNIPE-BIZ-77',+ 'serial' => 'BIZ-SN-777',+ ]);+ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => $adapter->name(),+ 'external_id' => 'biz-udid-abc',+ ]);++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::response(['status' => 'OK']),+ ]);++ $this->assertTrue($adapter->push($asset));++ Http::assertSent(function ($request) {+ if (! str_ends_with($request->url(), '/devices')) {+ return true;+ }+ if ($request->method() !== 'POST') {+ return false;+ }+ $body = $request->data();++ return ($body['operation'] ?? null) === 'update_device'+ && ($body['serialnumber'] ?? null) === 'BIZ-SN-777'+ && ($body['asset_tag'] ?? null) === 'SNIPE-BIZ-77'+ && ($request->header('accessToken')[0] ?? null) === 'fake-access-token'+ && ($request->header('Authorization')[0] ?? null) === 'Bearer fake-jwt'+ && ! array_key_exists('accessToken', $body)+ && ! array_key_exists('elements', $body);+ });+ }++ public function test_notes_field_target_is_notes_because_business_supports_it(): void+ {+ // Business exposes a `notes` string on operation=update_device.+ // Manager v2 does not, which is the Business adapter's main+ // feature advantage over the Manager adapter.+ $this->assertSame('notes', $this->configured()->notesFieldTarget());+ }++ public function test_push_falls_back_to_external_id_when_serial_missing(): void+ {+ $adapter = $this->configured();+ $instance = SyncAdapterInstance::where('slug', 'mosyle_business')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'direction.asset_tag', 'push');++ $asset = Asset::factory()->create([+ 'asset_tag' => 'SNIPE-BIZ-88',+ 'serial' => null,+ ]);+ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => $adapter->name(),+ 'external_id' => 'BIZ-SN-888',+ ]);++ Http::fake([+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),+ '*/devices' => Http::response(['status' => 'OK']),+ ]);++ $this->assertTrue($adapter->push($asset));++ Http::assertSent(function ($request) {+ if (! str_ends_with($request->url(), '/devices')) {+ return true;+ }++ return ($request->data()['serialnumber'] ?? null) === 'BIZ-SN-888';+ });+ }++ private function configured(): MosyleBusinessAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'mosyle_business')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://example.com/mosyle-business');+ SyncAdapterConfig::put($instance->id, 'access_token', Crypt::encrypt('fake-access-token'));+ SyncAdapterConfig::put($instance->id, 'email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'password', Crypt::encrypt('fake-password'));++ return new MosyleBusinessAdapter($instance->fresh());+ }+}diff --git a/tests/Feature/SyncAdapters/NewBuiltInAdaptersRenderTest.php b/tests/Feature/SyncAdapters/NewBuiltInAdaptersRenderTest.phpindex ca290d1ff2..f8b82ef064 100644--- a/tests/Feature/SyncAdapters/NewBuiltInAdaptersRenderTest.php+++ b/tests/Feature/SyncAdapters/NewBuiltInAdaptersRenderTest.php@@ -17,14 +17,14 @@ use Tests\TestCase;*/class NewBuiltInAdaptersRenderTest extends TestCase{- public function test_mosyle_renders_with_its_schema_label()+ public function test_mosyle_manager_renders_with_its_schema_label(){$html = $this->actingAs(User::factory()->superuser()->create())->get(route('settings.adapters.index'))->assertOk()->getContent();- $this->assertStringContainsString('Mosyle', $html);+ $this->assertStringContainsString('Mosyle Manager', $html);// Schema field names from MosyleAdapter::settingsSchema() post-#19790.// Mosyle Manager v2 requires accessToken + email + password on login.$this->assertMatchesRegularExpression('/name="mosyle_access_token"/', $html);@@ -32,6 +32,26 @@ class NewBuiltInAdaptersRenderTest extends TestCase$this->assertMatchesRegularExpression('/name="mosyle_password"/', $html);}+ public function test_mosyle_business_renders_with_its_schema_label()+ {+ // Mosyle Business is a separate adapter from Mosyle Manager+ // because the Business v1 API has a different auth model,+ // different endpoint shape, and a different OS enum. The+ // catalog auto-discovers it via SyncAdapter::allTypes()'s+ // glob scan of app/SyncAdapters/*/Adapter.php, so this test+ // guards against a slug-collision regression that would hide+ // either adapter from the picker.+ $html = $this->actingAs(User::factory()->superuser()->create())+ ->get(route('settings.adapters.index'))+ ->assertOk()+ ->getContent();++ $this->assertStringContainsString('Mosyle Business', $html);+ $this->assertMatchesRegularExpression('/name="mosyle_business_access_token"/', $html);+ $this->assertMatchesRegularExpression('/name="mosyle_business_email"/', $html);+ $this->assertMatchesRegularExpression('/name="mosyle_business_password"/', $html);+ }+public function test_meraki_systems_manager_renders_with_both_schema_fields(){$html = $this->actingAs(User::factory()->superuser()->create())