Skip to content

A free open source IT asset/license management system

Fixed #19955 - use v2 Addigy API

snipe539f47050d18
diff --git a/app/SyncAdapters/Addigy/AddigyAdapter.php b/app/SyncAdapters/Addigy/AddigyAdapter.php
index 738e76c6fe..5de84fe23c 100644
--- a/app/SyncAdapters/Addigy/AddigyAdapter.php
+++ b/app/SyncAdapters/Addigy/AddigyAdapter.php
@@ -2,18 +2,59 @@
namespace App\SyncAdapters\Addigy;
+use App\Models\Asset;
+use App\Models\AssetExternalSource;
+use App\Models\SyncAdapterConfig;
+use App\Models\User;
use App\SyncAdapters\HostInventoryRecord;
+use App\SyncAdapters\PushableAdapter;
use App\SyncAdapters\SyncAdapter;
use Carbon\Carbon;
use Illuminate\Support\Arr;
+use Illuminate\Support\Facades\Log;
/**
- * Addigy adapter. Pulls device inventory from the Addigy API and
- * normalizes it into HostInventoryRecord objects. Uses Addigy's
- * client-id + client-secret header pair (not bearer-token auth).
+ * Addigy adapter. Pulls device inventory from Addigy API v2 and
+ * normalizes it into HostInventoryRecord objects. Uses Addigy's single
+ * `x-api-key` header (v2) rather than the retired v1 client-id +
+ * client-secret pair.
+ *
+ * Push surface: Snipe-IT asset name -> Addigy device name via the Set
+ * Device Name MDM command. End-user assignment (Snipe-IT assigned
+ * user -> Addigy end-user tied to the device) is opt-in per instance
+ * because it requires an Addigy end-user ID lookup per push.
*/
-class AddigyAdapter extends SyncAdapter
+class AddigyAdapter extends SyncAdapter implements PushableAdapter
{
+ /**
+ * Device-fact identifiers to request on every `POST /devices` call.
+ * v2's response shape is a `facts` map keyed by identifier (each
+ * value is `{type, value}`), so the client has to tell the server
+ * up front which facts it wants. These names come from the v2
+ * OpenAPI vocabulary (`AuditFilter.audit_field` example uses
+ * `device_model_name`) plus the matching v1 field names where
+ * Addigy preserved them. If a tenant renames or lacks a built-in
+ * fact, its key is simply missing from the response map and
+ * normalize() reads null.
+ *
+ * @var list<string>
+ */
+ private const DESIRED_FACTS = [
+ 'device_name',
+ 'serial_number',
+ 'device_model_name',
+ 'network_mac_address',
+ 'network_ip_address',
+ 'os_type',
+ 'os_version',
+ 'last_online_at',
+ 'asset_tag',
+ 'user_email',
+ 'policy_id',
+ 'is_supervised',
+ 'agent_version',
+ ];
+
public static function typeLabel(): string
{
return 'Addigy';
@@ -29,24 +70,30 @@ class AddigyAdapter extends SyncAdapter
return 'https://api.addigy.com/api/v2/documentation/';
}
- public function baseUrlPlaceholder(): ?string
+ /**
+ * Addigy v2's host is fixed at api.addigy.com, so the admin doesn't
+ * type a URL. The client hardcodes the base URL.
+ */
+ public function usesConfigurableUrl(): bool
{
- return 'https://prod.addigy.com';
+ return false;
}
public function settingsSchema(): array
{
return [
[
- 'key' => 'key_id',
- 'label' => trans('admin/settings/sync_adapters.label_client_id'),
- 'help' => trans('admin/settings/sync_adapters.addigy_key_id_help'),
+ 'key' => 'api_key',
+ 'label' => trans('admin/settings/sync_adapters.label_api_key'),
+ 'secret' => true,
+ 'help' => trans('admin/settings/sync_adapters.addigy_api_key_help'),
],
[
- 'key' => 'key_secret',
- 'label' => trans('admin/settings/sync_adapters.label_client_secret'),
- 'secret' => true,
- 'help' => trans('admin/settings/sync_adapters.addigy_key_secret_help'),
+ 'key' => 'push_end_user_assignment',
+ 'label' => trans('admin/settings/sync_adapters.addigy_push_end_user_assignment_label'),
+ 'type' => 'checkbox',
+ 'required' => false,
+ 'help' => trans('admin/settings/sync_adapters.addigy_push_end_user_assignment_help'),
],
];
}
@@ -72,11 +119,7 @@ class AddigyAdapter extends SyncAdapter
public function fetchGroups(): array
{
- $client = new AddigyClient(
- baseUrl: $this->url(),
- clientId: $this->credential('key_id'),
- clientSecret: $this->credential('key_secret'),
- );
+ $client = $this->makeClient();
return array_map(
fn (array $policy) => [
@@ -89,21 +132,26 @@ class AddigyAdapter extends SyncAdapter
public function pull(): iterable
{
- $client = new AddigyClient(
- baseUrl: $this->url(),
- clientId: $this->credential('key_id'),
- clientSecret: $this->credential('key_secret'),
- );
+ $client = $this->makeClient();
+
+ foreach ($client->devices(self::DESIRED_FACTS) as $device) {
+ // Cache orgid off the first DeviceAudit we see so push can
+ // target `/o/{orgid}/end-users/*` without the admin
+ // supplying it. v2 has no "get my current org" endpoint,
+ // but every DeviceAudit carries the field. The write
+ // short-circuits when nothing changed so repeated pulls
+ // don't thrash the config table.
+ $this->cacheOrganizationId((string) ($device['orgid'] ?? ''));
- foreach ($client->devices() as $device) {
yield $this->normalize($device);
}
}
/**
- * Convert an Addigy device payload into the normalized record
- * shape. Addigy's `agentid` is stable per enrolled device and is
- * what we key asset_external_sources on.
+ * Convert an Addigy v2 DeviceAudit payload into the normalized
+ * record shape. `agentid` is stable per enrolled device and is
+ * what we key asset_external_sources on. Everything else lives
+ * in the `facts` map keyed by identifier.
*
* @param array<string, mixed> $device
*/
@@ -112,34 +160,276 @@ class AddigyAdapter extends SyncAdapter
return new HostInventoryRecord(
sourceKey: $this->name(),
sourceId: (string) Arr::get($device, 'agentid'),
- hostname: Arr::get($device, 'name'),
- hardwareSerial: Arr::get($device, 'serial_number'),
- hardwareModel: Arr::get($device, 'hardware_model'),
+ hostname: self::fact($device, 'device_name'),
+ hardwareSerial: self::fact($device, 'serial_number'),
+ hardwareModel: self::fact($device, 'device_model_name'),
manufacturer: 'Apple',
- primaryMac: Arr::get($device, 'network_mac_address'),
- primaryIp: Arr::get($device, 'network_ip_address'),
- os: Arr::get($device, 'os_type'),
- osVersion: Arr::get($device, 'os_version'),
- lastSeen: $this->parseTimestamp(Arr::get($device, 'last_online')),
+ primaryMac: self::fact($device, 'network_mac_address'),
+ primaryIp: self::fact($device, 'network_ip_address'),
+ os: self::fact($device, 'os_type'),
+ osVersion: self::fact($device, 'os_version'),
+ lastSeen: $this->parseTimestamp(self::fact($device, 'last_online_at')),
// Addigy's "asset_tag" is the operator-assigned tag from
// their inventory settings, distinct from the Snipe-IT one.
- assetTag: Arr::get($device, 'asset_tag'),
- assignedUserEmail: Arr::get($device, 'user_email'),
- vendorGroupId: Arr::has($device, 'policy_id') ? (string) Arr::get($device, 'policy_id') : null,
+ assetTag: self::fact($device, 'asset_tag'),
+ assignedUserEmail: self::fact($device, 'user_email'),
+ vendorGroupId: ($policyId = self::fact($device, 'policy_id')) !== null ? (string) $policyId : null,
extra: [
- 'addigy_policy_id' => Arr::get($device, 'policy_id'),
- 'addigy_supervised' => Arr::get($device, 'is_supervised'),
- 'addigy_agent_version' => Arr::get($device, 'agent_version'),
+ 'addigy_policy_id' => self::fact($device, 'policy_id'),
+ 'addigy_supervised' => self::fact($device, 'is_supervised'),
+ 'addigy_agent_version' => self::fact($device, 'agent_version'),
],
);
}
+ /**
+ * Pull a single fact value out of a v2 DeviceAudit payload.
+ * Returns null when the fact is missing, the server reported an
+ * error_msg on it, or the value is explicitly null.
+ */
+ private static function fact(array $device, string $identifier): mixed
+ {
+ $fact = Arr::get($device, 'facts.'.$identifier);
+ if (! is_array($fact)) {
+ return null;
+ }
+ if (! empty($fact['error_msg'])) {
+ return null;
+ }
+
+ return $fact['value'] ?? null;
+ }
+
private function parseTimestamp(mixed $value): ?Carbon
{
if ($value === null || $value === '') {
return null;
}
+ if (is_numeric($value)) {
+ // Addigy occasionally emits timestamps as Unix epoch
+ // seconds (seen on last_online_at). Treat anything numeric
+ // as epoch so Carbon::parse doesn't try to interpret it as
+ // a year.
+ return Carbon::createFromTimestamp((int) $value);
+ }
+
return Carbon::parse($value);
}
+
+ /**
+ * Push is always available on a configured instance. Both
+ * Set-Device-Name and end-user assignment use the same API key as
+ * pull, so if pull works push works too.
+ */
+ public function canPush(): bool
+ {
+ return true;
+ }
+
+ /**
+ * Addigy exposes no device-level freeform notes field writable via
+ * the API, so composed-notes push has no target here. Returning
+ * null disables the composed-notes section of the settings UI.
+ */
+ public function notesFieldTarget(): ?string
+ {
+ return null;
+ }
+
+ /**
+ * Hostname is the only standard field Addigy accepts writes on
+ * (via the Set Device Name MDM command). Narrowing the pushable
+ * set hides push/both from the direction picker for every other
+ * standard field so the admin can't opt into a push that would
+ * silently drop at payload build time.
+ */
+ public function pushableFields(): array
+ {
+ return ['hostname'];
+ }
+
+ /**
+ * Push Snipe-IT-authoritative fields to Addigy. Two separate
+ * surfaces, each toggled independently:
+ *
+ * 1. Hostname -> Set Device Name MDM command, when `hostname` is
+ * push-directed in the mapping UI.
+ * 2. Assigned user -> Addigy end-user device assignment, when
+ * the per-instance `push_end_user_assignment` flag is on and
+ * the asset has an assigned user with a resolvable email.
+ *
+ * The two don't share a payload (two different endpoints), so this
+ * doesn't delegate to pushViaSinglePayload. Return true when at
+ * least one surface actually fired.
+ *
+ * @param array<int, string> $changedFields
+ */
+ public function push(Asset $asset, array $changedFields = []): bool
+ {
+ $hostnameConfigured = $this->shouldPushHostname($changedFields);
+ $endUserConfigured = $this->pushEndUserAssignmentEnabled() && $this->assignedUserChanged($changedFields);
+
+ if (! $hostnameConfigured && ! $endUserConfigured) {
+ Log::channel('sync-adapters')->info(
+ $this->name().' push: skipped asset '.$asset->id
+ .' (asset_tag='.($asset->asset_tag ?? '(none)').') - no push surface configured.',
+ );
+
+ return false;
+ }
+
+ // Direct external-source lookup. Base class pushPrologue bakes
+ // in a pushDirectedFields check that assumes mapping-field
+ // semantics, which end-user assignment sits outside, so we
+ // read the external_source row ourselves.
+ $externalSource = AssetExternalSource::query()
+ ->where('asset_id', $asset->id)
+ ->where('source', $this->name())
+ ->first();
+
+ if ($externalSource === null) {
+ Log::channel('sync-adapters')->info(
+ $this->name().' push: skipped asset '.$asset->id
+ .' (asset_tag='.($asset->asset_tag ?? '(none)').') - no asset_external_sources row for this adapter instance.',
+ );
+
+ return false;
+ }
+
+ $client = $this->makeClient();
+ $dispatched = false;
+
+ if ($hostnameConfigured) {
+ $dispatched = $this->pushHostname($asset, $externalSource, $client) || $dispatched;
+ }
+
+ if ($endUserConfigured) {
+ $dispatched = $this->pushEndUserAssignment($asset, $externalSource, $client) || $dispatched;
+ }
+
+ return $dispatched;
+ }
+
+ private function shouldPushHostname(array $changedFields): bool
+ {
+ if (! in_array('hostname', $this->pushDirectedFields(), true)) {
+ return false;
+ }
+
+ // Respect the pushPrologue intersection check: if the caller
+ // handed us a specific changedFields set, hostname has to be
+ // in it. Empty set means "push everything directed push" so
+ // we still fire.
+ return $changedFields === [] || in_array('hostname', $changedFields, true);
+ }
+
+ private function pushHostname(Asset $asset, AssetExternalSource $externalSource, AddigyClient $client): bool
+ {
+ $name = $asset->name;
+ if ($name === null || $name === '') {
+ return false;
+ }
+
+ if ($this->isPushDryRun()) {
+ Log::channel('sync-adapters')->info(
+ $this->name().' push [dry-run]: would set Addigy device '.$externalSource->external_id.' name='.$name,
+ );
+
+ return true;
+ }
+
+ $client->setDeviceName((string) $externalSource->external_id, (string) $name);
+
+ Log::channel('sync-adapters')->info(
+ $this->name().' push: set Addigy device '.$externalSource->external_id.' name='.$name,
+ );
+
+ return true;
+ }
+
+ private function pushEndUserAssignmentEnabled(): bool
+ {
+ return (bool) SyncAdapterConfig::get($this->instance->id, 'push_end_user_assignment');
+ }
+
+ /**
+ * Snipe-IT doesn't surface "assigned user" in changedFields today
+ * (it's not a mapping field). Treat an empty changedFields set as
+ * "push everything configured" and let the end-user branch run.
+ * When the caller sends a specific set, only run if `assigned_to`
+ * is in it so a hostname-only save doesn't re-check end-user state.
+ */
+ private function assignedUserChanged(array $changedFields): bool
+ {
+ return $changedFields === [] || in_array('assigned_to', $changedFields, true);
+ }
+
+ private function pushEndUserAssignment(Asset $asset, AssetExternalSource $externalSource, AddigyClient $client): bool
+ {
+ $orgId = (string) (SyncAdapterConfig::get($this->instance->id, 'cached_orgid') ?? '');
+ if ($orgId === '') {
+ Log::channel('sync-adapters')->info(
+ $this->name().' push: skipped end-user assignment for asset '.$asset->id
+ .' - cached_orgid not yet captured. Run a pull first.',
+ );
+
+ return false;
+ }
+
+ if (! ($asset->assignedTo instanceof User) || empty($asset->assignedTo->email)) {
+ Log::channel('sync-adapters')->info(
+ $this->name().' push: skipped end-user assignment for asset '.$asset->id
+ .' - no assigned user with an email on the Snipe-IT side.',
+ );
+
+ return false;
+ }
+
+ $email = (string) $asset->assignedTo->email;
+
+ if ($this->isPushDryRun()) {
+ Log::channel('sync-adapters')->info(
+ $this->name().' push [dry-run]: would resolve Addigy end user by email='.$email
+ .' and assign to device '.$externalSource->external_id,
+ );
+
+ return true;
+ }
+
+ $endUserId = $client->findEndUserIdByEmail($orgId, $email);
+ if ($endUserId === null) {
+ Log::channel('sync-adapters')->info(
+ $this->name().' push: skipped end-user assignment for asset '.$asset->id
+ .' - no unique Addigy end-user match for email='.$email,
+ );
+
+ return false;
+ }
+
+ $client->assignDeviceToEndUser($orgId, (string) $externalSource->external_id, $endUserId);
+
+ Log::channel('sync-adapters')->info(
+ $this->name().' push: assigned Addigy device '.$externalSource->external_id
+ .' to end-user '.$endUserId.' (email='.$email.')',
+ );
+
+ return true;
+ }
+
+ private function cacheOrganizationId(string $orgId): void
+ {
+ if ($orgId === '') {
+ return;
+ }
+ if (SyncAdapterConfig::get($this->instance->id, 'cached_orgid') === $orgId) {
+ return;
+ }
+ SyncAdapterConfig::put($this->instance->id, 'cached_orgid', $orgId);
+ }
+
+ private function makeClient(): AddigyClient
+ {
+ return new AddigyClient(apiKey: $this->credential('api_key'));
+ }
}
diff --git a/app/SyncAdapters/Addigy/AddigyClient.php b/app/SyncAdapters/Addigy/AddigyClient.php
index cdd6416c1b..3ed882e3fb 100644
--- a/app/SyncAdapters/Addigy/AddigyClient.php
+++ b/app/SyncAdapters/Addigy/AddigyClient.php
@@ -7,52 +7,94 @@ use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
/**
- * Thin wrapper around the Addigy API. Owns auth for the devices
- * endpoint the sync adapter uses. Yields raw decoded JSON, no
+ * Thin wrapper around the Addigy API v2. Handles auth for the pull +
+ * push endpoints the sync adapter uses. Yields raw decoded JSON, no
* normalization (that's the adapter's job).
*
- * Auth model: a header pair generated in the Addigy admin console
- * under Integrations -> Addigy API. Both are treated as secrets by
- * the framework and pass in the `client-id` and `client-secret`
- * headers on every request (Addigy's own naming, lowercase). Distinct
- * from the bearer-token pattern the other adapters use.
+ * Auth model: a single API key generated in the Addigy admin console
+ * under Integrations -> Addigy API. Passed in the `x-api-key` header
+ * on every request. Replaces v1's client-id + client-secret header
+ * pair, which Addigy retired in June 2026.
*
- * The v1 devices endpoint returns the full device list in one call,
- * so this client is single-request. Large tenants (thousands of
- * devices) can extend later to page through /api/v2/devices with the
- * cursor-based response shape.
+ * The devices listing endpoint is a paginated POST ("Universal Search
+ * Devices"). We page by `page` + `per_page` and dig values out of each
+ * record's `facts` map keyed by fact identifier. The adapter owns the
+ * list of fact identifiers it wants. This client just hands them to
+ * `desired_fact_identifiers` on the request body and streams the
+ * decoded response pages back.
*
- * Addigy API reference: https://addigy.freshdesk.com/support/solutions/folders/8000078965
+ * Addigy API reference: https://api.addigy.com/api/v2/documentation/
*/
class AddigyClient
{
use RetriesTransientHttpErrors;
+ /**
+ * Addigy v2 lives at a fixed host. The admin doesn't configure
+ * the base URL on the adapter form (usesConfigurableUrl() = false),
+ * so we hardcode it here rather than threading it through the
+ * constructor from a non-existent credential.
+ */
+ private const BASE_URL = 'https://api.addigy.com/api/v2';
+
+ /**
+ * Default page size for the paginated POST /devices endpoint.
+ * 100 matches what Addigy's console uses and keeps each page small
+ * enough to decode without pressure on the PHP memory limit.
+ */
+ private const DEFAULT_PER_PAGE = 100;
+
public function __construct(
- private readonly string $baseUrl,
- private readonly string $clientId,
- private readonly string $clientSecret,
+ private readonly string $apiKey,
) {}
/**
- * List every enrolled device in the Addigy tenant. Returned as a
- * generator for consistency with the other adapters, even though
- * the underlying endpoint is single-response.
+ * List every enrolled device in the Addigy tenant. Yields decoded
+ * device records (DeviceAudit shape: `agentid`, `orgid`,
+ * `audit_date`, `facts` keyed by identifier) one at a time so the
+ * caller can normalize + persist each without buffering the whole
+ * tenant.
*
+ * @param list<string> $desiredFactIdentifiers fact names to request on every device
* @return iterable<array<string, mixed>>
*/
- public function devices(): iterable
+ public function devices(array $desiredFactIdentifiers): iterable
{
- $response = $this->request()
- ->get('/api/devices')
- ->throw()
- ->json();
+ $page = 1;
+
+ while (true) {
+ $response = $this->request()
+ ->post('/devices', [
+ 'desired_fact_identifiers' => $desiredFactIdentifiers,
+ 'page' => $page,
+ 'per_page' => self::DEFAULT_PER_PAGE,
+ ])
+ ->throw()
+ ->json();
- // v1 returns a bare array of device objects on this endpoint.
- $devices = is_array($response) ? $response : [];
+ $items = is_array($response['items'] ?? null) ? $response['items'] : [];
- foreach ($devices as $device) {
- yield $device;
+ if ($items === []) {
+ return;
+ }
+
+ foreach ($items as $device) {
+ yield $device;
+ }
+
+ // Metadata.page_count is total number of pages. Stop when
+ // we've drained the last one. Fallback: if the server
+ // doesn't echo page_count, break when a page comes back
+ // with fewer items than we asked for.
+ $pageCount = (int) ($response['metadata']['page_count'] ?? 0);
+ if ($pageCount > 0 && $page >= $pageCount) {
+ return;
+ }
+ if ($pageCount === 0 && count($items) < self::DEFAULT_PER_PAGE) {
+ return;
+ }
+
+ $page++;
}
}
@@ -62,28 +104,108 @@ class AddigyClient
* Policies are Addigy's device-grouping concept. MSPs often use
* them as customer proxies.
*
+ * v2 moved policy listing to a POST with a filter body. An empty
+ * `policies` array in the body returns every policy.
+ *
* @return array<int, array<string, mixed>>
*/
public function policies(): array
{
$response = $this->request()
- ->get('/api/policies')
+ ->post('/oa/policies/query', ['policies' => []])
->throw()
->json();
+ if (is_array($response['items'] ?? null)) {
+ return $response['items'];
+ }
+
return is_array($response) ? $response : [];
}
+ /**
+ * Rename an Addigy device via the Set Device Name MDM command.
+ * Addigy's doc: "available only on supervised devices or devices
+ * running macOS 10.10 or later". On macOS the command sets only
+ * the computer name and local hostname. iOS/iPadOS requires
+ * supervision. Addigy's response is an MDM command receipt, not a
+ * synchronous device state change.
+ */
+ public function setDeviceName(string $agentId, string $deviceName): void
+ {
+ $this->request()
+ ->post('/mdm/settings/device/name', [
+ 'agent_id' => $agentId,
+ 'device_name' => $deviceName,
+ ])
+ ->throw();
+ }
+
+ /**
+ * Resolve an Addigy end-user by email. Addigy's end-user query
+ * takes a free-form `search` string so an exact-email match isn't
+ * guaranteed. We filter the paged response client-side to pick
+ * only entries whose `emails[*].value` matches the queried email
+ * exactly (case-insensitive), returning the single id when
+ * exactly one survives and null for zero or multi-match. The
+ * caller logs the skip reason.
+ */
+ public function findEndUserIdByEmail(string $organizationId, string $email): ?string
+ {
+ $response = $this->request()
+ ->post('/o/'.$organizationId.'/end-users/query', [
+ 'page' => 1,
+ 'per_page' => 100,
+ 'query' => ['search' => $email],
+ ])
+ ->throw()
+ ->json();
+
+ $items = is_array($response['items'] ?? null) ? $response['items'] : [];
+
+ $matches = [];
+ foreach ($items as $item) {
+ if (! is_array($item) || empty($item['id'])) {
+ continue;
+ }
+ $emails = is_array($item['emails'] ?? null) ? $item['emails'] : [];
+ foreach ($emails as $entry) {
+ $value = is_array($entry) ? ($entry['value'] ?? null) : null;
+ if (is_string($value) && strcasecmp($value, $email) === 0) {
+ $matches[] = (string) $item['id'];
+ break;
+ }
+ }
+ }
+
+ $unique = array_values(array_unique($matches));
+
+ return count($unique) === 1 ? $unique[0] : null;
+ }
+
+ /**
+ * Assign a device to an Addigy end user. Addigy requires both the
+ * agent id (device) and the end-user id (resolved separately via
+ * findEndUserIdByEmail).
+ */
+ public function assignDeviceToEndUser(string $organizationId, string $agentId, string $endUserId): void
+ {
+ $this->request()
+ ->post('/o/'.$organizationId.'/end-users/devices', [
+ 'agent_id' => $agentId,
+ 'end_user_id' => $endUserId,
+ ])
+ ->throw();
+ }
+
private function request(): PendingRequest
{
return $this->withTransientRetry(
- Http::baseUrl(rtrim($this->baseUrl, '/'))
+ Http::baseUrl(self::BASE_URL)
->withOptions(['allow_redirects' => false])
- ->withHeaders([
- 'client-id' => $this->clientId,
- 'client-secret' => $this->clientSecret,
- ])
+ ->withHeaders(['x-api-key' => $this->apiKey])
->acceptJson()
+ ->asJson()
->timeout(30)
);
}
diff --git a/app/SyncAdapters/SyncAdapter.php b/app/SyncAdapters/SyncAdapter.php
index 2afd8c2051..2e3220b2c1 100644
--- a/app/SyncAdapters/SyncAdapter.php
+++ b/app/SyncAdapters/SyncAdapter.php
@@ -153,14 +153,17 @@ abstract class SyncAdapter
}
/**
- * Type slug -> {label, docs_url} catalog. Powers the help pane's
- * table of supported adapters so admins can jump into either the
- * "Add adapter" modal with the type pre-selected or the docs page
- * (vendor's own for named adapters, Snipe-IT's own for Custom
- * HTTP). docs_url is null for adapters whose vendor has no stable
- * public reference URL or gates its docs behind a login.
+ * Type slug -> {label, docs_url, direction} catalog. Powers the
+ * help pane's list of supported adapters so admins can jump into
+ * either the "Add adapter" modal with the type pre-selected or
+ * the docs page (vendor's own for named adapters, Snipe-IT's own
+ * for Custom HTTP). docs_url is null for adapters whose vendor
+ * has no stable public reference URL or gates its docs behind a
+ * login. direction is derived from whether the class implements
+ * PushableAdapter so the catalog UI reflects reality without a
+ * separate list for admins or docs to drift from.
*
- * @return array<string, array{label: string, docs_url: ?string}>
+ * @return array<string, array{label: string, docs_url: ?string, direction: 'pull'|'both'}>
*/
public static function typeCatalog(): array
{
@@ -169,6 +172,7 @@ abstract class SyncAdapter
$out[$slug] = [
'label' => $class::typeLabel(),
'docs_url' => $class::docsUrl(),
+ 'direction' => is_a($class, PushableAdapter::class, true) ? 'both' : 'pull',
];
}
@@ -911,7 +915,7 @@ abstract class SyncAdapter
SyncAdapterConfig::put(
$this->instance->id,
'create_snipeit_assets_on_pull',
- $request->boolean($slug . '_create_snipeit_assets_on_pull') ? '1' : '0',
+ $request->boolean($slug.'_create_snipeit_assets_on_pull') ? '1' : '0',
);
// Per-device enrichment opt-in. Only persisted for adapters
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index ec3e89cc59..2d44476ff8 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -36,6 +36,9 @@ return [
'catalog_add_tooltip' => 'Add new',
'catalog_docs_link_label' => 'API docs for :adapter',
'catalog_docs_none' => 'No public API docs available for this adapter.',
+ 'catalog_direction_pull' => 'Pull',
+ 'catalog_direction_both' => 'Pull + Push',
+ 'catalog_direction_tooltip' => 'Sync direction: :direction',
'add_button' => 'Add adapter',
'add_modal_title' => 'Add sync adapter',
@@ -226,8 +229,9 @@ return [
'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.',
- 'addigy_key_secret_help' => 'Paired with Client ID above. Displayed once in the Addigy admin console at creation time. Needs read access to Devices.',
+ 'addigy_api_key_help' => 'Addigy retired API v1 in June 2026. This adapter uses v2 and needs a v2-generated API key. Generate it under Account -> Integrations -> Addigy API in your Addigy admin console. The key needs read access to Devices and Policies. Push support (Set Device Name and End User Assignment) additionally needs write access to those surfaces. If you were previously using v1 client-ID + client-secret credentials here, issue a fresh v2 key and paste it.',
+ 'addigy_push_end_user_assignment_label' => 'Push end-user assignment',
+ 'addigy_push_end_user_assignment_help' => 'When on, assigning an asset to a Snipe-IT user also assigns that user as the Addigy end user tied to the device. Snipe-IT resolves the Addigy end user by email on each push, so the Snipe-IT user needs an email that matches an Addigy end-user record. Needs at least one successful pull first to cache your organization id (no stock "get my org" endpoint in v2).',
'unifi_api_key_help' => 'Two paths depending on the Base URL above. If pointing at a local UniFi console or Network Application (UniFi OS 4.0.6+ / Network 9.0.108+), generate the key under Settings -> Admins & Users -> API Keys. If pointing at https://api.ui.com (Site Manager cloud, used by hosted Snipe-IT installs when the UniFi consoles are behind NAT and cannot be reached directly), generate the key in the UniFi Site Manager developer portal with Site Manager + Network scopes. Older controllers using session cookies are not supported.',
'unifi_site_id_help' => 'The UniFi site to sync from. Click Refresh Sites above after saving the API key to populate this list from your controller or from Site Manager. On Site Manager cloud each row maps to a console (two sites on the same console share one row because the public cloud API does not expose a per-site device filter today).',
'unifi_access_api_token_help' => 'Sign in to the UniFi Portal, open the console where Access is installed, and go to Access -> Settings -> General -> Advanced -> API Token to generate one. UniFi Access 1.9.1 or later is required, and the API is not available on consoles that have upgraded to Identity Enterprise. This is a different credential from the UniFi Network API key, so running both requires one adapter instance of each.',
diff --git a/resources/views/settings/adapters.blade.php b/resources/views/settings/adapters.blade.php
index 002ee7f526..4ff51d5cfd 100644
--- a/resources/views/settings/adapters.blade.php
+++ b/resources/views/settings/adapters.blade.php
@@ -169,6 +169,14 @@
<ul class="list-unstyled adapter-catalog" aria-label="{{ trans('admin/settings/sync_adapters.catalog_caption') }}">
@foreach ($adapterCatalog as $slug => $entry)
<li class="adapter-catalog-item">
+ @php
+ $directionLabel = trans('admin/settings/sync_adapters.catalog_direction_'.$entry['direction']);
+ $directionIcon = $entry['direction'] === 'both' ? 'fa fa-exchange' : 'fa fa-arrow-down';
+ @endphp
+ <span class="adapter-catalog-direction tooltip-base" data-placement="top" title="{{ trans('admin/settings/sync_adapters.catalog_direction_tooltip', ['direction' => $directionLabel]) }}">
+ <i class="{{ $directionIcon }}" aria-hidden="true"></i>
+ <span class="sr-only">{{ $directionLabel }}</span>
+ </span>
<span class="adapter-catalog-docs">
@if ($entry['docs_url'])
@php
diff --git a/tests/Feature/SyncAdapters/Addigy/AddigyAdapterTest.php b/tests/Feature/SyncAdapters/Addigy/AddigyAdapterTest.php
index bd416c8c46..cf8719b6b1 100644
--- a/tests/Feature/SyncAdapters/Addigy/AddigyAdapterTest.php
+++ b/tests/Feature/SyncAdapters/Addigy/AddigyAdapterTest.php
@@ -12,10 +12,12 @@ use Illuminate\Support\Facades\Http;
use Tests\TestCase;
/**
- * End-to-end coverage for the Addigy adapter through
- * SyncAdapter. Mocks the Addigy API, asserts assets +
- * external ids land correctly, and that the client-id / client-secret
- * header pair (not bearer) goes out on the request.
+ * End-to-end coverage for the Addigy adapter against the Addigy API v2
+ * surface. Mocks the paginated POST /devices endpoint and asserts that
+ * assets + external ids land correctly, that the single x-api-key
+ * header goes out on the request, and that device-fact values are read
+ * out of the v2 `facts` map rather than top-level v1 field names
+ * (#19955).
*/
class AddigyAdapterTest extends TestCase
{
@@ -31,9 +33,12 @@ class AddigyAdapterTest extends TestCase
$adapter = $this->configuredAddigyAdapter();
Http::fake([
- '*/api/devices' => Http::response([
- $this->addigyDevice(agentid: 'agent-1', name: 'design-mbp', hardware_model: 'MacBook Pro'),
- $this->addigyDevice(agentid: 'agent-2', name: 'staff-imac', hardware_model: 'iMac'),
+ 'api.addigy.com/api/v2/devices' => Http::response([
+ 'items' => [
+ $this->addigyDevice(agentid: 'agent-1', device_name: 'design-mbp', device_model_name: 'MacBook Pro'),
+ $this->addigyDevice(agentid: 'agent-2', device_name: 'staff-imac', device_model_name: 'iMac'),
+ ],
+ 'metadata' => ['page' => 1, 'page_count' => 1, 'per_page' => 100, 'result_count' => 2, 'total' => 2],
]),
]);
@@ -46,43 +51,77 @@ class AddigyAdapterTest extends TestCase
$this->assertDatabaseHas('assets', ['name' => 'design-mbp']);
}
- public function test_client_id_and_client_secret_headers_are_sent_not_bearer()
+ public function test_x_api_key_header_is_sent_not_bearer_or_v1_pair()
{
$adapter = $this->configuredAddigyAdapter();
Http::fake([
- '*/api/devices' => Http::response([]),
+ 'api.addigy.com/api/v2/devices' => Http::response([
+ 'items' => [],
+ 'metadata' => ['page' => 1, 'page_count' => 0, 'per_page' => 100, 'result_count' => 0, 'total' => 0],
+ ]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ // Addigy API v2 authenticates with a single x-api-key header.
+ // A regression to withToken() (Authorization: Bearer) or to the
+ // retired v1 client-id + client-secret pair would silently
+ // 401 against a real tenant.
+ Http::assertSent(function ($request) {
+ return $request->hasHeader('x-api-key', 'fake-addigy-api-key')
+ && ! $request->hasHeader('Authorization')
+ && ! $request->hasHeader('client-id')
+ && ! $request->hasHeader('client-secret');
+ });
+ }
+
+ public function test_devices_endpoint_posts_with_desired_facts_and_pagination()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+
+ Http::fake([
+ 'api.addigy.com/api/v2/devices' => Http::response([
+ 'items' => [],
+ 'metadata' => ['page' => 1, 'page_count' => 0, 'per_page' => 100, 'result_count' => 0, 'total' => 0],
+ ]),
]);
iterator_to_array($adapter->pull());
- // Addigy's API uses a header pair, not bearer-token auth.
- // A regression to withToken() would silently 401 against a
- // real tenant.
Http::assertSent(function ($request) {
- return $request->hasHeader('client-id', 'fake-addigy-client-id')
- && $request->hasHeader('client-secret', 'fake-addigy-client-secret')
- && ! $request->hasHeader('Authorization');
+ if ($request->method() !== 'POST') {
+ return false;
+ }
+ $body = $request->data();
+
+ return is_array($body['desired_fact_identifiers'] ?? null)
+ && in_array('serial_number', $body['desired_fact_identifiers'], true)
+ && in_array('device_model_name', $body['desired_fact_identifiers'], true)
+ && isset($body['page'], $body['per_page']);
});
}
- public function test_normalized_record_carries_expected_fields()
+ public function test_normalized_record_reads_fact_values_out_of_the_v2_facts_map()
{
$adapter = $this->configuredAddigyAdapter();
Http::fake([
- '*/api/devices' => Http::response([
- $this->addigyDevice(
- agentid: 'agent-7',
- name: 'lab-mbp',
- hardware_model: 'MacBookPro18,3',
- serial_number: 'C02XYZ',
- network_mac_address: 'aa:bb:cc:11:22:33',
- network_ip_address: '10.0.0.42',
- os_type: 'macOS',
- os_version: '14.2.1',
- last_online: '2026-01-15T10:00:00.000Z',
- ),
+ 'api.addigy.com/api/v2/devices' => Http::response([
+ 'items' => [
+ $this->addigyDevice(
+ agentid: 'agent-7',
+ device_name: 'lab-mbp',
+ device_model_name: 'MacBookPro18,3',
+ serial_number: 'C02XYZ',
+ network_mac_address: 'aa:bb:cc:11:22:33',
+ network_ip_address: '10.0.0.42',
+ os_type: 'macOS',
+ os_version: '14.2.1',
+ last_online_at: '2026-01-15T10:00:00.000Z',
+ ),
+ ],
+ 'metadata' => ['page' => 1, 'page_count' => 1, 'per_page' => 100, 'result_count' => 1, 'total' => 1],
]),
]);
@@ -103,43 +142,362 @@ class AddigyAdapterTest extends TestCase
$this->assertNotNull($record->lastSeen);
}
+ public function test_fact_with_error_msg_falls_through_to_null()
+ {
+ // A tenant that doesn't have a built-in fact (or doesn't grant
+ // the API key read access to it) returns the fact entry with an
+ // error_msg set. normalize() must treat that as absent.
+ $adapter = $this->configuredAddigyAdapter();
+
+ Http::fake([
+ 'api.addigy.com/api/v2/devices' => Http::response([
+ 'items' => [[
+ 'agentid' => 'agent-err',
+ 'facts' => [
+ 'device_name' => ['type' => 'string', 'value' => 'present-host'],
+ 'serial_number' => ['type' => 'string', 'error_msg' => 'fact unavailable'],
+ ],
+ ]],
+ 'metadata' => ['page' => 1, 'page_count' => 1, 'per_page' => 100, 'result_count' => 1, 'total' => 1],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertSame('present-host', $records[0]->hostname);
+ $this->assertNull($records[0]->hardwareSerial);
+ }
+
+ public function test_pagination_follows_metadata_page_count_until_exhausted()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+
+ Http::fake([
+ 'api.addigy.com/api/v2/devices' => Http::sequence()
+ ->push([
+ 'items' => [$this->addigyDevice(agentid: 'p1-a', device_name: 'page1-a')],
+ 'metadata' => ['page' => 1, 'page_count' => 2, 'per_page' => 100, 'result_count' => 1, 'total' => 2],
+ ])
+ ->push([
+ 'items' => [$this->addigyDevice(agentid: 'p2-a', device_name: 'page2-a')],
+ 'metadata' => ['page' => 2, 'page_count' => 2, 'per_page' => 100, 'result_count' => 1, 'total' => 2],
+ ])
+ ->push([
+ 'items' => [],
+ 'metadata' => ['page' => 3, 'page_count' => 2, 'per_page' => 100, 'result_count' => 0, 'total' => 2],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+
+ $this->assertCount(2, $records);
+ $this->assertSame('page1-a', $records[0]->hostname);
+ $this->assertSame('page2-a', $records[1]->hostname);
+ }
+
+ public function test_unix_epoch_last_online_at_is_parsed_as_epoch_seconds()
+ {
+ // Addigy occasionally emits last_online_at as a Unix epoch int.
+ // Carbon::parse mis-reads that as a bare year, so parseTimestamp
+ // routes numerics to createFromTimestamp.
+ $adapter = $this->configuredAddigyAdapter();
+
+ Http::fake([
+ 'api.addigy.com/api/v2/devices' => Http::response([
+ 'items' => [[
+ 'agentid' => 'agent-epoch',
+ 'facts' => [
+ 'device_name' => ['type' => 'string', 'value' => 'epoch-host'],
+ 'last_online_at' => ['type' => 'number', 'value' => 1737112800],
+ ],
+ ]],
+ 'metadata' => ['page' => 1, 'page_count' => 1, 'per_page' => 100, 'result_count' => 1, 'total' => 1],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertSame(2025, $records[0]->lastSeen->year);
+ }
+
+ public function test_fetch_groups_posts_to_v2_policies_query_endpoint()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+
+ Http::fake([
+ 'api.addigy.com/api/v2/oa/policies/query' => Http::response([
+ ['policyId' => 'pol-1', 'name' => 'Engineering'],
+ ['policyId' => 'pol-2', 'name' => 'Executive'],
+ ]),
+ ]);
+
+ $groups = $adapter->fetchGroups();
+
+ $this->assertSame([
+ ['id' => 'pol-1', 'label' => 'Engineering'],
+ ['id' => 'pol-2', 'label' => 'Executive'],
+ ], $groups);
+ }
+
+ public function test_pull_captures_orgid_from_device_audit_response_for_later_push_use()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+ $instanceId = $adapter->instance()->id;
+
+ Http::fake([
+ 'api.addigy.com/api/v2/devices' => Http::response([
+ 'items' => [[
+ 'agentid' => 'agent-cache',
+ 'orgid' => 'org-cached-123',
+ 'facts' => ['device_name' => ['type' => 'string', 'value' => 'orgcache-host']],
+ ]],
+ 'metadata' => ['page' => 1, 'page_count' => 1, 'per_page' => 100, 'result_count' => 1, 'total' => 1],
+ ]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ $this->assertSame('org-cached-123', SyncAdapterConfig::get($instanceId, 'cached_orgid'));
+ }
+
+ public function test_push_set_device_name_fires_the_mdm_command_when_hostname_is_push_directed()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+ $instance = $adapter->instance();
+
+ // Direct hostname toward push.
+ SyncAdapterConfig::put($instance->id, 'direction.hostname', 'push');
+
+ $asset = \App\Models\Asset::factory()->create(['name' => 'pushed-mbp']);
+ $this->seedExternalSource($instance->id, $asset->id, 'agent-push-1');
+
+ Http::fake([
+ 'api.addigy.com/api/v2/mdm/settings/device/name' => Http::response([], 200),
+ ]);
+
+ $this->assertTrue($adapter->push($asset));
+
+ Http::assertSent(function ($request) {
+ if (! str_ends_with($request->url(), '/mdm/settings/device/name')) {
+ return false;
+ }
+ $body = $request->data();
+
+ return ($body['agent_id'] ?? null) === 'agent-push-1'
+ && ($body['device_name'] ?? null) === 'pushed-mbp';
+ });
+ }
+
+ public function test_push_skips_hostname_when_direction_is_not_push()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+ $instance = $adapter->instance();
+
+ // No direction stored: default is 'pull' for standard fields.
+ $asset = \App\Models\Asset::factory()->create(['name' => 'quiet-host']);
+ $this->seedExternalSource($instance->id, $asset->id, 'agent-quiet');
+
+ Http::fake();
+
+ $this->assertFalse($adapter->push($asset));
+
+ Http::assertNothingSent();
+ }
+
+ public function test_push_end_user_assignment_resolves_by_email_and_posts_the_assignment()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+ $instance = $adapter->instance();
+
+ SyncAdapterConfig::put($instance->id, 'push_end_user_assignment', '1');
+ SyncAdapterConfig::put($instance->id, 'cached_orgid', 'org-xyz');
+
+ $user = \App\Models\User::factory()->create(['email' => '[email protected]']);
+ $asset = \App\Models\Asset::factory()->create([
+ 'assigned_to' => $user->id,
+ 'assigned_type' => \App\Models\User::class,
+ ]);
+ $this->seedExternalSource($instance->id, $asset->id, 'agent-user-1');
+
+ Http::fake([
+ 'api.addigy.com/api/v2/o/org-xyz/end-users/query' => Http::response([
+ 'items' => [[
+ 'id' => 'end-user-42',
+ 'emails' => [['value' => '[email protected]', 'type' => 'work']],
+ ]],
+ 'metadata' => ['page' => 1, 'page_count' => 1, 'per_page' => 100, 'result_count' => 1, 'total' => 1],
+ ]),
+ 'api.addigy.com/api/v2/o/org-xyz/end-users/devices' => Http::response([], 200),
+ ]);
+
+ $this->assertTrue($adapter->push($asset));
+
+ Http::assertSent(function ($request) {
+ return str_ends_with($request->url(), '/o/org-xyz/end-users/devices')
+ && ($request->data()['agent_id'] ?? null) === 'agent-user-1'
+ && ($request->data()['end_user_id'] ?? null) === 'end-user-42';
+ });
+ }
+
+ public function test_push_end_user_assignment_skips_when_cached_orgid_is_missing()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+ $instance = $adapter->instance();
+
+ SyncAdapterConfig::put($instance->id, 'push_end_user_assignment', '1');
+ // No cached_orgid set.
+
+ $user = \App\Models\User::factory()->create(['email' => '[email protected]']);
+ $asset = \App\Models\Asset::factory()->create([
+ 'assigned_to' => $user->id,
+ 'assigned_type' => \App\Models\User::class,
+ ]);
+ $this->seedExternalSource($instance->id, $asset->id, 'agent-user-2');
+
+ Http::fake();
+
+ $this->assertFalse($adapter->push($asset));
+
+ Http::assertNothingSent();
+ }
+
+ public function test_push_end_user_assignment_skips_when_no_unique_match_for_email()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+ $instance = $adapter->instance();
+
+ SyncAdapterConfig::put($instance->id, 'push_end_user_assignment', '1');
+ SyncAdapterConfig::put($instance->id, 'cached_orgid', 'org-xyz');
+
+ $user = \App\Models\User::factory()->create(['email' => '[email protected]']);
+ $asset = \App\Models\Asset::factory()->create([
+ 'assigned_to' => $user->id,
+ 'assigned_type' => \App\Models\User::class,
+ ]);
+ $this->seedExternalSource($instance->id, $asset->id, 'agent-user-3');
+
+ Http::fake([
+ 'api.addigy.com/api/v2/o/org-xyz/end-users/query' => Http::response([
+ 'items' => [
+ ['id' => 'eu-1', 'emails' => [['value' => '[email protected]']]],
+ ['id' => 'eu-2', 'emails' => [['value' => '[email protected]']]],
+ ],
+ 'metadata' => ['page' => 1, 'page_count' => 1, 'per_page' => 100, 'result_count' => 2, 'total' => 2],
+ ]),
+ ]);
+
+ $this->assertFalse($adapter->push($asset));
+
+ // The query ran, but the assignment did not.
+ Http::assertNotSent(function ($request) {
+ return str_contains($request->url(), '/end-users/devices');
+ });
+ }
+
+ public function test_push_end_user_assignment_is_gated_by_the_opt_in_flag()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+ $instance = $adapter->instance();
+
+ // Opt-in flag off.
+ SyncAdapterConfig::put($instance->id, 'cached_orgid', 'org-xyz');
+ // Direct hostname so the push isn't a no-op across the board.
+ SyncAdapterConfig::put($instance->id, 'direction.hostname', 'push');
+
+ $user = \App\Models\User::factory()->create(['email' => '[email protected]']);
+ $asset = \App\Models\Asset::factory()->create([
+ 'name' => 'host-with-user',
+ 'assigned_to' => $user->id,
+ 'assigned_type' => \App\Models\User::class,
+ ]);
+ $this->seedExternalSource($instance->id, $asset->id, 'agent-gated');
+
+ Http::fake([
+ 'api.addigy.com/api/v2/mdm/settings/device/name' => Http::response([], 200),
+ ]);
+
+ $this->assertTrue($adapter->push($asset));
+
+ Http::assertNotSent(function ($request) {
+ return str_contains($request->url(), '/end-users/');
+ });
+ }
+
+ public function test_can_push_returns_true_and_notes_target_is_null()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+
+ $this->assertTrue($adapter->canPush());
+ $this->assertNull($adapter->notesFieldTarget(), 'Addigy exposes no device-level notes field.');
+ }
+
+ public function test_pushable_fields_only_includes_hostname()
+ {
+ $adapter = $this->configuredAddigyAdapter();
+
+ // Narrowing hides push/both from the direction picker for
+ // every other standard field. A regression that widens this
+ // set would let admins opt into pushes that silently drop.
+ $this->assertSame(['hostname'], $adapter->pushableFields());
+ }
+
private function configuredAddigyAdapter(): AddigyAdapter
{
$instance = SyncAdapterInstance::where('slug', 'addigy')->firstOrFail();
- SyncAdapterConfig::put($instance->id, 'url', 'https://prod.addigy.com');
- // key_id is non-secret, stored as plain text.
- SyncAdapterConfig::put($instance->id, 'key_id', 'fake-addigy-client-id');
- SyncAdapterConfig::put($instance->id, 'key_secret', Crypt::encrypt('fake-addigy-client-secret'));
+ SyncAdapterConfig::put($instance->id, 'api_key', Crypt::encrypt('fake-addigy-api-key'));
return new AddigyAdapter($instance->fresh());
}
+ private function seedExternalSource(int $instanceId, int $assetId, string $externalId): void
+ {
+ \App\Models\AssetExternalSource::query()->create([
+ 'asset_id' => $assetId,
+ 'source' => 'addigy',
+ 'external_id' => $externalId,
+ 'company_id' => null,
+ ]);
+ }
+
/**
+ * Build a v2 DeviceAudit payload with the given fact values. Null
+ * values are omitted from the facts map so tests can exercise the
+ * "fact missing on this tenant" case.
+ *
* @return array<string, mixed>
*/
private function addigyDevice(
string $agentid,
- string $name = 'device',
- string $hardware_model = 'MacBook',
+ string $device_name = 'device',
+ string $device_model_name = 'MacBook',
?string $serial_number = null,
?string $network_mac_address = null,
?string $network_ip_address = null,
?string $os_type = 'macOS',
?string $os_version = null,
- ?string $last_online = null,
+ ?string $last_online_at = null,
): array {
- return [
- 'agentid' => $agentid,
- 'name' => $name,
- 'hardware_model' => $hardware_model,
+ $facts = [];
+ foreach ([
+ 'device_name' => $device_name,
+ 'device_model_name' => $device_model_name,
'serial_number' => $serial_number,
'network_mac_address' => $network_mac_address,
'network_ip_address' => $network_ip_address,
'os_type' => $os_type,
'os_version' => $os_version,
- 'last_online' => $last_online,
+ 'last_online_at' => $last_online_at,
'policy_id' => 'policy-abc',
'agent_version' => '4.0.0',
+ ] as $identifier => $value) {
+ if ($value !== null) {
+ $facts[$identifier] = ['type' => 'string', 'value' => $value];
+ }
+ }
+
+ return [
+ 'agentid' => $agentid,
+ 'orgid' => 'org-test',
+ 'audit_date' => '2026-01-15T10:00:00Z',
+ 'facts' => $facts,
];
}
}
diff --git a/tests/Feature/SyncAdapters/Addigy/AddigySettingsPageTest.php b/tests/Feature/SyncAdapters/Addigy/AddigySettingsPageTest.php
index 226efc6917..1b30824951 100644
--- a/tests/Feature/SyncAdapters/Addigy/AddigySettingsPageTest.php
+++ b/tests/Feature/SyncAdapters/Addigy/AddigySettingsPageTest.php
@@ -12,10 +12,10 @@ use Tests\TestCase;
/**
* Smoke coverage for the Addigy adapter's registration + settings-page
- * presence. Addigy is the first adapter to use the URL+key-pair auth
- * shape (UrlKeyPairAdapter base + url_keypair partial), so this test
- * proves the shell renders, both credential fields persist, and each
- * gets encrypted at rest. pull() is still a stub so no sync coverage.
+ * presence. v2 authenticates with a single x-api-key, so the
+ * settings form carries one secret credential rather than v1's
+ * client-id + client-secret pair. The adapter's base URL is fixed
+ * (api.addigy.com), so no `url` field is on the form either.
*/
class AddigySettingsPageTest extends TestCase
{
@@ -27,54 +27,39 @@ class AddigySettingsPageTest extends TestCase
->assertSee('Addigy');
}
- public function test_saving_addigy_persists_url_and_encrypts_both_credentials()
+ public function test_saving_addigy_encrypts_the_api_key()
{
$addigy = SyncAdapterInstance::where('slug', 'addigy')->firstOrFail();
$this->actingAs(User::factory()->superuser()->create())
->post(route('settings.adapters.save', $addigy), [
- 'addigy_url' => 'https://prod.addigy.com/api',
- 'addigy_key_id' => 'plaintext-addigy-client-id',
- 'addigy_key_secret' => 'plaintext-addigy-client-secret',
+ 'addigy_api_key' => 'plaintext-addigy-api-key',
'addigy_default_category_id' => Category::factory()->create()->id,
'addigy_default_status_id' => Statuslabel::factory()->rtd()->create()->id,
])
->assertRedirect(route('settings.adapters.index', ['adapter' => $addigy->slug]));
- $this->assertSame('https://prod.addigy.com/api', SyncAdapterConfig::get($addigy->id, 'url'));
-
- // key_id is a non-secret credential (Client ID is a public
- // identifier per OAuth 2.0 convention), stored as plain text.
- // key_secret is encrypted at rest. Both are stored under
- // distinct keys so a mix-up would surface here.
- $storedKeyId = SyncAdapterConfig::get($addigy->id, 'key_id');
- $storedKeySecret = SyncAdapterConfig::get($addigy->id, 'key_secret');
- $this->assertSame('plaintext-addigy-client-id', $storedKeyId);
- $this->assertNotSame('plaintext-addigy-client-secret', $storedKeySecret);
- $this->assertSame('plaintext-addigy-client-secret', Crypt::decrypt($storedKeySecret));
+ $storedApiKey = SyncAdapterConfig::get($addigy->id, 'api_key');
+ $this->assertNotSame('plaintext-addigy-api-key', $storedApiKey);
+ $this->assertSame('plaintext-addigy-api-key', Crypt::decrypt($storedApiKey));
}
- public function test_blank_credentials_on_save_fail_validation()
+ public function test_blank_api_key_on_save_fails_validation()
{
$addigy = SyncAdapterInstance::where('slug', 'addigy')->firstOrFail();
- SyncAdapterConfig::put($addigy->id, 'key_id', 'existing-key-id');
- SyncAdapterConfig::put($addigy->id, 'key_secret', Crypt::encrypt('existing-key-secret'));
+ SyncAdapterConfig::put($addigy->id, 'api_key', Crypt::encrypt('existing-api-key'));
$this->actingAs(User::factory()->superuser()->create())
->from(route('settings.adapters.index', ['adapter' => $addigy->slug]))
->post(route('settings.adapters.save', $addigy), [
- 'addigy_url' => 'https://prod.addigy.com/api',
- 'addigy_key_id' => '',
- 'addigy_key_secret' => '',
+ 'addigy_api_key' => '',
'addigy_default_category_id' => Category::factory()->create()->id,
'addigy_default_status_id' => Statuslabel::factory()->rtd()->create()->id,
])
->assertRedirect()
- ->assertSessionHasErrors(['addigy_key_id', 'addigy_key_secret']);
+ ->assertSessionHasErrors(['addigy_api_key']);
- // Stored values stay put because the save was rejected.
- // key_id is plain text, key_secret is encrypted.
- $this->assertSame('existing-key-id', SyncAdapterConfig::get($addigy->id, 'key_id'));
- $this->assertSame('existing-key-secret', Crypt::decrypt(SyncAdapterConfig::get($addigy->id, 'key_secret')));
+ // Stored value stays put because the save was rejected.
+ $this->assertSame('existing-api-key', Crypt::decrypt(SyncAdapterConfig::get($addigy->id, 'api_key')));
}
}
diff --git a/tests/Feature/SyncAdapters/DemoModeLocksFormTest.php b/tests/Feature/SyncAdapters/DemoModeLocksFormTest.php
index b690f0f2cb..5cb40420d1 100644
--- a/tests/Feature/SyncAdapters/DemoModeLocksFormTest.php
+++ b/tests/Feature/SyncAdapters/DemoModeLocksFormTest.php
@@ -38,10 +38,10 @@ class DemoModeLocksFormTest extends TestCase
$this->assertMatchesRegularExpression('/name="fleet_log_heartbeats"[^>]*disabled/', $html);
$this->assertMatchesRegularExpression('/name="fleet_mapping\[hostname\]"[^>]*disabled/', $html);
- // Same coverage for the key-pair auth shape (Addigy). Different
- // partial, same shell, so locking must apply symmetrically.
- $this->assertMatchesRegularExpression('/name="addigy_key_id"[^>]*disabled/', $html);
- $this->assertMatchesRegularExpression('/name="addigy_key_secret"[^>]*disabled/', $html);
+ // Same coverage for the single-API-key auth shape (Addigy v2).
+ // Different partial, same shell, so locking must apply
+ // symmetrically.
+ $this->assertMatchesRegularExpression('/name="addigy_api_key"[^>]*disabled/', $html);
$this->assertMatchesRegularExpression('/name="addigy_active"[^>]*disabled/', $html);
// Save button lives in the footer, disabled by the index page