A free open source IT asset/license management system
Remove mapped heartbeat logging when heartbeats are off
snipe5a17e367228c
diff --git a/app/SyncAdapters/JamfPlatform/JamfPlatformAdapter.php b/app/SyncAdapters/JamfPlatform/JamfPlatformAdapter.phpnew file mode 100644index 0000000000..5b010b0841--- /dev/null+++ b/app/SyncAdapters/JamfPlatform/JamfPlatformAdapter.php@@ -0,0 +1,165 @@+<?php++namespace App\SyncAdapters\JamfPlatform;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\SyncAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * Jamf Platform adapter. Pulls device inventory via the Jamf Platform+ * API (GA September 2025) and normalizes it into HostInventoryRecord+ * objects.+ *+ * The Platform API is Jamf's unified gateway that fronts multiple+ * products including what used to be Jamf Now (blueprints + basic+ * device inventory). Customers previously configuring Jamf Now+ * authenticate here, and Jamf Pro / Jamf School customers can also+ * point this adapter at their Platform environment for cross-product+ * inventory. The full-featured JamfAdapter (Jamf Pro Classic + Pro+ * API) and JamfSchoolAdapter (Network-ID basic auth) remain the right+ * choice when an admin needs the deeper per-product surface Platform+ * does not yet subsume.+ */+class JamfPlatformAdapter extends SyncAdapter+{+ public static function typeLabel(): string+ {+ return 'Jamf Platform';+ }++ public static function typeSlug(): string+ {+ return 'jamf_platform';+ }++ public static function docsUrl(): ?string+ {+ return 'https://developer.jamf.com/platform-api/';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://us.api.jamfcloud.com';+ }++ public function settingsSchema(): array+ {+ return [+ [+ 'key' => 'client_id',+ 'label' => trans('admin/settings/sync_adapters.label_client_id'),+ 'help' => trans('admin/settings/sync_adapters.jamf_platform_client_id_help'),+ ],+ [+ 'key' => 'client_secret',+ 'label' => trans('admin/settings/sync_adapters.label_client_secret'),+ 'secret' => true,+ 'help' => trans('admin/settings/sync_adapters.jamf_platform_client_secret_help'),+ ],+ [+ 'key' => 'environment_id',+ 'label' => trans('admin/settings/sync_adapters.label_environment_id'),+ 'help' => trans('admin/settings/sync_adapters.jamf_platform_environment_id_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'jamf_platform_udid' => ['label_key' => 'admin/settings/sync_adapters.extra_udid'],+ 'jamf_platform_device_type' => ['label_key' => 'admin/settings/sync_adapters.extra_device_type'],+ 'jamf_platform_supervised' => ['label_key' => 'admin/settings/sync_adapters.extra_supervised', 'type' => 'boolean'],+ 'jamf_platform_blueprint_id' => ['label_key' => 'admin/settings/sync_adapters.extra_blueprint_id'],+ ];+ }++ public function supportsGroupScoping(): bool+ {+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return trans('admin/settings/sync_adapters.vendor_group_jamf_platform_blueprint');+ }++ public function fetchGroups(): array+ {+ $client = $this->buildClient();++ return array_map(+ fn (array $blueprint) => [+ 'id' => (string) ($blueprint['id'] ?? ''),+ 'label' => (string) ($blueprint['name'] ?? $blueprint['id'] ?? '?'),+ ],+ $client->blueprints(),+ );+ }++ public function pull(): iterable+ {+ $client = $this->buildClient();++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ private function buildClient(): JamfPlatformClient+ {+ return new JamfPlatformClient(+ baseUrl: $this->url(),+ clientId: $this->credential('client_id'),+ clientSecret: $this->credential('client_secret'),+ environmentId: $this->credential('environment_id'),+ );+ }++ /**+ * Convert a Platform device payload into the normalized record+ * shape. Device UDID is stable per enrolled device and is what we+ * key asset_external_sources on. Field paths follow the Jamf+ * Platform devices envelope. If the tenant this adapter is pointed+ * at reports a different shape, the reference at+ * https://developer.jamf.com/platform-api/reference/ is+ * authoritative.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'udid'),+ hostname: Arr::get($device, 'name'),+ hardwareSerial: Arr::get($device, 'serialNumber'),+ hardwareModel: Arr::get($device, 'model'),+ manufacturer: 'Apple',+ primaryMac: Arr::get($device, 'wifiMacAddress'),+ primaryIp: null,+ os: Arr::get($device, 'os'),+ osVersion: Arr::get($device, 'osVersion'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'lastReported')),+ assetTag: Arr::get($device, 'assetTag'),+ vendorGroupId: Arr::has($device, 'blueprintId') ? (string) Arr::get($device, 'blueprintId') : null,+ extra: [+ 'jamf_platform_udid' => Arr::get($device, 'udid'),+ 'jamf_platform_device_type' => Arr::get($device, 'deviceType'),+ 'jamf_platform_supervised' => Arr::get($device, 'isSupervised'),+ 'jamf_platform_blueprint_id' => Arr::get($device, 'blueprintId'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/JamfPlatform/JamfPlatformClient.php b/app/SyncAdapters/JamfPlatform/JamfPlatformClient.phpnew file mode 100644index 0000000000..06b2e953f6--- /dev/null+++ b/app/SyncAdapters/JamfPlatform/JamfPlatformClient.php@@ -0,0 +1,148 @@+<?php++namespace App\SyncAdapters\JamfPlatform;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Jamf Platform API. Owns auth and pagination+ * for the endpoints the sync adapter uses. Yields raw decoded JSON, no+ * normalization (that's the adapter's job).+ *+ * Product context: Jamf's Platform API (GA September 2025) is a single+ * gateway that fronts multiple Jamf products, including what used to be+ * Jamf Now (blueprints + basic device inventory) alongside cross-product+ * workflows. Customers previously on Jamf Now authenticate here, and+ * customers on Jamf Pro or Jamf School can also use this endpoint for+ * their cross-product needs. Jamf Pro's rich per-product API and Jamf+ * School's Network-ID basic-auth API stay in their own adapters+ * (JamfAdapter and JamfSchoolAdapter) because Platform does not subsume+ * their full surface yet.+ *+ * Auth model: OAuth 2.0 client credentials. The admin creates an+ * integration in Jamf Account, grants it the capabilities it needs,+ * and copies the client id + client secret plus the environment UUID+ * into this adapter's settings. This client exchanges those for a+ * 15-minute bearer token at /auth/token and caches it on the instance+ * so a full-fleet pull does not re-authenticate on every request.+ *+ * Required request headers:+ * - Authorization: Bearer <access_token>+ * - X-Environment-Id: <UUID>+ * - Accept: application/json+ *+ * Jamf Platform API reference: https://developer.jamf.com/platform-api/+ */+class JamfPlatformClient+{+ private ?string $accessToken = null;++ public function __construct(+ private readonly string $baseUrl,+ private readonly string $clientId,+ private readonly string $clientSecret,+ private readonly string $environmentId,+ ) {}++ /**+ * Iterate every device in the environment, one page at a time.+ * Returns a generator so callers stream through large fleets+ * without holding the whole list in memory.+ *+ * Platform API collection endpoints use page + page-size (integer,+ * 1-based) and return a `{results: [...], totalCount: N}` envelope.+ * The loop terminates on either a short page (fewer than page-size+ * records back) or when seen-so-far matches totalCount, whichever+ * hits first.+ *+ * @return iterable<array<string, mixed>>+ */+ public function devices(int $pageSize = 100): iterable+ {+ $page = 1;++ do {+ $response = $this->request()+ ->get('/devices/v1/devices', [+ 'page' => $page,+ 'page-size' => $pageSize,+ ])+ ->throw()+ ->json();++ $devices = $response['results'] ?? [];+ foreach ($devices as $device) {+ yield $device;+ }++ $total = $response['totalCount'] ?? null;+ $seenSoFar = ($page - 1) * $pageSize + count($devices);+ $done = count($devices) < $pageSize+ || ($total !== null && $seenSoFar >= $total);+ $page++;+ } while (! $done);+ }++ /**+ * List every Blueprint in the environment. Blueprints are Jamf's+ * device-grouping concept (configuration profile bundle applied to+ * a set of devices, historically the core primitive of Jamf Now).+ * Used by the adapter's fetchGroups() so admins can map Blueprints+ * to Snipe-IT companies.+ *+ * @return array<int, array<string, mixed>>+ */+ public function blueprints(): array+ {+ $response = $this->request()+ ->get('/blueprints/v1/blueprints')+ ->throw()+ ->json();++ return $response['results'] ?? [];+ }++ /**+ * Base HTTP client with resolved bearer token AND the environment+ * scope header the Platform API requires on every environment-+ * scoped call. The environment id is a UUID copied from Jamf+ * Account after the integration is created.+ */+ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withOptions(['allow_redirects' => false])+ ->withToken($this->bearer())+ ->withHeaders(['X-Environment-Id' => $this->environmentId])+ ->acceptJson()+ ->timeout(60);+ }++ /**+ * Exchange client credentials for a bearer token. Tokens are+ * short-lived (15 minutes per Jamf docs) and cached on this+ * instance so a full sync run does not retrigger auth per request.+ * Failures throw up to the sync runner and land in the+ * sync-adapters log.+ */+ private function bearer(): string+ {+ if ($this->accessToken !== null) {+ return $this->accessToken;+ }++ $response = Http::asForm()+ ->withOptions(['allow_redirects' => false])+ ->timeout(30)+ ->post(rtrim($this->baseUrl, '/').'/auth/token', [+ 'grant_type' => 'client_credentials',+ 'client_id' => $this->clientId,+ 'client_secret' => $this->clientSecret,+ ])+ ->throw()+ ->json();++ return $this->accessToken = (string) ($response['access_token'] ?? '');+ }+}diff --git a/app/SyncAdapters/SyncsHostFromRecord.php b/app/SyncAdapters/SyncsHostFromRecord.phpindex 996ffc142a..6f8f5426dc 100644--- a/app/SyncAdapters/SyncsHostFromRecord.php+++ b/app/SyncAdapters/SyncsHostFromRecord.php@@ -46,7 +46,18 @@ trait SyncsHostFromRecord$previousExternal = $isNew ? [] : self::loadExternalSourceInventory($asset->id);$wasDirty = $asset->isDirty();- $asset->saveOrFail();++ // Heartbeat-only asset-side write: Skip logging when heartbeat-logging is turned off,+ // when the mapping directs last_seen to a custom field (target custom:X).+ // Otherwise the vendor's heartbeat lands on the asset and fires AssetObserver::updating+ // on save, which writes an `update` Actionlog.+ if (!$isNew && self::isHeartbeatOnlyAssetDirty($asset, $mapping, $instance)) {+ if (!$asset->saveQuietly()) {+ throw new RuntimeException('Failed to save asset during heartbeat-only sync.');+ }+ } else {+ $asset->saveOrFail();+ }// External-source column writes gather during the mapping// loop and go out together so we make one row-write per@@ -732,6 +743,40 @@ trait SyncsHostFromRecord$asset->{$field->db_column} = $value;}+ /**+ * Detect the "sync only changed the last_seen custom field" case+ *+ * @param array<string, string> $mapping+ */+ private static function isHeartbeatOnlyAssetDirty(+ Asset $asset,+ array $mapping,+ ?SyncAdapterInstance $instance,+ ): bool {+ if (!$asset->isDirty()) {+ return false;+ }+ if ($instance === null) {+ return false;+ }+ $adapter = $instance->adapter();+ if (!$adapter instanceof SyncAdapter || $adapter->logsHeartbeats()) {+ return false;+ }++ $lastSeenTarget = $mapping['last_seen'] ?? MappingTargets::defaultTarget('last_seen');+ if (!str_starts_with($lastSeenTarget, 'custom:')) {+ return false;+ }++ $field = CustomField::find((int) substr($lastSeenTarget, 7));+ if ($field === null || $field->db_column === null) {+ return false;+ }++ return array_keys($asset->getDirty()) === [$field->db_column];+ }+/*** Write the inventory columns onto the asset's external-source* row. The identity columns (source, external_id, company_id)diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 0e92a7bb54..7e09f958cc 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -181,6 +181,9 @@ return ['abm_category_family_label' => 'Category for :family','abm_category_family_help' => 'Route the :family product family to a specific category, overriding the default category above. Leave blank to inherit the default.','abm_section_categories_title' => 'Category mapping by product family',+ 'jamf_platform_client_id_help' => 'Create an integration in Jamf Account under API integrations, then grant it the capabilities for Devices (read) and Blueprints (read) on your Platform environment. Copy the Client ID from the integration detail page.',+ 'jamf_platform_client_secret_help' => 'Paired with the Client ID above. Jamf shows the secret once at integration creation time.',+ 'jamf_platform_environment_id_help' => 'UUID of the Platform environment the integration is scoped to. Copy from Jamf Account under Environments, or from the URL of your environment console. Sent as the X-Environment-Id header on every request.',// Custom HTTP adapter'custom_auth_method_help' => 'How the adapter authenticates against your API. <code>Bearer</code> sends a Bearer token in the <code>Authorization</code> header. <code>Basic</code> sends username + password. <code>API Key</code> sends the value in a custom header. <code>None</code> sends no auth headers.',@@ -253,6 +256,7 @@ return ['extra_team' => ':vendor Team','extra_uuid' => ':vendor UUID','extra_udid' => ':vendor UDID',+ 'extra_device_type' => ':vendor Device Type','extra_status' => ':vendor Status','extra_byod' => ':vendor Personal (BYOD)','extra_active' => ':vendor Active',@@ -317,6 +321,7 @@ return ['label_site_id' => 'Site ID','label_organization_id' => 'Organization ID','label_environment' => 'Environment',+ 'label_environment_id' => 'Environment ID','label_token_id' => 'Token ID','label_token_secret' => 'Token Secret','label_asset_tag_custom_field_name' => 'Asset Tag Custom Field Name',@@ -331,6 +336,7 @@ return ['vendor_group_jamf_site' => 'Jamf Site','vendor_group_jamf_school_location' => 'Jamf School Location','vendor_group_kandji_blueprint' => 'Kandji Blueprint',+ 'vendor_group_jamf_platform_blueprint' => 'Jamf Platform Blueprint','vendor_group_mosyle_location' => 'Mosyle Location','vendor_group_kaseya_organization' => 'Kaseya Organization',