Skip to content

A free open source IT asset/license management system

Added Sophos Central sync adapter

BJ Hinkle59242306e370
diff --git a/app/SyncAdapters/SophosCentral/SophosCentralAdapter.php b/app/SyncAdapters/SophosCentral/SophosCentralAdapter.php
new file mode 100644
index 0000000000..3306436b6e
--- /dev/null
+++ b/app/SyncAdapters/SophosCentral/SophosCentralAdapter.php
@@ -0,0 +1,364 @@
+<?php
+
+namespace App\SyncAdapters\SophosCentral;
+
+use App\SyncAdapters\HostInventoryRecord;
+use App\SyncAdapters\SyncAdapter;
+use Carbon\Carbon;
+use Illuminate\Support\Arr;
+
+/**
+ * Sophos Central adapter. Pulls endpoint inventory and security status
+ * from Sophos Central (Sophos Endpoint / Intercept X) and normalizes it
+ * into HostInventoryRecord objects.
+ *
+ * Sophos is often a second source for devices another adapter already
+ * created (an MDM, or Apple Business Manager), and the only source for
+ * machines no MDM covers: Linux laptops, the odd Windows PC, Macs that
+ * were never added to ABM. Records are keyed on the hardware serial, the
+ * way the Zentral adapter does it, so "match by serial" joins them to
+ * existing assets and a reinstall (which Sophos gives a new endpoint id)
+ * stays on the same asset. Endpoints without a serial fall back to the
+ * Sophos endpoint id.
+ *
+ * Sophos can hold more than one endpoint record for the same machine
+ * after a reinstall or hand-off. pull() keeps the most recently seen one.
+ *
+ * Sophos reports no hardware model or manufacturer.
+ */
+class SophosCentralAdapter extends SyncAdapter
+{
+ /**
+ * Sophos endpoint types. Every Linux device is reported as a server,
+ * laptops included, so the type alone can't separate Linux laptops
+ * from Linux servers.
+ */
+ public const ENDPOINT_TYPES = [
+ 'computer' => 'Computers',
+ 'server' => 'Servers',
+ ];
+
+ public static function typeLabel(): string
+ {
+ return 'Sophos Central';
+ }
+
+ public static function typeSlug(): string
+ {
+ return 'sophos_central';
+ }
+
+ public static function docsUrl(): ?string
+ {
+ return 'https://developer.sophos.com/intro';
+ }
+
+ /**
+ * Sophos hosts are fixed: tokens come from id.sophos.com, and the
+ * tenant's regional data host is discovered through whoami. There is
+ * nothing for the admin to type.
+ */
+ public function usesConfigurableUrl(): bool
+ {
+ return false;
+ }
+
+ public function settingsSchema(): array
+ {
+ return [
+ [
+ 'key' => 'client_id',
+ 'label' => trans('admin/settings/sync_adapters.label_client_id'),
+ 'help' => trans('admin/settings/sync_adapters.sophos_client_id_help'),
+ ],
+ [
+ 'key' => 'client_secret',
+ 'label' => trans('admin/settings/sync_adapters.label_client_secret'),
+ 'secret' => true,
+ 'help' => trans('admin/settings/sync_adapters.sophos_client_secret_help'),
+ ],
+ [
+ 'key' => 'endpoint_types',
+ 'label' => trans('admin/settings/sync_adapters.sophos_label_endpoint_types'),
+ 'type' => 'multiselect',
+ 'options' => self::ENDPOINT_TYPES,
+ 'default' => ['computer'],
+ 'required' => false,
+ 'help' => trans('admin/settings/sync_adapters.sophos_endpoint_types_help'),
+ ],
+ [
+ 'key' => 'skip_cloud_instances',
+ 'label' => trans('admin/settings/sync_adapters.sophos_label_skip_cloud_instances'),
+ 'type' => 'checkbox',
+ 'required' => false,
+ 'help' => trans('admin/settings/sync_adapters.sophos_skip_cloud_instances_help'),
+ ],
+ ];
+ }
+
+ public function presetExtraFields(): array
+ {
+ return [
+ 'sophos_endpoint_id' => ['label_key' => 'admin/settings/sync_adapters.extra_endpoint_id'],
+ 'sophos_endpoint_type' => ['label_key' => 'admin/settings/sync_adapters.extra_device_type'],
+ 'sophos_health' => ['label_key' => 'admin/settings/sync_adapters.extra_health'],
+ 'sophos_threat_status' => ['label_key' => 'admin/settings/sync_adapters.extra_threat_status'],
+ 'sophos_service_status' => ['label_key' => 'admin/settings/sync_adapters.extra_service_status'],
+ 'sophos_tamper_protection' => ['label_key' => 'admin/settings/sync_adapters.extra_tamper_protection', 'type' => 'boolean'],
+ 'sophos_encryption_status' => ['label_key' => 'admin/settings/sync_adapters.extra_encryption_status'],
+ 'sophos_isolation_status' => ['label_key' => 'admin/settings/sync_adapters.extra_isolation_status'],
+ 'sophos_last_user' => ['label_key' => 'admin/settings/sync_adapters.extra_last_user'],
+ 'sophos_installed_products' => ['label_key' => 'admin/settings/sync_adapters.extra_installed_products'],
+ 'sophos_group' => ['label_key' => 'admin/settings/sync_adapters.extra_group'],
+ ];
+ }
+
+ public function supportsAdminDefinedExtras(): bool
+ {
+ return true;
+ }
+
+ public function pull(): iterable
+ {
+ $types = $this->allowedEndpointTypes();
+ $skipCloud = $this->skipsCloudInstances();
+
+ // One record per machine: key on the serial (or the endpoint id
+ // when there isn't one) and keep the most recently seen endpoint.
+ $current = [];
+ foreach ($this->buildClient()->endpoints() as $endpoint) {
+ if (! in_array(strtolower((string) Arr::get($endpoint, 'type')), $types, true)) {
+ continue;
+ }
+ if ($skipCloud && Arr::get($endpoint, 'cloud.provider')) {
+ continue;
+ }
+
+ $key = self::serialOf($endpoint) ?? 'id:'.Arr::get($endpoint, 'id');
+ if (! isset($current[$key]) || self::seenLater($endpoint, $current[$key])) {
+ $current[$key] = $endpoint;
+ }
+ }
+
+ foreach ($current as $endpoint) {
+ yield $this->normalize($endpoint);
+ }
+ }
+
+ private function buildClient(): SophosCentralClient
+ {
+ return new SophosCentralClient(
+ clientId: $this->credential('client_id'),
+ clientSecret: $this->credential('client_secret'),
+ );
+ }
+
+ /**
+ * Convert a Sophos endpoint (view=full) into the normalized record.
+ *
+ * @param array<string, mixed> $endpoint
+ */
+ private function normalize(array $endpoint): HostInventoryRecord
+ {
+ $serial = self::serialOf($endpoint);
+ $endpointId = (string) Arr::get($endpoint, 'id');
+ [$os, $osVersion] = self::osNameAndVersion($endpoint);
+
+ $extra = [
+ 'sophos_endpoint_id' => $endpointId,
+ 'sophos_endpoint_type' => Arr::get($endpoint, 'type'),
+ 'sophos_health' => Arr::get($endpoint, 'health.overall'),
+ 'sophos_threat_status' => Arr::get($endpoint, 'health.threats.status'),
+ 'sophos_service_status' => Arr::get($endpoint, 'health.services.status'),
+ 'sophos_tamper_protection' => Arr::get($endpoint, 'tamperProtectionEnabled'),
+ 'sophos_encryption_status' => Arr::get($endpoint, 'encryption.overallStatus'),
+ 'sophos_isolation_status' => Arr::get($endpoint, 'isolation.status'),
+ 'sophos_last_user' => Arr::get($endpoint, 'associatedPerson.name')
+ ?? Arr::get($endpoint, 'associatedPerson.viaLogin'),
+ 'sophos_installed_products' => self::installedProducts($endpoint),
+ 'sophos_group' => Arr::get($endpoint, 'group.name'),
+ ];
+ $extra = $this->applyAdminExtras($extra, $endpoint);
+
+ return new HostInventoryRecord(
+ sourceKey: $this->name(),
+ sourceId: $serial ?? $endpointId,
+ hostname: Arr::get($endpoint, 'hostname'),
+ hardwareSerial: $serial,
+ hardwareModel: $this->modelFor($endpoint),
+ manufacturer: null,
+ primaryMac: Arr::first((array) Arr::get($endpoint, 'macAddresses', [])),
+ primaryIp: Arr::first((array) Arr::get($endpoint, 'ipv4Addresses', [])),
+ os: $os,
+ osVersion: $osVersion,
+ lastSeen: $this->parseTimestamp(Arr::get($endpoint, 'lastSeenAt')),
+ extra: $extra,
+ );
+ }
+
+ /**
+ * Sophos reports no hardware model, but a new asset needs one, so this
+ * is a readable placeholder per platform and type, for example
+ * "macOS computer (model unknown)", which an admin can merge into a
+ * real model later. When another adapter already supplies real models,
+ * set this adapter's model mapping to skip: adopted assets then keep
+ * their model, and new assets still get the placeholder.
+ *
+ * @param array<string, mixed> $endpoint
+ */
+ private function modelFor(array $endpoint): string
+ {
+ $platform = match (strtolower((string) Arr::get($endpoint, 'os.platform'))) {
+ 'macos' => 'macOS',
+ 'linux' => 'Linux',
+ 'windows' => 'Windows',
+ '' => 'Unknown',
+ default => (string) Arr::get($endpoint, 'os.platform'),
+ };
+ $type = Arr::get($endpoint, 'type') ?: 'endpoint';
+
+ return $platform.' '.$type.' (model unknown)';
+ }
+
+ /**
+ * The hardware serial, or null when Sophos has none.
+ *
+ * @param array<string, mixed> $endpoint
+ */
+ private static function serialOf(array $endpoint): ?string
+ {
+ $serial = trim((string) Arr::get($endpoint, 'serialNumber', ''));
+
+ return $serial === '' ? null : $serial;
+ }
+
+ /**
+ * True when $a was seen more recently than $b. Timestamps are compared
+ * as dates, so a different precision or UTC offset can't reorder them.
+ * A missing or unreadable timestamp counts as the oldest.
+ *
+ * @param array<string, mixed> $a
+ * @param array<string, mixed> $b
+ */
+ private static function seenLater(array $a, array $b): bool
+ {
+ return self::lastSeenMillis($a) > self::lastSeenMillis($b);
+ }
+
+ /**
+ * @param array<string, mixed> $endpoint
+ */
+ private static function lastSeenMillis(array $endpoint): int
+ {
+ $value = Arr::get($endpoint, 'lastSeenAt');
+ if (! is_string($value) || $value === '') {
+ return 0;
+ }
+
+ try {
+ return (int) Carbon::parse($value)->valueOf();
+ } catch (\Throwable) {
+ return 0;
+ }
+ }
+
+ /**
+ * Split Sophos's OS fields into an OS name and a version.
+ *
+ * Sophos puts both in os.name ("macOS Tahoe 26.6", "Ubuntu 24.04.3 LTS",
+ * "Windows 11 Pro") and fills majorVersion, minorVersion and build only
+ * some of the time. On Linux those numbers drop Ubuntu's leading zero
+ * (24.04 comes back as 24 and 4) or are missing, so the version is read
+ * from the name there. On macOS and Windows the numbers are more precise
+ * than the name ("macOS Sonoma 14" carries 14.6), so they win.
+ *
+ * @param array<string, mixed> $endpoint
+ * @return array{0: ?string, 1: ?string}
+ */
+ private static function osNameAndVersion(array $endpoint): array
+ {
+ $name = trim((string) preg_replace('/\s+/', ' ', (string) Arr::get($endpoint, 'os.name', '')));
+ $platform = strtolower((string) Arr::get($endpoint, 'os.platform', ''));
+
+ // The version inside the name: a dotted number anywhere ("24.04.3"),
+ // or a bare number at the very end ("macOS Sonoma 14"). A bare number
+ // mid-name, like the 11 in "Windows 11 Pro", is part of the product name.
+ $nameVersion = null;
+ if (preg_match('/(?<![\w.])\d+(?:\.\d+)+(?![\w.])/', $name, $match)
+ || preg_match('/(?<=\s)\d+$/', $name, $match)) {
+ $nameVersion = $match[0];
+ $name = trim((string) preg_replace('/\s+/', ' ', (string) preg_replace('/(?<![\w.])'.preg_quote($nameVersion, '/').'(?![\w.])/', '', $name, 1)));
+ }
+
+ $numbers = array_filter(
+ [Arr::get($endpoint, 'os.majorVersion'), Arr::get($endpoint, 'os.minorVersion'), Arr::get($endpoint, 'os.build')],
+ fn ($part) => $part !== null && $part !== '',
+ );
+ $numericVersion = $numbers === [] ? null : implode('.', $numbers);
+
+ $version = $platform === 'linux'
+ ? ($nameVersion ?? $numericVersion)
+ : ($numericVersion ?? $nameVersion);
+
+ $os = $name !== '' ? $name : (Arr::get($endpoint, 'os.platform') ?: null);
+
+ return [$os, $version];
+ }
+
+ /**
+ * Installed Sophos products as a comma-separated list of product codes,
+ * for example "coreAgent, endpointProtection, interceptX".
+ *
+ * @param array<string, mixed> $endpoint
+ */
+ private static function installedProducts(array $endpoint): ?string
+ {
+ $codes = collect((array) Arr::get($endpoint, 'assignedProducts', []))
+ ->filter(fn ($product) => is_array($product) && ($product['status'] ?? null) === 'installed')
+ ->pluck('code')
+ ->filter()
+ ->sort()
+ ->values();
+
+ return $codes->isEmpty() ? null : $codes->implode(', ');
+ }
+
+ /**
+ * The admin's endpoint-type selection, lower-cased. Nothing selected
+ * (or nothing saved yet) means computers only, the schema default.
+ *
+ * @return array<int, string>
+ */
+ private function allowedEndpointTypes(): array
+ {
+ try {
+ $decoded = json_decode($this->credential('endpoint_types'), true);
+ } catch (\Throwable) {
+ $decoded = null;
+ }
+
+ $types = is_array($decoded)
+ ? array_values(array_map('strtolower', array_filter($decoded, 'is_string')))
+ : [];
+
+ return $types === [] ? ['computer'] : $types;
+ }
+
+ private function skipsCloudInstances(): bool
+ {
+ try {
+ return $this->credential('skip_cloud_instances') === '1';
+ } catch (\Throwable) {
+ return false;
+ }
+ }
+
+ private function parseTimestamp(mixed $value): ?Carbon
+ {
+ if ($value === null || $value === '') {
+ return null;
+ }
+
+ return Carbon::parse($value);
+ }
+}
diff --git a/app/SyncAdapters/SophosCentral/SophosCentralClient.php b/app/SyncAdapters/SophosCentral/SophosCentralClient.php
new file mode 100644
index 0000000000..33842edc76
--- /dev/null
+++ b/app/SyncAdapters/SophosCentral/SophosCentralClient.php
@@ -0,0 +1,190 @@
+<?php
+
+namespace App\SyncAdapters\SophosCentral;
+
+use Illuminate\Http\Client\ConnectionException;
+use Illuminate\Http\Client\PendingRequest;
+use Illuminate\Http\Client\RequestException;
+use Illuminate\Support\Facades\Http;
+use RuntimeException;
+
+/**
+ * Thin wrapper around the Sophos Central API. Owns auth, tenant
+ * discovery and pagination for the endpoints the sync adapter uses.
+ * Yields raw decoded JSON, no normalization (that's the adapter's job).
+ *
+ * Auth model: OAuth 2.0 client credentials. The admin creates an API
+ * credential in Sophos Central (Global Settings -> API Credentials
+ * Management) with the Service Principal Read-Only role, and copies the
+ * client id + client secret into this adapter's settings. This client
+ * exchanges those for a bearer token at id.sophos.com (valid for about
+ * an hour) and caches it on the instance for the rest of the run.
+ *
+ * Discovery: Sophos serves each tenant from a regional data host. After
+ * the token exchange, GET /whoami/v1 on the global API host returns the
+ * tenant id and that data host. Every data call then goes to the data
+ * host with the bearer token and an X-Tenant-ID header. Only tenant-level
+ * credentials are supported here; partner and organization credentials
+ * return a different idType and would need a tenant picker.
+ *
+ * Sophos Central API reference: https://developer.sophos.com/intro
+ */
+class SophosCentralClient
+{
+ public const TOKEN_URL = 'https://id.sophos.com/api/v2/oauth2/token';
+
+ public const WHOAMI_URL = 'https://api.central.sophos.com/whoami/v1';
+
+ /** Guard against a paging loop if the API ever repeats a key. */
+ private const MAX_PAGES = 1000;
+
+ private ?string $accessToken = null;
+
+ private ?string $tenantId = null;
+
+ private ?string $dataHost = null;
+
+ public function __construct(
+ private readonly string $clientId,
+ private readonly string $clientSecret,
+ ) {}
+
+ /**
+ * Iterate every endpoint (computers and servers) in the tenant, one
+ * page at a time. `view=full` is required: the default, basic and
+ * summary views leave serialNumber out.
+ *
+ * Paging is key-based: each response carries pages.nextKey, which is
+ * passed back as pageFromKey. The loop ends when no nextKey comes back.
+ *
+ * @return iterable<int, array<string, mixed>>
+ */
+ public function endpoints(int $pageSize = 500): iterable
+ {
+ $fromKey = null;
+ $seenKeys = [];
+
+ for ($page = 0; $page < self::MAX_PAGES; $page++) {
+ $params = ['pageSize' => $pageSize, 'view' => 'full'];
+ if (is_string($fromKey)) {
+ $params['pageFromKey'] = $fromKey;
+ }
+
+ $response = $this->request()
+ ->get('/endpoint/v1/endpoints', $params)
+ ->throw()
+ ->json();
+
+ foreach ($response['items'] ?? [] as $endpoint) {
+ yield $endpoint;
+ }
+
+ $fromKey = $response['pages']['nextKey'] ?? null;
+ if (! is_string($fromKey) || $fromKey === '' || isset($seenKeys[$fromKey])) {
+ return;
+ }
+ $seenKeys[$fromKey] = true;
+ }
+ }
+
+ /**
+ * Base HTTP client for tenant-scoped calls: the discovered data host,
+ * the bearer token and the tenant header. Retries connection errors
+ * and 429s the same way the Apple Business Manager client does.
+ */
+ private function request(): PendingRequest
+ {
+ $this->discover();
+
+ return Http::baseUrl($this->dataHost)
+ ->withOptions(['allow_redirects' => false])
+ ->withToken($this->bearer())
+ ->withHeaders(['X-Tenant-ID' => $this->tenantId])
+ ->acceptJson()
+ ->timeout(60)
+ ->retry(3, 500, fn (\Exception $e) => $e instanceof ConnectionException
+ || ($e instanceof RequestException && $e->response->status() === 429));
+ }
+
+ /**
+ * Resolve the tenant id and regional data host once per run.
+ * The data host comes from the API rather than from the admin, so it
+ * skips the base-URL validation other adapters get; check it here
+ * before any token is sent to it.
+ */
+ private function discover(): void
+ {
+ if ($this->tenantId !== null && $this->dataHost !== null) {
+ return;
+ }
+
+ $whoami = Http::withOptions(['allow_redirects' => false])
+ ->withToken($this->bearer())
+ ->acceptJson()
+ ->timeout(30)
+ ->get(self::WHOAMI_URL)
+ ->throw()
+ ->json();
+
+ $idType = (string) ($whoami['idType'] ?? '');
+ if ($idType !== 'tenant') {
+ throw new RuntimeException(
+ 'This Sophos Central credential is '.($idType !== '' ? $idType : 'not')
+ .'-level. Create a tenant-level API credential (Global Settings -> API Credentials Management) and use that instead.',
+ );
+ }
+
+ $tenantId = (string) ($whoami['id'] ?? '');
+ $dataHost = (string) ($whoami['apiHosts']['dataRegion'] ?? '');
+ if ($tenantId === '' || ! self::isSophosHost($dataHost)) {
+ throw new RuntimeException('Sophos Central returned an unexpected tenant id or data host from whoami.');
+ }
+
+ $this->tenantId = $tenantId;
+ $this->dataHost = rtrim($dataHost, '/');
+ }
+
+ /**
+ * True for an https URL whose host is sophos.com or a subdomain of it.
+ */
+ public static function isSophosHost(string $url): bool
+ {
+ $parts = parse_url($url);
+ if (! is_array($parts) || ($parts['scheme'] ?? '') !== 'https') {
+ return false;
+ }
+ $host = strtolower($parts['host'] ?? '');
+
+ return $host === 'sophos.com' || str_ends_with($host, '.sophos.com');
+ }
+
+ /**
+ * Exchange the client credentials for a bearer token, cached for the
+ * rest of this run. A full pull finishes well inside the token's hour.
+ */
+ private function bearer(): string
+ {
+ if ($this->accessToken !== null) {
+ return $this->accessToken;
+ }
+
+ $response = Http::asForm()
+ ->withOptions(['allow_redirects' => false])
+ ->timeout(30)
+ ->post(self::TOKEN_URL, [
+ 'grant_type' => 'client_credentials',
+ 'client_id' => $this->clientId,
+ 'client_secret' => $this->clientSecret,
+ 'scope' => 'token',
+ ])
+ ->throw()
+ ->json();
+
+ $token = (string) ($response['access_token'] ?? '');
+ if ($token === '') {
+ throw new RuntimeException('Sophos Central did not return an access token. Check the client id and secret.');
+ }
+
+ return $this->accessToken = $token;
+ }
+}
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index a4b05d7aa6..deed5a71ae 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -279,6 +279,10 @@ return [
'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.',
'landscape_token_help' => 'Landscape does not have a UI for API tokens. Obtain one by POSTing your credentials to <code>/api/v2/login</code> on your Landscape instance and copying the <code>token</code> field from the JSON response. Pass an <code>expiry_minutes</code> value on that call to control how long the token stays valid (defaults to 24h). The account behind the token needs read access to computers.',
+ 'sophos_client_id_help' => 'Create a credential in Sophos Central under Global Settings -> API Credentials Management, with the Service Principal Read-Only role. Copy the Client ID from the credential page. Only tenant-level credentials are supported.',
+ 'sophos_client_secret_help' => 'Paired with the Client ID above. Sophos Central shows the secret once, when the credential is created. Credentials expire eventually and can\'t be renewed, so create a new one when that happens.',
+ 'sophos_endpoint_types_help' => 'Only sync these Sophos endpoint types. Sophos lists every Linux device as a server, laptops included.',
+ 'sophos_skip_cloud_instances_help' => 'Skip endpoints that Sophos reports as cloud instances, such as AWS or Azure virtual machines.',
// Google Workspace (ChromeOS) adapter
'google_workspace_label_service_account_email' => 'Service Account Email',
@@ -414,6 +418,15 @@ return [
'extra_reboot_required' => ':vendor Reboot Required',
'extra_ubuntu_pro' => 'Ubuntu Pro',
'extra_osquery_version' => 'osquery Version',
+ 'extra_endpoint_id' => ':vendor Endpoint ID',
+ 'extra_health' => ':vendor Health',
+ 'extra_threat_status' => ':vendor Threat Status',
+ 'extra_service_status' => ':vendor Service Status',
+ 'extra_tamper_protection' => ':vendor Tamper Protection',
+ 'extra_encryption_status' => ':vendor Encryption Status',
+ 'extra_isolation_status' => ':vendor Isolation Status',
+ 'extra_last_user' => ':vendor Last User',
+ 'extra_installed_products' => ':vendor Installed Products',
// Shared label strings for adapter settings schemas. Adapters
// reach for these via trans() so the labels localize alongside
@@ -483,6 +496,10 @@ return [
'abm_option_mode_business' => 'Apple Business Manager',
'abm_option_mode_school' => 'Apple School Manager',
+ // Sophos Central adapter-specific labels.
+ 'sophos_label_endpoint_types' => 'Endpoint Types',
+ 'sophos_label_skip_cloud_instances' => 'Skip Cloud Instances',
+
// Custom HTTP option strings.
'custom_option_auth_bearer' => 'Bearer Token',
'custom_option_auth_basic' => 'Basic Auth',
diff --git a/tests/Feature/SyncAdapters/SophosCentral/SophosCentralAdapterTest.php b/tests/Feature/SyncAdapters/SophosCentral/SophosCentralAdapterTest.php
new file mode 100644
index 0000000000..db3feaccbe
--- /dev/null
+++ b/tests/Feature/SyncAdapters/SophosCentral/SophosCentralAdapterTest.php
@@ -0,0 +1,469 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters\SophosCentral;
+
+use App\Models\Asset;
+use App\Models\CustomField;
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\Models\User;
+use App\SyncAdapters\SophosCentral\SophosCentralAdapter;
+use App\SyncAdapters\SyncAdapter;
+use Illuminate\Http\Client\Request;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Http;
+use RuntimeException;
+use Tests\TestCase;
+
+/**
+ * End-to-end coverage for the Sophos Central adapter through
+ * SyncAdapter. Fakes the token exchange at id.sophos.com, the whoami
+ * tenant discovery on the global API host, and the endpoint list on the
+ * discovered regional data host.
+ */
+class SophosCentralAdapterTest extends TestCase
+{
+ private const DATA_HOST = 'https://api-us03.central.sophos.com';
+
+ private const TENANT_ID = '11111111-2222-3333-4444-555555555555';
+
+ protected function setUp(): void
+ {
+ parent::setUp();
+ Statuslabel::factory()->rtd()->create();
+ }
+
+ public function test_pulls_endpoints_and_creates_assets_keyed_on_serial()
+ {
+ $adapter = $this->configuredAdapter();
+ $this->fakeSophos([[
+ $this->endpoint(id: 'ep-1', serial: 'C02AAA111', hostname: 'mac-one'),
+ $this->endpoint(id: 'ep-2', serial: 'C02BBB222', hostname: 'mac-two'),
+ ]]);
+
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $this->assertDatabaseCount('asset_external_sources', 2);
+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'sophos_central', 'external_id' => 'C02AAA111']);
+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'sophos_central', 'external_id' => 'C02BBB222']);
+ $this->assertDatabaseHas('assets', ['serial' => 'C02AAA111', 'name' => 'mac-one']);
+ }
+
+ public function test_normalized_record_carries_expected_fields()
+ {
+ $adapter = $this->configuredAdapter();
+ $this->fakeSophos([[
+ $this->endpoint(id: 'ep-7', serial: 'C02XYZ789', hostname: 'alice-mbp') + [
+ 'macAddresses' => ['3c:22:fb:00:11:22', '3c:22:fb:00:11:33'],
+ 'ipv4Addresses' => ['10.0.0.7'],
+ 'health' => ['overall' => 'good', 'threats' => ['status' => 'good'], 'services' => ['status' => 'good']],
+ 'tamperProtectionEnabled' => true,
+ 'encryption' => ['overallStatus' => 'encrypted'],
+ 'isolation' => ['status' => 'notIsolated'],
+ 'associatedPerson' => ['name' => 'Alice Example', 'viaLogin' => 'alice-mbp\\alice'],
+ 'assignedProducts' => [
+ ['code' => 'interceptX', 'status' => 'installed'],
+ ['code' => 'coreAgent', 'status' => 'installed'],
+ ['code' => 'xdr', 'status' => 'notInstalled'],
+ ],
+ 'group' => ['name' => 'Laptops'],
+ ],
+ ]]);
+
+ $records = iterator_to_array($adapter->pull(), false);
+ $this->assertCount(1, $records);
+ $record = $records[0];
+
+ $this->assertSame('sophos_central', $record->sourceKey);
+ $this->assertSame('C02XYZ789', $record->sourceId);
+ $this->assertSame('C02XYZ789', $record->hardwareSerial);
+ $this->assertSame('alice-mbp', $record->hostname);
+ $this->assertSame('macOS computer (model unknown)', $record->hardwareModel);
+ $this->assertNull($record->manufacturer);
+ $this->assertSame('3c:22:fb:00:11:22', $record->primaryMac);
+ $this->assertSame('10.0.0.7', $record->primaryIp);
+ $this->assertSame('macOS Tahoe', $record->os);
+ $this->assertSame('26.6', $record->osVersion);
+ $this->assertNotNull($record->lastSeen);
+ $this->assertSame('ep-7', $record->extra['sophos_endpoint_id']);
+ $this->assertSame('computer', $record->extra['sophos_endpoint_type']);
+ $this->assertSame('good', $record->extra['sophos_health']);
+ $this->assertTrue($record->extra['sophos_tamper_protection']);
+ $this->assertSame('encrypted', $record->extra['sophos_encryption_status']);
+ $this->assertSame('notIsolated', $record->extra['sophos_isolation_status']);
+ $this->assertSame('Alice Example', $record->extra['sophos_last_user']);
+ $this->assertSame('coreAgent, interceptX', $record->extra['sophos_installed_products']);
+ $this->assertSame('Laptops', $record->extra['sophos_group']);
+ }
+
+ public function test_admin_defined_extras_overlay_a_dot_path_from_the_endpoint()
+ {
+ // An admin maps a Sophos field the adapter doesn't preset (the
+ // login name, kept apart from the person's display name) to a
+ // Snipe-IT custom field through the Custom Extras widget.
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Sophos login']);
+ $adapter = $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'sophos_central')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'field_paths', json_encode([
+ 'custom:'.$customField->id => 'associatedPerson.viaLogin',
+ ]));
+ SyncAdapterConfig::put($instance->id, 'mapping.custom:'.$customField->id, 'custom:'.$customField->id);
+ $this->fakeSophos([[
+ $this->endpoint(id: 'ep-9', serial: 'C02LOGIN99') + [
+ 'associatedPerson' => ['name' => 'Alice Example', 'viaLogin' => 'alice-mbp\\alice'],
+ ],
+ ]]);
+
+ $record = iterator_to_array($adapter->pull(), false)[0];
+
+ $this->assertSame('alice-mbp\\alice', $record->extra['custom:'.$customField->id]);
+ $this->assertSame('Alice Example', $record->extra['sophos_last_user']);
+ }
+
+ public function test_admin_defined_extras_join_the_presets_in_the_mapping_picker()
+ {
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Sophos login']);
+ $adapter = $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'sophos_central')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'field_paths', json_encode([
+ 'custom:'.$customField->id => 'associatedPerson.viaLogin',
+ ]));
+
+ $extraFields = $adapter->extraFields();
+
+ $this->assertTrue($adapter->supportsAdminDefinedExtras());
+ $this->assertTrue($extraFields['custom:'.$customField->id]['admin_defined']);
+ $this->assertArrayHasKey('sophos_health', $extraFields);
+ $this->assertArrayHasKey('sophos_tamper_protection', $extraFields);
+ }
+
+ public function test_follows_next_key_across_pages()
+ {
+ $adapter = $this->configuredAdapter();
+ $this->fakeSophos([
+ [$this->endpoint(id: 'ep-1', serial: 'SERIAL-1'), $this->endpoint(id: 'ep-2', serial: 'SERIAL-2')],
+ [$this->endpoint(id: 'ep-3', serial: 'SERIAL-3')],
+ ]);
+
+ $records = iterator_to_array($adapter->pull(), false);
+
+ $this->assertCount(3, $records);
+ Http::assertSent(fn (Request $request) => str_starts_with($request->url(), self::DATA_HOST.'/endpoint/v1/endpoints')
+ && str_contains($request->url(), 'pageFromKey=page-2'));
+ }
+
+ public function test_sends_bearer_and_tenant_header_to_the_discovered_data_host()
+ {
+ $adapter = $this->configuredAdapter();
+ $this->fakeSophos([[$this->endpoint(id: 'ep-1', serial: 'SERIAL-1')]]);
+
+ iterator_to_array($adapter->pull(), false);
+
+ Http::assertSent(fn (Request $request) => str_starts_with($request->url(), self::DATA_HOST.'/endpoint/v1/endpoints')
+ && $request->hasHeader('Authorization', 'Bearer stub-bearer')
+ && $request->hasHeader('X-Tenant-ID', self::TENANT_ID)
+ && str_contains($request->url(), 'view=full'));
+ }
+
+ public function test_refuses_a_data_host_outside_sophos()
+ {
+ $adapter = $this->configuredAdapter();
+ Http::fake([
+ 'https://id.sophos.com/*' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ 'https://api.central.sophos.com/whoami/v1' => Http::response([
+ 'id' => self::TENANT_ID,
+ 'idType' => 'tenant',
+ 'apiHosts' => ['global' => 'https://api.central.sophos.com', 'dataRegion' => 'https://evil.example.com'],
+ ]),
+ '*' => Http::response([], 500),
+ ]);
+
+ try {
+ iterator_to_array($adapter->pull(), false);
+ $this->fail('Expected the pull to refuse a non-Sophos data host.');
+ } catch (RuntimeException $e) {
+ $this->assertStringContainsString('unexpected tenant id or data host', $e->getMessage());
+ }
+
+ Http::assertNotSent(fn (Request $request) => str_contains($request->url(), 'evil.example.com'));
+ }
+
+ public function test_refuses_partner_level_credentials()
+ {
+ $adapter = $this->configuredAdapter();
+ Http::fake([
+ 'https://id.sophos.com/*' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ 'https://api.central.sophos.com/whoami/v1' => Http::response([
+ 'id' => 'partner-1',
+ 'idType' => 'partner',
+ 'apiHosts' => ['global' => 'https://api.central.sophos.com'],
+ ]),
+ ]);
+
+ $this->expectException(RuntimeException::class);
+ $this->expectExceptionMessage('partner-level');
+ iterator_to_array($adapter->pull(), false);
+ }
+
+ public function test_endpoint_without_a_serial_falls_back_to_the_endpoint_id()
+ {
+ $adapter = $this->configuredAdapter();
+ $this->fakeSophos([[$this->endpoint(id: 'ep-no-serial', serial: null, hostname: 'no-serial-box')]]);
+
+ $records = iterator_to_array($adapter->pull(), false);
+
+ $this->assertCount(1, $records);
+ $this->assertSame('ep-no-serial', $records[0]->sourceId);
+ $this->assertNull($records[0]->hardwareSerial);
+ }
+
+ public function test_duplicate_serials_keep_the_most_recently_seen_endpoint()
+ {
+ $adapter = $this->configuredAdapter();
+ $this->fakeSophos([[
+ $this->endpoint(id: 'ep-old', serial: 'SAME-SERIAL', hostname: 'old-owner-mbp', lastSeen: '2025-03-27T10:00:00.000Z'),
+ $this->endpoint(id: 'ep-new', serial: 'SAME-SERIAL', hostname: 'new-owner-mbp', lastSeen: '2026-09-23T10:00:00.000Z'),
+ ]]);
+
+ $records = iterator_to_array($adapter->pull(), false);
+
+ $this->assertCount(1, $records);
+ $this->assertSame('new-owner-mbp', $records[0]->hostname);
+ $this->assertSame('ep-new', $records[0]->extra['sophos_endpoint_id']);
+ }
+
+ public function test_newest_record_is_chosen_by_date_not_by_text()
+ {
+ // As text, "12:00+02:00" sorts after "11:00Z", but as a moment in
+ // time it is 10:00 UTC, an hour earlier. A record with no timestamp
+ // counts as the oldest.
+ $adapter = $this->configuredAdapter();
+ $this->fakeSophos([[
+ $this->endpoint(id: 'ep-offset', serial: 'SAME-SERIAL', hostname: 'earlier', lastSeen: '2026-09-23T12:00:00+02:00'),
+ $this->endpoint(id: 'ep-utc', serial: 'SAME-SERIAL', hostname: 'later', lastSeen: '2026-09-23T11:00:00.000Z'),
+ $this->endpoint(id: 'ep-none', serial: 'SAME-SERIAL', hostname: 'never-seen', lastSeen: ''),
+ ]]);
+
+ $records = iterator_to_array($adapter->pull(), false);
+
+ $this->assertCount(1, $records);
+ $this->assertSame('later', $records[0]->hostname);
+ }
+
+ public function test_os_name_and_version_are_split_per_platform()
+ {
+ $adapter = $this->configuredAdapter(endpointTypes: ['computer', 'server']);
+ $this->fakeSophos([[
+ array_merge($this->endpoint(id: 'ep-mac', serial: 'MAC-1'),
+ ['os' => ['platform' => 'macOS', 'name' => 'macOS Sonoma 14', 'majorVersion' => 14, 'minorVersion' => 6]]),
+ array_merge($this->endpoint(id: 'ep-ubuntu', serial: 'LNX-1', type: 'server'),
+ ['os' => ['platform' => 'linux', 'name' => 'Ubuntu 24.04.3 LTS', 'majorVersion' => 24, 'minorVersion' => 4]]),
+ array_merge($this->endpoint(id: 'ep-ubuntu-bare', serial: 'LNX-2', type: 'server'),
+ ['os' => ['platform' => 'linux', 'name' => 'Ubuntu 22.04.2 LTS']]),
+ array_merge($this->endpoint(id: 'ep-win', serial: 'WIN-1'),
+ ['os' => ['platform' => 'windows', 'name' => 'Windows 11 Pro ', 'majorVersion' => 11, 'minorVersion' => 0, 'build' => 26100]]),
+ ]]);
+
+ $byId = collect(iterator_to_array($adapter->pull(), false))->keyBy('sourceId');
+
+ // macOS: the numbers are more precise than the name.
+ $this->assertSame(['macOS Sonoma', '14.6'], [$byId['MAC-1']->os, $byId['MAC-1']->osVersion]);
+ // Linux: the numbers drop Ubuntu's leading zero, so the name wins.
+ $this->assertSame(['Ubuntu LTS', '24.04.3'], [$byId['LNX-1']->os, $byId['LNX-1']->osVersion]);
+ $this->assertSame(['Ubuntu LTS', '22.04.2'], [$byId['LNX-2']->os, $byId['LNX-2']->osVersion]);
+ // Windows: the 11 is part of the product name; the numbers carry the build.
+ $this->assertSame(['Windows 11 Pro', '11.0.26100'], [$byId['WIN-1']->os, $byId['WIN-1']->osVersion]);
+ }
+
+ public function test_pulls_computers_only_by_default()
+ {
+ $adapter = $this->configuredAdapter();
+ $this->fakeSophos([[
+ $this->endpoint(id: 'ep-mac', serial: 'MAC-1'),
+ $this->endpoint(id: 'ep-srv', serial: 'SRV-1', type: 'server', platform: 'linux', osName: 'Ubuntu 24.04.3 LTS'),
+ ]]);
+
+ $records = iterator_to_array($adapter->pull(), false);
+
+ $this->assertSame(['MAC-1'], array_map(fn ($r) => $r->sourceId, $records));
+ }
+
+ public function test_type_selection_and_cloud_skip_filter_endpoints()
+ {
+ $adapter = $this->configuredAdapter(endpointTypes: ['computer', 'server'], skipCloud: true);
+ $this->fakeSophos([[
+ $this->endpoint(id: 'ep-mac', serial: 'MAC-1'),
+ $this->endpoint(id: 'ep-laptop', serial: 'LNX-LAPTOP', type: 'server', platform: 'linux', osName: 'Ubuntu 25.10'),
+ $this->endpoint(id: 'ep-aws', serial: 'EC2-1', type: 'server', platform: 'linux', osName: 'Ubuntu 24.04.3 LTS')
+ + ['cloud' => ['provider' => 'aws', 'instanceId' => 'i-0123']],
+ ]]);
+
+ $records = iterator_to_array($adapter->pull(), false);
+
+ $this->assertEqualsCanonicalizing(['MAC-1', 'LNX-LAPTOP'], array_map(fn ($r) => $r->sourceId, $records));
+ $linux = collect($records)->firstWhere('sourceId', 'LNX-LAPTOP');
+ $this->assertSame('Linux server (model unknown)', $linux->hardwareModel);
+ }
+
+ public function test_adopts_an_existing_asset_by_serial_when_the_toggle_is_on()
+ {
+ $adapter = $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'sophos_central')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'adopt_by_serial', '1');
+ $existing = Asset::factory()->create(['serial' => 'ADOPT-ME-001', 'name' => 'pre-existing']);
+
+ $this->fakeSophos([[$this->endpoint(id: 'ep-1', serial: 'ADOPT-ME-001', hostname: 'sophos-sees-it')]]);
+
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $this->assertDatabaseCount('assets', 1);
+ $this->assertDatabaseHas('asset_external_sources', [
+ 'asset_id' => $existing->id,
+ 'source' => 'sophos_central',
+ 'external_id' => 'ADOPT-ME-001',
+ ]);
+ }
+
+ public function test_model_mapping_on_skip_keeps_an_adopted_assets_real_model()
+ {
+ // The setup for when another adapter already supplies real models:
+ // adopt by serial, with the model mapping on skip. The adopted asset
+ // keeps its model, and a device only Sophos sees still comes in with
+ // the placeholder.
+ $adapter = $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'sophos_central')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'adopt_by_serial', '1');
+ SyncAdapterConfig::put($instance->id, 'mapping.model', 'skip');
+ $existing = Asset::factory()->create(['serial' => 'ADOPT-ME-001']);
+ $realModelId = $existing->model_id;
+
+ $this->fakeSophos([[
+ $this->endpoint(id: 'ep-1', serial: 'ADOPT-ME-001'),
+ $this->endpoint(id: 'ep-2', serial: 'SOPHOS-ONLY-1'),
+ ]]);
+
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $this->assertSame($realModelId, $existing->fresh()->model_id);
+ $created = Asset::where('serial', 'SOPHOS-ONLY-1')->firstOrFail();
+ $this->assertSame('macOS computer (model unknown)', $created->model->name);
+ }
+
+ public function test_a_reinstalled_endpoint_stays_on_the_same_asset()
+ {
+ // Sophos gives a reinstall a new endpoint id. Keying on the serial
+ // keeps the machine on the asset the first sync created.
+ $adapter = $this->configuredAdapter();
+
+ // Two separate pulls: each page is its own run, so neither carries a nextKey.
+ $this->fakeSophos([
+ [$this->endpoint(id: 'ep-before', serial: 'REINSTALLED-1', hostname: 'before')],
+ [$this->endpoint(id: 'ep-after', serial: 'REINSTALLED-1', hostname: 'after')],
+ ], chained: false);
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $this->assertDatabaseCount('assets', 1);
+ $this->assertDatabaseCount('asset_external_sources', 1);
+ $this->assertDatabaseHas('assets', ['serial' => 'REINSTALLED-1', 'name' => 'after']);
+ }
+
+ public function test_settings_page_renders_the_sophos_schema_fields()
+ {
+ $html = $this->actingAs(User::factory()->superuser()->create())
+ ->get(route('settings.adapters.index'))
+ ->assertOk()
+ ->getContent();
+
+ $this->assertStringContainsString('Sophos Central', $html);
+ $this->assertMatchesRegularExpression('/name="sophos_central_client_id"/', $html);
+ $this->assertMatchesRegularExpression('/name="sophos_central_client_secret"/', $html);
+ // The Custom Extras widget renders, since the adapter opts in.
+ $this->assertStringContainsString('sophos_central_field_paths', $html);
+ }
+
+ /**
+ * @param array<int, string> $endpointTypes
+ */
+ private function configuredAdapter(array $endpointTypes = [], bool $skipCloud = false): SophosCentralAdapter
+ {
+ $instance = SyncAdapterInstance::where('slug', 'sophos_central')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'client_id', 'stub-client');
+ SyncAdapterConfig::put($instance->id, 'client_secret', Crypt::encrypt('fake-secret'));
+ if ($endpointTypes !== []) {
+ SyncAdapterConfig::put($instance->id, 'endpoint_types', json_encode($endpointTypes));
+ }
+ if ($skipCloud) {
+ SyncAdapterConfig::put($instance->id, 'skip_cloud_instances', '1');
+ }
+
+ return new SophosCentralAdapter($instance->fresh());
+ }
+
+ /**
+ * Fake the token, whoami and endpoint calls. Each element of $pages is
+ * one page of endpoints. Chained pages carry a nextKey to the next one
+ * (one pull, several pages); unchained pages each answer a separate pull.
+ *
+ * @param array<int, array<int, array<string, mixed>>> $pages
+ */
+ private function fakeSophos(array $pages, bool $chained = true): void
+ {
+ $sequence = Http::sequence();
+ foreach ($pages as $i => $items) {
+ $isLast = ! $chained || $i === array_key_last($pages);
+ $sequence->push([
+ 'items' => $items,
+ 'pages' => array_filter([
+ 'fromKey' => ($i === 0 || ! $chained) ? null : 'page-'.($i + 1),
+ 'nextKey' => $isLast ? null : 'page-'.($i + 2),
+ 'size' => count($items),
+ 'maxSize' => 500,
+ ], fn ($value) => $value !== null),
+ ]);
+ }
+
+ Http::fake([
+ 'https://id.sophos.com/*' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ 'https://api.central.sophos.com/whoami/v1' => Http::response([
+ 'id' => self::TENANT_ID,
+ 'idType' => 'tenant',
+ 'apiHosts' => ['global' => 'https://api.central.sophos.com', 'dataRegion' => self::DATA_HOST],
+ ]),
+ self::DATA_HOST.'/endpoint/v1/endpoints*' => $sequence,
+ ]);
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ private function endpoint(
+ string $id,
+ ?string $serial,
+ string $hostname = 'host',
+ string $type = 'computer',
+ string $platform = 'macOS',
+ string $osName = 'macOS Tahoe 26.6',
+ string $lastSeen = '2026-09-23T10:00:00.000Z',
+ ): array {
+ return array_filter([
+ 'id' => $id,
+ 'type' => $type,
+ 'hostname' => $hostname,
+ 'serialNumber' => $serial,
+ 'os' => ['isServer' => $type === 'server', 'platform' => $platform, 'name' => $osName, 'majorVersion' => 26, 'minorVersion' => 6],
+ 'lastSeenAt' => $lastSeen,
+ ], fn ($value) => $value !== null);
+ }
+}