Skip to content

A free open source IT asset/license management system

Sync Adapters: Reworked Mosyle for the Manager API (#19790)

snipe1076642a906f
diff --git a/app/SyncAdapters/Mosyle/MosyleAdapter.php b/app/SyncAdapters/Mosyle/MosyleAdapter.php
index 6cbfabfb86..78850fb7bd 100644
--- a/app/SyncAdapters/Mosyle/MosyleAdapter.php
+++ b/app/SyncAdapters/Mosyle/MosyleAdapter.php
@@ -11,18 +11,27 @@ use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
/**
- * Mosyle adapter. Pulls device inventory from a Mosyle tenant (either
- * Manager or Business) via the Mosyle API and normalizes it into
- * HostInventoryRecord objects. The configured base URL determines
- * which product the adapter targets. Also pushes Snipe-IT-
- * authoritative asset_tag back via Mosyle's serial-number-scoped
- * set_asset_tag operation.
+ * Mosyle adapter. Pulls device inventory from a Mosyle Manager v2
+ * tenant via the Mosyle API and normalizes it into HostInventoryRecord
+ * objects. Also pushes Snipe-IT-authoritative asset_tag back via
+ * Mosyle's /devices elements endpoint.
+ *
+ * Business v1 (businessapi.mosyle.com/v1) uses a different endpoint
+ * shape than Manager v2 and is not covered by this adapter today. The
+ * base URL field accepts a Business URL but the device endpoints
+ * expect Manager-shaped payloads, so Business tenants will see the
+ * login succeed and device calls fail. See issue #19790.
*/
class MosyleAdapter extends SyncAdapter implements PushableAdapter
{
public static function typeLabel(): string
{
- return 'Mosyle';
+ // Mosyle Manager and Mosyle Business are different products
+ // with different API shapes. This adapter targets Manager v2
+ // only. Labeling it as "Mosyle Manager" in the adapter picker
+ // keeps Business customers from configuring this expecting it
+ // to work against businessapi.mosyle.com/v1.
+ return 'Mosyle Manager';
}
public static function typeSlug(): string
@@ -44,10 +53,21 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter
{
return [
[
- 'key' => 'token',
+ 'key' => 'access_token',
'label' => trans('admin/settings/sync_adapters.label_access_token'),
'secret' => true,
- 'help' => trans('admin/settings/sync_adapters.mosyle_token_help'),
+ 'help' => trans('admin/settings/sync_adapters.mosyle_access_token_help'),
+ ],
+ [
+ 'key' => 'email',
+ 'label' => trans('general.email'),
+ 'help' => trans('admin/settings/sync_adapters.mosyle_email_help'),
+ ],
+ [
+ 'key' => 'password',
+ 'label' => trans('general.password'),
+ 'secret' => true,
+ 'help' => trans('admin/settings/sync_adapters.mosyle_password_help'),
],
];
}
@@ -55,37 +75,55 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter
public function extraFields(): array
{
return [
- 'mosyle_user_id' => ['label_key' => 'admin/settings/sync_adapters.extra_user_id'],
- 'mosyle_supervised' => ['label_key' => 'admin/settings/sync_adapters.extra_supervised', 'type' => 'boolean'],
+ // 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 (basic). Dual-SIM imeiOne/Two, carrier labels,
+ // phone numbers etc. are intentionally left off per #19790
+ // triage. Add on request if a carrier-managed-iPhone-fleet
+ // customer surfaces.
+ '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 on devices currently in
+ // lost mode. Expect these to stay null on healthy devices.
+ '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 supportsGroupScoping(): bool
- {
- return true;
- }
-
- public function vendorGroupLabel(): string
- {
- return trans('admin/settings/sync_adapters.vendor_group_mosyle_location');
- }
-
- public function fetchGroups(): array
- {
- $client = new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));
-
- return array_map(
- fn (array $location) => [
- 'id' => (string) ($location['id'] ?? $location['locationid'] ?? ''),
- 'label' => (string) ($location['name'] ?? $location['location_name'] ?? $location['id'] ?? '?'),
- ],
- $client->locations(),
- );
- }
-
public function pull(): iterable
{
- $client = new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));
+ $client = $this->makeClient();
foreach ($client->devices() as $device) {
yield $this->normalize($device);
@@ -97,6 +135,10 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter
* Mosyle's `deviceudid` is stable per enrolled device and is what
* we key asset_external_sources on.
*
+ * Field names here match the Mosyle Manager v2 /listdevices response
+ * shape (issue #19790): `username` not `usename`, `last_lan_ip` for
+ * the device IP (`ip_address` is not a documented field).
+ *
* @param array<string, mixed> $device
*/
private function normalize(array $device): HostInventoryRecord
@@ -109,17 +151,53 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter
hardwareModel: Arr::get($device, 'device_model_name'),
manufacturer: 'Apple',
primaryMac: Arr::get($device, 'wifi_mac_address'),
- primaryIp: Arr::get($device, 'ip_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, 'usename'),
- vendorGroupId: Arr::has($device, 'locationid') ? (string) Arr::get($device, 'locationid') : null,
+ 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 (only populated when the device is in 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'),
],
);
}
@@ -134,10 +212,9 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter
}
/**
- * Mosyle writes are token-scoped. Same credential used for pull
- * works for push when the API token has the "Devices - Write"
- * permission. No tier / license gate, so canPush is always true
- * for a configured instance.
+ * Mosyle writes use the same credential set as reads (access token
+ * + login) and the same JWT token flow. No tier / license gate, so
+ * canPush is always true for a configured instance.
*/
public function canPush(): bool
{
@@ -145,22 +222,34 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter
}
/**
- * Mosyle exposes a freeform notes field per device via the
- * `set_notes_by_serial_number` operation. Returning the field
- * name here signals to the push framework that composed notes
- * can flow to this vendor.
+ * Mosyle Manager v2's push payload does not include a notes field.
+ * The documented writable fields on /devices elements are asset_tag,
+ * device_name, lock-screen message, and custom tags. Returning null
+ * here keeps the composed-notes push framework from calling us at
+ * push time. The settings-page UI section is gated separately via
+ * supportsComposedNotesPush() below.
*/
public function notesFieldTarget(): ?string
{
- return 'notes';
+ return null;
+ }
+
+ /**
+ * Mosyle Manager v2's push payload has no field that admin-composed
+ * notes could land in, so hide the composed-notes section on the
+ * adapter settings page entirely. Prevents admins from filling in a
+ * template that would get silently dropped at push time.
+ */
+ public function supportsComposedNotesPush(): bool
+ {
+ return false;
}
/**
* Push Snipe-IT asset_tag back to Mosyle. Mosyle's write API is
- * a single POST endpoint dispatched by an `operation` field.
- * `set_asset_tag_by_serial_number` targets the device by serial
- * (Mosyle also accepts UDID, but serial is what we cached from
- * pull and is more stable across re-enrollment).
+ * POST /devices with an `elements` array keyed by `serialnumber`.
+ * Mosyle also accepts UDID, but serial is what we cached from pull
+ * and is more stable across re-enrollment.
*
* @param array<int, string> $changedFields
*/
@@ -173,58 +262,19 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter
$serial = $asset->serial;
if ($serial === null || $serial === '') {
- // Mosyle keys writes by serial number, not the UDID we
- // stored as external_id. Fall back to external_id when
- // the asset has no serial (Mosyle Business uses
- // serial == external_id for some device types).
+ // Mosyle keys writes by serial, not the UDID we stored as
+ // external_id. Fall back to external_id when the asset has
+ // no serial.
$serial = $externalSource->external_id;
}
- $client = null;
- $pushedFields = array_merge(
- $this->pushAssetTagField($asset, $serial, $client),
- $this->pushComposedNotesField($asset, $serial, $client),
- );
-
- if ($pushedFields === []) {
- return false;
- }
-
- if ($this->isPushDryRun()) {
- // Sub-helpers already logged their per-field dry-run lines.
- // Skip the summary line but count as attempted so the
- // controller flash reflects that admins actually did the
- // thing they clicked.
- return true;
- }
-
- Log::channel('sync-adapters')->info(sprintf(
- '%s push: updated Mosyle device serial=%s fields [%s]',
- $this->name(),
- $serial,
- implode(', ', $pushedFields),
- ));
-
- return true;
- }
-
- /**
- * Push the asset_tag field to Mosyle if it's in pushDirectedFields
- * and has a non-empty value. Handles both dry-run and real calls.
- * $client is passed by reference so the shared HTTP client gets
- * lazy-instantiated once across both push helpers.
- *
- * @return array<int, string> Names of the fields actually pushed.
- */
- private function pushAssetTagField(Asset $asset, string $serial, ?MosyleClient &$client): array
- {
if (! in_array('asset_tag', $this->pushDirectedFields(), true)) {
- return [];
+ return false;
}
$value = $this->assetValueForSourceField($asset, 'asset_tag');
if ($value === null || $value === '') {
- return [];
+ return false;
}
if ($this->isPushDryRun()) {
@@ -235,44 +285,27 @@ class MosyleAdapter extends SyncAdapter implements PushableAdapter
$value,
));
- return ['asset_tag'];
+ return true;
}
- $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));
- $client->updateDeviceAssetTagBySerial($serial, (string) $value);
+ $this->makeClient()->updateDeviceAssetTagBySerial($serial, (string) $value);
+
+ Log::channel('sync-adapters')->info(sprintf(
+ '%s push: updated Mosyle device serial=%s fields [asset_tag]',
+ $this->name(),
+ $serial,
+ ));
- return ['asset_tag'];
+ return true;
}
- /**
- * Push composed notes to Mosyle if a template + target are
- * configured. Independent from the asset_tag push because
- * Mosyle's write API dispatches per-op, so notes get a second
- * POST to /devices with the notes operation.
- *
- * @return array<int, string> Names of the fields actually pushed.
- */
- private function pushComposedNotesField(Asset $asset, string $serial, ?MosyleClient &$client): array
+ private function makeClient(): MosyleClient
{
- $composedNotes = $this->composeNotesForPush($asset);
- if ($composedNotes === null) {
- return [];
- }
-
- if ($this->isPushDryRun()) {
- Log::channel('sync-adapters')->info(sprintf(
- '%s push [dry-run]: would set Mosyle device serial=%s notes=%s',
- $this->name(),
- $serial,
- $composedNotes['value'],
- ));
-
- return ['notes'];
- }
-
- $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));
- $client->updateDeviceNotesBySerial($serial, $composedNotes['value']);
-
- return ['notes'];
+ return new MosyleClient(
+ baseUrl: $this->url(),
+ accessToken: $this->credential('access_token'),
+ email: $this->credential('email'),
+ password: $this->credential('password'),
+ );
}
}
diff --git a/app/SyncAdapters/Mosyle/MosyleClient.php b/app/SyncAdapters/Mosyle/MosyleClient.php
index d107b6ab9e..343e9272ce 100644
--- a/app/SyncAdapters/Mosyle/MosyleClient.php
+++ b/app/SyncAdapters/Mosyle/MosyleClient.php
@@ -6,128 +6,164 @@ use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
/**
- * Thin wrapper around the Mosyle API. Owns auth + pagination for the
- * endpoints the sync adapter uses. Yields raw decoded JSON, no
+ * Thin wrapper around the Mosyle Manager v2 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: bearer access token generated in the Mosyle admin console
- * (Account -> API). The same token works for both Mosyle Manager v2
- * (https://managerapi.mosyle.com/v2) and Mosyle Business v1
- * (https://businessapi.mosyle.com/v1). the base URL configured on the
- * adapter determines which product this instance talks to.
+ * Auth model (Mosyle Manager v2):
+ * 1. POST /login with { accessToken, email, password } returns a JWT
+ * bearer token in the Authorization response header, valid 24h.
+ * 2. Every subsequent request carries BOTH the accessToken in the
+ * request body AND the JWT in the Authorization: Bearer header.
+ * Dropping either returns a 401 "accessToken Required".
*
- * Mosyle's devices endpoint takes POST with a JSON body (not GET with
- * query params like the other vendors here), which is unusual but
- * documented and stable.
+ * JWT is cached on this instance for the life of the sync run (same
+ * pattern IntuneClient uses for its OAuth 2.0 token). No cross-run
+ * persistence. A single sync spawns a single client so one login
+ * services every /listdevices page call.
*
- * Mosyle API reference: https://school.mosyle.com/api/docs
+ * Reads use POST (/listdevices with options), writes use POST
+ * (/devices with elements). Both carry accessToken in the body.
+ *
+ * The Mosyle API is not publicly documented. The endpoint and payload
+ * shapes here match the Manager v2 doc transcription from issue #19790.
+ * Business v1 (businessapi.mosyle.com/v1) is not covered by this
+ * client. If an admin points the base URL at Business the login flow
+ * may still succeed but device endpoints are expected to differ.
*/
class MosyleClient
{
+ // Mosyle Manager splits devices by OS, which is a required option
+ // on /listdevices. A full-tenant pull iterates each OS.
+ private const DEVICE_OSES = [
+ 'macos',
+ 'ios',
+ 'tvos',
+ 'visionos',
+ ];
+
+ private ?string $jwt = null;
+
public function __construct(
private readonly string $baseUrl,
- private readonly string $token,
+ private readonly string $accessToken,
+ private readonly string $email,
+ private readonly string $password,
) {}
/**
- * Iterate every managed device in the Mosyle tenant, one page at a
- * time. Returns a generator so callers stream through large fleets
- * without holding the whole list in memory.
+ * Iterate every managed device in the Mosyle 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 /listdevices for a single OS. Terminates when a page
+ * comes back shorter than page_size.
*
* @return iterable<array<string, mixed>>
*/
- public function devices(int $perPage = 200): iterable
+ private function devicesForOs(string $os, int $pageSize): iterable
{
$page = 1;
do {
$response = $this->request()
- ->post('/devices', [
+ ->post('/listdevices', [
+ 'accessToken' => $this->accessToken,
'options' => [
+ 'os' => $os,
+ 'page_size' => $pageSize,
'page' => $page,
- 'per_page' => $perPage,
],
])
->throw()
->json();
- // Mosyle's response nests devices under
- // response[0].response.rows on Manager v2 and under
- // response.devices on Business v1. Try both shapes so this
- // client works against either product.
- $rows = $response['response'][0]['response']['rows']
- ?? $response['response']['devices']
- ?? [];
+ $rows = $response['response']['devices'] ?? [];
foreach ($rows as $device) {
yield $device;
}
- $done = count($rows) < $perPage;
+ $done = count($rows) < $pageSize;
$page++;
} while (! $done);
}
- /**
- * List every Location in the Mosyle tenant. Used by the
- * adapter's fetchGroups() so admins can map Locations to
- * Snipe-IT companies. Mosyle uses POST for reads (same shape
- * as devices()).
- *
- * @return array<int, array<string, mixed>>
- */
- public function locations(): array
- {
- $response = $this->request()
- ->post('/locations', [])
- ->throw()
- ->json();
-
- return $response['response'][0]['response']['rows']
- ?? $response['response']['locations']
- ?? [];
- }
-
/**
* Update writable per-device metadata by serial number. Mosyle's
- * write API is a single POST endpoint dispatched by the
- * `operation` field. `set_asset_tag_by_serial_number` sets the
- * device's asset_tag field per Mosyle's Manager v2 API. Fields
- * the caller doesn't include stay untouched.
+ * push API is POST /devices with an `elements` array keyed by
+ * `serialnumber`. Each element may carry asset_tag and the other
+ * documented writable fields. Fields the caller doesn't include
+ * stay untouched.
+ *
+ * Mosyle Manager v2 does not expose a notes field for push, so the
+ * adapter never calls this for notes.
*/
public function updateDeviceAssetTagBySerial(string $serial, string $assetTag): void
{
$this->request()
->post('/devices', [
- 'operation' => 'set_asset_tag_by_serial_number',
- 'serial_number' => $serial,
- 'asset_tag' => $assetTag,
+ 'accessToken' => $this->accessToken,
+ 'elements' => [
+ [
+ 'serialnumber' => $serial,
+ 'asset_tag' => $assetTag,
+ ],
+ ],
])
->throw();
}
/**
- * Set the device's notes field. Same operation-dispatch shape
- * as asset_tag. Mosyle Manager v2 exposes `set_notes_by_serial_number`
- * for admin freeform notes. On tenants where the operation
- * doesn't exist Mosyle returns a 4xx that surfaces in the log.
+ * Fetch (or reuse) the JWT bearer token. First call POSTs to
+ * /login. Subsequent calls reuse the cached value for the life of
+ * this client instance.
+ *
+ * Mosyle returns the JWT in the Authorization response header, not
+ * the body (unusual but documented).
*/
- public function updateDeviceNotesBySerial(string $serial, string $notes): void
+ private function bearer(): string
{
- $this->request()
- ->post('/devices', [
- 'operation' => 'set_notes_by_serial_number',
- 'serial_number' => $serial,
- 'notes' => $notes,
+ if ($this->jwt !== null) {
+ return $this->jwt;
+ }
+
+ $response = Http::baseUrl(rtrim($this->baseUrl, '/'))
+ ->withOptions(['allow_redirects' => false])
+ ->acceptJson()
+ ->asJson()
+ ->timeout(30)
+ ->post('/login', [
+ 'accessToken' => $this->accessToken,
+ 'email' => $this->email,
+ 'password' => $this->password,
])
->throw();
+
+ $header = $response->header('Authorization');
+ if ($header === '' || ! str_starts_with($header, 'Bearer ')) {
+ throw new \RuntimeException('Mosyle /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])
- ->withToken($this->token)
+ ->withToken($this->bearer())
->acceptJson()
->asJson()
->timeout(30);
diff --git a/app/SyncAdapters/SyncAdapter.php b/app/SyncAdapters/SyncAdapter.php
index 53958ccd21..6e6d608f1d 100644
--- a/app/SyncAdapters/SyncAdapter.php
+++ b/app/SyncAdapters/SyncAdapter.php
@@ -1492,6 +1492,22 @@ abstract class SyncAdapter
: null;
}
+ /**
+ * Whether the composed-notes push UI should appear on this
+ * adapter's settings page. Default is "yes if the adapter is
+ * pushable at all" so existing adapters stay unchanged. Adapters
+ * targeting APIs that have no notes-like field anywhere in their
+ * push payload (Mosyle Manager v2's push elements, for example)
+ * override this to false so admins don't fill in a template that
+ * can never land. notesFieldTarget() returning null doesn't carry
+ * this meaning (Workspace ONE / NinjaOne return null legitimately
+ * because the admin picks the target).
+ */
+ public function supportsComposedNotesPush(): bool
+ {
+ return $this instanceof PushableAdapter && $this->canPush();
+ }
+
/**
* Currently-selected target for a field, or the shipped default
* when no per-instance override exists. Standard fields fall back
diff --git a/database/migrations/2026_10_08_180859_rename_mosyle_token_credential_to_access_token.php b/database/migrations/2026_10_08_180859_rename_mosyle_token_credential_to_access_token.php
new file mode 100644
index 0000000000..afad540a73
--- /dev/null
+++ b/database/migrations/2026_10_08_180859_rename_mosyle_token_credential_to_access_token.php
@@ -0,0 +1,66 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Support\Facades\DB;
+
+/**
+ * Rename the Mosyle adapter's `token` credential key to `access_token`
+ * on any existing sync_adapter_instances rows. The Mosyle Manager v2
+ * API requires three auth fields on login (accessToken + email +
+ * password), so the single-field token name was ambiguous. Issue
+ * #19790.
+ *
+ * The adapter never worked against a real Mosyle tenant in its
+ * original form, so any value in the old `token` field was almost
+ * certainly never validated. The migration still rotates it onto the
+ * new key rather than dropping it, so admins who have a half-configured
+ * instance don't have to re-paste the token after the upgrade.
+ *
+ * Email and password are new credential fields with no legacy source,
+ * so admins will need to add those on the settings page after upgrade
+ * before the adapter can actually complete a login.
+ */
+return new class extends Migration
+{
+ public function up(): void
+ {
+ $rows = DB::table('sync_adapter_instances')
+ ->where('adapter_type', 'mosyle')
+ ->get();
+
+ foreach ($rows as $row) {
+ $config = $row->config ? json_decode($row->config, true) : [];
+ if (! is_array($config) || ! array_key_exists('token', $config)) {
+ continue;
+ }
+
+ $config['access_token'] = $config['token'];
+ unset($config['token']);
+
+ DB::table('sync_adapter_instances')
+ ->where('id', $row->id)
+ ->update(['config' => json_encode($config)]);
+ }
+ }
+
+ public function down(): void
+ {
+ $rows = DB::table('sync_adapter_instances')
+ ->where('adapter_type', 'mosyle')
+ ->get();
+
+ foreach ($rows as $row) {
+ $config = $row->config ? json_decode($row->config, true) : [];
+ if (! is_array($config) || ! array_key_exists('access_token', $config)) {
+ continue;
+ }
+
+ $config['token'] = $config['access_token'];
+ unset($config['access_token']);
+
+ DB::table('sync_adapter_instances')
+ ->where('id', $row->id)
+ ->update(['config' => json_encode($config)]);
+ }
+ }
+};
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index 18888e0da6..73a132587e 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -162,7 +162,44 @@ return [
'jamf_school_network_id_help' => 'Find your Network ID under Organization -> Settings -> API in the Jamf School admin console.',
'jamf_school_api_key_help' => 'Generate under Organization -> Settings -> API in Jamf School. Needs read access to Devices (and Locations if you use group-to-company mapping).',
'jumpcloud_token_help' => 'Copy from your JumpCloud admin user\'s profile page (top-right menu -> My API Key). API keys inherit the admin user\'s permissions, so use an account with read access to Systems.',
- 'mosyle_token_help' => 'Generate under Account -> API in your Mosyle admin console (Manager or Business). Needs read access to Devices.',
+ '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 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.
+ 'mosyle_extra_battery' => 'Mosyle Battery',
+ 'mosyle_extra_total_disk' => 'Mosyle Total Disk',
+ 'mosyle_extra_available_disk' => 'Mosyle Available Disk',
+ 'mosyle_extra_bluetooth_mac' => 'Mosyle Bluetooth MAC',
+ 'mosyle_extra_ethernet_mac' => 'Mosyle Ethernet MAC',
+ 'mosyle_extra_device_type' => 'Mosyle Device Type',
+ 'mosyle_extra_build_version' => 'Mosyle Build Version',
+ 'mosyle_extra_carrier' => 'Mosyle Carrier',
+ 'mosyle_extra_imei' => 'Mosyle IMEI',
+ 'mosyle_extra_meid' => 'Mosyle MEID',
+ 'mosyle_extra_activation_lock_enabled' => 'Mosyle Activation Lock Enabled',
+ 'mosyle_extra_device_locator_enabled' => 'Mosyle Device Locator Enabled',
+ 'mosyle_extra_cloud_backup_enabled' => 'Mosyle Cloud Backup Enabled',
+ 'mosyle_extra_last_cloud_backup_date' => 'Mosyle Last Cloud Backup Date',
+ 'mosyle_extra_sip_enabled' => 'Mosyle SIP Enabled',
+ 'mosyle_extra_device_attestation_status' => 'Mosyle Device Attestation Status',
+ 'mosyle_extra_enrollment_type' => 'Mosyle Enrollment Type',
+ 'mosyle_extra_status' => 'Mosyle Status',
+ 'mosyle_extra_management_status' => 'Mosyle Management Status',
+ 'mosyle_extra_os_update_status' => 'Mosyle OS Update Status',
+ 'mosyle_extra_date_last_beat' => 'Mosyle Last Heartbeat',
+ 'mosyle_extra_date_last_push' => 'Mosyle Last MDM Push',
+ 'mosyle_extra_user_id' => 'Mosyle User ID',
+ 'mosyle_extra_supervised' => 'Mosyle Supervised',
+ 'mosyle_extra_user_type' => 'Mosyle User Type',
+ 'mosyle_extra_location' => 'Mosyle Location',
+ 'mosyle_extra_tags' => 'Mosyle Tags',
+ 'mosyle_extra_last_ssid' => 'Mosyle Last SSID',
+ 'mosyle_extra_lost_mode_status' => 'Mosyle Lost Mode Status',
+ 'mosyle_extra_latitude' => 'Mosyle Latitude',
+ 'mosyle_extra_longitude' => 'Mosyle Longitude',
+ 'mosyle_extra_altitude' => 'Mosyle Altitude',
'osctrl_token_help' => 'Generate under Users -> API tokens in your osctrl admin console. The user issuing the token needs read access to the target environment\'s nodes.',
'osctrl_environment_help' => 'The osctrl environment name to sync from (e.g. prod, dev).',
'addigy_key_id_help' => 'Generate under Integrations -> Addigy API in your Addigy admin console. Both Client ID and Client Secret come from the same "Create API Integration" flow. Client ID is a public identifier and not encrypted at rest.',
@@ -418,7 +455,6 @@ return [
'vendor_group_jamf_school_location' => 'Jamf School Location',
'vendor_group_kandji_blueprint' => 'Iru (Kandji) Blueprint',
'vendor_group_jamf_platform_blueprint' => 'Jamf Platform Blueprint',
- 'vendor_group_mosyle_location' => 'Mosyle Location',
'vendor_group_kaseya_organization' => 'Kaseya Organization',
'vendor_group_google_workspace_org_unit' => 'Google Organizational Unit',
diff --git a/resources/views/blade/sync-adapter/form.blade.php b/resources/views/blade/sync-adapter/form.blade.php
index cd34543192..3cc820e7c8 100644
--- a/resources/views/blade/sync-adapter/form.blade.php
+++ b/resources/views/blade/sync-adapter/form.blade.php
@@ -540,7 +540,7 @@
multiple candidates. Positioned after the standard + extras
mapping so admins finish configuring the per-field targets
before deciding what goes into the composed notes blob. --}}
- @if ($adapter instanceof \App\SyncAdapters\PushableAdapter && $adapter->canPush())
+ @if ($adapter instanceof \App\SyncAdapters\PushableAdapter && $adapter->canPush() && $adapter->supportsComposedNotesPush())
<fieldset>
<x-form.legend icon="tip" help_text="{{ trans('admin/settings/sync_adapters.push_notes_section_intro') }}">
{{ trans('admin/settings/sync_adapters.push_notes_section_title') }}
diff --git a/tests/Feature/SyncAdapters/Mosyle/MosyleAdapterTest.php b/tests/Feature/SyncAdapters/Mosyle/MosyleAdapterTest.php
index 01efdacbdd..fd3024ef15 100644
--- a/tests/Feature/SyncAdapters/Mosyle/MosyleAdapterTest.php
+++ b/tests/Feature/SyncAdapters/Mosyle/MosyleAdapterTest.php
@@ -12,11 +12,10 @@ use Illuminate\Support\Facades\Http;
use Tests\TestCase;
/**
- * End-to-end coverage for the Mosyle adapter through
- * SyncAdapter. Mocks the Mosyle Manager v2 response shape (the
- * nested response[0].response.rows form), asserts assets + external
- * ids land correctly, and that the client sends POST (not GET) since
- * Mosyle's reads use POST bodies.
+ * End-to-end coverage for the Mosyle adapter through SyncAdapter.
+ * Mocks Mosyle Manager v2's actual response shapes: JWT returned in
+ * the Authorization header on /login, /listdevices paginated by OS,
+ * accessToken required in the request body on every call.
*/
class MosyleAdapterTest extends TestCase
{
@@ -27,26 +26,24 @@ class MosyleAdapterTest extends TestCase
Statuslabel::factory()->rtd()->create();
}
- public function test_pulls_devices_from_mosyle_and_creates_assets()
+ public function test_pulls_devices_from_mosyle_and_creates_assets(): void
{
$adapter = $this->configuredMosyleAdapter();
Http::fake([
- '*/devices' => Http::sequence()
- ->push([
- 'response' => [[
- 'response' => [
- 'rows' => [
- $this->mosyleDevice(udid: 'aaa-111', name: 'edu-ipad-01', model: 'iPad (10th generation)'),
- $this->mosyleDevice(udid: 'bbb-222', name: 'edu-ipad-02', model: 'iPad Air'),
- ],
- ],
- ]],
- ])
- // Empty second page terminates the client's pagination loop.
- ->push([
- 'response' => [['response' => ['rows' => []]]],
- ]),
+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),
+ '*/listdevices' => Http::sequence()
+ // First macOS page returns two devices.
+ ->push($this->devicesResponse([
+ $this->mosyleDevice(udid: 'aaa-111', name: 'edu-ipad-01', model: 'iPad (10th generation)'),
+ $this->mosyleDevice(udid: 'bbb-222', name: 'edu-ipad-02', model: 'iPad Air'),
+ ]))
+ // Empty page terminates macOS pagination.
+ ->push($this->devicesResponse([]))
+ // iOS / tvOS / visionOS all empty.
+ ->push($this->devicesResponse([]))
+ ->push($this->devicesResponse([]))
+ ->push($this->devicesResponse([])),
]);
foreach ($adapter->pull() as $record) {
@@ -58,47 +55,209 @@ class MosyleAdapterTest extends TestCase
$this->assertDatabaseHas('assets', ['name' => 'edu-ipad-01']);
}
- public function test_client_sends_post_not_get()
+ public function test_login_is_called_once_and_jwt_is_reused_across_pages(): void
{
+ // Issue #19790 regression: a Mosyle sync against a tenant with
+ // devices across multiple OSes must POST /login exactly once
+ // and reuse the JWT. Repeated /login would consume Mosyle's
+ // auth rate limit on every page.
$adapter = $this->configuredMosyleAdapter();
Http::fake([
- '*/devices' => Http::response([
- 'response' => [['response' => ['rows' => []]]],
- ]),
+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),
+ '*/listdevices' => Http::response($this->devicesResponse([])),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ $loginCalls = 0;
+ Http::assertSent(function ($request) use (&$loginCalls) {
+ if (str_ends_with($request->url(), '/login')) {
+ $loginCalls++;
+ }
+
+ return true;
+ });
+ $this->assertSame(1, $loginCalls, 'Expected /login to be called exactly once per sync run.');
+ }
+
+ public function test_devices_request_carries_access_token_in_body(): void
+ {
+ // Mosyle 401s with "accessToken Required" if the token is only
+ // in the Authorization header. Both the JWT bearer AND the
+ // body-level accessToken are required on every /listdevices
+ // call.
+ $adapter = $this->configuredMosyleAdapter();
+
+ Http::fake([
+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),
+ '*/listdevices' => Http::response($this->devicesResponse([])),
]);
iterator_to_array($adapter->pull());
- // Mosyle's devices endpoint takes POST with a JSON body,
- // unlike every other adapter here. A regression to GET would
- // 405 against a real tenant. this catches it before it ships.
Http::assertSent(function ($request) {
- return $request->method() === 'POST';
+ if (! str_ends_with($request->url(), '/listdevices')) {
+ return true;
+ }
+
+ return $request->method() === 'POST'
+ && ($request->data()['accessToken'] ?? null) === 'fake-access-token'
+ && ($request->header('Authorization')[0] ?? null) === 'Bearer fake-jwt';
+ });
+ }
+
+ public function test_devices_request_iterates_each_supported_os(): void
+ {
+ $adapter = $this->configuredMosyleAdapter();
+
+ Http::fake([
+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),
+ '*/listdevices' => Http::response($this->devicesResponse([])),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ $osesRequested = [];
+ Http::assertSent(function ($request) use (&$osesRequested) {
+ if (str_ends_with($request->url(), '/listdevices')) {
+ $osesRequested[] = $request->data()['options']['os'] ?? null;
+ }
+
+ return true;
});
+
+ $this->assertSame(['macos', 'ios', 'tvos', 'visionos'], $osesRequested);
}
- public function test_normalized_record_carries_expected_fields()
+ public function test_normalized_record_populates_extra_fields_from_manager_v2_payload(): void
{
+ // Issue #19790: Mosyle Manager v2 returns ~90 fields per device
+ // and we expose a curated subset as extras so admins can map
+ // them to custom fields. This locks in the field-name mapping
+ // (Mosyle API key -> adapter extra key) so a Manager-side
+ // rename or an adapter-side typo would be caught on CI.
$adapter = $this->configuredMosyleAdapter();
Http::fake([
- '*/devices' => Http::sequence()
- ->push([
- 'response' => [['response' => ['rows' => [
- $this->mosyleDevice(
- udid: 'ccc-333',
- name: 'staff-mbp',
- model: 'MacBook Pro',
- serial: 'C02XYZ',
- os: 'macOS',
- osversion: '14.2.1',
- wifi_mac: 'aa:bb:cc:11:22:33',
- date_info: '2026-01-15T10:00:00.000Z',
- ),
- ]]]],
- ])
- ->push(['response' => [['response' => ['rows' => []]]]]),
+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),
+ '*/listdevices' => Http::sequence()
+ ->push($this->devicesResponse([[
+ 'deviceudid' => 'xxx-999',
+ 'serial_number' => 'C02-EXTRA',
+ // Hardware
+ 'battery' => '87',
+ 'total_disk' => '256.0000000000',
+ 'available_disk' => '103.5',
+ 'bluetooth_mac_address' => '11:22:33:44:55:66',
+ 'ethernet_mac_address' => '77:88:99:aa:bb:cc',
+ 'device_type' => 'Mac',
+ 'BuildVersion' => '23B74',
+ // Cellular
+ 'carrier' => 'Verizon',
+ 'imei' => '990000862471854',
+ 'meid' => 'A1000012345678',
+ // Security / posture
+ 'isActivationLockEnabled' => true,
+ 'isDeviceLocatorServiceEnabled' => true,
+ 'isCloudBackupEnabled' => false,
+ 'LastCloudBackupDate' => '2026-01-10T04:00:00Z',
+ 'SystemIntegrityProtectionEnabled' => true,
+ 'DeviceAttestationStatus' => 'VERIFIED',
+ // MDM / lifecycle
+ 'enrollment_type' => 'ADE',
+ 'status' => 'enrolled',
+ 'ManagementStatus' => 'Managed',
+ 'OSUpdateStatus' => 'UpToDate',
+ 'date_last_beat' => '2026-01-15T09:50:00Z',
+ 'date_last_push' => '2026-01-15T09:51:00Z',
+ 'userid' => 'u-42',
+ 'is_supervised' => true,
+ // User / scoping
+ 'usertype' => 'faculty',
+ 'location' => 'HQ',
+ 'tags' => ['loaner', 'ipad-cart-3'],
+ // Network
+ 'last_ssid' => 'office-wifi-5g',
+ // Lost mode
+ 'lostmode_status' => 'inactive',
+ 'latitude' => '37.7749',
+ 'longitude' => '-122.4194',
+ 'altitude' => '12.5',
+ ]]))
+ ->push($this->devicesResponse([]))
+ ->push($this->devicesResponse([]))
+ ->push($this->devicesResponse([]))
+ ->push($this->devicesResponse([])),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertCount(1, $records);
+ $extra = $records[0]->extra;
+
+ // Hardware
+ $this->assertSame('87', $extra['mosyle_battery']);
+ $this->assertSame('256.0000000000', $extra['mosyle_total_disk']);
+ $this->assertSame('103.5', $extra['mosyle_available_disk']);
+ $this->assertSame('11:22:33:44:55:66', $extra['mosyle_bluetooth_mac']);
+ $this->assertSame('77:88:99:aa:bb:cc', $extra['mosyle_ethernet_mac']);
+ $this->assertSame('Mac', $extra['mosyle_device_type']);
+ $this->assertSame('23B74', $extra['mosyle_build_version']);
+ // Cellular
+ $this->assertSame('Verizon', $extra['mosyle_carrier']);
+ $this->assertSame('990000862471854', $extra['mosyle_imei']);
+ // Security / posture
+ $this->assertTrue($extra['mosyle_activation_lock_enabled']);
+ $this->assertFalse($extra['mosyle_cloud_backup_enabled']);
+ $this->assertSame('2026-01-10T04:00:00Z', $extra['mosyle_last_cloud_backup_date']);
+ $this->assertSame('VERIFIED', $extra['mosyle_device_attestation_status']);
+ // MDM / lifecycle
+ $this->assertSame('ADE', $extra['mosyle_enrollment_type']);
+ $this->assertSame('Managed', $extra['mosyle_management_status']);
+ $this->assertSame('u-42', $extra['mosyle_user_id']);
+ $this->assertTrue($extra['mosyle_supervised']);
+ // User / scoping
+ $this->assertSame('faculty', $extra['mosyle_user_type']);
+ $this->assertSame('HQ', $extra['mosyle_location']);
+ $this->assertSame(['loaner', 'ipad-cart-3'], $extra['mosyle_tags']);
+ // Network
+ $this->assertSame('office-wifi-5g', $extra['mosyle_last_ssid']);
+ // Lost mode
+ $this->assertSame('inactive', $extra['mosyle_lost_mode_status']);
+ $this->assertSame('37.7749', $extra['mosyle_latitude']);
+ $this->assertSame('-122.4194', $extra['mosyle_longitude']);
+ }
+
+ public function test_normalized_record_uses_manager_v2_field_names(): void
+ {
+ // Issue #19790: the original adapter had wrong field names
+ // (`usename` instead of `username`, `ip_address` not in the
+ // Mosyle response at all, `locationid` instead of `location`).
+ // This locks in the Manager v2 names from the API doc.
+ $adapter = $this->configuredMosyleAdapter();
+
+ Http::fake([
+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),
+ '*/listdevices' => Http::sequence()
+ ->push($this->devicesResponse([
+ $this->mosyleDevice(
+ udid: 'ccc-333',
+ name: 'staff-mbp',
+ model: 'MacBook Pro',
+ serial: 'C02XYZ',
+ os: 'macOS',
+ osversion: '14.2.1',
+ wifi_mac: 'aa:bb:cc:11:22:33',
+ last_lan_ip: '10.0.1.47',
+ username: 'jdoe',
+ useremail: '[email protected]',
+ date_info: '2026-01-15T10:00:00.000Z',
+ ),
+ ]))
+ ->push($this->devicesResponse([]))
+ ->push($this->devicesResponse([]))
+ ->push($this->devicesResponse([]))
+ ->push($this->devicesResponse([])),
]);
$records = iterator_to_array($adapter->pull());
@@ -112,16 +271,51 @@ class MosyleAdapterTest extends TestCase
$this->assertSame('C02XYZ', $record->hardwareSerial);
$this->assertSame('Apple', $record->manufacturer);
$this->assertSame('aa:bb:cc:11:22:33', $record->primaryMac);
+ $this->assertSame('10.0.1.47', $record->primaryIp);
$this->assertSame('macOS', $record->os);
$this->assertSame('14.2.1', $record->osVersion);
+ $this->assertSame('jdoe', $record->assignedUserName);
+ $this->assertSame('[email protected]', $record->assignedUserEmail);
$this->assertNotNull($record->lastSeen);
}
+ public function test_login_missing_authorization_header_throws(): void
+ {
+ $adapter = $this->configuredMosyleAdapter();
+
+ Http::fake([
+ '*/login' => Http::response(['status' => 'OK'], 200),
+ '*/listdevices' => Http::response($this->devicesResponse([])),
+ ]);
+
+ $this->expectExceptionMessage('Mosyle /login did not return a Bearer token');
+
+ iterator_to_array($adapter->pull());
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ private function devicesResponse(array $devices): array
+ {
+ return [
+ 'status' => 'OK',
+ 'response' => [
+ 'devices' => $devices,
+ 'rows' => (string) count($devices),
+ 'page_size' => 200,
+ 'page' => 1,
+ ],
+ ];
+ }
+
private function configuredMosyleAdapter(): MosyleAdapter
{
$instance = SyncAdapterInstance::where('slug', 'mosyle')->firstOrFail();
SyncAdapterConfig::put($instance->id, 'url', 'https://managerapi.mosyle.com/v2');
- SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-mosyle-token'));
+ 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 MosyleAdapter($instance->fresh());
}
@@ -137,6 +331,9 @@ class MosyleAdapterTest extends TestCase
?string $os = 'iOS',
?string $osversion = null,
?string $wifi_mac = null,
+ ?string $last_lan_ip = null,
+ ?string $username = null,
+ ?string $useremail = null,
?string $date_info = null,
): array {
return [
@@ -147,6 +344,9 @@ class MosyleAdapterTest extends TestCase
'os' => $os,
'osversion' => $osversion,
'wifi_mac_address' => $wifi_mac,
+ 'last_lan_ip' => $last_lan_ip,
+ 'username' => $username,
+ 'useremail' => $useremail,
'date_info' => $date_info,
'is_supervised' => true,
];
diff --git a/tests/Feature/SyncAdapters/Mosyle/MosylePushTest.php b/tests/Feature/SyncAdapters/Mosyle/MosylePushTest.php
index 3561bdc4db..47cf1538d7 100644
--- a/tests/Feature/SyncAdapters/Mosyle/MosylePushTest.php
+++ b/tests/Feature/SyncAdapters/Mosyle/MosylePushTest.php
@@ -14,10 +14,10 @@ use Illuminate\Support\Facades\Http;
use Tests\TestCase;
/**
- * End-to-end coverage for the Mosyle push path. Mosyle's write API
- * is a single POST endpoint dispatched by an `operation` field, so
- * tests verify the payload carries the right operation + serial +
- * value.
+ * End-to-end coverage for the Mosyle push path. Mosyle Manager v2's
+ * write API is POST /devices with an `elements` array keyed by
+ * `serialnumber`, carrying accessToken in the body and the JWT bearer
+ * in the Authorization header. Issue #19790.
*/
class MosylePushTest extends TestCase
{
@@ -27,12 +27,12 @@ class MosylePushTest extends TestCase
Statuslabel::factory()->rtd()->create();
}
- public function test_mosyle_adapter_implements_pushable_interface()
+ public function test_mosyle_adapter_implements_pushable_interface(): void
{
$this->assertInstanceOf(PushableAdapter::class, $this->configuredMosyle());
}
- public function test_push_asset_tag_sends_operation_scoped_by_serial()
+ public function test_push_asset_tag_sends_elements_array_keyed_by_serial(): void
{
$adapter = $this->configuredMosyle();
$instance = SyncAdapterInstance::where('slug', 'mosyle')->firstOrFail();
@@ -49,29 +49,30 @@ class MosylePushTest extends TestCase
]);
Http::fake([
- '*/devices' => Http::response(['status' => 'ok']),
+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),
+ '*/devices' => Http::response(['status' => 'OK']),
]);
- $adapter->push($asset);
+ $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) === 'set_asset_tag_by_serial_number'
- && ($body['serial_number'] ?? null) === 'MOS-SN-777'
- && ($body['asset_tag'] ?? null) === 'SNIPE-MOS-77';
+ return ($body['accessToken'] ?? null) === 'fake-access-token'
+ && ($body['elements'][0]['serialnumber'] ?? null) === 'MOS-SN-777'
+ && ($body['elements'][0]['asset_tag'] ?? null) === 'SNIPE-MOS-77'
+ && ($request->header('Authorization')[0] ?? null) === 'Bearer fake-jwt';
});
}
- public function test_push_falls_back_to_external_id_when_serial_missing()
+ public function test_push_falls_back_to_external_id_when_serial_missing(): void
{
- // Mosyle Business uses the device serial as external_id for
- // some device types, so pushes still work for assets that
- // never populated the serial column but do have an
- // asset_external_sources row.
$adapter = $this->configuredMosyle();
$instance = SyncAdapterInstance::where('slug', 'mosyle')->firstOrFail();
SyncAdapterConfig::put($instance->id, 'direction.asset_tag', 'push');
@@ -87,21 +88,48 @@ class MosylePushTest extends TestCase
]);
Http::fake([
- '*/devices' => Http::response(['status' => 'ok']),
+ '*/login' => Http::response(null, 200, ['Authorization' => 'Bearer fake-jwt']),
+ '*/devices' => Http::response(['status' => 'OK']),
]);
- $adapter->push($asset);
+ $this->assertTrue($adapter->push($asset));
Http::assertSent(function ($request) {
- return ($request->data()['serial_number'] ?? null) === 'MOS-SN-888';
+ if (! str_ends_with($request->url(), '/devices')) {
+ return true;
+ }
+
+ return ($request->data()['elements'][0]['serialnumber'] ?? null) === 'MOS-SN-888';
});
}
+ public function test_notes_field_target_is_null_because_manager_v2_push_has_no_notes(): void
+ {
+ // Mosyle Manager v2's push payload exposes asset_tag,
+ // device_name, lock-screen message, and custom tags. There is
+ // no notes field, so the composed-notes framework must skip
+ // Mosyle. Regression test for the pre-fix adapter claiming to
+ // support notes push via a non-existent operation.
+ $this->assertNull($this->configuredMosyle()->notesFieldTarget());
+ }
+
+ public function test_mosyle_opts_out_of_composed_notes_push_ui(): void
+ {
+ // Manager v2 has no field that admin-composed notes could land
+ // in, so the settings-page UI section is hidden. notesFieldTarget
+ // returning null is not enough on its own because other adapters
+ // (Workspace ONE, NinjaOne) legitimately return null and still
+ // expect the UI to appear so the admin can pick a target.
+ $this->assertFalse($this->configuredMosyle()->supportsComposedNotesPush());
+ }
+
private function configuredMosyle(): MosyleAdapter
{
$instance = SyncAdapterInstance::where('slug', 'mosyle')->firstOrFail();
SyncAdapterConfig::put($instance->id, 'url', 'https://example.com/mosyle');
- SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-mosyle-token'));
+ 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 MosyleAdapter($instance->fresh());
}
diff --git a/tests/Feature/SyncAdapters/NewBuiltInAdaptersRenderTest.php b/tests/Feature/SyncAdapters/NewBuiltInAdaptersRenderTest.php
index 7eb506e614..ca290d1ff2 100644
--- a/tests/Feature/SyncAdapters/NewBuiltInAdaptersRenderTest.php
+++ b/tests/Feature/SyncAdapters/NewBuiltInAdaptersRenderTest.php
@@ -25,8 +25,11 @@ class NewBuiltInAdaptersRenderTest extends TestCase
->getContent();
$this->assertStringContainsString('Mosyle', $html);
- // Schema field label from MosyleAdapter::settingsSchema()
- $this->assertMatchesRegularExpression('/name="mosyle_token"/', $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);
+ $this->assertMatchesRegularExpression('/name="mosyle_email"/', $html);
+ $this->assertMatchesRegularExpression('/name="mosyle_password"/', $html);
}
public function test_meraki_systems_manager_renders_with_both_schema_fields()