A free open source IT asset/license management system
Sync Adapters: Fxed #19909 - added Zoho’s ManageEngine Endpoint Central
sniped4d451317caa
diff --git a/app/SyncAdapters/EndpointCentral/EndpointCentralAdapter.php b/app/SyncAdapters/EndpointCentral/EndpointCentralAdapter.phpnew file mode 100644index 0000000000..69e2240565--- /dev/null+++ b/app/SyncAdapters/EndpointCentral/EndpointCentralAdapter.php@@ -0,0 +1,482 @@+<?php++namespace App\SyncAdapters\EndpointCentral;++use App\Models\Asset;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableSyncAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * ManageEngine Endpoint Central adapter. Pulls managed-computer+ * inventory from a cloud OR on-prem Endpoint Central tenant and+ * normalizes it into HostInventoryRecord objects. Also pushes+ * Snipe-IT's asset_tag back to the vendor as the device's "Remarks"+ * freeform field (the writable free-text slot ME exposes per+ * computer).+ *+ * Deployment variants:+ *+ * Cloud: hosted on Zoho's infrastructure, OAuth 2.0 refresh-token+ * flow against accounts.zoho.{region}. Admin generates a refresh+ * token at api-console.zoho.com with scopes DesktopCentralCloud.SOM+ * (plus .Inventory for the hardware opt-in and .SOM.CREATE for+ * push) and pastes the client ID + secret + refresh token into+ * Snipe-IT. The data_center setting selects the right regional+ * accounts host.+ *+ * On-prem: admin issues an API Key / AuthToken from Admin ->+ * Integrations in the on-prem console and pastes it in. Snipe-IT+ * sends it as a Zoho-authtoken header per ME's historical scheme.+ * FIXME: unverified against a modern on-prem tenant.+ *+ * Serial resolution: the list endpoint omits hardware serial. An+ * opt-in setting enables a per-device detail fetch at pull time+ * so adopt_by_serial works. Costs an extra API call per device per+ * sync when the opt-in is on.+ *+ * ME API docs: https://www.manageengine.com/products/desktop-central/help/api/cloud/api-index.html+ */+class EndpointCentralAdapter extends PushableSyncAdapter+{+ private const DATA_CENTERS = [+ 'us' => 'US (accounts.zoho.com)',+ 'eu' => 'EU (accounts.zoho.eu)',+ 'in' => 'India (accounts.zoho.in)',+ 'au' => 'Australia (accounts.zoho.com.au)',+ 'cn' => 'China (accounts.zoho.com.cn)',+ 'jp' => 'Japan (accounts.zoho.jp)',+ ];++ public static function typeLabel(): string+ {+ return 'ManageEngine Endpoint Central';+ }++ public static function typeSlug(): string+ {+ return 'endpoint_central';+ }++ public static function docsUrl(): ?string+ {+ return 'https://www.manageengine.com/products/desktop-central/help/api/cloud/api-index.html';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://desktopcentralcloud.manageengine.com';+ }++ public function settingsSchema(): array+ {+ return [+ [+ 'key' => 'mode',+ 'label' => trans('admin/settings/sync_adapters.endpoint_central_label_mode'),+ 'type' => 'select',+ 'options' => [+ EndpointCentralClient::MODE_CLOUD => trans('admin/settings/sync_adapters.endpoint_central_option_mode_cloud'),+ EndpointCentralClient::MODE_ONPREM => trans('admin/settings/sync_adapters.endpoint_central_option_mode_onprem'),+ ],+ 'default' => EndpointCentralClient::MODE_CLOUD,+ 'help' => trans('admin/settings/sync_adapters.endpoint_central_mode_help'),+ ],+ // Cloud-only credentials.+ [+ 'key' => 'data_center',+ 'label' => trans('admin/settings/sync_adapters.endpoint_central_label_data_center'),+ 'type' => 'select',+ 'options' => self::DATA_CENTERS,+ 'default' => 'us',+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.endpoint_central_data_center_help'),+ ],+ [+ 'key' => 'client_id',+ 'label' => trans('admin/settings/sync_adapters.label_client_id'),+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.endpoint_central_client_id_help'),+ ],+ [+ 'key' => 'client_secret',+ 'label' => trans('admin/settings/sync_adapters.label_client_secret'),+ 'secret' => true,+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.endpoint_central_client_secret_help'),+ ],+ [+ 'key' => 'refresh_token',+ 'label' => trans('admin/settings/sync_adapters.endpoint_central_label_refresh_token'),+ 'secret' => true,+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.endpoint_central_refresh_token_help'),+ ],+ // On-prem-only credential.+ [+ 'key' => 'auth_token',+ 'label' => trans('admin/settings/sync_adapters.endpoint_central_label_auth_token'),+ 'secret' => true,+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.endpoint_central_auth_token_help'),+ ],+ // Opt-in N+1 hardware fetch for serial resolution.+ [+ 'key' => 'fetch_hardware_details',+ 'label' => trans('admin/settings/sync_adapters.endpoint_central_label_fetch_hardware_details'),+ 'type' => 'checkbox',+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.endpoint_central_fetch_hardware_details_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'endpoint_central_resource_id' => ['label_key' => 'admin/settings/sync_adapters.endpoint_central_extra_resource_id'],+ 'endpoint_central_live_status' => ['label_key' => 'admin/settings/sync_adapters.endpoint_central_extra_live_status'],+ 'endpoint_central_agent_version' => ['label_key' => 'admin/settings/sync_adapters.extra_agent_version'],+ 'endpoint_central_domain' => ['label_key' => 'admin/settings/sync_adapters.endpoint_central_extra_domain'],+ 'endpoint_central_remote_office' => ['label_key' => 'admin/settings/sync_adapters.endpoint_central_extra_remote_office'],+ ];+ }++ public function supportsGroupScoping(): bool+ {+ // Remote Office is ME's per-site tenancy construct. Admins can+ // route devices to Snipe-IT companies via the group mapping UI+ // once we expose the Remote Office id as the vendor group id.+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return trans('admin/settings/sync_adapters.endpoint_central_vendor_group_remote_office');+ }++ public function fetchGroups(): array+ {+ // FIXME: ME has a Remote Offices endpoint+ // (/dcapi/som/remoteOffices) that would populate this. Returning+ // an empty list for v1 so the group-mapping UI is visible but+ // callers cannot pick a vendor group until this is wired up+ // against a tenant.+ return [];+ }++ public function pull(): iterable+ {+ $client = $this->buildClient();+ $fetchHardware = $this->credentialBool('fetch_hardware_details');++ foreach ($client->computers() as $computer) {+ $hardwareDetails = null;+ if ($fetchHardware) {+ $resourceId = (string) ($computer['computerId'] ?? '');+ if ($resourceId !== '') {+ $hardwareDetails = $client->hardwareDetails($resourceId);+ }+ }++ yield $this->normalize($computer, $hardwareDetails);+ }+ }++ private function buildClient(): EndpointCentralClient+ {+ $mode = $this->credentialOrDefault('mode', EndpointCentralClient::MODE_CLOUD);+ $dataCenter = $this->credentialOrDefault('data_center', 'us');+ $accountsHost = EndpointCentralClient::ZOHO_ACCOUNTS_HOSTS[$dataCenter]+ ?? EndpointCentralClient::ZOHO_ACCOUNTS_HOSTS['us'];++ return new EndpointCentralClient(+ mode: $mode,+ baseUrl: $this->url(),+ clientId: $this->credentialOrNull('client_id'),+ clientSecret: $this->credentialOrNull('client_secret'),+ refreshToken: $this->credentialOrNull('refresh_token'),+ accountsHost: $accountsHost,+ authToken: $this->credentialOrNull('auth_token'),+ );+ }++ /**+ * Convert one computer payload into the normalized record shape.+ * The computerId from the list endpoint is stable per enrolled+ * device and is what we key asset_external_sources on. When the+ * hardware opt-in is on, pull the serial out of+ * biosDetails[0].serialNumber (the common location per the ME+ * hardware response).+ *+ * @param array<string, mixed> $computer+ * @param array<string, mixed>|null $hardwareDetails+ */+ private function normalize(array $computer, ?array $hardwareDetails): HostInventoryRecord+ {+ // ME's list endpoint has no hardware model string. When the+ // opt-in hardware fetch is off, fall back to the osName so+ // admins get a reasonable grouping (per Windows release, per+ // macOS version, etc.) rather than a null that would reject+ // the AssetModel save. Admins who turn on fetch_hardware_details+ // get the actual motherboard model name.+ $hardwareModel = self::extractHardwareModel($hardwareDetails)+ ?? Arr::get($computer, 'osName')+ ?? Arr::get($computer, 'osPlatform');++ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($computer, 'computerId'),+ hostname: Arr::get($computer, 'computerName'),+ hardwareSerial: self::extractSerialNumber($hardwareDetails),+ hardwareModel: $hardwareModel,+ manufacturer: self::extractManufacturer($hardwareDetails),+ primaryMac: self::firstMacAddress(Arr::get($computer, 'macAddress')),+ primaryIp: Arr::get($computer, 'ipAddress'),+ os: Arr::get($computer, 'osPlatform') ?? Arr::get($computer, 'osName'),+ osVersion: Arr::get($computer, 'osVersion'),+ lastSeen: $this->parseTimestamp(Arr::get($computer, 'lastContactTime')),+ assignedUserName: self::firstLoggedUser(Arr::get($computer, 'loggedUsers')),+ vendorGroupId: Arr::has($computer, 'remoteOfficeID') ? (string) Arr::get($computer, 'remoteOfficeID') : null,+ extra: [+ 'endpoint_central_resource_id' => (string) Arr::get($computer, 'computerId'),+ 'endpoint_central_live_status' => Arr::get($computer, 'liveStatus'),+ 'endpoint_central_agent_version' => Arr::get($computer, 'agentVersion'),+ 'endpoint_central_domain' => Arr::get($computer, 'domainName'),+ 'endpoint_central_remote_office' => Arr::get($computer, 'remoteOfficeName'),+ ],+ );+ }++ /**+ * ME's hardware endpoint groups BIOS entries under biosDetails as+ * an array. The device serial lives on the first (typically only)+ * entry. motherBoardDetails[0].serialNumber is the fallback when+ * biosDetails is absent, which happens on some device classes.+ *+ * @param array<string, mixed>|null $hardwareDetails+ */+ private static function extractSerialNumber(?array $hardwareDetails): ?string+ {+ if ($hardwareDetails === null) {+ return null;+ }++ $candidates = [+ Arr::get($hardwareDetails, 'biosDetails.0.serialNumber'),+ Arr::get($hardwareDetails, 'motherBoardDetails.0.serialNumber'),+ ];++ foreach ($candidates as $value) {+ if (is_string($value) && $value !== '') {+ return $value;+ }+ }++ return null;+ }++ /**+ * Hardware model string from the motherboard or system group.+ *+ * @param array<string, mixed>|null $hardwareDetails+ */+ private static function extractHardwareModel(?array $hardwareDetails): ?string+ {+ if ($hardwareDetails === null) {+ return null;+ }++ $candidates = [+ Arr::get($hardwareDetails, 'motherBoardDetails.0.hardwareName'),+ Arr::get($hardwareDetails, 'motherBoardDetails.0.hardwareDescription'),+ ];++ foreach ($candidates as $value) {+ if (is_string($value) && $value !== '') {+ return $value;+ }+ }++ return null;+ }++ /**+ * Manufacturer string from the motherboard or BIOS group.+ *+ * @param array<string, mixed>|null $hardwareDetails+ */+ private static function extractManufacturer(?array $hardwareDetails): ?string+ {+ if ($hardwareDetails === null) {+ return null;+ }++ $candidates = [+ Arr::get($hardwareDetails, 'motherBoardDetails.0.hardwareManufacturer'),+ Arr::get($hardwareDetails, 'biosDetails.0.hardwareManufacturer'),+ ];++ foreach ($candidates as $value) {+ if (is_string($value) && $value !== '') {+ return $value;+ }+ }++ return null;+ }++ /**+ * ME returns macAddress as a comma-separated list when a device+ * has multiple interfaces. Grab the first non-empty entry for+ * the normalized primaryMac slot. The rest live on the raw+ * payload and admins can map them to custom fields separately.+ */+ private static function firstMacAddress(mixed $raw): ?string+ {+ if (! is_string($raw) || $raw === '') {+ return null;+ }++ foreach (explode(',', $raw) as $candidate) {+ $candidate = trim($candidate);+ if ($candidate !== '') {+ return $candidate;+ }+ }++ return null;+ }++ /**+ * loggedUsers is a comma-separated list of recent logged-in+ * accounts, newest first per ME's convention. We take the first+ * for the normalized assignedUserName slot and let admins map+ * the raw string to a custom field if they want the full list.+ */+ private static function firstLoggedUser(mixed $raw): ?string+ {+ if (! is_string($raw) || $raw === '') {+ return null;+ }++ foreach (explode(',', $raw) as $candidate) {+ $candidate = trim($candidate);+ if ($candidate !== '') {+ return $candidate;+ }+ }++ return null;+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ try {+ // ME emits timestamps as both ISO 8601 strings and Unix epoch+ // milliseconds depending on endpoint version. Numeric input+ // in the plausible ms range is treated as epoch milliseconds.+ if (is_numeric($value) && $value >= 1_000_000_000_000 && $value <= 100_000_000_000_000) {+ return Carbon::createFromTimestampMsUTC((int) $value);+ }++ return Carbon::parse($value);+ } catch (\Throwable $e) {+ Log::channel('sync-adapters')->warning(+ $this->name().': skipped unparseable Endpoint Central timestamp ('.var_export($value, true).'): '.$e->getMessage()+ );++ return null;+ }+ }++ private function credentialOrNull(string $key): ?string+ {+ try {+ $value = $this->credential($key);+ } catch (\Throwable) {+ return null;+ }++ return $value === '' ? null : $value;+ }++ private function credentialOrDefault(string $key, string $default): string+ {+ $value = $this->credentialOrNull($key);++ return $value ?? $default;+ }++ private function credentialBool(string $key): bool+ {+ return $this->credentialOrNull($key) === '1';+ }++ /**+ * ME exposes Remarks as the writable per-computer freeform slot+ * admins commonly use for inventory tags. canPush is always true+ * for a configured instance since the write capability is tied to+ * the OAuth scope / API token (gated at auth time rather than+ * per-request).+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * ME's "Remarks" freeform field is a plausible notes target but+ * we already route asset_tag there (the writable per-computer+ * slot). Keeping notes unmapped for v1 so admins can configure+ * push-asset_tag without accidentally overwriting Remarks via+ * two paths. Revisit once ME exposes a separate notes field.+ */+ public function notesFieldTarget(): ?string+ {+ return null;+ }++ /**+ * Snipe-IT asset_tag flows to ME's Remarks freeform field.+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): bool+ {+ return $this->pushViaSinglePayload($asset, $changedFields);+ }++ /**+ * @return array{0: array<string, mixed>, 1: array<int, string>}+ */+ protected function buildPushPayload(Asset $asset): array+ {+ $payload = [];+ $pushed = [];++ if (in_array('asset_tag', $this->pushDirectedFields(), true)) {+ $value = $this->assetValueForSourceField($asset, 'asset_tag');+ if (is_string($value) && $value !== '') {+ $payload['remarks'] = $value;+ $pushed[] = 'asset_tag';+ }+ }++ return [$payload, $pushed];+ }++ /**+ * @param array<string, mixed> $payload+ */+ protected function dispatchPush(\App\Models\AssetExternalSource $externalSource, array $payload): void+ {+ $this->buildClient()->updateRemarks($externalSource->external_id, $payload);+ }+}diff --git a/app/SyncAdapters/EndpointCentral/EndpointCentralClient.php b/app/SyncAdapters/EndpointCentral/EndpointCentralClient.phpnew file mode 100644index 0000000000..9b95587000--- /dev/null+++ b/app/SyncAdapters/EndpointCentral/EndpointCentralClient.php@@ -0,0 +1,239 @@+<?php++namespace App\SyncAdapters\EndpointCentral;++use App\SyncAdapters\Traits\RetriesTransientHttpErrors;+use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the ManageEngine Endpoint Central API. Owns auth+ * + pagination for the endpoints the sync adapter uses. Yields raw+ * decoded JSON, no normalization (that's the adapter's job).+ *+ * ME Endpoint Central ships in two flavors with different auth models:+ *+ * Cloud (hosted on Zoho's infrastructure): OAuth 2.0 refresh-token+ * flow. The admin generates a refresh token out-of-band via Zoho's+ * self-client flow at api-console.zoho.com with scope+ * DesktopCentralCloud.SOM.READ (plus .Inventory.READ for the+ * hardware opt-in, and .SOM.CREATE for push). We exchange the+ * long-lived refresh_token for a 1-hour access_token on first use+ * and cache it on this instance. Cloud uses multiple regional+ * accounts hosts (US / EU / IN / AU / CN / JP) that admins pick on+ * the settings page.+ *+ * On-prem (self-hosted): the admin generates an API Key /+ * AuthToken in the Admin -> Integrations area of the on-prem+ * console and pastes it into Snipe-IT. We send it as a+ * `Authorization: Zoho-authtoken {token}` header, which is the+ * historical ME header shape still used by current on-prem+ * releases per the vendor docs. FIXME: this needs confirmation+ * against a modern on-prem tenant since the ME docs on the auth+ * shape have some gaps in public cloud docs. Admins seeing 401 should+ * file an issue so we can switch to Bearer / Basic as needed.+ *+ * ME API reference: https://www.manageengine.com/products/desktop-central/help/api/cloud/api-index.html+ */+class EndpointCentralClient+{+ use RetriesTransientHttpErrors;++ public const MODE_CLOUD = 'cloud';++ public const MODE_ONPREM = 'onprem';++ /**+ * Zoho's regional accounts hosts for the OAuth token endpoint.+ * The data_center setting on the adapter maps to one of these.+ * Keeping the map here keeps the adapter's settings schema free+ * of the specific URLs and avoids drift if Zoho adds a region.+ *+ * @var array<string, string>+ */+ public const ZOHO_ACCOUNTS_HOSTS = [+ 'us' => 'https://accounts.zoho.com',+ 'eu' => 'https://accounts.zoho.eu',+ 'in' => 'https://accounts.zoho.in',+ 'au' => 'https://accounts.zoho.com.au',+ 'cn' => 'https://accounts.zoho.com.cn',+ 'jp' => 'https://accounts.zoho.jp',+ ];++ private ?string $accessToken = null;++ private ?int $expiresAt = null;++ public function __construct(+ private readonly string $mode,+ private readonly string $baseUrl,+ // Cloud mode: client credentials from Zoho self-client + refresh token.+ private readonly ?string $clientId = null,+ private readonly ?string $clientSecret = null,+ private readonly ?string $refreshToken = null,+ // Cloud mode: Zoho regional accounts host. Keyed by MODE_CLOUD + a data_center selector in the adapter settings.+ private readonly ?string $accountsHost = null,+ // On-prem mode: API Key / AuthToken from Admin -> Integrations in the on-prem console.+ private readonly ?string $authToken = null,+ ) {+ }++ /**+ * Iterate every managed computer on the tenant, one page at a+ * time. Returns a generator so callers stream through large+ * fleets without holding the whole list in memory.+ *+ * The list endpoint returns computerId / computerName /+ * computerFQDNName / ipAddress / macAddress / osName /+ * osVersion / osPlatform / lastContactTime / loggedUsers /+ * agentVersion / domainName / remoteOfficeName per device. It+ * does NOT return hardware serial. Serial resolution lives on+ * the per-device hardwareDetails() endpoint and is opt-in on+ * the adapter.+ *+ * @return iterable<array<string, mixed>>+ */+ public function computers(int $pageSize = 100): iterable+ {+ $page = 1;++ do {+ $response = $this->request()+ ->get('/dcapi/som/computersInfo', [+ 'page' => $page,+ 'pageLimit' => $pageSize,+ ])+ ->throw()+ ->json();++ // ME wraps list responses in {message_response: {computers: [...]}, message_type, status, message_version}. The exact wrapper key varies between the /dcapi/* paths and the legacy /api/1.4/* paths. Walk the common locations and bail cleanly on unexpected shapes.+ $results = $response['message_response']['computers']+ ?? $response['computers']+ ?? (is_array($response) ? $response : []);++ if (!is_array($results)) {+ $results = [];+ }++ foreach ($results as $computer) {+ yield $computer;+ }++ // ME paginates by page number and returns a short page on+ // the final response. No totalCount in the common response+ // shape, so a short page is the terminal signal.+ $done = count($results) < $pageSize;+ $page++;+ } while (!$done);+ }++ /**+ * Fetch the rich hardware details for one device. Only called+ * when the admin has enabled the hardware opt-in on the adapter.+ * The serial number lives under biosDetails.serialNumber on+ * most device classes.+ *+ * Returns null on any failure so one bad device does not abort+ * the entire pull.+ *+ * @return array<string, mixed>|null+ */+ public function hardwareDetails(string $resourceId): ?array+ {+ try {+ $response = $this->request()+ ->get('/dcapi/inventory/computers/' . rawurlencode($resourceId) . '/hardware')+ ->throwIfServerError()+ ->json();+ } catch (\Throwable) {+ return null;+ }++ if (!is_array($response)) {+ return null;+ }++ return $response['message_response'] ?? $response;+ }++ /**+ * Push an asset_tag update to one device. ME exposes a "Remarks"+ * freeform field on each computer that admins use for ad-hoc+ * tagging. The push surface maps Snipe-IT's asset_tag onto that+ * remarks field via POST /dcapi/som/computers/updateRemarks.+ *+ * FIXME: unverified against a live tenant. The remarks endpoint+ * is documented in the Cloud API index but the request body+ * shape is based on the ME convention of wrapping writes in+ * message_type/message_response envelopes. Expect to adjust if+ * admins hit 400/404 on first use.+ *+ * @param array<string, mixed> $payload+ */+ public function updateRemarks(string $resourceId, array $payload): void+ {+ $this->request()+ ->post('/dcapi/som/computers/updateRemarks', array_merge(+ ['resourceIds' => [$resourceId]],+ $payload,+ ))+ ->throw();+ }++ private function request(): PendingRequest+ {+ $request = Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withOptions(['allow_redirects' => false])+ ->acceptJson()+ ->timeout(30);++ if ($this->mode === self::MODE_CLOUD) {+ $request = $request->withHeaders([+ 'Authorization' => 'Zoho-oauthtoken ' . $this->bearer(),+ ]);+ } else {+ // On-prem AuthToken header per ME's historical scheme.+ // FIXME: confirm against a modern on-prem tenant.+ $request = $request->withHeaders([+ 'Authorization' => 'Zoho-authtoken ' . $this->authToken,+ ]);+ }++ return $this->withTransientRetry($request);+ }++ /**+ * Exchange the long-lived Zoho refresh token for a 1-hour access+ * token via accounts.zoho.{region}/oauth/v2/token. Cached on this+ * instance with a 60-second buffer before expiry so a slow sync+ * does not present a token that is about to be rejected.+ *+ * Response shape (per Zoho docs):+ * {access_token, scope, api_domain, token_type, expires_in}+ */+ private function bearer(): string+ {+ $now = time();+ if ($this->accessToken !== null && $this->expiresAt !== null && $now < $this->expiresAt - 60) {+ return $this->accessToken;+ }++ $response = Http::asForm()+ ->withOptions(['allow_redirects' => false])+ ->timeout(30)+ ->post(rtrim((string) $this->accountsHost, '/') . '/oauth/v2/token', [+ 'grant_type' => 'refresh_token',+ 'refresh_token' => $this->refreshToken,+ 'client_id' => $this->clientId,+ 'client_secret' => $this->clientSecret,+ ])+ ->throw()+ ->json();++ $this->accessToken = (string) ($response['access_token'] ?? '');+ $expiresIn = (int) ($response['expires_in'] ?? 0);+ $this->expiresAt = $expiresIn > 0 ? $now + $expiresIn : null;++ return $this->accessToken;+ }+}diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 541926d733..0233f3be0f 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -575,4 +575,25 @@ return ['abm_extra_mdm_device_erase_status' => 'AxM MDM Device Erase Status','abm_extra_mdm_storage_total' => 'AxM MDM Storage Total','abm_extra_mdm_storage_free' => 'AxM MDM Storage Free',++ // ManageEngine Endpoint Central adapter.+ 'endpoint_central_label_mode' => 'Deployment',+ 'endpoint_central_mode_help' => 'Cloud: hosted on Zoho infrastructure (desktopcentralcloud.manageengine.com). On-prem: self-hosted ManageEngine Endpoint Central (your own URL).',+ 'endpoint_central_option_mode_cloud' => 'Cloud',+ 'endpoint_central_option_mode_onprem' => 'On-prem',+ 'endpoint_central_label_data_center' => 'Zoho Data Center',+ 'endpoint_central_data_center_help' => 'Cloud tenants only. Picks the regional Zoho accounts host used for the OAuth token exchange. Must match the data center of the Zoho developer console where you generated the refresh token.',+ 'endpoint_central_client_id_help' => 'Cloud tenants only. Client ID from the Zoho Self Client at api-console.zoho.com.',+ 'endpoint_central_client_secret_help' => 'Cloud tenants only. Client Secret from the Zoho Self Client at api-console.zoho.com.',+ 'endpoint_central_label_refresh_token' => 'Refresh Token',+ 'endpoint_central_refresh_token_help' => 'Cloud tenants only. Long-lived refresh token generated via the Zoho Self Client with scope DesktopCentralCloud.SOM.READ (plus .Inventory.READ for hardware details and .SOM.CREATE for push). Snipe-IT exchanges it for a 1-hour access token on each sync.',+ 'endpoint_central_label_auth_token' => 'Authentication Token',+ 'endpoint_central_auth_token_help' => 'On-prem tenants only. API Key / AuthToken from Admin -> Integrations in your Endpoint Central console. Snipe-IT sends it as a Zoho-authtoken header.',+ 'endpoint_central_label_fetch_hardware_details' => 'Fetch hardware details',+ 'endpoint_central_fetch_hardware_details_help' => 'Resolves the hardware serial number via a per-device call to /dcapi/inventory/computers/{id}/hardware. Required for adopt-by-serial to work with Endpoint Central. Adds one API call per device per sync run.',+ 'endpoint_central_extra_resource_id' => 'ME Resource ID',+ 'endpoint_central_extra_live_status' => 'ME Live Status',+ 'endpoint_central_extra_domain' => 'ME Domain',+ 'endpoint_central_extra_remote_office' => 'ME Remote Office',+ 'endpoint_central_vendor_group_remote_office' => 'Remote Office',];diff --git a/tests/Feature/SyncAdapters/EndpointCentral/EndpointCentralAdapterTest.php b/tests/Feature/SyncAdapters/EndpointCentral/EndpointCentralAdapterTest.phpnew file mode 100644index 0000000000..0f632a288e--- /dev/null+++ b/tests/Feature/SyncAdapters/EndpointCentral/EndpointCentralAdapterTest.php@@ -0,0 +1,276 @@+<?php++namespace Tests\Feature\SyncAdapters\EndpointCentral;++use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\EndpointCentral\EndpointCentralAdapter;+use App\SyncAdapters\EndpointCentral\EndpointCentralClient;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++class EndpointCentralAdapterTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ }++ public function test_cloud_mode_exchanges_refresh_token_and_pulls_computers()+ {+ $adapter = $this->configuredCloudAdapter();++ Http::fake([+ 'accounts.zoho.com/oauth/v2/token' => Http::response([+ 'access_token' => 'fake-access-token',+ 'token_type' => 'Bearer',+ 'expires_in' => 3600,+ ]),+ '*/dcapi/som/computersInfo*' => Http::response($this->computersListResponse([+ $this->computer(id: 'ec-1', name: 'win-01', ip: '10.0.0.10'),+ $this->computer(id: 'ec-2', name: 'win-02', ip: '10.0.0.11'),+ ])),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 2);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'endpoint_central', 'external_id' => 'ec-1']);+ $this->assertDatabaseHas('assets', ['name' => 'win-01']);+ }++ public function test_access_token_is_cached_across_requests_within_a_pull()+ {+ $adapter = $this->configuredCloudAdapter();++ Http::fake([+ 'accounts.zoho.com/oauth/v2/token' => Http::response([+ 'access_token' => 'fake-access-token',+ 'expires_in' => 3600,+ ]),+ '*/dcapi/som/computersInfo*' => Http::response($this->computersListResponse([+ $this->computer(id: 'ec-1', name: 'host1'),+ $this->computer(id: 'ec-2', name: 'host2'),+ ])),+ ]);++ iterator_to_array($adapter->pull());++ $tokenCalls = 0;+ Http::assertSent(function ($request) use (&$tokenCalls) {+ if (str_contains($request->url(), 'accounts.zoho.com/oauth/v2/token')) {+ $tokenCalls++;+ }++ return true;+ });++ $this->assertSame(1, $tokenCalls, 'OAuth token endpoint should be hit at most once per pull');+ }++ public function test_zoho_data_center_setting_routes_to_regional_accounts_host()+ {+ $instance = SyncAdapterInstance::where('slug', 'endpoint_central')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://desktopcentralcloud.manageengine.eu');+ SyncAdapterConfig::put($instance->id, 'mode', EndpointCentralClient::MODE_CLOUD);+ SyncAdapterConfig::put($instance->id, 'data_center', 'eu');+ SyncAdapterConfig::put($instance->id, 'client_id', 'fake-client-id');+ SyncAdapterConfig::put($instance->id, 'client_secret', Crypt::encrypt('fake-client-secret'));+ SyncAdapterConfig::put($instance->id, 'refresh_token', Crypt::encrypt('fake-refresh-token'));++ $adapter = new EndpointCentralAdapter($instance->fresh());++ Http::fake([+ 'accounts.zoho.eu/oauth/v2/token' => Http::response([+ 'access_token' => 'eu-token',+ 'expires_in' => 3600,+ ]),+ '*/dcapi/som/computersInfo*' => Http::response($this->computersListResponse([])),+ ]);++ iterator_to_array($adapter->pull());++ Http::assertSent(fn($request) => str_contains($request->url(), 'accounts.zoho.eu/oauth/v2/token'));+ Http::assertNotSent(fn($request) => str_contains($request->url(), 'accounts.zoho.com/oauth/v2/token'));+ }++ public function test_onprem_mode_sends_authtoken_header_and_skips_oauth()+ {+ $instance = SyncAdapterInstance::where('slug', 'endpoint_central')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://desktopcentral.example.com');+ SyncAdapterConfig::put($instance->id, 'mode', EndpointCentralClient::MODE_ONPREM);+ SyncAdapterConfig::put($instance->id, 'auth_token', Crypt::encrypt('fake-onprem-token'));++ $adapter = new EndpointCentralAdapter($instance->fresh());++ Http::fake([+ '*/dcapi/som/computersInfo*' => Http::response($this->computersListResponse([+ $this->computer(id: 'ec-op-1', name: 'onprem-host'),+ ])),+ ]);++ iterator_to_array($adapter->pull());++ Http::assertNotSent(fn($request) => str_contains($request->url(), 'accounts.zoho'));+ Http::assertSent(function ($request) {+ return $request->hasHeader('Authorization', 'Zoho-authtoken fake-onprem-token');+ });+ }++ public function test_fetch_hardware_details_toggle_resolves_serial_via_per_device_call()+ {+ $instance = SyncAdapterInstance::where('slug', 'endpoint_central')->firstOrFail();+ $this->seedCloudCredentials($instance);+ SyncAdapterConfig::put($instance->id, 'fetch_hardware_details', '1');++ $adapter = new EndpointCentralAdapter($instance->fresh());++ Http::fake([+ 'accounts.zoho.com/oauth/v2/token' => Http::response(['access_token' => 'tok', 'expires_in' => 3600]),+ '*/dcapi/som/computersInfo*' => Http::response($this->computersListResponse([+ $this->computer(id: 'ec-1', name: 'mac-01'),+ ])),+ '*/dcapi/inventory/computers/ec-1/hardware' => Http::response([+ 'message_response' => [+ 'biosDetails' => [+ [+ 'serialNumber' => 'ABC123SERIAL',+ 'hardwareManufacturer' => 'Dell',+ ]+ ],+ 'motherBoardDetails' => [+ [+ 'hardwareName' => 'Latitude 7420',+ 'hardwareManufacturer' => 'Dell',+ ]+ ],+ ],+ ]),+ ]);++ $records = iterator_to_array($adapter->pull());++ $this->assertSame('ABC123SERIAL', $records[0]->hardwareSerial);+ $this->assertSame('Latitude 7420', $records[0]->hardwareModel);+ $this->assertSame('Dell', $records[0]->manufacturer);+ }++ public function test_fetch_hardware_details_off_leaves_serial_null()+ {+ $adapter = $this->configuredCloudAdapter();++ Http::fake([+ 'accounts.zoho.com/oauth/v2/token' => Http::response(['access_token' => 'tok', 'expires_in' => 3600]),+ '*/dcapi/som/computersInfo*' => Http::response($this->computersListResponse([+ $this->computer(id: 'ec-1', name: 'mac-01'),+ ])),+ ]);++ $records = iterator_to_array($adapter->pull());++ $this->assertNull($records[0]->hardwareSerial);+ Http::assertNotSent(fn($request) => str_contains($request->url(), '/hardware'));+ }++ public function test_push_sends_remarks_update_with_asset_tag()+ {+ $instance = SyncAdapterInstance::where('slug', 'endpoint_central')->firstOrFail();+ $this->seedCloudCredentials($instance);+ SyncAdapterConfig::put($instance->id, 'direction.asset_tag', 'push');++ $adapter = new EndpointCentralAdapter($instance->fresh());++ $asset = \App\Models\Asset::factory()->create([+ 'asset_tag' => 'SNIPE-9001',+ 'serial' => 'ABC123',+ ]);+ \App\Models\AssetExternalSource::query()->create([+ 'asset_id' => $asset->id,+ 'source' => 'endpoint_central',+ 'external_id' => 'ec-push-1',+ 'company_id' => null,+ ]);++ Http::fake([+ 'accounts.zoho.com/oauth/v2/token' => Http::response(['access_token' => 'tok', 'expires_in' => 3600]),+ '*/dcapi/som/computers/updateRemarks' => Http::response(['status' => 'success']),+ ]);++ $this->assertTrue($adapter->push($asset, ['asset_tag']));++ Http::assertSent(function ($request) {+ if (!str_contains($request->url(), '/updateRemarks')) {+ return false;+ }+ $body = json_decode($request->body(), true);++ return ($body['resourceIds'][0] ?? null) === 'ec-push-1'+ && ($body['remarks'] ?? null) === 'SNIPE-9001';+ });+ }++ private function configuredCloudAdapter(): EndpointCentralAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'endpoint_central')->firstOrFail();+ $this->seedCloudCredentials($instance);++ return new EndpointCentralAdapter($instance->fresh());+ }++ private function seedCloudCredentials(SyncAdapterInstance $instance): void+ {+ SyncAdapterConfig::put($instance->id, 'url', 'https://desktopcentralcloud.manageengine.com');+ SyncAdapterConfig::put($instance->id, 'mode', EndpointCentralClient::MODE_CLOUD);+ SyncAdapterConfig::put($instance->id, 'data_center', 'us');+ SyncAdapterConfig::put($instance->id, 'client_id', 'fake-client-id');+ SyncAdapterConfig::put($instance->id, 'client_secret', Crypt::encrypt('fake-client-secret'));+ SyncAdapterConfig::put($instance->id, 'refresh_token', Crypt::encrypt('fake-refresh-token'));+ }++ /**+ * @param array<int, array<string, mixed>> $computers+ * @return array<string, mixed>+ */+ private function computersListResponse(array $computers): array+ {+ return ['message_response' => ['computers' => $computers]];+ }++ /**+ * @return array<string, mixed>+ */+ private function computer(+ string $id,+ string $name = 'host',+ ?string $ip = null,+ ?string $mac = null,+ ?string $os = 'Windows 10 Professional Edition (x64)',+ ?string $osPlatform = 'Windows',+ ?string $osVersion = '10.0.19045',+ ?string $lastContactTime = '2026-01-15T10:00:00Z',+ ): array {+ return [+ 'computerId' => $id,+ 'computerName' => $name,+ 'computerFQDNName' => $name . '.example.com',+ 'ipAddress' => $ip,+ 'macAddress' => $mac,+ 'osName' => $os,+ 'osPlatform' => $osPlatform,+ 'osVersion' => $osVersion,+ 'lastContactTime' => $lastContactTime,+ 'liveStatus' => 'Live',+ 'agentVersion' => '11.0',+ 'loggedUsers' => null,+ 'domainName' => 'EXAMPLE',+ 'remoteOfficeID' => '1',+ 'remoteOfficeName' => 'HQ',+ ];+ }+}